diff --git a/cmake/libs/libfaiss.cmake b/cmake/libs/libfaiss.cmake index 88dd4407c..8cc693a3f 100644 --- a/cmake/libs/libfaiss.cmake +++ b/cmake/libs/libfaiss.cmake @@ -11,6 +11,9 @@ knowhere_file_glob( thirdparty/faiss/faiss/impl/result_handler/ResultHandler.cpp thirdparty/faiss/faiss/impl/fast_scan/*.cpp thirdparty/faiss/faiss/impl/hnsw/*.cpp + thirdparty/faiss/faiss/impl/pipnn/HashPrune.cpp + thirdparty/faiss/faiss/impl/pipnn/Partition.cpp + thirdparty/faiss/faiss/impl/pipnn/kernels.cpp thirdparty/faiss/faiss/impl/pq_code_distance/*.cpp thirdparty/faiss/faiss/impl/scalar_quantizer/*.cpp thirdparty/faiss/faiss/invlists/*.cpp @@ -22,6 +25,17 @@ knowhere_file_glob( thirdparty/faiss/faiss/cppcontrib/knowhere/utils/*.cpp ) +# Select SVS explicitly below. Faiss's SSD-backed RaBitQ index is disabled. +knowhere_file_glob( + GLOB + FAISS_OPTIONAL_SRCS + thirdparty/faiss/faiss/impl/svs_io.cpp + thirdparty/faiss/faiss/IndexIVFRaBitQSSD.cpp + thirdparty/faiss/faiss/invlists/DiskIOBackend.cpp + thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp +) +list(REMOVE_ITEM FAISS_SRCS ${FAISS_OPTIONAL_SRCS}) + if(WITH_SVS) knowhere_file_glob( GLOB @@ -48,6 +62,7 @@ knowhere_file_glob( FAISS_DD_AVX512_SRCS thirdparty/faiss/faiss/impl/fast_scan/impl-avx512.cpp thirdparty/faiss/faiss/impl/hnsw/avx512.cpp + thirdparty/faiss/faiss/impl/nndescent/gram-avx512.cpp thirdparty/faiss/faiss/impl/pq_code_distance/avx512.cpp thirdparty/faiss/faiss/impl/result_handler/avx512.cpp thirdparty/faiss/faiss/impl/polysemous_training/avx512.cpp @@ -57,6 +72,7 @@ knowhere_file_glob( thirdparty/faiss/faiss/utils/distances_fused/avx512.cpp thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp thirdparty/faiss/faiss/utils/simd_impl/distances_avx512.cpp + thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp ) @@ -107,6 +123,7 @@ knowhere_file_glob( thirdparty/faiss/faiss/impl/approx_topk/avx2.cpp thirdparty/faiss/faiss/impl/fast_scan/impl-avx2.cpp thirdparty/faiss/faiss/impl/hnsw/avx2.cpp + thirdparty/faiss/faiss/impl/nndescent/gram-avx2.cpp thirdparty/faiss/faiss/impl/pq_code_distance/avx2.cpp thirdparty/faiss/faiss/impl/result_handler/avx2.cpp thirdparty/faiss/faiss/impl/binary_hamming/avx2.cpp @@ -115,6 +132,7 @@ knowhere_file_glob( thirdparty/faiss/faiss/utils/distances_fused/simdlib_based.cpp thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp thirdparty/faiss/faiss/utils/simd_impl/distances_avx2.cpp + thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp thirdparty/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp @@ -163,13 +181,14 @@ knowhere_file_glob( FAISS_DD_NEON_SRCS thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp thirdparty/faiss/faiss/impl/approx_topk/neon.cpp - thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp thirdparty/faiss/faiss/impl/binary_hamming/neon.cpp + thirdparty/faiss/faiss/impl/nndescent/gram-neon.cpp thirdparty/faiss/faiss/impl/pq_code_distance/neon.cpp thirdparty/faiss/faiss/cppcontrib/knowhere/impl/sq-neon-fastpath.cpp thirdparty/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp thirdparty/faiss/faiss/utils/hamming_distance/hamming_neon.cpp thirdparty/faiss/faiss/utils/simd_impl/distances_aarch64.cpp + thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp thirdparty/faiss/faiss/utils/simd_impl/partitioning_neon.cpp thirdparty/faiss/faiss/utils/simd_impl/rabitq_neon.cpp ) @@ -222,6 +241,7 @@ knowhere_file_glob( thirdparty/faiss/faiss/utils/simd_impl/distances_rvv.cpp thirdparty/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp thirdparty/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp + thirdparty/faiss/faiss/utils/distances_fused/rvv.cpp ) # combine files list(APPEND FAISS_RVV_SRCS ${FAISS_DD_RVV_SRCS}) @@ -420,6 +440,11 @@ if(__X86_64) message(STATUS "Skip Faiss AVX512_SPR: compiler does not support required SPR flags") endif() + # Match the BMI2 requirement in upstream Faiss's x86 runtime dispatch. + set_property(SOURCE ${FAISS_DD_AVX2_SRCS} ${FAISS_DD_AVX512_SRCS} + ${FAISS_AVX512_VPOPCNT_SRCS} ${FAISS_AVX512_SPR_SRCS} + APPEND PROPERTY COMPILE_OPTIONS -mbmi2) + add_library(faiss_avx2 OBJECT ${FAISS_AVX2_SRCS} ${FAISS_FASTSCAN_SRCS}) target_compile_options(faiss_avx2 PRIVATE $<$: -msse4.2 -mavx2 -mfma -mf16c -mpopcnt>) diff --git a/src/index/data_view_dense_index/refine_computer.h b/src/index/data_view_dense_index/refine_computer.h index 790d56386..11744a35e 100644 --- a/src/index/data_view_dense_index/refine_computer.h +++ b/src/index/data_view_dense_index/refine_computer.h @@ -171,7 +171,7 @@ struct QuantDataDistanceComputer : faiss::DistanceComputer { void set_query(const float* x) override { if (quant_data->GetOriginDataType() == DataFormatEnum::fp32) { - qc->q = x; + qc->set_query(x); if constexpr (NeedNormalize) { q_norm = GetL2Norm(x, dim); } @@ -180,7 +180,7 @@ struct QuantDataDistanceComputer : faiss::DistanceComputer { if (convert_data(x, query_buf.data(), quant_data->GetOriginDataType(), 1, dim) != true) { throw std::runtime_error("fail to convert data to fp32 type."); } - qc->q = query_buf.data(); + qc->set_query(query_buf.data()); if constexpr (NeedNormalize) { q_norm = GetL2Norm(query_buf.data(), dim); } diff --git a/tests/faiss/CMakeLists.txt b/tests/faiss/CMakeLists.txt index 270302429..5e5f84ada 100644 --- a/tests/faiss/CMakeLists.txt +++ b/tests/faiss/CMakeLists.txt @@ -1,5 +1,4 @@ set(FAISS_TEST_SRCS - ../../thirdparty/faiss/tests/test_omp_threads.cpp ../../thirdparty/faiss/tests/test_heap.cpp ../../thirdparty/faiss/tests/test_partitioning.cpp ../../thirdparty/faiss/tests/test_simdlib.cpp @@ -8,26 +7,22 @@ set(FAISS_TEST_SRCS ../../thirdparty/faiss/tests/test_cppcontrib_uintreader.cpp ../../thirdparty/faiss/tests/test_distances_simd.cpp ../../thirdparty/faiss/tests/test_hnsw.cpp - ../../thirdparty/faiss/tests/test_binary_flat.cpp ../../thirdparty/faiss/tests/test_cppcontrib_sa_decode.cpp ../../thirdparty/faiss/tests/test_ondisk_ivf.cpp ../../thirdparty/faiss/tests/test_pq_encoding.cpp - ../../thirdparty/faiss/tests/test_RCQ_cropping.cpp - ../../thirdparty/faiss/tests/test_ivfpq_codec.cpp - ../../thirdparty/faiss/tests/test_ivfpq_indexing.cpp - ../../thirdparty/faiss/tests/test_merge.cpp ../../thirdparty/faiss/tests/test_threaded_index.cpp - ../../thirdparty/faiss/tests/test_pairs_decoding.cpp ../../thirdparty/faiss/tests/test_dealloc_invlists.cpp ../../thirdparty/faiss/tests/test_params_override.cpp - ../../thirdparty/faiss/tests/test_sliding_ivf.cpp - ../../thirdparty/faiss/tests/test_transfer_invlists.cpp ../../thirdparty/faiss/tests/test_distances_dispatch.cpp ../../thirdparty/faiss/tests/test_fastscan_perf.cpp ../../thirdparty/faiss/tests/test_ivf_index.cpp + ../../thirdparty/faiss/tests/test_lowlevel_ivf.cpp + ../../thirdparty/faiss/tests/test_pipnn.cpp + ../../thirdparty/faiss/tests/test_rabitq_batch_estimates.cpp + ../../thirdparty/faiss/tests/test_super_kmeans_foundations.cpp + ../../thirdparty/faiss/tests/test_simd_levels.cpp ../../thirdparty/faiss/tests/test_disable_pq_sdc_tables.cpp ../../thirdparty/faiss/tests/test_common_ivf_empty_index.cpp - ../../thirdparty/faiss/tests/test_callback.cpp ) find_package(GTest REQUIRED) diff --git a/thirdparty/faiss/.github/actions/build_cmake/action.yml b/thirdparty/faiss/.github/actions/build_cmake/action.yml index 22e782f0d..ccf436ea2 100644 --- a/thirdparty/faiss/.github/actions/build_cmake/action.yml +++ b/thirdparty/faiss/.github/actions/build_cmake/action.yml @@ -32,6 +32,10 @@ inputs: description: 'Upload test artifacts. Prevents collisions when multiple jobs need to run build_cmake.' required: false default: 'true' + warnings_as_errors: + description: 'Fail the build of the Faiss library on compiler warnings.' + required: false + default: OFF runs: using: composite steps: @@ -87,7 +91,7 @@ runs: # -p "$CONDA" on every install below: a bare `conda install` targets # whatever env is active, which is base regardless of the above. - conda install -y -q -p "$CONDA" python=3.12 cmake=3.30.4 make=4.2 swig=4.0 "numpy>=2.0,<3.0" scipy=1.16 pytest=7.4 pytest-timeout gflags=2.2 setuptools + conda install -y -q -p "$CONDA" python=3.12 cmake>=4.0 make=4.2 swig=4.0 "numpy>=2.0,<3.0" scipy=1.16 pytest=7.4 pytest-timeout gflags=2.2 setuptools # install base packages for ARM64 if [ "${{ runner.arch }}" = "ARM64" ]; then @@ -113,7 +117,7 @@ runs: # test_gpu_index_serialize). CUDA 13.2 matches both the non-cuVS GPU # job and the pip-wheel cuVS build (whose GPU smoke test passes), and # the T4 driver. Only libnvJitLink must be 13.3: the conda libcuvs - # 26.06 build links it (needs the __nvJitLinkCreate_13_3 symbol), and + # 26.10 build links it (needs the __nvJitLinkCreate_13_3 symbol), and # it is a standalone package that cuda-nvcc / cuda-cudart-dev / # cuda-version do NOT pull to 13.3, so pin it explicitly — otherwise # an older libnvJitLink.so.13 is left in the env and libcuvs fails to @@ -124,8 +128,8 @@ runs: 'libnvjitlink>=13.3,<14' \ libcublas-dev libcusolver-dev libcusparse-dev \ gxx_linux-64=14.2 \ - libcuvs=26.06 'cuda-version>=13.2,<14' sysroot_linux-64=2.34 \ - -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia + libcuvs=26.10 'cuda-version>=13.2,<14' sysroot_linux-64=2.34 \ + -c rapidsai -c conda-forge -c nvidia conda clean --index-cache 2>/dev/null || true else conda install -y -q -p "$CONDA" cuda-libraries-dev=13.2 cuda-nvcc=13.2 cuda-nvtx=13.2 cuda-cupti=13.2 cuda-cudart-dev=13.2 gxx_linux-64=14.2 -c "nvidia/label/cuda-13.2" @@ -134,7 +138,7 @@ runs: # install SVS runtime for SVS builds if [ "${{ inputs.svs }}" = "ON" ]; then - conda install -y -q -p "$CONDA" libsvs-runtime=0.4.0 -c conda-forge + conda install -y -q -p "$CONDA" libsvs-runtime=0.5.0 -c conda-forge fi # install test packages @@ -152,7 +156,7 @@ runs: # cuVS builds previously got pytorch-gpu from conda, now unified to pip. # torch's cu132 wheels bundle a CUDA 13.2 nvidia-nvjitlink; when torch is # imported it dlopens that libnvJitLink.so.13 RTLD_GLOBAL and shadows the - # conda 13.3 lib that cuVS 26.06 needs, so faiss then fails to load with + # conda 13.3 lib that cuVS 26.10 needs, so faiss then fails to load with # "undefined symbol __nvJitLinkCreate_13_3". No torch cu133 build exists, # so upgrade the pip nvjitlink to 13.3 (symbol-complete, CUDA-13 forward # compatible). cuVS-only: the non-cuVS GPU path does not use libcuvs. @@ -160,45 +164,30 @@ runs: pip install --break-system-packages --upgrade "nvidia-nvjitlink>=13.3,<14" fi else - # TestLowLevelIVF.IVFRQ hangs on pytorch>=2.7, so left it as <2.5 for now. - conda install -y -q -p "$CONDA" "pytorch<2.5" -c pytorch + "$CONDA/bin/python" -m pip install "torch==2.15.0+cpu" --break-system-packages --index-url https://download.pytorch.org/whl/cpu + "$CONDA/bin/python" -c "import sysconfig, torch; assert torch.__file__.startswith(sysconfig.get_paths()['purelib']), torch.__file__; assert torch.__version__ == '2.15.0+cpu' and torch.version.cuda is None and torch.version.hip is None, torch.__version__" fi - - name: ROCm - Install dependencies - if: inputs.rocm == 'ON' + - name: Prepare native crash reporting + id: crash-diagnostics + if: inputs.metal != 'ON' shell: bash run: | - # Update repos and install kmod, wget, gpg - sudo apt-get -qq update >/dev/null - sudo apt-get -qq install -y kmod wget gpg >/dev/null - - # Download, prepare, and install the package signing key - mkdir --parents --mode=0755 /etc/apt/keyrings - wget https://repo.radeon.com/rocm/rocm.gpg.key -O - | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null - - - name: Add rocm repository + if directory=$(mktemp -d "$RUNNER_TEMP/faiss-crashes.XXXXXX") \ + && "$CONDA/bin/python" "$GITHUB_ACTION_PATH/native-crash-report" --start --state "$directory" \ + && echo "directory=$directory" >> "$GITHUB_OUTPUT"; then + echo 'Native crash reporting prepared' + else + echo 'Native crash reporting unavailable on this runner' + fi + - name: ROCm - Install dependencies if: inputs.rocm == 'ON' shell: bash run: | - # Get UBUNTU version name - UBUNTU_VERSION_NAME=`cat /etc/os-release | grep UBUNTU_CODENAME | awk -F= '{print $2}'` - - # Exported so the torch wheel step resolves the same release. - ROCM_VERSION="7.2" - echo "ROCM_VERSION=${ROCM_VERSION}" >> "$GITHUB_ENV" - - sudo mkdir -p /etc/apt/keyrings - wget -qO /tmp/rocm.gpg.key https://repo.radeon.com/rocm/rocm.gpg.key - echo "2de99e2354646a90d9903e2a669fc4e36b02c1bbff7075c481e12d7edab2c88b /tmp/rocm.gpg.key" | sha256sum --check - - echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/${ROCM_VERSION} ${UBUNTU_VERSION_NAME} main" | sudo tee /etc/apt/sources.list.d/rocm.list - - # Pin ROCm packages to avoid conflicts with other packages - sudo printf '%s\n' 'Package: *' 'Pin: release o=repo.radeon.com' 'Pin-Priority: 600' | sudo tee /etc/apt/preferences.d/rocm-pin-600 >/dev/null - + # The job container starts from bare ubuntu:24.04. The ROCm SDK's HIP + # compiler builds host code against the system GCC headers and libc6-dev, + # and hipify-perl needs perl; apt's ROCm packages used to pull these in. sudo apt-get -qq update >/dev/null - sudo apt-get -qq install -y rocm rocm-hip-sdk rocm-dev >/dev/null - - echo "/opt/rocm/bin" >> "$GITHUB_PATH" + sudo apt-get -qq install -y build-essential >/dev/null - name: Pin BLAS/LAPACK versions if: inputs.rocm == 'ON' @@ -209,9 +198,6 @@ runs: "libcblas=3.9.0=35_*" \ "liblapack=3.9.0=35_*" - # Fake presence of MI325X-class accelerators - echo "gfx942" | sudo tee /opt/rocm/bin/target.lst - # Cleanup sudo apt-get -qq autoclean >/dev/null sudo apt-get -qq clean >/dev/null @@ -231,6 +217,97 @@ runs: SYSROOT_LIB="$CONDA/x86_64-conda-linux-gnu/sysroot/usr/lib64" test -f "$SYSROOT_LIB/libpthread_nonshared.a" sudo ln -s "$SYSROOT_LIB/libpthread_nonshared.a" /usr/lib64/libpthread_nonshared.a + - name: ROCm - Install the ROCm SDK and torch via pip + if: inputs.rocm == 'ON' + shell: bash + run: | + set -euo pipefail + conda list -p "$CONDA" --show-channel-urls + + conda install -y -q -p "$CONDA" "pip<26" + + # Name the interpreter rather than trusting PATH, and drive pip through + # it, so nothing here depends on $GITHUB_PATH ordering. + PY="$CONDA/bin/python" + + # These wheels exist for one CPython ABI only, so bail with the version in + # hand rather than letting it read as "no matching distribution". + "$PY" -c 'import sys; assert sys.version_info[:2] == (3, 12), "need CPython 3.12 for the ROCm wheels, got %s" % sys.version' + + # ROCm 10.1 comes from AMD's pip packages, the ones the torch wheels + # depend on. `import torch` dlopens them from site-packages by absolute + # path, so faiss is built against them too: a second ROCm in the process + # (such as apt's /opt/rocm) aborts it when torch is imported after faiss. + # Everything goes in with one pip install before `rocm-sdk init`, which + # hardlinks the devel tree to the runtime files torch loads; reinstalling + # a rocm wheel afterwards would break those links. The device wheels and + # faiss's kernels target the runner's MI325X (gfx942). + # + # ROCm 10.1 also has a signed apt repo (stable.repo.amd.com, key + # rocm/gpg/packages.gpg, package amdrocm-core-sdk10.1-gfx942), but its + # libamdhip64 lands in /opt/rocm/core-10.1. Torch dlopens the pip copy + # by absolute path, and a second copy in the process aborts it, so the + # build stays on this index. It publishes no signatures, so every file + # is pinned by SHA-256 below and pip rejects any other. numpy and + # setuptools are absent: the conda env already provides them. The rocm + # meta package is an sdist, so the build uses conda's setuptools; + # isolating it would fetch setuptools unchecked. These hashes are for + # the GPU_TARGET wheels, so a different target needs its own hashes. + ROCM_VERSION=10.1.0 + GPU_TARGET=gfx942 + # Unquoted heredoc: ${GPU_TARGET} expands, and each hash stays on its + # requirement's line so a trailing backslash is not eaten. + "$PY" -m pip install --require-hashes --no-build-isolation \ + --index-url https://stable.repo.amd.com/rocm/whl-next/ \ + -r /dev/stdin <> "$GITHUB_ENV" + "$CONDA/bin/rocm-sdk" path --bin >> "$GITHUB_PATH" + + # Check torch resolves to this interpreter's own site-packages before + # trusting it: a stale tree left on the self-hosted runner has shadowed + # the fresh install before, and a wrong-ABI hit there surfaces as an + # unrelated-looking "Failed to load PyTorch C extensions". + "$PY" -c "import sysconfig, torch; p = sysconfig.get_paths()['purelib']; assert torch.__file__.startswith(p), 'torch loaded from %s, expected under %s' % (torch.__file__, p)" + + # torch.version.hip is the HIP component version; the product version is + # torch.version.rocm. Kept on one line: an unindented continuation would + # terminate this block scalar and break the manifest. + "$PY" -c "import sys, torch; rocm = getattr(torch.version, 'rocm', None) or ''; print('torch', torch.__version__, 'rocm', rocm, 'hip', torch.version.hip); sys.exit(None if rocm.startswith('${ROCM_VERSION}') else 'expected a ROCm ${ROCM_VERSION} build, got rocm=%s' % rocm)" - name: Print NVIDIA GPU info if: inputs.gpu == 'ON' && inputs.rocm != 'ON' shell: bash @@ -238,7 +315,7 @@ runs: - name: Print AMD GPU info if: inputs.gpu == 'ON' && inputs.rocm == 'ON' shell: bash - run: rocm-smi + run: amd-smi - name: Setup ccache uses: hendrikmuhs/ccache-action@v1 with: @@ -258,7 +335,20 @@ runs: eval "$(conda shell.bash hook)" conda activate "$CONDA" conda list -p "$CONDA" --show-channel-urls + ROCM_ARGS=() + if [ "${{ inputs.rocm }}" = "ON" ]; then + # The pip ROCm SDK from the install step, the copy torch loads. + ROCM_ARGS=( + -DCMAKE_PREFIX_PATH="$(rocm-sdk path --cmake)" + -DCMAKE_HIP_PLATFORM=amd + -DCMAKE_HIP_COMPILER="$ROCM_PATH/lib/llvm/bin/clang++" + -DCMAKE_HIP_COMPILER_ROCM_ROOT="$ROCM_PATH" + -DCMAKE_HIP_ARCHITECTURES="$ROCM_GPU_TARGET" + -DGPU_TARGETS="$ROCM_GPU_TARGET" + ) + fi cmake -B build \ + "${ROCM_ARGS[@]}" \ -DBUILD_TESTING=ON \ -DBUILD_SHARED_LIBS=ON \ -DFAISS_ENABLE_GPU=${{ inputs.gpu }} \ @@ -267,6 +357,7 @@ runs: -DFAISS_OPT_LEVEL=${{ inputs.opt_level }} \ -DFAISS_ENABLE_SVS=${{ inputs.svs }} \ -DFAISS_ENABLE_C_API=ON \ + -DFAISS_WARNINGS_AS_ERRORS=${{ inputs.warnings_as_errors }} \ -DPYTHON_EXECUTABLE=$CONDA/bin/python \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER_LAUNCHER=ccache \ @@ -288,11 +379,22 @@ runs: -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_PREFIX_PATH="$(brew --prefix libomp)" \ . - cmake --build build --target faiss faiss_metal swigfaiss TestMetalIndexFlat TestMetalIndexIVFFlat TestMetalIndexIVFPQ -j$(sysctl -n hw.logicalcpu) + cmake --build build --target \ + faiss faiss_metal swigfaiss \ + TestMetalIndexFlat TestMetalIndexIVFFlat TestMetalIndexIVFPQ \ + TestMetalIndexBinaryFlat TestMetalBinaryFlatFailures \ + -j$(sysctl -n hw.logicalcpu) - name: C++ tests if: inputs.metal != 'ON' shell: bash run: | + if ulimit -c unlimited 2>/dev/null; then + echo 'NATIVE_CRASH_MECHANISM {"mechanism":"ulimit","result":"raised"}' + else + "$CONDA/bin/python" "$GITHUB_ACTION_PATH/native-crash-report" --enable-core "$$" \ + || echo 'NATIVE_CRASH_MECHANISM {"mechanism":"core_limit","result":"failed"}' + fi + echo "Core limit soft=$(ulimit -Sc) hard=$(ulimit -Hc)" conda list -p "$CONDA" --show-channel-urls export GTEST_OUTPUT="xml:$(realpath .)/test-results/googletest/" make -C build test @@ -322,100 +424,42 @@ runs: run: | conda list -p "$CONDA" --show-channel-urls $CONDA/bin/python setup.py install - - name: ROCm - install ROCm-enabled torch via pip + - name: ROCm - Check faiss and torch share one HIP runtime if: inputs.rocm == 'ON' shell: bash run: | - set -euo pipefail - conda list -p "$CONDA" --show-channel-urls - - conda install -y -q -p "$CONDA" "pip<26" wheel - - # Name the interpreter rather than trusting PATH, and drive pip through - # it, so nothing here depends on $GITHUB_PATH ordering. - PY="$CONDA/bin/python" - - # These wheels exist for one CPython ABI only, so bail with the version in - # hand rather than letting it read as "no matching distribution". - "$PY" -c 'import sys; assert sys.version_info[:2] == (3, 12), "need CPython 3.12 for the ROCm wheels, got %s" % sys.version' - - # Install AMD's torch wheels built against the exact system ROCm, from - # apt. The PyTorch Foundation wheels float and bundle an older ROCr that - # lacks hsa_amd_memory_get_preferred_copy_engine (ROCr 1.18.0, added in - # ROCm 7.0.0), which collides with the system libamdhip64. Matching both - # sides avoids the dual-runtime undefined-symbol/segfault failures. - ROCM_WHEEL_VERSION="${ROCM_VERSION}.0" - BASE="https://repo.radeon.com/rocm/manylinux/rocm-rel-${ROCM_VERSION}" - - "$PY" -m pip --version - "$PY" -c "import sys, sysconfig; print(sys.version, sysconfig.get_platform())" - - # Treat the directory listing as a flat index so pip matches wheel tags - # against the running interpreter. --no-deps avoids pulling - # triton/pytorch-triton-rocm (only on AMD's index, not PyPI); torch's - # import-time deps are installed explicitly below. --ignore-installed - # because this runner is self-hosted: a wrong-ABI torch left by an earlier - # run otherwise satisfies the requirement and skips tag matching entirely. - # `|| true` then inspect: a transient failure (network, disk) must not be - # mistaken for a tag rejection and retagged over. - RESOLVE_LOG="$(mktemp)" - if ! "$PY" -m pip install --no-deps --ignore-installed --no-index \ - --find-links "${BASE}/" torch torchvision torchaudio 2>&1 \ - | tee "$RESOLVE_LOG"; then - if ! grep -qE "No matching distribution found|Could not find a version" "$RESOLVE_LOG"; then - echo "pip failed for a reason other than wheel-tag rejection" >&2 - exit 1 - fi - # pip builds that reject the unqualified linux_x86_64 tag these wheels - # carry see an empty index, so retag: the wheels need a glibc well - # below the runner's, only the tag is wrong. - echo "Flat-index resolve found no candidate; retagging wheels" >&2 - PYTAG="$("$PY" -c 'import sys; print("cp%d%d" % sys.version_info[:2])')" - ROCM_RE="${ROCM_WHEEL_VERSION//./\\.}" - HTML="$(wget -qO- "${BASE}/")" - WHEELS=() - for pkg in torch torchvision torchaudio; do - # `|| true`: no match exits grep 1, which pipefail turns into a bare - # abort before the diagnostic below can run. - WHL="$(printf '%s\n' "$HTML" \ - | grep -oE "${pkg}-[0-9][^\"]*rocm${ROCM_RE}[^\"]*${PYTAG}-${PYTAG}-linux_x86_64\.whl" \ - | sort -V | tail -1 || true)" - if [ -z "${WHL}" ]; then - echo "Could not locate +rocm${ROCM_WHEEL_VERSION} ${PYTAG} ${pkg} wheel at ${BASE}" >&2 - exit 1 - fi - echo "Selected: ${WHL}" - # The listing percent-encodes the '+'; the URL needs it encoded, the - # file on disk must not be. - wget -q "${BASE}/${WHL}" -O "${WHL//%2B/+}" - WHEELS+=("$("$PY" -m wheel tags --platform-tag manylinux_2_28_x86_64 \ - --remove "${WHL//%2B/+}")") - done - "$PY" -m pip install --no-deps --ignore-installed "${WHEELS[@]}" - fi - "$PY" -m pip install numpy pillow filelock typing-extensions sympy networkx jinja2 fsspec - - # Check torch resolves to this interpreter's own site-packages before - # trusting it: a stale tree left on the self-hosted runner has shadowed - # the fresh install before, and a wrong-ABI hit there surfaces as an - # unrelated-looking "Failed to load PyTorch C extensions". - "$PY" -c "import sysconfig, torch; p = sysconfig.get_paths()['purelib']; assert torch.__file__.startswith(p), 'torch loaded from %s, expected under %s' % (torch.__file__, p)" - - # A HIP mismatch here is the dual-runtime problem above, much cheaper to - # read than the resulting segfault. Kept on one line: an unindented + # Load libfaiss first, the order that aborts when there are two copies of + # ROCm in the process, then torch. Kept on one line: an unindented # continuation would terminate this block scalar and break the manifest. - "$PY" -c "import os, sys, torch; hip = torch.version.hip or ''; want = os.environ['ROCM_VERSION']; print('torch', torch.__version__, 'hip', hip); sys.exit(None if hip.startswith(want) else 'expected a HIP %s build, got %s' % (want, hip))" + "$CONDA/bin/python" -c "import ctypes, os; ctypes.CDLL('build/faiss/libfaiss.so'); import torch; hip = {l.split()[-1] for l in open('/proc/self/maps') if 'libamdhip64' in l}; assert len({(s.st_dev, s.st_ino) for s in map(os.stat, hip)}) == 1, hip; print('HIP runtime:', *hip)" - name: Python tests (CPU only) if: inputs.gpu == 'OFF' && inputs.metal != 'ON' shell: bash run: | + if ulimit -c unlimited 2>/dev/null; then + echo 'NATIVE_CRASH_MECHANISM {"mechanism":"ulimit","result":"raised"}' + else + "$CONDA/bin/python" "$GITHUB_ACTION_PATH/native-crash-report" --enable-core "$$" \ + || echo 'NATIVE_CRASH_MECHANISM {"mechanism":"core_limit","result":"failed"}' + fi + echo "Core limit soft=$(ulimit -Sc) hard=$(ulimit -Hc)" + export PYTHONFAULTHANDLER=1 conda list -p "$CONDA" --show-channel-urls pytest --junitxml=test-results/pytest/results.xml tests/test_*.py - pytest --junitxml=test-results/pytest/results-torch.xml tests/torch_*.py + LD_PRELOAD="$CONDA/lib/libstdc++.so.6" \ + pytest --junitxml=test-results/pytest/results-torch.xml tests/torch_*.py - name: Python tests (CPU + GPU) if: inputs.gpu == 'ON' shell: bash run: | + if ulimit -c unlimited 2>/dev/null; then + echo 'NATIVE_CRASH_MECHANISM {"mechanism":"ulimit","result":"raised"}' + else + "$CONDA/bin/python" "$GITHUB_ACTION_PATH/native-crash-report" --enable-core "$$" \ + || echo 'NATIVE_CRASH_MECHANISM {"mechanism":"core_limit","result":"failed"}' + fi + echo "Core limit soft=$(ulimit -Sc) hard=$(ulimit -Hc)" + export PYTHONFAULTHANDLER=1 conda list -p "$CONDA" --show-channel-urls pytest --junitxml=test-results/pytest/results.xml tests/test_*.py pytest --junitxml=test-results/pytest/results-torch.xml tests/torch_*.py @@ -432,8 +476,18 @@ runs: conda list -p "$CONDA" --show-channel-urls FAISS_DISABLE_CPU_FEATURES=AVX2 LD_DEBUG=libs $CONDA/bin/python -c "import faiss" 2>&1 | grep faiss.so LD_DEBUG=libs $CONDA/bin/python -c "import faiss" 2>&1 | grep faiss_avx2.so + - name: Native crash report + if: failure() && inputs.metal != 'ON' && steps.crash-diagnostics.outputs.directory != '' + shell: bash + run: | + status=0 + timeout --kill-after=10s 300s "$CONDA/bin/python" "$GITHUB_ACTION_PATH/native-crash-report" \ + --state "${{ steps.crash-diagnostics.outputs.directory }}" || status=$? + if [ "$status" -ne 0 ]; then + echo "NATIVE CRASH REPORT: incomplete (reporter exit $status)" + fi - name: Upload test results - if: inputs.upload_artifacts == 'true' + if: always() && inputs.upload_artifacts == 'true' uses: actions/upload-artifact@v4 with: name: test-results-arch=${{ runner.arch }}-opt=${{ inputs.opt_level }}-gpu=${{ inputs.gpu }}-cuvs=${{ inputs.cuvs }}-rocm=${{ inputs.rocm }}-svs=${{ inputs.svs }} diff --git a/thirdparty/faiss/.github/actions/build_cmake/native-crash-report b/thirdparty/faiss/.github/actions/build_cmake/native-crash-report new file mode 100644 index 000000000..0c1e43129 --- /dev/null +++ b/thirdparty/faiss/.github/actions/build_cmake/native-crash-report @@ -0,0 +1,508 @@ +#!/usr/bin/env python3 +# 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. + +"""Print postmortem diagnostics for native crashes in Linux CI tests.""" + +import argparse +import fnmatch +import json +import itertools +import os +from pathlib import Path +import platform +import re +import resource +import shutil +import subprocess +import time + + +def mechanism(name, result, detail=""): + print("NATIVE_CRASH_MECHANISM", json.dumps({ + "mechanism": name, "result": result, "detail": detail, + }, default=str), flush=True) + + +def command(args, timeout=30): + try: + result = subprocess.run( + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, timeout=timeout, + env=dict(os.environ, DEBUGINFOD_URLS=""), + ) + return result.returncode, result.stdout + except (OSError, subprocess.TimeoutExpired) as exc: + return 1, str(exc) + + +def inside(path, workspace): + return Path(path).resolve().is_relative_to(workspace) + + +def enable_core(pid): + if pid != os.getppid(): + raise ValueError("core limits may only be raised for the calling shell") + before = resource.prlimit(pid, resource.RLIMIT_CORE) + mechanism("sudo_prlimit", "attempted", {"pid": pid, "before": before}) + code, output = command([ + "sudo", "-n", "prlimit", "--pid", str(pid), + "--core=unlimited:unlimited", + ], timeout=10) + if output: + print(output) + after = resource.prlimit(pid, resource.RLIMIT_CORE) + raised = not code and after == (resource.RLIM_INFINITY,) * 2 + mechanism("sudo_prlimit", "raised" if raised else "failed", { + "pid": pid, "after": after, "exit": code, + }) + return raised + + +def apport_context(state): + code, version = command(["dpkg-query", "-W", "apport"]) + mechanism("apport_version", "read" if not code else "unavailable", version) + for name in ( + "/etc/default/apport", "/proc/sys/fs/suid_dumpable", + "/proc/sys/kernel/core_uses_pid", + ): + try: + text = Path(name).read_text() + lines = [s for s in text.splitlines() + if s.strip() and not s.lstrip().startswith("#")] + mechanism("apport_config", "read", { + "path": name, "content": lines, + }) + except OSError as exc: + mechanism("apport_config", "unavailable", { + "path": name, "error": str(exc), + }) + for name in ("/var/lib/apport/coredump", "/var/crash"): + try: + info = Path(name).stat() + mechanism("apport_directory", "inspected", { + "path": name, "mode": oct(info.st_mode & 0o7777), + "uid": info.st_uid, "gid": info.st_gid, + "readable": os.access(name, os.R_OK | os.X_OK), + }) + except OSError as exc: + mechanism("apport_directory", "unavailable", { + "path": name, "error": str(exc), + }) + printed = unparsed = 0 + show = False + try: + with Path("/var/log/apport.log").open(errors="replace") as stream: + for line in stream: + stamp = re.search( + r"\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) " + r"[A-Z][a-z]{2} +\d+ \d\d:\d\d:\d\d \d{4}", line, + ) + if stamp: + try: + epoch = time.mktime(time.strptime( + stamp[0], "%a %b %d %H:%M:%S %Y", + )) + show = epoch >= state["since"] + except ValueError: + show = False + unparsed += 1 + elif not show and line.strip(): + unparsed += 1 + if show: + print("Apport log:", line.rstrip()) + printed += 1 + mechanism("apport_log", "read", { + "printed": printed, "unparsed_or_skipped": unparsed, + }) + except OSError as exc: + mechanism("apport_log", "unavailable", str(exc)) + + +def elf_type(path): + try: + with path.open("rb") as stream: + header = stream.read(18) + order = "little" if header[5] == 1 else "big" + if header[:4] == b"\x7fELF": + return int.from_bytes(header[16:18], order) + return None + except (OSError, IndexError): + return None + + +def core_file(path): + return elf_type(path) == 4 + + +def recent(path, state): + try: + info = path.stat() + return ( + not path.is_symlink() + and info.st_uid == state["uid"] + and info.st_mtime >= state["since"] + ) + except OSError: + return False + + +def find_cores(state, directory, pattern): + workspace = Path(state["workspace"]) + if not pattern.startswith("|"): + mechanism("plain", "attempted", pattern) + if Path(pattern).is_absolute(): + print("Cannot associate an absolute core path with this job:") + print(pattern) + mechanism("plain", "unsupported", "absolute path") + return + name = re.sub( + r"%%|%[A-Za-z]", + lambda match: "%" if match[0] == "%%" else "*", + Path(pattern).name, + ) + uses_pid = Path("/proc/sys/kernel/core_uses_pid").read_text().strip() + print("core_uses_pid:", uses_pid) + append_pid = ( + uses_pid == "1" + and "%p" not in re.findall(r"%%|%[A-Za-z]", pattern) + ) + found = 0 + for parent, dirs, files in os.walk(workspace): + dirs[:] = [d for d in dirs if d != ".git"] + for name_in_dir in files: + path = Path(parent) / name_in_dir + matches = fnmatch.fnmatch(name_in_dir, name) + base, _, suffix = name_in_dir.rpartition(".") + if append_pid and suffix.isdecimal(): + matches |= fnmatch.fnmatch(base, name) + if ( + matches + and recent(path, state) + and core_file(path) + ): + found += 1 + mechanism("plain", "found", path) + yield path + mechanism("plain", "finished", f"{found} cores") + return + + if "systemd-coredump" in pattern: + mechanism("systemd", "attempted") + code, output = command([ + "journalctl", "--no-pager", "--output=json", + f"--since=@{int(state['since'])}", f"COREDUMP_UID={state['uid']}", + ]) + if code: + print("Cannot query systemd core metadata:", output) + mechanism("systemd", "failed", output) + return + found = 0 + for line in output.splitlines(): + try: + record = json.loads(line) + if not inside(record["COREDUMP_CWD"], workspace): + continue + pid = record["COREDUMP_PID"] + timestamp = record["COREDUMP_TIMESTAMP"] + except ValueError: + print("Systemd query message:", line) + continue + except (KeyError, TypeError): + continue + path = directory / f"core-{pid}-{timestamp}" + code, output = command([ + "coredumpctl", "--no-pager", f"--output={path}", "dump", + f"COREDUMP_PID={pid}", f"COREDUMP_TIMESTAMP={timestamp}", + f"COREDUMP_UID={state['uid']}", + ], timeout=60) + if not code and core_file(path): + found += 1 + mechanism("systemd", "retrieved", path) + yield path + else: + print("Cannot retrieve systemd core:", output) + mechanism("systemd", "failed", output) + mechanism("systemd", "finished", f"{found} cores") + return + + if "apport" in pattern: + mechanism("apport_reports", "attempted") + found = 0 + for report in Path("/var/crash").glob("*.crash"): + if not recent(report, state): + continue + try: + with report.open(errors="replace") as stream: + cwd = next(( + s.partition(": ")[2].strip() + for s in stream if s.startswith("ProcCwd: ") + ), "") + if not cwd or not inside(cwd, workspace): + continue + except OSError: + continue + destination = directory / report.name + code, output = command( + ["apport-unpack", str(report), str(destination)], timeout=60 + ) + path = destination / "CoreDump" + if not code and core_file(path): + found += 1 + mechanism("apport_reports", "retrieved", path) + yield path + else: + print("Cannot unpack Apport core:", output) + mechanism("apport_reports", "failed", output) + mechanism("apport_reports", "finished", f"{found} cores") + excluded = 0 + found = 0 + mechanism("apport_raw", "attempted") + decoder = shutil.which("readelf") + if decoder is None: + mechanism("apport_raw", "failed", "readelf unavailable") + return + for path in Path("/var/lib/apport/coredump").glob("core.*"): + if not recent(path, state): + excluded += 1 + continue + if not core_file(path): + excluded += 1 + continue + _, notes = command([decoder, "--notes", str(path)], timeout=60) + files = [s.strip() for s in notes.splitlines() + if s.lstrip().startswith("/")] + if any(inside(p, workspace) for p in files): + found += 1 + print("Apport association: uid/time and workspace ELF mapping") + mechanism("apport_raw", "found", path) + yield path + else: + print("Raw Apport core lacks a workspace association:", path) + excluded += 1 + print("Apport raw candidates excluded or unreadable:", excluded) + mechanism("apport_raw", "finished", { + "found": found, "excluded": excluded, + }) + return + + print("Core collector is not supported:", pattern) + mechanism("collector", "unsupported", pattern) + + +def debugger(directory, isolated=False): + system = Path("/usr/bin/gdb") + existing = str(system) if system.is_file() else shutil.which("gdb") + if existing and not isolated: + source = "gdb_system" if existing == str(system) else "gdb_path" + mechanism(source, "selected", existing) + return existing + print("Installing postmortem tools outside the test environment") + mechanism("gdb_conda", "attempted", directory) + prefix = directory / "debugger" + code, output = command([ + "conda", "create", "--yes", "--prefix", str(prefix), + "--override-channels", "--channel", "conda-forge", "gdb", + ], timeout=180) + print(output) + mechanism("gdb_conda", "selected" if not code else "failed", prefix) + return str(prefix / "bin/gdb") if not code else None + + +def backtrace(gdb, core): + _, mappings = command([ + gdb, "-nx", "-q", "-batch", "-c", str(core), + "-ex", "info proc mappings", + ], timeout=60) + print(mappings) + files = [] + for line in mappings.splitlines(): + match = re.match( + r"\s*0x[0-9a-f]+\s+0x[0-9a-f]+\s+0x[0-9a-f]+" + r"\s+(0x[0-9a-f]+)\s+(?:[rwxps-]{4}\s+)?(/.+)$", line + ) + if match: + files.append((int(match[1], 16), Path(match[2].rstrip()))) + # The lowest file-backed mapping at offset zero is the main ELF image. + executable = next(( + p for offset, p in files + if offset == 0 and elf_type(p) in (2, 3) and ".so" not in p.name + ), None) + if executable is None: + print("Cannot identify the executable; symbolization is incomplete") + return False + print("Crashed executable:", executable) + code, output = command([ + gdb, "-nx", "-q", "-batch", str(executable), "-c", str(core), + "-ex", "set pagination off", "-ex", "info threads", + "-ex", "thread apply all bt", "-ex", "info sharedlibrary", + ], timeout=90) + print(output) + readelf = shutil.which("readelf") + if readelf: + libraries = {p for _, p in files if any(n in p.name for n in ( + "libtorch", "libc10", "libstdc++", "libgcc", "libgomp", "libomp", + "libopenblas", "libmkl", "libfaiss", "_swigfaiss", + ))} + for path in sorted(libraries | {executable}): + _, notes = command([readelf, "--notes", str(path)]) + ids = [s.strip() for s in notes.splitlines() if "Build ID:" in s] + print(path, "; ".join(ids) or "no build ID available") + else: + print("readelf unavailable; build IDs were not collected") + return code == 0 and "#0" in output + + +def context(state): + print("Source:", os.environ.get("GITHUB_SHA", "unknown")) + print("Host:", platform.platform(), platform.libc_ver()) + print("Reporter affinity:", sorted(os.sched_getaffinity(0))) + print("Host logical CPUs:", os.cpu_count()) + print("Reporter limits (not crash-time counters):", { + name: resource.getrlimit(value) for name, value in ( + ("core", resource.RLIMIT_CORE), ("files", resource.RLIMIT_NOFILE), + ("processes", resource.RLIMIT_NPROC), + ("stack", resource.RLIMIT_STACK), + ) + }) + print("Reporter environment; test-command overrides may differ") + for name in ( + "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", + "MKL_THREADING_LAYER", "LD_PRELOAD", + ): + print(name, os.environ.get(name, "unset")) + groups = Path("/proc/self/cgroup").read_text() + print("Reporter cgroup:", groups.strip()) + if "::" in groups: + group = groups.split("::", 1)[1].strip().lstrip("/") + path = Path("/sys/fs/cgroup") / group + while path.is_relative_to("/sys/fs/cgroup"): + for name in ( + "cpu.max", "memory.max", "pids.max", "cpuset.cpus.effective", + ): + entry = path / name + if entry.exists(): + print(entry, entry.read_text().strip()) + if path == Path("/sys/fs/cgroup"): + break + path = path.parent + cache = Path(state["workspace"]) / "build/CMakeCache.txt" + if cache.exists(): + for line in cache.read_text(errors="replace").splitlines(): + if line.partition(":")[0] in ( + "FAISS_OPT_LEVEL", "CMAKE_BUILD_TYPE", "FAISS_ENABLE_GPU", + "FAISS_ENABLE_ROCM", "FAISS_ENABLE_CUVS", "BLA_VENDOR", + ): + print(line) + prefix = os.environ.get("CONDA") + if prefix: + _, output = command([str(Path(prefix) / "bin/python"), "-c", """ +import ast +import importlib.metadata as metadata +import sys +print('Python:', sys.version) +for package in ('torch', 'numpy'): + try: + print(package, metadata.version(package)) + except metadata.PackageNotFoundError: + print(package, 'not installed') +try: + path = metadata.distribution('torch').locate_file('torch/version.py') + for node in ast.parse(path.read_text()).body: + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id in ( + 'git_version', 'cuda', 'hip', + ): + print('Torch', target.id, ast.literal_eval(node.value)) +except (metadata.PackageNotFoundError, OSError, ValueError, SyntaxError) as exc: + print('Torch build metadata unavailable:', exc) +"""]) + print(output) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--state", type=Path) + parser.add_argument("--enable-core", type=int, metavar="SHELL_PID") + parser.add_argument("--start", action="store_true") + parser.add_argument("--core", type=Path, action="append", default=[]) + args = parser.parse_args() + if args.enable_core is not None: + if not enable_core(args.enable_core): + raise SystemExit(1) + return + if args.state is None: + parser.error("--state is required for preparation and reporting") + pattern = Path("/proc/sys/kernel/core_pattern").read_text().strip() + print("Core route:", pattern) + if args.start: + args.state.mkdir(parents=True, exist_ok=True) + (args.state / "state.json").write_text(json.dumps({ + "since": time.time(), "workspace": str(Path.cwd().resolve()), + "uid": os.getuid(), + })) + mechanism("prepare", "ready", args.state) + return + state = json.loads((args.state / "state.json").read_text()) + try: + context(state) + except Exception as exc: + print("Context incomplete:", type(exc).__name__, str(exc)) + if "apport" in pattern: + try: + apport_context(state) + except Exception as exc: + mechanism("apport_context", "incomplete", str(exc)) + if args.core: + mechanism("explicit", "selected", args.core) + cores = iter(args.core) + else: + cores = find_cores(state, args.state, pattern) + first = next(cores, None) + if first is None: + print("NATIVE CRASH REPORT: unavailable (no job-owned core retrieved)") + print("Python fatal stacks, if any, are in the test output") + return + gdb = debugger(args.state) + if not gdb: + print("NATIVE CRASH REPORT: unavailable (debugger installation failed)") + return + _, version = command([gdb, "--version"]) + print("Debugger:", gdb, "\n".join(version.splitlines()[:2])) + reported = total = 0 + fallback = None + fallback_attempted = inside(gdb, args.state.resolve()) + for core in itertools.chain([first], cores): + total += 1 + print("::group::Native crash", core) + success = backtrace(gdb, core) + mechanism("backtrace", "reported" if success else "failed", { + "debugger": gdb, "core": str(core), + }) + if not success and not fallback_attempted: + fallback_attempted = True + mechanism("fallback", "attempted", "no usable native stack") + fallback = debugger(args.state, isolated=True) + if not success and fallback: + print("Retrying postmortem with isolated debugger:", fallback) + success = backtrace(fallback, core) + mechanism("backtrace", "reported" if success else "failed", { + "debugger": fallback, "core": str(core), + }) + gdb = fallback + reported += success + print("::endgroup::") + print("NATIVE CRASH REPORT:", reported, "cores reported out of", total) + print("Symbol and capture warnings are shown above") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print("NATIVE CRASH REPORT: unavailable:", type(exc).__name__, str(exc)) + mechanism("reporter", "failed", f"{type(exc).__name__}: {exc}") + raise SystemExit(1) diff --git a/thirdparty/faiss/.github/actions/build_conda/action.yml b/thirdparty/faiss/.github/actions/build_conda/action.yml index 8a0c2b226..4b52fcbba 100644 --- a/thirdparty/faiss/.github/actions/build_conda/action.yml +++ b/thirdparty/faiss/.github/actions/build_conda/action.yml @@ -20,17 +20,19 @@ runs: shell: bash id: choose_shell run: | - # Use pwsh on Windows; bash everywhere else - if [ "${{ runner.os }}" != "Windows" ]; then - echo "shell=bash" >> "$GITHUB_OUTPUT" - else - echo "shell=pwsh" >> "$GITHUB_OUTPUT" - fi + # bash on all platforms. On Windows, the conda of the pinned + # Miniforge (24.11.2-1) passes empty arguments to conda.exe from its + # PowerShell wrapper, and conda.exe rejects them ("invalid choice: + # ''"). conda works in bash through the setup-miniconda PATH setup. + echo "shell=bash" >> "$GITHUB_OUTPUT" - name: Setup miniconda uses: conda-incubator/setup-miniconda@v3 with: python-version: '3.12' - miniforge-version: latest + # Miniforge3 26.9.4-0 fails `conda init` on Windows runners ("needs + # sudo" for Scripts\conda.exe). Keep the Windows pin in sync with the + # windows-x86_64-DD-cmake job in workflows/build-pull-request.yml. + miniforge-version: ${{ runner.os == 'Windows' && '24.11.2-1' || 'latest' }} channels: conda-forge conda-remove-defaults: 'true' activate-environment: 'base' @@ -100,7 +102,7 @@ runs: run: | conda list --show-channel-urls conda build faiss-gpu-cuvs --python 3.12 --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \ - -c pytorch -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia + -c pytorch -c rapidsai -c conda-forge -c nvidia - name: Conda build (GPU w/ cuVS) w/ anaconda upload if: inputs.label != '' && inputs.cuda != '' && inputs.cuvs != '' shell: ${{ steps.choose_shell.outputs.shell }} @@ -110,7 +112,7 @@ runs: run: | conda list --show-channel-urls conda build faiss-gpu-cuvs --python 3.12 --variants '{ "cudatoolkit": "${{ inputs.cuda }}" }' \ - --user pytorch --label ${{ inputs.label }} -c pytorch -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia + --user pytorch --label ${{ inputs.label }} -c pytorch -c rapidsai -c conda-forge -c nvidia - name: Check installed packages channel shell: ${{ steps.choose_shell.outputs.shell }} run: | diff --git a/thirdparty/faiss/.github/scripts/install-openblas.ps1 b/thirdparty/faiss/.github/scripts/install-openblas.ps1 index b253d73c3..263f98b4c 100644 --- a/thirdparty/faiss/.github/scripts/install-openblas.ps1 +++ b/thirdparty/faiss/.github/scripts/install-openblas.ps1 @@ -88,7 +88,11 @@ try { throw "OpenBLAS archive hash mismatch: expected $expectedHash, got $actualHash" } - Expand-Archive -LiteralPath $archivePath -DestinationPath $extractPath + # Not Expand-Archive: cibuildwheel launches this script from pwsh, so + # Windows PowerShell inherits pwsh's PSModulePath and loads the PS 7 + # Archive module, which calls a ZipFile overload that .NET Framework lacks. + Add-Type -AssemblyName System.IO.Compression.FileSystem + [System.IO.Compression.ZipFile]::ExtractToDirectory($archivePath, $extractPath) $sourcePath = if ($archiveSubdirectory) { Join-Path $extractPath $archiveSubdirectory } else { diff --git a/thirdparty/faiss/.github/workflows/build-pip.yml b/thirdparty/faiss/.github/workflows/build-pip.yml index d8483d82b..f1474b167 100644 --- a/thirdparty/faiss/.github/workflows/build-pip.yml +++ b/thirdparty/faiss/.github/workflows/build-pip.yml @@ -39,7 +39,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-14, macos-15-intel, windows-2022, windows-11-arm, 2-core-ubuntu-arm] + os: [ubuntu-latest, macos-15, macos-15-intel, windows-2022, windows-11-arm, 2-core-ubuntu-arm] steps: - name: Checkout uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 diff --git a/thirdparty/faiss/.github/workflows/build-pull-request.yml b/thirdparty/faiss/.github/workflows/build-pull-request.yml index ee18252ed..e7f14eedc 100644 --- a/thirdparty/faiss/.github/workflows/build-pull-request.yml +++ b/thirdparty/faiss/.github/workflows/build-pull-request.yml @@ -49,6 +49,8 @@ jobs: filters: | gpu: - 'faiss/gpu/**' + - 'contrib/e_means/**' + - 'tests/*e_means*.py' - 'faiss/gpu_metal/**' - 'c_api/gpu/**' - 'cmake/**' @@ -73,9 +75,66 @@ jobs: uses: actions/checkout@v4 - name: Build and Test (cmake) uses: ./.github/actions/build_cmake + with: + warnings_as_errors: ON - name: Build C++ demos run: | make -C build demo_diversity_result_handler + linux-x86_64-static-disk-ivf-cmake: + name: Linux x86_64 static DISK_IVF install (cmake) + needs: [linux-x86_64-cmake, changes] + if: ${{ needs.changes.outputs.has_cpu_changes == 'true' || github.event_name != 'pull_request' }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Install dependencies + run: | + sudo apt-get -qq update + sudo apt-get -qq install -y libopenblas-dev libaio-dev + - name: Build and install a static Faiss with IndexIVFRaBitQSSD + run: | + cmake -B build \ + -DFAISS_ENABLE_DISK_IVF=ON \ + -DBUILD_SHARED_LIBS=OFF \ + -DFAISS_ENABLE_GPU=OFF \ + -DFAISS_ENABLE_PYTHON=OFF \ + -DFAISS_ENABLE_MKL=OFF \ + -DFAISS_ENABLE_EXTRAS=OFF \ + -DBUILD_TESTING=OFF \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX="$PWD/install" \ + . + cmake --build build --target faiss -j$(nproc) + cmake --install build + # no libaio path of the build machine in the installed targets + ! grep -n "/libaio" install/share/faiss/faiss-targets*.cmake + - name: Build and run a program that uses the installed Faiss + run: | + # the installed package must bring libaio and OpenMP itself + mkdir consumer + cat > consumer/CMakeLists.txt <<'EOF' + cmake_minimum_required(VERSION 3.24) + project(faiss_consumer CXX) + find_package(faiss REQUIRED) + add_executable(consumer main.cpp) + target_link_libraries(consumer faiss) + EOF + cat > consumer/main.cpp <<'EOF' + #include + #include + #include + #include + int main() { + faiss::IndexFlatL2 quantizer(64); + faiss::IndexIVFRaBitQSSD index(&quantizer, 64, 4, 64, 4); + return faiss::get_compile_options().find("DISK_IVF") == + std::string::npos; + } + EOF + cmake -B consumer/build -S consumer -DCMAKE_PREFIX_PATH="$PWD/install" + cmake --build consumer/build + consumer/build/consumer linux-x86_64-AVX2-cmake: name: Linux x86_64 AVX2 (cmake) needs: [linux-x86_64-cmake, changes] @@ -88,6 +147,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: avx2 + warnings_as_errors: ON linux-x86_64-AVX512-cmake: name: Linux x86_64 AVX512 (cmake) needs: [linux-x86_64-cmake, changes] @@ -100,6 +160,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: avx512 + warnings_as_errors: ON linux-x86_64-AVX512_SPR-cmake: name: Linux x86_64 AVX512_SPR (cmake) needs: [linux-x86_64-cmake, changes] @@ -112,6 +173,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: avx512_spr + warnings_as_errors: ON linux-x86_64-DD-cmake: name: Linux x86_64 Dynamic Dispatch (cmake) needs: [linux-x86_64-cmake, changes] @@ -124,6 +186,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: dd + warnings_as_errors: ON linux-x86_64-GPU-cmake: name: Linux x86_64 GPU (cmake) needs: [linux-x86_64-cmake, changes] @@ -199,6 +262,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: sve + warnings_as_errors: ON env: # Context: https://github.com/facebookresearch/faiss/wiki/Troubleshooting#surprising-faiss-openmp-and-openblas-interaction OPENBLAS_NUM_THREADS: '1' @@ -214,6 +278,7 @@ jobs: uses: ./.github/actions/build_cmake with: opt_level: dd + warnings_as_errors: ON env: OPENBLAS_NUM_THREADS: '1' linux-x86_64-conda: @@ -241,17 +306,38 @@ jobs: uses: conda-incubator/setup-miniconda@v3 with: python-version: '3.12' - miniforge-version: latest + # Miniforge3 26.9.4-0 fails `conda init` on Windows runners. Keep in + # sync with the Windows pin in actions/build_conda/action.yml. + miniforge-version: '24.11.2-1' channels: conda-forge - name: Install dependencies - shell: pwsh + # bash, not pwsh: the conda of the pinned Miniforge passes empty + # arguments to conda.exe from its PowerShell wrapper, so conda.exe + # rejects them ("invalid choice: ''") and the activation in the pwsh + # profile fails. The pwsh steps below get the env from this step + # through GITHUB_ENV and GITHUB_PATH. + shell: bash -el {0} run: | conda install -y -q cmake swig "numpy>=2.0,<3.0" scipy pytest gflags setuptools conda install -y -q mkl=2024.2.2 mkl-devel=2024.2.2 + prefix=$(cygpath -w "$CONDA_PREFIX") + echo "CONDA_PREFIX=$prefix" >> "$GITHUB_ENV" + # Each GITHUB_PATH line goes to the front, so the env root ends first. + echo "$prefix\\Scripts" >> "$GITHUB_PATH" + echo "$prefix\\Library\\bin" >> "$GITHUB_PATH" + echo "$prefix" >> "$GITHUB_PATH" - name: Build - shell: pwsh + # -NoProfile: the profile from setup-miniconda activates base, sets + # CONDA_PREFIX and PATH to base, and then fails to activate the env + # (see Install dependencies). These steps use CONDA_PREFIX and PATH + # from Install dependencies instead. + shell: pwsh -NoProfile -Command ". '{0}'" run: | - $pythonExe = (Get-Command python).Source + # The env python, not the first python on PATH: FindPython also + # searches the registry, where the runner Pythons have no NumPy. + $pythonExe = Join-Path $env:CONDA_PREFIX "python.exe" + & $pythonExe -c "import sys, numpy; print(sys.executable, sys.version); print(numpy.get_include())" + if ($LASTEXITCODE -ne 0) { throw "The conda env python at $pythonExe cannot import numpy" } $pythonDir = Split-Path $pythonExe # Add Python libs dir so MSVC linker can find python312.lib $env:LIB = "$pythonDir\libs;$env:LIB" @@ -264,13 +350,15 @@ jobs: -DFAISS_ENABLE_C_API=OFF ` -DBLA_VENDOR=Intel10_64_dyn ` -DCMAKE_BUILD_TYPE=Release ` + -DPython_EXECUTABLE="$pythonExe" ` + -DPython_FIND_REGISTRY=NEVER ` -DPython_ROOT_DIR="$pythonDir" ` . # Add faiss.dll and dependency DLLs to PATH for GoogleTest discovery $env:PATH = "$PWD\build\faiss\Release;$env:CONDA_PREFIX\Library\bin;$env:PATH" cmake --build build --config Release -j $env:NUMBER_OF_PROCESSORS - name: C++ tests - shell: pwsh + shell: pwsh -NoProfile -Command ". '{0}'" run: | # Copy all required DLLs next to the test executable: # faiss.dll, gtest/gtest_main DLLs, and conda dependency DLLs @@ -281,24 +369,25 @@ jobs: cd build ctest --output-on-failure -C Release -E "SIMDConfig.modern_hardware_has_simd_support" - name: Install Python extension - shell: pwsh + shell: pwsh -NoProfile -Command ". '{0}'" run: | $repoRoot = $PWD.Path $env:PATH = "$repoRoot\build\faiss\Release;$env:CONDA_PREFIX\Library\bin;$env:PATH" + $pythonExe = Join-Path $env:CONDA_PREFIX "python.exe" cd build\faiss\python - python setup.py install + & $pythonExe setup.py install # Copy faiss.dll and MKL DLLs next to the installed _swigfaiss.pyd - $siteDir = python -c "import sysconfig; print(sysconfig.get_paths()['purelib'])" + $siteDir = & $pythonExe -c "import sysconfig; print(sysconfig.get_paths()['purelib'])" $siteDir = "$siteDir\faiss" Copy-Item "$repoRoot\build\faiss\Release\faiss.dll" $siteDir\ Copy-Item "$env:CONDA_PREFIX\Library\bin\mkl_*.dll" $siteDir\ -ErrorAction SilentlyContinue Copy-Item "$env:CONDA_PREFIX\Library\bin\libiomp5md.dll" $siteDir\ -ErrorAction SilentlyContinue - name: Python tests - shell: pwsh + shell: pwsh -NoProfile -Command ". '{0}'" run: | $env:PATH = "$env:CONDA_PREFIX\Library\bin;$env:PATH" $tests = (Get-ChildItem tests/test_*.py).FullName - pytest $tests + & (Join-Path $env:CONDA_PREFIX "python.exe") -m pytest $tests windows-x86_64-conda: name: Windows x86_64 (conda) needs: [linux-x86_64-cmake, changes] @@ -358,7 +447,9 @@ jobs: name: Linux riscv64 Dynamic Dispatch cross-compile (cmake) needs: [linux-x86_64-cmake, changes] if: ${{ needs.changes.outputs.has_cpu_changes == 'true' || github.event_name != 'pull_request' }} - runs-on: ubuntu-latest + # Ubuntu 26.04 has no qemu-user-static, and its Ubuntu Ports riscv64 + # packages do not match the amd64 Multi-Arch: same versions on the runner. + runs-on: ubuntu-24.04 steps: - name: Checkout uses: actions/checkout@v4 @@ -469,6 +560,22 @@ jobs: build/tests/faiss_test \ --gtest_filter="*SQRVV*:*D5Overflow*:*D5bLargeDim*:*D10FloatQuery*" + - name: Run scalar quantizer RVV parity tests (via QEMU) + run: | + qemu-riscv64-static \ + -cpu rv64,v=true,x-zvfhmin=true \ + -L /usr/riscv64-linux-gnu \ + build/tests/faiss_test \ + --gtest_filter="ScalarQuantizer.*DistancePathParity*" + + - name: Run scalar quantizer RVV parity tests (VLEN=1024, via QEMU) + run: | + qemu-riscv64-static \ + -cpu rv64,v=true,vlen=1024,x-zvfhmin=true \ + -L /usr/riscv64-linux-gnu \ + build/tests/faiss_test \ + --gtest_filter="ScalarQuantizer.*DistancePathParity*" + index-io-backward-compatibility: needs: linux-x86_64-cmake name: Index serialization backward compatibility diff --git a/thirdparty/faiss/.github/workflows/build-release.yml b/thirdparty/faiss/.github/workflows/build-release.yml index 2d717fe8f..e695776a7 100644 --- a/thirdparty/faiss/.github/workflows/build-release.yml +++ b/thirdparty/faiss/.github/workflows/build-release.yml @@ -76,7 +76,7 @@ jobs: label: main osx-arm64-packages: name: OSX arm64 packages - runs-on: macos-14 + runs-on: macos-15 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/thirdparty/faiss/.github/workflows/index-io-backward-compatibility.yml b/thirdparty/faiss/.github/workflows/index-io-backward-compatibility.yml index 8d65acfe5..65fccf15e 100644 --- a/thirdparty/faiss/.github/workflows/index-io-backward-compatibility.yml +++ b/thirdparty/faiss/.github/workflows/index-io-backward-compatibility.yml @@ -52,7 +52,7 @@ jobs: eval "$(conda shell.bash hook)" conda create -n faiss_conda_read -y python=3.12 conda activate faiss_conda_read - conda install -y -c pytorch -c conda-forge faiss-cpu=1.15.1 "mkl>=2024.2.2,<2026" + conda install -y -c pytorch -c conda-forge faiss-cpu=1.16.0 "mkl>=2024.2.2,<2026" conda list - name: Run Conda reader (read Faiss index and verify) @@ -82,6 +82,14 @@ jobs: fetch-depth: 0 fetch-tags: true + - name: Setup miniconda + uses: conda-incubator/setup-miniconda@v3 + with: + python-version: '3.12' + miniforge-version: latest + channels: conda-forge + conda-remove-defaults: 'true' + # Step 1: Install conda faiss-cpu in a clean environment and write files - name: Create conda write environment with faiss-cpu shell: bash @@ -89,7 +97,7 @@ jobs: eval "$(conda shell.bash hook)" conda create -n faiss_conda_write -y python=3.12 conda activate faiss_conda_write - conda install -y -c pytorch -c conda-forge faiss-cpu=1.15.1 "mkl>=2024.2.2,<2026" + conda install -y -c pytorch -c conda-forge faiss-cpu=1.16.0 "mkl>=2024.2.2,<2026" conda list - name: Create shared data directory @@ -115,6 +123,7 @@ jobs: - name: Build with CMake uses: ./.github/actions/build_cmake with: + setup_conda: 'false' upload_artifacts: 'false' - name: Run CMake reader (read Faiss index and verify) diff --git a/thirdparty/faiss/.github/workflows/nightly.yml b/thirdparty/faiss/.github/workflows/nightly.yml index fbba88877..9f14b561e 100644 --- a/thirdparty/faiss/.github/workflows/nightly.yml +++ b/thirdparty/faiss/.github/workflows/nightly.yml @@ -76,7 +76,7 @@ jobs: label: nightly osx-arm64-nightly: name: OSX arm64 nightlies - runs-on: macos-14 + runs-on: macos-15 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/thirdparty/faiss/CHANGELOG.md b/thirdparty/faiss/CHANGELOG.md index 8a1f4c072..4fc9e5d2c 100644 --- a/thirdparty/faiss/CHANGELOG.md +++ b/thirdparty/faiss/CHANGELOG.md @@ -3,6 +3,165 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +## [1.16.0] - 2026-11-09 + +Added +- fc1095a9314f892938bf83f59e7ac966b5095def e-means: add benchmarks reproducing the paper (#5845) +- 2079677d10e5f6cf0823acd5aea453389cc866a2 e-means: add max_points_per_centroid (#5855) +- 8e5843c5ec8697957276401f1acba0ebec58a329 Add regression test for flat search in a nested OpenMP region (#5754) +- b80093c5b290578ed7de1975583e295309b4de81 Add DINO resident and SSD streaming e-means demos (#5815) +- 97fdfb09848869f0e4bf09537eb814c3bf86bf49 Add optional IVF assignment for centroid-sharded e-means (#5817) +- f6a82dc2fa89ebb34ceb7cce8750f9305d2f17db Add centroid-sharded e-means training (#5823) +- 0136502d7ae5319a72ad35f7eb62e4eb364d8b1b Add native INT8 CuTe assignment to e-means (#5816) +- 15b14b2862c06eb779c6c3d8d669b5df4b6b33ea Add FP8 CuTe assignment to e-means (#5820) +- 13a33bf7f5e27e1bf531e4a21ba47a306dc97d9f Add CuTe assignment backend to e-means (#5818) +- 7a038e7eb2f8c4c76c19ead6ed9c5485f5030fc5 Add INT8 Triton assignment to e-means (#5821) +- 87b533977b9b536c1cc0b96daa191778b3cedd58 Add FP8 Triton assignment to e-means (#5819) +- c8ab4f51ac0703419d7cc6950117d286d37c37ff Add Triton assignment backend to e-means (#5822) +- f61f80a2c4ea7420364bd8f9153c8171efb1e1e3 Add reduced-precision assignment to e-means (#5814) +- 8ac2fdc014e4f19ba30f617c038fb2719c984031 Add distributed E-means training (#5813) +- 3795ee68fbecc0fa4ad027748735eb7f513948ee Add reference e-means implementations (#5812) +- 951067d91521af476ebf0b5c51b26fa4bc98ad80 Print native crash diagnostics in Linux CMake CI (#5828) +- 7648f5ffea474bdbdabab3d5e1a2a528db12c601 InvertedListScanner::distances_to_codes, with a block kernel for 8-bit PQ (#5807) +- a6505c5c5d76eaf86f9196669564ee766a9a1b69 Expose caller-owned Dataset APIs for CAGRA (#5739) +- 4caf5040c34ee16e069b14c24d09631b21a63133 Add MetalIndexBinaryFlat with GPU Hamming search and exact top-k selection (#5759) +- 71c7f482d2da0aa1fbed179485818184a5d7df42 Add remove_ids to IndexShards and IndexReplicas, and add_with_ids to IndexReplicas (#5773) +- 6964ecd829582bfdc9872c0c93acc5bf78696a0f Make the multi-GPU Python helpers work on the Metal backend (#5747) +- b156cced9160a6e68086f6828692ca69a6dd87f8 feat(rvv): add bit-exact RVV decode_vector for raw-codec quantizers (#5689) +- 8ff93a84010dabb605dfcb1f30511e80336fc006 Serialization, clone and index_factory support for IndexPiPNN (#5758) +- 840aa1f4aff4b824989cfeee9e74236ad9585f66 Add HNSW level-0 links from a sample to remove search sinks (#5705) +- 89e5eb519570efbfc5432324735d978c932d4ae3 Add IndexPiPNN, a PiPNN graph index with beam search (#5734) +- 3effdb20dc6bd0ebc38d0b1c46c366f3667751a2 PiPNN build assembly (#5729) +- 07979b10e64d39a611196483f103b2d7b349b5f7 Randomized Ball Carving partition (#5714) +- 7069478c3f027edc8ece507158409208b2652d90 Numeric kernels +- 7a057952fdb93fec7865eb5459e3956cd9108b8b HashPrune reservoir and sketch kernel (#5708) +- b0074a3fa426027d9ff8575b44386d5922859ac9 Add fp16 support to `SuperKMeans` (#5692) +- e7c44eb000bebb16f84be38a115caa5d333a8229 Add AVX-512 fp16 conversion kernels (#5694) +- ea29bac75d0039ad9f3aa0351ac5cac6aabdb0bb RaBitQ: add batch-four estimates and 9-bit SIMD scoring (#5647) +- 76c0e01e0f4db5f943b44cf85530e68efe29f355 Add GPU-accelerated IVFPQ search to the Metal backend (#5449) +- 0db2f3088643c2b2d0bc1c3afdba1dc0c40fee1a rabitq neon kernels (#5532) +- 430a41ee4c52cd070470e180c6d0f57888588d6b Native fp16 k-means training for Faiss IVF (#5671) +- 6c8378e4f1b8d7a3a7986c2ca216923221fe6954 Add RVV implementation for decode_bf16_simd (#5641) +- e24a371a701ddcb7fe460d87fd9c8f400c440848 feat(rvv): add vector arithmetic kernels (#5655) +- 94a4331fee6524272a108d8eb5c176133a29c6b2 Add reranked types to IndexSQFastScan and fix flat RaBitQ filtering (#5661) +- dcf8ebb34623c1b3dde08e495ef974c92a179c4e Support IDSelector in flat fast-scan search (#5660) +- 1768a5a8e988706fcce2306865f18fce5b151115 Add RVV SIMD specialization for product quantizer distance-table computation (#5543) +- f323c18d5afa1bb72211f6ef8618863940cb5ab5 Add RVV encoding for QT_8bit_direct (#5640) +- 5e74b1bddeb5e554023a044007a4ce22fd19647e feat: implement RVV optimized scalar quantizer codecs and distance computation (#5535) +- b0d9e80288daa678493d46c975ae92d1c6eced6d Add fast scan variants of SQ indexes - IndexSQFastScan and IndexIVFSQFastScan (#5341) +- 4864f4d42084a56535eb43ba66f27b1ab64d5ff5 SVS: Add ParameterSpace.set_index_parameter support for Vamana (#5644) +- 0f23e6a2ef2fe1a29c05e6d58b7eae0826f55fff Add RVV SIMD specialization for scalar quantizer distance compute (#5539) + +Changed +- f34c0b881d9dd5d3a248abea827505f4d700bc02 Move the macOS arm64 CI jobs from macos-14 to macos-15 (#5875) +- 741138a12befa506e391de1a548f862db801056a E-means: quality batch at d <= 16 and no revival at d <= 2 by default (#5854) +- 731286f8bf0aebdb0185e5d00f9cd6f6ceae055c e-means: faiss-style verbose output that reports epochs and asks for a citation (#5841) +- 277b3c76b7a1507915eb8f5010dcb367cbc95494 e-means: rename niter to nepochs (#5848) +- a15797a21ffa09a927b1db5cea9778778b242a9a Compute the coarse distances in search_preassigned when they are not given (#5748) +- b9552647c3437ded6bcf6b8f10ed82945b4b231b Replace the e-means README with a user guide (#5842) +- e4500c2252dacdcb2d5288c05cfeb7950379ec50 Use BF16 defaults and share quantized rows across E-means sharding (#5844) +- 0a6f936730175a4be0c3475359bdb12b39222099 Emeans ssd speedups (#5839) +- 9246aa7dd0a2ff5fa09703b37e674545a7cfded4 Rename e-means operating_point to batch_law, allow batch_size without alpha0, and default niter to 5 (#5833) +- 22a0cb7edd99e23ae9eabf025c18f115fb02e319 Separate Emeans implementations (#5840) +- 1d40eebe82718de25e030c092406ebc916c36a0f Speed up the x86 8-bit scalar quantizer inner-product distance (#5829) +- efd79c971d21b44970013bdd7dcb9f98d482ebdf Upgrade CPU CMake CI to PyTorch 2.15 (#5827) +- 0b0250d1eccde136de4e0fbfe85f595e22c59991 SQ fp16 and bf16: four accumulators per code at d >= 384, any d at AVX-512 (#5806) +- a3217cbb13cc7ecf853f875c391fcad7c3a67a3b Give each SIMD level its own copy of the 65 shared functions (#5810) +- 2a6e785964d253b99cd38cad70168a3eae9aa67e Define the AVX-512 SQ specializations once for AVX512 and AVX512_SPR (#5808) +- c2d27c620f250f0a4ef5c5a9e6709b1410e9469c Search only the sample vectors at sinks after each round of HNSW level-0 links (#5804) +- 9d5b44252dc7bd2921303b9f59f171a7fd7b2896 Codify the Faiss SIMD guard rules and check them with a test (#5793) +- 0d3c380b8cc0bd854478e785f1f9ddf67e467ead Move SIMD code to dedicated translation units and align guards (#5792) +- 03aa1bd8fb746a6450362020342d54ff5eb17199 Give fvec_L2sqr_ny_y_transposed_D internal linkage in the AVX2 and AVX512 files (#5788) +- 167f443cef3c55b6cc6b1409b746c4aaf79ee5d2 Prefetch graph rows and vectors in PiPNN search (#5805) +- ea99cbce425c7681ae71a66e2134dc9b7f73b272 SVS 0.5.0 (#5785) +- 0c2cad85a2cf6e2a523115ebb1f539177d0cb435 Run the Windows conda CI steps in bash (#5795) +- 35a4ec21dcb6036fee1c40bf49afdd5de3cbeb57 Use 3 sample vectors per node by default for HNSW level-0 links (#5789) +- 1ec00116793a35706e4a70abb74052bfcf353406 Hamming: vector popcount for the default computer at AVX512 and AVX512_VPOPCNT (#5787) +- fc6596015001cf5627d4c91782ef16fa50d80517 Use a SIMD masked sum for the fp32 RaBitQ 1-bit estimate (#5782) +- d37bedea3ce2d5cc124d67b71df0c1c5b85a65b9 Train ProductQuantizer subquantizers in parallel (#5783) +- 386c96bf975d06abba4cc723dcb24f9edf954545 Default alpha to 1.2 for all metrics (#5786) +- 0a32a42fead593df8d57c7e21fa586099d85013c Scale the HNSW and PiPNN search check period by the thread count (#5784) +- c919a604e621876c43f33c54dc87a6c2e6eccc97 Dispatch RaBitQ scans once per inverted list (#5597) +- 6907ed11766275b239856bb24381542d664e5265 Prune inner-product graphs on cosines when norms vary (#5774) +- e353ed74de51d8d28443fae3ca8d2df5da790d7c 8-bit PQ code distance: 4-sum scalar kernel instead of gathers on AMD Zen 3/4/5 (#5751) +- 9e1630901add9f264d3640d2f554447a4e8e8c8d Build PiPNN graphs over distinct codes (#5768) +- 7834abae4f86839f2220dc88fb7b3403d2bb5e00 Size IVF fast-scan slice LUTs on the calling thread (#5721) +- 273212578948c95ce2681bc7496228fab7079e64 Dispatch more dimensions to the SIMD fvec_L2sqr_ny_transposed kernels (#5757) +- ee6927dedd66ba57192c65d4de7bff8c69c0f332 ivflib::search_with_distance_to_code: search through InvertedListScanner::distance_to_code (#5755) +- 56c96d5efcfd3b498f70bd3be61e75da4455e491 Move Faiss C++ tests to Python (#5743) +- a55e0b2af6fc5c26c68cae363c6e4c734f0f2981 Upgrade cuVS to 26.10 (#5633) +- 494330fb1f77124814a4a07653b5a1af89cc3af3 Speed up the NEON 8-bit scalar quantizer L2 distance (#5733) +- 1a9ddc60d2201c9a44dfca3acead6ee38fbe21dc Use monotonic dynamic scheduling so libomp 12 does not take its static-steal path (#5723) +- 3fc6bcd9560fae13a1d83ae6f1d74c191a32aea6 On ROCm, stage pageable host copies in pinned memory (#5712) +- cec5702b0b1c31f242b9d35d5f193b0d80ccd9dc DD: give fvec_L2sqr_ny_nearest_y_transposed_D internal linkage (#5720) +- db6aa06d968084434c8ae270f699d3ba16079300 Hoist per-list allocations out of the IVF fast-scan search loops (#5717) +- 39079668a8bebcad6a89143df7bf7e9bc542f93e Select OpenBLAS OMP build in conda for AArch64 + Linux (#5669) +- 44afa7729d34c9392d2af62683285e593a28db35 Stop allocating per (query, probe) on OpenMP workers in IVF RaBitQ fast-scan (#5716) +- 6692d7ab3748e95d155c49b7821dc9ef70a2611a Stop copying QueryFactorsData per block in RaBitQHeapHandler +- 3a980624265e442653cd0e74a5b903f7bb32c5e0 faiss/conda: extend LSQ NEON-flaky test skip to all arm64 (#5713) +- 2839c39f2058ef49554273c6e98a8244cbe243e1 Make the GPU IVF search return the same neighbours on every run (#5682) +- a2f79430051d5c8c458300645a15c6efa496d1f4 Optimize 4-bit PQ fastscan accumulation on Arm CPUs (#5709) +- 83ae8b0908312c1e40734a806a3cc435b64f9496 Move the RVV distance kernels into free-standing headers (#5697) +- 1dab0c1cdf4dc66fb0f4d0370b02041c4889e8c1 Quarantine unstable cuVS Python GPU tests (#5699) +- ae4466d57e9a72977c58e79f6ed49d9a905f07ff Avoid widening fp16 data for k-means++ initialization (#5693) +- ea9151d71b4da86295a5aa3a2270b9845b46e133 RaBitQ: broadcast one sign word per 32 dims in the AVX2 RBQ9 kernel (#5696) +- 41023120df6b8f6a41f6f4a9b1d5f6d299f4b4d1 Defer IVF list scan setup until needed (#5595) +- fdb9535c15b1b2990fd28f76f0641e65b95162f8 Make search stats collection configurable (#5670) +- 7f6bf10b1c83b1634c3cfd3367ba1e76907c79b9 Halve IndexSQFastScan rerank memory with a split-nibble layout (#5662) +- b1c149654519857160402bf9d15a69e5bcf8c275 migrate from bit-manipulation builtins in fbcode/faiss (#5667) +- 2496f63f764595b10a8c0bc8eeb1ccf54a36b897 Avoid search stats contention during concurrent search (#5663) +- 3f4838ead310c3591ea1f3ad42a6cd97e4f56a4b Batch the IVF ScalarQuantizer scan four codes at a time (#5456) +- 1dbb3d25b07f221585cb335ad071639fc2374d44 Update backward compatibility test to v1.15.1 (#5646) + +Fixed +- 29782a03747addd1122bf040b6c3488c8d669fe9 Fix verbose e-means tests after the `nepochs` rename (#5869) +- 8babd49cf041798f36440189de5b74e1d2079c44 Fix assignment after progressive-dimension Kmeans training (#5861) +- b7c44bcc92e60e73e5cbc5b40b4c32d24d72652e Initialize SVS Vamana graph parameters in the default constructor. (#5834) +- 9acf8b0c16a51aafa12b9d9bcf13998b9138a8c5 Guard fp16 threshold in mock builds [unused-const-variable] (#5835) +- 0c269acddb19bb77ad1c0d149b71a022c12d857b Validate codebook size in read_ResidualQuantizer_old and bounds-check IndexBinaryIVF::reconstruct_from_offset (#5764) +- 7ac4a6c2b224684608c46f4f4bc7f2ade2176b60 Fix database-parallel kNN when the parallel region gets fewer threads (#5824) +- 98a23e442a3d6adddc025cb810ca0b17e5202d75 Fix OMP exception safety in ProductQuantizer (#5771) +- d87b58b4b74b08684be8d5b08cb6c93a744d1b7b fbcode/faiss/tests/test_fast_scan_distance_to_code.cpp (#5772) +- 48f21296c9b0b391ba878be3d7ba10ed0e250f13 Drop constants [unused-const-variable] (#5794) +- 2f890e8488582c84087e23c058c1db6a4ff45db8 Fix train_NonUniform skipping training row 0 and racing on a shared buffer (#5791) +- d4a6548c9a354bee366c14f39409d399f75c497f Faiss OSS nightly autofix (#5790) +- 5712d8201d90bbf3a184353e69e115c13dffbfcb Fix cuVS IVF-Flat workspace sizing after CPU-to-GPU cloning (#5763) +- bce5e24dd753296e241a67dbd0914cb652382fc5 Re-enable the cuVS CAGRA Python tests that hung on cuVS 26.06 (#5770) +- 450dd7928c4d3e33b9a8becc6d470063b6a65f7c Fix AArch64's conda multi output recipe (#5727) +- 55afdff94d07e140bb553397617dfdddfbfb66f3 cmake: install utils/popcount.h (#5744) +- d4a4e3ee300dcd26e6e74116de2118a4a10a684f Fix build for CPUTYPE=znver4 (#5752) +- 56797f9d33a172e2b4ac2dca77be28248c81c53d Match scalar tie-break in AVX2/AVX512 Lloyd-Max encode (#5715) +- 5b4aa4679ca60cf397119f46d7c70d19b612dc64 fbcode/faiss/gpu/utils (#5737) +- a643100c88dbf3a0f06f23fa8d9d7c0b76885200 Faiss OSS nightly autofix (#5731) +- 4f63b42b922a5b41bbc925a7b55043460e548d42 Keep AVX512-TU copies of the AVX2 QBS loop out of the AVX2 path (#5724) +- c966dab152b133411b06687cc8e5888c8ca8ab90 Faiss OSS nightly autofix (#5728) +- 5d635f354ccc22f7a3a9c38d185762cfdfec58fd DD: give PQCodeDistanceScalar a SIMD level so the AVX2 path cannot run AVX512 code (#5719) +- f46050eb56c6458e368496ff74281630fd462e4c Deflake test_io TestIVFPQRead.test_reader (#5718) +- 8b884ecc96d19633ab7d8dedd8c6f4efb9597004 Fix IndexFastScan::reset() leaving stale ntotal2 (crash on search) (#5614) +- d380b7d96c6009bb8d6dbef79222c02fca284df6 Fix IndexFlatCodes::reset on mmap-loaded codes (#5707) +- 6c51305e6410d6b682d5f34f7da1c10bb4a37989 Avoid double-advancing HNSW visited tables (#5596) +- 76978eee4a2d8a603aefced9ecf0a45f60b4dd45 Fix selector handling for IVF iterator scans (#5592) +- 38460ee969aa49990e635853b2d41bf12e3ef235 Fix Faiss fp16 parity tests across architectures (#5695) +- 88a28bcd80aa4469bd15520c510186c98f51d985 Faiss OSS nightly autofix (#5686) +- ec94295adcaaf5d7480ea9ace573eb9e0c8369f9 Bound the fast scan LUT scale by the accumulated sum (#5658) +- 3f08095cee9d36698ad5d72bf19fb7b2dfcb1f8c fix: release SuperKMeans sample buffer after rotation (#5648) +- 02cacc5293e22b800be55c09662e2e22d4c62923 Fix TSAN races in side `hsnw_stats` and `rabitq_stats` (#5657) +- bf8be4a79bdc4d1aac60f4ec0c7190123c973a0a fix(ci): use GCC 14 riscv64 cross-compiler for RVV tuple/zvfhmin intrinsics (#5653) +- 98af2cf627ec8d2f3e149c7d7b60d4ddea7a0ccb Fix osx-arm64 conda build: drop redundant openblas pin, allow single-platform release dispatch (#5652) +- 3778f5892d0c663a6c926609354174b278028321 Fix IDSelector handling in unbounded HNSW search (#5508) + +Deprecated +- 8f176c3d67bf6846e62ad6ade42afd8060bec749 Remove the replicas parameter (#5809) +- de495c95ab75c0a73e19d0d4f3f5598eabfa4cfe Remove redundant contrib, torch, Manifold and telemetry tests (#5801) +- ce25a1036f52a10f5d5faa00212691fa75639b75 Remove redundant Panorama, general index, factory and SWIG tests (#5802) +- ca60fb500fada5a1dc77a8909998fe6191c9ea33 Remove redundant clustering, binary index and SIMD distance tests (#5800) +- 49155804521a7dc32e9049b861bd99a3ba196797 Remove redundant serialization, mmap and deserialization tests (#5798) +- 2f8c1d2b75660a269b7df5e0b7c9c2e9cbe6036e Remove redundant SVS, HNSW, NSG and PiPNN tests (#5799) +- f2130c2ff4c8c7b9a1c730e5b1030832c9848ff9 Remove redundant IVF and search parameter tests (#5803) +- 1c84f080f25f96a7f1e18e946073101eb886b1cb Remove redundant PQ, AQ and SQ fast-scan tests (#5797) +- 20104132da6698dd0e8fa4d35e934ac74e062259 Remove redundant PQ, AQ, SQ and RaBitQ tests (#5796) +- 42aac2fb4e17a66a6b17e7a99e3df229bcf757b8 Remove the cuVS 26.02 compatibility paths from the cuVS GPU code (#5750) + ## [1.15.1] - 2026-09-15 Added @@ -1480,7 +1639,8 @@ by conda install -c pytorch faiss-gpu cudatoolkit=10.0. - C bindings. - Extended tutorial to GPU indices. -[Unreleased]: https://github.com/facebookresearch/faiss/compare/v1.15.1...HEAD +[Unreleased]: https://github.com/facebookresearch/faiss/compare/v1.16.0...HEAD +[1.16.0]: https://github.com/facebookresearch/faiss/compare/v1.15.1...v1.16.0 [1.15.1]: https://github.com/facebookresearch/faiss/compare/v1.15.0...v1.15.1 [1.15.0]: https://github.com/facebookresearch/faiss/compare/v1.14.3...v1.15.0 [1.14.3]: https://github.com/facebookresearch/faiss/compare/v1.14.2...v1.14.3 diff --git a/thirdparty/faiss/CMakeLists.txt b/thirdparty/faiss/CMakeLists.txt index 15b612e7f..2aa63755f 100644 --- a/thirdparty/faiss/CMakeLists.txt +++ b/thirdparty/faiss/CMakeLists.txt @@ -74,7 +74,7 @@ if(FAISS_ENABLE_CUVS) endif() project(faiss - VERSION 1.15.1 + VERSION 1.16.0 DESCRIPTION "A library for efficient similarity search and clustering of dense vectors." HOMEPAGE_URL "https://github.com/facebookresearch/faiss" LANGUAGES ${FAISS_LANGUAGES}) @@ -95,6 +95,7 @@ option(FAISS_ENABLE_PYTHON "Build Python extension." ON) option(FAISS_ENABLE_C_API "Build C API." OFF) option(FAISS_ENABLE_EXTRAS "Build extras like benchmarks and demos" ON) option(FAISS_USE_LTO "Enable Link-Time optimization" OFF) +option(FAISS_WARNINGS_AS_ERRORS "Fail the build of the Faiss library on compiler warnings (GCC and Clang)." OFF) if(APPLE AND CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64") set(_FAISS_METAL_DEFAULT ON) else() @@ -103,6 +104,10 @@ endif() option(FAISS_ENABLE_METAL "Enable Metal GPU backend for Apple Silicon." ${_FAISS_METAL_DEFAULT}) option(FAISS_ENABLE_SVS "Enable SVS (Intel(R) Scalable Vector Search) integration." OFF) +option(FAISS_ENABLE_DISK_IVF "Build IndexIVFRaBitQSSD (Linux only, needs libaio)." OFF) +if(FAISS_ENABLE_DISK_IVF AND NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "FAISS_ENABLE_DISK_IVF is only supported on Linux") +endif() set(FAISS_SVS_RUNTIME_VERSION "v0" CACHE STRING "Version of the SVS runtime API to use") set_property(CACHE FAISS_SVS_RUNTIME_VERSION PROPERTY STRINGS "v0") @@ -122,7 +127,7 @@ if(FAISS_ENABLE_GPU) endif() if(FAISS_ENABLE_CUVS AND NOT TARGET cuvs::cuvs) - find_package(cuvs) + find_package(cuvs REQUIRED) endif() if(FAISS_ENABLE_CUVS AND NOT TARGET rmm::rmm) diff --git a/thirdparty/faiss/INSTALL.md b/thirdparty/faiss/INSTALL.md index ca110e62b..dd3df9fc8 100644 --- a/thirdparty/faiss/INSTALL.md +++ b/thirdparty/faiss/INSTALL.md @@ -12,13 +12,13 @@ To install the latest stable release: ``` shell # CPU-only version -$ conda install -c pytorch -c conda-forge faiss-cpu=1.15.1 +$ conda install -c pytorch -c conda-forge faiss-cpu=1.16.0 # GPU(+CPU) version -$ conda install -c pytorch -c nvidia -c conda-forge faiss-gpu=1.15.1 +$ conda install -c pytorch -c nvidia -c conda-forge faiss-gpu=1.16.0 # GPU(+CPU) version with NVIDIA cuVS -$ conda install -c pytorch -c nvidia -c rapidsai -c conda-forge libnvjitlink faiss-gpu-cuvs=1.15.1 +$ conda install -c pytorch -c nvidia -c rapidsai -c conda-forge libnvjitlink faiss-gpu-cuvs=1.16.0 # GPU(+CPU) version using AMD ROCm not yet available ``` @@ -34,15 +34,15 @@ If you prefer [Pixi](https://pixi.sh/latest/), you can use the same channels and ``` shell # CPU-only version $ pixi init -c pytorch -c conda-forge -$ pixi add faiss-cpu=1.15.1 +$ pixi add faiss-cpu=1.16.0 # GPU(+CPU) version $ pixi init -c pytorch -c nvidia -c conda-forge -$ pixi add faiss-gpu=1.15.1 +$ pixi add faiss-gpu=1.16.0 # GPU(+CPU) version with NVIDIA cuVS $ pixi init -c pytorch -c nvidia -c rapidsai -c conda-forge -$ pixi add libnvjitlink faiss-gpu-cuvs=1.15.1 +$ pixi add libnvjitlink faiss-gpu-cuvs=1.16.0 ``` Pixi resolves packages from the listed Conda channels, so the same channel requirements described above still apply. @@ -54,10 +54,10 @@ Nightly pre-release packages can be installed as follows: $ conda install -c pytorch/label/nightly -c conda-forge faiss-cpu # GPU(+CPU) version -$ conda install -c pytorch/label/nightly -c nvidia -c conda-forge faiss-gpu=1.15.1 +$ conda install -c pytorch/label/nightly -c nvidia -c conda-forge faiss-gpu=1.16.0 # GPU(+CPU) version with NVIDIA cuVS (package built with CUDA 13.2) -conda install -c pytorch -c rapidsai -c rapidsai-nightly -c conda-forge -c nvidia pytorch/label/nightly::faiss-gpu-cuvs 'cuda-version=13.2' +conda install -c pytorch -c rapidsai -c conda-forge -c nvidia pytorch/label/nightly::faiss-gpu-cuvs 'cuda-version=13.2' # GPU(+CPU) version using AMD ROCm not yet available ``` @@ -90,7 +90,7 @@ The optional requirements are: - for AMD GPUs: - AMD ROCm, - for using NVIDIA cuVS implementations: - - libcuvs=26.06 + - libcuvs=26.10 - for the python bindings: - python 3, - numpy, @@ -101,13 +101,13 @@ section of the wiki](https://github.com/facebookresearch/faiss/wiki/Troubleshoot ### Building with NVIDIA cuVS -[cuVS](https://docs.rapids.ai/api/cuvs/nightly/) contains state-of-the-art implementations of several algorithms for running approximate nearest neighbors and clustering on the GPU. It is built on top of the [RAPIDS RAFT](https://github.com/rapidsai/raft) library of high performance machine learning primitives. Building Faiss with cuVS enabled allows a user to choose between regular GPU implementations in Faiss and cuVS implementations for specific algorithms. +[cuVS](https://docs.rapids.ai/api/cuvs/stable/) contains state-of-the-art implementations of several algorithms for running approximate nearest neighbors and clustering on the GPU. It is built on top of the [RAPIDS RAFT](https://github.com/rapidsai/raft) library of high performance machine learning primitives. Building Faiss with cuVS enabled allows a user to choose between regular GPU implementations in Faiss and cuVS implementations for specific algorithms. The libcuvs dependency should be installed via conda: ``` -conda install -c rapidsai -c conda-forge -c nvidia libcuvs=26.06 'cuda-version=13.2' +conda install -c rapidsai -c conda-forge -c nvidia libcuvs=26.10 'cuda-version=13.2' ``` -For more ways to install cuVS 26.06, refer to the [RAPIDS Installation Guide](https://docs.rapids.ai/install). +For more ways to install cuVS 26.10, refer to the [RAPIDS Installation Guide](https://docs.rapids.ai/install). ### Building with Intel(R) SVS @@ -140,6 +140,8 @@ Several options can be passed to CMake, among which: are `ON` and `OFF`), - `-DFAISS_ENABLE_SVS=ON` in order to enable the Intel(R) Scalable Vector Search (SVS) integration (default is `OFF`, possible values are `ON` and `OFF`). Note: This will download and build the SVS runtime library (`libsvs_runtime.so`). When installing the python package, this library will be copied into the package directory. For C++ usage, ensure this library is in your library path. + - `-DFAISS_ENABLE_DISK_IVF=ON` in order to build `IndexIVFRaBitQSSD`, an IVF index whose RaBitQ codes are split between memory and an SSD (default is `OFF`, possible values are `ON` and `OFF`). + Note: Linux only. This requires libaio (`libaio-dev` on Debian/Ubuntu, or `libaio` from conda-forge). - optimization-related options: - `-DCMAKE_BUILD_TYPE=Release` in order to enable generic compiler optimization options (enables `-O3` on gcc for instance), @@ -162,6 +164,11 @@ Several options can be passed to CMake, among which: determine which architecture(s) you should pick), - `-DFAISS_ENABLE_ROCM=ON` in order to enable building GPU indices for AMD GPUs. `-DFAISS_ENABLE_GPU` must be `ON` when using this option. (possible values are `ON` and `OFF`), + - `-DCMAKE_HIP_ARCHITECTURES="gfx90a;gfx942"` for specifying which AMD GPU + architectures to build against when `-DFAISS_ENABLE_ROCM=ON` (see the + [LLVM AMDGPU docs](https://llvm.org/docs/AMDGPUUsage.html#processors) to + determine which architecture(s) you should pick). ROCm installations that do + not ship a default target list require this option, - python-related options: - `-DPython_EXECUTABLE=/path/to/python3.7` in order to build a python interface for a different python than the default one (see @@ -269,6 +276,182 @@ $ ./build/demos/demo_ivfpq_indexing_gpu This produces the GPU code equivalent to the CPU `demo_ivfpq_indexing`. It also shows how to translate indexes from/to a GPU. +### CAGRA datasets and HNSW interop + +With `FAISS_ENABLE_CUVS=ON`, CAGRA builds require a caller-owned +`faiss::gpu::Dataset`. The index owns its graph and borrows vector storage. +`viewHost`, `viewDevice`, and `viewDevicePadded` borrow an existing allocation; +`makeDevicePadded` delegates allocation and padding to cuVS. Like cuVS, it rejects +device/managed input whose row stride already matches the required padding; +use a view for that storage. Preparation runs asynchronously on the resource's +stream, so keep the source allocation alive and unchanged until copying finishes. +The returned Dataset controls the new allocation's lifetime. Calling +`dataset.view()` creates another non-owning descriptor of the same storage +without extending its lifetime. +Public signatures take pointers, extents, strides, and Faiss types, without +requiring RAFT or cuVS types. + +For a packed host Float32 array `xb` with `n` rows and dimension `d`, build a graph +and export independent CPU HNSW storage as follows: + +```cpp +#include +#include +#include +#include + +faiss::gpu::StandardGpuResources resources; +auto source = faiss::gpu::Dataset::viewHost( + xb, n, d, faiss::NumericType::Float32, d); +faiss::gpu::GpuIndexCagra graphOnly(&resources, d); +graphOnly.train(source); // Host data builds a graph; isSearchReady() is false. + +faiss::IndexHNSWCagra cpu(d, 32); +cpu.base_level_only = true; +graphOnly.copyTo(&cpu); // CPU index now owns its graph and packed vectors. + +faiss::gpu::GpuIndexCagra imported(&resources, d); +imported.copyFrom(&cpu); // Imports graph and metadata; isSearchReady() is false. +``` + +The CPU index remains independent of the original Dataset after `copyTo`. +`copyFrom(cpuIndex, Dataset* dataset = nullptr)` imports only the graph and +metadata when the optional Dataset is omitted. It retains no CPU vector storage, +and the CPU index can be destroyed after the call. Graph retrieval remains +available; search and full CPU HNSW export with `copyTo` require attached vectors. + +To import a searchable index, wrap a preallocated writable device buffer with +the regular Dataset API and pass its address. For this Float32 example, +`deviceBuffer` must point to at least `n * stride` floats on device 0, with a +16-byte-aligned base address: + +```cpp +const faiss::idx_t stride = ((static_cast(d) + 3) / 4) * 4; +auto destination = faiss::gpu::Dataset::viewDevicePadded( + deviceBuffer, n, d, faiss::NumericType::Float32, stride, 0); +faiss::gpu::GpuIndexCagra searchable(&resources, d); +searchable.copyFrom(&cpu, &destination); // Fills the buffer; isSearchReady() is true. +``` + +The supplied Dataset must have the CPU index's row count, dimension, and dtype, +and be CAGRA-compatible on the GPU index's device. A compatible standard-layout +device view is also accepted. `copyFrom` copies the CPU vectors into that +allocation and zeroes its padding; previous contents need not be initialized. +The upload completes before return, so the CPU index can then be destroyed. +Ownership stays with the caller, and the GPU index borrows the allocation for +search. `isSearchReady()` derives readiness from the graph and attached Dataset; +there is no separate readiness setting. Keep the allocation alive and unchanged +through index use and queued GPU work. +`GpuIndexBinaryCagra::copyFrom` follows the same optional-output contract with +`UInt8` and dimensions measured in bytes. + +A standard device view is searchable without a vector copy when its base address +is 16-byte aligned and its row stride equals the dimension rounded up to a +16-byte row width. For example, packed Float32 vectors of dimension 12 need no +extra padding. Any padding elements must already be zero. Otherwise, build the +graph from a standard Dataset and explicitly attach prepared storage: + +```cpp +auto padded = faiss::gpu::Dataset::makeDevicePadded(&resources, source, 0); +graphOnly.updateDataset(padded); +``` + +`updateDataset` preserves the graph and borrows already-populated storage; +it does not fill the allocation. The new storage must contain the same vectors +in the same order, shape, and dtype. It checks metadata but cannot verify +vector identity. It can also attach vectors after a graph-only `copyFrom`. +Keep all borrowed allocations alive and unchanged through +index use and queued GPU work; make data ready on the index resource's stream +before use. Caller-supplied CUDA streams must also outlive GPU resources that +cache cuVS allocations, even after reverting the default stream. `reset()` clears +the borrowed binding and allows rebuilding. Repeated `train` or `add` calls on +an already trained CAGRA leave its graph and Dataset unchanged. A moved owning Dataset retains the +allocation and existing bindings. Dimensions and row +strides are in elements; binary CAGRA uses `UInt8` with Dataset dimension equal +to the index's bit dimension divided by eight. + +For preencoded BBQ vectors, populate `faiss::gpu::BBQQuantizer` with device +pointers to the codes, centroid, and correction arrays, then call +`Dataset::viewDeviceBBQ(quantizer, n, d, numericType, device)`; an optional final +quantizer supplies the second layout for asymmetric distances. There is no public +BBQ encoder in this API. Keep every buffer owner alive explicitly, including in +Python: these raw pointers do not retain their allocations. Use +`GpuIndexCagra` with NN-descent and dimensions divisible by 32. Training builds +the graph and leaves `isSearchReady()` false. Call `updateDataset` with the +corresponding dense device-padded vectors before search or CPU HNSW export; +`makeDevicePadded` and `copyToHost` do not decode BBQ storage. + +Building a graph with `train` or `add` requires an explicit Dataset. Their +inherited pointer overloads reject calls; use the Dataset +overloads on `GpuIndexCagra` or `GpuIndexBinaryCagra`. Dataset ownership replaces +`store_dataset`. Pointer APIs for other index families are unchanged. Dataset +construction, build, attachment, and import are available in C++ and Python; +there is no C Dataset binding. Existing CPU HNSW search and serialization remain +available. Generic CPU-to-GPU CAGRA cloning imports the graph only, like +`copyFrom(cpu)`; call `updateDataset` with populated device storage before search. + +In Python, `Dataset.viewHost(array)` borrows a two-dimensional NumPy array and +infers its shape, dtype, and row stride. It accepts `float32`, `float16`, `int8`, +and `uint8`, with contiguous columns, without copying or converting the array. +For example, binary CAGRA uses a `uint8` array with a dimension in bytes: + +```python +import faiss +import numpy as np + +xb = np.random.RandomState(7).randint(0, 256, (512, 19)).astype("uint8") +resources = faiss.StandardGpuResources() +source = faiss.Dataset.viewHost(xb) +storage = faiss.Dataset.makeDevicePadded(resources, source, 0) +resources.syncDefaultStreamCurrentDevice() # xb must survive the async copy. + +config = faiss.GpuIndexCagraConfig() +config.build_algo = faiss.graph_build_algo_NN_DESCENT +config.graph_degree = 16 +config.intermediate_graph_degree = 32 +index = faiss.GpuIndexBinaryCagra(resources, xb.shape[1] * 8, config) +index.train(storage) # add(storage) also builds the entire graph. +assert index.isSearchReady() +distances, labels = index.search(xb[:8], 1) +packed_copy = storage.copyToHost() # An independent, ready NumPy array. + +cpu = faiss.IndexBinaryHNSWCagra() +cpu.base_level_only = True +index.copyTo(cpu) +imported = faiss.GpuIndexBinaryCagra(resources, index.d, config) +imported.copyFrom(cpu) # Graph and metadata only; not search ready. +imported.updateDataset(storage) # Borrows these already-populated vectors. +``` + +For custom IDs, wrap an empty CAGRA in `IndexIDMap` (or `IndexBinaryIDMap`), +then call `mapped.train(storage)` and `mapped.add_with_ids(storage, ids)`. +The IDs must cover every vector in the graph. `IndexIDMap2` variants are also +supported. The wrapper keeps Dataset ownership on the wrapped CAGRA, so deleting +the IDMap does not invalidate a CAGRA that the caller still retains. + +Python retains references to keep borrowed storage alive: `viewHost(array)` +retains the NumPy array, `view()` retains its source Dataset, and CAGRA retains +the Dataset passed to `train`, `add`, `updateDataset`, or `copyFrom`. +Deleting the user's Dataset variable therefore does not invalidate a search-ready +index. Successful replacement, graph-only import, or `reset()` releases the index's +previous Dataset reference; destroying the index also releases it. An owning +Dataset frees its allocation when its last reference is released, including +references from other indexes or views. C++ ownership and stream rules remain +unchanged: preparation is asynchronous, so retain the source until its copy +finishes. Raw-pointer views cannot retain an allocation owner; retain that owner +explicitly. `copyToHost()` waits for device work and returns an independent, +packed NumPy array with the original dtype. For Float16 or Int8 indexes, pass +the matching search type: +`index.search(xq, k, numeric_type=storage.getNumericType())`. + +Use `copyFrom(cpu)` or `copyFrom(cpu, None)` for graph-only import, and +`copyFrom(cpu, destination)` to fill and attach existing device storage under +the contract above. The raw `Dataset.viewDevice` and `Dataset.viewDevicePadded` +argument order is `(data, numRows, dim, numericType, rowStride, device)`. +Convert an integer device address with `faiss.cast_integer_to_void_ptr(address)` +when passing `data`. Raw host-pointer and output operations remain available as +`viewHost_c` and `copyToHost_c`. + ### A real-life benchmark A longer example runs and evaluates Faiss on the SIFT1M dataset. To run it, diff --git a/thirdparty/faiss/benchs/avx512_result_handlers/partition.cpp b/thirdparty/faiss/benchs/avx512_result_handlers/partition.cpp index bb51415fa..8831780be 100644 --- a/thirdparty/faiss/benchs/avx512_result_handlers/partition.cpp +++ b/thirdparty/faiss/benchs/avx512_result_handlers/partition.cpp @@ -60,7 +60,6 @@ constexpr int B = 16; // AVX-512 processes 16 floats at a time struct KVBufferB { __m512 val; __m512i idx; - static constexpr uint32_t nval = B; // always full }; struct KVPartialBuffer { @@ -74,7 +73,7 @@ struct PartialBuffer2B { KVBufferB b1; uint32_t nval = 0; // number of values, size <= 2 * B - // Append a buffer (KVBufferB or KVPartialBuffer) to this 2B buffer + // Append a partial buffer to this 2B buffer template inline void append(const BufferT& partial) { const uint32_t partial_nval = partial.nval; diff --git a/thirdparty/faiss/benchs/bench_hnsw_stats.cpp b/thirdparty/faiss/benchs/bench_hnsw_stats.cpp new file mode 100644 index 000000000..32968d59c --- /dev/null +++ b/thirdparty/faiss/benchs/bench_hnsw_stats.cpp @@ -0,0 +1,75 @@ +/* + * 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. + */ + +#include +#include +#include + +#include +#include +#include +#include + +namespace faiss { +namespace { + +constexpr int kDimension = 8; +constexpr idx_t kDatabaseSize = 1; + +struct BenchmarkIndex { + BenchmarkIndex() : index(kDimension, 2) { + std::vector database(kDatabaseSize * kDimension / 8); + for (size_t i = 0; i < database.size(); ++i) { + database[i] = static_cast(i * 17 + 3); + } + + index.hnsw.efConstruction = 2; + index.add(kDatabaseSize, database.data()); + index.hnsw.efSearch = 1; + } + + IndexBinaryHNSW index; +}; + +const IndexBinaryHNSW& get_index() { + static const BenchmarkIndex benchmark_index; + return benchmark_index.index; +} + +void bench_binary_hnsw_single_query(benchmark::State& state) { + omp_set_num_threads(1); + set_search_stats_enabled(state.range(0) != 0); + constexpr std::array query{}; + int32_t distance; + idx_t label; + + for (auto _ : state) { + get_index().search(1, query.data(), 1, &distance, &label); + benchmark::DoNotOptimize(distance); + benchmark::DoNotOptimize(label); + } + state.SetItemsProcessed(state.iterations()); +} + +BENCHMARK(bench_binary_hnsw_single_query) + ->ArgName("stats") + ->Arg(0) + ->Arg(1) + ->ThreadRange(1, 64) + ->UseRealTime(); + +} // namespace +} // namespace faiss + +int main(int argc, char** argv) { + omp_set_num_threads(1); + faiss::get_index(); + benchmark::Initialize(&argc, argv); + benchmark::RunSpecifiedBenchmarks(); + benchmark::Shutdown(); + return 0; +} diff --git a/thirdparty/faiss/benchs/bench_rabitq_batch_estimates.cpp b/thirdparty/faiss/benchs/bench_rabitq_batch_estimates.cpp index 340e2fe1c..28cab0336 100644 --- a/thirdparty/faiss/benchs/bench_rabitq_batch_estimates.cpp +++ b/thirdparty/faiss/benchs/bench_rabitq_batch_estimates.cpp @@ -5,9 +5,9 @@ * LICENSE file in the root directory of this source tree. */ -// Standalone microbenchmark: four single estimates vs the batch-four API. -// Build target bench_rabitq_batch_estimates, then run with OMP_NUM_THREADS=1 -// and OPENBLAS_NUM_THREADS=1. Query preparation is outside the timed region. +// Microbenchmark: four single estimates against the batch API. +// Build bench_rabitq_batch_estimates. Run it with OMP_NUM_THREADS=1 +// and OPENBLAS_NUM_THREADS=1. #include #include #include @@ -23,11 +23,13 @@ int main() { std::normal_distribution normal; std::printf("dim,round,single_ns_per_code,batch_ns_per_code,speedup\n"); for (int d : {128, 768, 960, 1536}) { - std::vector data(n * d), query(d); - for (auto& v : data) + std::vector data(size_t(n) * d), query(d); + for (auto& v : data) { v = normal(rng); - for (auto& v : query) + } + for (auto& v : query) { v = normal(rng); + } faiss::IndexRaBitQ index(d, faiss::METRIC_L2, 8); index.train(n, data.data()); index.add(n, data.data()); @@ -55,8 +57,9 @@ int main() { dc.distance_to_code_1bit(codes[i + j]); } } - for (float distance : distances) + for (float distance : distances) { checksum += distance; + } } } const double ns = std::chrono::duration( diff --git a/thirdparty/faiss/benchs/e_means/README.md b/thirdparty/faiss/benchs/e_means/README.md new file mode 100644 index 000000000..0ca0567d3 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/README.md @@ -0,0 +1,451 @@ +# Reproducing the e-means paper + +e-means is a modern, robust replacement for k-means developed at Meta FAIR. e-means delivers a **~10× speedup in epochs and wall-clock** while achieving **lower loss** compared to Lloyd's k-means, with no additional hyperparameters. e-means uses a mini-batch update rule specialized for the k-means problem, based on exponential moving averages. More details can be found in [arXiv](https://arxiv.org/abs/2611.09501) [Browser demo](https://e-means.github.io/playground.html). +The main implementation of e-means is in [`contrib/e_means`](https://github.com/facebookresearch/faiss/tree/main/contrib/e_means), we refer to the documentation therein for an introduction to the API. + +This document and code explains how to reproduce key results from the paper. + +If you use e-means for scientific work, please cite our paper using the following BibTeX entry: + +```bibtex +@misc{bessa2026emeans, + title = {{e-means}: outperforming {k-means} (in one-tenth the epochs)}, + author = {Bessa, Swann and Mazar{\'e}, Pierre-Emmanuel and Szilvasy, Gergely and + Touvron, Hugo and Picard, David and Douze, Matthijs and J{\'e}gou, Herv{\'e}}, + year = {2026}, + note = {Preprint}, + url = {https://arxiv.org/abs/2611.09501} +} +``` + +Code contributors: Gergely Szilvasy, Swann Bessa, Matthijs Douze + +## 1. What you need + +- **One 80 GB SM90 GPU.** The CuTe kernels are tuned for it, and the timings are only + comparable to the paper's on it. The 100M results put 20 to 51 GB of data on the card. Figure + 3's Faiss arm runs on CPU cores. +- **Software.** `faiss.contrib.e_means` is in the faiss repository but not yet in a faiss + release, so install faiss from PyPI for its compiled core and add the library from a checkout of + the repository: + + ```bash + python -m venv emeans && source emeans/bin/activate + pip install torch faiss-cpu + pip install quack-kernels==0.6.5 nvidia-cutlass-dsl==4.7.1 "cuda-python>=13,<14" # CuTe kernels + pip install flash-kmeans==0.3.1 h5py matplotlib # the baseline (exactly 0.3.1), ImageNet-CLIP, plots + git clone https://github.com/facebookresearch/faiss.git + cp -r faiss/contrib/e_means "$(python -c 'import faiss, os; print(os.path.dirname(faiss.__file__))')/contrib/" + cd faiss/benchs/e_means + ``` + + These exact commands were run from scratch on such a GPU (they installed PyTorch 2.15.0, Triton + 3.9.0 and faiss-cpu 1.15.1): every Table 3 seed tested crossed at the same budget as in the + paper, with the same test errors, and the e-means test suite passed. The paper's numbers were + measured with PyTorch 2.14 and Triton 3.8. Flash-KMeans is written in Triton, so its times can + move by a few percent with the Triton version. + + +### Minimal DEEP* 10M run, one seed + +With the software above installed, download only the needed DEEP* prefix +(3,843,840,008 bytes: an 8-byte header and 10,010,000 rows of 96 float32 values). +The extra 10,000 rows supply the paper's evaluation split: + +```bash +curl --fail --location --range 0-3843840007 \ + --output /tmp/base.1B.fbin.part \ + https://huggingface.co/datasets/suchun/deep1b-mirror/resolve/main/base.1B.fbin +python demo_deep10m.py +``` + +The script [`demo_deep10m.py`](demo_deep10m.py) reads the `.fbin` header and +memory-maps only this prefix with NumPy. + +This runs seed 123 with 65,536 clusters for 2 epochs (Table 3's reported +DEEP* 10M budget), +with the quality batch recipe, float32 input cast to bfloat16 per batch, CuTe +assignment, and the paper's warm-up, timing and test split. +For readability of this small test the starting centroids +are sampled without replacement using a seeded NumPy generator, so their +values differ from the paper's CUDA initialization, and it runs with a single seed. +It prints training seconds and test MSE. Seed 10's paper Flash@25 test MSE is +`0.3423`. + + +Run the mini-test with +```bash +python demo_deep10m.py +``` + +The output should look similar to: +
+ Click to expand + +``` +Load data: /tmp/base.1B.fbin.part, 10,010,000 vectors of dimension 96, float32 +Loaded 10,000,000 x 96 training values onto the GPU: 3.84 GB in 1.55 s +Sample test set: 5,000 x 96 from 10,000 evaluation rows, seed 1234 +Sample initialization: 65,536 x 96 from 10,000,000 training rows, seed 123 +E-means warm-up: n=10,000,000, d=96, k=65,536, epochs=2, seed=123, quality/CuTe/bfloat16 +Warm-up complete: 14.8146 s, batch=65,536, steps=306, alpha0=0.0705062, last-pass objective=3.38942e+06 +E-means run 1: n=10,000,000, d=96, k=65,536, epochs=2, seed=123, quality/CuTe/bfloat16 +Run 1 complete: 0.5188 s, batch=65,536, steps=306, alpha0=0.0705062, last-pass objective=3.38942e+06 +E-means run 2: n=10,000,000, d=96, k=65,536, epochs=2, seed=123, quality/CuTe/bfloat16 +Run 2 complete: 0.5198 s, batch=65,536, steps=306, alpha0=0.0705062, last-pass objective=3.38942e+06 +E-means run 3: n=10,000,000, d=96, k=65,536, epochs=2, seed=123, quality/CuTe/bfloat16 +Run 3 complete: 0.5191 s, batch=65,536, steps=306, alpha0=0.0705062, last-pass objective=3.38942e+06 +DEEP* 10M: 10,000,000 vectors, 65,536 clusters, 2 epochs, seed 123 +GPU: +Input: float32, cast to bfloat16 per batch; CuTe assignment +Training time: 0.5191 s +Timed calls: 0.5188 s, 0.5198 s, 0.5191 s +Test MSE (5,000 held-out vectors): 0.34197278 +``` + +
+This example reaches MSE=0.34197278 in about +half a second on one 80 GB GPU. This is a better MSE than Lloyd's reference MSE of 0.3423. +The script scores in float32 and uses different +starting centroids from the paper, and runs in a single seed. +Read on for the full runs. + + +## 2. Reproducing Table 3, Figure 4(b) and Figure 3 + +The `paper_*` files in this folder re-measure the timed results of the e-means paper with the +e-means that ships in faiss (`faiss.contrib.e_means`), against the baseline the paper used for +each result, with the paper's timing protocol. You choose how far to go (1M, 10M or 100M rows), +download only the data that choice needs, and run one command per result. + +| Paper result | What it shows | Compared with | Scales | +|---|---|---|---| +| Table 3 | epochs e-means needs to reach Flash-KMeans' error after 25 iterations, and how much faster it gets there | Flash-KMeans 0.3.1 | 1M, 10M, 100M rows | +| Figure 4(b) | test error against wall-clock time | Flash-KMeans 0.3.1 | 10M, 100M rows | +| Figure 3 | training and test error against epochs (no timing) | Faiss k-means on the CPU | 1M, 10M rows | + +**Not covered:** Table 3's 1B row and its DINOv3 cell at 100M rows (several GPUs, or more memory +than one GPU holds), the Faiss-GPU and cuML curves of Figure 4(b), and the k-means++ Faiss, Sculley +and Staleness-Reduction curves of Figure 3. + +### Choose your scale and download the data + +Each scale includes the ones below it. Larger scales read a longer prefix of the large corpora, +so **the download grows about fivefold per step**: + +| Choice | Download | Time at 25 MB/s (200 Mbit/s) | Time at 250 MB/s | Results you can reproduce | +|---|---|---|---|---| +| `--results 1M` | 4.5 GB | about 3 min | under a minute | Table 3, 1M row. Figure 3, DEEP* 1M and ImageNet-CLIP 1M | +| `--results 10M` | 21.7 GB | about 14 min | about 1 min | the above, plus Table 3, 10M row. Figure 4(b), upper row. Figure 3, SPACEV 10M and SIFT 10M | +| `--results 100M` | 100.8 GB | about 67 min | about 7 min | the above, plus Table 3, 100M row. Figure 4(b), lower row | + +```bash +export EMEANS_DATA=/path/to/data # where the files go +export EMEANS_CACHE=/path/to/cache # small files written by the scripts +python paper_download.py --results 1M --dry-run # prints the table above and the file list +python paper_download.py --results 1M # asks for confirmation, then downloads +``` + +Measured from our cluster (16 parallel requests, 270 to 400 MB/s): `--results 1M` took 82 s, moving up to `10M` 58 s more, and up to `100M` 305 s more. + +`paper_download.py` fetches only the bytes each result reads, with parallel HTTP range requests: +a prefix of each corpus, and, for SPACEV and SimSearchNet++, the 20,000 held-out test rows, saved +in a small `heldout_rows.npy` beside the corpus (they sit near the end of files of 140 and 256 GB, +which therefore need not be downloaded). An interrupted download resumes where it stopped, and +moving to a larger scale later only fetches what is missing. At the end it checks every dataset +against fingerprints of the paper's own arrays and stops on any difference, so a wrong or corrupted +file cannot produce plausible-looking numbers. Then build the Flash-KMeans copy the paper used on +two corpora, once: + +```bash +python paper_flash_matched.py +``` + +## 3. Run + +### Full benchmark commands + +One GPU per command. Every timed run is written once to its own JSON file under `--out` (default +`./results`), named after everything that varies, so an interrupted command resumes and several +commands can run in parallel on different GPUs (pass `--dataset` to split the work). + +```bash +# Table 3: one row at a time, then print it +python paper_bench.py table3 --scale 1M # also --scale 10M, --scale 100M +python paper_bench.py table3 --print + +# Figure 4(b): one row at a time, then draw it +python paper_bench.py figure4 --scale 10M # also --scale 100M +python paper_bench.py figure4 --plot # figure4.pdf + +# Figure 3: e-means first (it draws the starting rows on the GPU), then Faiss on the CPU +python paper_bench.py figure3 --method emeans +python paper_bench.py figure3 --method faiss +python paper_bench.py figure3 --plot # figure3.pdf + +# any setting: a dataset, seeds, e-means budgets in epochs, Flash budgets in iterations +python paper_bench.py run --dataset deep1b-10M --seeds 10 11 --epochs 1 2 --flash-iters 25 +``` + +## 4. Compare with the paper without re-running the baseline + +`paper_targets.json` holds the paper's baseline measurements, per dataset and seed (10 to 19): +Flash-KMeans' test error and time after 25 iterations, Flash-KMeans' whole Figure 4(b) curve (1 +to 100 iterations), and Faiss's error after 25 iterations for Figure 3. You can therefore time +e-means alone and compare it with them: + +```bash +python paper_bench.py crossing --dataset fb-ssnpp-1M --seeds 10 11 12 --target paper +python paper_bench.py figure4 --plot # with no local Flash runs, Flash is drawn from the file +``` + +Test errors transfer to any hardware. Times transfer only to the same GPU model. + +## 5. How the numbers are measured + +- **One timed run** is a fresh process. It loads the data, takes the paper's starting centroids + (the first k rows of a permutation drawn by a seeded CUDA generator, identical for both + methods), makes one untimed identical warm-up call (two iterations for Flash-KMeans), then times + one call between two GPU synchronizations, or the median of three when it took under 2 s. + Loading, starting centroids and scoring are not timed. Both methods of a dataset and seed run in + the same job, on the same GPU. +- **The test error** is the mean over the test rows of the squared distance to the nearest + centroid: nearest by an IEEE float32 product (TF32 off), distance recomputed by direct difference + in float64. The test rows are the second half of each dataset's frozen evaluation set. +- **e-means** runs the library's default recipe (the "throughput" batch at 1M rows, the "quality" + batch above), bfloat16 assignment with its CuTe kernels. Float32 data goes through + `CastQuantizer(d, torch.bfloat16)` (through `QuantizedEmeans`). SimSearchNet++ at 100M rows, whose float32 copy does not fit + one GPU, is cast to bfloat16 once (exact for its uint8 values). `--input cast|bf16` forces either. + A budget of T epochs is its own run, whose schedule anneals over T epochs. +- **Flash-KMeans** must be release 0.3.1 (any other is refused). It runs its standard function + `batch_kmeans_Euclid` in float16 on data held on the GPU, every iteration forced. On SPACEV it uses + a copy with squared norms in float32, and on SimSearchNet++, whose squared norms overflow + float16, that copy's large-N function. +- **Table 3:** per seed, Flash-KMeans' error after 25 iterations is the target, and e-means runs 1.0, + 1.2, 1.4, ... epochs and the first budget at or below the target is the seed's crossing. The + seed's speedup is Flash's time over e-means' time there. A cell is the upper median of the + crossings and the median of the per-seed speedups. +- **Figure 4(b):** each point is the median over seeds of the run time, against the median over + seeds of the error in percent above Flash's median error after 25 iterations (the zero line). +- **Figure 3:** training error is each method's error on its own last-pass assignment over every + training row. Each curve is the mean over seeds, divided by Faiss after 25 iterations. + +## 6. The files + +| File | What it is | +|---|---| +| `paper_download.py` | Downloads the data for the scale you choose and checks it | +| `paper_bench.py` | The command line: `run`, `crossing`, `table3`, `figure4`, `figure3`, `targets`, `compare` | +| `paper_xb.py` | The timing protocol, how each method is called, and the test-error scorer | +| `paper_data.py` | The datasets and the paper's evaluation split, checked against the paper's arrays | +| `paper_flash_matched.py` | Builds the Flash-KMeans 0.3.1 copy with float32 squared norms | +| `paper_targets.json` | The paper's baseline measurements, per dataset and seed | +| `paper_splits/` | Held-out row numbers, and fingerprints of the paper's arrays | + +## 7. Where the data comes from + +| Dataset | Source | +|---|---| +| DEEP* | Deep1B (`base.1B.fbin`, `query.public.10K.fbin`), from the Hugging Face mirror `suchun/deep1b-mirror` | +| SIFT | BigANN, `https://dl.fbaipublicfiles.com/billion-scale-ann-benchmarks/bigann/` | +| SPACEV 1M, 10M | SPACEV1B (Microsoft), the original parts `vectors.bin/vectors_N.bin`, from the Hugging Face mirror `jkhe/spacev1b` | +| SPACEV 100M | a 100M sample of SPACEV (not a prefix of the 1B file), Hugging Face `unum-cloud/ann-spacev-100m` | +| SimSearchNet++ | `https://dl.fbaipublicfiles.com/billion-scale-ann-benchmarks/FB_ssnpp_database.u8bin` | +| DINOv3 | `https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/` (first chunk, and `queries_clean.bvecs`) | +| ImageNet-CLIP | the VIBE benchmark (Jääsaari et al., 2025), Hugging Face `vector-index-bench/vibe` | + +Each mirror was checked to hold the same bytes as the copies the paper used. + +## 8. Our run + +Run on 80 GB GPUs with `faiss.contrib.e_means`, PyTorch 2.14, Triton 3.8, CUTLASS DSL 4.7.1 and Flash-KMeans 0.3.1 in the same environment, seeds 10 to 19, every rule above. The campaign ran on the code before it was merged into faiss. Re-running Table 3 at 1M and 10M and Figure 3 on faiss `main` gave the same crossing on every seed and the same test errors. + +These timings include a fix to the CuTe argmin decode cache, which is being made separately. Without it, a budget with a partial epoch (1.2, 1.4, ... epochs) recompiles a kernel on every call when the vectors are wide, which adds about 0.3 s per call on SimSearchNet++ and DINOv3 at 1M rows, so their Table 3 speedups come out far lower. Test errors and crossings are unaffected. + +**Table 3.** Epochs, then speedup over Flash-KMeans at 25 iterations (10 seeds per cell). "Research code" is the paper's earlier re-timing of the authors' implementation, with Flash under PyTorch 2.8 and Triton 3.4. + +| Dataset | `--input cast` (default) | `--input bf16` | Research code | +|---|---|---|---| +| DEEP* 1M | 2.0, 12.8x | 2.0, 14.3x | 2.0, 10.6x | +| DINOv3/4096 1M | 2.0, 12.7x | 2.0, 14.3x | 2.0, 18.2x | +| SPACEV 1M | 2.4, 9.5x | 2.4, 10.5x | 2.4, 11.4x | +| SimSearchNet++ 1M | 1.4, 12.9x | 1.4, 14.3x | 1.4, 12.8x | +| DEEP* 10M | 2.0, 27.8x | 2.0, 28.8x | 2.0, 26.0x | +| DINOv3/4096 10M | 1.4, 23.3x | 1.4, 24.0x | 1.6, 26.3x | +| SPACEV 10M | 2.0, 19.2x | 2.0, 20.6x | 2.2, 24.0x | +| SimSearchNet++ 10M | 1.6, 23.8x | 1.6, 24.9x | 1.6, 18.3x | +| DEEP* 100M | 2.0, 27.0x | 2.0, 27.0x | 2.0, 30.0x | +| SPACEV 100M | 1.4, 35.9x | 1.4, 36.1x | 1.4, 37.8x | +| SimSearchNet++ 100M | -- | 2.6, 19.9x | 2.6, 11.6x | + +The two input routes cross at the same budget on every seed and give bit-identical test errors on every run. Pre-casting is faster by the cost of the per-batch conversion, about 10% at k=16,384, 4% at k=65,536 and 0.6% at k=262,144. SimSearchNet++ at 100M runs pre-cast only (its float32 copy does not fit one GPU). + +**Figure 4(b).** First e-means budget at or below Flash@25 (speedup), and e-means after 25 epochs relative to Flash@25, medians over seeds 10 to 19. + +| Panel | First budget at or below Flash@25 | 25 epochs | +|---|---|---| +| DEEP* 10M | 2 epochs (31.0x) | -0.64% | +| SPACEV 10M | 2 epochs (19.9x) | -1.04% | +| SimSearchNet++ 10M | 2 epochs (21.5x) | -0.60% | +| SIFT/512 10M | 2 epochs (29.4x) | -0.52% | +| DEEP* 100M | 3 epochs (17.1x) | -0.54% | +| SPACEV 100M | 2 epochs (25.5x) | -4.20% | +| SimSearchNet++ 100M | 3 epochs (17.3x) | -0.39% | +| SIFT/512 100M | 2 epochs (24.3x) | -0.43% | + +**Figure 3.** e-means after 25 epochs, test error relative to Faiss after 25 iterations (mean over seeds 10 to 19): DEEP* 1M 0.9909, ImageNet-CLIP 1M 0.9889, SPACEV 10M 0.9898, SIFT 10M 0.9951. + +Every Flash-KMeans target behind these numbers is in `paper_targets.json`. + +**Cost on one 80 GB GPU** (wall time of our jobs, fresh processes and loading included, both input +routes): Table 3 took 8 to 29 minutes per 1M dataset and 35 to 49 minutes per 10M dataset (10 +seeds each), and about 70 minutes per 100M dataset and seed including that seed's Figure 4 +e-means curve. A Figure 4 seed at 10M rows took about 13 minutes. At 100M, Flash's curve is the +long part: 100 iterations alone took 30 minutes (DEEP*) to 57 minutes (SimSearchNet++). Figure 3's +e-means arm took 4 to 46 minutes per dataset (10 seeds), and its Faiss arm about 2 minutes per +seed at 1M rows and 50 at 10M on 32 CPU cores. + +## 9. Large scale e-means DINO with approximate assignment + +These demos show e-means training on the public DINO10B dataset in +a scalable way. + +The code is primarlily intended to run on a single multi-GPU machine. +Every worker holds one contiguous centroid shard and an equal row contribution +per global batch. `k`, `n`, and the resolved global batch size must divide by +the number of workers. + +Both `demo_sharded_centroids.py` and `demo_training_from_ssd.py` accept +fractional `--epochs`, including budgets below one pass. The rounded fractional +row count must also divide by the number of workers. For a budget of 2.6, +training runs a full pass, a 0.6 pass, then a final full pass for closing means. +Below one epoch, only the sampled prefix contributes to closing means. + +### Download DINO10B + +The public corpus is at +https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/. +All training demos need the first base chunk and the held-out test queries: + +- `chunked_base_10B/chunk_0000.bvecs`: 200,000,000 vectors, + 205,600,000,000 bytes (about 191.5 GiB). +- `queries_clean.bvecs`: 100,000 held-out queries, + 102,800,000 bytes (about 98 MiB). + +Both files contain 1,024 uint8 coordinates per vector, preceded by a four-byte +little-endian dimension header. Use an SSD-backed location with enough free +space. The commands below use `/tmp/DINO10B`; replace that root throughout +and pass `--data PATH` to the demos if you use another location. + +Download the public instructions and the clustering data: + +```bash +mkdir -p /tmp/DINO10B/chunked_base_10B +# minimal test +wget -c -O /tmp/DINO10B/README.md \ + https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/README.md +wget -c -O /tmp/DINO10B/queries_clean.bvecs \ + https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/queries_clean.bvecs +# the test set comes from here +wget -c -O /tmp/DINO10B/train_queries_99M.bvecs \ + https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/train_queries_99M.bvecs +for i in {0000..0049}; do + wget -c -O /tmp/DINO10B/chunked_base_10B/chunk_$i.bvecs \ + https://dl.fbaipublicfiles.com/large_objects/dino_vitl_10B/chunked_base_10B/chunk_$i.bvecs +done +``` + +The complete corpus takes about 10.28 TB but if you can download only a subset +for smaller scale tests, eg. chunk_0000.bvecs, ..., chunk_0004.bvecs is enough +for tests at 1B scale. For the default MSE evaluation, also place +`train_queries_99M.bvecs` in `/tmp/DINO10B`. Nearest-neighbor ground truth is not needed. + +#### Held-out MSE + +Both training demos evaluate every test vector after each epoch and again +after finalization, including any final closing-mean update. `test_mse` is +the average squared L2 distance to the nearest centroid. + +By default, evaluation uses the first `min(n, 50000)` vectors from +`train_queries_99M.bvecs`. These vectors are separate from the +`chunked_base_10B` corpus used for clustering. + +To reproduce the old query-based results, pass `--test-on-queries`. The shipped +100,000 vectors in `queries_clean.bvecs` are permuted with Numpy +`RandomState(1234)`; the first half is reserved for validation and the second +half is evaluated, matching the reference's test set. + + +### Reproducing the DINO10B e-means+IVF results + +The results of the scaling plot of Figure 1 are from tables 20 and 21 (for n=10B vectors and n=1B vectors +respectively. +They can be reproduced with the code below. + +#### 1B scale repro + +This needs 4 GPUs (of one model for timing). The following command reproduces the setting with +3 epochs, IVF1024 and L_IVF=4: + +```bash +python demo_training_from_ssd.py \ + --launch 4 --data /tmp/DINO10B \ + --n 1000_000_000 --k $((1<<21)) \ + --epochs 2 --nlist 1024 --nprobe 4 \ + --seed 1 --final-closing-mean \ + --batch-size $((1<<21)) --ssd-ram-gib 100 +``` + +Each epoch logs `train_assignment_mse`, the error after taking means under +that epoch's fixed assignments, and `test_mse`, computed with fresh exhaustive +assignments. Training error is computed from sums and counts without another +SSD scan; cancellation and FP32 sum rounding can affect its accuracy. It +does not reassign training rows to the updated centroids. + +The output of this code should look like [this](https://gist.github.com/mdouze/fa52b4f73cdc83c9d7e961229ea67b09). +The final test MSE is 143958, which is close to 14.389e4 reported in the paper (which is an average over 10 seeds). + +The options are: + +- `--launch 4` means running on 4 GPUs. The command can also be launched with torchrun or slurm on multiple machines. + +- `--final-closing-mean` does a final pass to compute the final centroids. +The alternative is to accumulate them during the last epoch, but this uses more GPU memory. + +- `--batch-size` overrides the batch size. In general, use the largest possible that fits on the GPU + +- `--ssd-ram-gib` sets the batch prefetch cache size. Higer can be faster when the ssd I/O is slow. + +Add `--exact` to use `EmeansShardedCentroids` with exhaustive BF16 assignment +instead of IVF. In this mode, `--nlist` and `--nprobe` are ignored; SSD loading, +fractional epochs, query evaluation, and saved-assignment closing are unchanged. + +To run regular Lloyd k-means on the same data, add `--kmeans` and specify +`--batch-size`, for example: + +```bash +python demo_training_from_ssd.py \ + --launch 4 --data /tmp/DINO10B \ + --n 1000_000_000 --k $((1<<21)) \ + --epochs 3 --nlist 1024 --nprobe 4 \ + --seed 1 --kmeans \ + --batch-size $((1<<21)) --ssd-ram-gib 100 +``` + +Fractional budgets are supported: `--epochs 2.6` means two complete Lloyd +updates and one update from a 0.6-pass sample. + + +#### 10B scale repro + +Similarly, the 10B command is: +```bash +python demo_training_from_ssd.py \ + --launch 8 --n 10_000_000_000 --k $((1<<24)) \ + --epochs 1.5 --ivf --nlist 4096 --nprobe 4 \ + --batch-size $((1<<21)) --ssd-ram-gib 120 \ + --final-closing-mean +``` + +The ouput looks like [this gist](https://gist.github.com/mdouze/6e0d8d2677a514b3d72e3e9b2bdf2680). +This runs in 2605.09 s (5/7 GPU hours) and obtains test MSE = 126902, which is close to the result reported in tab 20: MSE=12.682e4 in 7.5h (the paper's results were obtained with a slightly slower version of the code). diff --git a/thirdparty/faiss/benchs/e_means/ctypes_liburing.py b/thirdparty/faiss/benchs/e_means/ctypes_liburing.py new file mode 100644 index 000000000..f3be9cea2 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/ctypes_liburing.py @@ -0,0 +1,340 @@ +# 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. + +"""The reference ctypes io_uring subset: aligned READ requests without wheels. + +Submission uses membarrier before publishing SQEs and after waiting for CQEs, +including on ARM. Completion heads are published at the next submission. +The caller must keep writable buffers alive until their requests complete. +""" +from __future__ import annotations + +import ctypes +import errno +import mmap +import os +import platform +import struct + + +# Linux userspace ABI: fixed per architecture, forever. io_uring numbers +# are shared; only membarrier differs. +_SYSCALLS = { + # nr_setup, nr_enter, nr_membarrier + "x86_64": (425, 426, 324), + "aarch64": (425, 426, 283), + "arm64": (425, 426, 283), # Darwin spelling; harmless if unused +} + +# membarrier commands (linux/membarrier.h). +_MEMBARRIER_REGISTER_PRIVATE_EXPEDITED = 0x10 +_MEMBARRIER_PRIVATE_EXPEDITED = 0x08 + +_IORING_OP_READ = 22 +_IORING_ENTER_GETEVENTS = 1 +_IORING_OFF_SQ_RING = 0 +_IORING_OFF_CQ_RING = 0x8000000 +_IORING_OFF_SQES = 0x10000000 +_SQE_BYTES = 64 +_CQE_BYTES = 16 + + +_libc = ctypes.CDLL(None, use_errno=True) +# libc syscall returns -1 and sets errno. Full-width arguments preserve +# pointers on 64-bit platforms. +_libc.syscall.argtypes = [ctypes.c_long] * 7 +_libc.syscall.restype = ctypes.c_long + + +def _syscall(nr, a1=0, a2=0, a3=0, a4=0, a5=0, a6=0): + result = _libc.syscall(nr, a1, a2, a3, a4, a5, a6) + return -ctypes.get_errno() if result == -1 else result + + +class _SqOffsets(ctypes.Structure): + _fields_ = [ + ("head", ctypes.c_uint32), + ("tail", ctypes.c_uint32), + ("ring_mask", ctypes.c_uint32), + ("ring_entries", ctypes.c_uint32), + ("flags", ctypes.c_uint32), + ("dropped", ctypes.c_uint32), + ("array", ctypes.c_uint32), + ("resv1", ctypes.c_uint32), + ("resv2", ctypes.c_uint64), + ] + + +class _CqOffsets(ctypes.Structure): + _fields_ = [ + ("head", ctypes.c_uint32), + ("tail", ctypes.c_uint32), + ("ring_mask", ctypes.c_uint32), + ("ring_entries", ctypes.c_uint32), + ("overflow", ctypes.c_uint32), + ("cqes", ctypes.c_uint32), + ("flags", ctypes.c_uint32), + ("resv1", ctypes.c_uint32), + ("resv2", ctypes.c_uint64), + ] + + +class _Params(ctypes.Structure): + _fields_ = [ + ("sq_entries", ctypes.c_uint32), + ("cq_entries", ctypes.c_uint32), + ("flags", ctypes.c_uint32), + ("sq_thread_cpu", ctypes.c_uint32), + ("sq_thread_idle", ctypes.c_uint32), + ("features", ctypes.c_uint32), + ("wq_fd", ctypes.c_uint32), + ("resv", ctypes.c_uint32 * 3), + ("sq_off", _SqOffsets), + ("cq_off", _CqOffsets), + ] + + +assert ctypes.sizeof(_Params) == 120, ctypes.sizeof(_Params) + + +_registered = False + + +def _fence(): + """A full memory barrier both CPUs honor. Raises, never degrades.""" + global _registered + nr = _numbers()[2] + if not _registered: + rc = _syscall(nr, _MEMBARRIER_REGISTER_PRIVATE_EXPEDITED, 0, 0) + if rc != 0: + raise OSError( + -rc if rc < 0 else rc, "membarrier registration failed" + ) + _registered = True + rc = _syscall(nr, _MEMBARRIER_PRIVATE_EXPEDITED, 0, 0) + if rc != 0: + raise OSError(-rc if rc < 0 else rc, "membarrier fence failed") + + +def _numbers(): + """(setup, enter, membarrier) syscall numbers for this CPU.""" + try: + return _SYSCALLS[platform.machine()] + except KeyError: + raise OSError( + errno.ENOSYS, + "no syscall numbers for architecture %r (have: %s)" + % (platform.machine(), sorted(_SYSCALLS)), + ) + + +def _u32(view, offset): + return struct.unpack_from("I", view, offset)[0] + + +def _put_u32(view, offset, value): + struct.pack_into("I", view, offset, value & 0xFFFFFFFF) + + +class _Sqe: + """A reserved submission slot; fields land in the shared ring.""" + + def __init__(self, ring, index): + self._ring = ring + self._off = index * _SQE_BYTES + + @property + def user_data(self): + return struct.unpack_from("Q", self._ring._sqes, self._off + 32)[0] + + @user_data.setter + def user_data(self, value): + struct.pack_into("Q", self._ring._sqes, self._off + 32, value) + + +class _Ring: + def __init__(self): + self.fd = -1 + self.entries = 0 + self._sq = None + self._cq = None + self._sqes = None + self._sq_mask = 0 + self._cq_mask = 0 + self._sq_tail = 0 + self._cq_head = 0 + self._pending = 0 + self._closed = False + + +class _Cqe: + def __init__(self): + self.res = 0 + self.user_data = 0 + + +def io_uring(): + """An uninitialized ring; pass it to io_uring_queue_init next.""" + return _Ring() + + +def io_uring_cqe(): + """A completion holder; peek_cqe fills its res/user_data.""" + return _Cqe() + + +def io_uring_queue_init(entries, ring, flags): + """Create the ring: setup syscall plus the three shared mappings.""" + if flags != 0: + raise ValueError( + "only flags=0 (plain syscall-driven ring); got %r" % (flags,) + ) + if entries <= 0 or entries & (entries - 1): + raise ValueError( + "entries must be a positive power of two, not %r" % (entries,) + ) + nr_setup = _numbers()[0] + params = _Params() + params.sq_entries = entries + fd = _syscall(nr_setup, int(entries), ctypes.addressof(params)) + if fd < 0: + err = -fd + if err == errno.ENOSYS: + raise OSError( + err, + "io_uring_setup missing: pre-5.1 kernel, " + "seccomp-blocked io_uring, or wrong syscall " + "numbers for %s" % platform.machine(), + ) + raise OSError(err, "io_uring_setup failed") + if params.cq_entries < entries: + os.close(fd) + raise OSError( + "CQ ring holds %d entries for a depth-%d queue; " + "cannot bound completions" % (params.cq_entries, entries) + ) + sq_size = params.sq_off.array + entries * 4 + cq_size = params.cq_off.cqes + params.cq_entries * _CQE_BYTES + ring.fd = fd + try: + sq = ring._sq = mmap.mmap( + fd, sq_size, offset=_IORING_OFF_SQ_RING, access=mmap.ACCESS_WRITE + ) + cq = ring._cq = mmap.mmap( + fd, cq_size, offset=_IORING_OFF_CQ_RING, access=mmap.ACCESS_WRITE + ) + sqes = ring._sqes = mmap.mmap( + fd, + entries * _SQE_BYTES, + offset=_IORING_OFF_SQES, + access=mmap.ACCESS_WRITE, + ) + except Exception: + io_uring_queue_exit(ring) + raise + # Identity submission map: slot i consumes SQE i. Written once; the + # kernel never touches it again. + for i in range(entries): + _put_u32(sq, params.sq_off.array + i * 4, i) + ring.fd = fd + ring.entries = entries + ring._sq = sq + ring._cq = cq + ring._sqes = sqes + ring._sq_mask = _u32(sq, params.sq_off.ring_mask) + ring._cq_mask = _u32(cq, params.cq_off.ring_mask) + ring._sq_off = params.sq_off + ring._cq_off = params.cq_off + return 0 + + +def io_uring_queue_exit(ring): + """Unmap the rings and close the fd. Idempotent.""" + if ring._closed: + return + ring._closed = True + try: + for mapping in (ring._sq, ring._cq, ring._sqes): + if mapping is not None: + mapping.close() + finally: + if ring.fd >= 0: + os.close(ring.fd) + ring.fd = -1 + + +def io_uring_get_sqe(ring): + """Reserve a submission slot, or None when the queue is full.""" + if ring._pending >= ring.entries: + return None + slot = (ring._sq_tail + ring._pending) & ring._sq_mask + ring._pending += 1 + return _Sqe(ring, slot) + + +def _buf_address(buf): + try: + return ctypes.addressof(ctypes.c_char.from_buffer(buf)) + except (TypeError, BufferError) as exc: + raise TypeError( + "prep_read needs a writable contiguous buffer " + "(mmap, bytearray); got %s: %s" % (type(buf).__name__, exc) + ) + + +def io_uring_prep_read(sqe, fd, buf, nbytes, offset): + """Point a reserved slot at an O_DIRECT read. Mirrors the C call.""" + addr = _buf_address(buf) + ring = sqe._ring + off = sqe._off + ring._sqes[off : off + _SQE_BYTES] = b"\0" * _SQE_BYTES + view = ring._sqes + struct.pack_into("B", view, off, _IORING_OP_READ) + struct.pack_into("i", view, off + 4, int(fd)) + struct.pack_into("Q", view, off + 8, int(offset)) + struct.pack_into("Q", view, off + 16, addr) + struct.pack_into("I", view, off + 24, int(nbytes)) + + +def io_uring_submit_and_wait(ring, wait_nr): + """Publish new submissions and wait for at least wait_nr completions. + + The fence orders the SQE fills (and the lazy head publish) before + the tail the kernel is about to read; the second fence orders the + completion reads below after the kernel's publish. Returns the + enter count; raises rather than returning a negative errno, because + the caller loops on completions and a silent -errno would spin. + """ + n = ring._pending + _fence() + _put_u32(ring._sq, ring._sq_off.tail, ring._sq_tail + n) + _put_u32(ring._cq, ring._cq_off.head, ring._cq_head) + ring._sq_tail += n + ring._pending = 0 + nr_enter = _numbers()[1] + ret = _syscall( + nr_enter, ring.fd, n, int(wait_nr), _IORING_ENTER_GETEVENTS, 0, 0 + ) + if ret < 0: + raise OSError(-ret, "io_uring_enter failed") + _fence() + return ret + + +def io_uring_peek_cqe(ring, cqe): + """Fill cqe with the next completion; -EAGAIN when none is ready.""" + tail = _u32(ring._cq, ring._cq_off.tail) + if ring._cq_head == tail: + return -errno.EAGAIN + off = (ring._cq_head & ring._cq_mask) * _CQE_BYTES + ring._cq_off.cqes + view = ring._cq + cqe.user_data = struct.unpack_from("Q", view, off)[0] + cqe.res = struct.unpack_from("i", view, off + 8)[0] + return 0 + + +def io_uring_cqe_seen(ring, cqe): + """Consume one completion; the real head publishes at next submit.""" + ring._cq_head += 1 diff --git a/thirdparty/faiss/benchs/e_means/demo_deep10m.py b/thirdparty/faiss/benchs/e_means/demo_deep10m.py new file mode 100644 index 000000000..59cad40a4 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/demo_deep10m.py @@ -0,0 +1,153 @@ +# 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. + +"""Run e-means at Table 3's DEEP* 10M budget (2 epochs), with one seed. + + python demo_deep10m.py + +Requires the software and curl command in README.md, which downloads +the first 10,010,000 rows to /tmp/base.1B.fbin.part. +Uses the paper's timing and test split, with float32 scoring; +starting rows are sampled without replacement with a seeded NumPy generator. +This runs one budget; it does not search for the first crossing or run Flash. +""" + +import gc +import time + +import numpy as np +import torch +from faiss.contrib.e_means import QuantizedEmeans +from faiss.contrib.e_means.quantizer import CastQuantizer + +seed = 123 + + +# TF32 off, including for the test-error scorer. +torch.backends.cuda.matmul.allow_tf32 = False +torch.backends.cudnn.allow_tf32 = False + + +####################### Load data +path = "/tmp/base.1B.fbin.part" +print( + f"Load data: {path}, 10,010,000 vectors of dimension 96, float32", + flush=True, +) +load_start = time.perf_counter() +_, d = np.fromfile(path, dtype="= 2.0: + break +seconds = float(np.median(calls)) +del x, init +gc.collect() +torch.cuda.empty_cache() + +# Rank centroids and compute squared distances in float32. +c = torch.tensor(centroids, device="cuda") +queries = torch.tensor(test, device="cuda") +norms = (c * c).sum(1) +best = torch.full((len(test),), float("inf"), device="cuda") +nearest = torch.zeros(len(test), dtype=torch.int64, device="cuda") +for j in range(0, k, 16384): + distances = ( + norms[j:j + 16384][None, :] - 2.0 * (queries @ c[j:j + 16384].t()) + ) + values, indices = distances.min(1) + better = values < best + best = torch.where(better, values, best) + nearest = torch.where(better, indices + j, nearest) +diff = queries - c[nearest] +mse = float((diff * diff).sum()) / len(test) +print(f"DEEP* 10M: {n:,} vectors, {k:,} clusters, 2 epochs, seed {seed}") +print(f"GPU: {torch.cuda.get_device_name()}") +print("Input: float32, cast to bfloat16 per batch; CuTe assignment") +print(f"Training time: {seconds:.4f} s") +print("Timed calls: " + ", ".join(f"{s:.4f} s" for s in calls)) +print(f"Test MSE ({len(test):,} held-out vectors): {mse:.8f}") diff --git a/thirdparty/faiss/benchs/e_means/demo_sharded_centroids.py b/thirdparty/faiss/benchs/e_means/demo_sharded_centroids.py new file mode 100644 index 000000000..6e7b47d7d --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/demo_sharded_centroids.py @@ -0,0 +1,240 @@ +# 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. + +"""Resident DINO training on two GPUs with exact sharded assignment. + +python demo_sharded_centroids.py --launch 2 +In fbcode: buck2 run -c hpc_comms.use_nccl=2.29 \ + fbcode//faiss/benchs/e_means:demo_sharded_centroids -- --launch 2 +""" + +import argparse +from datetime import timedelta +import math +import os +import time + +import torch +import torch.distributed as dist +from torch.distributed.launcher.api import elastic_launch, LaunchConfig + +if __package__: + from .dino_data import ( + DinoBvecs, DinoQueries, DinoTrainset, compute_mse_per_batches, + ) +else: + from dino_data import ( + DinoBvecs, DinoQueries, DinoTrainset, compute_mse_per_batches, + ) + +from faiss.contrib.e_means import ( + EmeansShardedCentroids, + EmeansShardedCentroidsIVF, +) +from faiss.contrib.e_means.base import _epoch_rows, _epoch_seed +from faiss.contrib.e_means.e_means_torch import _torch_generator + + +def launch(args, worker): + if min(_epoch_rows(args.n, args.epochs)) < 1: + raise ValueError("--epochs must process at least one training row") + if args.launch: + if not 1 <= args.launch <= torch.cuda.device_count(): + raise ValueError("--launch exceeds visible GPU count") + os.environ.setdefault("OMP_NUM_THREADS", "1") + config = LaunchConfig( + min_nodes=1, + max_nodes=1, + nproc_per_node=args.launch, + rdzv_backend="c10d", + rdzv_endpoint="localhost:0", + run_id="e-means-sharded", + max_restarts=0, + start_method="spawn", + ) + elastic_launch(config, worker)(args) + else: + worker(args) + + +def run(args): + device = torch.device("cuda", int(os.environ["LOCAL_RANK"])) + torch.cuda.set_device(device) + dist.init_process_group("nccl", timeout=timedelta(minutes=60)) + try: + rank, ranks = dist.get_rank(), dist.get_world_size() + if args.n % ranks: + raise ValueError("--n must be divisible by the GPU count") + if args.query_batch_size < 1: + raise ValueError("query batch size must be positive") + dataset = DinoBvecs(args.data, args.n) + test_vectors = ( + DinoTrainset(args.data, min(args.n, 50_000)) + if not args.test_on_queries else DinoQueries(args.data, dataset.d) + ) + if rank == 0: + print( + f"Query evaluation: exhaustive {args.query_precision}, " + f"FP32 distances, batch_size={args.query_batch_size}, " + f"test_vectors={test_vectors.n}, " + f"source={'train_queries_99M.bvecs prefix' if not args.test_on_queries else 'query test split (seed=1234)'}", + flush=True, + ) + start = time.perf_counter() + x = dataset.resident( + args.n * rank // ranks, args.n * (rank + 1) // ranks, device + ) + mean = x.mean(dim=0) + dist.all_reduce(mean) + mean /= ranks + x.sub_(mean) + scale = 1.0 + if args.ivf: + variance = x.square().mean() + dist.all_reduce(variance) + scale = (variance / ranks).sqrt().item() + if scale <= 0: + raise ValueError("DINO corpus has zero variance") + x.div_(scale) + model_type = ( + EmeansShardedCentroidsIVF if args.ivf else EmeansShardedCentroids + ) + extra = {"nlist": args.nlist, "nprobe": args.nprobe} if args.ivf else {} + model = model_type( + dataset.d, + args.k, + nepochs=args.epochs, + batch_law="quality", + seed=args.seed, + assignment_backend=args.assignment_backend, + group=dist.group.WORLD, + verbose=True, + **extra, + ) + initial_ids = torch.randperm( + len(x), + device=device, + generator=_torch_generator(device, args.seed + rank), + )[: model.k] + model.begin(args.n, x[initial_ids].float()) + del initial_ids + batch = model.recipe["batch_size"] // ranks + for epoch, global_rows in enumerate(model.recipe["epoch_rows"]): + local_rows = global_rows // ranks + preceding_rows = sum(model.recipe["epoch_rows"][:epoch]) + order = torch.randperm( + len(x), + device=device, + generator=_torch_generator( + device, _epoch_seed(args.seed, epoch) + ), + ) + for begin in range(0, local_rows, batch): + end = min(local_rows, begin + batch) + previous_revivals = model.n_splits + model.update(model.accumulate(x[order[begin:end]])) + revived = model.n_splits - previous_revivals + if rank == 0 and revived: + progress = (preceding_rows + end * ranks) / args.n + print( + f"epoch={progress:g} step={begin // batch + 1} " + f"centroid_revivals={revived} " + f"revivals_total={model.n_splits}", + flush=True, + ) + model.end_epoch() + test_mse = compute_mse_per_batches( + model, test_vectors.batches(mean, scale, args.query_batch_size), + precision=args.query_precision, + ) * scale**2 + model.iteration_stats[-1]["test_mse"] = test_mse + if rank == 0: + passes = sum(model.recipe["epoch_rows"][:epoch + 1]) / args.n + print( + f"epoch={passes:g} test_mse={test_mse:.6f} " + f"centroid_revivals={model.iteration_stats[-1]['nsplit']} " + f"revivals_total={model.n_splits}", + flush=True, + ) + del order + model.finalize() + test_mse = compute_mse_per_batches( + model, test_vectors.batches(mean, scale, args.query_batch_size), + precision=args.query_precision, + ) * scale**2 + assert torch.isfinite(model.centroids).all() + if args.output: + torch.save( + { + "centroids": model.centroids.cpu(), + "mean": mean.cpu(), + "scale": scale, + "centroid_begin": model.centroid_begin, + "recipe": model.recipe, + "iteration_stats": model.iteration_stats, + "test_mse": test_mse, + "test_query_count": test_vectors.n, + "test_on_xt": not args.test_on_queries, + "query_precision": args.query_precision, + }, + f"{args.output}.rank{rank}.pt", + ) + torch.cuda.synchronize() + if rank == 0: + moving_mse = ( + model.obj[-1].item() / model.recipe["epoch_rows"][-1] * scale**2 + ) + print( + f"PASS: n={args.n} k={args.k} ranks={ranks} " + f"elapsed={time.perf_counter() - start:.1f}s " + f"MSE={moving_mse:.6f} " + f"test_mse={test_mse:.6f}", + flush=True, + ) + finally: + dist.destroy_process_group() + + +def positive_epochs(value): + epochs = float(value) + if not math.isfinite(epochs) or epochs <= 0: + raise argparse.ArgumentTypeError("epochs must be finite and positive") + return epochs + + +def parser(): + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--launch", type=int, nargs="?", const=2) + result.add_argument("--data", default="/tmp/DINO10B") + result.add_argument("--n", type=int, default=10_000_000) + result.add_argument("--k", type=int, default=10_000) + result.add_argument( + "--epochs", type=positive_epochs, default=2.0, + help="training passes, including fractional budgets such as 0.6 or 2.6", + ) + result.add_argument("--seed", type=int, default=0) + result.add_argument( + "--assignment-backend", choices=("native", "triton"), default="triton" + ) + result.add_argument("--ivf", action="store_true") + result.add_argument("--nlist", type=int, default=256) + result.add_argument("--nprobe", type=int, default=4) + result.add_argument("--output") + result.add_argument("--query-batch-size", type=int, default=1024) + result.add_argument( + "--test-on-queries", action="store_true", + help="evaluate MSE on the queries_clean.bvecs test split to reproduce old results; " + "default: first min(n, 50000) vectors from train_queries_99M.bvecs", + ) + result.add_argument( + "--query-precision", choices=("bf16", "fp32"), default="bf16", + help="exhaustive query assignment precision; reported distances use FP32", + ) + return result + + +if __name__ == "__main__": + args = parser().parse_args() + launch(args, run) diff --git a/thirdparty/faiss/benchs/e_means/demo_training_from_ssd.py b/thirdparty/faiss/benchs/e_means/demo_training_from_ssd.py new file mode 100644 index 000000000..478478705 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/demo_training_from_ssd.py @@ -0,0 +1,441 @@ +# 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. + +"""Train sharded e-means or Lloyd k-means from SSD windows. + +buck2 run -c hpc_comms.use_nccl=2.29 \ + fbcode//faiss/benchs/e_means:demo_training_from_ssd -- --launch 2 +The default case is 200M DINO points and 1M centroids. Every rank scans its +own row range. Prefetch is automatic; --ssd-prefetch-chunk-groups defaults +to 4 and groups random windows by scan chunks. --final-closing-mean makes +a sequential no-search pass using the final training epoch's saved labels. +Assignment uses IVF by default; --exact searches all centroid shards instead. +--kmeans freezes centroids for each epoch and takes their means afterward. +It requires --batch-size and skips saved-assignment closing. +""" + +from contextlib import closing as _closing +from datetime import timedelta +import json +import os +import time + +import numpy as np +import torch +import torch.distributed as dist + +if __package__: + from .demo_sharded_centroids import launch, parser as resident_parser + from .dino_data import ( + DinoBvecs, DinoQueries, DinoTrainset, compute_mse_per_batches, + ) + from .ssd_streaming import SSDPrefetch, SSDRowSource + from .lloyd import LloydShardedCentroids, LloydShardedCentroidsIVF +else: + from demo_sharded_centroids import launch, parser as resident_parser + from dino_data import ( + DinoBvecs, DinoQueries, DinoTrainset, compute_mse_per_batches, + ) + from ssd_streaming import SSDPrefetch, SSDRowSource + from lloyd import LloydShardedCentroids, LloydShardedCentroidsIVF + +from faiss.contrib.e_means import EmeansShardedCentroids, EmeansShardedCentroidsIVF +from faiss.contrib.e_means.base import _ALPHA_LAW, _epoch_seed, _resolve_recipe + + +def training_recipe(args, ranks): + if args.kmeans and args.batch_size is None: + raise ValueError("--kmeans requires --batch-size (processing rows per batch)") + if args.batch_size is None: + return _resolve_recipe(args.n, args.k, args.epochs, "quality", None, None) + batch = args.batch_size + if not 1 <= batch <= args.n or batch % ranks: + raise ValueError("batch size must be in [1, n] and divide by worker count") + if args.kmeans: + # Explicit settings bypass the e-means recipe in the shared lifecycle. + # Lloyd updates do not use alpha. + return batch, 1.0 + coefficient, k_exp, batch_exp, n_exp, iter_exp = _ALPHA_LAW + alpha = ( + coefficient + * args.k**k_exp + * batch**batch_exp + * args.n**n_exp + * args.epochs**iter_exp + ) + return batch, min(max(alpha, 1e-4), 1.0) + + +def run(args): + device = torch.device("cuda", int(os.environ["LOCAL_RANK"])) + torch.cuda.set_device(device) + dist.init_process_group("nccl", timeout=timedelta(minutes=60)) + source = None + try: + rank, ranks = dist.get_rank(), dist.get_world_size() + final_closing_mean = args.final_closing_mean and not args.kmeans + if args.n % ranks or args.k % ranks: + raise ValueError("n and k must divide by worker count") + if final_closing_mean and args.k > 2**31: + raise ValueError("CPU int32 closing codes require k <= 2**31") + if args.query_batch_size < 1: + raise ValueError("query batch size must be positive") + if args.verbose_every < 1: + raise ValueError("verbose interval must be positive") + batch, alpha = training_recipe(args, ranks) + dataset = DinoBvecs(args.data, args.n) + test_vectors = ( + None + if args.initialization_only + else ( + DinoTrainset(args.data, min(args.n, 50_000)) + if not args.test_on_queries else DinoQueries(args.data, dataset.d) + ) + ) + source = SSDRowSource( + dataset.paths, + dataset.d, + args.n * rank // ranks, + args.n * (rank + 1) // ranks, + header_bytes=4, + ) + local_k = args.k // ranks + model_type = EmeansShardedCentroids if args.exact else EmeansShardedCentroidsIVF + if args.kmeans: + model_type = LloydShardedCentroids if args.exact else LloydShardedCentroidsIVF + extra = {} if args.exact else {"nlist": args.nlist, "nprobe": args.nprobe} + model = model_type( + dataset.d, + args.k, + nepochs=args.epochs, + batch_law="quality", + batch_size=batch if args.batch_size is not None else None, + alpha0=alpha if args.batch_size is not None else None, + seed=args.seed, + assignment_backend=args.assignment_backend, + group=dist.group.WORLD, + verbose=True, + capture_assignments=final_closing_mean, + **extra, + ) + loader = SSDPrefetch( + source, + device, + batch // ranks, + chunk_groups=args.ssd_prefetch_chunk_groups, + chunk_bytes=args.ssd_chunk_mib << 20, + ram_budget_bytes=int(args.ssd_ram_gib * (1 << 30)), + read_threads=args.ssd_read_threads, + extract_threads=args.ssd_extract_threads, + ) + if rank == 0: + host_bytes = 2 * loader.window_rows * dataset.d + gpu_batch_bytes = loader.batch_size * dataset.d * 4 + batch_source = "quality recipe" if args.batch_size is None else "override" + print( + f"Query evaluation: exhaustive {args.query_precision}, " + f"FP32 distances, batch_size={args.query_batch_size}, " + f"test_vectors={test_vectors.n if test_vectors is not None else 0}, " + f"source={'train_queries_99M.bvecs prefix' if not args.test_on_queries else 'query test split (seed=1234)'}", + flush=True, + ) + if args.exact: + print("Training assignment: BF16 brute force over all centroid shards", flush=True) + else: + route_bytes = batch * args.nprobe * ( + 4 if args.nlist <= torch.iinfo(torch.int32).max else 8 + ) + print( + f"Coarse routing: reader-local rows, gathered list IDs=" + f"{route_bytes / (1 << 20):.3f} MiB per rank", flush=True, + ) + rounded_rows = args.exact and not args.kmeans + batch_dtype = "BF16" if rounded_rows else "FP32" + gathered_item_bytes = 2 if rounded_rows else 4 + update_description = ( + "Lloyd: frozen centroids per epoch, epoch mean updates" + if args.kmeans else f"e-means: alpha0={alpha:.6g}" + ) + print( + f"SSD training: global_batch={batch} rows " + f"per_rank_batch={loader.batch_size} rows ({batch_source}) " + f"{update_description}\n" + f"Batch communication: all-gather, " + f"gathered {batch_dtype} batch buffer=" + f"{batch * dataset.d * gathered_item_bytes / (1 << 30):.3f} " + f"GiB per rank\n" + f"SSD prefetch: {loader.n_prefetch} batches per window, " + f"2 host windows per rank, window_rows={loader.window_rows}, " + f"chunk_groups={loader.chunk_groups}, direct={all(source.direct)}\n" + f"SSD memory: pinned host buffers={host_bytes / (1 << 30):.3f} GiB " + f"per rank, {host_bytes * ranks / (1 << 30):.3f} GiB total; " + f"each FP32 CUDA batch={gpu_batch_bytes / (1 << 30):.3f} GiB per rank", + flush=True, + ) + if final_closing_mean: + print( + f"Closing codes: CPU int32 in source-row order, " + f"{4 * source.n / (1 << 30):.3f} GiB per rank, " + f"{4 * args.n / (1 << 30):.3f} GiB total", + flush=True, + ) + start = time.perf_counter() + rng = np.random.RandomState(args.seed + rank) + ids = rng.choice(source.n, local_k, replace=False) + initial = torch.empty( + (local_k, dataset.d), dtype=torch.uint8, pin_memory=True + ) + if rank == 0: + print("Queued SSD reads for random initial centroids", flush=True) + initial_stats = source.gather(ids, initial, depth=args.ssd_io_depth) + initial_stats["time_s"] = time.perf_counter() - start + loader.stats["bytes_read"] += initial_stats["bytes_read"] + if args.initialization_only: + check = np.linspace( + 0, local_k - 1, min(local_k, 1024), dtype=np.int64 + ) + absolute = source.begin + ids[check] + expected = np.empty((len(check), dataset.d), dtype=np.uint8) + for mapping, hi, lo in zip( + dataset.maps, dataset.ends, np.r_[0, dataset.ends[:-1]] + ): + selected = (absolute >= lo) & (absolute < hi) + expected[selected] = mapping[absolute[selected] - lo, 4:] + np.testing.assert_array_equal(initial[check].numpy(), expected) + if rank == 0: + print( + f"PASS initialization rank={rank}: " + + json.dumps( + { + "n": args.n, + "k": args.k, + "checked": len(check), + "initialization": initial_stats, + } + ), + flush=True, + ) + return + assert test_vectors is not None + sample_n = min(local_k, max(1, 10_000 // ranks)) + sample = initial[:sample_n].to(device).double() + total = sample.sum(0) + total_sq = sample.square().sum() + dist.all_reduce(total) + dist.all_reduce(total_sq) + mean = total / (sample_n * ranks) + scale = ( + (total_sq / (sample_n * ranks * dataset.d) - mean.square().mean()) + .clamp_min(0) + .sqrt() + .item() + ) + if scale <= 0: + raise ValueError("DINO centering sample has zero variance") + mean = mean.float() + del sample + model.begin(args.n, (initial.to(device).float() - mean) / scale) + del initial, ids + if rank == 0: + print(f"SSD center_scale={scale:.6g}", flush=True) + closing_codes = None + for epoch, global_rows in enumerate(model.recipe["epoch_rows"]): + passes = sum(model.recipe["epoch_rows"][:epoch + 1]) / args.n + epoch_steps = model.recipe["epoch_steps"][epoch] + batch_objectives, batch_rows = [], [] + order = loader.order(_epoch_seed(args.seed + rank, epoch)) + order = order[:global_rows // ranks] + capture = ( + final_closing_mean + and epoch == len(model.recipe["epoch_rows"]) - 1 + ) + if capture: + closing_codes = torch.empty(source.n, dtype=torch.int32) + if global_rows < args.n: + closing_codes.fill_(-1) + at = 0 + with _closing( + loader.batches(order, mean=mean, scale=scale) + ) as batches: + for step, rows in enumerate(batches, start=1): + stats = model.accumulate(rows) + if capture: + closing_codes.numpy()[order[at:at + len(rows)]] = ( + stats["labels"] + .to(device="cpu", dtype=torch.int32).numpy() + ) + at += len(rows) + batch_objectives.append(stats["objective"].detach().clone()) + batch_rows.append(stats["n"]) + model.update(stats) + if ( + (step - 1) % args.verbose_every == 0 + or step == epoch_steps + ): + # Each owner contributes only its winning rows' SSE. + objective = batch_objectives[-1].clone() + dist.all_reduce(objective) + # Report the largest cumulative wait across workers. + ssd_wait = objective.new_tensor(loader.stats["wait_s"]) + dist.all_reduce(ssd_wait, op=dist.ReduceOp.MAX) + if rank == 0: + batch_mse = ( + objective.item() / batch_rows[-1] * scale**2 + ) + print( + f"epoch={passes:g} steps={step}/{epoch_steps} " + f"batch_mse={batch_mse:.6f} " + f"revivals_total={model.n_splits} " + f"elapsed={time.perf_counter() - start:.1f}s " + f"ssd_wait={ssd_wait.item():.1f}s", + flush=True, + ) + model.end_epoch() + if args.kmeans: + model.iteration_stats[-1]["assignment_mse"] *= scale**2 + # Collect all batches with one reduction and host transfer per epoch. + objectives = torch.stack(batch_objectives) + dist.all_reduce(objectives) + model.iteration_stats[-1]["batch_mse"] = [ + value / count * scale**2 + for value, count in zip(objectives.tolist(), batch_rows) + ] + test_mse = compute_mse_per_batches( + model, test_vectors.batches(mean, scale, args.query_batch_size), + precision=args.query_precision, + ) * scale**2 + model.iteration_stats[-1]["test_mse"] = test_mse + if rank == 0: + training_mse = ( + f"train_assignment_mse={model.iteration_stats[-1]['assignment_mse']:.6f} " + if args.kmeans else "" + ) + print( + f"epoch={passes:g} {training_mse}test_mse={test_mse:.6f} " + f"revivals_total={model.n_splits}", + flush=True, + ) + del order + if final_closing_mean: + if rank == 0: + host_bytes = 2 * loader.batch_size * dataset.d + print( + f"Sequential saved-assignment final-closing-mean scan (no search): " + f"global_batch={batch} rows, per_rank_batch={loader.batch_size} rows, " + f"1 prefetched batch per window, 2 host windows per rank, " + f"pinned host buffers={host_bytes / (1 << 30):.3f} GiB per rank, " + f"{host_bytes * ranks / (1 << 30):.3f} GiB total", + flush=True, + ) + with _closing( + loader.batches(sequential=True, mean=mean, scale=scale) + ) as batches: + model.final_closing_mean(batches, assignments=closing_codes) + del closing_codes + if rank == 0: + print( + f"final_closing_mean time={model.closing_stats['time_s']:.1f}s " + f"rows={model.closing_stats['rows']}", + flush=True, + ) + else: + model.finalize() + test_mse = compute_mse_per_batches( + model, test_vectors.batches(mean, scale, args.query_batch_size), + precision=args.query_precision, + ) * scale**2 + assert torch.isfinite(model.centroids).all() + torch.cuda.synchronize() + closing = getattr(model, "closing_stats", None) + if closing is not None: + closing = { + **closing, + "assignment_mse": closing["assignment_mse"] * scale**2, + } + report = { + "algorithm": "kmeans" if args.kmeans else "emeans", + "n": args.n, + "k": args.k, + "ranks": ranks, + "elapsed_s": time.perf_counter() - start, + "moving_pass_mse": ( + model.obj[-1].item() / model.recipe["epoch_rows"][-1] * scale**2 + ), + "test_mse": test_mse, + "test_query_count": test_vectors.n, + "test_on_xt": not args.test_on_queries, + "query_precision": args.query_precision, + "scale": scale, + "closing": closing, + "ssd": loader.stats, + "initialization": initial_stats, + "recipe": model.recipe, + "iteration_stats": model.iteration_stats, + "peak_gpu_bytes": torch.cuda.max_memory_allocated(device), + } + if args.kmeans: + report["pre_update_train_mse"] = report.pop("moving_pass_mse") + report["train_assignment_mse"] = model.iteration_stats[-1]["assignment_mse"] + if rank == 0: + print(f"PASS rank={rank}: {json.dumps(report)}", flush=True) + if args.output: + torch.save( + { + "centroids": model.centroids.cpu(), + "mean": mean.cpu(), + "scale": scale, + "centroid_begin": model.centroid_begin, + "report": report, + }, + f"{args.output}.rank{rank}.pt", + ) + finally: + if source is not None: + source.close() + dist.destroy_process_group() + + +def parser(): + result = resident_parser() + result.description = __doc__ + result.set_defaults(n=200_000_000, k=1_000_000, nlist=16384, ivf=True) + result.add_argument( + "--exact", action="store_true", + help="use brute-force centroid-sharded assignment; ignore --nlist and --nprobe", + ) + result.add_argument( + "--kmeans", action="store_true", + help="run Lloyd updates once per epoch; requires --batch-size and skips final closing", + ) + result.add_argument( + "--batch-size", + type=int, + help="global processing batch size; refits the EMA step for e-means", + ) + result.add_argument("--ssd-prefetch-chunk-groups", type=int, default=4) + result.add_argument("--ssd-chunk-mib", type=int, default=64) + result.add_argument("--ssd-ram-gib", type=float, default=16) + result.add_argument("--ssd-io-depth", type=int, default=256) + result.add_argument( + "--initialization-only", + action="store_true", + help="verify sampled rows, report queued initialization I/O and exit", + ) + result.add_argument("--ssd-read-threads", type=int, default=1) + result.add_argument("--ssd-extract-threads", type=int, default=4) + result.add_argument("--verbose-every", type=int, default=10) + result.add_argument( + "--final-closing-mean", action="store_true", default=True + ) + result.add_argument( + "--no-final-closing-mean", + dest="final_closing_mean", + action="store_false", + ) + return result + + +if __name__ == "__main__": + launch(parser().parse_args(), run) diff --git a/thirdparty/faiss/benchs/e_means/dino_data.py b/thirdparty/faiss/benchs/e_means/dino_data.py new file mode 100644 index 000000000..f97dd1beb --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/dino_data.py @@ -0,0 +1,236 @@ +# 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. + +"""Bounded reads of the DINO bvecs corpus.""" + +from pathlib import Path + +import numpy as np + + +class DinoQueries: + """The fixed test half of DINO10B's queries, loaded into CPU memory. + + Match the reference validation/test split: permute the shipped queries + with RandomState(1234), reserve the first half for validation, and + evaluate the remaining half. + """ + + def __init__(self, root, d, n=100_000): + path = Path(root) / "queries_clean.bvecs" + if not path.exists(): + raise FileNotFoundError( + f"download the DINO10B test queries to {path}" + ) + if path.stat().st_size != n * (d + 4): + raise ValueError(f"expected {n} {d}-dimensional queries in {path}") + vectors = np.fromfile(path, dtype=np.uint8).reshape(n, d + 4) + headers = vectors[:, :4].copy().view("= n: + self.paths = self.paths[:index] + break + if ( + self.paths[0].match("chunk_[0-9][0-9][0-9][0-9].bvecs") + and path.name != f"chunk_{index:04d}.bvecs" + ): + raise ValueError(f"missing chunk in required DINO prefix: {path}") + if Path(str(path) + ".parts.json").exists(): + raise ValueError(f"unfinished DINO download: {path}") + size = path.stat().st_size + if size % self.row_bytes: + raise ValueError(f"incomplete bvecs chunk: {path}") + lengths.append(size // self.row_bytes) + self.maps.append( + np.memmap( + path, + dtype=np.uint8, + mode="r", + shape=(lengths[-1], self.row_bytes), + ) + ) + self.ends = np.cumsum(lengths) + if not 0 < n <= self.ends[-1]: + raise ValueError( + f"requested {n} rows; corpus contains {self.ends[-1]}" + ) + self.n = n + + def read(self, begin, end): + if not 0 <= begin <= end <= self.n: + raise IndexError("DINO row range out of bounds") + output = np.empty((end - begin, self.d), dtype=np.uint8) + at = 0 + for mapping, hi, lo in zip( + self.maps, self.ends, np.r_[0, self.ends[:-1]] + ): + a, b = max(begin, int(lo)), min(end, int(hi)) + if a < b: + output[at : at + b - a] = mapping[a - lo : b - lo, 4:] + at += b - a + return output + + def resident(self, begin, end, device): + import torch + + output = torch.empty((end - begin, self.d), device=device) + for a in range(begin, end, 65536): + b = min(end, a + 65536) + output[a - begin : b - begin] = torch.from_numpy( + self.read(a, b) + ).to(device) + return output + + +class DinoTrainset: + """The first n vectors from train_queries_99M.bvecs, in bounded batches.""" + + def __init__(self, root, n): + if n <= 0: + raise ValueError("requested row count must be positive") + path = Path(root) / "train_queries_99M.bvecs" + with path.open("rb") as stream: + header = np.frombuffer(stream.read(4), dtype=" size // row_bytes: + raise ValueError(f"requested {n} rows; file contains {size // row_bytes}") + self.n = n + self.vectors = np.memmap( + path, dtype=np.uint8, mode="r", shape=(n, row_bytes) + ) + + def batches(self, mean, scale, batch_size): + import torch + + if batch_size < 1: + raise ValueError("batch size must be positive") + for begin in range(0, self.n, batch_size): + block = self.vectors[begin:min(begin + batch_size, self.n)] + headers = block[:, :4].copy().view(" 0)[:, None], means.float(), self._centroids[begin:end] + )) + # Fixed-assignment SSE after taking means, without another scan: + # sum_i ||x_i||^2 - sum_j ||S_j||^2 / N_j. + objective = self._row_square - explained + dist.all_reduce(objective, group=self._group) + assignment_mse = objective.clamp_min(0).item() / rows + self._lloyd_prepared = None + super().end_epoch() + self.iteration_stats[-1]["assignment_mse"] = assignment_mse + except BaseException: + self._failed = True + raise + + def finalize(self): + if self.centroids is not None: + return self.centroids + if self._epoch != len(self.recipe["epoch_rows"]): + raise RuntimeError("finish all epochs before finalize") + self._lloyd_prepared = None + # Keep the means computed with FP64 counts, including counts > 2**24. + # Use the common finalizer to package objectives and release buffers. + centroids = self._centroids + super().finalize() + self.centroids = centroids + self._row_square = None + if hasattr(self, "_ivf"): + self._ivf = None + return self.centroids + + +class LloydShardedCentroids(_LloydEpoch, EmeansShardedCentroids): + """BF16 exhaustive assignment with original FP32 row statistics.""" + + def begin(self, n, initial): + super().begin(n, initial) + self.recipe.update(fine_dtype="bf16", statistics_dtype="float32") + + def _prepare_torch_assignment(self, centroids): + # Keep the input representation FP32 for communication/statistics; + # only the frozen assignment operands use BF16 tensor cores. + return self._execution_backend.prepare_centroids( + centroids, torch.bfloat16, spherical=self.spherical + ) + + def _local_assignment(self, rows, prepared, second_out=None): + # The caller retains its FP32 gathered rows for owner accumulation. + return super()._local_assignment( + rows.to(torch.bfloat16), prepared, second_out=second_out + ) + + +class LloydShardedCentroidsIVF(_LloydEpoch, EmeansShardedCentroidsIVF): + """Lloyd training with BF16 IVF search and original FP32 row statistics.""" diff --git a/thirdparty/faiss/benchs/e_means/paper_bench.py b/thirdparty/faiss/benchs/e_means/paper_bench.py new file mode 100644 index 000000000..4283c8ed3 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_bench.py @@ -0,0 +1,479 @@ +# 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. + +"""Reproduce the e-means paper's Table 3, Figure 4(b) and Figure 3 with faiss.contrib.e_means. + +Pick a dataset, seeds and budgets; every run is timed the paper's way (paper_xb.py: a fresh +process, an untimed identical warm-up, both methods on the same GPU, one exact scorer) and +written as one JSON file under --out (default ./results). Existing files are kept, so an +interrupted command resumes where it stopped. + + # any budgets, both methods + python paper_bench.py run --dataset deep1b-10M --seeds 10 11 --epochs 1 2 --flash-iters 25 + + # Table 3's measurement for one dataset: the fewest epochs (1.0, 1.2, ...) at which e-means + # reaches Flash-KMeans' test error after 25 iterations, and the speedup there + python paper_bench.py crossing --dataset fb-ssnpp-1M --seeds 10 11 12 + python paper_bench.py crossing --dataset fb-ssnpp-1M --target paper # no Flash run + + # whole artifacts (one GPU; run a dataset per job to parallelize), then print or plot + python paper_bench.py table3 --scale 1M python paper_bench.py table3 --print + python paper_bench.py figure4 --scale 10M python paper_bench.py figure4 --plot + python paper_bench.py figure3 --method emeans python paper_bench.py figure3 --plot + +--target paper reads paper_targets.json: Flash-KMeans' test error and time after 25 iterations +for every (dataset, seed) of the paper, so a crossing can be checked without running Flash. +Speedups are only printed against a Flash run timed in the same job (--target measure, the +default). figure4 --plot draws Flash's curve from the same file when --out holds no Flash runs. + +--input cast|bf16 chooses how e-means' input reaches bfloat16 (see paper_xb.py). The two routes +must agree; `compare` prints them side by side when both were run. +""" +import argparse +import glob +import json +import os +import sys + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import paper_data as data # noqa: E402 +import paper_xb as xb # noqa: E402 + +SEEDS = list(range(10, 20)) +LADDER = [round(1.0 + 0.2 * i, 1) for i in range(13)] # 1.0, 1.2, ..., 3.4 epochs +TABLE3 = {"1M": ["deep1b-1M", "dino10b-1M-div4096", "spacev-1M", "fb-ssnpp-1M"], + "10M": ["deep1b-10M", "dino10b-10M-div4096", "spacev-10M", "fb-ssnpp-10M"], + "100M": ["deep1b-100M", "spacev-100M", "fb-ssnpp-100M"]} +TABLE3_SEEDS = {"1M": SEEDS, "10M": SEEDS, "100M": SEEDS} # the paper: 10 seeds at every scale +FIGURE4 = {"10M": ["deep1b-10M", "spacev-10M", "fb-ssnpp-10M", "sift1b-10M-div512"], + "100M": ["deep1b-100M", "spacev-100M", "fb-ssnpp-100M", "sift1b-100M-div512"]} +FIG4_EPOCHS = [0.125, 0.25, 0.5, 1, 2, 3, 5, 8, 12, 17, 25] +FIG4_ITERATIONS = [1, 2, 3, 5, 8, 12, 17, 25, 40, 60, 80, 100] +FIGURE3 = {"deep1b-1M": "DEEP* 1M", "imagenet-clip-512-normalized": "ImageNet-CLIP 1M", + "spacev-10M": "SPACEV 10M", "sift1b-10M-normalized": "SIFT 10M"} +FIG3_BUDGETS = [1, 2, 3, 5, 8, 12, 17, 25] +TITLES = {"deep1b": "DEEP*", "spacev": "SPACEV", "fb-ssnpp": "SimSearchNet++", + "sift1b": "SIFT/512", "dino10b": "DINOv3/4096"} +TARGETS = os.path.join(HERE, "paper_targets.json") + + +def title(name): + return TITLES[name.split("-")[0] if not name.startswith("fb-ssnpp") else "fb-ssnpp"] + + +def route_for(name, route): + """The input route a dataset runs with: the one asked for, else paper_xb's default for its + shape (cast where a float32 copy fits one GPU).""" + if route: + return route + fp = json.load(open(os.path.join(data.SPLITS, "fingerprints.json")))[name] + return xb.default_input(fp["n_train"], fp["dim"]) + + +def save(record, path): + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp%d" % os.getpid() + json.dump(record, open(tmp, "w"), indent=1) + os.replace(tmp, path) + + +def timed_run(out, spec): + """One timed run, cached as a JSON file named after everything that varies.""" + if spec["method"] == "emeans": + spec = dict(spec, input=route_for(spec["dataset"], spec.get("input"))) + budget = ("e%g_%s" % (spec["epochs"], spec["input"]) + if spec["method"] == "emeans" else "i%d" % spec["iterations"]) + path = os.path.join(out, "runs", spec["dataset"], "%s_%s_s%d.json" % ( + spec["method"], budget, spec["seed"])) + if os.path.exists(path): + return json.load(open(path)) + record = xb.isolated(spec) + save(record, path) + if spec["method"] == "emeans": + print("%s seed %d: e-means %g epochs (%s): test %.6g in %.4f s" % ( + spec["dataset"], spec["seed"], spec["epochs"], record["input"], record["test_mse"], + record["seconds"]), flush=True) + else: + print("%s seed %d: Flash-KMeans %d iterations: test %.6g in %.4f s" % ( + spec["dataset"], spec["seed"], spec["iterations"], record["test_mse"], + record["seconds"]), flush=True) + return record + + +def paper_target(name, seed): + targets = json.load(open(TARGETS)) + return (targets["table3"].get(name) or targets["figure4"][name])["per_seed"][str(seed)] + + +def crossing(out, name, seeds, target="measure", route=None, ladder=LADDER): + """Per seed: Flash@25's test error (measured here, or the paper's), then e-means at 1.0, + 1.2, ... epochs until it is at or below it. Writes /crossing/__s.""" + rows = [] + for seed in seeds: + if target == "measure": + flash = timed_run(out, dict(method="flash", dataset=name, seed=seed, iterations=25)) + goal = flash["test_mse"] + else: + flash, goal = None, paper_target(name, seed)["test_mse"] + runs = [] + for epochs in ladder: + runs.append(timed_run(out, dict(method="emeans", dataset=name, seed=seed, + epochs=epochs, input=route))) + if runs[-1]["test_mse"] <= goal: + break + hit = runs[-1] if runs[-1]["test_mse"] <= goal else None + record = dict(dataset=name, seed=seed, target=goal, target_source=target, flash=flash, + emeans=runs, crossing=hit["epochs"] if hit else None, + speedup=flash["seconds"] / hit["seconds"] if hit and flash else None) + save(record, os.path.join(out, "crossing", "%s_%s_s%d.json" % ( + name, runs[-1]["input"], seed))) + rows.append(record) + print("%s seed %d: crossing %s epochs%s" % ( + name, seed, record["crossing"], + ", speedup %.1fx" % record["speedup"] if record["speedup"] else ""), flush=True) + return rows + + +def cell(out, name, route=None): + """Table 3 cell from the crossing files: upper median of the crossings, median of the + per-seed speedups, and the seeds behind them.""" + recs = [json.load(open(p)) for p in sorted(glob.glob(os.path.join( + out, "crossing", "%s_%s_s*.json" % (name, route_for(name, route)))))] + recs = [r for r in recs if r["target_source"] == "measure"] + hits = [r for r in recs if r["crossing"] is not None] + if not hits: + return None + cross = sorted(r["crossing"] for r in hits) + return dict(seeds=len(recs), crossed=len(hits), crossing=cross[len(cross) // 2], + speedup=float(np.median([r["speedup"] for r in hits])), crossings=cross) + + +def print_table3(out, route): + for scale, names in TABLE3.items(): + print("%s rows" % scale) + for name in names: + c = cell(out, name, route) + print(" %-20s %s" % (name, "no runs" if c is None else + "%2d seeds (%d crossed): %.1f epochs, %5.1fx crossings %s" % ( + c["seeds"], c["crossed"], c["crossing"], c["speedup"], + c["crossings"]))) + + +def figure4_runs(out, name, seeds, route): + for seed in seeds: + for iterations in FIG4_ITERATIONS: + timed_run(out, dict(method="flash", dataset=name, seed=seed, iterations=iterations)) + for epochs in FIG4_EPOCHS: + timed_run(out, dict(method="emeans", dataset=name, seed=seed, epochs=epochs, + input=route)) + + +def curves(out, name, route): + """(base, {"flash": [(budget, seconds, % above base)], "emeans": [...]}, seeds): medians + over seeds, base being Flash's median test error after 25 iterations.""" + folder = os.path.join(out, "runs", name) + flash = [json.load(open(p)) for p in glob.glob(os.path.join(folder, "flash_i*_s*.json"))] + if not flash and os.path.exists(TARGETS): # no Flash runs here: the paper's curve + curve = json.load(open(TARGETS))["figure4"].get(name, {}).get("flash_curve", {}) + flash = [dict(iterations=int(it), seed=int(seed), **v) + for it, seeds in curve.items() for seed, v in seeds.items()] + em = [json.load(open(p)) for p in glob.glob(os.path.join(folder, "emeans_e*_s*.json"))] + em = [r for r in em if r["input"] == route_for(name, route) and r["epochs"] in FIG4_EPOCHS] + base = [r["test_mse"] for r in flash if r["iterations"] == 25] + if not base or not em: + return None, {}, 0 + base = float(np.median(base)) + pts = {} + for method, recs, key in (("flash", flash, "iterations"), ("emeans", em, "epochs")): + pts[method] = [(b, float(np.median([r["seconds"] for r in recs if r[key] == b])), + float(np.median([100.0 * (r["test_mse"] / base - 1.0) for r in recs + if r[key] == b]))) + for b in sorted({r[key] for r in recs})] + return base, pts, len({r["seed"] for r in em}) + + +def plot_figure4(out, route): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + scales = [s for s in FIGURE4 if any(curves(out, n, route)[1] for n in FIGURE4[s])] + fig, axes = plt.subplots(len(scales), 4, figsize=(13.6, 3.4 * len(scales)), squeeze=False) + for row, scale in zip(axes, scales): + for ax, name in zip(row, FIGURE4[scale]): + base, pts, seeds = curves(out, name, route) + if not pts: + ax.set_title("%s %s (no runs)" % (title(name), scale)) + continue + flash25 = [s for b, s, _ in pts["flash"] if b == 25][0] + cross = next(((b, s) for b, s, q in pts["emeans"] if q <= 0), None) + print("%-20s %2d seeds: first e-means budget at or below Flash@25: %s, " + "25 epochs %+.2f%%" % (name, seeds, "%g epochs (%.1fx)" % ( + cross[0], flash25 / cross[1]) if cross else "none", pts["emeans"][-1][2])) + for method, colour, marker, label in (("emeans", "#1b6ca8", "o", "e-means"), + ("flash", "#c1121f", "s", "Flash-KMeans")): + ax.plot([s for _, s, _ in pts[method]], [q for _, _, q in pts[method]], + color=colour, marker=marker, ms=3.5, lw=1.4, label=label) + ax.axhline(0.0, color="0.5", lw=0.8, ls="--") + ax.set_xscale("log") + ax.set_ylim(min(q for m in pts.values() for _, _, q in m) - 0.2, 3.0) + ax.set_title("%s %s, %d seeds" % (title(name), scale, seeds)) + ax.set_xlabel("seconds (median over seeds)") + ax.grid(True, lw=0.3, alpha=0.5) + row[0].set_ylabel("test MSE, % above Flash@25") + axes[0][0].legend(frameon=False) + fig.tight_layout() + fig.savefig(os.path.join(out, "figure4.pdf")) + print("wrote %s" % os.path.join(out, "figure4.pdf")) + + +def figure3_runs(out, name, method, seeds, route): + """Figure 3: training and test error against epochs, e-means (GPU) against Faiss k-means + (CPU, 25 Lloyd iterations read off after 1, 2, 3, 5, ...). Both start from the paper's + starting rows; the e-means arm draws them on the GPU and saves them for the Faiss arm, so run + it first. Training error is each method's error on its OWN last-pass assignment over every + training row, so neither spends an extra pass on scoring.""" + import faiss + faiss.omp_set_num_threads(len(os.sched_getaffinity(0))) + train, test = data.load(name) + x = data.rows(train, name) # (n, d) float32 in memory + n, d = x.shape + k = xb.k_for(n) + for seed in seeds: + path = os.path.join(out, "figure3", "%s_%s_s%d.json" % ( + name, method if method == "faiss" else "emeans_" + (route or "cast"), seed)) + if os.path.exists(path): + continue + start_path = os.path.join(data.CACHE, name, "starts_s%d.npy" % seed) + if not os.path.exists(start_path): + if method == "faiss": + sys.exit("%s seed %d: run the e-means arm first (it draws the starting rows on " + "the GPU)" % (name, seed)) + np.save(start_path, xb.starts(n, k, seed)) + c0 = x[np.load(start_path)] # (k, d) the shared start + points = (fig3_emeans if method == "emeans" else fig3_faiss)(x, test, k, seed, c0, route) + save(dict(dataset=name, method=method, input=route, seed=seed, k=k, points=points), path) + + +def _train_mse(x, centroids, codes, chunk=1 << 20): + total = 0.0 + for s in range(0, len(x), chunk): + diff = x[s:s + chunk] - centroids[codes[s:s + chunk]] + total += float(np.einsum("ij,ij->", diff, diff, dtype=np.float64)) + return total / len(x) + + +def fig3_emeans(x, test, k, seed, c0, route): + import torch + from faiss.contrib.e_means import Emeans, QuantizedEmeans + from faiss.contrib.e_means.quantizer import CastQuantizer + n, d = x.shape + route = route or "cast" + xg = torch.from_numpy(x).cuda() + model = Emeans + kw = dict(seed=seed, batch_law=xb.batch_law(n), assignment_backend="cute", + capture_assignments=True) + if route == "cast": + model = QuantizedEmeans + kw["quantizer"] = CastQuantizer(d, torch.bfloat16) + else: + xg = xg.to(torch.bfloat16) + c0g = torch.from_numpy(c0).cuda() + out = [] + for epochs in FIG3_BUDGETS: + km = model(d, k, nepochs=epochs, **kw) + km.train(xg, init_centroids=c0g) + c = km.centroids.cpu().numpy() + out.append(dict(budget=epochs, train=_train_mse(x, c, km.assignments.cpu().numpy()), + test=xb.test_error(c, test))) + print("seed %d e-means %2d epochs: train %.6g test %.6g" % ( + seed, epochs, out[-1]["train"], out[-1]["test"]), flush=True) + return out + + +def fig3_faiss(x, test, k, seed, c0, route): + import faiss + n, d = x.shape + centroids, out = c0, [] + for iteration in range(1, max(FIG3_BUDGETS) + 1): + if iteration in FIG3_BUDGETS: # the assignment this iteration is about to make + _, codes = faiss.knn(x, centroids, 1) + km = faiss.Kmeans(d, k, niter=1, nredo=1, seed=seed, max_points_per_centroid=10**9, + min_points_per_centroid=1, verbose=False) + km.train(x, init_centroids=centroids) # one Lloyd iteration + centroids = km.centroids + if iteration in FIG3_BUDGETS: + _, nearest = faiss.knn(test, centroids, 1) + diff = test - centroids[nearest[:, 0]] + out.append(dict(budget=iteration, train=_train_mse(x, centroids, codes[:, 0]), + test=float(np.einsum("ij,ij->", diff, diff, dtype=np.float64) + / len(test)))) + print("seed %d Faiss %2d iterations: train %.6g test %.6g" % ( + seed, iteration, out[-1]["train"], out[-1]["test"]), flush=True) + return out + + +def plot_figure3(out): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + fig, axes = plt.subplots(2, len(FIGURE3), figsize=(13.6, 6.0), squeeze=False) + for j, (name, label) in enumerate(FIGURE3.items()): + recs = [json.load(open(p)) for p in glob.glob(os.path.join( + out, "figure3", "%s_*_s*.json" % name))] + faiss_recs = [r for r in recs if r["method"] == "faiss"] + if not faiss_recs: + continue + for i, what in enumerate(("train", "test")): + ref = np.mean([r["points"][-1][what] for r in faiss_recs]) + for method, colour in (("emeans", "#1b6ca8"), ("faiss", "#555555")): + rr = [r for r in recs if r["method"] == method] + if not rr: + continue + budgets = [p["budget"] for p in rr[0]["points"]] + ys = [np.mean([r["points"][b][what] for r in rr]) / ref + for b in range(len(budgets))] + axes[i][j].plot(budgets, ys, marker="o", ms=3, color=colour, + label="%s (%d seeds)" % (method, len(rr))) + axes[i][j].set_xscale("log") + axes[i][j].axhline(1.0, color="0.6", lw=0.8, ls="--") + axes[i][j].set_title("%s, %s error" % (label, what)) + axes[i][j].grid(True, lw=0.3, alpha=0.5) + axes[0][0].legend(frameon=False) + axes[1][0].set_xlabel("epochs") + fig.tight_layout() + fig.savefig(os.path.join(out, "figure3.pdf")) + print("wrote %s" % os.path.join(out, "figure3.pdf")) + + +def build_targets(out): + """paper_targets.json from a finished campaign: every Flash@25 test error and time, per + (dataset, seed), for Table 3 and Figure 4(b); Flash's whole Figure 4(b) curve (1 to 100 + iterations) per seed; and Faiss@25 for Figure 3.""" + result = dict(note="Flash-KMeans after 25 iterations (Table 3, Figure 4(b)) and its whole " + "Figure 4(b) curve (flash_curve: iterations -> seed -> test_mse, seconds); " + "Faiss k-means after 25 Lloyd iterations (Figure 3, which has no Flash " + "arm). Test error per row, exact scorer of paper_xb.test_error; seconds " + "are one 80 GB GPU, median of the timed calls (paper_xb.timed).", + table3={}, figure4={}, figure3={}) + for key, names in (("table3", sum(TABLE3.values(), [])), + ("figure4", sum(FIGURE4.values(), []))): + for name in names: + recs = [json.load(open(p)) for p in glob.glob(os.path.join( + out, "runs", name, "flash_i25_s*.json"))] + if recs: + r0 = recs[0] + result[key][name] = dict( + flash_api=r0["flash_api"], flash_norms=r0["flash_norms"], + torch=r0["torch"], triton=r0["triton"], + median_test_mse=float(np.median([r["test_mse"] for r in recs])), + per_seed={str(r["seed"]): dict(test_mse=r["test_mse"], seconds=r["seconds"]) + for r in sorted(recs, key=lambda r: r["seed"])}) + if key == "figure4": # Flash's whole curve, for --plot + curve = {} + for it in FIG4_ITERATIONS: + for p in sorted(glob.glob(os.path.join(out, "runs", name, + "flash_i%d_s*.json" % it))): + r = json.load(open(p)) + curve.setdefault(str(it), {})[str(r["seed"])] = dict( + test_mse=r["test_mse"], seconds=r["seconds"]) + result[key][name]["flash_curve"] = curve + for name in FIGURE3: + recs = [json.load(open(p)) for p in glob.glob(os.path.join( + out, "figure3", "%s_faiss_s*.json" % name))] + if recs: + result["figure3"][name] = dict( + reference="faiss k-means, 25 Lloyd iterations, CPU", + median_test_mse=float(np.median([r["points"][-1]["test"] for r in recs])), + per_seed={str(r["seed"]): dict(test_mse=r["points"][-1]["test"], + train_mse=r["points"][-1]["train"]) + for r in sorted(recs, key=lambda r: r["seed"])}) + save(result, TARGETS) + print("wrote %s" % TARGETS) + + +def compare_inputs(out): + """The two input routes side by side, per (dataset, budget, seed): they must agree.""" + for folder in sorted(glob.glob(os.path.join(out, "runs", "*"))): + name = os.path.basename(folder) + recs = {} + for p in glob.glob(os.path.join(folder, "emeans_e*_s*.json")): + r = json.load(open(p)) + recs.setdefault((r["epochs"], r["seed"]), {})[r["input"]] = r + pairs = [v for v in recs.values() if len(v) == 2] + if not pairs: + continue + err = [100.0 * (v["cast"]["test_mse"] / v["bf16"]["test_mse"] - 1.0) for v in pairs] + time_ratio = [v["cast"]["seconds"] / v["bf16"]["seconds"] for v in pairs] + print("%-20s %3d pairs: cast vs bf16 test error %+.4f%% median (max |%.4f|%%), " + "time ratio %.3f median (%.3f-%.3f)" % ( + name, len(pairs), np.median(err), np.max(np.abs(err)), np.median(time_ratio), + min(time_ratio), max(time_ratio))) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("command", choices=["run", "crossing", "table3", "figure4", "figure3", + "targets", "compare"]) + ap.add_argument("--dataset", choices=sorted(data.DATASETS)) + ap.add_argument("--scale", choices=["1M", "10M", "100M"]) + ap.add_argument("--seeds", type=int, nargs="+") + ap.add_argument("--method", choices=["emeans", "flash", "both", "faiss"], default="both") + ap.add_argument("--epochs", type=float, nargs="+", default=[]) + ap.add_argument("--flash-iters", type=int, nargs="+", default=[]) + ap.add_argument("--input", choices=["cast", "bf16"], + help="how e-means' input reaches bfloat16 (default: cast where a float32 " + "copy fits one GPU, else bf16)") + ap.add_argument("--target", choices=["measure", "paper"], default="measure") + ap.add_argument("--out", default="results") + ap.add_argument("--print", action="store_true", help="table3: print the rows") + ap.add_argument("--plot", action="store_true", help="figure3/figure4: draw the figure") + a = ap.parse_args() + if a.command == "run": + for seed in a.seeds or [10]: + if a.method in ("flash", "both"): + for it in a.flash_iters: + timed_run(a.out, dict(method="flash", dataset=a.dataset, seed=seed, + iterations=it)) + if a.method in ("emeans", "both"): + for ep in a.epochs: + timed_run(a.out, dict(method="emeans", dataset=a.dataset, seed=seed, + epochs=ep, input=a.input)) + elif a.command == "crossing": + crossing(a.out, a.dataset, a.seeds or SEEDS, a.target, a.input) + elif a.command == "table3": + if a.print: + print_table3(a.out, a.input) + return + names = [a.dataset] if a.dataset else TABLE3[a.scale] + for name in names: + scale = next(s for s, v in TABLE3.items() if name in v) + crossing(a.out, name, a.seeds or TABLE3_SEEDS[scale], "measure", a.input) + elif a.command == "figure4": + if a.plot: + plot_figure4(a.out, a.input) + return + for name in [a.dataset] if a.dataset else FIGURE4[a.scale]: + figure4_runs(a.out, name, a.seeds or SEEDS, a.input) + elif a.command == "figure3": + if a.plot: + plot_figure3(a.out) + return + for name in [a.dataset] if a.dataset else list(FIGURE3): + figure3_runs(a.out, name, "faiss" if a.method == "faiss" else "emeans", + a.seeds or SEEDS, a.input) + elif a.command == "targets": + build_targets(a.out) + else: + compare_inputs(a.out) + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/benchs/e_means/paper_data.py b/thirdparty/faiss/benchs/e_means/paper_data.py new file mode 100644 index 000000000..9bf30a4b0 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_data.py @@ -0,0 +1,222 @@ +# 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. + +"""The datasets of the e-means paper's Figure 3, Figure 4 and Table 3, split as in the paper. + +The files are public and live under the folder named by the EMEANS_DATA environment variable +(default ./data, file list in README.md). For each dataset: + + train the rows the paper trained on: the first n rows of the corpus (ImageNet-CLIP: a fixed + one-million-row subset of its training split) + test the paper's test rows: every test error in the paper is measured on these rows + +Where the test rows come from. Each dataset has a frozen evaluation set, cut in half by one fixed +permutation (seed 1234): the first half is validation (unused here), the second half is test. + DEEP* and SIFT, 1M and 10M the 10,000 rows that follow the training rows in the same file + DEEP* and SIFT, 100M the corpus's public query file (10,000 rows) + DINOv3 the corpus's public query file (100,000 rows) + SPACEV 100M the public query file of that separate 100M sample + SPACEV 1M/10M, SimSearchNet++, ImageNet-CLIP + 20,000 rows held out of the file, listed in paper_splits/ (read + from heldout_rows.npy beside the corpus when paper_download.py + saved them there, so the whole corpus need not be downloaded) + +Training rows of a prefix corpus stay in the type the file stores (float32, uint8 or int8) and +are memory-mapped, so a 100M corpus is never copied. rows(train, name, ...) converts a slice to +float32 with the dataset's rescaling (a power of two, so exact). + +load() compares each dataset once with the paper's own arrays (paper_splits/fingerprints.json): +both evaluation halves byte for byte, and 1,000 evenly spaced training rows. A different file, a +wrong row range or a wrong rescaling fails loudly instead of producing plausible numbers. +""" +import hashlib +import json +import os + +import numpy as np + +ROOT = os.environ.get("EMEANS_DATA", "data") +CACHE = os.environ.get("EMEANS_CACHE", "cache") +SPLITS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "paper_splits") + +DEEP = ("deep1b/base.1B.fbin", "deep1b/base.fvecs") # either file works +DEEP_QUERIES = ("deep1b/query.public.10K.fbin", "deep1b/deep1B_queries.fvecs") +SIFT = ("bigann/base.1B.u8bin", "bigann/bigann_base.bvecs") +SIFT_QUERIES = ("bigann/query.public.10K.u8bin", "bigann/bigann_query.bvecs") +SPACEV = ("spacev1b/base.1.4B.i8bin",) +SPACEV100M = ("spacev100m/base.100M.i8bin",) # a separate 100M sample +SPACEV100M_QUERIES = ("spacev100m/query.30K.i8bin",) +SSNPP = ("fb_ssnpp/FB_ssnpp_database.u8bin",) +DINO = ("dino_vitl_10B/chunked_base_10B/chunk_0000.bvecs",) +DINO_QUERIES = ("dino_vitl_10B/queries_clean.bvecs",) +IMAGENET = ("vibe/imagenet-clip-512-normalized.hdf5",) +# The held-out rows of SPACEV and SimSearchNet++ sit near the end of their files; paper_download.py +# saves them in this small file beside the corpus, so only the corpus's prefix has to be downloaded. +HELDOUT = "heldout_rows.npy" + +# name: base file, rows used for training, where the evaluation rows are, and a rescaling. +# eval="next" the 10,000 rows right after the training rows +# eval= a query file +# held_out=<.npy> row numbers of the base file (paper_splits/) +DATASETS = { + "deep1b-1M": dict(base=DEEP, n=10**6, eval="next"), + "deep1b-10M": dict(base=DEEP, n=10**7, eval="next"), + "deep1b-100M": dict(base=DEEP, n=10**8, eval=DEEP_QUERIES), + "sift1b-10M-normalized": dict(base=SIFT, n=10**7, eval="next", normalize=True), + "sift1b-10M-div512": dict(base=SIFT, n=10**7, eval="next", divide=512.0), + "sift1b-100M-div512": dict(base=SIFT, n=10**8, eval=SIFT_QUERIES, divide=512.0), + "spacev-1M": dict(base=SPACEV, n=10**6, held_out="spacev_holdout_rows.npy"), + "spacev-10M": dict(base=SPACEV, n=10**7, held_out="spacev_holdout_rows.npy"), + "spacev-100M": dict(base=SPACEV100M, n=10**8, eval=SPACEV100M_QUERIES), + "fb-ssnpp-1M": dict(base=SSNPP, n=10**6, held_out="fb_ssnpp_holdout_rows.npy"), + "fb-ssnpp-10M": dict(base=SSNPP, n=10**7, held_out="fb_ssnpp_holdout_rows.npy"), + "fb-ssnpp-100M": dict(base=SSNPP, n=10**8, held_out="fb_ssnpp_holdout_rows.npy"), + "dino10b-1M-div4096": dict(base=DINO, n=10**6, eval=DINO_QUERIES, divide=4096.0), + "dino10b-10M-div4096": dict(base=DINO, n=10**7, eval=DINO_QUERIES, divide=4096.0), + "imagenet-clip-512-normalized": dict(base=IMAGENET, n=10**6, + held_out="imagenet_clip_holdout_rows.npy"), +} + + +def find(names): + """The first of the candidate file names present under ROOT.""" + for name in names: + if os.path.exists(os.path.join(ROOT, name)): + return os.path.join(ROOT, name) + raise FileNotFoundError("none of %s under %s (see README.md)" % (list(names), ROOT)) + + +def matrix(path): + """A vector file as a read-only memory map of shape (n, d), in the type it stores. + + .fvecs/.bvecs store a 4-byte dimension before every row; .fbin/.u8bin/.i8bin store one + 8-byte header (rows, dimension) and then the rows. The row count comes from the file + size, so a partially downloaded file works as long as it holds the rows asked for.""" + ext = os.path.splitext(path)[1] + size = os.path.getsize(path) + if ext in (".fvecs", ".bvecs"): + dtype = np.dtype(np.float32 if ext == ".fvecs" else np.uint8) + d = int(np.fromfile(path, dtype=np.int32, count=1)[0]) + width = 4 + d * dtype.itemsize # bytes per row + raw = np.memmap(path, dtype=np.uint8, mode="r", shape=(size // width, width)) + return raw[:, 4:].view(dtype) # (n, d) + dtype = np.dtype({".fbin": np.float32, ".u8bin": np.uint8, ".i8bin": np.int8}[ext]) + n, d = (int(v) for v in np.fromfile(path, dtype=np.int32, count=2)) + n = min(n, (size - 8) // (d * dtype.itemsize)) + return np.memmap(path, dtype=dtype, mode="r", offset=8, shape=(n, d)) + + +def _rescale(arr, spec): + if spec.get("normalize"): # unit rows in float32, zero rows stay zero + norms = np.linalg.norm(arr, axis=1, keepdims=True) + norms[norms == 0] = 1.0 + arr /= norms + if spec.get("divide"): # a power of two: exact in float32 + arr /= spec["divide"] + return arr + + +def rows(train, name, start=0, stop=None, index=None): + """float32 copy of training rows (a range, or the listed row numbers), rescaled as the paper + rescaled them. `train` is what load(name) returned; cached training rows are already + rescaled.""" + part = np.array(train[start:stop] if index is None else train[index], dtype=np.float32) + return part if _cached_train(name) else _rescale(part, DATASETS[name]) + + +def halves(evaluation): + """The paper's validation and test halves of an evaluation set (fixed seed 1234).""" + perm = np.random.RandomState(1234).permutation(evaluation.shape[0]) + n_val = int(round(0.5 * evaluation.shape[0])) + return evaluation[perm[:n_val]], evaluation[perm[n_val:]] + + +def sha256(arr): + return hashlib.sha256(np.ascontiguousarray(arr, dtype=np.float32).tobytes()).hexdigest() + + +def _cached_train(name): + """The two datasets that are not a prefix of a file keep float32 training rows in the cache.""" + spec = DATASETS[name] + return bool(spec.get("normalize")) or spec["base"] == IMAGENET + + +def _imagenet(spec): + """ImageNet-CLIP: the held-out rows come out of its training split, and Figure 3 trains on + one fixed one-million-row subset of what is left.""" + import h5py + corpus = np.asarray(h5py.File(find(spec["base"]), "r")["train"], dtype=np.float32) + held = np.load(os.path.join(SPLITS, spec["held_out"])) + keep = np.ones(corpus.shape[0], dtype=bool) + keep[held] = False + train, evaluation = corpus[keep], corpus[held] + subset = np.sort(np.random.RandomState(1234).choice(train.shape[0], spec["n"], + replace=False)) + return train[subset], evaluation + + +def _prefix(name): + spec = DATASETS[name] + mat = matrix(find(spec["base"])) + assert mat.shape[0] >= spec["n"], "%s holds %d rows, %d needed" % ( + find(spec["base"]), mat.shape[0], spec["n"]) + return mat[:spec["n"]] + + +def _evaluation(name): + spec = DATASETS[name] + if "held_out" in spec: + index = np.load(os.path.join(SPLITS, spec["held_out"])) + small = os.path.join(os.path.dirname(find(spec["base"])), HELDOUT) + if os.path.exists(small): # written by paper_download.py, in index order + evaluation = np.load(small).astype(np.float32) + else: + evaluation = np.array(matrix(find(spec["base"]))[index], dtype=np.float32) + elif spec["eval"] == "next": + evaluation = np.array(matrix(find(spec["base"]))[spec["n"]:spec["n"] + 10_000], + dtype=np.float32) + else: + evaluation = np.array(matrix(find(spec["eval"])), dtype=np.float32) + return _rescale(evaluation, spec) + + +def load(name): + """(train, test) for one timed run. + + The first call checks the dataset against the paper's fingerprints, then caches the test rows + (and, for the two non-prefix datasets, the float32 training rows) under $EMEANS_CACHE + (default ./cache) with a stamp saying the check passed. Later calls, one per timed run since + every run is a fresh process, only map the files. Cached files are written under a temporary + name and renamed, so concurrent jobs never read a partial file.""" + spec = DATASETS[name] + folder = os.path.join(CACHE, name) + os.makedirs(folder, exist_ok=True) + train_path, test_path = (os.path.join(folder, part + ".npy") for part in ("train", "test")) + stamp = os.path.join(folder, "checked") + own = _cached_train(name) + if not os.path.exists(stamp): + if spec["base"] == IMAGENET: + train, evaluation = _imagenet(spec) + else: + train, evaluation = _prefix(name), _evaluation(name) + if own: + train = _rescale(np.array(train, dtype=np.float32), spec) + val, test = halves(evaluation) + want = json.load(open(os.path.join(SPLITS, "fingerprints.json")))[name] + sample = np.linspace(0, train.shape[0] - 1, 1000).astype(np.int64) + sampled = (np.asarray(train[sample]) if own + else _rescale(np.array(train[sample], dtype=np.float32), spec)) + for what, arr in (("val", val), ("test", test), ("train_rows", sampled)): + assert sha256(arr) == want[what + "_sha256"], ( + "%s: the %s rows differ from the paper's; check the file and README.md" % ( + name, what)) + assert tuple(train.shape) == (want["n_train"], want["dim"]), (name, train.shape) + for path, arr in ((train_path, train), (test_path, test)) if own else ((test_path, test),): + tmp = "%s.tmp%d.npy" % (path[:-4], os.getpid()) + np.save(tmp, arr) + os.replace(tmp, path) + open(stamp, "w").write("checked against paper_splits/fingerprints.json\n") + train = np.load(train_path, mmap_mode="r") if own else _prefix(name) + return train, np.load(test_path) diff --git a/thirdparty/faiss/benchs/e_means/paper_download.py b/thirdparty/faiss/benchs/e_means/paper_download.py new file mode 100644 index 000000000..534f7b904 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_download.py @@ -0,0 +1,360 @@ +# 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. + +"""Download exactly the data the paper's results need, for the scales you choose. + + python paper_download.py --results 1M # the 1M results only (smallest download) + python paper_download.py --results 10M # the 1M and 10M results + python paper_download.py --results 100M # the 1M, 10M and 100M results + python paper_download.py --results 10M --dry-run # sizes only, nothing downloaded + +The corpora are billions of rows, but each result reads only a prefix of a file and, for SPACEV +and SimSearchNet++, 20,000 held-out rows near its end. This script fetches those bytes and nothing +else, with parallel HTTP range requests, into the layout paper_data.py expects under --data +(default $EMEANS_DATA): the prefix as a file of the corpus's own format, and the held-out rows in a +small heldout_rows.npy beside it. Before downloading, it prints what each choice costs and asks for +confirmation (--yes skips the question). An interrupted download resumes where it stopped. At the +end every downloaded dataset is checked against the paper's fingerprints. +""" +import argparse +import concurrent.futures +import json +import os +import sys +import time +import urllib.request + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import paper_data as data # noqa: E402 + +HF = "https://huggingface.co/datasets" +FB = "https://dl.fbaipublicfiles.com" +SPACEV_PART = 4294967295 # bytes per part of the SPACEV1B release + +# local file (under --data): where it comes from and how its rows are laid out. +# layout "bin": 8-byte header then rows of d values; "bvecs": a 4-byte header per row; +# "whole": downloaded entirely (size given) +SOURCES = { + "deep1b/base.1B.fbin": dict(url=HF + "/suchun/deep1b-mirror/resolve/main/base.1B.fbin", + layout="bin", row=96 * 4), + "deep1b/query.public.10K.fbin": dict( + url=HF + "/suchun/deep1b-mirror/resolve/main/query.public.10K.fbin", layout="whole", + size=3840008), + "bigann/base.1B.u8bin": dict(url=FB + "/billion-scale-ann-benchmarks/bigann/base.1B.u8bin", + layout="bin", row=128), + "bigann/query.public.10K.u8bin": dict( + url=FB + "/billion-scale-ann-benchmarks/bigann/query.public.10K.u8bin", layout="whole", + size=1280008), + "spacev1b/base.1.4B.i8bin": dict( + parts=HF + "/jkhe/spacev1b/resolve/main/vectors.bin/vectors_%d.bin", layout="bin", + row=100), + "spacev100m/base.100M.i8bin": dict( + url=HF + "/unum-cloud/ann-spacev-100m/resolve/main/base.100M.i8bin", layout="whole", + size=10000000008), + "spacev100m/query.30K.i8bin": dict( + url=HF + "/unum-cloud/ann-spacev-100m/resolve/main/query.30K.i8bin", layout="whole", + size=2931608), + "fb_ssnpp/FB_ssnpp_database.u8bin": dict( + url=FB + "/billion-scale-ann-benchmarks/FB_ssnpp_database.u8bin", layout="bin", row=256), + "dino_vitl_10B/chunked_base_10B/chunk_0000.bvecs": dict( + url=FB + "/large_objects/dino_vitl_10B/chunked_base_10B/chunk_0000.bvecs", + layout="bvecs", row=4 + 1024), + "dino_vitl_10B/queries_clean.bvecs": dict( + url=FB + "/large_objects/dino_vitl_10B/queries_clean.bvecs", layout="whole", + size=102800000), + "vibe/imagenet-clip-512-normalized.hdf5": dict( + url=HF + "/vector-index-bench/vibe/resolve/main/imagenet-clip-512-normalized.hdf5", + layout="whole", size=2627494208), +} + +# What each choice gives, and the datasets it needs (each level includes the ones before it). +LEVELS = { + "1M": ("Table 3, 1M row; Figure 3, DEEP* 1M and ImageNet-CLIP 1M panels", + ["deep1b-1M", "dino10b-1M-div4096", "spacev-1M", "fb-ssnpp-1M", + "imagenet-clip-512-normalized"]), + "10M": ("Table 3, 10M row; Figure 4(b), upper row; Figure 3, SPACEV 10M and SIFT 10M panels", + ["deep1b-10M", "dino10b-10M-div4096", "spacev-10M", "fb-ssnpp-10M", + "sift1b-10M-div512", "sift1b-10M-normalized"]), + "100M": ("Table 3, 100M row (DEEP*, SPACEV, SimSearchNet++); Figure 4(b), lower row", + ["deep1b-100M", "spacev-100M", "fb-ssnpp-100M", "sift1b-100M-div512"]), +} +ORDER = ["1M", "10M", "100M"] +CHUNK = 64 << 20 # bytes per range request + + +def local_name(candidates): + """The candidate file name this script provides (paper_data accepts several).""" + return next(c for c in candidates if c in SOURCES) + + +def needs(name): + """{local file: [(start, stop) byte ranges]} that dataset `name` reads.""" + spec = data.DATASETS[name] + base = local_name(spec["base"]) + src = SOURCES[base] + out = {} + if src["layout"] == "whole": + out[base] = [(0, src["size"])] + else: + head = 8 if src["layout"] == "bin" else 0 + rows = spec["n"] + (10_000 if spec.get("eval") == "next" else 0) + out[base] = [(0, head + rows * src["row"])] + if isinstance(spec.get("eval"), tuple): + q = local_name(spec["eval"]) + out[q] = [(0, SOURCES[q]["size"])] + return out + + +def heldout_needs(name): + """(local corpus file, held-out row numbers) for a dataset whose test rows are held out of + its corpus file, else None.""" + spec = data.DATASETS[name] + if "held_out" not in spec or spec["base"] == data.IMAGENET: + return None + return local_name(spec["base"]), np.load(os.path.join(data.SPLITS, spec["held_out"])) + + +def heldout_bytes(f, rows): + return len(rows) * SOURCES[f]["row"] + + +def merge(ranges): + out = [] + for a, b in sorted(ranges): + if out and a <= out[-1][1]: + out[-1] = (out[-1][0], max(out[-1][1], b)) + else: + out.append((a, b)) + return out + + +def subtract(ranges, done): + """The parts of `ranges` not yet covered by `done` (both merged).""" + out = [] + for a, b in ranges: + for c, d in done: + if d <= a or c >= b: + continue + if c > a: + out.append((a, c)) + a = max(a, d) + if a >= b: + break + if a < b: + out.append((a, b)) + return out + + +def plan(level): + files = {} + for lv in ORDER[:ORDER.index(level) + 1]: + for name in LEVELS[lv][1]: + for f, rs in needs(name).items(): + files.setdefault(f, []).extend(rs) + held = {} + for lv in ORDER[:ORDER.index(level) + 1]: + for name in LEVELS[lv][1]: + h = heldout_needs(name) + if h: + held[h[0]] = h[1] + return {f: merge(rs) for f, rs in files.items()}, held + + +def plan_bytes(level): + files, held = plan(level) + return (sum(b - a for rs in files.values() for a, b in rs) + + sum(heldout_bytes(f, r) for f, r in held.items())) + + +def requests_for(f, a, b): + """(url, remote start, remote stop, local offset) pieces for local bytes [a, b).""" + src = SOURCES[f] + out = [] + while a < b: + stop = min(b, a + CHUNK) + if "parts" in src: # SPACEV1B: concatenated parts + i, off = divmod(a, SPACEV_PART) + stop = min(stop, (i + 1) * SPACEV_PART) + out.append((src["parts"] % (i + 1), off, off + stop - a, a)) + else: + out.append((src["url"], a, stop, a)) + a = stop + return out + + +def fetch(url, start, stop, tries=6): + """Bytes [start, stop) of url, read with a buffer bounded by the request. + + The server must honour the range: HTTP 206 with exactly the requested + Content-Range. HTTP 200 (the whole file) is accepted only when the request + asked for the whole file, checked by start == 0 and a matching Content-Length. + At most stop - start + 1 bytes are read, and the length must match exactly, + so a server that ignores Range cannot pull a whole corpus file into memory. + """ + want = stop - start + for attempt in range(tries): + try: + req = urllib.request.Request(url, headers={"Range": "bytes=%d-%d" % (start, stop - 1)}) + with urllib.request.urlopen(req, timeout=120) as r: + if r.status == 206: + expected = "bytes %d-%d/" % (start, stop - 1) + answered = r.headers.get("Content-Range") or "" + if not answered.startswith(expected): + raise IOError("asked for %s, server sent %r" % (expected, answered)) + elif r.status == 200: + length = r.headers.get("Content-Length") + if start != 0 or length is None or int(length) != want: + raise IOError("server ignored the Range request (HTTP 200, %s bytes)" + % length) + else: + raise IOError("unexpected HTTP %d" % r.status) + body = r.read(want + 1) + if len(body) != want: + raise IOError("read %d bytes, expected %d" % (len(body), want)) + return body + except Exception as e: # noqa: BLE001 + if attempt == tries - 1: + raise RuntimeError("%s [%d, %d): %s" % (url, start, stop, e)) + time.sleep(2 ** attempt) + + +def download(root, todo, threads): + """Fetch the missing ranges with at most `threads` requests in flight. + + Each completed chunk is written and released before the next request is + submitted, so memory stays near threads * CHUNK whatever the file size. + """ + total = 0 + for f, rs in todo.items(): # what is still missing + state = os.path.join(root, f) + ".ranges.json" + done = merge(json.load(open(state))) if os.path.exists(state) else [] + total += sum(b - a for a, b in subtract(rs, done)) + got = 0 + t0 = time.time() + for f, rs in todo.items(): + path = os.path.join(root, f) + os.makedirs(os.path.dirname(path), exist_ok=True) + state = path + ".ranges.json" + done = merge(json.load(open(state))) if os.path.exists(state) else [] + missing = subtract(rs, done) + if not missing: + continue + if not os.path.exists(path): + open(path, "wb").close() + pieces = iter([p for a, b in missing for p in requests_for(f, a, b)]) + with open(path, "r+b") as fh, concurrent.futures.ThreadPoolExecutor(threads) as pool: + pending = {} + + def submit_next(): + for u, s, e, off in pieces: # at most one per call + pending[pool.submit(fetch, u, s, e)] = off + return + + for _ in range(threads): + submit_next() + while pending: + finished, _ = concurrent.futures.wait( + pending, return_when=concurrent.futures.FIRST_COMPLETED) + for fut in finished: + off = pending.pop(fut) + body = fut.result() + fh.seek(off) + fh.write(body) + done = merge(done + [(off, off + len(body))]) + json.dump(done, open(state, "w")) + got += len(body) + del body, fut # release before the next request + submit_next() + rate = got / max(time.time() - t0, 1e-9) + print("\r%6.2f of %.2f GB (%.0f MB/s, %s) " % ( + got / 1e9, total / 1e9, rate / 1e6, f), end="", flush=True) + print() + + +def download_heldout(root, held, threads): + """The held-out rows, fetched block by block (consecutive rows share one request) and saved in + the order of their row list as heldout_rows.npy beside the corpus file.""" + for f, rows in held.items(): + out = os.path.join(root, os.path.dirname(f), data.HELDOUT) + if os.path.exists(out): + continue + src = SOURCES[f] + dtype = {".u8bin": np.uint8, ".i8bin": np.int8, ".fbin": np.float32}[os.path.splitext(f)[1]] + d = src["row"] // np.dtype(dtype).itemsize + order = np.argsort(rows) + srt = rows[order] + cuts = np.flatnonzero(np.diff(srt) != 1) + 1 + blocks = np.split(srt, cuts) + pieces = [] + for block in blocks: # (local start, stop) per block + a, b = 8 + int(block[0]) * src["row"], 8 + (int(block[-1]) + 1) * src["row"] + pieces.append(requests_for(f, a, b)) + with concurrent.futures.ThreadPoolExecutor(threads) as pool: + bodies = list(pool.map(lambda reqs: b"".join(fetch(u, s, e) for u, s, e, _o in reqs), + pieces)) + sorted_rows = np.frombuffer(b"".join(bodies), dtype=dtype).reshape(len(srt), d) + result = np.empty_like(sorted_rows) + result[order] = sorted_rows # back to the row list's order + tmp = out[:-4] + ".tmp%d.npy" % os.getpid() + np.save(tmp, result) + os.replace(tmp, out) + print("saved %d held-out rows (%d range requests) in %s" % (len(rows), len(blocks), out)) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--results", choices=ORDER, required=True, + help="1M: the 1M results; 10M: the 1M and 10M results; 100M: all three") + ap.add_argument("--data", default=data.ROOT, help="where to put the files ($EMEANS_DATA)") + ap.add_argument("--threads", type=int, default=16, help="parallel range requests") + ap.add_argument("--dry-run", action="store_true", help="print the sizes and stop") + ap.add_argument("--yes", action="store_true", help="do not ask for confirmation") + ap.add_argument("--no-check", action="store_true", help="skip the fingerprint check") + a = ap.parse_args() + + print("What each choice downloads (each includes the ones above it). Larger scales read a\n" + "longer prefix of the big corpora, so the download grows about fivefold per step:\n") + for lv in ORDER: + size = plan_bytes(lv) + mark = " <- your choice" if lv == a.results else "" + print(" --results %-5s %7.1f GB about %s at 25 MB/s (200 Mbit/s), %s at 250 MB/s%s" % ( + lv, size / 1e9, hours(size / 25e6), hours(size / 250e6), mark)) + print(" adds: %s" % LEVELS[lv][0]) + todo, held = plan(a.results) + print("\nFiles for --results %s, under %s:" % (a.results, a.data)) + for f, rs in todo.items(): + print(" %-50s %8.2f GB" % (f, sum(b - x for x, b in rs) / 1e9)) + for f, rows in held.items(): + print(" %-50s %8.4f GB (%d held-out rows)" % ( + os.path.join(os.path.dirname(f), data.HELDOUT), heldout_bytes(f, rows) / 1e9, + len(rows))) + if a.dry_run: + return + if not a.yes and input("\nDownload? [y/N] ").strip().lower() not in ("y", "yes"): + sys.exit("nothing downloaded") + download(a.data, todo, a.threads) + download_heldout(a.data, held, a.threads) + if a.no_check: + return + os.environ["EMEANS_DATA"] = a.data + data.ROOT = a.data + for lv in ORDER[:ORDER.index(a.results) + 1]: + for name in LEVELS[lv][1]: + data.load(name) # raises on a fingerprint mismatch + print("checked %s against the paper's fingerprints" % name) + + +def hours(seconds): + if seconds < 60: + return "under a minute" + return "%.0f min" % (seconds / 60) if seconds < 5400 else "%.1f h" % (seconds / 3600) + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/benchs/e_means/paper_flash_matched.py b/thirdparty/faiss/benchs/e_means/paper_flash_matched.py new file mode 100644 index 000000000..a4fc7d63c --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_flash_matched.py @@ -0,0 +1,64 @@ +# 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. + +"""Build $EMEANS_CACHE/flash_matched/flash_kmeans: Flash-KMeans 0.3.1 with squared norms in +float32. + +Flash-KMeans works in float16, whose largest value is 65,504. SimSearchNet++ rows have squared +norms near 4.3e6, and SPACEV's reach 6.2e4, so the paper ran a copy of Flash-KMeans that computes +squared norms in float32 on those two corpora. This script makes that copy from the installed +package by applying the paper's eight one-line edits, and refuses to run if any edit does not +match exactly. paper_xb.py puts the copy first on the path for SPACEV and SimSearchNet++ +only. + + python paper_flash_matched.py +""" +import importlib.metadata +import importlib.util +import os +import shutil + +TARGET = os.path.join(os.environ.get("EMEANS_CACHE", "cache"), "flash_matched", + "flash_kmeans") +# file: [(stock text, patched text, occurrences)] +EDITS = { + "interface.py": [ + ("(x_b[:, i:i + _CHUNK] ** 2).sum(dim=-1)", + "(x_b[:, i:i + _CHUNK].float() ** 2).sum(dim=-1)", 1)], + "kmeans_large.py": [ + ("(centroids_g[g] ** 2).sum(dim=-1)", "(centroids_g[g].float() ** 2).sum(dim=-1)", 2), + ("(x_block ** 2).sum(dim=-1)", "(x_block.float() ** 2).sum(dim=-1)", 2)], + "kmeans_triton_impl.py": [ + ("(x[:, i:i + XSQ_CHUNK] ** 2).sum(dim=-1)", + "(x[:, i:i + XSQ_CHUNK].float() ** 2).sum(dim=-1)", 1)], + "torch_fallback.py": [ + ("(centroids ** 2).sum(dim=-1)", "(centroids.float() ** 2).sum(dim=-1)", 1), + ("(x ** 2).sum(dim=-1)", "(x.float() ** 2).sum(dim=-1)", 1)], +} + + +def main(): + version = importlib.metadata.version("flash-kmeans") + assert version == "0.3.1", "the paper used flash-kmeans 0.3.1, found %s" % version + source = os.path.dirname(importlib.util.find_spec("flash_kmeans").origin) + target = TARGET + if os.path.isdir(target): + shutil.rmtree(target) + shutil.copytree(source, target, ignore=shutil.ignore_patterns("__pycache__")) + for name, edits in EDITS.items(): + path = os.path.join(target, name) + text = open(path).read() + for stock, patched, count in edits: + assert text.count(stock) == count, "%s: expected %d of %r, found %d" % ( + name, count, stock, text.count(stock)) + text = text.replace(stock, patched) + open(path, "w").write(text) + with open(os.path.join(os.path.dirname(target), "VERSION"), "w") as fh: + fh.write(version + "\n") # paper_xb.py checks it before every run + print("wrote %s (flash-kmeans %s, 8 edits)" % (target, version)) + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/benchs/e_means/paper_splits/fb_ssnpp_holdout_rows.npy b/thirdparty/faiss/benchs/e_means/paper_splits/fb_ssnpp_holdout_rows.npy new file mode 100644 index 000000000..3d62ab92f Binary files /dev/null and b/thirdparty/faiss/benchs/e_means/paper_splits/fb_ssnpp_holdout_rows.npy differ diff --git a/thirdparty/faiss/benchs/e_means/paper_splits/fingerprints.json b/thirdparty/faiss/benchs/e_means/paper_splits/fingerprints.json new file mode 100644 index 000000000..f1384e29d --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_splits/fingerprints.json @@ -0,0 +1,163 @@ +{ + "deep1b-1M": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "ca94deceddb13e16d6cfb81365e2e18c319bf704b1d0ea9a28e5067bba03c458", + "test_sha256": "05d685ccf5e413a0559348b3586ec82a72da637d50b7d2b9a521e70c6cd29b6f", + "n_train": 1000000, + "dim": 96, + "train_rows_sha256": "7b74aeede93a64c6a2e598f021fbaa42061a7e09e9f3f75f1c1254fbb4419368", + "n_eval_rows_in_train": 4 + }, + "deep1b-10M": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "0fa76bc2c0a60d583c89eec77db556960e915d8d77bef9f140ab7bbca0fdb14f", + "test_sha256": "e1ecb70c88c869952d779fb80537f93e0a15bb0ee569d7cc82b96ff07a3ae7f2", + "n_train": 10000000, + "dim": 96, + "train_rows_sha256": "896964f606091f58515f3ca6bc07bc158780aa4ae92509326ec775839f5afa43", + "n_eval_rows_in_train": 4 + }, + "sift1b-10M-normalized": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "c83fe6e48b31c58be5401ef3b8f785d8485113497ddfd6d1bdd993247eaa13a1", + "test_sha256": "7fc972439547305af4eea62707b3cbabcf1c270223e1cc2c03a5ba6c308294d6", + "n_train": 10000000, + "dim": 128, + "train_rows_sha256": "ee0a06b1698e6677ac5d87e276c6410b3dddee779261954ee124cf616a7ac13a", + "n_eval_rows_in_train": 0 + }, + "sift1b-10M-div512": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "37e40955c494ae50329980dd81a0b3ec715c671d3a41db9c112e31deb5a8d079", + "test_sha256": "d862fd984033eb81b634e6fe2d2fc1f0d3628bf54704c9cf569e11b58cfd918a", + "n_train": 10000000, + "dim": 128, + "train_rows_sha256": "a58015e513521c4c5e1dcf8840d0bbb8a1a83f662f2d89d7dbe20fd6168fe634", + "n_eval_rows_in_train": 0 + }, + "spacev-1M": { + "kind": "region_scatter", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "1c59da848fc792157f107733da4a2f288568c51ea4fe44cdbbc1b9cd1352acec", + "test_sha256": "ecb6c6d304eb772d0891685bb2cf0b417efe15924894879af7b7fcfd431a0549", + "n_train": 1000000, + "dim": 100, + "train_rows_sha256": "07c827691fb18f648271d20258f7e65df5bd09ffbfb5956523e7c543ab2cbd8a", + "n_eval_rows_in_train": 6 + }, + "spacev-10M": { + "kind": "region_scatter", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "1c59da848fc792157f107733da4a2f288568c51ea4fe44cdbbc1b9cd1352acec", + "test_sha256": "ecb6c6d304eb772d0891685bb2cf0b417efe15924894879af7b7fcfd431a0549", + "n_train": 10000000, + "dim": 100, + "train_rows_sha256": "156dfae5210d85e26f34f5bf1539d6c07056e1387c567846b426161e01488ab8", + "n_eval_rows_in_train": 45 + }, + "fb-ssnpp-1M": { + "kind": "region_scatter", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "d51b5e50430b61a8a4a314a5df903195005da36e4de56e0a11ad3908b0a1dd08", + "test_sha256": "fae0b470fc0a3c74bcc04245b821bf34045a199185b3ecae2c21f1c2a7b10e40", + "n_train": 1000000, + "dim": 256, + "train_rows_sha256": "cb4988c357268c46c8a33a55cebb5d88199badeb32a72fb6187e93aa2674274b", + "n_eval_rows_in_train": 0 + }, + "fb-ssnpp-10M": { + "kind": "region_scatter", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "d51b5e50430b61a8a4a314a5df903195005da36e4de56e0a11ad3908b0a1dd08", + "test_sha256": "fae0b470fc0a3c74bcc04245b821bf34045a199185b3ecae2c21f1c2a7b10e40", + "n_train": 10000000, + "dim": 256, + "train_rows_sha256": "fe49ca7ae0cc3985c3f0c57d6b8e2ddfbe1c31d3023ba200ea1d442e1351b5c8", + "n_eval_rows_in_train": 0 + }, + "dino10b-1M-div4096": { + "kind": "shipped_queries", + "n_val": 50000, + "n_test": 50000, + "val_sha256": "6245215f29eb5830639169300a74215660bb0959d7aed0df67ef312e310e351f", + "test_sha256": "cc83c532b4b780b77959998f67239d5eca42bbc8d55bb00270d7143222c0fcfd", + "n_train": 1000000, + "dim": 1024, + "train_rows_sha256": "124629fc9bcaccbd82c71d41a5579271c3d7d428047ba669ee4792b989c040a9", + "n_eval_rows_in_train": 0 + }, + "dino10b-10M-div4096": { + "kind": "shipped_queries", + "n_val": 50000, + "n_test": 50000, + "val_sha256": "6245215f29eb5830639169300a74215660bb0959d7aed0df67ef312e310e351f", + "test_sha256": "cc83c532b4b780b77959998f67239d5eca42bbc8d55bb00270d7143222c0fcfd", + "n_train": 10000000, + "dim": 1024, + "train_rows_sha256": "2cc25b207e9fbc4072843bf111a01e30352d674493fd4a2ed8d6d71d96126d5a", + "n_eval_rows_in_train": 0 + }, + "imagenet-clip-512-normalized": { + "kind": "permutation", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "d4a24d9e28cd08300757997fd35f85f5409dff30d1c5708bfa9af1a5c1e47ffd", + "test_sha256": "454156aeec55974679c951c6a7dea28d9cdcbdfe708688676a825b333a7969f4", + "n_train": 1000000, + "dim": 512, + "train_rows_sha256": "d501e387a6b2f67bd13d58b11bb6e278097a58a12ff6b82d4633c5bccab74542", + "n_eval_rows_in_train": 0 + }, + "deep1b-100M": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "51c157bca54cb8d5b14f83bae0a5d6ecaf1f5ea1e718d99ed572316573d242b1", + "test_sha256": "f9498a2f17e77521d8199ba00f6b471d19872a6365a1df1dcadc6afee5b96a51", + "n_train": 100000000, + "dim": 96, + "train_rows_sha256": "a3bbb7543770fe9bd2fbc42e98f07c9339474fea0bbb47f0d9bae09fe5703bf8" + }, + "spacev-100M": { + "kind": "none: shipped queries halved (the runner's fallback)", + "n_val": 14658, + "n_test": 14658, + "val_sha256": "a8daffd3e6a2a350a949d26b9d0cf804930aa395cedc9e4864e64f5f6614701b", + "test_sha256": "4ebca4d4c7eef088cbac3c2679ca2953145fb0125fef84f561bb1bbe7ecce858", + "n_train": 100000000, + "dim": 100, + "train_rows_sha256": "9cf4d973282cff25a5ae003aad99c43e4e1c5a0bbefe876b4dc889da1fddbbc3" + }, + "fb-ssnpp-100M": { + "kind": "region_scatter", + "n_val": 10000, + "n_test": 10000, + "val_sha256": "d51b5e50430b61a8a4a314a5df903195005da36e4de56e0a11ad3908b0a1dd08", + "test_sha256": "fae0b470fc0a3c74bcc04245b821bf34045a199185b3ecae2c21f1c2a7b10e40", + "n_train": 100000000, + "dim": 256, + "train_rows_sha256": "e7e386454b1f76ee58aa148db4e6d69b16b348b0b4a0b523c08fb9f17b35bd8f" + }, + "sift1b-100M-div512": { + "kind": "shipped_queries", + "n_val": 5000, + "n_test": 5000, + "val_sha256": "6c13f12d83bbf77db9ad20f1e07dbd2085d92dd80141f7ff102369436cb936d2", + "test_sha256": "1467f88475df6ed20f097ea1e19a6c14f718cd9c3b498ec56c87eef926d77b62", + "n_train": 100000000, + "dim": 128, + "train_rows_sha256": "e4a5e57e116cb862a1c734a011ff00a120700a4254a8f834e1f3e57e2930497b" + } +} \ No newline at end of file diff --git a/thirdparty/faiss/benchs/e_means/paper_splits/imagenet_clip_holdout_rows.npy b/thirdparty/faiss/benchs/e_means/paper_splits/imagenet_clip_holdout_rows.npy new file mode 100644 index 000000000..c07e805bd Binary files /dev/null and b/thirdparty/faiss/benchs/e_means/paper_splits/imagenet_clip_holdout_rows.npy differ diff --git a/thirdparty/faiss/benchs/e_means/paper_splits/spacev_holdout_rows.npy b/thirdparty/faiss/benchs/e_means/paper_splits/spacev_holdout_rows.npy new file mode 100644 index 000000000..028da0a30 Binary files /dev/null and b/thirdparty/faiss/benchs/e_means/paper_splits/spacev_holdout_rows.npy differ diff --git a/thirdparty/faiss/benchs/e_means/paper_targets.json b/thirdparty/faiss/benchs/e_means/paper_targets.json new file mode 100644 index 000000000..c41b7105f --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_targets.json @@ -0,0 +1,5191 @@ +{ + "note": "Flash-KMeans after 25 iterations (Table 3, Figure 4(b)) and its whole Figure 4(b) curve (flash_curve: iterations -> seed -> test_mse, seconds); Faiss k-means after 25 Lloyd iterations (Figure 3, which has no Flash arm). Test error per row, exact scorer of paper_xb.test_error; seconds are one 80 GB GPU, median of the timed calls (paper_xb.timed).", + "table3": { + "deep1b-1M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.38925347141324373, + "per_seed": { + "10": { + "test_mse": 0.38919252648892905, + "seconds": 0.4124198970384896 + }, + "11": { + "test_mse": 0.38923256872522605, + "seconds": 0.41167728893924505 + }, + "12": { + "test_mse": 0.3891145776744891, + "seconds": 0.41430215490981936 + }, + "13": { + "test_mse": 0.388604828664113, + "seconds": 0.41173722594976425 + }, + "14": { + "test_mse": 0.39029624076382124, + "seconds": 0.41405491810292006 + }, + "15": { + "test_mse": 0.38927437410126137, + "seconds": 0.412183798965998 + }, + "16": { + "test_mse": 0.38946275139203773, + "seconds": 0.4117860560072586 + }, + "17": { + "test_mse": 0.3895240858935367, + "seconds": 0.411761399009265 + }, + "18": { + "test_mse": 0.3886529636672202, + "seconds": 0.41281670599710196 + }, + "19": { + "test_mse": 0.3895203570572017, + "seconds": 0.4117704149102792 + } + } + }, + "dino10b-1M-div4096": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.012281439280918568, + "per_seed": { + "10": { + "test_mse": 0.012280051907529123, + "seconds": 1.7048634730745107 + }, + "11": { + "test_mse": 0.012281021809028462, + "seconds": 1.700088840094395 + }, + "12": { + "test_mse": 0.012275702506309608, + "seconds": 1.6989943580701947 + }, + "13": { + "test_mse": 0.012280834847192746, + "seconds": 1.7057941450038925 + }, + "14": { + "test_mse": 0.012286114296906162, + "seconds": 1.6976826750906184 + }, + "15": { + "test_mse": 0.012285734681322939, + "seconds": 1.6996825569076464 + }, + "16": { + "test_mse": 0.012281856752808672, + "seconds": 1.7030585550237447 + }, + "17": { + "test_mse": 0.012282634820973035, + "seconds": 1.702651873929426 + }, + "18": { + "test_mse": 0.012280630042359698, + "seconds": 1.6973353630164638 + }, + "19": { + "test_mse": 0.012289143588676816, + "seconds": 1.7031852600630373 + } + } + }, + "spacev-1M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 7228.99001443477, + "per_seed": { + "10": { + "test_mse": 7234.811019872948, + "seconds": 0.3299303390085697 + }, + "11": { + "test_mse": 7222.725897980618, + "seconds": 0.32963504490908235 + }, + "12": { + "test_mse": 7231.216850668475, + "seconds": 0.3347917159553617 + }, + "13": { + "test_mse": 7227.869108892536, + "seconds": 0.32981012493837625 + }, + "14": { + "test_mse": 7228.853473679543, + "seconds": 0.3301071940222755 + }, + "15": { + "test_mse": 7228.659372677212, + "seconds": 0.32961608201730996 + }, + "16": { + "test_mse": 7231.679887030567, + "seconds": 0.33207320992369205 + }, + "17": { + "test_mse": 7244.3311146384685, + "seconds": 0.32953192200511694 + }, + "18": { + "test_mse": 7229.126555189999, + "seconds": 0.33055219892412424 + }, + "19": { + "test_mse": 7226.154128604722, + "seconds": 0.32965485798195004 + } + } + }, + "fb-ssnpp-1M": { + "flash_api": "kmeans_largeN", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 113555.28402890626, + "per_seed": { + "10": { + "test_mse": 113596.10330664062, + "seconds": 0.4848793790442869 + }, + "11": { + "test_mse": 113556.028696875, + "seconds": 0.4865547879599035 + }, + "12": { + "test_mse": 113554.5393609375, + "seconds": 0.4827135599916801 + }, + "13": { + "test_mse": 113543.33660390625, + "seconds": 0.48272885102778673 + }, + "14": { + "test_mse": 113571.81424101563, + "seconds": 0.4829856650903821 + }, + "15": { + "test_mse": 113522.3395296875, + "seconds": 0.4884952900465578 + }, + "16": { + "test_mse": 113580.54007265625, + "seconds": 0.48794245696626604 + }, + "17": { + "test_mse": 113531.37636484375, + "seconds": 0.4825386080192402 + }, + "18": { + "test_mse": 113633.30314335937, + "seconds": 0.4828505050390959 + }, + "19": { + "test_mse": 113530.51823398437, + "seconds": 0.48328677599783987 + } + } + }, + "deep1b-10M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.3423093055814813, + "per_seed": { + "10": { + "test_mse": 0.34233559704884153, + "seconds": 15.826704894076101 + }, + "11": { + "test_mse": 0.3421662719613289, + "seconds": 15.850354993948713 + }, + "12": { + "test_mse": 0.34189472554908956, + "seconds": 15.82683536899276 + }, + "13": { + "test_mse": 0.34232683521348806, + "seconds": 15.838169638067484 + }, + "14": { + "test_mse": 0.34230542548964066, + "seconds": 15.840124418027699 + }, + "15": { + "test_mse": 0.34231318567332203, + "seconds": 15.851295443018898 + }, + "16": { + "test_mse": 0.342084271418539, + "seconds": 15.851885267999023 + }, + "17": { + "test_mse": 0.3419608554851684, + "seconds": 15.84296643093694 + }, + "18": { + "test_mse": 0.3428588249360746, + "seconds": 15.844692645012401 + }, + "19": { + "test_mse": 0.3423334397282002, + "seconds": 15.840148041024804 + } + } + }, + "dino10b-10M-div4096": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.011224445864631562, + "per_seed": { + "10": { + "test_mse": 0.0112285244733945, + "seconds": 68.05752124998253 + }, + "11": { + "test_mse": 0.011224412719217362, + "seconds": 67.77608941704966 + }, + "12": { + "test_mse": 0.011221044873259962, + "seconds": 67.99694074096624 + }, + "13": { + "test_mse": 0.011229953408604488, + "seconds": 67.81753147998825 + }, + "14": { + "test_mse": 0.011224479010045762, + "seconds": 67.79422312602401 + }, + "15": { + "test_mse": 0.011227821770741138, + "seconds": 67.92696786404122 + }, + "16": { + "test_mse": 0.01122725334596471, + "seconds": 68.2583589659771 + }, + "17": { + "test_mse": 0.011217344943094067, + "seconds": 68.00641511601862 + }, + "18": { + "test_mse": 0.011217106495206245, + "seconds": 67.99312512599863 + }, + "19": { + "test_mse": 0.011223606559332983, + "seconds": 68.14903502701782 + } + } + }, + "spacev-10M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 6377.446315411906, + "per_seed": { + "10": { + "test_mse": 6371.824526583065, + "seconds": 11.205384804983623 + }, + "11": { + "test_mse": 6372.926796913727, + "seconds": 11.222986552049406 + }, + "12": { + "test_mse": 6378.324062727225, + "seconds": 11.209727579029277 + }, + "13": { + "test_mse": 6377.816538892278, + "seconds": 11.20420452998951 + }, + "14": { + "test_mse": 6378.518548119242, + "seconds": 11.203694280935451 + }, + "15": { + "test_mse": 6381.371819929729, + "seconds": 11.341129004955292 + }, + "16": { + "test_mse": 6377.076091931534, + "seconds": 11.345899566018488 + }, + "17": { + "test_mse": 6378.0412522329125, + "seconds": 11.21095499000512 + }, + "18": { + "test_mse": 6373.178720078798, + "seconds": 11.212661353987642 + }, + "19": { + "test_mse": 6373.8937764533775, + "seconds": 11.224880087072961 + } + } + }, + "fb-ssnpp-10M": { + "flash_api": "kmeans_largeN", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 109524.84575659179, + "per_seed": { + "10": { + "test_mse": 109534.63756191406, + "seconds": 21.76742266700603 + }, + "11": { + "test_mse": 109523.15172392578, + "seconds": 21.784127225051634 + }, + "12": { + "test_mse": 109478.39268691406, + "seconds": 21.84094322891906 + }, + "13": { + "test_mse": 109505.3901296875, + "seconds": 21.776910719112493 + }, + "14": { + "test_mse": 109526.53978925782, + "seconds": 21.800771398935467 + }, + "15": { + "test_mse": 109510.41311367188, + "seconds": 21.828368448012043 + }, + "16": { + "test_mse": 109504.918525, + "seconds": 21.792950792005286 + }, + "17": { + "test_mse": 109537.62386220704, + "seconds": 21.785762496991083 + }, + "18": { + "test_mse": 109528.76618632812, + "seconds": 21.78301236103289 + }, + "19": { + "test_mse": 109532.9995758789, + "seconds": 21.77431908797007 + } + } + }, + "deep1b-100M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.3050453965514258, + "per_seed": { + "10": { + "test_mse": 0.30528084310726356, + "seconds": 426.07208114594687 + }, + "11": { + "test_mse": 0.30468672122955015, + "seconds": 421.4674853950273 + }, + "12": { + "test_mse": 0.3052773698880303, + "seconds": 423.0855056120781 + }, + "13": { + "test_mse": 0.3047988915155164, + "seconds": 430.52769569004886 + }, + "14": { + "test_mse": 0.3048814662487586, + "seconds": 426.4019639249891 + }, + "15": { + "test_mse": 0.30493703865551536, + "seconds": 422.0754697889788 + }, + "16": { + "test_mse": 0.30515375444733633, + "seconds": 420.5065470620757 + }, + "17": { + "test_mse": 0.30474902257619013, + "seconds": 429.45558752305806 + }, + "18": { + "test_mse": 0.3052334514227464, + "seconds": 426.4517082950333 + }, + "19": { + "test_mse": 0.305597167981323, + "seconds": 422.1122991539305 + } + } + }, + "spacev-100M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 4146.505375955967, + "per_seed": { + "10": { + "test_mse": 4144.92761725816, + "seconds": 462.7176042330684 + }, + "11": { + "test_mse": 4144.519724253782, + "seconds": 459.1536513910396 + }, + "12": { + "test_mse": 4146.151165590582, + "seconds": 466.315742068924 + }, + "13": { + "test_mse": 4146.85958632135, + "seconds": 457.5796683100052 + }, + "14": { + "test_mse": 4153.135390527034, + "seconds": 456.93971357203554 + }, + "15": { + "test_mse": 4144.3053186497655, + "seconds": 462.3473034220515 + }, + "16": { + "test_mse": 4143.452488819318, + "seconds": 463.38001738500316 + }, + "17": { + "test_mse": 4149.331915353175, + "seconds": 460.5306828659959 + }, + "18": { + "test_mse": 4148.729763960434, + "seconds": 458.4442690249998 + }, + "19": { + "test_mse": 4158.269308565905, + "seconds": 459.79508772306144 + } + } + }, + "fb-ssnpp-100M": { + "flash_api": "kmeans_largeN", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 105023.15370986328, + "per_seed": { + "10": { + "test_mse": 105067.80133798828, + "seconds": 872.7275820500217 + }, + "11": { + "test_mse": 105032.88047041015, + "seconds": 868.2380740729859 + }, + "12": { + "test_mse": 105059.79596308594, + "seconds": 864.7011476320913 + }, + "13": { + "test_mse": 105020.86475166016, + "seconds": 871.1214464789955 + }, + "14": { + "test_mse": 105035.0956540039, + "seconds": 870.4829383710166 + }, + "15": { + "test_mse": 105025.4426680664, + "seconds": 865.9788600910688 + }, + "16": { + "test_mse": 105005.4102040039, + "seconds": 866.8769044510555 + }, + "17": { + "test_mse": 104997.0900758789, + "seconds": 874.1807672110153 + }, + "18": { + "test_mse": 104960.861421875, + "seconds": 868.9203098589787 + }, + "19": { + "test_mse": 105013.5650319336, + "seconds": 866.7472124310443 + } + } + } + }, + "figure4": { + "deep1b-10M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.3423093055814813, + "per_seed": { + "10": { + "test_mse": 0.34233559704884153, + "seconds": 15.826704894076101 + }, + "11": { + "test_mse": 0.3421662719613289, + "seconds": 15.850354993948713 + }, + "12": { + "test_mse": 0.34189472554908956, + "seconds": 15.82683536899276 + }, + "13": { + "test_mse": 0.34232683521348806, + "seconds": 15.838169638067484 + }, + "14": { + "test_mse": 0.34230542548964066, + "seconds": 15.840124418027699 + }, + "15": { + "test_mse": 0.34231318567332203, + "seconds": 15.851295443018898 + }, + "16": { + "test_mse": 0.342084271418539, + "seconds": 15.851885267999023 + }, + "17": { + "test_mse": 0.3419608554851684, + "seconds": 15.84296643093694 + }, + "18": { + "test_mse": 0.3428588249360746, + "seconds": 15.844692645012401 + }, + "19": { + "test_mse": 0.3423334397282002, + "seconds": 15.840148041024804 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 0.3592876723239124, + "seconds": 0.635074298013933 + }, + "11": { + "test_mse": 0.358691934512559, + "seconds": 0.6343091829912737 + }, + "12": { + "test_mse": 0.3587937885757736, + "seconds": 0.6342892560642213 + }, + "13": { + "test_mse": 0.35994459516940497, + "seconds": 0.6343724849866703 + }, + "14": { + "test_mse": 0.3592860068029884, + "seconds": 0.6358506489777938 + }, + "15": { + "test_mse": 0.35964099930892596, + "seconds": 0.6374819609336555 + }, + "16": { + "test_mse": 0.3592635267378053, + "seconds": 0.6375119300791994 + }, + "17": { + "test_mse": 0.3593250535022855, + "seconds": 0.637998781981878 + }, + "18": { + "test_mse": 0.3596673824405745, + "seconds": 0.6380798360332847 + }, + "19": { + "test_mse": 0.3592047908893762, + "seconds": 0.6377757919253781 + } + }, + "2": { + "10": { + "test_mse": 0.351193494271108, + "seconds": 1.2712480539921671 + }, + "11": { + "test_mse": 0.3504202437407017, + "seconds": 1.2647102730115876 + }, + "12": { + "test_mse": 0.35046882624360526, + "seconds": 1.26468861696776 + }, + "13": { + "test_mse": 0.3515185937131878, + "seconds": 1.264870779006742 + }, + "14": { + "test_mse": 0.3507287979496771, + "seconds": 1.2647102089831606 + }, + "15": { + "test_mse": 0.3510044937612402, + "seconds": 1.2716738550225273 + }, + "16": { + "test_mse": 0.3508095537334235, + "seconds": 1.2717624319484457 + }, + "17": { + "test_mse": 0.35069855021450885, + "seconds": 1.2707457569194958 + }, + "18": { + "test_mse": 0.3510650489925975, + "seconds": 1.2716734930872917 + }, + "19": { + "test_mse": 0.3509169352000683, + "seconds": 1.2718684100545943 + } + }, + "3": { + "10": { + "test_mse": 0.3482264739614265, + "seconds": 1.9026840210426599 + }, + "11": { + "test_mse": 0.34757092223084657, + "seconds": 1.8968920350307599 + }, + "12": { + "test_mse": 0.3476035867145882, + "seconds": 1.8967013460351154 + }, + "13": { + "test_mse": 0.3484324742661765, + "seconds": 1.895570712047629 + }, + "14": { + "test_mse": 0.34791043563006463, + "seconds": 1.8965024380013347 + }, + "15": { + "test_mse": 0.34770198771036676, + "seconds": 1.906167214969173 + }, + "16": { + "test_mse": 0.3479352717236806, + "seconds": 1.907877448014915 + }, + "17": { + "test_mse": 0.347577930013867, + "seconds": 1.9057403889019042 + }, + "18": { + "test_mse": 0.3479120989444951, + "seconds": 1.905447918921709 + }, + "19": { + "test_mse": 0.34795228371846953, + "seconds": 1.9055918829981238 + } + }, + "5": { + "10": { + "test_mse": 0.3458123755458337, + "seconds": 3.1684995329706 + }, + "11": { + "test_mse": 0.3448834077592171, + "seconds": 3.1567214319948107 + }, + "12": { + "test_mse": 0.3451106086074993, + "seconds": 3.156761836959049 + }, + "13": { + "test_mse": 0.34603438524014263, + "seconds": 3.1650066380389035 + }, + "14": { + "test_mse": 0.34547851648653516, + "seconds": 3.1658240519464016 + }, + "15": { + "test_mse": 0.3450880130470484, + "seconds": 3.1748447640566155 + }, + "16": { + "test_mse": 0.3451756053754132, + "seconds": 3.1746573329437524 + }, + "17": { + "test_mse": 0.3449679168461956, + "seconds": 3.1740461019799113 + }, + "18": { + "test_mse": 0.34540141820570675, + "seconds": 3.174305410007946 + }, + "19": { + "test_mse": 0.34527806079288403, + "seconds": 3.1729588579619303 + } + }, + "8": { + "10": { + "test_mse": 0.3442603497530251, + "seconds": 5.065425325999968 + }, + "11": { + "test_mse": 0.3435832318478491, + "seconds": 5.053944366984069 + }, + "12": { + "test_mse": 0.34353929289223195, + "seconds": 5.049065890954807 + }, + "13": { + "test_mse": 0.3444673814708873, + "seconds": 5.05021760892123 + }, + "14": { + "test_mse": 0.3440098149934881, + "seconds": 5.056151547003537 + }, + "15": { + "test_mse": 0.3435278460826688, + "seconds": 5.076256560976617 + }, + "16": { + "test_mse": 0.3436276910306266, + "seconds": 5.074899522936903 + }, + "17": { + "test_mse": 0.3435404554134087, + "seconds": 5.0748496550368145 + }, + "18": { + "test_mse": 0.3442778239295184, + "seconds": 5.0650436229771 + }, + "19": { + "test_mse": 0.34393290648984487, + "seconds": 5.0701598869636655 + } + }, + "12": { + "10": { + "test_mse": 0.34317414119170214, + "seconds": 7.572224274044856 + }, + "11": { + "test_mse": 0.3427702727376214, + "seconds": 7.586878058034927 + }, + "12": { + "test_mse": 0.34264818150387083, + "seconds": 7.586129629984498 + }, + "13": { + "test_mse": 0.3433553834520404, + "seconds": 7.59851910895668 + }, + "14": { + "test_mse": 0.3430598179262457, + "seconds": 7.589913964038715 + }, + "15": { + "test_mse": 0.3428644364146179, + "seconds": 7.613068518927321 + }, + "16": { + "test_mse": 0.34288521894020857, + "seconds": 7.610260810004547 + }, + "17": { + "test_mse": 0.3428069937244349, + "seconds": 7.611394968931563 + }, + "18": { + "test_mse": 0.3435474089479173, + "seconds": 7.608125882106833 + }, + "19": { + "test_mse": 0.3432285629190427, + "seconds": 7.6122420760802925 + } + }, + "17": { + "10": { + "test_mse": 0.3426199629439191, + "seconds": 10.768505699001253 + }, + "11": { + "test_mse": 0.34244789334824727, + "seconds": 10.767030582064763 + }, + "12": { + "test_mse": 0.34227229146440963, + "seconds": 10.75750926497858 + }, + "13": { + "test_mse": 0.34269758067783074, + "seconds": 10.767128388979472 + }, + "14": { + "test_mse": 0.3426350167534607, + "seconds": 10.743042860995047 + }, + "15": { + "test_mse": 0.3425088666419259, + "seconds": 10.782427056925371 + }, + "16": { + "test_mse": 0.34241555812135005, + "seconds": 10.785693460027687 + }, + "17": { + "test_mse": 0.34233721569971437, + "seconds": 10.78000354708638 + }, + "18": { + "test_mse": 0.34326511971931284, + "seconds": 10.778779792948626 + }, + "19": { + "test_mse": 0.3427787279453536, + "seconds": 10.77890134404879 + } + }, + "25": { + "10": { + "test_mse": 0.34233559704884153, + "seconds": 15.826704894076101 + }, + "11": { + "test_mse": 0.3421662719613289, + "seconds": 15.850354993948713 + }, + "12": { + "test_mse": 0.34189472554908956, + "seconds": 15.82683536899276 + }, + "13": { + "test_mse": 0.34232683521348806, + "seconds": 15.838169638067484 + }, + "14": { + "test_mse": 0.34230542548964066, + "seconds": 15.840124418027699 + }, + "15": { + "test_mse": 0.34231318567332203, + "seconds": 15.851295443018898 + }, + "16": { + "test_mse": 0.342084271418539, + "seconds": 15.851885267999023 + }, + "17": { + "test_mse": 0.3419608554851684, + "seconds": 15.84296643093694 + }, + "18": { + "test_mse": 0.3428588249360746, + "seconds": 15.844692645012401 + }, + "19": { + "test_mse": 0.3423334397282002, + "seconds": 15.840148041024804 + } + }, + "40": { + "10": { + "test_mse": 0.34211952542852103, + "seconds": 25.344307532999665 + }, + "11": { + "test_mse": 0.3419099626014735, + "seconds": 25.21795676497277 + }, + "12": { + "test_mse": 0.34165186511288176, + "seconds": 25.339642817969434 + }, + "13": { + "test_mse": 0.34212154253305005, + "seconds": 25.33669970394112 + }, + "14": { + "test_mse": 0.34211339979458777, + "seconds": 25.332887753029354 + }, + "15": { + "test_mse": 0.34216152570544683, + "seconds": 25.361066548968665 + }, + "16": { + "test_mse": 0.34199668537044836, + "seconds": 25.361664796015248 + }, + "17": { + "test_mse": 0.34162503027813934, + "seconds": 25.37944965902716 + }, + "18": { + "test_mse": 0.3425917821079126, + "seconds": 25.35700431105215 + }, + "19": { + "test_mse": 0.3420971293954526, + "seconds": 25.35801020101644 + } + }, + "60": { + "10": { + "test_mse": 0.3421239907644846, + "seconds": 37.82353489706293 + }, + "11": { + "test_mse": 0.3417985106957397, + "seconds": 37.86148888396565 + }, + "12": { + "test_mse": 0.3415311290367512, + "seconds": 38.00831806997303 + }, + "13": { + "test_mse": 0.3419714812830166, + "seconds": 38.04204827500507 + }, + "14": { + "test_mse": 0.3419785369710899, + "seconds": 37.8236934900051 + }, + "15": { + "test_mse": 0.34220305324514666, + "seconds": 38.037354225991294 + }, + "16": { + "test_mse": 0.3420021739107412, + "seconds": 38.03991285501979 + }, + "17": { + "test_mse": 0.34156692652413756, + "seconds": 38.06608389294706 + }, + "18": { + "test_mse": 0.3425422897474786, + "seconds": 38.03920794604346 + }, + "19": { + "test_mse": 0.3419430902768431, + "seconds": 38.06951012602076 + } + }, + "80": { + "10": { + "test_mse": 0.34211276219635456, + "seconds": 50.67664395994507 + }, + "11": { + "test_mse": 0.3418655345490065, + "seconds": 50.482297899900004 + }, + "12": { + "test_mse": 0.34158023311705327, + "seconds": 50.67472800204996 + }, + "13": { + "test_mse": 0.34202545691753017, + "seconds": 50.67426065704785 + }, + "14": { + "test_mse": 0.3419569906045225, + "seconds": 50.664209364913404 + }, + "15": { + "test_mse": 0.3421784983095759, + "seconds": 50.76244800596032 + }, + "16": { + "test_mse": 0.3419796069879216, + "seconds": 50.75666114303749 + }, + "17": { + "test_mse": 0.3415680881716896, + "seconds": 50.7568332219962 + }, + "18": { + "test_mse": 0.34248481745928727, + "seconds": 50.758813383989036 + }, + "19": { + "test_mse": 0.341906131943804, + "seconds": 50.747829455067404 + } + }, + "100": { + "10": { + "test_mse": 0.34210454780878247, + "seconds": 63.062100572977215 + }, + "11": { + "test_mse": 0.3417751396761106, + "seconds": 63.34561266901437 + }, + "12": { + "test_mse": 0.3415709428146946, + "seconds": 63.340145790949464 + }, + "13": { + "test_mse": 0.34199854647537725, + "seconds": 63.409812227939256 + }, + "14": { + "test_mse": 0.34191428194110707, + "seconds": 63.06089104397688 + }, + "15": { + "test_mse": 0.34215991643474436, + "seconds": 63.453968818997964 + }, + "16": { + "test_mse": 0.3419621693495969, + "seconds": 63.448064110009 + }, + "17": { + "test_mse": 0.34157213031165884, + "seconds": 63.39371441095136 + }, + "18": { + "test_mse": 0.34247671065413915, + "seconds": 63.44312867894769 + }, + "19": { + "test_mse": 0.3419193190745616, + "seconds": 63.439663566998206 + } + } + } + }, + "spacev-10M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 6377.446315411906, + "per_seed": { + "10": { + "test_mse": 6371.824526583065, + "seconds": 11.205384804983623 + }, + "11": { + "test_mse": 6372.926796913727, + "seconds": 11.222986552049406 + }, + "12": { + "test_mse": 6378.324062727225, + "seconds": 11.209727579029277 + }, + "13": { + "test_mse": 6377.816538892278, + "seconds": 11.20420452998951 + }, + "14": { + "test_mse": 6378.518548119242, + "seconds": 11.203694280935451 + }, + "15": { + "test_mse": 6381.371819929729, + "seconds": 11.341129004955292 + }, + "16": { + "test_mse": 6377.076091931534, + "seconds": 11.345899566018488 + }, + "17": { + "test_mse": 6378.0412522329125, + "seconds": 11.21095499000512 + }, + "18": { + "test_mse": 6373.178720078798, + "seconds": 11.212661353987642 + }, + "19": { + "test_mse": 6373.8937764533775, + "seconds": 11.224880087072961 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 6940.92741675418, + "seconds": 0.4545654660323635 + }, + "11": { + "test_mse": 6947.65826910736, + "seconds": 0.45538266003131866 + }, + "12": { + "test_mse": 6942.037535462811, + "seconds": 0.45478571800049394 + }, + "13": { + "test_mse": 6938.884825984394, + "seconds": 0.45515123195946217 + }, + "14": { + "test_mse": 6947.323930310339, + "seconds": 0.4538246770389378 + }, + "15": { + "test_mse": 6927.839585991896, + "seconds": 0.4548468069988303 + }, + "16": { + "test_mse": 6937.677979367813, + "seconds": 0.454567426990252 + }, + "17": { + "test_mse": 6944.714535041019, + "seconds": 0.4555079959682189 + }, + "18": { + "test_mse": 6934.1057684709285, + "seconds": 0.4554601560230367 + }, + "19": { + "test_mse": 6936.002835235292, + "seconds": 0.45432685903506353 + } + }, + "2": { + "10": { + "test_mse": 6673.29479907805, + "seconds": 0.9003509620670229 + }, + "11": { + "test_mse": 6675.026071409666, + "seconds": 0.8992667350685224 + }, + "12": { + "test_mse": 6673.183556869665, + "seconds": 0.9002138950163499 + }, + "13": { + "test_mse": 6671.684869324692, + "seconds": 0.8997406050330028 + }, + "14": { + "test_mse": 6684.539255998296, + "seconds": 0.8998571230331436 + }, + "15": { + "test_mse": 6659.910309687099, + "seconds": 0.9009002209641039 + }, + "16": { + "test_mse": 6666.59345965289, + "seconds": 0.9006051850155927 + }, + "17": { + "test_mse": 6673.268011199832, + "seconds": 0.9031701219500974 + }, + "18": { + "test_mse": 6669.482593480009, + "seconds": 0.900739977019839 + }, + "19": { + "test_mse": 6675.006739197707, + "seconds": 0.9006321460474283 + } + }, + "3": { + "10": { + "test_mse": 6565.930108453162, + "seconds": 1.3603996259626001 + }, + "11": { + "test_mse": 6569.759287242609, + "seconds": 1.3604720289586112 + }, + "12": { + "test_mse": 6570.022408624434, + "seconds": 1.3607943480601534 + }, + "13": { + "test_mse": 6570.356852245354, + "seconds": 1.3624426879687235 + }, + "14": { + "test_mse": 6579.552481993496, + "seconds": 1.3613824039930478 + }, + "15": { + "test_mse": 6558.7538023181705, + "seconds": 1.362856641993858 + }, + "16": { + "test_mse": 6561.501724649639, + "seconds": 1.3600339900003746 + }, + "17": { + "test_mse": 6566.343252519715, + "seconds": 1.3636679599876516 + }, + "18": { + "test_mse": 6563.1283517042175, + "seconds": 1.3608377749915235 + }, + "19": { + "test_mse": 6571.177311504181, + "seconds": 1.3628901490010321 + } + }, + "5": { + "10": { + "test_mse": 6477.759039709337, + "seconds": 2.2600858689984307 + }, + "11": { + "test_mse": 6479.291270182505, + "seconds": 2.2633781569311395 + }, + "12": { + "test_mse": 6480.882021178693, + "seconds": 2.258793117944151 + }, + "13": { + "test_mse": 6487.702258362929, + "seconds": 2.2568310078931972 + }, + "14": { + "test_mse": 6486.336420735704, + "seconds": 2.2623952300054953 + }, + "15": { + "test_mse": 6478.571674733675, + "seconds": 2.2641634970204905 + }, + "16": { + "test_mse": 6478.044578353184, + "seconds": 2.2648054269957356 + }, + "17": { + "test_mse": 6479.400790415464, + "seconds": 2.2659892970114015 + }, + "18": { + "test_mse": 6475.657626060848, + "seconds": 2.2696314019849524 + }, + "19": { + "test_mse": 6480.88606251082, + "seconds": 2.2708810709882528 + } + }, + "8": { + "10": { + "test_mse": 6426.218425538072, + "seconds": 3.6213023230666295 + }, + "11": { + "test_mse": 6425.324886399134, + "seconds": 3.6175414560129866 + }, + "12": { + "test_mse": 6428.302589091382, + "seconds": 3.6162189920432866 + }, + "13": { + "test_mse": 6436.5806562046055, + "seconds": 3.6208353949477896 + }, + "14": { + "test_mse": 6432.96003530586, + "seconds": 3.6183879560558125 + }, + "15": { + "test_mse": 6430.634727861715, + "seconds": 3.637867192970589 + }, + "16": { + "test_mse": 6430.679840358911, + "seconds": 3.6228781959507614 + }, + "17": { + "test_mse": 6430.3400385933965, + "seconds": 3.6496644020080566 + }, + "18": { + "test_mse": 6424.180001428591, + "seconds": 3.6371742409537546 + }, + "19": { + "test_mse": 6426.882274278225, + "seconds": 3.6330291019985452 + } + }, + "12": { + "10": { + "test_mse": 6398.069176307819, + "seconds": 5.438983385916799 + }, + "11": { + "test_mse": 6397.379205647471, + "seconds": 5.42991675902158 + }, + "12": { + "test_mse": 6402.720208825042, + "seconds": 5.431085882009938 + }, + "13": { + "test_mse": 6407.541677602817, + "seconds": 5.43074817804154 + }, + "14": { + "test_mse": 6402.112725041343, + "seconds": 5.429549462045543 + }, + "15": { + "test_mse": 6405.546815280933, + "seconds": 5.440778852964286 + }, + "16": { + "test_mse": 6402.466421227036, + "seconds": 5.429495315009262 + }, + "17": { + "test_mse": 6403.845638964666, + "seconds": 5.455962743028067 + }, + "18": { + "test_mse": 6397.358777802676, + "seconds": 5.455309723969549 + }, + "19": { + "test_mse": 6398.8251678926645, + "seconds": 5.435135485022329 + } + }, + "17": { + "10": { + "test_mse": 6382.297711997208, + "seconds": 7.698624561075121 + }, + "11": { + "test_mse": 6383.214373383886, + "seconds": 7.689485382987186 + }, + "12": { + "test_mse": 6388.174391741091, + "seconds": 7.698480848921463 + }, + "13": { + "test_mse": 6388.997308290326, + "seconds": 7.684363653999753 + }, + "14": { + "test_mse": 6386.496774760449, + "seconds": 7.703033761004917 + }, + "15": { + "test_mse": 6392.3116658270355, + "seconds": 7.711999140970875 + }, + "16": { + "test_mse": 6388.163507445023, + "seconds": 7.708333374990616 + }, + "17": { + "test_mse": 6390.505571580241, + "seconds": 7.691101213044021 + }, + "18": { + "test_mse": 6383.500545116609, + "seconds": 7.719095656997524 + }, + "19": { + "test_mse": 6382.813052233962, + "seconds": 7.693075170973316 + } + }, + "25": { + "10": { + "test_mse": 6371.824526583065, + "seconds": 11.205384804983623 + }, + "11": { + "test_mse": 6372.926796913727, + "seconds": 11.222986552049406 + }, + "12": { + "test_mse": 6378.324062727225, + "seconds": 11.209727579029277 + }, + "13": { + "test_mse": 6377.816538892278, + "seconds": 11.20420452998951 + }, + "14": { + "test_mse": 6378.518548119242, + "seconds": 11.203694280935451 + }, + "15": { + "test_mse": 6381.371819929729, + "seconds": 11.341129004955292 + }, + "16": { + "test_mse": 6377.076091931534, + "seconds": 11.345899566018488 + }, + "17": { + "test_mse": 6378.0412522329125, + "seconds": 11.21095499000512 + }, + "18": { + "test_mse": 6373.178720078798, + "seconds": 11.212661353987642 + }, + "19": { + "test_mse": 6373.8937764533775, + "seconds": 11.224880087072961 + } + }, + "40": { + "10": { + "test_mse": 6365.677363588727, + "seconds": 18.084702899097465 + }, + "11": { + "test_mse": 6365.7216809309675, + "seconds": 18.11604086100124 + }, + "12": { + "test_mse": 6371.177713753484, + "seconds": 18.125306972069666 + }, + "13": { + "test_mse": 6369.2242019558935, + "seconds": 18.133408359019086 + }, + "14": { + "test_mse": 6369.94185185038, + "seconds": 18.13481119996868 + }, + "15": { + "test_mse": 6375.939182972536, + "seconds": 18.148499785049353 + }, + "16": { + "test_mse": 6368.16561954084, + "seconds": 18.15601485100342 + }, + "17": { + "test_mse": 6370.422352779378, + "seconds": 18.104405516991392 + }, + "18": { + "test_mse": 6365.270535433494, + "seconds": 18.188358729996253 + }, + "19": { + "test_mse": 6366.562812729839, + "seconds": 18.13094521104358 + } + }, + "60": { + "10": { + "test_mse": 6362.588613059185, + "seconds": 27.20761030097492 + }, + "11": { + "test_mse": 6362.7780841457925, + "seconds": 27.198636221000925 + }, + "12": { + "test_mse": 6368.159821029265, + "seconds": 27.182853962061927 + }, + "13": { + "test_mse": 6364.946911308784, + "seconds": 27.194870566017926 + }, + "14": { + "test_mse": 6367.004518762664, + "seconds": 27.197861966094933 + }, + "15": { + "test_mse": 6374.633833618183, + "seconds": 27.29804562701611 + }, + "16": { + "test_mse": 6365.851432403447, + "seconds": 27.28143629099941 + }, + "17": { + "test_mse": 6365.9587163720635, + "seconds": 27.220732684014365 + }, + "18": { + "test_mse": 6362.551573603247, + "seconds": 27.326070235983934 + }, + "19": { + "test_mse": 6363.640485069364, + "seconds": 27.233065943000838 + } + }, + "80": { + "10": { + "test_mse": 6361.406546042841, + "seconds": 36.319831799017265 + }, + "11": { + "test_mse": 6361.7478796822425, + "seconds": 36.30627588904463 + }, + "12": { + "test_mse": 6367.0406518116515, + "seconds": 36.28308038902469 + }, + "13": { + "test_mse": 6363.837309948859, + "seconds": 36.2791878139833 + }, + "14": { + "test_mse": 6365.949730791658, + "seconds": 36.290334052057005 + }, + "15": { + "test_mse": 6374.22255191169, + "seconds": 36.41535903100157 + }, + "16": { + "test_mse": 6364.911574841582, + "seconds": 36.31916565698339 + }, + "17": { + "test_mse": 6364.752202693611, + "seconds": 36.34490712196566 + }, + "18": { + "test_mse": 6361.693263954809, + "seconds": 36.445443038013764 + }, + "19": { + "test_mse": 6362.5362292357095, + "seconds": 36.34666182199726 + } + }, + "100": { + "10": { + "test_mse": 6360.975373445277, + "seconds": 45.49672582303174 + }, + "11": { + "test_mse": 6361.1702256142225, + "seconds": 45.42753864801489 + }, + "12": { + "test_mse": 6366.735978614943, + "seconds": 45.403699696063995 + }, + "13": { + "test_mse": 6363.585940966577, + "seconds": 45.39515957306139 + }, + "14": { + "test_mse": 6365.919801414762, + "seconds": 45.40244901902042 + }, + "15": { + "test_mse": 6373.970966268697, + "seconds": 45.542194424022455 + }, + "16": { + "test_mse": 6364.694017873795, + "seconds": 45.38686033396516 + }, + "17": { + "test_mse": 6364.392615098821, + "seconds": 45.44955535401823 + }, + "18": { + "test_mse": 6361.15794383644, + "seconds": 45.707065194961615 + }, + "19": { + "test_mse": 6362.541542928762, + "seconds": 45.528691780986264 + } + } + } + }, + "fb-ssnpp-10M": { + "flash_api": "kmeans_largeN", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 109524.84575659179, + "per_seed": { + "10": { + "test_mse": 109534.63756191406, + "seconds": 21.76742266700603 + }, + "11": { + "test_mse": 109523.15172392578, + "seconds": 21.784127225051634 + }, + "12": { + "test_mse": 109478.39268691406, + "seconds": 21.84094322891906 + }, + "13": { + "test_mse": 109505.3901296875, + "seconds": 21.776910719112493 + }, + "14": { + "test_mse": 109526.53978925782, + "seconds": 21.800771398935467 + }, + "15": { + "test_mse": 109510.41311367188, + "seconds": 21.828368448012043 + }, + "16": { + "test_mse": 109504.918525, + "seconds": 21.792950792005286 + }, + "17": { + "test_mse": 109537.62386220704, + "seconds": 21.785762496991083 + }, + "18": { + "test_mse": 109528.76618632812, + "seconds": 21.78301236103289 + }, + "19": { + "test_mse": 109532.9995758789, + "seconds": 21.77431908797007 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 112344.52123359375, + "seconds": 0.8845072250114754 + }, + "11": { + "test_mse": 112354.26203046874, + "seconds": 0.884447417978663 + }, + "12": { + "test_mse": 112365.34817773437, + "seconds": 0.8832498689880595 + }, + "13": { + "test_mse": 112390.32555039063, + "seconds": 0.8835942409932613 + }, + "14": { + "test_mse": 112278.58211015625, + "seconds": 0.8828548320452683 + }, + "15": { + "test_mse": 112435.9764109375, + "seconds": 0.8885394089738838 + }, + "16": { + "test_mse": 112363.25063710938, + "seconds": 0.8882013639668003 + }, + "17": { + "test_mse": 112368.95871992188, + "seconds": 0.8898513350286521 + }, + "18": { + "test_mse": 112449.89020898438, + "seconds": 0.8897799180122092 + }, + "19": { + "test_mse": 112381.216378125, + "seconds": 0.8892045899992809 + } + }, + "2": { + "10": { + "test_mse": 110972.474053125, + "seconds": 1.7473414390115067 + }, + "11": { + "test_mse": 110966.00535234375, + "seconds": 1.7499926540185697 + }, + "12": { + "test_mse": 110997.58958984374, + "seconds": 1.7510138459620066 + }, + "13": { + "test_mse": 111013.55496992187, + "seconds": 1.7581198990228586 + }, + "14": { + "test_mse": 110937.6255640625, + "seconds": 1.7488849479705095 + }, + "15": { + "test_mse": 111049.75323085938, + "seconds": 1.7618076810031198 + }, + "16": { + "test_mse": 110968.15685390624, + "seconds": 1.759674106957391 + }, + "17": { + "test_mse": 110999.21369023438, + "seconds": 1.7615744349895976 + }, + "18": { + "test_mse": 111003.5572078125, + "seconds": 1.761569199967198 + }, + "19": { + "test_mse": 111015.31385859376, + "seconds": 1.7618119880207814 + } + }, + "3": { + "10": { + "test_mse": 110435.33861796875, + "seconds": 2.6134047330124304 + }, + "11": { + "test_mse": 110417.28268046875, + "seconds": 2.610630729002878 + }, + "12": { + "test_mse": 110432.96344814452, + "seconds": 2.6115819399710745 + }, + "13": { + "test_mse": 110483.716953125, + "seconds": 2.6133818479720503 + }, + "14": { + "test_mse": 110422.93294658203, + "seconds": 2.610384237021208 + }, + "15": { + "test_mse": 110485.20151132812, + "seconds": 2.637185851985123 + }, + "16": { + "test_mse": 110420.94422539063, + "seconds": 2.6308056300040334 + }, + "17": { + "test_mse": 110451.28116054687, + "seconds": 2.630686325021088 + }, + "18": { + "test_mse": 110441.43859257812, + "seconds": 2.6311097409925424 + }, + "19": { + "test_mse": 110483.72978476563, + "seconds": 2.629570060002152 + } + }, + "5": { + "10": { + "test_mse": 109996.99276289063, + "seconds": 4.351906376017723 + }, + "11": { + "test_mse": 110001.61465009766, + "seconds": 4.353852368018124 + }, + "12": { + "test_mse": 109987.47049746093, + "seconds": 4.351936242019292 + }, + "13": { + "test_mse": 110023.59828085937, + "seconds": 4.343197321984917 + }, + "14": { + "test_mse": 109982.57383759765, + "seconds": 4.339489521982614 + }, + "15": { + "test_mse": 110022.33891679687, + "seconds": 4.370865307981148 + }, + "16": { + "test_mse": 109973.91517851563, + "seconds": 4.37695846601855 + }, + "17": { + "test_mse": 110025.11156523437, + "seconds": 4.37342468299903 + }, + "18": { + "test_mse": 109977.99975039062, + "seconds": 4.373566509981174 + }, + "19": { + "test_mse": 110038.19817773438, + "seconds": 4.3728189779794775 + } + }, + "8": { + "10": { + "test_mse": 109761.76982929687, + "seconds": 6.95300771802431 + }, + "11": { + "test_mse": 109770.09875664063, + "seconds": 6.95994263398461 + }, + "12": { + "test_mse": 109727.42580058594, + "seconds": 6.951088049041573 + }, + "13": { + "test_mse": 109778.04860117187, + "seconds": 7.037627830985002 + }, + "14": { + "test_mse": 109749.88620800781, + "seconds": 6.950180398009252 + }, + "15": { + "test_mse": 109755.35110273438, + "seconds": 6.990693069004919 + }, + "16": { + "test_mse": 109737.8124703125, + "seconds": 6.987860528985038 + }, + "17": { + "test_mse": 109788.39266445313, + "seconds": 6.991775147966109 + }, + "18": { + "test_mse": 109746.49503164063, + "seconds": 6.988245036976878 + }, + "19": { + "test_mse": 109782.47985976562, + "seconds": 6.993523691024166 + } + }, + "12": { + "10": { + "test_mse": 109644.33880800781, + "seconds": 10.45745559700299 + }, + "11": { + "test_mse": 109657.81722617187, + "seconds": 10.403271410032175 + }, + "12": { + "test_mse": 109590.32019824219, + "seconds": 10.435809459013399 + }, + "13": { + "test_mse": 109637.54189414062, + "seconds": 10.431324893026613 + }, + "14": { + "test_mse": 109629.36383730469, + "seconds": 10.43899859697558 + }, + "15": { + "test_mse": 109610.8221078125, + "seconds": 10.474087148031686 + }, + "16": { + "test_mse": 109603.3541703125, + "seconds": 10.479133562999777 + }, + "17": { + "test_mse": 109645.85444541015, + "seconds": 10.479580771992914 + }, + "18": { + "test_mse": 109637.17158398438, + "seconds": 10.475215498008765 + }, + "19": { + "test_mse": 109646.7228711914, + "seconds": 10.475019216013607 + } + }, + "17": { + "10": { + "test_mse": 109577.55731933593, + "seconds": 14.765825630980544 + }, + "11": { + "test_mse": 109580.62386289063, + "seconds": 14.766812210029457 + }, + "12": { + "test_mse": 109524.88184785156, + "seconds": 14.729242462955881 + }, + "13": { + "test_mse": 109551.49489375, + "seconds": 14.773005197988823 + }, + "14": { + "test_mse": 109567.01141972656, + "seconds": 14.757318192976527 + }, + "15": { + "test_mse": 109538.25421445312, + "seconds": 14.870652365032583 + }, + "16": { + "test_mse": 109548.76097851562, + "seconds": 14.835961105010938 + }, + "17": { + "test_mse": 109576.52400166016, + "seconds": 14.856400726013817 + }, + "18": { + "test_mse": 109572.86652539062, + "seconds": 14.923120491032023 + }, + "19": { + "test_mse": 109571.98369072266, + "seconds": 14.85673073597718 + } + }, + "25": { + "10": { + "test_mse": 109534.63756191406, + "seconds": 21.76742266700603 + }, + "11": { + "test_mse": 109523.15172392578, + "seconds": 21.784127225051634 + }, + "12": { + "test_mse": 109478.39268691406, + "seconds": 21.84094322891906 + }, + "13": { + "test_mse": 109505.3901296875, + "seconds": 21.776910719112493 + }, + "14": { + "test_mse": 109526.53978925782, + "seconds": 21.800771398935467 + }, + "15": { + "test_mse": 109510.41311367188, + "seconds": 21.828368448012043 + }, + "16": { + "test_mse": 109504.918525, + "seconds": 21.792950792005286 + }, + "17": { + "test_mse": 109537.62386220704, + "seconds": 21.785762496991083 + }, + "18": { + "test_mse": 109528.76618632812, + "seconds": 21.78301236103289 + }, + "19": { + "test_mse": 109532.9995758789, + "seconds": 21.77431908797007 + } + }, + "40": { + "10": { + "test_mse": 109500.87496894531, + "seconds": 34.727117330010515 + }, + "11": { + "test_mse": 109500.53323095704, + "seconds": 34.75680090097012 + }, + "12": { + "test_mse": 109453.34040410156, + "seconds": 34.717730374017265 + }, + "13": { + "test_mse": 109477.85198632813, + "seconds": 34.70766986999661 + }, + "14": { + "test_mse": 109507.14114121094, + "seconds": 34.72964735404821 + }, + "15": { + "test_mse": 109488.86945742187, + "seconds": 34.94093260902446 + }, + "16": { + "test_mse": 109477.94310546874, + "seconds": 34.95076176401926 + }, + "17": { + "test_mse": 109509.27307783203, + "seconds": 34.97223184700124 + }, + "18": { + "test_mse": 109503.4739890625, + "seconds": 34.90761968400329 + }, + "19": { + "test_mse": 109509.08005634765, + "seconds": 34.9518132910016 + } + }, + "60": { + "10": { + "test_mse": 109488.25173652344, + "seconds": 52.13514725404093 + }, + "11": { + "test_mse": 109496.66208798828, + "seconds": 52.01641469995957 + }, + "12": { + "test_mse": 109435.78193925781, + "seconds": 52.0493566240184 + }, + "13": { + "test_mse": 109467.19210390624, + "seconds": 52.05468468304025 + }, + "14": { + "test_mse": 109492.01538144531, + "seconds": 52.120833348017186 + }, + "15": { + "test_mse": 109481.26341289062, + "seconds": 52.4286145149963 + }, + "16": { + "test_mse": 109466.20038867187, + "seconds": 52.47564775997307 + }, + "17": { + "test_mse": 109500.78487509766, + "seconds": 52.401765603979584 + }, + "18": { + "test_mse": 109491.99969296875, + "seconds": 52.4373019579798 + }, + "19": { + "test_mse": 109501.76515830078, + "seconds": 52.41139507899061 + } + }, + "80": { + "10": { + "test_mse": 109486.31857480468, + "seconds": 69.4968881829991 + }, + "11": { + "test_mse": 109492.8955446289, + "seconds": 69.3167182590114 + }, + "12": { + "test_mse": 109432.1425751953, + "seconds": 69.4521753359586 + }, + "13": { + "test_mse": 109464.9663234375, + "seconds": 69.43323950300692 + }, + "14": { + "test_mse": 109488.98553574219, + "seconds": 69.47830444900319 + }, + "15": { + "test_mse": 109479.26984257813, + "seconds": 69.88557936198777 + }, + "16": { + "test_mse": 109461.82478828124, + "seconds": 69.92117116804002 + }, + "17": { + "test_mse": 109496.77152587891, + "seconds": 69.89437870000256 + }, + "18": { + "test_mse": 109491.83606328125, + "seconds": 69.88538150204113 + }, + "19": { + "test_mse": 109498.97592509765, + "seconds": 69.87894627498463 + } + }, + "100": { + "10": { + "test_mse": 109485.3569392578, + "seconds": 86.73687970696483 + }, + "11": { + "test_mse": 109492.14070283202, + "seconds": 86.79373870498966 + }, + "12": { + "test_mse": 109431.7457107422, + "seconds": 86.83598489401629 + }, + "13": { + "test_mse": 109463.88779140625, + "seconds": 86.80401744501432 + }, + "14": { + "test_mse": 109489.18488964844, + "seconds": 86.7372075309977 + }, + "15": { + "test_mse": 109478.5110546875, + "seconds": 87.37012085400056 + }, + "16": { + "test_mse": 109461.44376914062, + "seconds": 87.39782533602556 + }, + "17": { + "test_mse": 109495.54388017578, + "seconds": 87.3865255790297 + }, + "18": { + "test_mse": 109492.50643476563, + "seconds": 87.40612701798091 + }, + "19": { + "test_mse": 109497.99369033203, + "seconds": 87.35372787999222 + } + } + } + }, + "sift1b-10M-div512": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.19363175118867187, + "per_seed": { + "10": { + "test_mse": 0.19353448569804058, + "seconds": 16.00201056903461 + }, + "11": { + "test_mse": 0.193595385302828, + "seconds": 16.009654482011683 + }, + "12": { + "test_mse": 0.19370466110552115, + "seconds": 16.00938501395285 + }, + "13": { + "test_mse": 0.19336606369989956, + "seconds": 16.032744019001257 + }, + "14": { + "test_mse": 0.19308715010360517, + "seconds": 16.08109540300211 + }, + "15": { + "test_mse": 0.19379085354099168, + "seconds": 16.103011441999115 + }, + "16": { + "test_mse": 0.19350520360069476, + "seconds": 16.100705436896533 + }, + "17": { + "test_mse": 0.19380505151832172, + "seconds": 16.092027414008044 + }, + "18": { + "test_mse": 0.19366811707451576, + "seconds": 16.090518348035403 + }, + "19": { + "test_mse": 0.1937282207365163, + "seconds": 16.101038144901395 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 0.20167190137342478, + "seconds": 0.6666665619704872 + }, + "11": { + "test_mse": 0.20135772374936284, + "seconds": 0.665854736987967 + }, + "12": { + "test_mse": 0.20144930101171718, + "seconds": 0.6673494399874471 + }, + "13": { + "test_mse": 0.20096855673488842, + "seconds": 0.6677555249771103 + }, + "14": { + "test_mse": 0.20116414694083945, + "seconds": 0.6646053480217233 + }, + "15": { + "test_mse": 0.20149965384593216, + "seconds": 0.6704863200429827 + }, + "16": { + "test_mse": 0.20123299957120008, + "seconds": 0.6693297509336844 + }, + "17": { + "test_mse": 0.20103799246803006, + "seconds": 0.6681621229508892 + }, + "18": { + "test_mse": 0.20066373312757677, + "seconds": 0.6558585159946233 + }, + "19": { + "test_mse": 0.20128908790958436, + "seconds": 0.668996379012242 + } + }, + "2": { + "10": { + "test_mse": 0.1978945424033358, + "seconds": 1.2911167929996736 + }, + "11": { + "test_mse": 0.19760113822679112, + "seconds": 1.280550287978258 + }, + "12": { + "test_mse": 0.19756724646485774, + "seconds": 1.2790376149932854 + }, + "13": { + "test_mse": 0.19729321981391298, + "seconds": 1.2699480930459686 + }, + "14": { + "test_mse": 0.19722804636548746, + "seconds": 1.2825813940144144 + }, + "15": { + "test_mse": 0.1977389401686934, + "seconds": 1.2810668719466776 + }, + "16": { + "test_mse": 0.19755109826531062, + "seconds": 1.2740274360403419 + }, + "17": { + "test_mse": 0.19728405669115642, + "seconds": 1.2726721850922331 + }, + "18": { + "test_mse": 0.1969501072262386, + "seconds": 1.276845584041439 + }, + "19": { + "test_mse": 0.19747678565866467, + "seconds": 1.2784539419226348 + } + }, + "3": { + "10": { + "test_mse": 0.1964680147415297, + "seconds": 1.9367891360307112 + }, + "11": { + "test_mse": 0.19631248599888, + "seconds": 1.9440743260201998 + }, + "12": { + "test_mse": 0.19619987325501234, + "seconds": 1.9414716089959256 + }, + "13": { + "test_mse": 0.19594163051595065, + "seconds": 1.9279882409609854 + }, + "14": { + "test_mse": 0.19589511038920432, + "seconds": 1.9453303440241143 + }, + "15": { + "test_mse": 0.19648006815729482, + "seconds": 1.9696662720525637 + }, + "16": { + "test_mse": 0.19613953326222036, + "seconds": 1.936767605948262 + }, + "17": { + "test_mse": 0.19602053468309535, + "seconds": 1.9730990609386936 + }, + "18": { + "test_mse": 0.1957461060387277, + "seconds": 1.9394160500960425 + }, + "19": { + "test_mse": 0.19617586328229578, + "seconds": 1.9346708270022646 + } + }, + "5": { + "10": { + "test_mse": 0.1952656183927713, + "seconds": 3.210232215002179 + }, + "11": { + "test_mse": 0.19515857851054433, + "seconds": 3.209959965024609 + }, + "12": { + "test_mse": 0.1949880410046015, + "seconds": 3.204696064000018 + }, + "13": { + "test_mse": 0.19472808638682412, + "seconds": 3.209545416990295 + }, + "14": { + "test_mse": 0.1946429968811905, + "seconds": 3.2123321809922345 + }, + "15": { + "test_mse": 0.19528363138356727, + "seconds": 3.225310854963027 + }, + "16": { + "test_mse": 0.1949344108252466, + "seconds": 3.2124387739459053 + }, + "17": { + "test_mse": 0.19499584533430406, + "seconds": 3.224772252026014 + }, + "18": { + "test_mse": 0.1948199002811878, + "seconds": 3.2283614219632 + }, + "19": { + "test_mse": 0.1950195605103073, + "seconds": 3.2255146380048245 + } + }, + "8": { + "10": { + "test_mse": 0.19446399968406705, + "seconds": 5.128512572031468 + }, + "11": { + "test_mse": 0.19442162017514977, + "seconds": 5.127583011984825 + }, + "12": { + "test_mse": 0.19432509660443362, + "seconds": 5.137972013966646 + }, + "13": { + "test_mse": 0.19410006677129724, + "seconds": 5.130122730042785 + }, + "14": { + "test_mse": 0.19383999763384133, + "seconds": 5.126634462969378 + }, + "15": { + "test_mse": 0.19461794012386688, + "seconds": 5.15506398899015 + }, + "16": { + "test_mse": 0.19426394985397574, + "seconds": 5.141284245066345 + }, + "17": { + "test_mse": 0.19437327238784755, + "seconds": 5.156660399050452 + }, + "18": { + "test_mse": 0.19423665405852567, + "seconds": 5.156266356003471 + }, + "19": { + "test_mse": 0.1943606824595027, + "seconds": 5.157912884023972 + } + }, + "12": { + "10": { + "test_mse": 0.19395002682083504, + "seconds": 7.715599533985369 + }, + "11": { + "test_mse": 0.19397850686001092, + "seconds": 7.717049909988418 + }, + "12": { + "test_mse": 0.19392528766101547, + "seconds": 7.710277826990932 + }, + "13": { + "test_mse": 0.19378982307930231, + "seconds": 7.712769075005781 + }, + "14": { + "test_mse": 0.19340736517007334, + "seconds": 7.718612427008338 + }, + "15": { + "test_mse": 0.19414562963293408, + "seconds": 7.759046744904481 + }, + "16": { + "test_mse": 0.19384816363856075, + "seconds": 7.7597466360311955 + }, + "17": { + "test_mse": 0.19401978580425566, + "seconds": 7.756955248070881 + }, + "18": { + "test_mse": 0.19393497709369864, + "seconds": 7.758317903033458 + }, + "19": { + "test_mse": 0.1939735173676332, + "seconds": 7.759007048909552 + } + }, + "17": { + "10": { + "test_mse": 0.19377416623188193, + "seconds": 10.931788595975377 + }, + "11": { + "test_mse": 0.19368658679432704, + "seconds": 10.921791786968242 + }, + "12": { + "test_mse": 0.19376278943987757, + "seconds": 10.924723408999853 + }, + "13": { + "test_mse": 0.19355485187990742, + "seconds": 10.925847122038249 + }, + "14": { + "test_mse": 0.1932207227988988, + "seconds": 10.95088445401052 + }, + "15": { + "test_mse": 0.19396544528463747, + "seconds": 10.984192215953954 + }, + "16": { + "test_mse": 0.19363327536125222, + "seconds": 10.989084957051091 + }, + "17": { + "test_mse": 0.19384939553796507, + "seconds": 10.982171206967905 + }, + "18": { + "test_mse": 0.1937879863300207, + "seconds": 10.991027642972767 + }, + "19": { + "test_mse": 0.1938776555409072, + "seconds": 10.984086434007622 + } + }, + "25": { + "10": { + "test_mse": 0.19353448569804058, + "seconds": 16.00201056903461 + }, + "11": { + "test_mse": 0.193595385302828, + "seconds": 16.009654482011683 + }, + "12": { + "test_mse": 0.19370466110552115, + "seconds": 16.00938501395285 + }, + "13": { + "test_mse": 0.19336606369989956, + "seconds": 16.032744019001257 + }, + "14": { + "test_mse": 0.19308715010360517, + "seconds": 16.08109540300211 + }, + "15": { + "test_mse": 0.19379085354099168, + "seconds": 16.103011441999115 + }, + "16": { + "test_mse": 0.19350520360069476, + "seconds": 16.100705436896533 + }, + "17": { + "test_mse": 0.19380505151832172, + "seconds": 16.092027414008044 + }, + "18": { + "test_mse": 0.19366811707451576, + "seconds": 16.090518348035403 + }, + "19": { + "test_mse": 0.1937282207365163, + "seconds": 16.101038144901395 + } + }, + "40": { + "10": { + "test_mse": 0.1934395492757825, + "seconds": 25.770620863011573 + }, + "11": { + "test_mse": 0.19353877571896688, + "seconds": 25.67056545196101 + }, + "12": { + "test_mse": 0.19357219698691946, + "seconds": 25.647213766991626 + }, + "13": { + "test_mse": 0.19315234950793755, + "seconds": 25.768359737005085 + }, + "14": { + "test_mse": 0.19297832078200228, + "seconds": 25.765999928000383 + }, + "15": { + "test_mse": 0.19372117294833602, + "seconds": 25.77005816309247 + }, + "16": { + "test_mse": 0.19333476320521703, + "seconds": 25.798948146984912 + }, + "17": { + "test_mse": 0.19364528115724478, + "seconds": 25.78480474301614 + }, + "18": { + "test_mse": 0.19352437625216298, + "seconds": 25.795339812058955 + }, + "19": { + "test_mse": 0.19366725889387326, + "seconds": 25.766670636017807 + } + }, + "60": { + "10": { + "test_mse": 0.19334122370983495, + "seconds": 38.632354588015005 + }, + "11": { + "test_mse": 0.19349052609294007, + "seconds": 38.63020523899468 + }, + "12": { + "test_mse": 0.1935804010107911, + "seconds": 38.43641631101491 + }, + "13": { + "test_mse": 0.19310037641506098, + "seconds": 38.626822220976464 + }, + "14": { + "test_mse": 0.19298308433498493, + "seconds": 38.53852134698536 + }, + "15": { + "test_mse": 0.1936512094889084, + "seconds": 38.65763181191869 + }, + "16": { + "test_mse": 0.19325557830252135, + "seconds": 38.66600435099099 + }, + "17": { + "test_mse": 0.1935358706256709, + "seconds": 38.650710180052556 + }, + "18": { + "test_mse": 0.19348814674693826, + "seconds": 38.6708239170257 + }, + "19": { + "test_mse": 0.19363403322338976, + "seconds": 38.65109736099839 + } + }, + "80": { + "10": { + "test_mse": 0.19331961544059692, + "seconds": 51.488172154000495 + }, + "11": { + "test_mse": 0.19347058881331872, + "seconds": 51.51762602798408 + }, + "12": { + "test_mse": 0.19356936090947097, + "seconds": 51.23308390798047 + }, + "13": { + "test_mse": 0.1930844866175448, + "seconds": 51.23728101403685 + }, + "14": { + "test_mse": 0.19299000330011873, + "seconds": 51.48574777803151 + }, + "15": { + "test_mse": 0.1936574710214663, + "seconds": 51.511449510930106 + }, + "16": { + "test_mse": 0.19324305745354176, + "seconds": 51.553186081931926 + }, + "17": { + "test_mse": 0.19347850877870357, + "seconds": 51.532906217034906 + }, + "18": { + "test_mse": 0.19345205436074112, + "seconds": 51.541060199961066 + }, + "19": { + "test_mse": 0.1936029690405353, + "seconds": 51.50853909202851 + } + }, + "100": { + "10": { + "test_mse": 0.19330090212827888, + "seconds": 64.31890472501982 + }, + "11": { + "test_mse": 0.19347345266773963, + "seconds": 64.35539573401911 + }, + "12": { + "test_mse": 0.1935751393024378, + "seconds": 64.04692582995631 + }, + "13": { + "test_mse": 0.19305796598818462, + "seconds": 64.04634604003513 + }, + "14": { + "test_mse": 0.19300998019402835, + "seconds": 64.34019417804666 + }, + "15": { + "test_mse": 0.19366084768530553, + "seconds": 64.38317269308027 + }, + "16": { + "test_mse": 0.19324225549996263, + "seconds": 64.40452891099267 + }, + "17": { + "test_mse": 0.19344170040171546, + "seconds": 64.39264033199288 + }, + "18": { + "test_mse": 0.19345990347970682, + "seconds": 64.40016022196505 + }, + "19": { + "test_mse": 0.19359419960876467, + "seconds": 64.41275337396655 + } + } + } + }, + "deep1b-100M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.3050453965514258, + "per_seed": { + "10": { + "test_mse": 0.30528084310726356, + "seconds": 426.07208114594687 + }, + "11": { + "test_mse": 0.30468672122955015, + "seconds": 421.4674853950273 + }, + "12": { + "test_mse": 0.3052773698880303, + "seconds": 423.0855056120781 + }, + "13": { + "test_mse": 0.3047988915155164, + "seconds": 430.52769569004886 + }, + "14": { + "test_mse": 0.3048814662487586, + "seconds": 426.4019639249891 + }, + "15": { + "test_mse": 0.30493703865551536, + "seconds": 422.0754697889788 + }, + "16": { + "test_mse": 0.30515375444733633, + "seconds": 420.5065470620757 + }, + "17": { + "test_mse": 0.30474902257619013, + "seconds": 429.45558752305806 + }, + "18": { + "test_mse": 0.3052334514227464, + "seconds": 426.4517082950333 + }, + "19": { + "test_mse": 0.305597167981323, + "seconds": 422.1122991539305 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 0.32284267080682555, + "seconds": 17.221488405019045 + }, + "11": { + "test_mse": 0.3220038633116448, + "seconds": 17.139356813044287 + }, + "12": { + "test_mse": 0.32302700966550796, + "seconds": 17.3628897969611 + }, + "13": { + "test_mse": 0.3222165155484789, + "seconds": 17.172393767046742 + }, + "14": { + "test_mse": 0.322025512654151, + "seconds": 17.070633566007018 + }, + "15": { + "test_mse": 0.322627614886578, + "seconds": 16.998987372033298 + }, + "16": { + "test_mse": 0.32325767708843123, + "seconds": 17.21153611293994 + }, + "17": { + "test_mse": 0.3226564512550284, + "seconds": 17.157322854036465 + }, + "18": { + "test_mse": 0.32295194431023566, + "seconds": 17.06209169200156 + }, + "19": { + "test_mse": 0.32233402153593377, + "seconds": 17.073410302982666 + } + }, + "2": { + "10": { + "test_mse": 0.3144202728074982, + "seconds": 34.433246375003364 + }, + "11": { + "test_mse": 0.3137096663126291, + "seconds": 34.277906667091884 + }, + "12": { + "test_mse": 0.31457486836133014, + "seconds": 34.53720375709236 + }, + "13": { + "test_mse": 0.31400500277099586, + "seconds": 34.368072521989234 + }, + "14": { + "test_mse": 0.3139166631679145, + "seconds": 33.945569331990555 + }, + "15": { + "test_mse": 0.3145977196815166, + "seconds": 33.82663276907988 + }, + "16": { + "test_mse": 0.31486448394578925, + "seconds": 34.303137552924454 + }, + "17": { + "test_mse": 0.3144331737153592, + "seconds": 34.30174478201661 + }, + "18": { + "test_mse": 0.3147438461048245, + "seconds": 34.097716065938585 + }, + "19": { + "test_mse": 0.31430357730660874, + "seconds": 34.07597215601709 + } + }, + "3": { + "10": { + "test_mse": 0.3112089397479208, + "seconds": 51.55186245596269 + }, + "11": { + "test_mse": 0.3106302704108517, + "seconds": 51.376918007968925 + }, + "12": { + "test_mse": 0.3114379948884327, + "seconds": 51.66260720405262 + }, + "13": { + "test_mse": 0.3108079046467241, + "seconds": 51.42346727498807 + }, + "14": { + "test_mse": 0.3108555958751715, + "seconds": 50.781998592894524 + }, + "15": { + "test_mse": 0.3114481303259264, + "seconds": 50.620560845010914 + }, + "16": { + "test_mse": 0.31172313350220343, + "seconds": 51.30325022293255 + }, + "17": { + "test_mse": 0.3112011894614584, + "seconds": 51.242288655019365 + }, + "18": { + "test_mse": 0.3116485081118165, + "seconds": 51.06810270703863 + }, + "19": { + "test_mse": 0.31112852121421636, + "seconds": 50.96886715409346 + } + }, + "5": { + "10": { + "test_mse": 0.3086617425311446, + "seconds": 85.3217397860135 + }, + "11": { + "test_mse": 0.3080500507761789, + "seconds": 85.63563060795423 + }, + "12": { + "test_mse": 0.30875360369839894, + "seconds": 86.10458003799431 + }, + "13": { + "test_mse": 0.30820179826791727, + "seconds": 85.46290098095778 + }, + "14": { + "test_mse": 0.308199235801159, + "seconds": 84.70036290795542 + }, + "15": { + "test_mse": 0.3085952384627905, + "seconds": 84.24834506202023 + }, + "16": { + "test_mse": 0.3089660584904596, + "seconds": 85.3854368510656 + }, + "17": { + "test_mse": 0.30849916201494826, + "seconds": 84.98392210295424 + }, + "18": { + "test_mse": 0.3089291186945428, + "seconds": 84.76850048499182 + }, + "19": { + "test_mse": 0.30843476829305166, + "seconds": 84.87761602003593 + } + }, + "8": { + "10": { + "test_mse": 0.30721172159275667, + "seconds": 136.5333571350202 + }, + "11": { + "test_mse": 0.30642723607003497, + "seconds": 137.0526473709615 + }, + "12": { + "test_mse": 0.30721693609170597, + "seconds": 138.13813428406138 + }, + "13": { + "test_mse": 0.3065260296645303, + "seconds": 136.625447027036 + }, + "14": { + "test_mse": 0.3066035669214977, + "seconds": 135.33728329406586 + }, + "15": { + "test_mse": 0.3069130611939295, + "seconds": 134.42806207505055 + }, + "16": { + "test_mse": 0.30732769970399465, + "seconds": 136.8328097179765 + }, + "17": { + "test_mse": 0.3068420684827568, + "seconds": 136.114696623059 + }, + "18": { + "test_mse": 0.30730693952336485, + "seconds": 135.63723923906218 + }, + "19": { + "test_mse": 0.3067782213025881, + "seconds": 135.32308973604813 + } + }, + "12": { + "10": { + "test_mse": 0.30643405825648423, + "seconds": 204.24975315399934 + }, + "11": { + "test_mse": 0.30561511921965195, + "seconds": 205.50360436795745 + }, + "12": { + "test_mse": 0.30624457457114385, + "seconds": 206.87902722402941 + }, + "13": { + "test_mse": 0.3055482921725933, + "seconds": 204.77225952001754 + }, + "14": { + "test_mse": 0.30594067367793987, + "seconds": 203.04485306504648 + }, + "15": { + "test_mse": 0.30601895486045977, + "seconds": 201.92913695797324 + }, + "16": { + "test_mse": 0.30617887253951465, + "seconds": 205.2555595159065 + }, + "17": { + "test_mse": 0.3058557070842684, + "seconds": 204.00608159496915 + }, + "18": { + "test_mse": 0.3063155008417212, + "seconds": 203.90269370598253 + }, + "19": { + "test_mse": 0.30622001356267736, + "seconds": 202.98451367090456 + } + }, + "17": { + "10": { + "test_mse": 0.30590104407812807, + "seconds": 288.2038208800368 + }, + "11": { + "test_mse": 0.30509770915881806, + "seconds": 291.13045548892114 + }, + "12": { + "test_mse": 0.30570619126039766, + "seconds": 292.2071459350409 + }, + "13": { + "test_mse": 0.3050583101271833, + "seconds": 289.9319531529909 + }, + "14": { + "test_mse": 0.30537611527414643, + "seconds": 287.4153153959196 + }, + "15": { + "test_mse": 0.30538394287380627, + "seconds": 285.47769204503857 + }, + "16": { + "test_mse": 0.30546270437166234, + "seconds": 290.1108050979674 + }, + "17": { + "test_mse": 0.30533934811297114, + "seconds": 289.39269088592846 + }, + "18": { + "test_mse": 0.3058220932060045, + "seconds": 288.2979556990322 + }, + "19": { + "test_mse": 0.3059245491882476, + "seconds": 287.4109216199722 + } + }, + "25": { + "10": { + "test_mse": 0.30528084310726356, + "seconds": 426.07208114594687 + }, + "11": { + "test_mse": 0.30468672122955015, + "seconds": 421.4674853950273 + }, + "12": { + "test_mse": 0.3052773698880303, + "seconds": 423.0855056120781 + }, + "13": { + "test_mse": 0.3047988915155164, + "seconds": 430.52769569004886 + }, + "14": { + "test_mse": 0.3048814662487586, + "seconds": 426.4019639249891 + }, + "15": { + "test_mse": 0.30493703865551536, + "seconds": 422.0754697889788 + }, + "16": { + "test_mse": 0.30515375444733633, + "seconds": 420.5065470620757 + }, + "17": { + "test_mse": 0.30474902257619013, + "seconds": 429.45558752305806 + }, + "18": { + "test_mse": 0.3052334514227464, + "seconds": 426.4517082950333 + }, + "19": { + "test_mse": 0.305597167981323, + "seconds": 422.1122991539305 + } + }, + "40": { + "10": { + "test_mse": 0.3050185450496431, + "seconds": 673.8742048291024 + }, + "11": { + "test_mse": 0.30441775441020175, + "seconds": 685.0599425929831 + }, + "12": { + "test_mse": 0.30497713129452175, + "seconds": 684.9467377041001 + }, + "13": { + "test_mse": 0.30452974197040783, + "seconds": 679.105334872962 + }, + "14": { + "test_mse": 0.304410431213609, + "seconds": 686.3299190759426 + }, + "15": { + "test_mse": 0.304456776719115, + "seconds": 685.1319200780708 + }, + "16": { + "test_mse": 0.3049412056688823, + "seconds": 681.9080791099695 + }, + "17": { + "test_mse": 0.3045386337741842, + "seconds": 690.9649963650154 + }, + "18": { + "test_mse": 0.30498426444011045, + "seconds": 691.7466515159467 + }, + "19": { + "test_mse": 0.3052550493840681, + "seconds": 684.1135274739936 + } + }, + "60": { + "10": { + "test_mse": 0.3048539279589315, + "seconds": 1009.5391646180069 + }, + "11": { + "test_mse": 0.3043146841630242, + "seconds": 1028.5173888480058 + }, + "12": { + "test_mse": 0.3047312450238373, + "seconds": 1026.2891125779133 + }, + "13": { + "test_mse": 0.30442784645716875, + "seconds": 1016.0826655059354 + }, + "14": { + "test_mse": 0.3043405795727735, + "seconds": 1027.014101035078 + }, + "15": { + "test_mse": 0.30434495666174016, + "seconds": 1025.4105524530169 + }, + "16": { + "test_mse": 0.30480355172300605, + "seconds": 1020.8941236890387 + }, + "17": { + "test_mse": 0.3042103681179694, + "seconds": 1030.1815293580294 + }, + "18": { + "test_mse": 0.304932935386399, + "seconds": 1037.1129652869422 + }, + "19": { + "test_mse": 0.3047646350577917, + "seconds": 1022.2293786309892 + } + }, + "80": { + "10": { + "test_mse": 0.30461968830426744, + "seconds": 1357.2125520170666 + }, + "11": { + "test_mse": 0.3043060580353046, + "seconds": 1342.4185133950086 + }, + "12": { + "test_mse": 0.3046011309388967, + "seconds": 1354.2483367220266 + }, + "13": { + "test_mse": 0.3044616661678822, + "seconds": 1364.5995655270526 + }, + "14": { + "test_mse": 0.30421775917105803, + "seconds": 1354.614204409998 + }, + "15": { + "test_mse": 0.30430632506354216, + "seconds": 1349.6569307750324 + }, + "16": { + "test_mse": 0.304489429577865, + "seconds": 1349.495203229948 + }, + "17": { + "test_mse": 0.3043340475799387, + "seconds": 1353.0362622909015 + }, + "18": { + "test_mse": 0.30472491992453077, + "seconds": 1351.2380533730611 + }, + "19": { + "test_mse": 0.3046503186647096, + "seconds": 1366.4088970599696 + } + }, + "100": { + "10": { + "test_mse": 0.30456193307895335, + "seconds": 1695.6327411050443 + }, + "11": { + "test_mse": 0.3043693642367345, + "seconds": 1692.3509753430262 + }, + "12": { + "test_mse": 0.3044948668335316, + "seconds": 1683.7526012369199 + }, + "13": { + "test_mse": 0.304536013149298, + "seconds": 1721.4296310910722 + }, + "14": { + "test_mse": 0.30418903084736704, + "seconds": 1688.4626972459955 + }, + "15": { + "test_mse": 0.30431018465855814, + "seconds": 1691.3313170210458 + }, + "16": { + "test_mse": 0.304442561049327, + "seconds": 1693.7777738260338 + }, + "17": { + "test_mse": 0.30434407588651263, + "seconds": 1705.960295341094 + }, + "18": { + "test_mse": 0.3047431005873201, + "seconds": 1711.7678854529513 + }, + "19": { + "test_mse": 0.30445974386358776, + "seconds": 1722.6164715179475 + } + } + } + }, + "spacev-100M": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 4146.505375955967, + "per_seed": { + "10": { + "test_mse": 4144.92761725816, + "seconds": 462.7176042330684 + }, + "11": { + "test_mse": 4144.519724253782, + "seconds": 459.1536513910396 + }, + "12": { + "test_mse": 4146.151165590582, + "seconds": 466.315742068924 + }, + "13": { + "test_mse": 4146.85958632135, + "seconds": 457.5796683100052 + }, + "14": { + "test_mse": 4153.135390527034, + "seconds": 456.93971357203554 + }, + "15": { + "test_mse": 4144.3053186497655, + "seconds": 462.3473034220515 + }, + "16": { + "test_mse": 4143.452488819318, + "seconds": 463.38001738500316 + }, + "17": { + "test_mse": 4149.331915353175, + "seconds": 460.5306828659959 + }, + "18": { + "test_mse": 4148.729763960434, + "seconds": 458.4442690249998 + }, + "19": { + "test_mse": 4158.269308565905, + "seconds": 459.79508772306144 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 5487.287523102024, + "seconds": 17.558798081008717 + }, + "11": { + "test_mse": 5510.280332148037, + "seconds": 17.557970432913862 + }, + "12": { + "test_mse": 5498.376011558293, + "seconds": 17.561070000985637 + }, + "13": { + "test_mse": 5509.18964452695, + "seconds": 17.55950778501574 + }, + "14": { + "test_mse": 5509.704760343279, + "seconds": 17.559105998952873 + }, + "15": { + "test_mse": 5506.2921395866815, + "seconds": 17.5584929989418 + }, + "16": { + "test_mse": 5493.158489964073, + "seconds": 17.557154996902682 + }, + "17": { + "test_mse": 5486.76196057247, + "seconds": 17.56163289898541 + }, + "18": { + "test_mse": 5505.800411830462, + "seconds": 17.55533603404183 + }, + "19": { + "test_mse": 5500.827473792157, + "seconds": 17.515845667920075 + } + }, + "2": { + "10": { + "test_mse": 5000.314889092035, + "seconds": 35.99305234197527 + }, + "11": { + "test_mse": 5015.173606820171, + "seconds": 36.054272327106446 + }, + "12": { + "test_mse": 5012.118235583496, + "seconds": 36.26036331197247 + }, + "13": { + "test_mse": 5031.673419505081, + "seconds": 36.30829669605009 + }, + "14": { + "test_mse": 5013.210261307453, + "seconds": 36.125889318063855 + }, + "15": { + "test_mse": 5021.396880574008, + "seconds": 35.77746357396245 + }, + "16": { + "test_mse": 5004.092339249484, + "seconds": 35.94585652195383 + }, + "17": { + "test_mse": 5004.448072839625, + "seconds": 36.132699367939495 + }, + "18": { + "test_mse": 5021.512211200261, + "seconds": 36.06222066399641 + }, + "19": { + "test_mse": 5020.390944891758, + "seconds": 35.9429029020248 + } + }, + "3": { + "10": { + "test_mse": 4759.511304256815, + "seconds": 54.172219411004335 + }, + "11": { + "test_mse": 4765.415330717751, + "seconds": 54.49343410204165 + }, + "12": { + "test_mse": 4774.327375597191, + "seconds": 54.801222798996605 + }, + "13": { + "test_mse": 4787.209697273413, + "seconds": 54.948303741985 + }, + "14": { + "test_mse": 4764.467388400191, + "seconds": 54.606253650039434 + }, + "15": { + "test_mse": 4780.290531582625, + "seconds": 54.103642089059576 + }, + "16": { + "test_mse": 4759.87845053319, + "seconds": 54.23765430401545 + }, + "17": { + "test_mse": 4764.291397885782, + "seconds": 54.63501121709123 + }, + "18": { + "test_mse": 4774.6024789314315, + "seconds": 54.41250688000582 + }, + "19": { + "test_mse": 4777.999391012236, + "seconds": 54.62017350108363 + } + }, + "5": { + "10": { + "test_mse": 4509.913298113267, + "seconds": 90.61229681794066 + }, + "11": { + "test_mse": 4508.7731940881295, + "seconds": 91.29722688999027 + }, + "12": { + "test_mse": 4527.463261424096, + "seconds": 91.80282570701092 + }, + "13": { + "test_mse": 4533.250194636065, + "seconds": 92.21559859102126 + }, + "14": { + "test_mse": 4517.8520933253285, + "seconds": 91.41917002096307 + }, + "15": { + "test_mse": 4522.068147505594, + "seconds": 90.53314453805797 + }, + "16": { + "test_mse": 4510.528827767202, + "seconds": 90.9086039919639 + }, + "17": { + "test_mse": 4519.568799857501, + "seconds": 91.56236813403666 + }, + "18": { + "test_mse": 4521.25214576437, + "seconds": 91.21910959191155 + }, + "19": { + "test_mse": 4526.235011590706, + "seconds": 91.21933630399872 + } + }, + "8": { + "10": { + "test_mse": 4347.65775779535, + "seconds": 145.56604562699795 + }, + "11": { + "test_mse": 4342.47227501275, + "seconds": 146.1746917840792 + }, + "12": { + "test_mse": 4353.824090126655, + "seconds": 147.39764994103462 + }, + "13": { + "test_mse": 4362.212246857888, + "seconds": 148.0534975520568 + }, + "14": { + "test_mse": 4352.856345811845, + "seconds": 146.571654904983 + }, + "15": { + "test_mse": 4349.90822722984, + "seconds": 145.205093849916 + }, + "16": { + "test_mse": 4346.190452318531, + "seconds": 145.92557862901594 + }, + "17": { + "test_mse": 4351.021681217247, + "seconds": 147.06193084595725 + }, + "18": { + "test_mse": 4348.650214333125, + "seconds": 147.00866256200243 + }, + "19": { + "test_mse": 4361.3601748472665, + "seconds": 145.8992515919963 + } + }, + "12": { + "10": { + "test_mse": 4249.008756658968, + "seconds": 218.74324177391827 + }, + "11": { + "test_mse": 4241.720648351669, + "seconds": 219.23409022309352 + }, + "12": { + "test_mse": 4249.61794927178, + "seconds": 221.4118935399456 + }, + "13": { + "test_mse": 4254.371876078022, + "seconds": 222.85503264598083 + }, + "14": { + "test_mse": 4253.801645848685, + "seconds": 220.30953338299878 + }, + "15": { + "test_mse": 4250.424462648418, + "seconds": 218.0975842489861 + }, + "16": { + "test_mse": 4247.811892957023, + "seconds": 219.49350788805168 + }, + "17": { + "test_mse": 4250.7770143484595, + "seconds": 220.98350179195404 + }, + "18": { + "test_mse": 4249.7474687078375, + "seconds": 220.07024838705547 + }, + "19": { + "test_mse": 4261.536243004965, + "seconds": 219.30819035496097 + } + }, + "17": { + "10": { + "test_mse": 4187.002851113075, + "seconds": 310.0356100080535 + }, + "11": { + "test_mse": 4186.190179288984, + "seconds": 311.66458227299154 + }, + "12": { + "test_mse": 4191.29925591712, + "seconds": 314.20704847504385 + }, + "13": { + "test_mse": 4191.914805272185, + "seconds": 316.2452486989787 + }, + "14": { + "test_mse": 4195.299062003035, + "seconds": 312.52215543692 + }, + "15": { + "test_mse": 4188.523848925853, + "seconds": 309.2833673640853 + }, + "16": { + "test_mse": 4188.8835908654955, + "seconds": 311.54191619099583 + }, + "17": { + "test_mse": 4190.711760649423, + "seconds": 313.4946224410087 + }, + "18": { + "test_mse": 4192.289050517909, + "seconds": 312.4006591369398 + }, + "19": { + "test_mse": 4201.953380456157, + "seconds": 312.37547216401435 + } + }, + "25": { + "10": { + "test_mse": 4144.92761725816, + "seconds": 462.7176042330684 + }, + "11": { + "test_mse": 4144.519724253782, + "seconds": 459.1536513910396 + }, + "12": { + "test_mse": 4146.151165590582, + "seconds": 466.315742068924 + }, + "13": { + "test_mse": 4146.85958632135, + "seconds": 457.5796683100052 + }, + "14": { + "test_mse": 4153.135390527034, + "seconds": 456.93971357203554 + }, + "15": { + "test_mse": 4144.3053186497655, + "seconds": 462.3473034220515 + }, + "16": { + "test_mse": 4143.452488819318, + "seconds": 463.38001738500316 + }, + "17": { + "test_mse": 4149.331915353175, + "seconds": 460.5306828659959 + }, + "18": { + "test_mse": 4148.729763960434, + "seconds": 458.4442690249998 + }, + "19": { + "test_mse": 4158.269308565905, + "seconds": 459.79508772306144 + } + }, + "40": { + "10": { + "test_mse": 4115.042388126815, + "seconds": 741.5500914450968 + }, + "11": { + "test_mse": 4115.845047781796, + "seconds": 740.9098961909767 + }, + "12": { + "test_mse": 4117.153313768603, + "seconds": 744.0403645740589 + }, + "13": { + "test_mse": 4115.5213762883495, + "seconds": 737.4028665809892 + }, + "14": { + "test_mse": 4121.017933123667, + "seconds": 750.2060669169878 + }, + "15": { + "test_mse": 4113.808283680597, + "seconds": 730.0093185229925 + }, + "16": { + "test_mse": 4112.7710353567245, + "seconds": 728.5337553890422 + }, + "17": { + "test_mse": 4118.358353563593, + "seconds": 727.787404614035 + }, + "18": { + "test_mse": 4120.011498770178, + "seconds": 739.297978854971 + }, + "19": { + "test_mse": 4129.608016515938, + "seconds": 728.1616093589691 + } + }, + "60": { + "10": { + "test_mse": 4100.463731028578, + "seconds": 1111.6520293370122 + }, + "11": { + "test_mse": 4101.542666785547, + "seconds": 1110.2023335730191 + }, + "12": { + "test_mse": 4104.120486050497, + "seconds": 1113.3475746699842 + }, + "13": { + "test_mse": 4099.764642649185, + "seconds": 1104.456484246999 + }, + "14": { + "test_mse": 4105.681010682099, + "seconds": 1121.166766267037 + }, + "15": { + "test_mse": 4101.726156022827, + "seconds": 1094.3213459280087 + }, + "16": { + "test_mse": 4098.852929375101, + "seconds": 1093.903213166981 + }, + "17": { + "test_mse": 4101.791155262493, + "seconds": 1091.5198450210737 + }, + "18": { + "test_mse": 4105.773959274482, + "seconds": 1108.5442824499914 + }, + "19": { + "test_mse": 4114.144454107367, + "seconds": 1091.8190516510513 + } + }, + "80": { + "10": { + "test_mse": 4094.533131006462, + "seconds": 1468.539361329982 + }, + "11": { + "test_mse": 4094.9119720137305, + "seconds": 1469.8686436769785 + }, + "12": { + "test_mse": 4100.743951664152, + "seconds": 1472.638672993984 + }, + "13": { + "test_mse": 4093.9994540614116, + "seconds": 1454.3624952869723 + }, + "14": { + "test_mse": 4098.056268888435, + "seconds": 1467.758182974998 + }, + "15": { + "test_mse": 4095.107248422993, + "seconds": 1471.962771950988 + }, + "16": { + "test_mse": 4092.8327215690583, + "seconds": 1464.8692693370394 + }, + "17": { + "test_mse": 4097.028572157154, + "seconds": 1464.8737677860772 + }, + "18": { + "test_mse": 4100.6444216701175, + "seconds": 1498.2620094609447 + }, + "19": { + "test_mse": 4107.741340987976, + "seconds": 1472.7523656729609 + } + }, + "100": { + "10": { + "test_mse": 4091.4131462353735, + "seconds": 1850.1916840069462 + }, + "11": { + "test_mse": 4091.961005549479, + "seconds": 1819.8538262939546 + }, + "12": { + "test_mse": 4097.690318411415, + "seconds": 1830.190263016033 + }, + "13": { + "test_mse": 4090.506735854051, + "seconds": 1821.7178334499476 + }, + "14": { + "test_mse": 4095.7355189089385, + "seconds": 1852.9044614830054 + }, + "15": { + "test_mse": 4091.613618616627, + "seconds": 1855.721835297998 + }, + "16": { + "test_mse": 4090.541793451948, + "seconds": 1841.038144133985 + }, + "17": { + "test_mse": 4094.8495638584654, + "seconds": 1836.6412339450326 + }, + "18": { + "test_mse": 4098.480416543146, + "seconds": 1868.0469214110635 + }, + "19": { + "test_mse": 4104.100993750499, + "seconds": 1831.425127047929 + } + } + } + }, + "fb-ssnpp-100M": { + "flash_api": "kmeans_largeN", + "flash_norms": "float32", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 105023.15370986328, + "per_seed": { + "10": { + "test_mse": 105067.80133798828, + "seconds": 872.7275820500217 + }, + "11": { + "test_mse": 105032.88047041015, + "seconds": 868.2380740729859 + }, + "12": { + "test_mse": 105059.79596308594, + "seconds": 864.7011476320913 + }, + "13": { + "test_mse": 105020.86475166016, + "seconds": 871.1214464789955 + }, + "14": { + "test_mse": 105035.0956540039, + "seconds": 870.4829383710166 + }, + "15": { + "test_mse": 105025.4426680664, + "seconds": 865.9788600910688 + }, + "16": { + "test_mse": 105005.4102040039, + "seconds": 866.8769044510555 + }, + "17": { + "test_mse": 104997.0900758789, + "seconds": 874.1807672110153 + }, + "18": { + "test_mse": 104960.861421875, + "seconds": 868.9203098589787 + }, + "19": { + "test_mse": 105013.5650319336, + "seconds": 866.7472124310443 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 109314.8240375, + "seconds": 34.8888034359552 + }, + "11": { + "test_mse": 109333.072890625, + "seconds": 34.697357454919256 + }, + "12": { + "test_mse": 109255.82159492187, + "seconds": 34.66873847797979 + }, + "13": { + "test_mse": 109316.63156601563, + "seconds": 34.71739488292951 + }, + "14": { + "test_mse": 109219.00140292969, + "seconds": 34.61889591196086 + }, + "15": { + "test_mse": 109329.84455751954, + "seconds": 34.64539307903033 + }, + "16": { + "test_mse": 109199.76965507813, + "seconds": 34.70568859693594 + }, + "17": { + "test_mse": 109290.950284375, + "seconds": 34.72898936399724 + }, + "18": { + "test_mse": 109149.095015625, + "seconds": 34.62764696503291 + }, + "19": { + "test_mse": 109305.47111601563, + "seconds": 34.649689791025594 + } + }, + "2": { + "10": { + "test_mse": 107606.16763203125, + "seconds": 69.77918079996016 + }, + "11": { + "test_mse": 107563.26606689453, + "seconds": 69.55091639200691 + }, + "12": { + "test_mse": 107531.2659185547, + "seconds": 69.5640895140823 + }, + "13": { + "test_mse": 107576.21106884765, + "seconds": 69.46993263799231 + }, + "14": { + "test_mse": 107498.87276972656, + "seconds": 69.33897517097648 + }, + "15": { + "test_mse": 107599.75560048828, + "seconds": 69.29499241709709 + }, + "16": { + "test_mse": 107442.99169511719, + "seconds": 69.56864579301327 + }, + "17": { + "test_mse": 107585.99958339844, + "seconds": 69.52230068601784 + }, + "18": { + "test_mse": 107436.90228544922, + "seconds": 69.29939925397048 + }, + "19": { + "test_mse": 107570.34919726562, + "seconds": 69.31002930505201 + } + }, + "3": { + "10": { + "test_mse": 106799.97685087891, + "seconds": 104.75602851004805 + }, + "11": { + "test_mse": 106750.03750947266, + "seconds": 104.3067698860541 + }, + "12": { + "test_mse": 106744.99685419921, + "seconds": 104.34804715798236 + }, + "13": { + "test_mse": 106770.2195828125, + "seconds": 104.25405488000251 + }, + "14": { + "test_mse": 106697.16585234375, + "seconds": 103.95097597199492 + }, + "15": { + "test_mse": 106780.67980449219, + "seconds": 103.9227169790538 + }, + "16": { + "test_mse": 106681.29675898438, + "seconds": 104.38355676305946 + }, + "17": { + "test_mse": 106772.89377431641, + "seconds": 104.25354307997623 + }, + "18": { + "test_mse": 106664.01714570312, + "seconds": 103.88109684595838 + }, + "19": { + "test_mse": 106773.16751103515, + "seconds": 103.94603575998917 + } + }, + "5": { + "10": { + "test_mse": 106054.48940517579, + "seconds": 174.6035621170886 + }, + "11": { + "test_mse": 105977.35818496093, + "seconds": 174.0683854809031 + }, + "12": { + "test_mse": 105980.26970703126, + "seconds": 174.21647136309184 + }, + "13": { + "test_mse": 106027.46576298829, + "seconds": 173.82427563797683 + }, + "14": { + "test_mse": 105969.27405625, + "seconds": 173.35384269803762 + }, + "15": { + "test_mse": 105988.49208701172, + "seconds": 173.19729708193336 + }, + "16": { + "test_mse": 105976.15432148437, + "seconds": 173.8741542759817 + }, + "17": { + "test_mse": 105987.35754414063, + "seconds": 173.870824291982 + }, + "18": { + "test_mse": 105922.03954873046, + "seconds": 173.21777463704348 + }, + "19": { + "test_mse": 106031.19138320313, + "seconds": 173.19978928694036 + } + }, + "8": { + "10": { + "test_mse": 105604.5008328125, + "seconds": 279.3116181601072 + }, + "11": { + "test_mse": 105525.9653078125, + "seconds": 278.63572099490557 + }, + "12": { + "test_mse": 105533.47621806641, + "seconds": 278.49343635700643 + }, + "13": { + "test_mse": 105553.18844501954, + "seconds": 278.28834918898065 + }, + "14": { + "test_mse": 105508.59736669922, + "seconds": 277.43820760399103 + }, + "15": { + "test_mse": 105502.42569248046, + "seconds": 277.3245646330761 + }, + "16": { + "test_mse": 105550.11814580078, + "seconds": 278.23711025796365 + }, + "17": { + "test_mse": 105513.72280654297, + "seconds": 278.0767176889931 + }, + "18": { + "test_mse": 105511.54807177735, + "seconds": 277.23807074700017 + }, + "19": { + "test_mse": 105549.39733945312, + "seconds": 277.20858386997133 + } + }, + "12": { + "10": { + "test_mse": 105336.58311357422, + "seconds": 419.0092430290533 + }, + "11": { + "test_mse": 105289.86549414063, + "seconds": 418.0615110589424 + }, + "12": { + "test_mse": 105315.76749453125, + "seconds": 418.3016352780396 + }, + "13": { + "test_mse": 105294.59581455078, + "seconds": 417.603501984966 + }, + "14": { + "test_mse": 105282.90377226562, + "seconds": 415.7725886530243 + }, + "15": { + "test_mse": 105260.56905996094, + "seconds": 415.7261415909743 + }, + "16": { + "test_mse": 105305.3651798828, + "seconds": 417.3652212959714 + }, + "17": { + "test_mse": 105277.8040084961, + "seconds": 417.070691358007 + }, + "18": { + "test_mse": 105247.45514570312, + "seconds": 415.929774979013 + }, + "19": { + "test_mse": 105293.8990477539, + "seconds": 416.10434229299426 + } + }, + "17": { + "10": { + "test_mse": 105195.48927314453, + "seconds": 593.491673085955 + }, + "11": { + "test_mse": 105138.55965361328, + "seconds": 592.2193251049612 + }, + "12": { + "test_mse": 105168.30297109376, + "seconds": 592.3611922629643 + }, + "13": { + "test_mse": 105138.18957548829, + "seconds": 591.3537321100011 + }, + "14": { + "test_mse": 105147.75751982421, + "seconds": 589.4739695950411 + }, + "15": { + "test_mse": 105125.34356123047, + "seconds": 589.304817018914 + }, + "16": { + "test_mse": 105133.83403955078, + "seconds": 591.2838086549891 + }, + "17": { + "test_mse": 105125.10468183593, + "seconds": 591.016797113989 + }, + "18": { + "test_mse": 105077.80049609375, + "seconds": 589.3977352410438 + }, + "19": { + "test_mse": 105139.34668564453, + "seconds": 588.9092651880346 + } + }, + "25": { + "10": { + "test_mse": 105067.80133798828, + "seconds": 872.7275820500217 + }, + "11": { + "test_mse": 105032.88047041015, + "seconds": 868.2380740729859 + }, + "12": { + "test_mse": 105059.79596308594, + "seconds": 864.7011476320913 + }, + "13": { + "test_mse": 105020.86475166016, + "seconds": 871.1214464789955 + }, + "14": { + "test_mse": 105035.0956540039, + "seconds": 870.4829383710166 + }, + "15": { + "test_mse": 105025.4426680664, + "seconds": 865.9788600910688 + }, + "16": { + "test_mse": 105005.4102040039, + "seconds": 866.8769044510555 + }, + "17": { + "test_mse": 104997.0900758789, + "seconds": 874.1807672110153 + }, + "18": { + "test_mse": 104960.861421875, + "seconds": 868.9203098589787 + }, + "19": { + "test_mse": 105013.5650319336, + "seconds": 866.7472124310443 + } + }, + "40": { + "10": { + "test_mse": 104994.02324550781, + "seconds": 1388.948227713001 + }, + "11": { + "test_mse": 104976.86809208985, + "seconds": 1393.5572095130337 + }, + "12": { + "test_mse": 104981.67794902343, + "seconds": 1393.0895162109518 + }, + "13": { + "test_mse": 104942.27123173828, + "seconds": 1394.7208126919577 + }, + "14": { + "test_mse": 104966.25715175782, + "seconds": 1387.0468230081024 + }, + "15": { + "test_mse": 104956.44444296874, + "seconds": 1393.967334919027 + }, + "16": { + "test_mse": 104920.91686396484, + "seconds": 1384.3850846779533 + }, + "17": { + "test_mse": 104926.70873134765, + "seconds": 1388.881520867988 + }, + "18": { + "test_mse": 104906.56339384765, + "seconds": 1396.1447720430442 + }, + "19": { + "test_mse": 104931.90897294921, + "seconds": 1390.255410645972 + } + }, + "60": { + "10": { + "test_mse": 104960.89713427734, + "seconds": 2083.086337875924 + }, + "11": { + "test_mse": 104935.86476630859, + "seconds": 2085.292549230042 + }, + "12": { + "test_mse": 104943.99895644531, + "seconds": 2087.262513702968 + }, + "13": { + "test_mse": 104897.3398883789, + "seconds": 2083.2421415470308 + }, + "14": { + "test_mse": 104936.97944941407, + "seconds": 2080.388349432964 + }, + "15": { + "test_mse": 104911.41180390625, + "seconds": 2076.926937010023 + }, + "16": { + "test_mse": 104879.30083398438, + "seconds": 2075.863515361096 + }, + "17": { + "test_mse": 104883.62164423829, + "seconds": 2094.7407408190193 + }, + "18": { + "test_mse": 104873.36078837891, + "seconds": 2093.4570691679837 + }, + "19": { + "test_mse": 104894.59398984375, + "seconds": 2077.9455633730395 + } + }, + "80": { + "10": { + "test_mse": 104956.68086894532, + "seconds": 2765.60760628304 + }, + "11": { + "test_mse": 104918.32717021485, + "seconds": 2771.837965917075 + }, + "12": { + "test_mse": 104916.45729121094, + "seconds": 2793.7624023950193 + }, + "13": { + "test_mse": 104876.34483525391, + "seconds": 2784.337712961016 + }, + "14": { + "test_mse": 104922.80848378906, + "seconds": 2786.125111669069 + }, + "15": { + "test_mse": 104899.88633046875, + "seconds": 2772.3496217790525 + }, + "16": { + "test_mse": 104861.9919375, + "seconds": 2781.435513923061 + }, + "17": { + "test_mse": 104868.12349277343, + "seconds": 2783.728736071993 + }, + "18": { + "test_mse": 104846.53313876953, + "seconds": 2777.9862230109866 + }, + "19": { + "test_mse": 104893.30292021485, + "seconds": 2769.6440545739606 + } + }, + "100": { + "10": { + "test_mse": 104934.28610771484, + "seconds": 3466.4492718670517 + }, + "11": { + "test_mse": 104909.95030146485, + "seconds": 3492.196416625986 + }, + "12": { + "test_mse": 104909.20551113281, + "seconds": 3486.4395430219593 + }, + "13": { + "test_mse": 104865.9366368164, + "seconds": 3493.8812221710104 + }, + "14": { + "test_mse": 104911.20413105469, + "seconds": 3509.196816975018 + }, + "15": { + "test_mse": 104884.14773212891, + "seconds": 3484.763677206007 + }, + "16": { + "test_mse": 104855.04843046876, + "seconds": 3490.433669294929 + }, + "17": { + "test_mse": 104855.20770253906, + "seconds": 3476.038782261021 + }, + "18": { + "test_mse": 104827.74964228515, + "seconds": 3489.3481884280336 + }, + "19": { + "test_mse": 104886.78951513671, + "seconds": 3483.946903357981 + } + } + } + }, + "sift1b-100M-div512": { + "flash_api": "batch_kmeans_Euclid", + "flash_norms": "float16", + "gpu": "one 80 GB GPU", + "torch": "2.14.0+cu130", + "triton": "3.8.0", + "median_test_mse": 0.16350760020647476, + "per_seed": { + "10": { + "test_mse": 0.16338710352787075, + "seconds": 434.10679916496156 + }, + "11": { + "test_mse": 0.1632015380836308, + "seconds": 438.2466726540588 + }, + "12": { + "test_mse": 0.16368806632913205, + "seconds": 433.07830588601064 + }, + "13": { + "test_mse": 0.16385419216516733, + "seconds": 431.991708414047 + }, + "14": { + "test_mse": 0.1633236446716234, + "seconds": 426.45682099903934 + }, + "15": { + "test_mse": 0.16350230464642643, + "seconds": 434.2880566259846 + }, + "16": { + "test_mse": 0.16328803788514673, + "seconds": 436.34323572699213 + }, + "17": { + "test_mse": 0.1635736732416455, + "seconds": 436.72742203599773 + }, + "18": { + "test_mse": 0.16351289576652311, + "seconds": 436.17489558598027 + }, + "19": { + "test_mse": 0.1635649564296065, + "seconds": 428.2768052270403 + } + }, + "flash_curve": { + "1": { + "10": { + "test_mse": 0.17126036183270163, + "seconds": 16.51300050492864 + }, + "11": { + "test_mse": 0.17097850252851685, + "seconds": 16.54795324697625 + }, + "12": { + "test_mse": 0.1710501994700943, + "seconds": 16.55408764805179 + }, + "13": { + "test_mse": 0.17155954399859516, + "seconds": 16.621780391025823 + }, + "14": { + "test_mse": 0.1714501271790998, + "seconds": 16.54060591792222 + }, + "15": { + "test_mse": 0.17084026084968962, + "seconds": 16.509105629986152 + }, + "16": { + "test_mse": 0.17062158629111568, + "seconds": 16.560987671953626 + }, + "17": { + "test_mse": 0.171508063839613, + "seconds": 16.636705393902957 + }, + "18": { + "test_mse": 0.17119859130275286, + "seconds": 16.563239756971598 + }, + "19": { + "test_mse": 0.1713220656619172, + "seconds": 16.556433268007822 + } + }, + "2": { + "10": { + "test_mse": 0.16792386437307008, + "seconds": 33.64012912497856 + }, + "11": { + "test_mse": 0.1675123731935834, + "seconds": 33.82457416097168 + }, + "12": { + "test_mse": 0.16760273384251342, + "seconds": 33.94292713794857 + }, + "13": { + "test_mse": 0.16801608256103076, + "seconds": 34.26484855398303 + }, + "14": { + "test_mse": 0.16793256370711307, + "seconds": 33.861066328012384 + }, + "15": { + "test_mse": 0.1673500114183264, + "seconds": 33.62865000998136 + }, + "16": { + "test_mse": 0.16731324071672385, + "seconds": 34.05059219698887 + }, + "17": { + "test_mse": 0.16795065528644126, + "seconds": 34.30704964697361 + }, + "18": { + "test_mse": 0.16777696010725104, + "seconds": 33.98073096899316 + }, + "19": { + "test_mse": 0.16780990299908935, + "seconds": 33.97602890897542 + } + }, + "3": { + "10": { + "test_mse": 0.16658258595773215, + "seconds": 50.7322178989416 + }, + "11": { + "test_mse": 0.1661042485055121, + "seconds": 51.069212695001625 + }, + "12": { + "test_mse": 0.1662769244026935, + "seconds": 51.419040267006494 + }, + "13": { + "test_mse": 0.1666495762549644, + "seconds": 51.81752675800817 + }, + "14": { + "test_mse": 0.1664298923446002, + "seconds": 51.03053587093018 + }, + "15": { + "test_mse": 0.16594790987412253, + "seconds": 50.63734248804394 + }, + "16": { + "test_mse": 0.16599553004714782, + "seconds": 51.629628411028534 + }, + "17": { + "test_mse": 0.1665128149352575, + "seconds": 51.937291756039485 + }, + "18": { + "test_mse": 0.16631776017041056, + "seconds": 51.44371777691413 + }, + "19": { + "test_mse": 0.16640481901036355, + "seconds": 51.429640665999614 + } + }, + "5": { + "10": { + "test_mse": 0.16535723093365315, + "seconds": 84.91970783402212 + }, + "11": { + "test_mse": 0.16474809635853416, + "seconds": 85.54326723597478 + }, + "12": { + "test_mse": 0.1651196310948665, + "seconds": 86.07124764693435 + }, + "13": { + "test_mse": 0.16545448317380723, + "seconds": 86.96471226401627 + }, + "14": { + "test_mse": 0.1650445725265504, + "seconds": 85.85731127101462 + }, + "15": { + "test_mse": 0.16484016271294166, + "seconds": 84.82179705309682 + }, + "16": { + "test_mse": 0.16476145367961567, + "seconds": 86.55919765401632 + }, + "17": { + "test_mse": 0.1651745213330382, + "seconds": 87.06936744507402 + }, + "18": { + "test_mse": 0.16503719321621643, + "seconds": 86.32488442398608 + }, + "19": { + "test_mse": 0.16513516445722806, + "seconds": 86.21990556397941 + } + }, + "8": { + "10": { + "test_mse": 0.16460320809245288, + "seconds": 136.22750660590827 + }, + "11": { + "test_mse": 0.16392629208192822, + "seconds": 137.99589364905842 + }, + "12": { + "test_mse": 0.16446765532316363, + "seconds": 138.54552312707528 + }, + "13": { + "test_mse": 0.16475527793626535, + "seconds": 139.64739534497494 + }, + "14": { + "test_mse": 0.16424473348626717, + "seconds": 137.54567092098296 + }, + "15": { + "test_mse": 0.16418749052996245, + "seconds": 136.18053290899843 + }, + "16": { + "test_mse": 0.16401613103647933, + "seconds": 139.12487136397976 + }, + "17": { + "test_mse": 0.16433826139344496, + "seconds": 139.86170868005138 + }, + "18": { + "test_mse": 0.16432993289907177, + "seconds": 138.74131717998534 + }, + "19": { + "test_mse": 0.16436242463761583, + "seconds": 138.49360035092104 + } + }, + "12": { + "10": { + "test_mse": 0.16410383453445523, + "seconds": 204.7280760280555 + }, + "11": { + "test_mse": 0.16351573090869775, + "seconds": 206.44709704699926 + }, + "12": { + "test_mse": 0.16408500361514383, + "seconds": 208.47658277198207 + }, + "13": { + "test_mse": 0.1643414578031789, + "seconds": 210.09865277202334 + }, + "14": { + "test_mse": 0.16369360305365432, + "seconds": 206.46915029501542 + }, + "15": { + "test_mse": 0.16381977483506185, + "seconds": 205.33799603197258 + }, + "16": { + "test_mse": 0.16361423550061163, + "seconds": 209.2676797870081 + }, + "17": { + "test_mse": 0.16385070029698226, + "seconds": 210.22847230592743 + }, + "18": { + "test_mse": 0.163935288845288, + "seconds": 208.60592536896002 + }, + "19": { + "test_mse": 0.16397583854124734, + "seconds": 207.99770144803915 + } + }, + "17": { + "10": { + "test_mse": 0.16371247022014654, + "seconds": 290.24312527803704 + }, + "11": { + "test_mse": 0.16334680773751353, + "seconds": 293.05017263197806 + }, + "12": { + "test_mse": 0.1638897686206251, + "seconds": 293.9629983520135 + }, + "13": { + "test_mse": 0.1641293193998627, + "seconds": 297.87404307100223 + }, + "14": { + "test_mse": 0.16347429435769767, + "seconds": 292.82714360696264 + }, + "15": { + "test_mse": 0.1636244878089012, + "seconds": 290.0645106009906 + }, + "16": { + "test_mse": 0.16338217625516666, + "seconds": 296.2847417049343 + }, + "17": { + "test_mse": 0.1636797298060415, + "seconds": 298.07257617404684 + }, + "18": { + "test_mse": 0.16365742260623212, + "seconds": 294.48919450398535 + }, + "19": { + "test_mse": 0.16375283079196448, + "seconds": 294.88423836498987 + } + }, + "25": { + "10": { + "test_mse": 0.16338710352787075, + "seconds": 434.10679916496156 + }, + "11": { + "test_mse": 0.1632015380836308, + "seconds": 438.2466726540588 + }, + "12": { + "test_mse": 0.16368806632913205, + "seconds": 433.07830588601064 + }, + "13": { + "test_mse": 0.16385419216516733, + "seconds": 431.991708414047 + }, + "14": { + "test_mse": 0.1633236446716234, + "seconds": 426.45682099903934 + }, + "15": { + "test_mse": 0.16350230464642643, + "seconds": 434.2880566259846 + }, + "16": { + "test_mse": 0.16328803788514673, + "seconds": 436.34323572699213 + }, + "17": { + "test_mse": 0.1635736732416455, + "seconds": 436.72742203599773 + }, + "18": { + "test_mse": 0.16351289576652311, + "seconds": 436.17489558598027 + }, + "19": { + "test_mse": 0.1635649564296065, + "seconds": 428.2768052270403 + } + }, + "40": { + "10": { + "test_mse": 0.16326068984582048, + "seconds": 692.9863550440641 + }, + "11": { + "test_mse": 0.16305486932090274, + "seconds": 704.3369158960413 + }, + "12": { + "test_mse": 0.16350582635725913, + "seconds": 703.6264433880569 + }, + "13": { + "test_mse": 0.1637550596035856, + "seconds": 701.4395341089694 + }, + "14": { + "test_mse": 0.163250408687949, + "seconds": 689.9385794519912 + }, + "15": { + "test_mse": 0.16337328435883092, + "seconds": 693.9034354840405 + }, + "16": { + "test_mse": 0.16314377297033705, + "seconds": 706.2642456530593 + }, + "17": { + "test_mse": 0.1633160505059373, + "seconds": 706.4265778089175 + }, + "18": { + "test_mse": 0.16346078291788335, + "seconds": 705.4962386959232 + }, + "19": { + "test_mse": 0.16350406220493766, + "seconds": 697.9034677810268 + } + }, + "60": { + "10": { + "test_mse": 0.1631864016334745, + "seconds": 1038.7629286549054 + }, + "11": { + "test_mse": 0.1630494573251106, + "seconds": 1057.1041575400159 + }, + "12": { + "test_mse": 0.163457961929401, + "seconds": 1056.0177902990254 + }, + "13": { + "test_mse": 0.16354030529719116, + "seconds": 1051.8987457189942 + }, + "14": { + "test_mse": 0.1632099205562442, + "seconds": 1034.910355251981 + }, + "15": { + "test_mse": 0.1633235154137619, + "seconds": 1037.0231769609964 + }, + "16": { + "test_mse": 0.16317347222495845, + "seconds": 1056.2278979979455 + }, + "17": { + "test_mse": 0.1632695643545385, + "seconds": 1054.2401821460808 + }, + "18": { + "test_mse": 0.1634210911871462, + "seconds": 1057.9162673499668 + }, + "19": { + "test_mse": 0.16344990369588153, + "seconds": 1044.6139800919918 + } + }, + "80": { + "10": { + "test_mse": 0.16316115574487913, + "seconds": 1397.5283053389285 + }, + "11": { + "test_mse": 0.16308333667256109, + "seconds": 1397.0580290859798 + }, + "12": { + "test_mse": 0.16337804149920476, + "seconds": 1390.6876633099746 + }, + "13": { + "test_mse": 0.16348052378009692, + "seconds": 1389.1672998330323 + }, + "14": { + "test_mse": 0.163179751025916, + "seconds": 1384.7452804209897 + }, + "15": { + "test_mse": 0.16330583521463574, + "seconds": 1415.8623006709386 + }, + "16": { + "test_mse": 0.16312939052131142, + "seconds": 1367.303042865009 + }, + "17": { + "test_mse": 0.16324485866686556, + "seconds": 1411.7111580090132 + }, + "18": { + "test_mse": 0.1633836959147488, + "seconds": 1383.363618269912 + }, + "19": { + "test_mse": 0.16341344927710225, + "seconds": 1374.93796968495 + } + }, + "100": { + "10": { + "test_mse": 0.16311509007933303, + "seconds": 1749.3746151429368 + }, + "11": { + "test_mse": 0.16312178934524046, + "seconds": 1759.538489962928 + }, + "12": { + "test_mse": 0.16331694883593484, + "seconds": 1743.9339048460824 + }, + "13": { + "test_mse": 0.16342398361539234, + "seconds": 1762.5293722900096 + }, + "14": { + "test_mse": 0.16315608089003963, + "seconds": 1739.0833879039856 + }, + "15": { + "test_mse": 0.1632804352083649, + "seconds": 1740.8007955480134 + }, + "16": { + "test_mse": 0.1631137142304783, + "seconds": 1713.136827899958 + }, + "17": { + "test_mse": 0.16321804830385864, + "seconds": 1724.6547874230891 + }, + "18": { + "test_mse": 0.16335129568092396, + "seconds": 1739.2125695119612 + }, + "19": { + "test_mse": 0.1633674066562564, + "seconds": 1720.2028811100172 + } + } + } + } + }, + "figure3": { + "deep1b-1M": { + "reference": "faiss k-means, 25 Lloyd iterations, CPU", + "median_test_mse": 0.38921320633218964, + "per_seed": { + "10": { + "test_mse": 0.3891906460324864, + "train_mse": 0.36208297755750884 + }, + "11": { + "test_mse": 0.38922729777124043, + "train_mse": 0.36213860391758157 + }, + "12": { + "test_mse": 0.38919911489313885, + "train_mse": 0.3621391336388324 + }, + "13": { + "test_mse": 0.38857899804670587, + "train_mse": 0.3621651625726251 + }, + "14": { + "test_mse": 0.3903787545028616, + "train_mse": 0.3620961872118833 + }, + "15": { + "test_mse": 0.3894125532877603, + "train_mse": 0.3620399163246235 + }, + "16": { + "test_mse": 0.389147184134462, + "train_mse": 0.3620311939597388 + }, + "17": { + "test_mse": 0.38945949265528906, + "train_mse": 0.36207991374567805 + }, + "18": { + "test_mse": 0.3886175503086305, + "train_mse": 0.3621080500726862 + }, + "19": { + "test_mse": 0.38983425204513616, + "train_mse": 0.3620094678754594 + } + } + }, + "imagenet-clip-512-normalized": { + "reference": "faiss k-means, 25 Lloyd iterations, CPU", + "median_test_mse": 0.21316390911114022, + "per_seed": { + "10": { + "test_mse": 0.2130046609155388, + "train_mse": 0.20257447981009694 + }, + "11": { + "test_mse": 0.21313725408860978, + "train_mse": 0.20268387179561162 + }, + "12": { + "test_mse": 0.21335669568209142, + "train_mse": 0.20260088187769362 + }, + "13": { + "test_mse": 0.21306426332868922, + "train_mse": 0.202634178183816 + }, + "14": { + "test_mse": 0.21323452847109947, + "train_mse": 0.2026282299986003 + }, + "15": { + "test_mse": 0.21305605028884342, + "train_mse": 0.20263743020065425 + }, + "16": { + "test_mse": 0.21324065316992896, + "train_mse": 0.20266396846708215 + }, + "17": { + "test_mse": 0.21305377088941327, + "train_mse": 0.20257403970550228 + }, + "18": { + "test_mse": 0.21319650624686706, + "train_mse": 0.20261774753644501 + }, + "19": { + "test_mse": 0.21319056413367066, + "train_mse": 0.20265231815879306 + } + } + }, + "spacev-10M": { + "reference": "faiss k-means, 25 Lloyd iterations, CPU", + "median_test_mse": 6377.1451419106725, + "per_seed": { + "10": { + "test_mse": 6372.967523287641, + "train_mse": 6259.7186668087725 + }, + "11": { + "test_mse": 6371.5772086782645, + "train_mse": 6258.358805445194 + }, + "12": { + "test_mse": 6377.2236124856145, + "train_mse": 6259.639813180498 + }, + "13": { + "test_mse": 6377.599259268082, + "train_mse": 6259.153917329106 + }, + "14": { + "test_mse": 6377.066671335731, + "train_mse": 6259.40228101023 + }, + "15": { + "test_mse": 6380.27601809711, + "train_mse": 6258.7926770245285 + }, + "16": { + "test_mse": 6378.079303821931, + "train_mse": 6260.091475878016 + }, + "17": { + "test_mse": 6377.49157743784, + "train_mse": 6260.1887117354445 + }, + "18": { + "test_mse": 6373.735490907166, + "train_mse": 6259.86110460065 + }, + "19": { + "test_mse": 6373.958711297109, + "train_mse": 6259.709993443592 + } + } + }, + "sift1b-10M-normalized": { + "reference": "faiss k-means, 25 Lloyd iterations, CPU", + "median_test_mse": 0.19620587452418486, + "per_seed": { + "10": { + "test_mse": 0.19620781781224936, + "train_mse": 0.176787821637672 + }, + "11": { + "test_mse": 0.1960435898409463, + "train_mse": 0.17678286024831658 + }, + "12": { + "test_mse": 0.1962200707126999, + "train_mse": 0.17678734610877492 + }, + "13": { + "test_mse": 0.19616923661120098, + "train_mse": 0.17678088085304972 + }, + "14": { + "test_mse": 0.19581173847374353, + "train_mse": 0.17677441326355328 + }, + "15": { + "test_mse": 0.1963899325710243, + "train_mse": 0.17679407472583264 + }, + "16": { + "test_mse": 0.19614213895357727, + "train_mse": 0.17677348028617954 + }, + "17": { + "test_mse": 0.1962928355978323, + "train_mse": 0.17677447087976794 + }, + "18": { + "test_mse": 0.19620393123612037, + "train_mse": 0.17679307118480492 + }, + "19": { + "test_mse": 0.1963353810793771, + "train_mse": 0.17678997961523876 + } + } + } + } +} \ No newline at end of file diff --git a/thirdparty/faiss/benchs/e_means/paper_xb.py b/thirdparty/faiss/benchs/e_means/paper_xb.py new file mode 100644 index 000000000..739790fc7 --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/paper_xb.py @@ -0,0 +1,303 @@ +# 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. + +"""The paper's timing protocol (xbench) in one small module, for faiss.contrib.e_means. + +Every timed run is its own process (isolated). That process: + 1. loads the dataset (paper_data.py checks the public files against the paper's arrays); + 2. takes the paper's starting rows: the first k of a permutation drawn by a seeded CUDA + generator, exactly as the paper's runs drew them, so both methods of a (dataset, seed) + start from the same rows as the paper's own runs (starts); + 3. warms the method up with an untimed call: for e-means the identical call, for Flash-KMeans + two iterations at the exact shape, which is what compiles and tunes its kernels; + 4. frees GPU memory and times one call between two GPU synchronizations; when that call took + under 2 s it times two more from the same freed state and keeps the median (timed); + 5. scores the first call's centroids on the test half with one exact scorer: ranking by an + IEEE float32 product with TF32 off, distances recomputed by direct difference in float64. +paper_bench.py runs both methods of a (dataset, seed) one after the other in the same job, so on +the same GPU. + +e-means assigns in bfloat16 with its CuTe kernels. Its input reaches bfloat16 by one of two +routes, which must give the same result (comparing them is a check on the library): + cast float32 rows on the GPU, converted batch by batch by CastQuantizer(d, torch.bfloat16) + (the documented way to train on float32 data; without a quantizer e-means would assign + in real float32, which is far slower) + bf16 rows converted to bfloat16 once, before training, and passed with quantizer=None +The default is cast, and bf16 where a float32 copy would not fit one 80 GB GPU (SimSearchNet++ +at 100M rows). Every integer corpus here, and every rescaled one (a division by a power of two), +is exact in bfloat16, so there the two routes see identical values. + +Flash-KMeans runs the way its own code dispatches data held on the GPU: its standard function +batch_kmeans_Euclid, in float16. Two corpora follow the paper's float32-norm rule: SPACEV uses the +patched copy of that function, and SimSearchNet++, whose squared norms overflow float16 even there, +uses the patched large-N function. paper_flash_matched.py builds the patched copy. + + python paper_xb.py --one '{"method": "emeans", "dataset": "deep1b-1M", "seed": 10, + "epochs": 2, "input": "cast"}' +""" +import argparse +import gc +import hashlib +import importlib.metadata +import json +import os +import statistics +import subprocess +import sys +import time + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import paper_data as data # noqa: E402 + +CALLS, CALLS_MAX_S = 3, 2.0 # three timed calls when the first took under 2 s +FLASH_BLOCK = 1 << 20 # kmeans_largeN's block of rows +MATCHED = ("spacev", "fb-ssnpp") # Flash with float32 norms (the paper's rule) +LARGE_N = ("fb-ssnpp",) # ... through its large-N function +FLOAT32_MAX_BYTES = 60 * 2**30 # largest float32 copy the cast route puts on one GPU +FLASH_MATCHED = os.path.join(data.CACHE, "flash_matched") +FLASH_VERSION = "0.3.1" # the Flash-KMeans release the paper timed + + +def k_for(n): + """The paper's cluster count at each scale.""" + return 16384 if n <= 2 * 10**6 else 65536 if n <= 2 * 10**7 else 262144 + + +def batch_law(n): + """The paper's batch: the larger "throughput" batch at a million rows, the "quality" batch + (one eighth of it) at ten and a hundred million.""" + return "throughput" if n <= 2 * 10**6 else "quality" + + +def default_input(n, d): + return "cast" if 4 * n * d <= FLOAT32_MAX_BYTES else "bf16" + + +def pin_precision(): + import torch + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + + +def sync(): + import torch + torch.cuda.synchronize() + + +def free(): + import torch + gc.collect() + torch.cuda.empty_cache() + + +def upload(train, name, dtype, chunk=1 << 20): + """The training rows as a GPU tensor of `dtype`, rescaled as the paper rescaled them and + converted in chunks, so no full float32 copy is ever made on the host.""" + import torch + x = torch.empty(train.shape, dtype=dtype, device="cuda") + for s in range(0, train.shape[0], chunk): + x[s:s + chunk] = torch.from_numpy(data.rows(train, name, s, s + chunk)).cuda().to(dtype) + return x + + +def starts(n, k, seed): + """The paper's starting rows: the first k of a seeded permutation drawn on the GPU (the + paper's gpu_kmeans_init(..., init="random", seed=seed)). Checked to reproduce the paper's + starting centroids exactly with PyTorch 2.14.""" + import torch + generator = torch.Generator(device="cuda").manual_seed(int(seed)) + return torch.randperm(n, generator=generator, device="cuda")[:k].cpu().numpy() + + +def test_error(centroids, test, chunk_rows=32768, chunk_k=16384): + """Mean squared distance from each test row to its nearest centroid: ranked with an IEEE + float32 product (TF32 off), then the distance to the chosen centroid recomputed by direct + difference in float64, so the error has no norm cancellation.""" + import torch + pin_precision() + c = torch.as_tensor(np.ascontiguousarray(centroids, dtype=np.float32), device="cuda") + cn = (c.double() ** 2).sum(1).float() # (k,) + total = 0.0 + for s in range(0, test.shape[0], chunk_rows): + xb = torch.from_numpy(np.ascontiguousarray(test[s:s + chunk_rows])).cuda() # (m, d) + best = torch.full((xb.shape[0],), float("inf"), device="cuda") + arg = torch.zeros(xb.shape[0], dtype=torch.int64, device="cuda") + for j in range(0, c.shape[0], chunk_k): + v, a = (cn[j:j + chunk_k][None, :] - 2.0 * (xb @ c[j:j + chunk_k].t())).min(1) + better = v < best + best = torch.where(better, v, best) + arg = torch.where(better, a + j, arg) + diff = xb.double() - c[arg].double() # (m, d) + total += float((diff * diff).sum()) + return total / test.shape[0] + + +def timed(call, warmup): + """Untimed warmup(), then call() timed between two synchronizations: once, or three times + when the first took under 2 s, each from freed memory. Returns (the first call's centroids + as a NumPy array, the median time, every call's time).""" + warmup() + sync() + first, secs = None, [] + for i in range(CALLS): + free() + sync() + start = time.perf_counter() + out = call() + sync() + secs.append(time.perf_counter() - start) + if i == 0: + first = out.detach().float().cpu().numpy() + del out + if secs[0] >= CALLS_MAX_S: + break + return first, statistics.median(secs), secs + + +def library(): + """Which faiss.contrib.e_means ran: its folder and a short hash of its source files.""" + import faiss.contrib.e_means as em + folder = os.path.dirname(em.__file__) + h = hashlib.sha256() + for f in sorted(os.listdir(folder)): + if f.endswith(".py"): + h.update(f.encode() + open(os.path.join(folder, f), "rb").read()) + return dict(emeans_path=folder, emeans_source_sha256=h.hexdigest()[:16]) + + +def run_emeans(name, train, init, seed, epochs, route): + """faiss.contrib.e_means, bfloat16 assignment with its CuTe kernels, the input reaching + bfloat16 by `route` (module docstring).""" + import torch + from faiss.contrib.e_means import Emeans, QuantizedEmeans + from faiss.contrib.e_means.base import _resolve_recipe + from faiss.contrib.e_means.quantizer import CastQuantizer + n, d = train.shape + k = k_for(n) + model = Emeans + kw = dict(seed=seed, batch_law=batch_law(n), assignment_backend="cute") + if epochs < 1: # below one pass the paper keeps the one-pass batch, step + kw["batch_size"], kw["alpha0"] = _resolve_recipe(n, k, 1.0, kw["batch_law"], None, None) + if route == "cast": + x = upload(train, name, torch.float32) # (n, d) + model = QuantizedEmeans + kw["quantizer"] = CastQuantizer(d, torch.bfloat16) + elif route == "bf16": + x = upload(train, name, torch.bfloat16) # (n, d) + else: + raise ValueError("input must be cast or bf16, got %r" % route) + start = torch.from_numpy(init).cuda() # (k, d) float32 + + def call(): + km = model(d, k, nepochs=epochs, **kw) + km.train(x, init_centroids=start) + call.recipe = km.recipe + return km.centroids + + centroids, seconds, calls = timed(call, warmup=call) + recipe = call.recipe + return centroids, seconds, calls, dict( + input=route, batch=int(recipe["batch_size"]), alpha0=float(recipe["alpha0"]), + representation=str(recipe.get("representation")), + assignment_backend=str(recipe.get("assignment_backend")), **library()) + + +def run_flash(name, train, init, iterations): + """Flash-KMeans, float16 rows on the GPU, every iteration forced (tol=-1). Only the release + the paper timed is accepted: another one would give numbers that look right and are not the + paper's baseline.""" + import torch + version = importlib.metadata.version("flash-kmeans") + if version != FLASH_VERSION: + sys.exit("the paper timed flash-kmeans %s, found %s: pip install flash-kmeans==%s" + % (FLASH_VERSION, version, FLASH_VERSION)) + if name.startswith(MATCHED): + marker = os.path.join(FLASH_MATCHED, "VERSION") + if not os.path.exists(marker) or open(marker).read().strip() != FLASH_VERSION: + sys.exit("%s needs Flash-KMeans %s with float32 norms: run python " + "paper_flash_matched.py" % (name, FLASH_VERSION)) + sys.path.insert(0, FLASH_MATCHED) + import flash_kmeans + n, d = train.shape + k = k_for(n) + x = upload(train, name, torch.float16) # (n, d) + start = torch.from_numpy(init).cuda() # (k, d) float32 + if name.startswith(LARGE_N): + from flash_kmeans.kmeans_large import kmeans_largeN + + def solve(iters, rows=n): + out = kmeans_largeN(x[:rows].contiguous(), k, max_iters=iters, tol=-1, + BLOCK_N=FLASH_BLOCK, init_centroids=start.clone(), + device=x.device, dtype=torch.float16) + return out[1] if isinstance(out, (tuple, list)) else out + + sizes = [min(n, FLASH_BLOCK)] + ([n % FLASH_BLOCK] if n > FLASH_BLOCK and n % FLASH_BLOCK + else []) + centroids, seconds, calls = timed(lambda: solve(iterations), + warmup=lambda: [solve(2, rows) for rows in sizes]) + api = "kmeans_largeN" + else: + from flash_kmeans.kmeans_triton_impl import batch_kmeans_Euclid + start16 = start.half()[None] # (1, k, d) + + def solve(iters): + out = batch_kmeans_Euclid(x[None], k, max_iters=iters, tol=-1, + init_centroids=start16.clone()) + assert int(out[2]) == iters, "Flash ran %s iterations, %d asked" % (out[2], iters) + return out[1][0] + + centroids, seconds, calls = timed(lambda: solve(iterations), warmup=lambda: solve(2)) + api = "batch_kmeans_Euclid" + return centroids, seconds, calls, dict( + flash_api=api, flash_norms="float32" if name.startswith(MATCHED) else "float16", + flash_package=os.path.dirname(flash_kmeans.__file__), flash_version=version) + + +def one(spec): + """One timed run, in this process. Returns its record.""" + import torch + import triton + pin_precision() + train, test = data.load(spec["dataset"]) + n, d = train.shape + rows = starts(n, k_for(n), spec["seed"]) + order = np.argsort(rows) + init = np.empty((len(rows), d), dtype=np.float32) # train[rows], (k, d) + init[order] = data.rows(train, spec["dataset"], index=rows[order]) + if spec["method"] == "emeans": + spec = dict(spec, input=spec.get("input") or default_input(n, d)) + centroids, seconds, calls, extra = run_emeans(spec["dataset"], train, init, spec["seed"], + spec["epochs"], spec["input"]) + else: + centroids, seconds, calls, extra = run_flash(spec["dataset"], train, init, + spec["iterations"]) + return dict(spec, n=n, k=k_for(n), seconds=seconds, seconds_calls=calls, + test_mse=test_error(centroids, test), gpu=torch.cuda.get_device_name(), + device=str(torch.device("cuda", torch.cuda.current_device())), + visible_gpus=torch.cuda.device_count(), + torch=torch.__version__, triton=triton.__version__, **extra) + + +def isolated(spec, python=None): + """One timed run in a fresh process (python paper_xb.py --one), as the paper's runs were. + `python` runs it under another interpreter, for example to time Flash-KMeans in another + PyTorch and Triton environment; Flash-KMeans runs under $XB_FLASH_PYTHON when it is set.""" + if python is None and spec["method"] == "flash": + python = os.environ.get("XB_FLASH_PYTHON") or None + out = subprocess.run([python or sys.executable, os.path.join(HERE, "paper_xb.py"), "--one", + json.dumps(spec)], capture_output=True, text=True) + if out.returncode != 0: + raise RuntimeError("run %s failed:\n%s" % (spec, out.stderr[-3000:])) + return json.loads(out.stdout.strip().splitlines()[-1]) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--one", required=True, help="JSON spec of one timed run") + print(json.dumps(one(json.loads(ap.parse_args().one))), flush=True) diff --git a/thirdparty/faiss/benchs/e_means/ssd_streaming.py b/thirdparty/faiss/benchs/e_means/ssd_streaming.py new file mode 100644 index 000000000..04af645fb --- /dev/null +++ b/thirdparty/faiss/benchs/e_means/ssd_streaming.py @@ -0,0 +1,582 @@ +# 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. + +"""SSD scans into shuffled host windows and asynchronous CUDA batches. + +Adapts the window scans and chunk-group permutation from the reference +ssd_prefetch.py and data.py. Each rank reads its own contiguous row shard. +""" + +from concurrent.futures import ThreadPoolExecutor +import errno +import math +import mmap +import os +import queue +import time + +import numpy as np +import torch + + +class SSDRowSource: + """A rank's range in fixed-width uint8 files, optionally with row headers. + + ``paths`` are ordered corpus chunks. O_DIRECT uses page-aligned buffers + and reads; filesystems that refuse it fall back to buffered preadv. + """ + + def __init__(self, paths, d, begin, end, header_bytes=0, direct=True): + if d < 1 or header_bytes < 0 or not 0 <= begin < end: + raise ValueError("invalid SSD row layout or range") + self.d, self.header_bytes = int(d), int(header_bytes) + self.row_bytes = self.d + self.header_bytes + self.begin, self.n = int(begin), int(end - begin) + self.fds = [] + self.direct = [] + lengths = [] + try: + for path in paths: + size = os.path.getsize(path) + if size % self.row_bytes: + raise ValueError(f"incomplete row in {path}") + lengths.append(size // self.row_bytes) + try: + fd = os.open( + path, os.O_RDONLY | (os.O_DIRECT if direct else 0) + ) + is_direct = bool(direct) + except OSError as error: + if error.errno not in (errno.EINVAL, errno.EOPNOTSUPP): + raise + fd, is_direct = os.open(path, os.O_RDONLY), False + self.fds.append(fd) + self.direct.append(is_direct) + self.ends = np.cumsum(lengths) + if not lengths or end > self.ends[-1]: + raise ValueError("SSD shard exceeds file rows") + except BaseException: + self.close() + raise + + def close(self): + for fd in self.fds: + os.close(fd) + self.fds.clear() + + def read(self, begin, end): + """Read a sequential local range into an owned compact uint8 array.""" + if not 0 <= begin <= end <= self.n: + raise IndexError("SSD row range out of bounds") + out = np.empty((end - begin, self.d), dtype=np.uint8) + a, b, at = self.begin + begin, self.begin + end, 0 + for fd, hi, lo in zip(self.fds, self.ends, np.r_[0, self.ends[:-1]]): + start, stop = max(a, int(lo)), min(b, int(hi)) + if start >= stop: + continue + offset = (start - lo) * self.row_bytes + length = (stop - start) * self.row_bytes + aligned = int(offset) // mmap.PAGESIZE * mmap.PAGESIZE + slack = int(offset) - aligned + size = math.ceil((slack + length) / mmap.PAGESIZE) * mmap.PAGESIZE + with mmap.mmap(-1, size) as buffer: + got = os.preadv(fd, [buffer], aligned) + if got < slack + length: + raise OSError("short SSD read") + rows = np.ndarray( + (stop - start, self.row_bytes), + dtype=np.uint8, + buffer=buffer, + offset=slack, + ) + out[at : at + stop - start] = rows[:, self.header_bytes :] + del rows + at += stop - start + return out + + def read_views(self, begin, end, buffer): + """Read into a reusable aligned buffer and return borrowed payload views. + + Views retain bvecs row strides and skip headers without copying. Keep + ``buffer`` alive and unchanged until all views have been consumed. + A range crossing files returns one view per file, with local row offsets. + """ + if not 0 <= begin <= end <= self.n: + raise IndexError("SSD row range out of bounds") + a, b, cursor = self.begin + begin, self.begin + end, 0 + views = [] + for fd, hi, lo in zip(self.fds, self.ends, np.r_[0, self.ends[:-1]]): + start, stop = max(a, int(lo)), min(b, int(hi)) + if start >= stop: + continue + offset = (start - int(lo)) * self.row_bytes + length = (stop - start) * self.row_bytes + aligned = offset // mmap.PAGESIZE * mmap.PAGESIZE + slack = offset - aligned + size = math.ceil((slack + length) / mmap.PAGESIZE) * mmap.PAGESIZE + if cursor + size > len(buffer): + raise ValueError("SSD read buffer is too small") + target = memoryview(buffer)[cursor : cursor + size] + try: + got = os.preadv(fd, [target], aligned) + finally: + target.release() + if got < slack + length: + raise OSError("short SSD read") + rows = np.ndarray( + (stop - start, self.row_bytes), dtype=np.uint8, + buffer=buffer, offset=cursor + slack, + ) + views.append((start - self.begin, rows[:, self.header_bytes :])) + cursor += size + return views + + def gather(self, request, out, depth=256): + """Queue small aligned reads of random rows into a host array. + + Rows sharing a starting block use one read. Payload offsets include + bvecs headers, and reads span two blocks when a payload straddles one. + Buffers and the ring are bounded by depth; output order is preserved. + """ + if __package__: + from . import ctypes_liburing as uring + else: + import ctypes_liburing as uring + + request = np.asarray(request, dtype=np.int64) + if request.ndim != 1 or ( + len(request) and (request.min() < 0 or request.max() >= self.n) + ): + raise IndexError("random request outside SSD shard") + if depth < 1 or depth & (depth - 1): + raise ValueError("I/O depth must be a positive power of two") + destination = out.numpy() if isinstance(out, torch.Tensor) else out + if destination.shape != (len(request), self.d): + raise ValueError("random read output has the wrong shape") + stats = {"bytes_read": 0, "requests": 0} + if not len(request): + return stats + block = 4096 + slot_bytes = math.ceil((self.d + block - 1) / block) * block + ring = uring.io_uring() + buffers, views = [], [] + try: + uring.io_uring_queue_init(depth, ring, 0) + buffers = [mmap.mmap(-1, slot_bytes) for _ in range(depth)] + views = [ + np.frombuffer(buffer, dtype=np.uint8) for buffer in buffers + ] + cqe = uring.io_uring_cqe() + columns = np.arange(self.d) + absolute = self.begin + request + for fd, hi, lo in zip( + self.fds, self.ends, np.r_[0, self.ends[:-1]] + ): + ids = np.flatnonzero((absolute >= lo) & (absolute < hi)) + if not len(ids): + continue + starts = ( + absolute[ids] - lo + ) * self.row_bytes + self.header_bytes + perm = np.argsort(starts, kind="stable") + ids, starts = ids[perm], starts[perm] + blocks = starts // block + bounds = np.r_[ + 0, np.flatnonzero(np.diff(blocks)) + 1, len(ids) + ] + for first in range(0, len(bounds) - 1, depth): + pending = [] + for j in range(first, min(first + depth, len(bounds) - 1)): + a, b = int(bounds[j]), int(bounds[j + 1]) + offset = int(blocks[a]) * block + needed = int(starts[b - 1]) + self.d - offset + length = math.ceil(needed / block) * block + slot = len(pending) + sqe = uring.io_uring_get_sqe(ring) + uring.io_uring_prep_read( + sqe, fd, buffers[slot], length, offset + ) + sqe.user_data = slot + pending.append((a, b, offset, needed)) + uring.io_uring_submit_and_wait(ring, len(pending)) + error = None + for _ in pending: + if uring.io_uring_peek_cqe(ring, cqe): + raise OSError("missing random read completion") + a, b, offset, needed = pending[cqe.user_data] + if cqe.res < 0: + error = OSError(-cqe.res, "random SSD read failed") + elif cqe.res < needed: + error = OSError("short random SSD read") + else: + destination[ids[a:b]] = views[cqe.user_data][ + (starts[a:b] - offset)[:, None] + columns + ] + stats["bytes_read"] += cqe.res + stats["requests"] += 1 + uring.io_uring_cqe_seen(ring, cqe) + if error is not None: + raise error + finally: + uring.io_uring_queue_exit(ring) + views.clear() + for buffer in buffers: + buffer.close() + return stats + + +def chunk_grouped_order(n, rows_per_chunk, groups, window_rows, seed): + """Permute all rows once, grouping full windows by random scan chunks. + + Each full window draws from one of ``groups`` random subsets of scan + chunks. Full windows are shuffled across groups; short group tails are + placed last. Groups=1 gives a uniform row permutation. + """ + if min(n, rows_per_chunk, groups, window_rows) < 1: + raise ValueError("permutation dimensions must be positive") + rng = np.random.RandomState(seed) + if groups == 1: + return rng.permutation(n) + count = math.ceil(n / rows_per_chunk) + pieces = np.array_split(rng.permutation(count), min(groups, count)) + layout, full, partial = [], [], [] + for j, chunks in enumerate(pieces): + last = chunks == count - 1 + chunks = np.r_[chunks[~last], chunks[last]] + size = len(chunks) * rows_per_chunk - ( + count * rows_per_chunk - n if last.any() else 0 + ) + layout.append((chunks, size)) + full.extend((j, k) for k in range(size // window_rows)) + if size % window_rows: + partial.append((j, size // window_rows)) + positions, at = {}, 0 + for items in (full, partial): + for index in rng.permutation(len(items)): + j, k = items[index] + length = min(window_rows, layout[j][1] - k * window_rows) + positions[j, k] = (at, length) + at += length + output = np.empty(n, dtype=np.int64) + for j, (chunks, size) in enumerate(layout): + perm = rng.permutation(size) + for k in range(math.ceil(size / window_rows)): + dest, length = positions[j, k] + for start in range(0, length, 1 << 20): + q = perm[ + k * window_rows + + start : k * window_rows + + min(length, start + (1 << 20)) + ] + output[dest + start : dest + start + len(q)] = ( + chunks[q // rows_per_chunk] * rows_per_chunk + + q % rows_per_chunk + ) + return output + + +def _plan_window(request, n_rows, rows_per_chunk): + """Group requested rows by chunk, retaining their output destinations. + + Adapted from the reference ssd_prefetch._plan_file. Permutation windows + have distinct rows: a mask and inverse map replace the expensive sort. + Duplicate requests retain the stable-sort path. + """ + request = np.asarray(request, dtype=np.int64) + if request.ndim != 1 or ( + len(request) and (request.min() < 0 or request.max() >= n_rows) + ): + raise IndexError("prefetch request outside SSD shard") + count = len(request) + rows = None + if count: + mask = np.zeros(n_rows, dtype=bool) + mask[request] = True + rows = np.flatnonzero(mask) + del mask + if len(rows) == count: + inverse = np.empty( + n_rows, dtype=np.int32 if count < 2**31 else np.int64 + ) + inverse[request] = np.arange(count, dtype=inverse.dtype) + order = inverse[rows].astype(np.int64) + del inverse + else: + rows = None + if rows is None: + order = np.argsort(request, kind="stable") + rows = request[order] + chunk_ids = rows // rows_per_chunk + first = ( + np.r_[0, np.flatnonzero(np.diff(chunk_ids)) + 1] + if count else np.empty(0, dtype=np.int64) + ) + chunks = chunk_ids[first] + bounds = np.r_[first, count] + return rows, order, chunks, bounds + + +class SSDPrefetch: + """Two host windows, chunk scans, and one CUDA batch copied ahead. + + Random requests retain their exact order, including duplicates. Reads + within each window are issued in increasing chunk order; chunks with no + requested row are skipped. A window is reused only after its asynchronous + copies complete. Close the iterator before closing its source. + """ + + def __init__( + self, + source, + device, + batch_size, + *, + n_prefetch="auto", + chunk_groups=4, + chunk_bytes=64 << 20, + ram_budget_bytes=16 << 30, + read_threads=1, + extract_threads=4, + ): + if ( + min( + batch_size, + chunk_groups, + chunk_bytes, + ram_budget_bytes, + read_threads, + extract_threads, + ) + < 1 + ): + raise ValueError( + "SSD prefetch sizes and thread counts must be positive" + ) + self.source, self.device = source, torch.device(device) + if self.device.type != "cuda": + raise ValueError("SSD prefetch requires CUDA") + self.batch_size, self.chunk_groups = batch_size, chunk_groups + self.rows_per_chunk = max(1, chunk_bytes // source.row_bytes) + steps = math.ceil(source.n / batch_size) + capacity = ram_budget_bytes // (2 * batch_size * source.d) + if capacity < 1: + raise ValueError("RAM budget must fit two host batches") + self.n_prefetch = ( + min(steps, capacity) if n_prefetch == "auto" else int(n_prefetch) + ) + if not 1 <= self.n_prefetch <= capacity: + raise ValueError("prefetch windows exceed RAM budget") + self.window_rows = self.n_prefetch * batch_size + self.read_threads, self.extract_threads = read_threads, extract_threads + self.copy_stream = torch.cuda.Stream(self.device) + self.stats = {"bytes_read": 0, "wait_s": 0.0, "windows": 0} + + def order(self, seed): + return chunk_grouped_order( + self.source.n, + self.rows_per_chunk, + self.chunk_groups, + self.window_rows, + seed, + ) + + def fill_window(self, request, out): + planned = time.perf_counter() + rows, order, chunks, bounds = _plan_window( + request, self.source.n, self.rows_per_chunk + ) + self.stats["plan_s"] = ( + self.stats.get("plan_s", 0.0) + time.perf_counter() - planned + ) + if not len(rows): + return + destination = out.numpy() + + def tasks(): + for chunk, lo, hi in zip(chunks, bounds[:-1], bounds[1:]): + begin = int(chunk) * self.rows_per_chunk + end = min(self.source.n, begin + self.rows_per_chunk) + yield begin, end, int(lo), int(hi) + + def extract(task, views): + _, _, lo, hi = task + for begin, data in views: + a, b = np.searchsorted(rows[lo:hi], [begin, begin + len(data)]) + a, b = lo + int(a), lo + int(b) + destination[order[a:b]] = data[rows[a:b] - begin] + + scanned = time.perf_counter() + self._scan_chunks(tasks(), extract) + self.stats["scan_s"] = ( + self.stats.get("scan_s", 0.0) + time.perf_counter() - scanned + ) + self.stats["windows"] += 1 + + def _scan_chunks(self, tasks, extract): + """Pipeline reads and extraction with buffers leased until copying ends.""" + slots = 2 * (self.read_threads + self.extract_threads) + # Each file fragment needs up to two extra pages for aligned I/O. + size = math.ceil( + (self.rows_per_chunk * self.source.row_bytes + + 2 * mmap.PAGESIZE * len(self.source.fds)) / mmap.PAGESIZE + ) * mmap.PAGESIZE + buffers = [] + free = queue.Queue() + pending_reads, pending_extracts = [], [] + + def read_chunk(task): + slot = free.get() + try: + views = self.source.read_views(task[0], task[1], buffers[slot]) + return task, slot, views + except BaseException: + free.put(slot) + raise + + def consume(item): + task, slot, views = item + try: + extract(task, views) + finally: + views.clear() + free.put(slot) + + def dispatch(future, extractors): + item = future.result() + self.stats["bytes_read"] += ( + (item[0][1] - item[0][0]) * self.source.row_bytes + ) + pending_extracts.append(extractors.submit(consume, item)) + + try: + for slot in range(slots): + buffers.append(mmap.mmap(-1, size)) + free.put(slot) + with ThreadPoolExecutor(self.read_threads) as readers, ThreadPoolExecutor( + self.extract_threads + ) as extractors: + for task in tasks: + pending_reads.append(readers.submit(read_chunk, task)) + if len(pending_reads) >= 2 * self.read_threads: + dispatch(pending_reads.pop(0), extractors) + if len(pending_extracts) >= 2 * self.extract_threads: + pending_extracts.pop(0).result() + for future in pending_reads: + dispatch(future, extractors) + for future in pending_extracts: + future.result() + finally: + # Unconsumed completed reads can retain borrowed views on errors. + for future in pending_reads: + if future.done() and not future.cancelled() and future.exception() is None: + future.result()[2].clear() + pending_reads.clear() + pending_extracts.clear() + for buffer in buffers: + buffer.close() + + def fill_sequential(self, start, end, out): + def tasks(): + for begin in range(start, end, self.rows_per_chunk): + yield begin, min(end, begin + self.rows_per_chunk) + + def extract(task, views): + for begin, data in views: + out[begin - start : begin - start + len(data)].copy_( + torch.from_numpy(data) + ) + + self._scan_chunks(tasks(), extract) + self.stats["windows"] += 1 + + def batches(self, order=None, *, sequential=False, mean=None, scale=None): + """Yield rank-local FP32 CUDA batches, optionally centered. + + Sequential mode performs one corpus scan without permutation or + repeated sparse window scans, for centering and frozen closing means. + One batch per host window keeps sequential reads from delaying compute. + Random mode accepts a permutation prefix for a fractional pass. + """ + self.copy_stream.wait_stream(torch.cuda.current_stream(self.device)) + if not sequential and (order is None or len(order) > self.source.n): + raise ValueError( + "random mode needs at most one request per source row" + ) + n_rows = self.source.n if sequential else len(order) + if n_rows == 0: + return + window_rows = self.batch_size if sequential else self.window_rows + window_rows = min(window_rows, n_rows) + slots = [ + torch.empty( + (window_rows, self.source.d), + dtype=torch.uint8, + pin_memory=True, + ) + for _ in range(2) + ] + events = [None, None] + pool = ThreadPoolExecutor(1) + + def fill(start, slot): + if events[slot] is not None: + events[slot].synchronize() + end = min(n_rows, start + window_rows) + if sequential: + self.fill_sequential(start, end, slots[slot][: end - start]) + else: + self.fill_window(order[start:end], slots[slot][: end - start]) + return end - start + + def copies(): + future = pool.submit(fill, 0, 0) + for window, start in enumerate( + range(0, n_rows, window_rows) + ): + slot = window % 2 + waited = time.perf_counter() + length = future.result() + self.stats["wait_s"] += time.perf_counter() - waited + if start + window_rows < n_rows: + future = pool.submit( + fill, start + window_rows, 1 - slot + ) + for a in range(0, length, self.batch_size): + with torch.cuda.stream(self.copy_stream): + batch = ( + slots[slot][a : min(length, a + self.batch_size)] + .to(self.device, non_blocking=True) + .float() + ) + if mean is not None: + batch.sub_(mean) + if scale is not None: + batch.div_(scale) + done = torch.cuda.Event() + done.record(self.copy_stream) + events[slot] = done + yield batch, done + + iterator = copies() + pending = None + try: + for batch, ready in iterator: + if pending is not None: + previous, event = pending + torch.cuda.current_stream(self.device).wait_event(event) + previous.record_stream( + torch.cuda.current_stream(self.device) + ) + yield previous + pending = batch, ready + if pending is not None: + batch, ready = pending + torch.cuda.current_stream(self.device).wait_event(ready) + batch.record_stream(torch.cuda.current_stream(self.device)) + yield batch + finally: + iterator.close() + pool.shutdown(wait=True, cancel_futures=True) + self.copy_stream.synchronize() diff --git a/thirdparty/faiss/c_api/CMakeLists.txt b/thirdparty/faiss/c_api/CMakeLists.txt index 065c67deb..e4de91f4b 100644 --- a/thirdparty/faiss/c_api/CMakeLists.txt +++ b/thirdparty/faiss/c_api/CMakeLists.txt @@ -29,6 +29,7 @@ set(FAISS_C_SRC MetaIndexes_c.cpp clone_index_c.cpp error_impl.cpp + factory_tools_c.cpp index_factory_c.cpp index_io_c.cpp impl/AuxIndexStructures_c.cpp @@ -108,6 +109,13 @@ if(NOT WIN32) endif() endif() +# Faiss headers (e.g. impl/FaissException.h) contain OpenMP pragmas, so the +# C API sources must be compiled with the same OpenMP flags as libfaiss. +find_package(OpenMP REQUIRED) +foreach(t faiss_c faiss_c_avx2 faiss_c_avx512 faiss_c_avx512_spr faiss_c_sve) + target_link_libraries(${t} PRIVATE OpenMP::OpenMP_CXX) +endforeach() + function(faiss_install_headers headers p) foreach(h ${headers}) get_filename_component(f ${h} DIRECTORY) diff --git a/thirdparty/faiss/c_api/IndexFlat_c.cpp b/thirdparty/faiss/c_api/IndexFlat_c.cpp index 1a87cb817..007fd1c12 100644 --- a/thirdparty/faiss/c_api/IndexFlat_c.cpp +++ b/thirdparty/faiss/c_api/IndexFlat_c.cpp @@ -125,6 +125,11 @@ int faiss_IndexRefineFlat_new( DEFINE_DESTRUCTOR(IndexRefineFlat) DEFINE_INDEX_DOWNCAST(IndexRefineFlat) +FaissIndex* faiss_IndexRefineFlat_base_index(FaissIndexRefineFlat* index) { + return reinterpret_cast( + reinterpret_cast(index)->base_index); +} + DEFINE_GETTER(IndexRefineFlat, int, own_fields) DEFINE_SETTER(IndexRefineFlat, int, own_fields) diff --git a/thirdparty/faiss/c_api/IndexFlat_c.h b/thirdparty/faiss/c_api/IndexFlat_c.h index dbefb5390..e4b284fb9 100644 --- a/thirdparty/faiss/c_api/IndexFlat_c.h +++ b/thirdparty/faiss/c_api/IndexFlat_c.h @@ -100,6 +100,10 @@ int faiss_IndexRefineFlat_new( FAISS_DECLARE_DESTRUCTOR(IndexRefineFlat) FAISS_DECLARE_INDEX_DOWNCAST(IndexRefineFlat) +/// Get a pointer to the base index. +/// The returned pointer is borrowed, do not free. +FaissIndex* faiss_IndexRefineFlat_base_index(FaissIndexRefineFlat* index); + FAISS_DECLARE_GETTER_SETTER(IndexRefineFlat, int, own_fields) /// factor between k requested in search and the k requested from diff --git a/thirdparty/faiss/c_api/IndexReplicas_c.cpp b/thirdparty/faiss/c_api/IndexReplicas_c.cpp index 37c78494d..f78bb3c65 100644 --- a/thirdparty/faiss/c_api/IndexReplicas_c.cpp +++ b/thirdparty/faiss/c_api/IndexReplicas_c.cpp @@ -56,6 +56,10 @@ int faiss_IndexReplicas_remove_replica( CATCH_AND_HANDLE } +int faiss_IndexReplicas_count(const FaissIndexReplicas* index) { + return reinterpret_cast(index)->count(); +} + FaissIndex* faiss_IndexReplicas_at(FaissIndexReplicas* index, int i) { auto replica = reinterpret_cast(index)->at(i); return reinterpret_cast(replica); diff --git a/thirdparty/faiss/c_api/IndexReplicas_c.h b/thirdparty/faiss/c_api/IndexReplicas_c.h index 179b18c86..0f58a6305 100644 --- a/thirdparty/faiss/c_api/IndexReplicas_c.h +++ b/thirdparty/faiss/c_api/IndexReplicas_c.h @@ -22,7 +22,7 @@ extern "C" { FAISS_DECLARE_CLASS_INHERITED(IndexReplicas, Index) FAISS_DECLARE_DESTRUCTOR(IndexReplicas) -FAISS_DECLARE_GETTER_SETTER(IndexReplicas, int, own_fields) +FAISS_DECLARE_GETTER_SETTER(IndexReplicas, int, own_indices) int faiss_IndexReplicas_new(FaissIndexReplicas** p_index, idx_t d); @@ -39,6 +39,8 @@ int faiss_IndexReplicas_remove_replica( FaissIndexReplicas* index, FaissIndex* replica); +int faiss_IndexReplicas_count(const FaissIndexReplicas* index); + FaissIndex* faiss_IndexReplicas_at(FaissIndexReplicas* index, int i); #ifdef __cplusplus diff --git a/thirdparty/faiss/c_api/IndexShards_c.cpp b/thirdparty/faiss/c_api/IndexShards_c.cpp index 9d9c95dfc..03084540e 100644 --- a/thirdparty/faiss/c_api/IndexShards_c.cpp +++ b/thirdparty/faiss/c_api/IndexShards_c.cpp @@ -59,6 +59,10 @@ int faiss_IndexShards_remove_shard(FaissIndexShards* index, FaissIndex* shard) { CATCH_AND_HANDLE } +int faiss_IndexShards_count(const FaissIndexShards* index) { + return reinterpret_cast(index)->count(); +} + FaissIndex* faiss_IndexShards_at(FaissIndexShards* index, int i) { auto shard = reinterpret_cast(index)->at(i); return reinterpret_cast(shard); diff --git a/thirdparty/faiss/c_api/IndexShards_c.h b/thirdparty/faiss/c_api/IndexShards_c.h index 8f4a4b7ab..35e31698e 100644 --- a/thirdparty/faiss/c_api/IndexShards_c.h +++ b/thirdparty/faiss/c_api/IndexShards_c.h @@ -37,6 +37,9 @@ int faiss_IndexShards_add_shard(FaissIndexShards* index, FaissIndex* shard); int faiss_IndexShards_remove_shard(FaissIndexShards* index, FaissIndex* shard); +/// Returns the number of sub-indices (shards) +int faiss_IndexShards_count(const FaissIndexShards* index); + FaissIndex* faiss_IndexShards_at(FaissIndexShards* index, int i); #ifdef __cplusplus diff --git a/thirdparty/faiss/c_api/VectorTransform_c.cpp b/thirdparty/faiss/c_api/VectorTransform_c.cpp index 1378f7cef..529c19aa1 100644 --- a/thirdparty/faiss/c_api/VectorTransform_c.cpp +++ b/thirdparty/faiss/c_api/VectorTransform_c.cpp @@ -16,6 +16,7 @@ extern "C" { DEFINE_DESTRUCTOR(VectorTransform) DEFINE_GETTER(VectorTransform, int, is_trained) +DEFINE_SETTER_STATIC(VectorTransform, bool, int, is_trained) DEFINE_GETTER(VectorTransform, int, d_in) @@ -62,10 +63,78 @@ void faiss_VectorTransform_reverse_transform( DEFINE_DESTRUCTOR(LinearTransform) +int faiss_LinearTransform_new_with( + FaissLinearTransform** p_vt, + int d_in, + int d_out, + int have_bias) { + try { + *p_vt = reinterpret_cast( + new faiss::LinearTransform( + d_in, d_out, static_cast(have_bias))); + } + CATCH_AND_HANDLE +} + DEFINE_GETTER(LinearTransform, int, have_bias) +DEFINE_SETTER_STATIC(LinearTransform, bool, int, have_bias) DEFINE_GETTER(LinearTransform, int, is_orthonormal) +void faiss_LinearTransform_set_is_orthonormal_flag( + FaissLinearTransform* vt, + int is_orthonormal) { + reinterpret_cast(vt)->is_orthonormal = + static_cast(is_orthonormal); +} + +DEFINE_GETTER(LinearTransform, int, verbose) +DEFINE_SETTER_STATIC(LinearTransform, bool, int, verbose) + +void faiss_LinearTransform_A( + const FaissLinearTransform* vt, + const float** A, + size_t* size) { + const std::vector& v = + reinterpret_cast(vt)->A; + if (A) { + *A = v.data(); + } + if (size) { + *size = v.size(); + } +} + +int faiss_LinearTransform_set_A(FaissLinearTransform* vt, const float* A) { + try { + auto lt = reinterpret_cast(vt); + lt->A.assign(A, A + static_cast(lt->d_out) * lt->d_in); + } + CATCH_AND_HANDLE +} + +void faiss_LinearTransform_b( + const FaissLinearTransform* vt, + const float** b, + size_t* size) { + const std::vector& v = + reinterpret_cast(vt)->b; + if (b) { + *b = v.data(); + } + if (size) { + *size = v.size(); + } +} + +int faiss_LinearTransform_set_b(FaissLinearTransform* vt, const float* b) { + try { + auto lt = reinterpret_cast(vt); + lt->b.assign(b, b + lt->d_out); + } + CATCH_AND_HANDLE +} + void faiss_LinearTransform_transform_transpose( const FaissLinearTransform* vt, idx_t n, diff --git a/thirdparty/faiss/c_api/VectorTransform_c.h b/thirdparty/faiss/c_api/VectorTransform_c.h index 6be8d2da3..fefcab823 100644 --- a/thirdparty/faiss/c_api/VectorTransform_c.h +++ b/thirdparty/faiss/c_api/VectorTransform_c.h @@ -14,6 +14,7 @@ * vectors Often these are pre-processing steps. */ +#include #include "faiss_c.h" #ifdef __cplusplus @@ -27,6 +28,9 @@ FAISS_DECLARE_DESTRUCTOR(VectorTransform) /// Getter for is_trained FAISS_DECLARE_GETTER(VectorTransform, int, is_trained) +/// Setter for is_trained +FAISS_DECLARE_SETTER(VectorTransform, int, is_trained) + /// Getter for input dimension FAISS_DECLARE_GETTER(VectorTransform, int, d_in) @@ -75,6 +79,19 @@ void faiss_VectorTransform_reverse_transform( FAISS_DECLARE_CLASS_INHERITED(LinearTransform, VectorTransform) FAISS_DECLARE_DESTRUCTOR(LinearTransform) +/** Create a generic linear transformation y = A * x + b. + * + * @param p_vt output, the new transform + * @param d_in input dimension + * @param d_out output dimension + * @param have_bias whether to use the bias term b + */ +int faiss_LinearTransform_new_with( + FaissLinearTransform** p_vt, + int d_in, + int d_out, + int have_bias); + /// compute x = A^T * (x - b) /// is reverse transform if A has orthonormal lines void faiss_LinearTransform_transform_transpose( @@ -86,12 +103,56 @@ void faiss_LinearTransform_transform_transpose( /// compute A^T * A to set the is_orthonormal flag void faiss_LinearTransform_set_is_orthonormal(FaissLinearTransform* vt); -/// Getter for have_bias -FAISS_DECLARE_GETTER(LinearTransform, int, have_bias) +/// Getter and setter for have_bias +FAISS_DECLARE_GETTER_SETTER(LinearTransform, int, have_bias) /// Getter for is_orthonormal FAISS_DECLARE_GETTER(LinearTransform, int, is_orthonormal) +/// Set the is_orthonormal flag directly, without checking A +void faiss_LinearTransform_set_is_orthonormal_flag( + FaissLinearTransform* vt, + int is_orthonormal); + +/// Getter and setter for verbose +FAISS_DECLARE_GETTER_SETTER(LinearTransform, int, verbose) + +/** Getter for the transformation matrix A (row-major, size d_out * d_in once + * set). The pointer is owned by the transform and is invalidated by + * faiss_LinearTransform_set_A and by training. + * + * @param A output, pointer to the matrix (may be NULL) + * @param size output, number of floats in the matrix (may be NULL) + */ +void faiss_LinearTransform_A( + const FaissLinearTransform* vt, + const float** A, + size_t* size); + +/** Setter for the transformation matrix A. + * + * @param A matrix to copy, row-major, size d_out * d_in + */ +int faiss_LinearTransform_set_A(FaissLinearTransform* vt, const float* A); + +/** Getter for the bias vector b (size d_out once set). The pointer is owned + * by the transform and is invalidated by faiss_LinearTransform_set_b and by + * training. + * + * @param b output, pointer to the vector (may be NULL) + * @param size output, number of floats in the vector (may be NULL) + */ +void faiss_LinearTransform_b( + const FaissLinearTransform* vt, + const float** b, + size_t* size); + +/** Setter for the bias vector b. It is only applied if have_bias is set. + * + * @param b vector to copy, size d_out + */ +int faiss_LinearTransform_set_b(FaissLinearTransform* vt, const float* b); + FAISS_DECLARE_CLASS_INHERITED(RandomRotationMatrix, VectorTransform) FAISS_DECLARE_DESTRUCTOR(RandomRotationMatrix) diff --git a/thirdparty/faiss/c_api/factory_tools_c.cpp b/thirdparty/faiss/c_api/factory_tools_c.cpp new file mode 100644 index 000000000..8950aa4aa --- /dev/null +++ b/thirdparty/faiss/c_api/factory_tools_c.cpp @@ -0,0 +1,58 @@ +/* + * 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. + */ + +// -*- c++ -*- + +#include "factory_tools_c.h" +#include +#include +#include +#include +#include +#include +#include "macros_impl.h" + +namespace { + +void copy_to_buffer(const std::string& s, char* buffer, size_t size) { + FAISS_THROW_IF_NOT_FMT( + s.size() < size, + "buffer of size %zu is too small for factory string of length %zu", + size, + s.size()); + std::memcpy(buffer, s.c_str(), s.size() + 1); +} + +} // namespace + +int faiss_reverse_index_factory( + const FaissIndex* index, + char* buffer, + size_t size) { + try { + copy_to_buffer( + faiss::reverse_index_factory( + reinterpret_cast(index)), + buffer, + size); + } + CATCH_AND_HANDLE +} + +int faiss_reverse_index_binary_factory( + const FaissIndexBinary* index, + char* buffer, + size_t size) { + try { + copy_to_buffer( + faiss::reverse_index_factory( + reinterpret_cast(index)), + buffer, + size); + } + CATCH_AND_HANDLE +} diff --git a/thirdparty/faiss/c_api/factory_tools_c.h b/thirdparty/faiss/c_api/factory_tools_c.h new file mode 100644 index 000000000..89776a277 --- /dev/null +++ b/thirdparty/faiss/c_api/factory_tools_c.h @@ -0,0 +1,58 @@ +/* + * 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. + */ + +// -*- c -*- + +#ifndef FAISS_FACTORY_TOOLS_C_H +#define FAISS_FACTORY_TOOLS_C_H + +#include + +#include "IndexBinary_c.h" +#include "Index_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Get the factory string that describes the given index, by writing it to + * the given character buffer as a NUL-terminated string. + * + * The string is empty if the index type is not supported. + * + * @param index the index to describe + * @param buffer output buffer + * @param size size of the output buffer, including the terminating NUL + * @return 0 on success, otherwise an error code if the buffer is too small to + * hold the full string, in which case the buffer is left untouched + */ +int faiss_reverse_index_factory( + const FaissIndex* index, + char* buffer, + size_t size); + +/** Get the factory string that describes the given binary index, by writing + * it to the given character buffer as a NUL-terminated string. + * + * The string is empty if the index type is not supported. + * + * @param index the binary index to describe + * @param buffer output buffer + * @param size size of the output buffer, including the terminating NUL + * @return 0 on success, otherwise an error code if the buffer is too small to + * hold the full string, in which case the buffer is left untouched + */ +int faiss_reverse_index_binary_factory( + const FaissIndexBinary* index, + char* buffer, + size_t size); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/faiss/c_api/gpu/GpuIndex_c.cpp b/thirdparty/faiss/c_api/gpu/GpuIndex_c.cpp index 92d675a2e..65953dfc2 100644 --- a/thirdparty/faiss/c_api/gpu/GpuIndex_c.cpp +++ b/thirdparty/faiss/c_api/gpu/GpuIndex_c.cpp @@ -14,3 +14,7 @@ using faiss::gpu::GpuIndexConfig; DEFINE_GETTER(GpuIndexConfig, int, device) + +int faiss_GpuIndex_getDevice(const FaissGpuIndex* index) { + return reinterpret_cast(index)->getDevice(); +} diff --git a/thirdparty/faiss/c_api/gpu/GpuIndex_c.h b/thirdparty/faiss/c_api/gpu/GpuIndex_c.h index 4b7aab061..0c2b42bc3 100644 --- a/thirdparty/faiss/c_api/gpu/GpuIndex_c.h +++ b/thirdparty/faiss/c_api/gpu/GpuIndex_c.h @@ -22,6 +22,8 @@ FAISS_DECLARE_GETTER(GpuIndexConfig, int, device) FAISS_DECLARE_CLASS_INHERITED(GpuIndex, Index) +int faiss_GpuIndex_getDevice(const FaissGpuIndex* index); + #ifdef __cplusplus } #endif diff --git a/thirdparty/faiss/cmake/FindLibAIO.cmake b/thirdparty/faiss/cmake/FindLibAIO.cmake new file mode 100644 index 000000000..2bb002c9f --- /dev/null +++ b/thirdparty/faiss/cmake/FindLibAIO.cmake @@ -0,0 +1,23 @@ +# 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. + +# Finds libaio and defines the imported target LibAIO::LibAIO. Installed next +# to faiss-config.cmake, which finds libaio with it for a static Faiss. + +find_path(LIBAIO_INCLUDE_DIR NAMES libaio.h) +find_library(LIBAIO_LIBRARY NAMES aio) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LibAIO + REQUIRED_VARS LIBAIO_LIBRARY LIBAIO_INCLUDE_DIR) + +if(LibAIO_FOUND AND NOT TARGET LibAIO::LibAIO) + add_library(LibAIO::LibAIO UNKNOWN IMPORTED) + set_target_properties(LibAIO::LibAIO PROPERTIES + IMPORTED_LOCATION "${LIBAIO_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${LIBAIO_INCLUDE_DIR}") +endif() + +mark_as_advanced(LIBAIO_INCLUDE_DIR LIBAIO_LIBRARY) diff --git a/thirdparty/faiss/cmake/faiss-config.cmake.in b/thirdparty/faiss/cmake/faiss-config.cmake.in index 43ea9d4c8..86ed55f33 100644 --- a/thirdparty/faiss/cmake/faiss-config.cmake.in +++ b/thirdparty/faiss/cmake/faiss-config.cmake.in @@ -4,4 +4,15 @@ # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. +# A static Faiss is linked with its private dependencies by the consumer. +if("@FAISS_LIBRARY_TYPE@" STREQUAL "STATIC_LIBRARY") + include(CMakeFindDependencyMacro) + find_dependency(OpenMP) + if("@FAISS_ENABLE_DISK_IVF@") + list(PREPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}") + find_dependency(LibAIO) + list(POP_FRONT CMAKE_MODULE_PATH) + endif() +endif() + include("${CMAKE_CURRENT_LIST_DIR}/faiss-targets.cmake") diff --git a/thirdparty/faiss/cmake/thirdparty/fetch_rapids.cmake b/thirdparty/faiss/cmake/thirdparty/fetch_rapids.cmake index 8bb15c8b8..7c0f4f79a 100644 --- a/thirdparty/faiss/cmake/thirdparty/fetch_rapids.cmake +++ b/thirdparty/faiss/cmake/thirdparty/fetch_rapids.cmake @@ -15,7 +15,7 @@ # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= -set(RAPIDS_VERSION "26.06") +set(RAPIDS_VERSION "26.10") set(rapids-cmake-version ${RAPIDS_VERSION}) set(rapids-cmake-branch "release/${RAPIDS_VERSION}") diff --git a/thirdparty/faiss/cmake/toolchains/riscv64-linux-gnu.cmake b/thirdparty/faiss/cmake/toolchains/riscv64-linux-gnu.cmake index 2914d7e0d..bf26922d3 100644 --- a/thirdparty/faiss/cmake/toolchains/riscv64-linux-gnu.cmake +++ b/thirdparty/faiss/cmake/toolchains/riscv64-linux-gnu.cmake @@ -3,18 +3,23 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -# Cross-compilation toolchain for RISC-V 64-bit (lp64d ABI) on Ubuntu/Debian. +# Cross-compilation toolchain for RISC-V 64-bit (lp64d ABI) on Ubuntu 24.04. # -# Requires these packages installed on the build host: -# gcc-riscv64-linux-gnu g++-riscv64-linux-gnu +# Requires: +# gcc-14-riscv64-linux-gnu +# g++-14-riscv64-linux-gnu # -# Target libraries (e.g. libopenblas-dev:riscv64) are installed via apt -# multiarch to /usr/lib/riscv64-linux-gnu/. CMake's ONLY find-root mode -# searches ${CMAKE_FIND_ROOT_PATH}/usr/lib/riscv64-linux-gnu/ (via the -# compiler's multiarch tuple), so the CI script creates a symlink: +# Target libraries: +# libopenblas-dev:riscv64 +# +# Ubuntu multiarch installs target libraries into: +# /usr/lib/riscv64-linux-gnu +# +# The CI creates: # /usr/riscv64-linux-gnu/usr/lib/riscv64-linux-gnu -# -> /usr/lib/riscv64-linux-gnu -# before invoking cmake. +# -> /usr/lib/riscv64-linux-gnu +# +# so CMake can locate target libraries while using ONLY root mode. set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR riscv64) @@ -24,12 +29,20 @@ set(CMAKE_SYSTEM_PROCESSOR riscv64) set(CMAKE_C_COMPILER riscv64-linux-gnu-gcc-14) set(CMAKE_CXX_COMPILER riscv64-linux-gnu-g++-14) -# Cross-compiler sysroot provided by gcc-riscv64-linux-gnu. +# Do NOT set CMAKE_SYSROOT here. Ubuntu's cross toolchain resolves target +# libraries through its built-in paths (/usr/riscv64-linux-gnu/lib). Passing +# --sysroot=/usr/riscv64-linux-gnu makes ld prepend the sysroot to the +# absolute paths inside libc6-dev-riscv64-cross's libc.so linker script, +# producing doubled paths such as +# /usr/riscv64-linux-gnu/usr/riscv64-linux-gnu/lib/libc.so.6 +# and failing the CMake compiler check at link time. + set(CMAKE_FIND_ROOT_PATH /usr/riscv64-linux-gnu) -# Never look for host-side tools (cmake, python, …) inside the sysroot. +# Never search host binaries inside sysroot. set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -# Look for target libraries/headers/packages only inside the sysroot. + +# Target libraries/headers/packages only. set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/thirdparty/faiss/conda/faiss-gpu-cuvs/meta.yaml b/thirdparty/faiss/conda/faiss-gpu-cuvs/meta.yaml index adcfc9cee..8608f260c 100644 --- a/thirdparty/faiss/conda/faiss-gpu-cuvs/meta.yaml +++ b/thirdparty/faiss/conda/faiss-gpu-cuvs/meta.yaml @@ -1,4 +1,5 @@ # Copyright (c) Facebook, Inc. and its affiliates. +# Copyright 2026 Arm Limited and/or its affiliates # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. @@ -46,7 +47,7 @@ outputs: - {{ compiler('cxx') }} =12.4 - sysroot_linux-64 =2.17 # [linux64] - llvm-openmp # [osx] - - cmake >=3.30.4 + - cmake >=4.0 - make =4.2 # [not win] - _openmp_mutex =4.5=2_kmp_llvm # [x86_64] - mkl >=2024.2.2,<2026 # [x86_64] @@ -62,19 +63,19 @@ outputs: - _openmp_mutex =4.5=2_kmp_llvm # [x86_64] - mkl >=2024.2.2,<2026 # [x86_64] - openblas =0.3.34 # [not x86_64] - - libcuvs =26.06 + - libcuvs =26.10 - cuda-version {{ cuda_constraints }} - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - libsvs-runtime =0.5.0 # [x86_64 and linux] run: - _openmp_mutex =4.5=2_kmp_llvm # [x86_64] - mkl >=2024.2.2,<2026 # [x86_64] - - openblas =0.3.34 # [not x86_64] + - openblas =0.3.34 openmp_* # [not x86_64] - cuda-cudart {{ cuda_constraints }} - libcublas {{ libcublas_constraints }} - - libcuvs =26.06 + - libcuvs =26.10 - cuda-version {{ cuda_constraints }} - libnvjitlink - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - libsvs-runtime =0.5.0 # [x86_64 and linux] test: requires: - conda-build @@ -83,6 +84,7 @@ outputs: - test -f $PREFIX/lib/libfaiss_avx2$SHLIB_EXT # [x86_64 and not win] - conda inspect linkages -p $PREFIX $PKG_NAME # [not win] - conda inspect objects -p $PREFIX $PKG_NAME # [osx] + - python -c "import ctypes; lib = ctypes.CDLL('libopenblas.so.0'); assert lib.openblas_get_parallel() == 2" # [linux and not x86_64] - name: faiss-gpu-cuvs script: build-pkg.sh # [x86_64 and not win and not osx] @@ -96,7 +98,7 @@ outputs: - {{ compiler('cxx') }} =14.2 - sysroot_linux-64 =2.34 # [linux64] - swig =4.0 - - cmake >=3.30.4 + - cmake >=4.0 - make =4.2 # [not win] - _openmp_mutex =4.5=2_kmp_llvm # [x86_64] - mkl >=2024.2.2,<2026 # [x86_64] @@ -108,6 +110,7 @@ outputs: - numpy >=2.0,<2.3 - setuptools - {{ pin_subpackage('libfaiss', exact=True) }} + - openblas =0.3.34 openmp_* # [not x86_64] run: - mkl >=2024.2.2,<2026 # [x86_64] - _openmp_mutex =4.5=2_kmp_llvm # [x86_64] @@ -141,4 +144,7 @@ outputs: - test_cpu_dispatch.sh # [linux64] source_files: - tests/ - - faiss/gpu/test/ + - faiss/ # faiss/gpu/test/, and the sources that tests/test_simd_registry.py checks + - benchs/e_means/dino_data.py + - benchs/e_means/ssd_streaming.py + - benchs/e_means/lloyd.py diff --git a/thirdparty/faiss/conda/faiss-gpu/meta.yaml b/thirdparty/faiss/conda/faiss-gpu/meta.yaml index 9cee70b2b..b35c4d6f7 100644 --- a/thirdparty/faiss/conda/faiss-gpu/meta.yaml +++ b/thirdparty/faiss/conda/faiss-gpu/meta.yaml @@ -1,4 +1,5 @@ # Copyright (c) Facebook, Inc. and its affiliates. +# Copyright 2026 Arm Limited and/or its affiliates # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. @@ -60,14 +61,14 @@ outputs: - cuda-toolkit {{ cudatoolkit }} host: - mkl >=2024.2.2,<2026 # [x86_64] - - openblas =0.3.34 # [not x86_64] - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - openblas =0.3.34 openmp_* # [not x86_64] + - libsvs-runtime =0.5.0 # [x86_64 and linux] run: - mkl >=2024.2.2,<2026 # [x86_64] - - openblas =0.3.34 # [not x86_64] + - openblas =0.3.34 openmp_* # [not x86_64] - cuda-cudart {{ cuda_constraints }} - libcublas {{ libcublas_constraints }} - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - libsvs-runtime =0.5.0 # [x86_64 and linux] test: requires: - conda-build @@ -76,6 +77,7 @@ outputs: - test -f $PREFIX/lib/libfaiss_avx2$SHLIB_EXT # [x86_64 and not win] - conda inspect linkages -p $PREFIX $PKG_NAME # [not win] - conda inspect objects -p $PREFIX $PKG_NAME # [osx] + - python -c "import ctypes; lib = ctypes.CDLL('libopenblas.so.0'); assert lib.openblas_get_parallel() == 2" # [linux and not x86_64] - name: faiss-gpu script: build-pkg.sh # [x86_64 and not win and not osx] @@ -102,6 +104,7 @@ outputs: - setuptools - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win] - {{ pin_subpackage('libfaiss', exact=True) }} + - openblas =0.3.34 openmp_* # [not x86_64] run: - mkl >=2024.2.2,<2026 # [x86_64] - python {{ python }} @@ -132,4 +135,7 @@ outputs: - test_cpu_dispatch.sh # [linux64] source_files: - tests/ - - faiss/gpu/test/ + - faiss/ # faiss/gpu/test/, and the sources that tests/test_simd_registry.py checks + - benchs/e_means/dino_data.py + - benchs/e_means/ssd_streaming.py + - benchs/e_means/lloyd.py diff --git a/thirdparty/faiss/conda/faiss/meta.yaml b/thirdparty/faiss/conda/faiss/meta.yaml index ace4d5e22..b560ec86b 100644 --- a/thirdparty/faiss/conda/faiss/meta.yaml +++ b/thirdparty/faiss/conda/faiss/meta.yaml @@ -1,4 +1,5 @@ # Copyright (c) Facebook, Inc. and its affiliates. +# Copyright 2026 Arm Limited and/or its affiliates # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. @@ -60,7 +61,7 @@ outputs: host: - python {{ python }} - libcxx =20.1.1 # [osx and arm64] - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - libsvs-runtime =0.5.0 # [x86_64 and linux] {% if PY_VER == '3.10' or PY_VER == '3.11' %} - mkl >=2024.2.2,<2026 # [x86_64] - python_abi <3.12 @@ -69,12 +70,12 @@ outputs: - mkl >=2024.2.2,<2026 # [x86_64 and win] - python_abi =3.12 {% endif %} - - openblas =0.3.34 # [linux and not x86_64] + - openblas =0.3.34 openmp_* # [linux and not x86_64] - libopenblas =0.3.34 # [osx] run: - python {{ python }} - libcxx =20.1.1 # [osx and arm64] - - libsvs-runtime =0.4.0 # [x86_64 and linux] + - libsvs-runtime =0.5.0 # [x86_64 and linux] {% if PY_VER == '3.10' or PY_VER == '3.11' %} - mkl >=2024.2.2,<2026 # [x86_64] - python_abi <3.12 @@ -83,7 +84,7 @@ outputs: - mkl >=2024.2.2,<2026 # [x86_64 and win] - python_abi =3.12 {% endif %} - - openblas =0.3.34 # [linux and not x86_64] + - openblas =0.3.34 openmp_* # [linux and not x86_64] - libopenblas =0.3.34 # [osx] test: requires: @@ -95,6 +96,7 @@ outputs: - test -f $PREFIX/lib/MetalDistance.metallib # [osx and arm64] - conda inspect linkages -p $PREFIX $PKG_NAME # [not win] - conda inspect objects -p $PREFIX $PKG_NAME # [osx] + - python -c "import ctypes; lib = ctypes.CDLL('libopenblas.so.0'); assert lib.openblas_get_parallel() == 2" # [linux and not x86_64] - name: faiss-cpu script: build-pkg.sh # [x86_64 and not win and not osx] @@ -128,6 +130,7 @@ outputs: - numpy >=2.0,<3.0 - setuptools - {{ pin_subpackage('libfaiss', exact=True) }} + - openblas =0.3.34 openmp_* # [linux and not x86_64] - libcxx =20.1.1 # [osx and arm64] - _openmp_mutex =4.5=2_kmp_llvm # [x86_64 and not win] {% if PY_VER == '3.10' or PY_VER == '3.11' %} @@ -158,7 +161,8 @@ outputs: requires: - numpy >=2.0,<3.0 - scipy - - pytorch-cpu >=2.7 # [not win] + - pytest # [arm64] + - pytorch-cpu >=2.7 # [not win and not aarch64] - pytorch >=2.7 # [win] {% if PY_VER == '3.10' or PY_VER == '3.11' %} - mkl >=2024.2.2,<2026 # [x86_64] @@ -169,10 +173,15 @@ outputs: - python_abi =3.12 {% endif %} commands: - - python -X faulthandler -m unittest discover -v -s tests/ -p "test_*" - - python -X faulthandler -m unittest discover -v -s tests/ -p "torch_*" + - FAISS_METALLIB_PATH="$PREFIX/lib" python -X faulthandler -m pytest tests/ --ignore=tests/external_module_test.py -q -k 'not test_update_codebooks_with_double and not (TestProductLocalSearchQuantizer and test_lut) and not test_compute_GT_gpu and not test_compute_GT_ip_gpu' # [arm64] + - python -X faulthandler -m unittest discover -v -s tests/ -p "test_*" # [not arm64] + - python -X faulthandler -m unittest discover -v -s tests/ -p "torch_*" # [not aarch64] - sh test_cpu_dispatch.sh # [linux64] files: - test_cpu_dispatch.sh # [linux64] source_files: - tests/ + - faiss/ # sources that tests/test_simd_registry.py checks + - benchs/e_means/dino_data.py + - benchs/e_means/ssd_streaming.py + - benchs/e_means/lloyd.py diff --git a/thirdparty/faiss/contrib/README.md b/thirdparty/faiss/contrib/README.md index 8b9052c44..25b7190fb 100644 --- a/thirdparty/faiss/contrib/README.md +++ b/thirdparty/faiss/contrib/README.md @@ -68,6 +68,11 @@ Contains: - a 2-level clustering routine and a function that can apply it to train an IndexIVF +### e_means + +Mini-batch k-means with FP32 centroid state and exponential moving averages. +See the [E-means documentation](e_means/README.md) for the public `Emeans` API. + ### big_batch_search.py Search IVF indexes with one centroid after another. Useful for large diff --git a/thirdparty/faiss/contrib/e_means/README.md b/thirdparty/faiss/contrib/e_means/README.md new file mode 100644 index 000000000..0f8e9331e --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/README.md @@ -0,0 +1,572 @@ +

+ e-means +

+ +# e-means: outperforming k-means in one-tenth the epochs + +[arXiv](https://arxiv.org/abs/2611.09501) · Blog post link (soon) · [Browser demo](https://e-means.github.io/playground.html) · Reproduction scripts ([`benchs/e_means`](https://github.com/facebookresearch/faiss/tree/main/benchs/e_means)) + +Code contributors: Gergely Szilvasy, Swann Bessa, Matthijs Douze + + +## What e-means is + +A modern, robust replacement for k-means developed at Meta FAIR. e-means delivers a **~10× speedup in epochs and wall-clock** while achieving **lower loss** compared to Lloyd's k-means, with no additional hyperparameters. e-means uses a mini-batch update rule specialized for the k-means problem, based on exponential moving averages. + +## When to use it + +e-means exhibits robustness to a large array of scales, datasets and dimensions (see [paper](https://arxiv.org/abs/2611.09501)). On most k-means applications, e-means can achieve the same loss in about 10 times fewer epochs. + +![e-means against Lloyd's k-means, in epochs, CPU time and GPU time](figure/readme_figure_v6.png) + +## Citing e-means + +If you use e-means, please cite our paper using the following BibTeX entry: + +```bibtex +@misc{bessa2026emeans, + title = {{e-means}: outperforming {k-means} (in one-tenth the epochs)}, + author = {Bessa, Swann and Mazar{\'e}, Pierre-Emmanuel and Szilvasy, Gergely and + Touvron, Hugo and Picard, David and Douze, Matthijs and J{\'e}gou, Herv{\'e}}, + year = {2026}, + note = {Preprint}, + url = {https://arxiv.org/abs/2611.09501} +} +``` + +## Installation + + +e-means ships inside faiss, and with faiss alone you can run e-means on CPU. On GPU, e-means runs through PyTorch with Triton/CuTe kernels and never calls faiss, so the CPU build of faiss is enough on a GPU machine too. For GPU runs, install CUDA-enabled PyTorch using the [official instructions](https://pytorch.org/get-started/locally/): its Linux CUDA builds also install Triton. For the CuTe kernels on Hopper GPUs (SM90: H100 and H200), install CUTLASS DSL 4.7.1 or later and QuACK 0.6.5 or later. `cuda-cccl[cu13]` is optional but recommended for grouping performance. If you install only the Triton packages, select `assignment_backend="triton"` explicitly. + +```bash +pip install faiss-cpu # enough on a CPU, and also for GPU runs +# GPU runs: CUDA-enabled PyTorch from https://pytorch.org/get-started/locally/ (it brings Triton) +python -m pip install "nvidia-cutlass-dsl[cu13]>=4.7.1" "quack-kernels[cu13]>=0.6.5" "cuda-python>=13,<14" # CuTe, SM90 +python -m pip install "cuda-cccl[cu13]" # optional, recommended for grouping performance +``` + +```python +from faiss.contrib.e_means import NumpyEmeans +``` + +| Package | What it adds | +|---|---| +| faiss-cpu and NumPy | NumPy arrays on CPUs | +| PyTorch | data held as PyTorch tensors, on a CPU or a GPU | +| The three CuTe packages above | the fastest kernels, H100 and H200 only (`assignment_backend="cute"`) | +| `cuda-cccl` (optional) | faster grouping inside the CuTe kernels. Without it, e-means warns once and uses a PyTorch fallback | +| Triton | fast kernels on other recent NVIDIA GPUs, A100 or newer (`assignment_backend="triton"`) | + +GPU kernels compile the first time they run, which takes a few seconds. + +## Quick start + +Instantiate the `Emeans` class with the dimension `d` and the number of clusters `k`. Using the `train` method, train it on your vectors, and read the centroids and dataset labels returned. To assign additional vectors, use the `assign` method. On GPU, we provide Triton, CuTe, and PyTorch backends for training and assignment to the nearest centroid. On CPU, we rely on the faiss primitive `faiss.knn` with `k=1` (`k=2` for cost-based revival) for NumPy arrays, and Pytorch for CPU tensors. We highlight that the Triton and CuTe backends are much faster than the PyTorch backend, which is a fallback for GPUs not supporting Triton and CuTe. + +On a CPU: + +```python +import numpy as np +from faiss.contrib.e_means import NumpyEmeans + +x = np.random.rand(200_000, 64).astype("float32") # 200,000 vectors of dimension 64 + +em = NumpyEmeans(64, 500) # 500 clusters, 5 passes over the data by default +centroids, labels = em.train(x) # (500, 64) float32, and each vector's cluster +x_new = np.random.rand(100_000, 64).astype("float32") +distances, new_labels = em.assign(x_new) # the nearest centroid of new vectors +``` + +The labels come from the last training epoch, at no extra cost. They are not always each vector's nearest final centroid, because the centroids still moved during that last epoch. For exact nearest-centroid labels, call `assign` on the training vectors too. In practice, for a fixed FLOP budget T, it is better to run e-means on T epochs and use the returned labels, rather than running e-means on T-1 epochs and calling `assign` on the training vectors (which costs as many FLOPs as one epoch). + +On a GPU, pass a PyTorch tensor that is already on the GPU: e-means never moves data from CPU to GPU for you. +e-means picks the fastest kernels that can run your input: CuTe on an H100 and H200 for BF16 data, Triton on other recent NVIDIA GPUs, PyTorch otherwise. + +```python +import torch +from faiss.contrib.e_means import Emeans + +xg = torch.from_numpy(x).cuda().to(torch.bfloat16) # on the GPU, in 16-bit (BF16) +em = Emeans(64, 1024) +centroids, labels = em.train(xg) +print(em.recipe["assignment_backend"]) # the kernels it picked, "cute" on an H100 +``` + +To choose a backend explicitly, pass `assignment_backend="cute"`, `"triton"` or `"native"` (PyTorch). Both automatic and explicit selection raise an error if the selected backend cannot run or its required software is missing, broken or incompatible. Read `em.recipe["assignment_backend"]` to see which backend was selected. + +## Parameters + +By default, you only need to configure the number of training passes (`nepochs`). Hyperparameters such as batch size and initial step size are derived automatically using empirical scaling laws. + +### Core configuration + +- **`nepochs`** (`float`, default: `5`): Number of training passes. Fractional values (such as 2.5) are supported. A value of 5 is typically sufficient to beat Lloyd's loss at convergence. +- **`batch_law`** (`str`, default: `"auto"`): Determines how batch size is calculated: + - `"auto"`: Picks `"quality"` at low dimension and `"throughput"` otherwise (see the note below). + - `"throughput"`: Optimized for training speed. + - `"quality"`: Uses batches roughly $8\times$ smaller than `"throughput"`. This yields lower final MSE, though training may be slower on small datasets. + +> **Note on low dimension.** For $d \le 16$, e-means uses the quality batch by default, and for $d \le 2$ it also turns cluster revival off in the classes with mass-based revival (see Cluster revival). We found that the quality batch has a bigger advantage at low dimension, and that cluster revival is detrimental at $d = 2$. With several processes (`DistributedEmeans`, `EmeansShardedCentroids`), the batch must still divide by the number of processes, and on small low-dimension problems the quality batch may not: `begin` then raises, naming the law and the batch. Pass `batch_law="throughput"`, or a `batch_size` divisible by the number of processes. + +### Manual overrides + +- **`batch_size`** (`int`, optional): Overrides the scaling law. Setting this manually automatically adjusts `alpha0` via equation (3). +- **`alpha0`** (`float`, optional): Overrides the calculated initial step size. +- **`max_points_per_centroid`** (`int`, optional): Caps the training set, as in `faiss.Kmeans`. When `train` gets more than `max_points_per_centroid * k` vectors, it trains on a random subset of that many (drawn from `seed`) and returns label -1 for the others. The scaling laws then use the subset size. + +### Scaling laws + +| Index | Law | Formula | +|---|---|---| +| (1) | Batch size (`"throughput"`) | $B = 0.035134 \cdot k^{0.134749} \cdot n^{0.876473} \cdot T^{0.813344}$ | +| (2) | Batch size (`"quality"`) | $B = 0.00439175 \cdot k^{0.134749} \cdot n^{0.876473} \cdot T^{0.813344}$ | +| (3) | Starting step size ($\alpha_0$) | $\alpha_0 = 0.8244 \cdot k^{-0.4617} \cdot B^{0.9003} \cdot n^{-0.4498} \cdot T^{-0.1057}$ | + +Variables: $n$ is the total number of vectors, $k$ is the cluster count, $T$ is the number of passes +(`nepochs`), and $B$ is the batch size. + +Constraints: + +- The computed batch size $B$ from (1) or (2) is rounded to the nearest power of two and capped at + $\approx n/2$. The batch thus grows with the budget in jumps, so quality is not monotone across a + rounding boundary (e.g. n=4M, k=16,384: the batch doubles between nepochs 2.8 and 3). +- The step size $\alpha_0$ from (3) is clamped to the range $[0.0001, 1.0]$. + +### Examples + +These examples use the tensor `xg` from the GPU quickstart. + +```python +# 1. Custom pass count (default scaling laws applied) +em = Emeans(64, 1024, nepochs=3) +em.train(xg) +print(em.recipe["batch_size"], em.recipe["alpha0"], em.recipe["steps_per_pass"]) + +# 2. Fractional passes +em = Emeans(64, 1024, nepochs=2.5) + +# 3. Quality mode (uses Eq. 2; yields ~8x smaller batch size) +em = Emeans(64, 1024, batch_law="quality") + +# 4. Manual batch size (alpha0 adjusts automatically via Eq. 3) +em = Emeans(64, 1024, batch_size=8192) + +# 5. Full manual override +em = Emeans(64, 1024, batch_size=8192, alpha0=0.05) +``` + +## Settings and results in the `Emeans` class + +Settings are the arguments you pass to `Emeans` when you create the model. Only `d` and `k` are +required. `help(Emeans)` describes every argument and method in full. + +For conversion, use `QuantizedEmeans(d, k, quantizer=q)`; see "Data precision". + +```python +em = Emeans(64, 1024, nepochs=5, seed=0) # d and k, then any of the settings below +``` + +| Setting | Default | What it does | +|---|---|---| +| `d` | required | Dimension of the vectors | +| `k` | required | Number of clusters | +| `nepochs` | `5` | Passes over the data, can be fractional | +| `assignment_backend` | `"auto"` | Kernels that find the nearest centroids. Auto picks CuTe in H100/H200 BF16, else Triton, else PyTorch | +| `batch_law` | `"auto"` | Law that picks the batch size: `"throughput"` (equation 1), `"quality"` (equation 2), or `"auto"`, which picks between them (see the note on low dimension above) | +| `batch_size` | chosen by the batch law | Batch size. If omitted, chosen by equation (1) or (2) | +| `alpha0` | equation (3) | Starting step size. If omitted, computed from the batch size by equation (3) | +| `unused_threshold` | `None` | Revives clusters whose running count falls below this fraction of the mean. `None` uses cost-based revival for local, replicated and exhaustive centroid-sharded runs with more than one global centroid, across their admitted floating and encoded representations (see Cluster revival below). Pass a number to use mass-based revival. Caller-driven replicated/sharded loops retain final-pass labels without local train closing handover. | +| `max_points_per_centroid` | `None` | Trains on a random subset of `max_points_per_centroid * k` vectors when there are more; the others get label -1. `None` trains on all of them | +| `seed` | `1234` | Seeds the starting centroids, the shuffling and the revivals | +| `verbose` | `False` | Prints one line of statistics per pass | +| `assignment_chunk_size` | depends on the input | Rows searched at once. Memory and speed impact only | +| `centroid_chunk_size` | `4096` | Centroids searched at once, PyTorch kernels only | +| `capture_assignments` | `True` | Keeps each vector's label from the last pass (8 bytes per vector) | +| `spherical` | `False` | Keeps the centroids on the unit sphere, for cosine similarity | + +Results are what you read from the model once it is trained. + +```python +centroids, labels = em.train(xg) +print(em.centroids.shape, em.recipe["batch_size"]) # two of the results below +``` + +| Result | What it is | +|---|---| +| `em.train(x)` | Returns the centroids and each training vector's last-pass label | +| `em.centroids` | The centroids, as 32-bit floats, on the same device as the input | +| `em.assignments` | The same last-pass labels, kept on the model | +| `em.assign(x)` | Each vector's nearest centroid and its squared distance (in spherical mode, its similarity, where higher is closer) | +| `em.obj` | The error of each pass, measured while the centroids move (not the final error) | +| `em.iteration_stats` | Per pass: error, time, imbalance and number of splits | +| `em.recipe` | The batch size, step size, steps per pass, rows per pass and kernels actually used | +| `em.n_splits` | How many dead clusters were revived | + +## On the CPU + +e-means runs on the CPU whenever your data is a NumPy array or a PyTorch tensor on the CPU. It is convenient for small problems and for trying things out. GPUs are much faster, so we recommend using them for configurations where $n \times k > 10^{10}$, where $n$ is the dataset size and $k$ is the number of clusters. There are two paths depending on the input's type: + +- **NumPy arrays:** each vector's nearest centroid is found with `faiss.knn`, in 32-bit floats. Other float types, such as `float64`, are converted first, which makes a 32-bit copy. +- **PyTorch tensors on the CPU:** also computed in 32-bit floats with a dedicated PyTorch CPU path. 16-bit tensors (FP16, BF16) are accepted, but converted to 32-bit. + +Note that on CPU the `quantizer` parameter must remain `None`. Also, faiss and PyTorch use all available cores by default. To use fewer, call `faiss.omp_set_num_threads(n)` and `torch.set_num_threads(n)`. + +## On GPU: four cases + +What to do on GPU depends on what fits in its memory: the data, the centroids, or neither. If you want more speed, you can also use more GPUs. + +| Your situation | What to use | +|---|---| +| The data and the centroids both fit on 1 GPU | `train(x)`, with `x` on 1 GPU, see "Data and centroids fit on 1 GPU" | +| The data does not fit on 1 GPU, the centroids do | the batch loop, see "Data too big for GPU memory" | +| The two previous cases, but you want faster training | several GPUs with replicated centroids, see `DistributedEmeans` in "Several GPUs"| +| The centroids do not fit on 1 GPU | several GPUs with sharded centroids, see `EmeansShardedCentroids` in "Several GPUs" | + +### Data and centroids fit on 1 GPU +Put the data on the GPU and call `train`. The last pass keeps every vector's label (8 bytes per vector, turned off by `capture_assignments=False`), and training ends with the exact closing mean. The GPU must hold the +data, the centroids with their running sums, the labels and a small working buffer. CuTe keeps up to four row-workspace bindings per prepared centroid set (about 4 × chunk × d × 2 bytes, ~0.5 GiB at d = 3072 with the default chunk); a CUDA graph captured by the caller must keep the bindings it captured alive until it is reset. + +```python +import numpy as np, torch +from faiss.contrib.e_means import Emeans + +xg = torch.from_numpy(x).cuda() # your float32 NumPy array, copied to the GPU once +assert torch.isfinite(xg).all() # the GPU path does not check for NaN or infinity +em = Emeans(64, 1024, nepochs=5) +centroids, labels = em.train(xg) # both come back on the GPU +print(em.recipe["assignment_backend"], em.recipe["batch_size"]) # kernels used, batch size +``` + +Two things to know: + +- **The data must already be on the GPU.** A NumPy array or a CPU tensor trains on the CPU instead. +- **GPU data is not checked for NaN or infinity.** One bad value does not stop training and can go + unnoticed. In our tests, one infinite coordinate left a few broken centroids while the reported + loss looked normal. Check your data first: `assert torch.isfinite(xg).all()`. + + +### Data too big for memory + +This applies when your data does not fit in the memory of the device you train on (the GPU, or the RAM on a CPU), but the centroids do. `train` needs all the data as one array or tensor on that device. When your data does not fit on the device, you feed the batches yourself, and the model runs the same algorithm: `train` runs exactly this loop internally. + +Training runs on the device of the starting centroids you pass to `begin`, and every batch must be on that +same device. Copy each batch there yourself, using the following training loop: + +```python +import numpy as np, torch +from faiss.contrib.e_means import Emeans + +em = Emeans(d, k) # d: dimension, k: number of clusters +rng = np.random.default_rng(0) +start = torch.from_numpy(x[rng.choice(len(x), k, replace=False)]).cuda() # starting centroids +em.begin(len(x), start) # total rows: the model now lives on the GPU +B = em.recipe["batch_size"] +for rows in em.recipe["epoch_rows"]: # one entry per pass + order = rng.permutation(len(x))[:rows] # a fresh random order every pass + for i in range(0, rows, B): + batch = torch.from_numpy(x[order[i:i + B]]).cuda() # in practice: read from disk + em.update(em.accumulate(batch)) + em.end_epoch() +centroids = em.finalize() +``` + +Follow these rules: + +- Don't forget to call `begin` and `finalize`. +- Every batch must be exactly the recipe's batch size, except the last one of each pass, which is + whatever is left. +- If you have to do batch accumulation because your batch size is too large, call `accumulate` on each piece, then `update` once with what the last `accumulate` returned. +- Every vector must appear exactly once per pass. The code checks the counts, not which vectors you + send. + +As written, each copy waits for the GPU. To overlap loading and computing, use pinned host buffers +and a separate CUDA stream. The DINO demo's reader (`benchs/e_means/ssd_streaming.py`) does this for +data read from SSD. + +If the data does not fit on one GPU but fits across several, sharded centroids do the batching for +you, see the next section. + +## Several GPUs + +Multi-GPU training runs one copy of your program per GPU, launched with `torchrun`: + +```bash +torchrun --standalone --nproc-per-node=8 my_script.py +``` + +Each copy owns one GPU, joins a group (`torch.distributed`), and loads only its own share of the +data onto its GPU. e-means never splits or moves your dataset: you decide which rows each copy loads, +usually by its rank. The copies synchronize inside e-means at every batch, so they must all make the +same calls with the same settings. + +There are two classes, depending on whether the centroids fit on one GPU: + +| | Copied centroids (`DistributedEmeans`) | Sharded centroids (`EmeansShardedCentroids`) | +|---|---|---| +| Centroids on each GPU | all of them | a slice, 1/n_gpus of them | +| Use it when | the centroids fit on one GPU | the centroids do not fit on one GPU | +| At each batch | each GPU processes its share of the batch against all centroids, then the per-cluster sums are added across GPUs | the whole batch is sent to every GPU, each scores it against its slice, and the GPUs agree on each vector's nearest centroid | +| Training | your own batch loop: there is no `train` | `train(x_local)` does the batching | +| Also on CPUs | yes | no, GPUs only | +| Requirements | the batch and the rows of every pass divide by the number of GPUs | the same, plus `k` divides by the number of GPUs, every GPU holds the same number of rows (the IVF variant also needs `quantizer=None`) | + +The batch size is a power of two, so use 2, 4 or 8 GPUs: with 3 or 6, the batch does not divide. + +With sharded centroids, every GPU holds the whole batch at once, gathered from all the GPUs. +Budget `batch_size * d * bytes per value` on each GPU for it, on top of your data and the centroids. + +For sharded centroids, you have to run the following script on each GPU: + +```python +import os, numpy as np, torch, torch.distributed as dist +from faiss.contrib.e_means import EmeansShardedCentroids + +local_rank = int(os.environ["LOCAL_RANK"]) +torch.cuda.set_device(local_rank) +dist.init_process_group("nccl") +rank, world = dist.get_rank(), dist.get_world_size() + +data = np.load("vectors.npy", mmap_mode="r") # nothing read yet +d, k = data.shape[1], 1024 # dimension, number of clusters +assert len(data) % world == 0, "data rows must divide evenly across ranks" +share = len(data) // world # equal shares +x_local = torch.from_numpy(np.array(data[rank * share:(rank + 1) * share])).cuda() + +em = EmeansShardedCentroids(d, k, nepochs=5, group=dist.group.WORLD) +my_centroids, my_labels = em.train(x_local) # this GPU's slice, labels of its rows (global ids) + +slices = [torch.empty_like(my_centroids) for _ in range(world)] +dist.all_gather(slices, my_centroids.contiguous()) # all k centroids, in order +dist.destroy_process_group() +``` + +For copied centroids, the training loop each copy runs (with `d`, `k`, `x_local`, `rank` and `world` as above): + +```python +from faiss.contrib.e_means import DistributedEmeans + +em = DistributedEmeans(d, k, nepochs=5, group=dist.group.WORLD) +dev = x_local.device +init = x_local[torch.randperm(len(x_local), device=dev)[:k]] # rank 0's starting centroids are used +em.begin(len(x_local) * world, init) +B = em.recipe["batch_size"] # the batch summed over all GPUs +for rows in em.recipe["epoch_rows"]: # rows per pass, over all GPUs + order = torch.randperm(len(x_local), device=dev) + for start in range(0, rows, B): + a, b = start // world, min(rows, start + B) // world # this GPU's share of the batch + em.update(em.accumulate(x_local[order[a:b]])) # sums are added across GPUs + em.end_epoch() +centroids = em.finalize() # the same on every GPU +``` + +With sharded centroids, if you write your own loop over the data instead of calling `train` (as the +SSD demo does), the final means can come from the labels saved during the last pass, without searching again: +`em.final_closing_mean(batches, assignments=codes)`, called after the last pass and before `finalize`. +`codes` holds those labels on the CPU (int32 or int64, `-1` for rows the last pass skipped), and `batches` +must go over the rows in the same order. Without `assignments`, it assigns every row once more against +the final centroids. + +These are three distinct closing routes. Ordinary cost-based `finalize` uses +retained statistics from rows after each centroid's last split; empty centroids +keep their running positions. Saved mode averages the supplied labels without +repair or search, including rows saved before a later split, and validates their +counts against all final-pass assignments. A fresh scan assigns every supplied +row against the final centroid snapshot and averages those new assignments. + +`EmeansShardedCentroidsIVF` finds the nearest centroids with an IVF index, which is approximate and +pays off with very many centroids, typically above $10^6$. The 10-billion-vector DINO demos, resident on two GPUs and +streamed from SSD, are in `benchs/e_means/`, with their own README. + +The search inside the probed lists (`ivf_fine.py`) is one pass on CUDA: the routed (row, probe) pairs are +filed by list, each list is scanned once per tile of pairs, and the probes are merged at the end. Scores use +FP32 accumulation of the represented operands in contraction order, and the lower ID wins equal scores. +The probed lists come from the coarse scores through an exact radix select instead of `torch.topk`, for any +number of lists and probes (the same lists in the same order, the lower list ID winning equal scores). On H100/H200 with BF16 operands (the +`EmeansShardedCentroidsIVF` default) the kernel is CuTe (`ivf_fine_cute.py`, with the CuTe packages of the +table below); otherwise a Triton kernel returns the same bits and also serves FP16 and FP32 operands. On the +CPU the same search runs with PyTorch operations. The CuTe kernel times two candidate-tile widths (128 and +256) on the first call of each shape and keeps the faster one; set `ivf_fine.DEFAULT_TILE = 128` or `256` +to fix it. + +## Kernels and data precision on GPU +### Kernels +Most of e-means' runtime goes into assigning each training vector to its nearest centroid. We made optimized kernels in CuTe and Triton to make this computation as fast as possible. Note that we also provide a fallback to a plain PyTorch path, but it's much slower than the Triton and CuTe kernels, because it does not fuse the distance computation with the selection of the nearest centroid. + +Which implementation your run will use (CuTe, Triton, PyTorch) is automatically selected from your GPU type and your data's precision. + +| Your data | H100/H200 | B200 | B300 | A100 | Other recent GPUs (RTX 30/40, L40S, A10) | Older GPUs (V100, T4) | +|---|---|---|---|---|---|---| +| FP32, default BF16 conversion | **CuTe**¹ | Triton¹ | Triton¹ | Triton¹ | Triton¹ | no | +| Native FP32 (`quantizer=None`) | Triton | Triton | Triton | Triton | Triton | PyTorch | +| BF16 | **CuTe** | Triton | Triton | Triton | Triton | no | +| FP16 | Triton | Triton | Triton | Triton | Triton | no | +| FP8 (`float8_e4m3fn`) | Triton² | Triton | Triton | no | no | no | +| INT8, UINT8 | Triton² | Triton | no | Triton | no | no | +| float64 | no | no | no | no | no | no | + +- ¹ CUDA FP32 input uses BF16 operands by default. To retain native FP32 input, use + `QuantizedEmeans(d, k, quantizer=None)`. These are automatic choices for supported extents; + the selected backend is recorded in `em.recipe["assignment_backend"]`. +- ² CuTe if you pass `assignment_backend="cute"`. +- "no" means training is refused with an error at the start. +- Install the packages required by the selected backend. Missing, broken or incompatible required software + raises an error; e-means does not switch to another assignment backend. +- FP8 and INT8 data are used as raw codes in their own units, unless you pass the matching converter. + INT8 also needs a dimension of 43,919 or less. +- AMD GPUs require native FP32 via `QuantizedEmeans(d, k, quantizer=None)`, through PyTorch. + On the CPU, computation remains FP32 (see On the CPU). +- On CUDA, batch sums are deterministic on the segmented-reduction path (FP32/BF16, d ≤ 4096; d ≥ 128 + or SM90); other paths use `index_add_`, so call `torch.use_deterministic_algorithms(True)` if runs + must repeat exactly. + +### Data precision +The precision used in your e-means run has an important influence on training speed. On a GPU, e-means iterations can run in smaller number formats, which recent GPUs process faster: 16-bit floats (FP16, BF16), 8-bit floats +(FP8) or 8-bit integers (INT8). The centroids, the running sums and the returned distances always +stay in 32-bit floats (FP32): only the nearest-centroid search uses the smaller format because it is the main bottleneck. On the CPU, everything is FP32. +By default, FP32 data on a GPU is converted to BF16 for that search, by a `CastQuantizer(d, torch.bfloat16)`. +To keep the search in real FP32 instead, use `QuantizedEmeans(d, k, quantizer=None)`. + +Native exhaustive PyTorch assignment preserves the selected operand precision inside +`torch.autocast` contexts. CPU assignment remains FP32; explicitly selected +FP16/BF16 CUDA operands retain their precision. + +**How the format is chosen:** by your data's type, or by a converter you pass. Apart from that BF16 +default for FP32 data, e-means never converts on its own. The kernels used for each format and GPU +are in the table under Kernels, above. + +| Input numbers | CuTe kernels (H100) | Triton kernels | PyTorch kernels | +|---|---|---|---| +| Native FP32 (`quantizer=None`) | not supported | A100 or newer | CPU and any CUDA GPU | +| FP16, BF16 | BF16 only | A100 or newer | A100 or newer | +| FP8 (E4M3) | yes | H100, B200, B300 | not supported | +| INT8, UINT8 | yes | A100, H100, B200, dimension up to 43,919 | not supported | + +**How to convert data to lower precision.** You can either convert once yourself before training, which also saves memory, or keep the original precision in memory and pass a **converter** (`quantizer=`), which converts each chunk on the fly for faster distance computation: + +| Target | Convert once yourself | Keep FP32, convert on the fly | +|---|---|---| +| BF16 | `x.to(torch.bfloat16)` | Pass quantizer `CastQuantizer(d, torch.bfloat16)` when instantiating `QuantizedEmeans` | +| FP16 | `x.to(torch.float16)` | `CastQuantizer(d, torch.float16)` | +| FP8 | `q.compute_codes(x)` with a calibrated `Fp8Quantizer` | the calibrated `Fp8Quantizer` | +| INT8 | `q.compute_codes(x)` with a calibrated `Int8Quantizer` | not available: INT8 only takes codes made up front | + +```python +from faiss.contrib.e_means import QuantizedEmeans +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer + +xg32 = torch.from_numpy(x).cuda() + +# Native FP32, without the default BF16 conversion +centroids, labels = QuantizedEmeans(64, 1024, quantizer=None).train(xg32) + +# BF16, converted on the fly +centroids, labels = QuantizedEmeans(64, 1024, quantizer=CastQuantizer(64, torch.bfloat16)).train(xg32) + +# FP8: calibrate on a sample, then train on FP32 data (encoded per chunk) +q = Fp8Quantizer(64) +q.train(xg32[:50_000]) +q.to(xg32.device) +centroids, labels = QuantizedEmeans(64, 1024, quantizer=q).train(xg32) + +# INT8: calibrate, encode everything once, train on the codes +q = Int8Quantizer(64) +q.train(xg32[:50_000]) +q.to(xg32.device) +centroids, labels = QuantizedEmeans(64, 1024, quantizer=q).train(q.compute_codes(xg32)) +``` + +With a converter, the centroids and distances come back in your original FP32 units. + +**Values that do not fit the format:** + +| Format | Values outside its range | +|---|---| +| BF16 | never in practice: it has FP32's range. It only rounds, keeping about 3 significant digits | +| FP16 | values of 65,520 and above become infinity, silently: no clipping and no warning | +| FP8, INT8 | the converter is calibrated on your sample: a shift per dimension and one power-of-two scale. Values beyond the sample's range are clamped to the edge (448 for FP8) | + +So with FP16, check the data once with `CastQuantizer(d, torch.float16).validate(x)`, which raises if +anything is out of range, or use BF16. With FP8 and INT8, calibrate on a sample that includes your +extremes. `validate` reports out-of-range values for FP8. For INT8, clamping outliers is accepted by +design. + +**Centering.** `CastQuantizer(d, dtype, center=True)` subtracts your data's mean before rounding to 16 +bits. Call `train(sample)` to fit the mean and `to(device)` before use. It helps when the vectors sit +far from the origin, where rounding would otherwise spend the few available digits on the shared +offset. It is not available in spherical mode. With centering, pass FP32 data or +`q.compute_codes(x)`, not data you converted with `.to(...)` yourself. + +**Low dimension.** In very low dimensions (2 or 3), 16-bit formats are more likely to hurt the result, so FP32 is the safer choice: on a GPU, use `QuantizedEmeans(d, k, quantizer=None)` to keep FP32. + +## How the centroid updates work + +e-means is based on exponential moving average updates: each centroid is the ratio of two running averages: one counts the number of points the cluster receives, the other sums the embeddings of these points. At each mini-batch, these averages are updated as follows: + +``` +N_j <- (1 - alpha) * N_j + alpha * n_j # running count of the points cluster j receives +S_j <- (1 - alpha) * S_j + alpha * s_j # running sum of those points +c_j = S_j / N_j # the centroid +``` + +Here `n_j` and `s_j` are the count and the sum of the batch's points assigned to cluster j, and `alpha` is the step size. With the whole dataset as one batch and a step of 1, this is exactly one Lloyd iteration. The components added by e-means are: + +- The batch size and the starting step size come from two scaling laws, setting them automatically for any problem size. +- The step size shrinks during training along a cosine curve, down to a tenth of its starting value. +- A cluster that receives too few points is revived by splitting a busy cluster in two, as faiss does. The default rule is described under Cluster revival below. +- At the end of the last pass, each centroid is set to the exact mean of the points that pass assigned to it (see Cluster revival for revived centroids). This costs nothing extra, because those assignments were already made. + +### Cluster revival + +The same cost rule applies to `QuantizedEmeans`, `DistributedEmeans` and exhaustive `EmeansShardedCentroids` for their admitted floating and encoded FP8/INT8/UINT8 representations. Their statistics and removal costs use the represented rows in model units. Unencoded floating owners compare raw ranking keys before adding the common row norm; custom `_assign_rows` overrides must accept and honor the keyword-only `scores=True` request. Ordinary `scores=False` calls keep their existing output meaning. IVF fine-search capability and routing are documented separately. + +With the default `unused_threshold=None`, `Emeans` and `NumpyEmeans` use cost-based revival. Each cluster keeps running averages of its removal cost $R_j$, the sum of $d_2 - d_1$ over its points ($d_1$, $d_2$: squared distances to the nearest and second-nearest centroids), and of its long axis (Oja's rule). Every five updates, the clusters with $R_j < 0.3$ times the median, or $R_j \le 0$, are candidates: cheapest first, each is paired with the next cluster by the length of its axis, and moves to split it only if that split gains more than the removal costs, $\tfrac{2}{\pi}\lVert U_l \rVert > R_j$ (a candidate with $R_j \le 0$ always moves). A split puts the two copies at $c_j \mp s_j u_j$, $s_j = \sqrt{2 \lVert U_j \rVert / (\pi N_j)}$, the half-means of a Gaussian along the long axis $u_j$ ($U_j$: the running average behind it, $N_j$: the mass before the split). Moves continue until the end of training, and with captured assignments `train` sorts out the last pass at its end: a point assigned before its centroid was revived goes to its second-nearest centroid, or is assigned afresh if that centroid was itself revived after the point was assigned to it; a donor's other points from before its first split after them go to the nearer of the two centroids of that split; then every centroid returns the mean of its final last-pass points (a centroid with none keeps its running position). Without captured assignments, both centroids of a last-pass split return the mean of the points assigned to them after it. Pass a number to use mass-based revival instead. With the removal cost on, `update` only takes statistics from the same model's `accumulate`, and raises otherwise. + +Local `QuantizedEmeans.train` uses the same closing search and donor/twin repair +for captured cost training in floating and encoded representations, including +explicit quantizers. Closing sums use the rows' training representation and +decoded units; raw bytes retain numeric units and INT64 sums. Every populated +centroid returns its final-label mean, and an empty centroid keeps its position. + + +## Spherical e-means + +**What it does.** Spherical e-means clusters vectors by direction instead of position. It maximizes the cosine similarity between each vector and its centroid. On vectors of norm 1, this is the same as minimizing the squared distance on the unit sphere, which equals 2 − 2 × cosine. + +**How it works.** It is the e-means update of the previous section, with three changes: + +- Before every use, each centroid is its running average rescaled to norm 1. A zero centroid stays + zero. +- Each vector goes to the centroid with the highest dot product, which for vectors of norm 1 is the + highest cosine similarity. +- The closing step takes each cluster's exact mean, then rescales it to norm 1. + +The reported error is the sum of 2 − 2 × similarity over the vectors. + +**How to use it.** Normalize your vectors to norm 1 yourself, then pass `spherical=True`: + +```python +xs = torch.nn.functional.normalize(xg32, dim=1) # every vector now has norm 1 +em = Emeans(64, 1024, spherical=True) +centroids, labels = em.train(xs) +similarity, labels = em.assign(xs) # similarity: higher is closer +``` + +- `assign` returns each vector's dot product with its nearest centroid, where higher is closer, so make sure your vectors are normalized to obtain cosine similarity. +- It works with 32-bit and 16-bit floats, not with FP8 or INT8, and not with a centered `CastQuantizer`. +- The model does not check the norm of your vectors. Vectors that are not of norm 1 are accepted silently. Their labels still follow cosine similarity, but long vectors pull their centroid harder than short ones, and the reported error and similarities are no longer cosine quantities. + +## Demos and tests + +```bash +python demos/demo_e_means.py --data-dir /path/to/data # DEEP1M, one GPU, 3 passes, 10 seeds +torchrun --standalone --nproc-per-node=2 demos/demo_e_means_distributed.py +torchrun --standalone --nproc-per-node=2 demos/demo_e_means_sharded.py +python -m unittest discover -s tests -p 'test_e_means.py' +python -m unittest discover -s tests -p 'torch_test_e_means*.py' +``` + +The tests need two commands, because Python's default test discovery skips the PyTorch test files. +The 10-billion-vector demos (DINO10B, resident and from SSD) are in `benchs/e_means/`, with their own README. diff --git a/thirdparty/faiss/contrib/e_means/__init__.py b/thirdparty/faiss/contrib/e_means/__init__.py new file mode 100644 index 000000000..e72ec092b --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/__init__.py @@ -0,0 +1,46 @@ +# 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. + +"""Explicit NumPy reference and lazily imported tensor E-means.""" + +from .e_means import NumpyEmeans + +__all__ = [ + "Emeans", + "NumpyEmeans", + "QuantizedEmeans", + "DistributedEmeans", + "DistributedNumpyEmeans", + "EmeansShardedCentroids", + "EmeansShardedCentroidsIVF", +] + + +def __getattr__(name): + if name == "Emeans": + from .e_means_torch import Emeans + + return Emeans + if name == "QuantizedEmeans": + from .e_means_quantized import QuantizedEmeans + + return QuantizedEmeans + if name == "DistributedEmeans": + from .e_means_distributed import DistributedEmeans + + return DistributedEmeans + if name == "DistributedNumpyEmeans": + from .e_means_distributed import DistributedNumpyEmeans + + return DistributedNumpyEmeans + if name == "EmeansShardedCentroids": + from .sharded_centroids import EmeansShardedCentroids + + return EmeansShardedCentroids + if name == "EmeansShardedCentroidsIVF": + from .sharded_centroids_ivf import EmeansShardedCentroidsIVF + + return EmeansShardedCentroidsIVF + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/thirdparty/faiss/contrib/e_means/base.py b/thirdparty/faiss/contrib/e_means/base.py new file mode 100644 index 000000000..7a95bc409 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/base.py @@ -0,0 +1,545 @@ +# 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. + +"""Shared recipes and lifecycle for E-means implementations. + +Algorithm 1 and equations below refer to "E-Means: Scaling Laws for Mini-Batch +K-Means": https://arxiv.org/abs/2611.09501 +""" + +import math +import time + +import numpy as np + +# Epsilon in Equation 5: the cosine schedule's minimum step / initial step. +_ALPHA_MIN_FACTOR = 0.1 + +# Number of logical batch updates between revival checks (Algorithm 1, line 9). +_CHECK_UNUSED_EVERY = 5 + +# Above this complete floating contribution, accumulate sums/counts in FP64. +_FLOAT32_COUNT_LIMIT = 2**24 + +# Initial EMA mass N_j (Algorithm 1, line 1); c_j represents S_j / N_j. +# This implementation uses 2**-16; the paper initializes N_j to 1e-10. +_INIT_USAGE = 2.0**-16 + +# Revival threshold tau: revive N_j < tau * mean(N) (Algorithm 1, line 9). +_UNUSED_THRESHOLD = 0.1 + +# Removal threshold tau_R for unused_threshold=None: c_j may move if its +# removal cost R_j, the EMA of d2 - d1 over its rows, is below tau_R * median(R) +# or zero. +_REMOVAL_THRESHOLD = 0.3 + +# A (donor l, candidate j) pair moves only if the donor's split gain, Oja's +# _SPLIT_GAIN * |U_l| = (2/pi)|U_l|, exceeds the candidate's removal cost R_j +# (a candidate with R_j <= 0 always moves). Without it, every candidate moved: +# two centroids sharing one cluster each look free to remove (the other takes +# its rows), both left together, and the cluster was orphaned. +_SPLIT_GAIN = 2.0 / math.pi + +# In classes with mass-based revival, unused_threshold=None (the default) turns +# revival off at or below this dimension and uses _UNUSED_THRESHOLD above it. +# On 2-D data, reviving dead clusters by mass costs held-out error: on the +# foursquare and geonames corpora, switching it off lowered the median held-out +# error by 7-10% (36 paired runs, 3 passes). By d=3 and d=14 it made no +# difference. +_NO_REVIVAL_MAX_D = 2 + +# batch_law="auto" (the default) picks the quality law at or below this +# dimension and the throughput law above it. At 3 passes, the throughput +# batch makes 8 times fewer updates. At d <= 16 that cost E-means 11-20 +# percentage points of wins against Lloyd's algorithm at 25 iterations, and +# 0-6 points above (30,000 synthetic configurations, n in [1e5, 1e6], K in +# [10, 1e4]). +_AUTO_QUALITY_MAX_D = 16 + +# Batch law B = C_B * k**b_k * n**b_n * T**b_T (Section 4, Equation 7). +# Tuples contain (C_B, b_k, b_n, b_T), with T = nepochs. Quality uses one +# eighth of the throughput coefficient before power-of-two rounding and batch +# caps. +# These shipped fits used full passes with 100K-10M training rows; their +# coefficient values differ from those reported in the paper's Table 2. +_BATCH_LAWS = { + "throughput": (0.035134, 0.134749, 0.876473, 0.813344), + "quality": (0.00439175, 0.134749, 0.876473, 0.813344), +} + +# Step law alpha0 = C_alpha * k**a_k * B**a_B * n**a_n * T**a_T (Equation 6). +# Tuple order is (C_alpha, a_k, a_B, a_n, a_T); B is the resolved batch size. +# This shipped fit also included 100M rows and used a zero-ending cosine; +# execution uses the 0.1 floor in _ALPHA_MIN_FACTOR. Its coefficients also +# differ from Table 2. _step_law clamps the result to [1e-4, 1]. +_ALPHA_LAW = (0.8244, -0.4617, 0.9003, -0.4498, -0.1057) + + +def _round_power_of_two(value): + """Round a positive value to the nearest power of two.""" + if value <= 1: + return 1 + low = 2 ** int(math.floor(math.log2(value))) + high = 2 * low + return low if value / low < high / value else high + + +def _step_law(n, k, nepochs, batch_size): + """Initial EMA step coupled to a batch size by the fitted step law.""" + coefficient, k_exp, batch_exp, n_exp, iter_exp = _ALPHA_LAW + alpha0 = ( + coefficient + * k**k_exp + * batch_size**batch_exp + * n**n_exp + * nepochs**iter_exp + ) + return min(max(alpha0, 1e-4), 1.0) + + +def _resolve_batch_law(batch_law, d): + """Resolve ``batch_law="auto"`` to a fitted law, returning (law, reason). + + Any other value is returned unchanged (an unknown name fails in + ``_resolve_recipe``). + """ + if batch_law != "auto": + return batch_law, "requested" + if d <= _AUTO_QUALITY_MAX_D: + return "quality", "d <= %d" % _AUTO_QUALITY_MAX_D + return "throughput", "d > %d" % _AUTO_QUALITY_MAX_D + + +def _compact_label_dtype(k): + """Smallest signed integer type for labels below k and the sentinels -1, -2.""" + return np.int8 if k <= 127 else np.int16 if k <= 32767 else np.int32 + + +def _resolve_unused_threshold(unused_threshold, d): + """Revival threshold tau for a run, picked from ``d`` if ``None``.""" + if unused_threshold is None: + return 0.0 if d <= _NO_REVIVAL_MAX_D else _UNUSED_THRESHOLD + unused_threshold = float(unused_threshold) + if not unused_threshold >= 0: + raise ValueError("unused_threshold must be >= 0 (0 disables revival)") + return unused_threshold + + +def _divisibility_error(recipe, n, batch, processes): + """The error raised when a multi-process run cannot split its batches. + + Names the batch law that chose the batch (an automatic choice can pick the + small quality batch at low dimension) and how to make it divisible. + """ + law = recipe.get("batch_law") + if law is None: + source = "the given batch_size" + elif recipe.get("batch_law_requested") == "auto": + source = 'batch_law="auto", which chose the %s law because %s' % ( + law, recipe.get("batch_law_reason")) + else: + source = 'batch_law="%s"' % law + return ValueError( + "the global batch (%d rows, from %s), the global row count (%d) and " + "every epoch's rows (%s) must be divisible by the %d processes. Pass " + 'batch_law="throughput", or a batch_size divisible by %d.' + % (batch, source, n, list(recipe["epoch_rows"]), processes, processes)) + + +def _resolve_recipe(n, k, nepochs, batch_law, batch_size, alpha0): + """Resolve the recipe's statistical batch size B and initial EMA step. + + The batch comes from ``batch_law`` unless ``batch_size`` is given. The + step comes from the step law at that batch unless ``alpha0`` is given too. + """ + if batch_size is None: + coefficient, k_exp, n_exp, iter_exp = _BATCH_LAWS[batch_law] + raw_batch = coefficient * k**k_exp * n**n_exp * nepochs**iter_exp + batch_size = _round_power_of_two(raw_batch) + # These intentionally differ: they reproduce the two fitted recipes. + if batch_law == "throughput": + batch_size = min(batch_size, _round_power_of_two(n / 2)) + else: + batch_size = min(batch_size, n // 2) + batch_size = max(1, min(batch_size, n)) + else: + batch_size = min(int(batch_size), n) + if alpha0 is None: + alpha0 = _step_law(n, k, nepochs, batch_size) + return batch_size, float(alpha0) + + +def _epoch_rows(n, nepochs): + """Whole passes, a rounded fractional prefix, then moving closing. + + Round the fractional row count with Python's ties-to-even convention. + Below one pass, only that prefix contributes to closing means. + """ + whole = math.floor(nepochs) + remainder = int(round((nepochs - whole) * n)) + if whole == 0: + return [remainder] + return [n] * (whole - 1) + ([remainder] if remainder else []) + [n] + + +def _twin_reassign(order, labels, rows_of, centroids, moved_at, key, target, source, born, stale, span, chunk): + """The twin reassignment of ``Emeans._close_split_centroids`` on host arrays, in place on ``labels``.""" + for begin in range(0, len(order), chunk): + index = order[begin:begin + chunk] + rank, label = np.arange(begin, begin + len(index)), labels[index] + split = np.minimum(np.searchsorted(key, label * span + rank, side="right"), len(key) - 1) + child = target[split] + twin = ~stale[index] & (source[split] == label) & (born[split] > rank) & (moved_at[child] == born[split]) + own, child, rows = label[twin], child[twin], rows_of(index[twin]) + # FP32 differences, squared and summed in FP64; ties to the lower index. + near_own = np.square((rows - centroids[own]).astype("float64")).sum(axis=1) + near_child = np.square((rows - centroids[child]).astype("float64")).sum(axis=1) + labels[index[twin]] = np.where((near_child < near_own) | ((near_child == near_own) & (child < own)), child, own) + + +def _epoch_seed(seed, iteration): + """Derive one reproducible permutation seed without ambient RNG state. + + A pass must not replay the initialization draw, which uses the same stream + seeded with ``seed``. When the pass seed equals ``seed`` (modulo 2**32; + at pass 0 only for seeds 0 and 2**31), it moves by the golden-ratio constant. + """ + s = (seed * 1000003 + iteration) % 2**32 + if s == seed % 2**32: + s = (s + 0x9E3779B9) % 2**32 + return s + + +def _scheduled_alpha(alpha0, step, total_steps): + """Cosine-anneal an EMA step towards one tenth of its initial value.""" + fraction = min(step, total_steps) / max(1, total_steps) + cosine = 0.5 * (1.0 + math.cos(math.pi * fraction)) + return alpha0 * (_ALPHA_MIN_FACTOR + (1.0 - _ALPHA_MIN_FACTOR) * cosine) + + +_CITATION = ("This is e-means. If you use our work or find it useful, please cite the e-means " + "paper (Bessa et al., see faiss/contrib/e_means/README.md).") + + +def _format_passes(passes): + """Format a number of passes for verbose output: 3.0 -> '3', 1.4 -> '1.4'.""" + return "%.4g" % passes + + +def _same_operation(method, implementation, receiver): + """Check that a bound callback uses this function and receiver.""" + return (getattr(method, "__func__", None) is implementation + and getattr(method, "__self__", None) is receiver) + + +class _EmeansBase: + """Shared batch accounting and update orchestration.""" + + _removal_revival = True + + def _set_max_points_per_centroid(self, value): + if value is not None: + value = int(value) + if value < 1: + raise ValueError("max_points_per_centroid must be >= 1 or None") + self.max_points_per_centroid = value + + def _training_subset(self, n): + """Sorted row ids kept by max_points_per_centroid, or None for all.""" + if self.max_points_per_centroid is None: + return None + limit = self.max_points_per_centroid * self.k + if n <= limit: + return None + if self.verbose: + print( + "WARNING clustering %d points to %d centroids: sampling %d " + "points (max_points_per_centroid=%d)" + % (n, self.k, limit, self.max_points_per_centroid) + ) + # Generator.choice without shuffling draws a small subset without + # permuting the whole input, and seed % 2**64 accepts every seed the + # tensor model accepts (negative or above 2**32) without changing it. + rng = np.random.default_rng(self.seed % 2**64) + keep = rng.choice(n, limit, replace=False, shuffle=False) + keep.sort() + return keep + + def _invalidate_readout(self): + if self.spherical: + self._unit_generation += 1 + self._unit_version = None + + def _resolve_removal_revival(self): + """Cost-based revival under the default threshold, if k > 1.""" + if self.unused_threshold is None and self._removal_revival and self.k > 1: + self._unused_threshold = None + + def _keeps_removal_stats(self): + """Whether to keep [U | R] and the axes: cost-based revival reads R and + U, and every split is placed along the donor's axis from U.""" + return self._unused_threshold is None or self._unused_threshold > 0 + + def _revive_unused(self, rng): + source, target = self._choose_splits(rng) + return 0 if source is None else self._apply_splits(source, target) + + def _choose_removal_splits(self, removal, usage, axis_norm): + """Move centroids cheap to remove (R_j) to split the longest donors. + + Removal costs R_j are host float64; donor inputs N_j and |U_j| + follow the donor-selection backend. Evaluate split gain in float64 + from the FP32 donor ranking norm; keep the existing pair order until + the first unpaid pair. Nonpositive removal costs always pay. + """ + candidates = np.flatnonzero( + (removal <= 0) | (removal < _REMOVAL_THRESHOLD * np.median(removal))) + if len(candidates) == 0: + return None, None + kept = candidates[np.argsort(removal[candidates], kind="stable")].astype("int64") + donors = self._choose_removal_donors(kept, usage, axis_norm) + n = min(len(kept), len(donors)) + donors, kept = donors[:n], kept[:n] + gain = _SPLIT_GAIN * axis_norm[donors].astype("float32").astype("float64") + pays = (removal[kept] <= 0) | (gain > removal[kept]) + n = int(np.cumprod(pays).sum()) + return (donors[:n], kept[:n]) if n else (None, None) + + def _choose_removal_donors(self, kept, usage, axis_norm): + donors = usage > 0 + donors[kept] = False + donors = np.flatnonzero(donors) + return donors[np.argsort(-axis_norm[donors].astype("float32"), kind="stable")] + + def _require_running(self): + if self._failed: + raise RuntimeError( + "create a new object after execution failure" + ) + self._report_header_once() + + def _logical_batch_size(self): + return min( + self.recipe["batch_size"], + self.recipe["epoch_rows"][self._epoch] - self._epoch_rows, + ) + + def _local_batch_size(self): + return self._logical_batch_size() + + def _complete_statistics(self, accumulation): + self._batch_stats[...] = accumulation + return self._batch_stats + + def update(self, stats): + """Apply one complete batch's statistics, then revive unused clusters. + + The caller supplies matching sums, counts, objective and row count + for the recipe's next logical batch. Shapes, dtypes, values and + sequencing are caller responsibilities. Cost-based revival also + needs the removal statistics that only this model's ``accumulate`` + collects. + """ + self._require_running() + if self._unused_threshold is None and stats.get("removal") is not self._batch_removal: + raise ValueError("unused_threshold=None needs statistics from this model's accumulate") + expected_n = self._logical_batch_size() + ids, sums, counts, objective = self._prepare_statistics( + stats, expected_n + ) + alpha = _scheduled_alpha( + self.recipe["alpha0"], self._step, self.recipe["total_steps"] + ) + try: + self._apply_statistics( + ids, sums, counts, objective, alpha, 1.0 - alpha, alpha == 1 + ) + self._finish_step(expected_n) + except BaseException: + self._failed = True + self.assignments = None + raise + + def _finish_step(self, expected_n): + if (self._step + 1) % _CHECK_UNUSED_EVERY == 0: + self._revive_unused(self._split_rng) + self._invalidate_readout() + self._step += 1 + self._epoch_steps += 1 + self._epoch_rows += expected_n + self._pending_stats = None + self._batch_accumulation = self._batch_objective = None + self._batch_centroids = None + + def _epoch_objective(self): + return self._objective + + def _resolve_run_recipe(self, n): + """Build ``self.recipe``, the resolved training plan for this run. + + ``begin`` turns constructor options and the dataset size into this + dictionary. It records the statistical batch size B, initial EMA step + alpha0, rows and update counts per epoch, and total updates. The shared + lifecycle uses these to size each update, end epochs and anneal alpha. + + The recipe also records revival settings, the seed and execution + metadata. Assignment chunks subdivide a statistical batch without + changing its update schedule. Implementations add backend-specific + fields, such as the device or represented dtype. + + ``batch_law="auto"`` is resolved here, from the dimension. The recipe + records the resolved law and why, and the revival threshold the + constructor resolved from ``unused_threshold`` and the dimension, or + None for cost-based revival. + """ + batch_law, batch_law_reason = _resolve_batch_law( + self.batch_law, self.d + ) + self._batch_law_resolved = batch_law + batch_size, alpha0 = _resolve_recipe( + n, + self.k, + self.nepochs, + batch_law, + self.batch_size, + self.alpha0, + ) + steps_per_pass = (n + batch_size - 1) // batch_size + epoch_rows = _epoch_rows(n, self.nepochs) + epoch_steps = [ + (rows + batch_size - 1) // batch_size for rows in epoch_rows + ] + batch_given = self.batch_size is not None + alpha_given = self.alpha0 is not None + self.recipe = { + "name": (("manual" if alpha_given else "manual_batch") + if batch_given else "canonical_v1"), + "batch_law": None if batch_given else batch_law, + "batch_law_requested": None if batch_given else self.batch_law, + "batch_law_reason": None if batch_given else batch_law_reason, + "batch_size": batch_size, + "batch_size_requested": (int(self.batch_size) if batch_given + else None), + "alpha0": alpha0, + "alpha0_source": "given" if alpha_given else "step_law", + "nepochs": self.nepochs, + "steps_per_pass": steps_per_pass, + "total_steps": sum(epoch_steps), + "epoch_rows": epoch_rows, + "epoch_steps": epoch_steps, + "tail_policy": "keep", + "alpha_min_factor": _ALPHA_MIN_FACTOR, + "check_unused_every": _CHECK_UNUSED_EVERY, + "unused_threshold": self._unused_threshold, + "init_usage": _INIT_USAGE, + "seed": self.seed, + "backend": self._backend, + "assignment_chunk_size": self._get_assignment_chunk_size(), + } + + def _reports(self): + """Whether this process prints verbose output (one rank per group).""" + return self.verbose + + def _say(self, text): + # Like faiss's printf, a closed stdout (e.g. piped into head) never + # stops training: printing just stops for the rest of the run. + if getattr(self, "_quiet", False): + return + try: + print(text, flush=True) + except (OSError, ValueError): # broken pipe, or a closed file object + self._quiet = True + + def _describe_assignment(self): + recipe = self.recipe + if recipe["backend"] == "faiss": + return "faiss on CPU" + backend = recipe.get("assignment_backend") + name = {"native": "PyTorch", "triton": "Triton", "cute": "CuTe"}.get(backend, str(backend)) + representation = recipe.get("representation") + return "%s%s on %s" % (name, " " + representation if representation else "", + recipe.get("device")) + + def _describe_parallel(self): + """The devices and class of a multi-process run, or None.""" + return None + + def _report_header(self): + recipe = self.recipe + law = recipe["batch_law"] + if law is None: + extras = ["batch given"] + elif recipe.get("batch_law_requested") == "auto": + extras = ["%s batch law, auto for %s" + % (law, recipe["batch_law_reason"])] + else: + extras = ["%s batch law" % law] + if self.spherical: + extras.append("spherical") + if "index_factory" in recipe: + extras.append("IVF assignment, %d lists, %d probed" + % (self.nlist, recipe["nprobe"])) + self._say(_CITATION) + parallel = self._describe_parallel() + if parallel: + self._say(parallel) + self._say( + "Clustering %d points in %dD to %d clusters, %s epochs " + "(batch %d, alpha0 %.3g, %s)" + % (self._n, self.d, getattr(self, "global_k", self.k), + _format_passes(sum(recipe["epoch_rows"]) / self._n), + recipe["batch_size"], recipe["alpha0"], ", ".join(extras)) + ) + + def _report_header_once(self): + # After begin(), once subclasses have finished the recipe (sharded runs + # re-derive it for the global k), and only for runs that really start. + if getattr(self, "_header_due", False): + self._header_due = False + if self._reports(): + self._report_header() + + def _report_preprocessing(self, start, given_init, n): + # Up to the start of the epoch clock, so no second is counted twice. + self._say(" Preprocessing in %.2f s (%s; assignment: %s)" % ( + self._start_time - start, + "initial centroids given" if given_init + else "every row used as an initial centroid" if n == self.k + else "random initialization from the data, seed %d" % self.seed, + self._describe_assignment())) + + def _report_epoch(self, stat, epoch): + recipe = self.recipe + rows = recipe["epoch_rows"][epoch] + partial = "" if rows == self._n else " (%d of %d rows)" % (rows, self._n) + self._say( + " Epoch %s / %s%s, iteration %d / %d (%.2f s): " + "objective=%g" + % (_format_passes(sum(recipe["epoch_rows"][:epoch + 1]) / self._n), + _format_passes(sum(recipe["epoch_rows"]) / self._n), partial, + sum(recipe["epoch_steps"][:epoch + 1]), recipe["total_steps"], + stat["time"], stat["obj"]) + ) + + def end_epoch(self): + """Finish one complete pass and record its moving-pass objective.""" + self._require_running() + rows = self.recipe["epoch_rows"][self._epoch] + self._failed = True + objective, count_square = self._epoch_totals() + stat = { + "obj": objective, + "time": time.perf_counter() - self._start_time, + "imbalance_factor": self.k * count_square / (rows * rows), + "nsplit": self.n_splits - self._splits_before, + } + self.iteration_stats.append(stat) + self._epoch += 1 + if self._epoch < len(self.recipe["epoch_rows"]): + self._start_epoch() + self._failed = False + if self._reports(): + self._report_epoch(stat, self._epoch - 1) diff --git a/thirdparty/faiss/contrib/e_means/cute.py b/thirdparty/faiss/contrib/e_means/cute.py new file mode 100644 index 000000000..c3f3082b5 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/cute.py @@ -0,0 +1,670 @@ +# 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. + +"""Host adapter for E-means BF16/E4M3/native-byte CuTe assignment on SM90. + +Optional CuTe dependencies are resolved when the CuTe implementation is +selected. Assignment selects between the tiled kernel and a resource-legal +low-dimension row-owned kernel; there is no fallback backend. E4M3 uses tensor-core +partial accumulation with FP32 promotion every 128 contraction coordinates. +Ranking is approximate; distances are recomputed from selected represented operands. +""" + +from collections import OrderedDict +from dataclasses import dataclass, field +from functools import lru_cache +import importlib +import importlib.metadata +import importlib.util +import inspect +import weakref + + +_QUACK_VERSION = "0.6.5" +_CUTLASS_DSL_VERSION = "4.7.1" +_CUDA_PYTHON_MAJOR = 13 +_MIN_OPTIN_SMEM = 227 * 1024 +_TILE_N = 192 +_MAX_BINDINGS = 6 # Keeps top-1, second-distance and second-label bindings of the batch and tail shapes. + + +@lru_cache(maxsize=1) +def _stack_status(): + """Return a stable compatibility result without importing on Faiss load.""" + exact_versions = ( + ("quack-kernels", _QUACK_VERSION), + ("nvidia-cutlass-dsl", _CUTLASS_DSL_VERSION), + ) + try: + for distribution, expected in exact_versions: + if importlib.metadata.version(distribution) != expected: + return False, "%s version mismatch" % distribution + cuda_version = importlib.metadata.version("cuda-python") + if int(cuda_version.split(".", 1)[0]) != _CUDA_PYTHON_MAJOR: + return False, "cuda-python requires major version 13" + for module in ("cutlass", "cuda.bindings.driver", "quack"): + if importlib.util.find_spec(module) is None: + return False, "%s is unavailable" % module + cuda_driver = importlib.import_module("cuda.bindings.driver") + if not callable(getattr(cuda_driver, "CUstream", None)): + return False, "cuda-python ABI mismatch" + ops = importlib.import_module("quack.epilogue.ops") + lane_helper = getattr(ops, "_lane_warp_info_n", None) + if not callable(lane_helper): + return False, "QuACK ABI mismatch" + try: + inspect.signature(lane_helper).bind(object(), object(), object()) + except (TypeError, ValueError): + return False, "QuACK ABI mismatch" + for module, symbol in ( + ("quack.gemm_sm90", "GemmSm90"), + ("quack.tile_scheduler", "TileScheduler"), + ("quack.gemm_tvm_ffi_utils", "compile_gemm_kernel"), + ): + if not hasattr(importlib.import_module(module), symbol): + return False, "QuACK ABI mismatch" + except ( + AttributeError, + ImportError, + TypeError, + ValueError, + importlib.metadata.PackageNotFoundError, + ): + return False, "optional CuTe stack is unavailable" + return True, "ready" + + +def _require_stack(): + available, reason = _stack_status() + if not available: + raise RuntimeError( + "CuTe assignment requires quack-kernels==%s, " + "nvidia-cutlass-dsl==%s, and cuda-python>=13,<14 (%s)" + % ( + _QUACK_VERSION, + _CUTLASS_DSL_VERSION, + reason, + ) + ) + + +def _check_device(device): + """Fail before compilation unless the fixed kernel is legal.""" + import torch + + device = torch.device(device) + if device.type != "cuda": + raise ValueError("CuTe assignment requires a PyTorch CUDA tensor") + if getattr(torch.version, "hip", None) is not None: + raise RuntimeError("CuTe assignment requires NVIDIA CUDA SM90") + if device.index is None: + device = torch.device("cuda", torch.cuda.current_device()) + return _check_cuda_device(device) + + +@lru_cache(maxsize=None) +def _check_cuda_device(device): + """Check pinned-stack and hardware metadata once per explicit CUDA device.""" + import torch + + with torch.cuda.device(device): + _require_stack() + capability = torch.cuda.get_device_capability(device) + if capability != (9, 0): + raise RuntimeError( + "CuTe assignment requires exactly SM90; device is sm%d%d" + % capability + ) + properties = torch.cuda.get_device_properties(device) + smem = getattr(properties, "shared_memory_per_block_optin", None) + if smem is None: + smem = getattr(properties, "shared_memory_per_block", 0) + if smem < _MIN_OPTIN_SMEM: + raise RuntimeError( + "CuTe assignment requires at least %d bytes of opt-in " + "shared memory" + % _MIN_OPTIN_SMEM + ) + + +def _padded_extent(value, alignment): + return ((int(value) + alignment - 1) // alignment) * alignment + + +def _check_extent(name, value): + if value < 1 or value >= 2**31: + raise ValueError("CuTe assignment requires 0 < %s < 2**31" % name) + + +def _check_padded_span(name, rows, dim, element_size=2): + pitch = _padded_extent(dim, 16 // element_size) + if rows * pitch >= 2**31: + raise ValueError("CuTe padded %s storage must fit signed int32" % name) + return pitch + + +def _tensor_version(tensor): + """Return the mutation version, or disable reuse when unavailable.""" + try: + return tensor._version + except (AttributeError, RuntimeError): + return None + + +def _aligned_operand(rows, dim, device, dtype): + import torch + + pitch = _padded_extent(dim, 16 // dtype.itemsize) + if dtype is torch.bfloat16: + preferred = _padded_extent(dim, 16) + # Preserve legal 16B storage when a 32B pitch exceeds the index span. + if rows * preferred < 2**31: + pitch = preferred + if pitch == dim: + return torch.empty((rows, dim), dtype=dtype, device=device) + return torch.zeros((rows, pitch), dtype=dtype, device=device)[ + :, :dim + ] + + +@dataclass +class _PreparedCentroids: + source_ref: object + source_version: int + transform: object + transform_token: object + centroids: object + norms: object + padded_norms: object + peak: object = None + representation: object = None + bindings: OrderedDict = field(default_factory=OrderedDict) + transform_bias: object = None + spherical: bool = False + + @property + def num_centroids(self): + return self.centroids.shape[0] + + @property + def dim(self): + return self.centroids.shape[1] + + +@dataclass +class _Binding: + workspace: object + codes: object + scores: object + labels: object + launcher: object + kernel: object + row_norms: object = None + prepared_row_norms: object = None + second_scores: object = None + second_labels: object = None # Second-nearest indices written by the kernel. + + +def _can_refresh(cached, centroids): + return ( + isinstance(cached, _PreparedCentroids) + and cached.centroids.device == centroids.device + and cached.centroids.shape == centroids.shape + ) + + +def _transform_parameter(transform): + if transform is None: + return None + from .quantizer import CastQuantizer + + return transform.shift if isinstance(transform, CastQuantizer) else transform._bias + + +def _transform_token(transform): + if transform is None: + return None + # The prepared object retains transform, so its identity cannot be reused. + from .quantizer import CastQuantizer + + if isinstance(transform, CastQuantizer): + return id(transform), transform._fit_token() + bias = transform._bias + version = None if bias is None else _tensor_version(bias) + return ( + id(transform), + transform.scale, + None + if bias is None + # Versionless parameters cannot prove an unchanged transform. + else (bias.data_ptr(), version if version is not None else object(), bias.device), + ) + + +def _refresh_prepared(cached, centroids, source_version, transform, peak_out): + import torch + + if cached.centroids.dtype is torch.int8: + from .cute_argmin import stage_int8_rows + from .quantizer_int8 import _ENCODE_CHUNK_ELEMENTS + from .quantizer import _transform + + chunk = (len(centroids) if transform is None + else max(1, _ENCODE_CHUNK_ELEMENTS // centroids.shape[1])) + for begin in range(0, len(centroids), chunk): + end = min(begin + chunk, len(centroids)) + stage_int8_rows(_transform(centroids[begin:end].detach(), transform), + cached.centroids[begin:end], cached.norms[begin:end], + cached.representation) + elif cached.centroids.dtype is torch.bfloat16: + from .cute_argmin import affine_cast + + wide = None if cached.spherical else torch.empty_like(centroids) + value = (centroids.detach() if transform is None + else transform._center_rows(centroids.detach())) + affine_cast(value, None, 1.0, cached.centroids, None, squares=wide) + torch.autograd.graph.increment_version(cached.centroids) + if cached.spherical: + cached.norms.zero_() + else: + torch.sum(wide, dim=1, out=cached.norms) + else: + from .cute_argmin import affine_cast + from .quantizer_fp8 import _check_fp8_range + + peak = centroids.new_zeros(()) if peak_out is None else peak_out + cached.peak = peak + wide = torch.empty_like(centroids) + affine_cast(centroids.detach(), None if transform is None else transform._bias, + 1.0 if transform is None else transform.scale, + cached.centroids, peak, squares=wide) + torch.sum(wide, dim=1, out=cached.norms) + if peak_out is None: + _check_fp8_range(peak, "centroids") + cached.source_ref = weakref.ref(centroids) + cached.source_version = source_version + cached.transform = transform + # Retain this particular bias; the quantizer may replace its parameters. + cached.transform_bias = _transform_parameter(transform) + cached.transform_token = _transform_token(transform) + return cached + + +def _prepare_centroids(centroids, cached=None, transform=None, peak_out=None, dtype=None, spherical=False): + """Round one FP32 centroid state and compute norms from that mirror. + + Repeated public assignment reuses an unchanged installed centroid tensor. + A new same-shape training readout refreshes its mirror and norms in place, + preserving pointer-bound assignment workspaces across statistical batches. + Refresh and assignment are ordered on the caller's current CUDA stream. + """ + import torch + + if not isinstance(centroids, torch.Tensor): + raise TypeError("centroids must be a tensor") + _check_device(centroids.device) + if centroids.ndim != 2: + raise ValueError("centroids must be rank two") + if ( + not centroids.is_cuda + or centroids.dtype is not torch.float32 + or not centroids.is_contiguous() + ): + raise ValueError("centroids must be contiguous CUDA FP32") + dtype = torch.bfloat16 if dtype is None else dtype + if spherical and (dtype is not torch.bfloat16 or transform is not None): + raise ValueError("spherical CuTe requires unencoded BF16 operands") + if dtype is torch.bfloat16 and transform is not None: + from .quantizer import CastQuantizer + + if not isinstance(transform, CastQuantizer) or not transform.center: + raise ValueError("BF16 transform requires a centered CastQuantizer") + representation = ("int8" if dtype is torch.int8 else + "uint8" if dtype is torch.uint8 else None) + if dtype not in (torch.bfloat16, torch.float8_e4m3fn, torch.int8, torch.uint8): + raise ValueError("CuTe operands must be BF16, E4M3 or native bytes") + if representation is not None: + if centroids.shape[1] > 43919: + raise ValueError("INT8 assignment requires d <= 43919") + dtype = torch.int8 + k, dim = centroids.shape + _check_extent("K", k) + _check_extent("d", dim) + _check_padded_span("centroid", k, dim, dtype.itemsize) + padded_k = _padded_extent(k, _TILE_N) + if padded_k >= 2**31: + raise ValueError("CuTe padded centroid IDs must fit signed int32") + source_version = _tensor_version(centroids) + transform_token = _transform_token(transform) + if ( + isinstance(cached, _PreparedCentroids) + and cached.source_ref() is centroids + and source_version is not None + and cached.source_version == source_version + and cached.transform_bias is _transform_parameter(transform) + and cached.transform_token == transform_token + and cached.centroids.dtype is dtype + and cached.representation == representation + and cached.spherical == spherical + ): + if dtype is torch.float8_e4m3fn: + from .quantizer_fp8 import _check_fp8_range + + with torch.cuda.device(centroids.device): + if peak_out is None: + _check_fp8_range(cached.peak, "centroids") + elif peak_out is not cached.peak: + torch.maximum(peak_out, cached.peak, out=peak_out) + return cached + + with torch.cuda.device(centroids.device): + if _can_refresh(cached, centroids) and cached.centroids.dtype is dtype: + cached.representation = representation + cached.spherical = spherical + return _refresh_prepared(cached, centroids, source_version, transform, peak_out) + mirror = _aligned_operand(k, dim, centroids.device, dtype) + storage = torch.empty( + padded_k, dtype=torch.int32 if representation is not None else torch.float32, + device=centroids.device + ) + if padded_k != k: + storage[k:].fill_(torch.iinfo(torch.int32).max + if representation is not None else float("inf")) + prepared = _PreparedCentroids( + None, + None, + None, + None, + mirror, + storage[:k], + storage.view(1, padded_k), + representation=representation, + spherical=spherical, + ) + return _refresh_prepared(prepared, centroids, source_version, transform, peak_out) + + +# Runner-up IDs retain their early admission. Second distances share it from +# 32 centroid tiles (4096 centroids); top-one keeps its B*k cutoff. +# All modes retain the same plan legality checks below. +_GROUPED_LABEL_MIN_ROWS = 16384 + + +def _grouped_plan(batch, prepared, distance_dtype, second=0): + """Choose a legal BF16 plan using coarse measured work and grid size.""" + import torch + + early = (batch >= _GROUPED_LABEL_MIN_ROWS + and (second == 2 or (second == 1 and prepared.num_centroids >= 4096))) + if ((batch * prepared.num_centroids < 2**31 and not early) + or prepared.centroids.dtype is not torch.bfloat16 + or distance_dtype is not torch.float32): + return None + from .cute_grouped import _plan_fits_smem + from .cute_row_owned import _row_owned_shape_legal + + if not _row_owned_shape_legal(batch, prepared.num_centroids, prepared.dim): + return None + + properties = torch.cuda.get_device_properties(prepared.centroids.device) + if (properties.major, properties.minor) != (9, 0): + return None + # Prefer M256 with a full grid wave plus half a second wave. + wide_grid = (batch + 255) // 256 >= (3 * properties.multi_processor_count + 1) // 2 + plans = ((256, 3), (128, 3), (128, 2)) if wide_grid else ((128, 3), (128, 2)) + for tile_m, stages in plans: + tile_k = _padded_extent(prepared.dim, 16 if tile_m == 256 else 32) + plan = tile_k, tile_m, stages + if _plan_fits_smem(torch.bfloat16, plan, properties.shared_memory_per_block_optin): + return plan + return None + + +def _new_binding(batch, prepared, distance_dtype, second=0): + """``second``: 0 top-1 only, 1 also second distances, 2 also second labels.""" + import torch + + plan = _grouped_plan(batch, prepared, distance_dtype, second) + if plan is not None: + return _new_grouped_binding(batch, prepared, distance_dtype, plan=plan, second=second) + + from .cute_kernel import ( + launch_tiled_gemm, + prepare_tiled_gemm, + ) + from .cute_row_owned import ( + launch_row_owned, + prepare_row_owned, + row_owned_plan, + ) + + _check_extent("B", batch) + _check_padded_span("row", batch, prepared.dim, prepared.centroids.element_size()) + with torch.cuda.device(prepared.centroids.device): + workspace = _aligned_operand( + batch, prepared.dim, prepared.centroids.device, prepared.centroids.dtype + ) + scores = torch.empty( + batch, dtype=distance_dtype, device=workspace.device + ) + row_norms = ( + torch.empty( + batch, + dtype=( + torch.int32 if workspace.dtype is torch.int8 else torch.float32 + ), + device=workspace.device, + ) + if workspace.dtype in (torch.int8, torch.float8_e4m3fn) + else None + ) + second_scores = torch.empty_like(scores) if second else None + labelled = second == 2 or (bool(second) and workspace.dtype in (torch.int8, torch.float8_e4m3fn)) + second_label_dtype = (torch.int64 if workspace.dtype in (torch.int8, torch.float8_e4m3fn) + else torch.int32) + second_labels = (torch.empty(batch, dtype=second_label_dtype, device=workspace.device) + if labelled else None) + plan = row_owned_plan( + batch, + prepared.num_centroids, + prepared.dim, + workspace.device, + workspace.dtype, + ) + if plan is not None: + labels = torch.empty( + batch, dtype=torch.int64, device=workspace.device + ) + codes = None + kernel = prepare_row_owned( + workspace, + prepared, + scores, + labels, + plan, + row_norms=row_norms if workspace.dtype is torch.int8 else None, + second_scores=second_scores, + second_labels=second_labels, + ) + launcher = launch_row_owned + else: + labels = None + codes = torch.empty( + batch, dtype=torch.int64, device=workspace.device + ) + kernel = prepare_tiled_gemm(workspace, prepared, codes, scores, + row_norms if workspace.dtype is torch.int8 else None, + second_scores, second_labels=labelled) + launcher = launch_tiled_gemm + # The tiled kernel decodes second labels from its second keys. + second_labels = kernel.second_codes + return _Binding(workspace, codes, scores, labels, launcher, kernel, row_norms, + second_scores=second_scores, second_labels=second_labels) + + +def _new_grouped_binding(batch, prepared, distance_dtype, *, plan, second=0): + """Prepare the shared BF16 route with fixed grouping/output buffers.""" + import torch + + from .cute_grouped import launch_grouped, prepare_grouped + + if (prepared.centroids.dtype is not torch.bfloat16 + or prepared.representation is not None or distance_dtype is not torch.float32): + raise ValueError('private grouped integration currently requires unencoded BF16 operands/FP32 scores') + _check_extent('B', batch) + _check_padded_span('row', batch, prepared.dim, prepared.centroids.element_size()) + with torch.cuda.device(prepared.centroids.device): + workspace = _aligned_operand(batch, prepared.dim, prepared.centroids.device, torch.bfloat16) + scores = torch.empty(batch, dtype=torch.float32, device=workspace.device) + labels = torch.empty(batch, dtype=torch.int64, device=workspace.device) + second_scores = torch.empty_like(scores) if second else None + second_labels = torch.empty(batch, dtype=torch.int32, device=workspace.device) if second == 2 else None + # Both operands come from _aligned_operand (zeros past d up to the pitch); only the + # label variant uses that to gather whole vectors. + kernel = prepare_grouped(workspace, prepared, scores, labels, plan, second_scores, second_labels, + zero_padded=second_labels is not None) + return _Binding(workspace, None, scores, labels, launch_grouped, kernel, + second_scores=second_scores, second_labels=second_labels) + + +def _binding_key(batch, distance_dtype=None, second=0): + import torch + distance_dtype = torch.float32 if distance_dtype is None else distance_dtype + key = batch if distance_dtype is torch.float32 else (batch, distance_dtype) + return (key, "second") if second == 1 else (key, "second_labels") if second else key + + +def _binding_for(batch, prepared, distance_dtype=None, second=0): + import torch + distance_dtype = torch.float32 if distance_dtype is None else distance_dtype + key = _binding_key(batch, distance_dtype, second) + binding = prepared.bindings.pop(key, None) + if binding is None: + binding = _new_binding(batch, prepared, distance_dtype, second) + prepared.bindings[key] = binding + while len(prepared.bindings) > _MAX_BINDINGS: + prepared.bindings.popitem(last=False) + return binding + + +def _assign_rows(rows, prepared, distance_out=None, labels_out=None, second_out=None, + second_labels_out=None, *, scores=False): + """Assign rows into FP32 distances and INT64 labels; raw distances may be INT64. + + Optional second_out must be a same-device contiguous FP32 vector of row length. + Optional second_labels_out (with second_out) receives second-nearest indices + as a same-device contiguous INT32 vector; ties order by index. + + Calibrated FP8 retains this call's encoded rows in + the actual mode/distance-dtype binding selected by _binding_key. Statistics + consume that binding's workspace + on the caller-ordered stream before a later assignment can overwrite it. + """ + import torch + + _require_stack() + if not isinstance(prepared, _PreparedCentroids): + raise TypeError("prepared centroids have the wrong type") + if scores and prepared.centroids.dtype in (torch.int8, torch.float8_e4m3fn): + raise ValueError("scores=True requires unencoded floating operands") + if not isinstance(rows, torch.Tensor) or rows.ndim != 2: + raise ValueError("rows must be a rank-two tensor") + if ( + not rows.is_cuda + or (rows.dtype is not (torch.uint8 if prepared.representation == "uint8" + else prepared.centroids.dtype) + and not (prepared.centroids.dtype is torch.float8_e4m3fn + and prepared.transform is not None and rows.dtype is torch.float32)) + or not rows.is_contiguous() + ): + raise ValueError("rows must be contiguous CUDA BF16/E4M3/native-byte operands or FP32 FP8 input") + if rows.device != prepared.centroids.device: + raise ValueError("rows and centroids must be on the same device") + if rows.shape[1] != prepared.dim: + raise ValueError("rows and centroids must have the same dimension") + if rows.shape[0] < 1: + raise ValueError("rows must not be empty") + + from .cute_argmin import require_tensor + + if distance_out is None: + distance_out = torch.empty(len(rows), dtype=torch.float32, device=rows.device) + if labels_out is None: + labels_out = torch.empty(len(rows), dtype=torch.int64, device=rows.device) + distance_dtype = distance_out.dtype + raw_integer = prepared.centroids.dtype is torch.int8 and distance_dtype is torch.int64 + if distance_dtype is not torch.float32 and not raw_integer: + raise ValueError("INT64 distances require integer operands") + require_tensor(distance_out, "distances", dtype=distance_dtype, shape=(len(rows),), device=rows.device) + require_tensor(labels_out, "labels", dtype=torch.int64, shape=(len(rows),), device=rows.device) + if second_out is not None: + require_tensor(second_out, "second distances", dtype=distance_dtype, shape=(len(rows),), device=rows.device) + if second_labels_out is not None: + if second_out is None: + raise ValueError("second labels require second_out") + encoded = prepared.centroids.dtype in (torch.int8, torch.float8_e4m3fn) + label_dtype = second_labels_out.dtype if encoded and second_labels_out.dtype == torch.int64 else torch.int32 + require_tensor(second_labels_out, "second labels", dtype=label_dtype, shape=(len(rows),), + device=rows.device) + if second_out is not None and prepared.centroids.dtype in (torch.int8, torch.float8_e4m3fn) and prepared.num_centroids < 2: + raise ValueError("encoded SECOND requires at least two centroids") + second = 0 if second_out is None else 1 if second_labels_out is None else 2 + with torch.cuda.device(rows.device): + binding = _binding_for(rows.shape[0], prepared, distance_dtype, second) + if prepared.centroids.dtype is torch.int8: + from .cute_argmin import stage_int8_rows + + stage_int8_rows(rows, binding.workspace, binding.row_norms, + prepared.representation) + binding.launcher(binding.kernel, labels_out, distance_out) + elif prepared.centroids.dtype is torch.bfloat16: + binding.workspace.copy_(rows) + norms = distance_out + if not (prepared.spherical or scores): + torch.linalg.vector_norm(binding.workspace, dim=1, dtype=torch.float32, out=norms) + norms.square_() + else: + from .cute_argmin import ( + affine_cast, + launch_row_norms, + prepare_row_norms, + ) + + if rows.dtype is torch.float32: + q = prepared.transform + affine_cast(rows, q._bias, q.scale, binding.workspace, None, + packed_rows=True) + else: + binding.workspace.copy_(rows) + + if prepared.centroids.dtype is not torch.int8: + binding.launcher(binding.kernel, labels_out) + if prepared.centroids.dtype is torch.float8_e4m3fn: + if binding.prepared_row_norms is None: + binding.prepared_row_norms = prepare_row_norms( + binding.workspace, binding.row_norms, prepared.centroids) + launch_row_norms(binding.prepared_row_norms, distance_out, labels_out) + if second_out is not None: + launch_row_norms(binding.prepared_row_norms, binding.second_scores, binding.second_labels) + elif prepared.centroids.dtype is torch.bfloat16: + if second_out is not None and (prepared.spherical or scores): + second_out.copy_(binding.second_scores) + elif second_out is not None: + torch.add(norms, binding.second_scores, out=second_out).clamp_min_(0) + if prepared.spherical or scores: + distance_out.copy_(binding.scores) + else: + torch.add(norms, binding.scores, out=distance_out).clamp_min_(0) + if second_labels_out is not None: + second_labels_out.copy_(binding.second_labels) + if second_out is not None and prepared.centroids.dtype is not torch.bfloat16: + second_out.copy_(binding.second_scores) + if prepared.transform is not None and prepared.centroids.dtype is not torch.bfloat16 and not raw_integer: + # Operand-device scope retains stock ldexp for subnormal distances and zero. + torch.ldexp(distance_out, prepared.transform._distance_exponent, + out=distance_out) + if second_out is not None: + torch.ldexp(second_out, prepared.transform._distance_exponent, out=second_out) + return distance_out, labels_out diff --git a/thirdparty/faiss/contrib/e_means/cute_argmin.py b/thirdparty/faiss/contrib/e_means/cute_argmin.py new file mode 100644 index 000000000..db8724783 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/cute_argmin.py @@ -0,0 +1,609 @@ +# 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. + +"""Packed score/centroid-ID argmin and operand preparation for CuTe.""" + +from collections import OrderedDict +import math +from typing import NamedTuple + +import cuda.bindings.driver as cuda +import cutlass.cute as cute +from cutlass import BFloat16, Float32, Int8, Int32, Int64, Uint32, const_expr +from cutlass.cute.runtime import from_dlpack +from quack import utils as quack_utils +import torch + +_THREADS = 256 +INITIAL_KEY = 0x7F80000000000000 +_COMPILED = OrderedDict() +_AFFINE_PREPARE_COMPILED = OrderedDict() +_STAGE_ROW_NORMS_COMPILED = OrderedDict() +_PACKED_ROWS = 8 +_INT8_STAGE_COMPILED = OrderedDict() +INTEGER_INITIAL_KEY = 0x7FFFFFFFFFFFFFFF + + +def require_tensor( + tensor, + name, + *, + dtype=None, + shape=None, + device=None, + contiguous=True, +): + """Validate one tensor passed to a raw-pointer CuTe binding.""" + if not isinstance(tensor, torch.Tensor): + raise TypeError("%s must be a tensor" % name) + if not tensor.is_cuda: + raise ValueError("%s must be a CUDA tensor" % name) + if dtype is not None and tensor.dtype is not dtype: + raise ValueError( + "%s must be %s" % (name, str(dtype).split(".")[-1]) + ) + if shape is not None and tuple(tensor.shape) != tuple(shape): + raise ValueError("%s must have shape %s" % (name, tuple(shape))) + if device is not None and tensor.device != device: + raise ValueError("%s must be on %s" % (name, device)) + if contiguous and not tensor.is_contiguous(): + raise ValueError("%s must be contiguous" % name) + return tensor + + +@cute.jit +def encode_argmin_key(score: Float32, code: Int32) -> Int64: + """Encode native FP32 ordering, canonical signed zero, then lower ID.""" + score = Float32(0.0) if score == 0.0 else score + bits = score.bitcast(Uint32) + ordered = ~bits if (bits >> 31) != 0 else bits ^ Uint32(0x80000000) + return ( + (ordered.to(Int64) - Int64(0x80000000)) * Int64(0x100000000) + + code.to(Int64) + ) + + +@cute.jit +def decode_argmin_score(key: Int64) -> Float32: + """Invert the ordered FP32 word in a packed argmin key.""" + signed_order = (key >> Int64(32)).to(Int32) + ordered = (signed_order.to(Int64) + Int64(0x80000000)).to(Uint32) + score_bits = ( + ordered ^ Uint32(0x80000000) + if (ordered >> 31) != 0 + else ~ordered + ) + return score_bits.bitcast(Float32) + + +@torch.no_grad() +def stage_int8_rows(x, out, norms, representation): + """Stage native bytes or quantize FP32 rows into INT8 with INT32 norms.""" + if representation not in ("int8", "uint8"): + raise ValueError("unknown native-byte representation") + quantize = isinstance(x, torch.Tensor) and x.dtype is torch.float32 + expected = (torch.float32 if quantize else + torch.int8 if representation == "int8" else torch.uint8) + require_tensor( + x, "native-byte rows", dtype=expected, contiguous=False + ) + if x.ndim != 2: + raise ValueError("native-byte rows must be rank two") + require_tensor( + out, + "signed row mirror", + dtype=torch.int8, + shape=x.shape, + device=x.device, + contiguous=False, + ) + require_tensor( + norms, + "row norms", + dtype=torch.int32, + shape=(len(x),), + device=x.device, + ) + if x.stride(1) != 1 or out.stride(1) != 1: + raise ValueError("native-byte rows and mirror need unit inner stride") + input_pitch = x.stride(0) + output_pitch = out.stride(0) + if input_pitch < x.shape[1] or output_pitch < x.shape[1]: + raise ValueError("native-byte row pitches must cover the dimension") + if output_pitch % 16 or out.data_ptr() % 16: + raise ValueError("signed row mirror must retain 16-byte alignment") + input_storage = x.as_strided((len(x), input_pitch), (input_pitch, 1)) + output_storage = out.as_strided((len(x), output_pitch), (output_pitch, 1)) + with torch.cuda.device(x.device): + flat_x, flat_out = input_storage.reshape(-1), output_storage.reshape(-1) + key = ( + _PACKED_ROWS, + tuple(x.shape), + input_pitch, + output_pitch, + representation, + quantize, + x.device.index, + ) + compiled = _INT8_STAGE_COMPILED.pop(key, None) + if compiled is None: + compiled = cute.compile( + _StageRowNormsSm90( + integer=True, + unsigned=representation == "uint8", + quantize=quantize, + ), + from_dlpack(flat_x, assumed_align=4 if quantize else 1), + from_dlpack(flat_out, assumed_align=16), + from_dlpack(flat_out, assumed_align=16), + from_dlpack(norms, assumed_align=4), + from_dlpack(norms, assumed_align=4), + Int64(x.shape[1]), + Int64(input_pitch), + Int64(output_pitch), + Int64(output_pitch), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + _INT8_STAGE_COMPILED[key] = compiled + while len(_INT8_STAGE_COMPILED) > 4: + _INT8_STAGE_COMPILED.popitem(last=False) + compiled( + flat_x, flat_out, flat_out, norms, norms, + x.shape[1], input_pitch, output_pitch, output_pitch, + ) + + +class _AffineCastSm90: + """Store a BF16/E4M3 mirror with optional rounded squares and peak.""" + + def __init__( + self, centered, rows_per_block=1, with_peak=True, with_squares=False + ): + self.centered = centered + self.rows_per_block = rows_per_block + self.with_peak = with_peak + self.with_squares = with_squares + + @cute.jit + def __call__( + self, x, bias, out, peak, squares, scale, dim, pitch, stream + ): + rows = x.shape[0] // dim + self.kernel(x, bias, out, peak, squares, scale, dim, pitch).launch( + grid=( + (rows + self.rows_per_block - 1) // self.rows_per_block, + 1, + 1, + ), + block=(32 * self.rows_per_block, 1, 1), + stream=stream, + ) + + @cute.kernel + def kernel( + self, + x: cute.Tensor, + bias: cute.Tensor, + out: cute.Tensor, + peak: cute.Tensor, + squares: cute.Tensor, + scale: Float32, + dim: Int64, + pitch: Int64, + ): + thread, _, _ = cute.arch.thread_idx() + block, _, _ = cute.arch.block_idx() + thread = thread.to(Int64) + lane = thread % Int64(32) + row = ( + block.to(Int64) * Int64(self.rows_per_block) + + thread // Int64(32) + ) + rows = x.shape[0] // dim + column = lane + local_peak = Float32(0.0) + if row < rows: + while column < pitch: + output_index = row * pitch + column + if column < dim: + if const_expr(out.element_type is BFloat16): + value = x[row * dim + column] + else: + value = x[row * dim + column] * scale + if const_expr(self.centered): + value += bias[column] + if const_expr(self.with_peak): + absolute = -value if value < 0.0 else value + absolute = Float32.inf if value != value else absolute + local_peak = ( + absolute if absolute > local_peak else local_peak + ) + rounded = value.to(out.element_type) + out[output_index] = rounded + if const_expr(self.with_squares): + wide = rounded.to(Float32) + if const_expr(out.element_type is BFloat16): + squares[row * dim + column] = cute.math.mul( + wide, wide, rounding=cute.math.RoundingMode.NEAREST_EVEN, + ftz=False) + else: + squares[row * dim + column] = wide * wide + else: + out[output_index] = Float32(0.0).to(out.element_type) + column += Int64(32) + if const_expr(self.with_peak): + for offset in (16, 8, 4, 2, 1): + other_peak = cute.arch.shuffle_sync_bfly( + local_peak, offset=offset + ) + local_peak = ( + other_peak if other_peak > local_peak else local_peak + ) + if const_expr(self.with_peak): + if lane == 0: + cute.arch.atomic_fmax( + quack_utils.elem_pointer(peak, 0).llvm_ptr, + local_peak, + sem="relaxed", + scope="gpu", + ) + + +class _StageRowNormsSm90: + """Stage signed bytes and norms, or reduce selected FP8 differences.""" + + def __init__( + self, + integer=False, + unsigned=False, + rows_per_block=_PACKED_ROWS, + quantize=False, + ): + self.integer = integer + self.unsigned = unsigned + self.quantize = quantize + self.rows_per_block = rows_per_block + + @cute.jit + def __call__( + self, x, out, centroids, labels, norms, dim, input_pitch, output_pitch, + centroid_pitch, stream + ): + rows = norms.shape[0] + self.kernel( + x, out, centroids, labels, norms, dim, input_pitch, output_pitch, + centroid_pitch + ).launch( + grid=((rows + self.rows_per_block - 1) // self.rows_per_block, + 1, 1), + block=(32 * self.rows_per_block, 1, 1), + stream=stream, + ) + + @cute.kernel + def kernel( + self, + x: cute.Tensor, + out: cute.Tensor, + centroids: cute.Tensor, + labels: cute.Tensor, + norms: cute.Tensor, + dim: Int64, + input_pitch: Int64, + output_pitch: Int64, + centroid_pitch: Int64, + ): + thread, _, _ = cute.arch.thread_idx() + block, _, _ = cute.arch.block_idx() + thread = thread.to(Int64) + lane = thread % Int64(32) + row = (block.to(Int64) * Int64(self.rows_per_block) + + thread // Int64(32)) + rows = norms.shape[0] + column = lane + if const_expr(self.integer): + total = Int32(0) + if row < rows: + while column < output_pitch: + output_index = row * output_pitch + column + if column < dim: + if const_expr(self.quantize): + code = x[row * input_pitch + column] + if const_expr(self.unsigned): + code -= Float32(128.0) + code = cute.math.roundeven(code) + code = Float32(-128.0) if code < -128.0 else code + code = Float32(127.0) if code > 127.0 else code + value = code.to(Int32) + else: + value = x[row * input_pitch + column].to(Int32) + if const_expr(self.unsigned): + value -= Int32(128) + out[output_index] = value.to(Int8) + total += value * value + else: + out[output_index] = Int32(0).to(Int8) + column += Int64(32) + else: + total = Float32(0.0) + if row < rows: + while column < dim: + stored = x[ + row * input_pitch + column + ].to(Float32) + stored -= centroids[labels[row] * centroid_pitch + column].to(Float32) + total += stored * stored + column += Int64(32) + for offset in (16, 8, 4, 2, 1): + total += cute.arch.shuffle_sync_bfly(total, offset=offset) + if row < rows and lane == 0: + norms[row] = total + + +class PreparedRowNorms(NamedTuple): + compiled: object + flat_mirror: torch.Tensor + mirror: torch.Tensor + norms: torch.Tensor + centroids: torch.Tensor + flat_centroids: torch.Tensor + + +@torch.no_grad() +def prepare_row_norms(mirror, norms, centroids): + """Bind E4M3 operands for selected-centroid direct distances.""" + require_tensor(mirror, "E4M3 mirror", dtype=torch.float8_e4m3fn, + contiguous=False) + if mirror.ndim != 2 or mirror.stride(1) != 1: + raise ValueError("E4M3 mirror must be a row-major matrix") + require_tensor(norms, "row norms", dtype=torch.float32, + shape=(len(mirror),), device=mirror.device) + dim = mirror.shape[1] + pitch = mirror.stride(0) + if pitch < dim: + raise ValueError("E4M3 mirror pitch must cover its dimension") + storage = mirror.as_strided((len(mirror), pitch), (pitch, 1)).reshape(-1) + require_tensor(centroids, "E4M3 centroids", dtype=mirror.dtype, + device=mirror.device, contiguous=False) + if centroids.ndim != 2 or centroids.shape[1] != dim or centroids.stride(1) != 1: + raise ValueError("centroids must match the row dimension") + centroid_pitch = centroids.stride(0) + flat_centroids = centroids.as_strided((len(centroids), centroid_pitch), + (centroid_pitch, 1)).reshape(-1) + labels = torch.empty(len(mirror), dtype=torch.int64, device=mirror.device) + with torch.cuda.device(mirror.device): + key = (_PACKED_ROWS, tuple(mirror.shape), pitch, + tuple(centroids.shape), centroid_pitch, mirror.device.index) + compiled = _STAGE_ROW_NORMS_COMPILED.pop(key, None) + if compiled is None: + compiled = cute.compile( + _StageRowNormsSm90(), + from_dlpack(storage, assumed_align=16), + from_dlpack(storage, assumed_align=16), + from_dlpack(flat_centroids, assumed_align=16), + from_dlpack(labels, assumed_align=4), + from_dlpack(norms, assumed_align=4), + Int64(dim), + Int64(pitch), + Int64(pitch), + Int64(centroid_pitch), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + _STAGE_ROW_NORMS_COMPILED[key] = compiled + while len(_STAGE_ROW_NORMS_COMPILED) > 4: + _STAGE_ROW_NORMS_COMPILED.popitem(last=False) + return PreparedRowNorms(compiled, storage, mirror, norms, centroids, flat_centroids) + + +@torch.no_grad() +def launch_row_norms(prepared, norms_out=None, labels=None): + """Reduce on the caller's current CUDA stream into the actual destination.""" + if not isinstance(prepared, PreparedRowNorms): + raise TypeError("prepared row norms have the wrong type") + norms = prepared.norms if norms_out is None else norms_out + require_tensor(norms, "row norms", dtype=torch.float32, + shape=prepared.norms.shape, device=prepared.norms.device) + require_tensor(labels, "labels", dtype=torch.int64, + shape=norms.shape, device=norms.device) + with torch.cuda.device(prepared.mirror.device): + prepared.compiled(prepared.flat_mirror, prepared.flat_mirror, + prepared.flat_centroids, + labels, norms, + prepared.mirror.shape[1], prepared.mirror.stride(0), + prepared.mirror.stride(0), + prepared.centroids.stride(0)) + + +@torch.no_grad() +def affine_cast( + x, bias, scale, out, peak, *, packed_rows=False, squares=None +): + """Write a BF16/E4M3 mirror, optional rounded squares and transformed peak.""" + require_tensor(x, "rows", dtype=torch.float32) + require_tensor(out, "mirror", contiguous=False) + if out.dtype not in (torch.float8_e4m3fn, torch.bfloat16): + raise ValueError("mirror must be E4M3 or BF16") + if out.dtype is torch.bfloat16 and (bias is not None or scale != 1.0 or peak is not None): + raise ValueError("BF16 mirror requires identity scale, no bias and no peak") + with_peak = peak is not None + with_squares = squares is not None + if with_squares: + require_tensor(squares, "squares", dtype=torch.float32, + shape=x.shape, device=x.device) + if with_peak: + require_tensor( + peak, "peak", dtype=torch.float32, shape=(), device=x.device + ) + valid_scale = math.isfinite(scale) and scale > 0.0 + if not valid_scale or not math.log2(scale).is_integer(): + raise ValueError("FP8 assignment scale must be a power of two") + if scale > torch.finfo(torch.float32).max: + raise ValueError("FP8 assignment scale exceeds the FP32 range") + if with_peak and peak.requires_grad: + raise ValueError("FP8 peak accumulator does not match input") + if out.device != x.device or out.shape != x.shape or out.stride(1) != 1: + raise ValueError("mirror does not match rows") + centered = bias is not None + if centered: + require_tensor( + bias, + "bias", + dtype=torch.float32, + shape=(x.shape[1],), + device=x.device, + ) + bound_bias = bias + else: + bound_bias = x[0] + bound_peak = peak if with_peak else x[0] + pitch = out.stride(0) + storage = out.as_strided((len(x), pitch), (pitch, 1)) + with torch.cuda.device(x.device): + args = (x.reshape(-1), bound_bias, storage.reshape(-1), bound_peak, + (squares if with_squares else x).reshape(-1)) + rows_per_block = _PACKED_ROWS if packed_rows else 1 + key = ( + tuple(x.shape), + pitch, + centered, + rows_per_block, + with_peak, + with_squares, + out.dtype, + x.device.index, + ) + compiled = _AFFINE_PREPARE_COMPILED.pop(key, None) + if compiled is None: + operation = _AffineCastSm90(centered, rows_per_block, with_peak, with_squares) + specs = tuple(from_dlpack(tensor, assumed_align=16 if i == 2 else 4) + for i, tensor in enumerate(args)) + compiled = cute.compile( + operation, *specs, Float32(scale), Int64(x.shape[1]), Int64(pitch), + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi", + ) + _AFFINE_PREPARE_COMPILED[key] = compiled + while len(_AFFINE_PREPARE_COMPILED) > 4: + _AFFINE_PREPARE_COMPILED.popitem(last=False) + compiled(*args, scale, x.shape[1], pitch) + + +class _DecodeArgminOutputsSm90: + @cute.jit + def __call__( + self, + keys: cute.Tensor, + codes: cute.Tensor, + scores: cute.Tensor, + stream: cuda.CUstream, + ): + self.kernel(keys, codes, scores).launch( + grid=(cute.ceil_div(codes.shape[0], _THREADS), 1, 1), + block=(_THREADS, 1, 1), + stream=stream, + ) + + @cute.kernel + def kernel( + self, + keys: cute.Tensor, + codes: cute.Tensor, + scores: cute.Tensor, + ): + tidx, _, _ = cute.arch.thread_idx() + bidx, _, _ = cute.arch.block_idx() + row = bidx * _THREADS + tidx + if row < codes.shape[0]: + key = keys[row] + codes[row] = (key & Int64(0xFFFFFFFF)).to(Int32) + scores[row] = decode_argmin_score(key) + keys[row] = Int64(INITIAL_KEY) + + +class PreparedArgminDecode(NamedTuple): + compiled: object + keys: torch.Tensor + codes: torch.Tensor + scores: torch.Tensor + + +@torch.no_grad() +def prepare_argmin_decode(keys, codes, scores): + """Bind stable private outputs and compile their decode/reset kernel.""" + require_tensor(keys, "keys", dtype=torch.int64) + count = keys.numel() + if codes.dtype not in (torch.int32, torch.int64): + raise ValueError("codes must be int32 or int64") + require_tensor( + codes, + "codes", + shape=(count,), + device=keys.device, + ) + require_tensor( + scores, + "scores", + dtype=torch.float32, + shape=(count,), + device=keys.device, + ) + flat_keys = keys.reshape(-1) + keys_cute = from_dlpack(flat_keys, assumed_align=8).mark_layout_dynamic() + codes_cute = from_dlpack(codes, assumed_align=4).mark_layout_dynamic() + scores_cute = from_dlpack(scores, assumed_align=4).mark_layout_dynamic() + stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) + cache_key = (keys.device.index, codes.dtype) + compiled = _COMPILED.pop(cache_key, None) + if compiled is None: + compiled = cute.compile( + _DecodeArgminOutputsSm90(), + keys_cute, + codes_cute, + scores_cute, + stream, + options="--enable-tvm-ffi", + ) + _COMPILED[cache_key] = compiled + while len(_COMPILED) > 2: + _COMPILED.popitem(last=False) + return PreparedArgminDecode( + compiled, + flat_keys, + codes, + scores, + ) + + +@torch.no_grad() +def launch_argmin_decode(prepared, codes_out=None): + """Decode on the caller's current stream and restore the key sentinel.""" + if codes_out is not None: + require_tensor(codes_out, "codes", dtype=prepared.codes.dtype, + shape=prepared.codes.shape, device=prepared.codes.device) + codes = prepared.codes if codes_out is None else codes_out + with torch.cuda.device(prepared.scores.device): + prepared.compiled(prepared.keys, codes, prepared.scores) + + +@torch.no_grad() +def finalize_int8_outputs(prepared, labels_out=None, distance_out=None): + """Decode packed winners and reconstruct distances through INT64.""" + keys, row_norms, distances, labels = prepared + distance_dtype = distances.dtype + if distance_dtype not in (torch.float32, torch.int64): + raise ValueError("integer distances require FP32 or INT64") + labels = labels if labels_out is None else labels_out + distances = distances if distance_out is None else distance_out + require_tensor(labels, "labels", dtype=torch.int64, + shape=row_norms.shape, device=row_norms.device) + require_tensor(distances, "distances", dtype=distance_dtype, + shape=row_norms.shape, device=row_norms.device) + flat = keys.reshape(-1) + labels.copy_(flat).bitwise_and_(0xFFFFFFFF) + flat.bitwise_right_shift_(32).add_(row_norms) + distances.copy_(flat) + flat.fill_(INTEGER_INITIAL_KEY) diff --git a/thirdparty/faiss/contrib/e_means/cute_grouped.py b/thirdparty/faiss/contrib/e_means/cute_grouped.py new file mode 100644 index 000000000..2769e7c79 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/cute_grouped.py @@ -0,0 +1,549 @@ +# 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. + +# +# Selection/recovery adapted from cute_kmeans/cute/fitted_grouped.py and +# grouped_recovery.py at f858b07bb23ff8b86af5c6fadee242ff35deef8d. + +"""Private SM90 tile selection and grouped recovery, with owned scan reuse. + +Plans are explicit preparation metadata; this module does not choose routes. +The shared kernels retain BF16/FP8/INT8 score structure. BF16 L2 and spherical +assignment share this route; other representations are not newly qualified here. +""" +from typing import NamedTuple + +import cutlass +import cutlass.cute as cute +from cutlass import Float32, Int8, Int32, const_expr +from cutlass.cute.runtime import from_dlpack +from cutlass.utils import LayoutEnum +import cutlass.utils.hopper_helpers as hopper_utils +import torch +from quack import layout_utils, sm90_utils + +from .cute_argmin import require_tensor +from .cute_row_owned import ( + TILE_N, _RowOwnedAssignSm90, _assert_candidate_order, _operand_type, + _required_smem, _row_owned_shape_legal, _validate_operand, +) + +_RECOVERY_M = 256 +_RECOVERY_THREADS = 256 +_COMPILED = {} + + +class _TileSelectSm90(_RowOwnedAssignSm90): + """Select each row's nearest tile; with second labels, also the tile that + holds the best score of the others (its second-nearest tile).""" + def __init__(self, operand_type, tile_k, tile_m, stages, second=False, second_labels=False): + # Integer selection carries raw keys, rather than packed centroid IDs. + super().__init__(operand_type, False, tile_k, tile_m, stages, + 1 if tile_m == 64 else 2, second, second_labels) + self.score_type = Int32 if operand_type is Int8 else Float32 + + @cute.jit + def fold(self, accumulator, n_smem, coordinates, row_min, row_id, block, stage, + row_second=None, row_second_id=None): + values = layout_utils.reshape_acc_to_mn(accumulator) + fragment = cute.make_rmem_tensor_like(values[0, None]) + for column in cutlass.range_constexpr(cute.size(values, mode=[1])): + fragment[column] = n_smem[coordinates[0, column][1], stage] + norms = fragment.load() + if const_expr(self.score_type is Int32): + for row in cutlass.range_constexpr(cute.size(row_min)): + best = Int32(0x7FFFFFFF) + for column in cutlass.range_constexpr(cute.size(values, mode=[1])): + score = norms[column] - Int32(2) * values[row, column] + best = score if score < best else best + take = best < row_min[row] + row_min[row] = best if take else row_min[row] + row_id[row] = block if take else row_id[row] + else: + scales = cute.make_rmem_tensor_like(values[0, None]) + scales.fill(Float32(-2.0)) + for row in cutlass.range_constexpr(cute.size(row_min)): + scores = cute.math.fma(scales.load(), values[row, None].load(), norms) + # minimumNumber skips NaNs; no FTZ preserves subnormal order. + # A balanced tree limits the local dependency depth. + width = const_expr(cute.size(values, mode=[1])) + if const_expr(width < 1 or width > TILE_N or width & (width - 1)): + raise RuntimeError("row-owned score fragment must have power-of-two width") + minima = cute.make_rmem_tensor((width,), Float32) + for column in cutlass.range_constexpr(width): + minima[column] = scores[column] + for distance in (1, 2, 4, 8, 16, 32, 64): + if const_expr(distance < width): + for column in cutlass.range_constexpr(0, width, 2 * distance): + minima[column] = cute.arch.fmin( + minima[column], minima[column + distance], nan=False, ftz=False) + # All-NaN lanes become +Inf, so strict updates retain valid ID0. + best = cute.arch.fmin(Float32.inf, minima[0], nan=False, ftz=False) + take = best < row_min[row] + if const_expr(self.second_labels): + # A displaced earlier tile wins ties against a retained later tile. + other = cute.arch.fmax(best, row_min[row]) + loser = row_id[row] if take else block + take_second = (other < row_second[row]) | ( + (other == row_second[row]) & (loser < row_second_id[row])) + row_second_id[row] = loser if take_second else row_second_id[row] + row_second[row] = cute.arch.fmin(row_second[row], other) + elif const_expr(self.second): + # Best of the other tiles; recovery adds the winner tile's second. + row_second[row] = cute.arch.fmin( + row_second[row], cute.arch.fmax(best, row_min[row])) + row_min[row] = best if take else row_min[row] + row_id[row] = block if take else row_id[row] + + @cute.jit + def store(self, q, row_norms, output_values, output_labels, + coordinates, row_min, row_id, row_second=None, output_second=None, + row_second_id=None, output_second_labels=None): + row_block, _, _ = cute.arch.block_idx() + if cute.arch.lane_idx() % 4 == 0: + for local in cutlass.range_constexpr(cute.size(row_id)): + row = row_block * self.tile_m + coordinates[local, 0][0] + if row < q.shape[0]: + output_labels[row] = row_id[local] + if const_expr(self.second): + output_second[row] = row_second[local] + if const_expr(self.second_labels): + output_second_labels[row] = row_second_id[local] + + +class _RecoveryChunkPrefix: + """One owned prefix of 256-entry chunks, recomputed on the graph stream.""" + @cute.jit + def __call__(self, offsets, prefix, stream): + self.kernel(offsets, prefix).launch(grid=(1, 1, 1), block=(32, 1, 1), stream=stream) + + @cute.kernel + def kernel(self, offsets, prefix): + lane, _, _ = cute.arch.thread_idx() + carry = Int32(0) + if lane == 0: + prefix[0] = 0 + for start in cutlass.range(0, prefix.shape[0] - 1, 32, unroll=1): + tile = start + lane + chunks = Int32(0) + if tile + 1 < prefix.shape[0]: + count = Int32(offsets[tile + 1]) - Int32(offsets[tile]) + chunks = count // _RECOVERY_M + if count % _RECOVERY_M != 0: + chunks += 1 + # Every lane participates; inactive tail lanes contribute zero. + for distance in (1, 2, 4, 8, 16): + previous = cute.arch.shuffle_sync_up(chunks, offset=distance) + if lane >= distance: + chunks += previous + if tile + 1 < prefix.shape[0]: + prefix[tile + 1] = carry + chunks + carry += cute.arch.shuffle_sync(chunks, 31) + + +class _RecoverTilesSm90(_TileSelectSm90): + """Resolve one selected-tile chunk per CTA from an owned device prefix. + + The fixed grid bounds all chunk distributions; surplus CTAs skip staging. + With second labels, ``order`` groups 2B entries: entry r < B is row r under + its nearest tile, entry B + r is row r under its second-nearest tile. The + first kind does the usual work and also records the tile's own second + (``candidates[r]``, ``candidate_ids[r]``); the second kind records that + tile's nearest centroid (``candidates[B + r]``, ``candidate_ids[B + r]``). + The caller keeps the nearer of the two. + """ + def __init__(self, operand_type, logical_d, tile_k, second=False, second_labels=False): + super().__init__(operand_type, tile_k, _RECOVERY_M, 1, second, second_labels) + self.logical_d = logical_d + + @cute.jit + def __call__(self, rows, centroids, norms, order, offsets, prefix, codes, values, second, candidate_ids, + candidates, stream): + # Validated base/pitches are16-byte aligned; retain that fact after + # dynamic row indexing without asserting divisibility of logical d. + alignment = 128 // self.operand_type.width + rows = cute.make_tensor(rows.iterator, cute.make_layout(rows.shape, stride=( + cute.assume(rows.stride[0], divby=alignment), rows.stride[1]))) + centroids = cute.make_tensor(centroids.iterator, cute.make_layout(centroids.shape, stride=( + cute.assume(centroids.stride[0], divby=alignment), centroids.stride[1]))) + mma = hopper_utils.make_trivial_tiled_mma( + self.operand_type, self.operand_type, + cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.K, + self.score_type, atom_layout_mnk=(2, 1, 1), tiler_mn=(64, TILE_N), + ) + q_layout = sm90_utils.make_smem_layout( + self.operand_type, LayoutEnum.ROW_MAJOR, (_RECOVERY_M, self.tile_k), None) + c_layout = sm90_utils.make_smem_layout( + self.operand_type, LayoutEnum.ROW_MAJOR, (TILE_N, self.tile_k), None) + n_layout = cute.make_layout(TILE_N) + + @cute.struct + class Storage: + q: cute.struct.Align[cute.struct.MemRange[self.operand_type, cute.cosize(q_layout)], 1024] + c: cute.struct.Align[cute.struct.MemRange[self.operand_type, cute.cosize(c_layout)], 1024] + n: cute.struct.Align[cute.struct.MemRange[self.score_type, TILE_N], 128] + + self.kernel(rows, centroids, norms, order, offsets, prefix, codes, values, second, candidate_ids, + candidates, mma, q_layout, c_layout, n_layout, Storage).launch( + grid=((order.shape[0] - 1) // _RECOVERY_M + centroids.shape[0] // TILE_N, 1, 1), + block=(_RECOVERY_THREADS, 1, 1), stream=stream, min_blocks_per_mp=1) + + @cute.kernel + def kernel(self, rows, centroids, norms, order, offsets, prefix, codes, values, second, candidate_ids, + candidates, mma, q_layout, c_layout, n_layout, Storage: cutlass.Constexpr): + block, _, _ = cute.arch.block_idx() + n_rows = Int32(rows.shape[0]) + # The prefix maps active CTAs to one chunk; surplus CTAs do no work. + if block < Int32(prefix[prefix.shape[0] - 1]): + low, high = Int32(0), Int32(prefix.shape[0] - 1) + while low < high: + middle = (low + high) // 2 + if block < Int32(prefix[middle + 1]): + high = middle + else: + low = middle + 1 + tile = low + chunk = block - Int32(prefix[tile]) + begin = Int32(offsets[tile]) + chunk * _RECOVERY_M + end = Int32(offsets[tile + 1]) + if end - begin > _RECOVERY_M: + end = begin + _RECOVERY_M + thread, _, _ = cute.arch.thread_idx() + storage = cutlass.utils.SmemAllocator().allocate(Storage) + q_smem = storage.q.get_tensor(q_layout.outer, swizzle=q_layout.inner) + c_smem = storage.c.get_tensor(c_layout.outer, swizzle=c_layout.inner) + n_smem = storage.n.get_tensor(n_layout) + vector_width = 128 // self.operand_type.width + vectors = self.logical_d // vector_width + tail = vectors * vector_width + copy = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), self.operand_type, + num_bits_per_copy=128) + zero = cute.make_rmem_tensor((vector_width,), self.operand_type) + zero.fill(self.operand_type(0)) + if const_expr(vectors > 0): + linear = thread + while linear < TILE_N * vectors: + row, vector = linear // vectors, linear % vectors + source = cute.local_tile(centroids[tile * TILE_N + row, None], + (vector_width,), (vector,)) + target = cute.local_tile(c_smem[row, None], (vector_width,), (vector,)) + cute.copy(copy, source, target) + linear += _RECOVERY_THREADS + if const_expr(tail < self.tile_k): + linear = thread + while linear < TILE_N * (self.tile_k - tail): + row = linear // (self.tile_k - tail) + column = tail + linear % (self.tile_k - tail) + if column < self.logical_d: + c_smem[row, column] = centroids[tile * TILE_N + row, column] + else: + c_smem[row, column] = self.operand_type(0) + linear += _RECOVERY_THREADS + if thread < TILE_N: + n_smem[thread] = norms[tile * TILE_N + thread] + cute.arch.fence_view_async_shared() + cute.arch.sync_threads() + + warpgroup = cute.arch.make_warp_uniform(thread // 128) + group_mma = mma.get_slice(cute.make_layout(2, stride=128)(warpgroup)) + _, q_fragment, c_fragment = sm90_utils.partition_fragment_ABC( + group_mma, (_RECOVERY_M, TILE_N, self.tile_k), q_smem, c_smem) + coordinates = layout_utils.reshape_acc_to_mn(mma.get_slice(thread).partition_C( + cute.make_identity_tensor((_RECOVERY_M, TILE_N)))) + _assert_candidate_order(coordinates, mma, _RECOVERY_M) + position = begin + while position < end: + if const_expr(vectors > 0): + linear = thread + while linear < _RECOVERY_M * vectors: + row, vector = linear // vectors, linear % vectors + target = cute.local_tile(q_smem[row, None], (vector_width,), (vector,)) + if position + row < end: + source_row = Int32(order[position + row]) + if const_expr(self.second_labels): + source_row = source_row - n_rows if source_row >= n_rows else source_row + source = cute.local_tile(rows[source_row, None], + (vector_width,), (vector,)) + cute.copy(copy, source, target) + else: + cute.copy(copy, zero, target) + linear += _RECOVERY_THREADS + if const_expr(tail < self.tile_k): + linear = thread + while linear < _RECOVERY_M * (self.tile_k - tail): + row = linear // (self.tile_k - tail) + column = tail + linear % (self.tile_k - tail) + if position + row < end and column < self.logical_d: + source_row = Int32(order[position + row]) + if const_expr(self.second_labels): + source_row = source_row - n_rows if source_row >= n_rows else source_row + q_smem[row, column] = rows[source_row, column] + else: + q_smem[row, column] = self.operand_type(0) + linear += _RECOVERY_THREADS + cute.arch.fence_view_async_shared() + cute.arch.sync_threads() + accumulator = cute.make_rmem_tensor( + mma.partition_shape_C((_RECOVERY_M, TILE_N)), self.score_type) + self.gemm(mma, accumulator, q_fragment, c_fragment, zero_init=True, wg_wait=0) + acc = layout_utils.reshape_acc_to_mn(accumulator) + best = cute.make_rmem_tensor((cute.size(coordinates, mode=[0]),), self.score_type) + ids = cute.make_rmem_tensor_like(best, Int32) + best.fill(0x7FFFFFFF if const_expr(self.score_type is Int32) else Float32.inf) + # The native fallback sentinel is centroid0, never INT32_MAX. + ids.fill(0) + best2 = best2_ids = None + if const_expr(self.second): + best2 = cute.make_rmem_tensor_like(best) + best2.fill(Float32.inf) + if const_expr(self.second_labels): + best2_ids = cute.make_rmem_tensor_like(ids) + best2_ids.fill(0) + for column in cutlass.range_constexpr(cute.size(acc, mode=[1])): + local = coordinates[0, column][1] + centroid = tile * TILE_N + local + norm = n_smem[local] + for row in cutlass.range_constexpr(cute.size(best)): + score = (norm - Int32(2) * acc[row, column] + if const_expr(self.score_type is Int32) + else cute.math.fma(Float32(-2.0), acc[row, column], norm)) + take = (score < best[row]) | ((score == best[row]) & (centroid < ids[row])) + if const_expr(self.second): + loser_score = cute.arch.fmax(score, best[row]) + if const_expr(self.second_labels): + # A later winner can displace a lower-ID tied runner-up. + loser = ids[row] if take else centroid + take2 = (loser_score < best2[row]) | ( + (loser_score == best2[row]) & (loser < best2_ids[row])) + best2_ids[row] = loser if take2 else best2_ids[row] + best2[row] = cute.arch.fmin(best2[row], loser_score) + best[row] = score if take else best[row] + ids[row] = centroid if take else ids[row] + for offset in (2, 1): + for row in cutlass.range_constexpr(cute.size(best)): + other = cute.arch.shuffle_sync_bfly(best[row], offset=offset) + other_id = cute.arch.shuffle_sync_bfly(ids[row], offset=offset) + take = (other < best[row]) | ((other == best[row]) & (other_id < ids[row])) + if const_expr(self.second_labels): + # Keyed by (score, ID): the losing best or either side's second. + other2 = cute.arch.shuffle_sync_bfly(best2[row], offset=offset) + other2_id = cute.arch.shuffle_sync_bfly(best2_ids[row], offset=offset) + loser = best[row] if take else other + loser_id = ids[row] if take else other_id + take2 = (other2 < best2[row]) | ((other2 == best2[row]) & (other2_id < best2_ids[row])) + kept = other2 if take2 else best2[row] + kept_id = other2_id if take2 else best2_ids[row] + take_loser = (loser < kept) | ((loser == kept) & (loser_id < kept_id)) + best2[row] = loser if take_loser else kept + best2_ids[row] = loser_id if take_loser else kept_id + elif const_expr(self.second): + other2 = cute.arch.shuffle_sync_bfly(best2[row], offset=offset) + best2[row] = cute.arch.fmin(cute.arch.fmin(best2[row], other2), + cute.arch.fmax(best[row], other)) + best[row] = other if take else best[row] + ids[row] = other_id if take else ids[row] + if cute.arch.lane_idx() % 4 == 0: + for row in cutlass.range_constexpr(cute.size(best)): + entry = position + coordinates[row, 0][0] + if entry < end: + source_row = Int32(order[entry]) + if const_expr(self.second_labels): + if source_row >= n_rows: + # Under its second-nearest tile: that tile's nearest centroid. + candidates[source_row] = best[row] + candidate_ids[source_row] = ids[row] + else: + codes[source_row] = ids[row] + values[source_row] = best[row] + other = second[source_row] + second[source_row] = best2[row] if best2[row] < other else other + candidates[source_row] = best2[row] + candidate_ids[source_row] = best2_ids[row] + else: + codes[source_row] = ids[row] + values[source_row] = best[row] + if const_expr(self.second): + other = second[source_row] + second[source_row] = best2[row] if best2[row] < other else other + cute.arch.sync_threads() + position += _RECOVERY_M + + +class PreparedGrouped(NamedTuple): + selection: object + recovery: object + rows: torch.Tensor + centroids: torch.Tensor + norms: torch.Tensor + codes: torch.Tensor + values: torch.Tensor + labels: torch.Tensor + grouping: object + second: object = None + second_labels: object = None # Second-nearest indices (output). + keys: object = None # Labels: 2B tile keys, nearest then second-nearest tile. + candidates: object = None # Labels: (2B,) candidate distances. + candidate_ids: object = None # Labels: (2B,) candidate centroid indices. + schedule: object = None + chunk_prefix: object = None + + @property + def workspace_bytes(self): + prefix_bytes = (0 if self.chunk_prefix is None else + self.chunk_prefix.numel() * self.chunk_prefix.element_size()) + return self.codes.numel() * self.codes.element_size() + self.grouping.workspace_bytes + prefix_bytes + + @property + def grouping_provider(self): + return self.grouping.provider + + +def _plan_fits_smem(dtype, plan, smem): + tile_k, tile_m, stages = plan + recovery_smem = (_RECOVERY_M + TILE_N) * tile_k * dtype.itemsize + TILE_N * 4 + 2048 + return max(_required_smem(tile_k, tile_m, stages, dtype.itemsize), recovery_smem) <= smem + + +def _validate_plan(batch, clusters, dim, dtype, plan, smem): + _operand_type(dtype) + if (not isinstance(plan, tuple) or len(plan) != 3 + or not all(type(value) is int for value in plan)): + raise ValueError('grouped plan requires explicit (tile_k, tile_m, stages)') + tile_k, tile_m, stages = plan + if (not _row_owned_shape_legal(batch, clusters, dim, dtype is torch.int8) + or tile_k < dim or tile_k % (16 if dtype is torch.bfloat16 else 32) + or tile_m not in (64, 128, 256) or stages not in (2, 3)): + raise ValueError('grouped plan does not cover legal operands') + if not _plan_fits_smem(dtype, plan, smem): + raise ValueError('grouped plan exceeds opt-in shared memory') + + +def _compile(kind, operation, operands, key): + key = (kind,) + key + compiled = _COMPILED.pop(key, None) # Least recently used first. + if compiled is None: + tensors = tuple(None if value is None else from_dlpack( + value, assumed_align=16 if value.ndim == 2 or index == 2 else value.element_size()) + for index, value in enumerate(operands)) + for index in (0, 1): + tensor = (tensors[index].mark_layout_dynamic(leading_dim=1) if operands[index].ndim == 2 + else tensors[index].mark_layout_dynamic()) + tensors = tensors[:index] + (tensor,) + tensors[index + 1:] + tensors = tuple(t if i < 3 or t is None else t.mark_layout_dynamic() for i, t in enumerate(tensors)) + compiled = cute.compile(operation, *tensors, + cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options='--enable-tvm-ffi') + _COMPILED[key] = compiled + # Room for the top-1, second-distance and second-label kernels of the batch and tail shapes. + while len(_COMPILED) > 24: + _COMPILED.pop(next(iter(_COMPILED))) + return compiled + + +@torch.no_grad() +def prepare_grouped(rows, prepared, values, labels, plan, second=None, second_labels=None, + zero_padded=False): + """Bind an explicitly planned raw-key path; retain all fixed grouping buffers. + + ``zero_padded`` declares that rows and centroids are views of storage whose + columns past d, up to each row pitch, are zero. The second-label variant then + gathers whole 16-byte vectors across d in recovery instead of element by + element (the shared-memory tiles are identical either way); other variants + ignore it.""" + from .cute import _require_stack + from .e_means_grouping import prepare_grouping + + _require_stack() + centroids, norms = prepared.centroids, prepared.norms + operand_type = _operand_type(rows.dtype) + _validate_operand(rows, 'grouped rows', rows.device) + _validate_operand(centroids, 'grouped centroids', rows.device) + if centroids.dtype is not rows.dtype or rows.shape[1] != centroids.shape[1]: + raise ValueError('grouped requires matching operand dtypes and logical widths') + score_dtype = torch.int32 if rows.dtype is torch.int8 else torch.float32 + for value, name, dtype, shape in ( + (norms, 'centroid norms', score_dtype, (len(centroids),)), + (values, 'raw keys', score_dtype, (len(rows),)), + (labels, 'labels', torch.int64, (len(rows),)), + ) + (() if second_labels is None else ((second_labels, 'second labels', torch.int32, (len(rows),)),)): + require_tensor(value, name, dtype=dtype, shape=shape, device=rows.device) + if value.data_ptr() % (16 if name == 'centroid norms' else value.element_size()): + raise ValueError(name + ' pointer alignment is invalid') + for value in (rows, centroids): + if len(value) * value.stride(0) >= 2**31: + raise ValueError('grouped operand storage must fit signed int32') + properties = torch.cuda.get_device_properties(rows.device) + if (properties.major, properties.minor) != (9, 0): + raise RuntimeError('owned grouped kernels require exactly SM90') + _validate_plan(len(rows), len(centroids), rows.shape[1], rows.dtype, plan, + properties.shared_memory_per_block_optin) + tile_k, tile_m, stages = plan + if second_labels is not None and second is None: + raise ValueError('grouped second labels require second distances') + labelled = second_labels is not None + with torch.cuda.device(rows.device): + keys = candidates = candidate_ids = None + if labelled: + # One grouping of 2B entries: rows under their nearest tile, then their second-nearest. + keys = torch.empty(2 * len(rows), dtype=torch.int32, device=rows.device) + candidates = torch.empty(2 * len(rows), dtype=torch.float32, device=rows.device) + candidate_ids = torch.empty(2 * len(rows), dtype=torch.int32, device=rows.device) + codes = keys[:len(rows)] + grouping = prepare_grouping(keys, len(centroids) // TILE_N) + else: + codes = torch.empty(len(rows), dtype=torch.int32, device=rows.device) + grouping = prepare_grouping(codes, len(centroids) // TILE_N) + require_tensor(grouping.order, 'group order', dtype=torch.int32, + shape=((2 if labelled else 1) * len(rows),), device=rows.device) + require_tensor(grouping.offsets, 'group offsets', dtype=torch.uint64, + shape=(len(centroids) // TILE_N + 1,), device=rows.device) + width = rows.shape[1] + if zero_padded and labelled: + vector = 16 // rows.element_size() + width = min(-(-width // vector) * vector, rows.stride(0), centroids.stride(0), tile_k) + chunk_prefix = torch.empty(len(centroids) // TILE_N + 1, dtype=torch.int32, device=rows.device) + schedule = _compile('prefix', _RecoveryChunkPrefix(), (grouping.offsets, chunk_prefix), + (len(centroids) // TILE_N, rows.device.index)) + key = (rows.dtype, plan, rows.shape[1], tuple(centroids.shape), + rows.stride(0), centroids.stride(0), rows.device.index, second is not None, labelled, width) + selection = _compile('select', _TileSelectSm90(operand_type, *plan, second is not None, labelled), + (rows, centroids, norms, None, None, codes, second, + None if keys is None else keys[len(rows):]), key) + recovery = _compile('recover', _RecoverTilesSm90(operand_type, width, tile_k, + second is not None, labelled), + (rows, centroids, norms, grouping.order, grouping.offsets, chunk_prefix, + codes if keys is None else keys, values, second, candidate_ids, candidates), key) + return PreparedGrouped(selection, recovery, rows, centroids, norms, + codes, values, labels, grouping, second, second_labels, + keys, candidates, candidate_ids, schedule, chunk_prefix) + + +@torch.no_grad() +def launch_grouped(prepared, labels_out=None): + from .e_means_grouping import launch_grouping + + labels = prepared.labels if labels_out is None else labels_out + require_tensor(labels, 'labels', dtype=torch.int64, + shape=prepared.labels.shape, device=prepared.labels.device) + with torch.cuda.device(prepared.rows.device): + keys, n = prepared.keys, len(prepared.rows) + prepared.selection(prepared.rows, prepared.centroids, prepared.norms, + None, None, prepared.codes, prepared.second, + None if keys is None else keys[n:]) + launch_grouping(prepared.grouping) + prepared.schedule(prepared.grouping.offsets, prepared.chunk_prefix) + prepared.recovery(prepared.rows, prepared.centroids, prepared.norms, + prepared.grouping.order, prepared.grouping.offsets, prepared.chunk_prefix, + prepared.codes if keys is None else keys, prepared.values, prepared.second, + prepared.candidate_ids, prepared.candidates) + labels.copy_(prepared.codes) + if keys is not None: + # The nearest tile's own second, unless the second-nearest tile holds a nearer + # centroid; when both tiles are the same, that tile's own second is the answer. + ids, scores = prepared.candidate_ids, prepared.candidates + own = (keys[n:] == torch.div(prepared.codes, TILE_N, rounding_mode="floor")) | ( + scores[:n] < scores[n:]) | ( + (scores[:n] == scores[n:]) & (ids[:n] < ids[n:])) + torch.where(own, ids[:n], ids[n:], out=prepared.second_labels) diff --git a/thirdparty/faiss/contrib/e_means/cute_kernel.py b/thirdparty/faiss/contrib/e_means/cute_kernel.py new file mode 100644 index 000000000..2764c9507 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/cute_kernel.py @@ -0,0 +1,792 @@ +# Portions 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. + +# +# NativeRowVecLoad below is adapted from QuACK 0.6.5 RowVecLoad.begin_loop. +# Copyright (c) 2025-2026, Han Guo, Tri Dao. Licensed under Apache-2.0. +# Meta modified it to preserve int32 metadata and removed unrelated modes. +# Native INT8 packed reduction adapts PR #280 at e8e288285e885064b477a882e237fcc47da8a9b2. + +"""One fixed SM90 floating/native-INT8 GEMM-plus-argmin assignment kernel. + +The schedule uses cluster (2,1) with non-serpentine 33-cluster N panels. +All operands use CTA (128,192). BF16 uses TILE_K=64 with ping-pong +scheduling; E4M3 uses TILE_K=128 with cooperative scheduling and stock FP32 +promotion of each contraction tile. Native INT8 uses TILE_K=128 with +ping-pong scheduling and INT32 accumulation. The kernel reduces packed +``(score, centroid id)`` keys per input row. +""" + +from functools import partial +import hashlib +from pathlib import Path +from typing import NamedTuple, Optional + +import cutlass +import cutlass.cute as cute +from cutlass import Boolean, Float32, Int8, Int32, Int64, const_expr +import torch + +from quack import layout_utils, sm90_utils, utils as quack_utils +from quack.cache import jit_cache +from quack.compile_utils import make_fake_tensor as fake_tensor +from quack.cute_dsl_utils import ( + get_device_capacity, + get_max_active_clusters, + mlir_namedtuple, + torch2cute_dtype_map, +) +from quack.epilogue.mixin import ComposableEpiMixin +from quack.epilogue.ops import ( + EpiOp, + EpiSmemBytes, + RowVecLoad, + _lane_warp_info_n, +) +from quack.gemm_sm90 import GemmSm90 +from quack.gemm_tvm_ffi_utils import ( + compile_gemm_kernel, + get_major, + make_fake_gemm_tensors, + make_fake_varlen_args, + make_scheduler_args, + make_varlen_args, +) +from quack.rounding import RoundingMode +from quack.sm90_utils import partition_for_epilogue +from quack.tile_scheduler import ( + RasterOrderOption, + TileScheduler, + TileSchedulerOptions, +) + +from .cute_argmin import ( + INITIAL_KEY, + encode_argmin_key, + INTEGER_INITIAL_KEY, + finalize_int8_outputs, + launch_argmin_decode, + prepare_argmin_decode, + require_tensor, +) + + +TILE_M = 128 +TILE_N = 192 +_STAGED_ROW_BYTES = 128 +CLUSTER_M = 2 +CLUSTER_N = 1 +BLOCKED_N_CLUSTERS = 33 + + +def _persistent_cache_source_key(): + digest = hashlib.sha256() + for path in ( + Path(__file__), + Path(__file__).with_name("cute_argmin.py"), + ): + source = path.read_bytes() + digest.update(path.name.encode() + b"\0") + digest.update(len(source).to_bytes(8, "big")) + digest.update(source) + return digest.hexdigest() + + +# Every downstream Faiss module inlined into the artifact must participate. +_PERSISTENT_CACHE_SOURCE_KEY = _persistent_cache_source_key() + + +class NativeRowVecLoad(RowVecLoad): + """QuACK row-vector load modified to retain the source element type.""" + + @cute.jit + def begin(self, gemm, param, smem_tensor, ctx): + source, _ = super().begin(gemm, param, smem_tensor, ctx) + source_subtile = cute.group_modes(source, 3, cute.rank(source))[ + None, None, None, 0 + ] + registers = cute.make_rmem_tensor( + source_subtile.layout, source_subtile.element_type + ) + return [source, registers] + + @cute.jit + def begin_loop(self, gemm, state, epi_coord): + source, registers = state + should_load = Boolean(True) + if const_expr(gemm.epi_m_major): + should_load = epi_coord[0] == 0 + if should_load: + current = cute.group_modes(source, 3, cute.rank(source))[ + None, None, None, epi_coord + ] + loaded = cute.make_rmem_tensor( + current.layout, current.element_type + ) + cute.autovec_copy( + cute.filter_zeros(current), cute.filter_zeros(loaded) + ) + registers.store(loaded.load()) + return registers + + +def _blocked_scheduler_args(max_active): + return TileSchedulerOptions( + max_active_clusters=Int32(max_active), + raster_order=RasterOrderOption.AlongN, + max_swizzle_size=Int32(BLOCKED_N_CLUSTERS), + ) + + +@cute.jit +def _blocked_swizzle(params, cluster_id_in_problem: Int32): + n_group, within_n_group = divmod( + cluster_id_in_problem, params.num_clusters_in_group_fdd + ) + cid_m, cid_n = Int32(0), Int32(0) + if n_group < params.num_groups_regular: + cid_m, n_in = divmod(within_n_group, params.group_size_fdd) + cid_n = n_group * Int32(params.group_size_fdd.divisor) + n_in + else: + cid_m, n_in = divmod(within_n_group, params.group_size_tail_fdd) + cid_n = ( + params.num_groups_regular * Int32(params.group_size_fdd.divisor) + + n_in + ) + return cid_m, cid_n + + +class _BlockedTileScheduler(TileScheduler): + """Persistent monotonic-M traversal over 33-cluster N panels.""" + + @cute.jit + def _swizzle_cta(self, cluster_id_in_problem: Int32, *, loc=None, ip=None): + return _blocked_swizzle(self.params, cluster_id_in_problem) + + +class _AtomicRowArgMin(EpiOp): + """Reduce a 192-centroid tile and publish one packed key per row.""" + + def param_fields(self): + return [(self.name, object, None)] + + def to_params(self, gemm, args): + return {self.name: getattr(args, self.name)} + + def epi_m_major_score(self, arg_tensor, gemm): + return -1 + + def smem_bytes( + self, arg_tensor, cta_tile_shape_mnk, epi_tile, warp_shape_mnk=None + ): + return EpiSmemBytes() + + @cute.jit + def begin(self, gemm, param, smem_tensor, ctx): + score_type = Int32 if const_expr(gemm.acc_dtype is Int32) else Float32 + vector_layout = cute.make_layout( + (ctx.tile_M, ctx.tile_N), stride=(1, 0) + ) + state_layout = ctx.partition_for_epilogue_fn( + cute.make_rmem_tensor(vector_layout, score_type) + ).layout + state = ( + cute.make_rmem_tensor(state_layout, score_type), + cute.make_rmem_tensor(state_layout, Int32), + ) + if const_expr(cute.size(param, mode=[2]) == 2): + state = state + (cute.make_rmem_tensor(state_layout, score_type),) + if const_expr(getattr(gemm, "second_labels", False)): + state = state + (cute.make_rmem_tensor(state_layout, Int32),) + return state + + @cute.jit + def begin_loop(self, gemm, state, epi_coord): + current = tuple(t[None, None, None, epi_coord[0], epi_coord[1]] for t in state) + if const_expr(epi_coord[1] == 0): + if const_expr(gemm.acc_dtype is Int32): + cute.filter_zeros(current[0]).fill(0x7FFFFFFF) + else: + cute.filter_zeros(current[0]).fill(Float32.inf) + cute.filter_zeros(current[1]).fill(0x7FFFFFFF) + if const_expr(len(current) >= 3): + cute.filter_zeros(current[2]).fill(0x7FFFFFFF if const_expr(gemm.acc_dtype is Int32) else Float32.inf) + if const_expr(len(current) == 4): + cute.filter_zeros(current[3]).fill(0x7FFFFFFF) + return current + + @cute.jit + def end_loop_stage( + self, + gemm, + param, + state, + epi_coord, + epi_tile, + tiled_copy_t2r, + tiled_copy_r2s, + tidx, + ): + epi_tile_shape = cute.zipped_divide( + cute.make_layout(gemm.cta_tile_shape_mnk[:2]), epi_tile + ).shape[1] + if const_expr(epi_coord[1] != epi_tile_shape[1] - 1): + return None + return ( + False, + ( + state, + epi_coord, + epi_tile, + tiled_copy_t2r, + tiled_copy_r2s, + tidx, + ), + ) + + @cute.jit + def end_loop_finish( + self, + gemm, + param, + staged, + tile_coord_mnkl, + varlen_manager, + ): + ( + state, + epi_coord, + epi_tile, + tiled_copy_t2r, + tiled_copy_r2s, + tidx, + ) = staged + current = tuple(t[None, None, None, epi_coord[0], epi_coord[1]] for t in state) + current_min, current_idx = current[0], current[1] + tiled_copy = ( + tiled_copy_t2r if tiled_copy_t2r is not None else tiled_copy_r2s + ) + reference_src = tiled_copy_t2r is None + lanes_in_n, warps_in_n, _, is_lane_n_leader = _lane_warp_info_n( + tiled_copy, reference_src, tidx + ) + if const_expr(lanes_in_n > 1): + values = cute.filter_zeros(current_min) + ids = cute.filter_zeros(current_idx) + if const_expr(len(current) >= 3): + seconds = cute.filter_zeros(current[2]) + if const_expr(len(current) == 4): + second_ids = cute.filter_zeros(current[3]) + for i in cutlass.range(cute.size(values), unroll_full=True): + columns = lanes_in_n // 2 + while columns > 0: + other_value = cute.arch.shuffle_sync_bfly( + values[i], offset=columns + ) + other_id = cute.arch.shuffle_sync_bfly( + ids[i], offset=columns + ) + take_other = (other_value < values[i]) | ( + (other_value == values[i]) & (other_id < ids[i]) + ) + if const_expr(len(current) == 3): + # Second of the union: the smaller second, or the larger minimum. + other_second = cute.arch.shuffle_sync_bfly(seconds[i], offset=columns) + larger = other_value if other_value > values[i] else values[i] + smaller = other_second if other_second < seconds[i] else seconds[i] + seconds[i] = larger if larger < smaller else smaller + if const_expr(len(current) == 4): + # The same union, keyed by (score, id): the losing minimum + # or either side's second, whichever is smallest. + other_second = cute.arch.shuffle_sync_bfly(seconds[i], offset=columns) + other_second_id = cute.arch.shuffle_sync_bfly(second_ids[i], offset=columns) + loser = values[i] if take_other else other_value + loser_id = ids[i] if take_other else other_id + take_second = (other_second < seconds[i]) | ( + (other_second == seconds[i]) & (other_second_id < second_ids[i])) + best_second = other_second if take_second else seconds[i] + best_second_id = other_second_id if take_second else second_ids[i] + take_loser = (loser < best_second) | ( + (loser == best_second) & (loser_id < best_second_id)) + seconds[i] = loser if take_loser else best_second + second_ids[i] = loser_id if take_loser else best_second_id + values[i] = other_value if take_other else values[i] + ids[i] = other_id if take_other else ids[i] + columns //= 2 + assert warps_in_n == 1 + + partition = partial( + partition_for_epilogue, + epi_tile=epi_tile, + tiled_copy=tiled_copy, + tidx=tidx, + reference_src=reference_src, + ) + coordinates = partition( + cute.make_identity_tensor(gemm.cta_tile_shape_mnk[:2]) + )[None, None, None, epi_coord[0], epi_coord[1]] + row_min = layout_utils.convert_layout_zero_stride( + current_min, current_min.layout + )[None, 0] + row_idx = layout_utils.convert_layout_zero_stride( + current_idx, current_min.layout + )[None, 0] + if const_expr(len(current) >= 3): + row_second = layout_utils.convert_layout_zero_stride( + current[2], current_min.layout + )[None, 0] + # Without labels the second's own key carries the winner's ID. + row_second_id = row_idx + if const_expr(len(current) == 4): + row_second_id = layout_utils.convert_layout_zero_stride( + current[3], current_min.layout + )[None, 0] + row_coordinates = layout_utils.convert_layout_zero_stride( + coordinates, current_min.layout + )[None, 0] + + tile_m = gemm.cta_tile_shape_mnk[0] + batch_idx = tile_coord_mnkl[3] + limit_m = min( + varlen_manager.len_m(batch_idx) - tile_coord_mnkl[0] * tile_m, + tile_m, + ) + batch_keys = param[batch_idx, None, 0] + output = cute.local_tile( + batch_keys, (tile_m,), (tile_coord_mnkl[0],) + ) + if const_expr(cute.size(param, mode=[2]) == 2): + second = cute.local_tile(param[batch_idx, None, 1], (tile_m,), (tile_coord_mnkl[0],)) + if is_lane_n_leader: + for m in cutlass.range(cute.size(row_coordinates, mode=[0])): + local_row = row_coordinates[m][0] + if local_row < limit_m: + key = ( + row_min[m].to(Int64) * Int64(0x100000000) + + row_idx[m].to(Int64) + if const_expr(gemm.acc_dtype is Int32) + else encode_argmin_key(row_min[m], row_idx[m]) + ) + old = cute.arch.atomic_min( + quack_utils.elem_pointer(output, local_row).llvm_ptr, + key, + sem="relaxed", + scope="gpu", + ) + if const_expr(cute.size(param, mode=[2]) == 2): + # A losing tile's first, or the leading tile's second/displaced first. + own = (row_second[m].to(Int64) * Int64(0x100000000) + row_second_id[m].to(Int64) + if const_expr(gemm.acc_dtype is Int32) + else encode_argmin_key(row_second[m], row_second_id[m])) + cute.arch.atomic_min( + quack_utils.elem_pointer(second, local_row).llvm_ptr, + key if key > old else (own if own < old else old), sem="relaxed", scope="gpu") + + +class _GemmAssignMinSm90(ComposableEpiMixin, GemmSm90): + _epi_ops = ( + RowVecLoad("mCentroidNorms"), + NativeRowVecLoad("mCentroidIds"), + _AtomicRowArgMin("mLocalReduce"), + ) + _extra_param_fields = () + + def __init__(self, *args, **kwargs): + # Use stock per-K-tile FP32 promotion for E4M3 ranking. + kwargs.setdefault("fp8_fast_accum", args[1] is not cutlass.Float8E4M3FN) + super().__init__(*args, **kwargs) + + @mlir_namedtuple + class EpilogueArguments(NamedTuple): + mCentroidNorms: Optional[cute.Tensor] = None + mCentroidIds: Optional[cute.Tensor] = None + mLocalReduce: Optional[cute.Tensor] = None + + def epi_to_underlying_arguments(self, args, *, loc=None, ip=None): + self.rounding_mode = RoundingMode.RN + return self.EpilogueParams(**self._epi_ops_to_params_dict(args)) + + def get_scheduler_class(self, varlen_m=False): + if varlen_m: + raise ValueError("the fixed scheduler does not support varlen M") + return _BlockedTileScheduler + + +def _post_init(integer_scores, gemm, second_labels=False): + if integer_scores: + gemm.acc_dtype = Int32 + gemm.second_labels = second_labels + + +def _flatten_layout(shape, stride): + if not isinstance(shape, tuple): + if not isinstance(shape, int) or not isinstance(stride, int): + raise RuntimeError("epilogue layout is not compile-time constant") + return [(shape, stride)] + if not isinstance(stride, tuple) or len(shape) != len(stride): + raise RuntimeError("epilogue layout shape and stride differ") + pairs = [] + for sub_shape, sub_stride in zip(shape, stride): + pairs.extend(_flatten_layout(sub_shape, sub_stride)) + return pairs + + +def _static_offsets(layout): + offsets = [0] + for extent, stride in _flatten_layout( + tuple(layout.shape), tuple(layout.stride) + ): + offsets = [ + base + step * stride + for step in range(extent) + for base in offsets + ] + return offsets + + +def _assert_candidate_order(state_layout, id_layout): + """Prove each aliased row slot visits strictly increasing IDs.""" + state = _static_offsets(state_layout) + ids = _static_offsets(id_layout) + if len(state) != len(ids): + raise RuntimeError("score and ID fragments have different sizes") + last_by_row = {} + for row, candidate in zip(state, ids): + previous = last_by_row.get(row) + if previous is not None and candidate <= previous: + raise RuntimeError("centroid candidates are not ordered by ID") + last_by_row[row] = candidate + return len(state), len(last_by_row) + + +class _OrderedGemmAssignMinSm90(_GemmAssignMinSm90): + _schedule_guard_ran = False + _order_guard_ran = False + + def _setup_attributes(self, epilogue_args): + super()._setup_attributes(epilogue_args) + if self.acc_dtype is Int32 and ( + self.mma_is_rs + or self.fp8_slow_accum + or self.transform_a is not None + or self.split_k != 1 + ): + raise RuntimeError("native INT8 assignment requires plain SS WGMMA and no split-K") + tile = tuple(self.cta_tile_shape_mnk) + actual = ( + tile[:2], + tuple(self.cluster_shape_mnk), + tuple(self.atom_layout_mnk), + tuple(self.epi_tile), + tuple(self.epi_tile_shape), + bool(self.epi_m_major), + ) + fp8 = self.mma_a_dtype is cutlass.Float8E4M3FN + expected = ( + (TILE_M, TILE_N), + (CLUSTER_M, CLUSTER_N, 1), + (2 if fp8 else 1, 1, 1), + (128 if fp8 else 64, 32), + (1 if fp8 else 2, 6), + True, + ) + if fp8 and (self.pingpong or not self.fp8_slow_accum): + raise RuntimeError("FP8 requires accurate cooperative accumulation") + if actual != expected: + raise RuntimeError( + "fixed CuTe assignment schedule changed: %r" % (actual,) + ) + if tile[2] * self.mma_a_dtype.width != 1024: + raise RuntimeError("CuTe TILE_K must stage exactly 128 bytes") + type(self)._schedule_guard_ran = True + + @cute.jit + def mma(self, ab_pipeline, ab_read_state, mma_fn, acc, acc_slow, + k_tile_cnt, warp_group_idx): + # Stock RMEM recast preserves storage; only this native SS-WGMMA uses it. + if const_expr(self.acc_dtype is Int32): + if const_expr(mma_fn.func is not sm90_utils.gemm_w_idx + or len(mma_fn.args) != 4 or bool(mma_fn.keywords)): + raise RuntimeError("native INT8 bound MMA call changed") + acc = cute.recast_tensor(acc, Int32) + mma_fn = partial(sm90_utils.gemm_w_idx, mma_fn.args[0], acc, + *mma_fn.args[2:]) + return super().mma(ab_pipeline, ab_read_state, mma_fn, acc, acc_slow, + k_tile_cnt, warp_group_idx) + + def epi_retile_acc(self, acc, tRS_rD, tiled_copy_r2s): + if self.acc_dtype is Int32: + acc = cute.recast_tensor(acc, Int32) + return super().epi_retile_acc(acc, tRS_rD, tiled_copy_r2s) + + @cute.jit + def epi_visit_subtile(self, params, tensors, accumulator, c=None): + norms = tensors.get("mCentroidNorms") + centroid_ids = tensors.get("mCentroidIds") + local = tensors.get("mLocalReduce") + tile_min, tile_idx = local[0], local[1] + _assert_candidate_order(tile_min.layout, centroid_ids.layout) + type(self)._order_guard_ran = True + for i in cutlass.range(cute.size(tile_min), unroll_full=True): + score = (norms[i] - Int32(2) * accumulator[i] + if const_expr(self.acc_dtype is Int32) + else norms[i] - 2.0 * accumulator[i]) + old = tile_min[i] + take = score < old + old_idx = tile_idx[i] + tile_idx[i] = centroid_ids[i] if take else old_idx + if const_expr(self.acc_dtype is Int32): + if const_expr(len(local) == 4): + nearer = score < local[2][i] + local[2][i] = old if take else (score if nearer else local[2][i]) + local[3][i] = old_idx if take else (centroid_ids[i] if nearer else local[3][i]) + tile_min[i] = score if take else old + elif const_expr(len(local) == 4): + # Candidates arrive by increasing ID. A new best demotes the old + # one; otherwise this column replaces the second when strictly + # nearer. Comparisons with a NaN are false: it adds no candidate. + nearer = score < local[2][i] + local[2][i] = old if take else (score if nearer else local[2][i]) + local[3][i] = old_idx if take else (centroid_ids[i] if nearer else local[3][i]) + tile_min[i] = score if take else old + else: + tile_min[i] = cute.arch.fmin(old, score) + if const_expr(len(local) == 3): + other = cute.arch.fmax(score, old) + other = other if score == score else Float32.inf + local[2][i] = cute.arch.fmin(local[2][i], other) + return () + + +@jit_cache +def _compile_ordered( + operand, + tile_k, + a_major, + b_major, + device_capacity, + source_cache_key, + second=False, + second_labels=False, +): + del source_cache_key # Used by jit_cache when selecting a disk entry. + a, b, d, c, m, _, _, batch_axis = make_fake_gemm_tensors( + operand, operand, None, None, a_major, b_major, None, None + ) + epi_n = cute.sym_int() + integer_scores = operand is Int8 + epilogue = _GemmAssignMinSm90.EpilogueArguments( + mCentroidNorms=fake_tensor( + Int32 if integer_scores else Float32, + (batch_axis, epi_n), leading_dim=1, divisibility=4 + ), + mCentroidIds=fake_tensor( + Int32, (batch_axis, epi_n), leading_dim=1, divisibility=4 + ), + mLocalReduce=fake_tensor( + Int64, (batch_axis, m, 2), leading_dim=1, divisibility=1 + ) if second else fake_tensor( + Int64, (batch_axis, m, 1), leading_dim=2, divisibility=1 + ), + ) + _OrderedGemmAssignMinSm90._schedule_guard_ran = False + _OrderedGemmAssignMinSm90._order_guard_ran = False + compiled = compile_gemm_kernel( + _OrderedGemmAssignMinSm90, + operand, + (TILE_M, TILE_N, tile_k), + (CLUSTER_M, CLUSTER_N, 1), + operand is not cutlass.Float8E4M3FN, + True, + False, + False, + device_capacity, + a, + b, + d, + c, + epilogue, + _blocked_scheduler_args(1), + make_fake_varlen_args(False, False, False, None), + post_init=partial(_post_init, integer_scores, second_labels=second_labels), + ) + if not _OrderedGemmAssignMinSm90._schedule_guard_ran: + raise RuntimeError("QuACK did not invoke the fixed schedule guard") + if not _OrderedGemmAssignMinSm90._order_guard_ran: + raise RuntimeError("candidate order was not proved during compilation") + return compiled + + +def _centroid_metadata(prepared): + k = prepared.num_centroids + padded_k = ((k + TILE_N - 1) // TILE_N) * TILE_N + integer_scores = prepared.centroids.dtype is torch.int8 + norm_dtype = torch.int32 if integer_scores else torch.float32 + require_tensor( + prepared.norms, + "centroid norms", + dtype=norm_dtype, + shape=(k,), + device=prepared.centroids.device, + ) + require_tensor( + prepared.padded_norms, + "padded centroid norms", + dtype=norm_dtype, + shape=(1, padded_k), + device=prepared.centroids.device, + ) + if prepared.padded_norms[:, :k].data_ptr() != prepared.norms.data_ptr(): + raise ValueError("padded norms must alias the logical norm prefix") + ids = torch.full( + (1, padded_k), + 0x7FFFFFFF, + dtype=torch.int32, + device=prepared.centroids.device, + ) + ids[:, :k] = torch.arange( + k, dtype=torch.int32, device=prepared.centroids.device + )[None] + return ids + + +class PreparedTiledGemm(NamedTuple): + compiled: object + a: torch.Tensor + b: torch.Tensor + epilogue: object + scheduler: object + varlen: object + decode: object + second_decode: object = None + second_codes: object = None + + +@torch.no_grad() +def prepare_tiled_gemm(rows, prepared, codes, scores, row_norms=None, second_scores=None, + second_labels=False): + """Compile and bind one stable private full-or-tail workspace.""" + centroids = prepared.centroids + if ( + rows.ndim != 2 + or centroids.ndim != 2 + or rows.shape[1] != centroids.shape[1] + ): + raise ValueError("rows and centroids must be rank two with equal d") + if ( + rows.dtype not in (torch.bfloat16, torch.float8_e4m3fn, torch.int8) + or centroids.dtype is not rows.dtype + or rows.device != centroids.device + or not rows.is_cuda + ): + raise ValueError("CuTe operands must be same-device CUDA BF16/E4M3/INT8") + if rows.stride(-1) != 1 or centroids.stride(-1) != 1: + raise ValueError("CuTe operands must have unit inner stride") + element_bytes = rows.element_size() + if ( + rows.stride(-2) * element_bytes % 16 + or centroids.stride(-2) * element_bytes % 16 + ): + raise ValueError("CuTe row pitches must be 16-byte aligned") + ids = _centroid_metadata(prepared) + integer_scores = rows.dtype is torch.int8 + if integer_scores: + if rows.shape[1] > 43919: + raise ValueError("INT8 assignment requires d <= 43919") + require_tensor(row_norms, "integer row norms", dtype=torch.int32, + shape=(len(rows),), device=rows.device) + if second_labels and second_scores is None: + raise ValueError("second labels require second scores") + if second_scores is not None: + if rows.dtype in (torch.int8, torch.float8_e4m3fn) and prepared.num_centroids < 2: + raise ValueError("encoded SECOND requires at least two centroids") + require_tensor(second_scores, "second scores", dtype=scores.dtype, + shape=scores.shape, device=rows.device) + if integer_scores and not second_labels: + raise ValueError("integer tiled SECOND requires second labels") + keys = torch.full( + (1, rows.shape[0], 1), + INTEGER_INITIAL_KEY if integer_scores else INITIAL_KEY, + dtype=torch.int64, + device=rows.device, + ) + if second_scores is not None: + # Best and second-best keys in contiguous planes. + keys = keys.new_full( + (1, 2, rows.shape[0]), + INTEGER_INITIAL_KEY if integer_scores else INITIAL_KEY, + ).transpose(1, 2) + a = rows.unsqueeze(0) + b = centroids.unsqueeze(0) + tile_k = _STAGED_ROW_BYTES // element_bytes + compiled = _compile_ordered( + Int8 if integer_scores else torch2cute_dtype_map[rows.dtype], + tile_k, + get_major(a, "m", "k"), + get_major(b, "n", "k"), + get_device_capacity(rows.device), + _PERSISTENT_CACHE_SOURCE_KEY, + second_scores is not None, + second_labels, + ) + second_codes = None if second_scores is None else torch.empty_like(codes) + return PreparedTiledGemm( + compiled, + a, + b, + _GemmAssignMinSm90.EpilogueArguments( + mCentroidNorms=prepared.padded_norms, + mCentroidIds=ids, + mLocalReduce=keys, + ), + make_scheduler_args( + get_max_active_clusters(CLUSTER_M * CLUSTER_N), + BLOCKED_N_CLUSTERS, + None, + ), + make_varlen_args(None, None, None), + ( + (keys[..., 0], row_norms, scores, codes) + if integer_scores + else prepare_argmin_decode(keys[..., 0], codes, scores) + ), + ( + None + if second_scores is None + else ( + (keys[..., 1], row_norms, second_scores, second_codes) + if integer_scores + else prepare_argmin_decode( + keys[..., 1], second_codes, second_scores + ) + ) + ), + second_codes if second_labels else None, + ) + + +@torch.no_grad() +def launch_tiled_gemm(prepared, labels_out=None, distance_out=None): + """Launch assignment and decode/reset into the actual output destinations.""" + prepared.compiled( + prepared.a, + prepared.b, + None, + None, + prepared.epilogue, + prepared.scheduler, + prepared.varlen, + None, + None, + ) + if prepared.a.dtype is torch.int8: + finalize_int8_outputs(prepared.decode, labels_out, distance_out) + else: + launch_argmin_decode(prepared.decode, labels_out) + if prepared.second_decode is not None: + if prepared.a.dtype is torch.int8: + finalize_int8_outputs(prepared.second_decode) + else: + launch_argmin_decode(prepared.second_decode) diff --git a/thirdparty/faiss/contrib/e_means/cute_row_owned.py b/thirdparty/faiss/contrib/e_means/cute_row_owned.py new file mode 100644 index 000000000..a3a99a62b --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/cute_row_owned.py @@ -0,0 +1,913 @@ +# 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. + +# +# Adapted from PR #280 cute_kmeans/cute/row_owned.py at +# e8e288285e885064b477a882e237fcc47da8a9b2. + +"""Low-dimension SM90 floating and integer row-owned assignment kernel. + +Floating operands rank FP32 scores; native bytes rank exact INT32 scores and +return reconstructed FP32 distances. A compile-time layout proof establishes +increasing centroid visitation order, and the cross-lane reduction explicitly +breaks ties by centroid ID. +""" + +from typing import NamedTuple + +import cutlass +import cutlass.cute as cute +from cutlass import ( + BFloat16, + Float8E4M3FN, + Float32, + Int8, + Int32, + Int64, + const_expr, + pipeline, +) +from cutlass.cute.nvgpu import cpasync +from cutlass.cute.runtime import from_dlpack +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait +from cutlass.utils import LayoutEnum +import cutlass.utils.hopper_helpers as hopper_utils +import torch + +from quack import copy_utils, layout_utils, pipeline as quack_pipeline +from quack import sm90_utils + +from .cute_argmin import require_tensor, encode_argmin_key, decode_argmin_score + + +TILE_N = 128 +LOCAL_ID_BITS = 7 +_MAX_SCORE_TERM = 48_896 # max(c*c - 2*x*c), x/c in [-128,127]; P06 bound. +_PRODUCER_THREADS = 128 +_WARPGROUP_THREADS = 128 +_SMEM_OVERHEAD = 2048 + + +@cute.jit +def _shuffle_key(key, offset: cutlass.Constexpr): + low = cute.arch.shuffle_sync_bfly(key.to(Int32), offset=offset) + high = cute.arch.shuffle_sync_bfly((key >> Int64(32)).to(Int32), offset=offset) + return high.to(Int64) * Int64(0x100000000) + (low.to(Int64) & Int64(0xFFFFFFFF)) + + +def _assert_candidate_order(coordinates, tiled_mma, tile_m): + """Prove this geometry's row slots visit strictly increasing centroid IDs. + + Adapted from ``cute_kernel._assert_candidate_order`` for the + row-owned accumulator. Thread zero's slice carries the whole geometry: + its layout is asserted equal to the compiled thread's, so a real thread's + candidate is thread zero's plus one offset that is constant over the + fragment. Two properties therefore transfer to every thread. + + Each slot keeps one row, and all slots see the same centroid per column. + Each slot's centroid IDs also strictly increase, so PR #280's + ``score < row_min`` retains the lowest ID without a per-candidate tie + comparison. Centroid blocks are scanned in increasing order, extending + that property to the full scan. The cross-lane butterfly still breaks + ties explicitly by ID. + """ + static = layout_utils.reshape_acc_to_mn( + tiled_mma.get_slice(0).partition_C( + cute.make_identity_tensor((tile_m, TILE_N)) + ) + ) + if str(static.layout) != str(coordinates.layout): + raise RuntimeError("row-owned candidates are thread dependent") + for row in range(cute.size(static, mode=[0])): + for column in range(cute.size(static, mode=[1])): + slot, candidate = static[row, column] + if type(slot) is not int or type(candidate) is not int: + raise RuntimeError("row-owned candidates are not static") + if slot != static[row, 0][0]: + raise RuntimeError("a row-owned slot spans several rows") + if candidate != static[0, column][1]: + raise RuntimeError("row-owned slots disagree on candidates") + if column and candidate <= static[row, column - 1][1]: + raise RuntimeError("centroid candidates are not ordered by ID") + + +def _row_owned_shape_legal(batch, clusters, dim, packed_integer=False): + return ( + batch >= 1 + and clusters >= TILE_N + and clusters % TILE_N == 0 + and dim >= 1 + and (not packed_integer or _MAX_SCORE_TERM * dim * TILE_N + TILE_N - 1 < 2**31) + ) + + +def _row_owned_tile_k(dim): + return max(128, 64 * _ceil_div(dim, 64)) + + +class _RowOwnedAssignSm90: + """Compute exact row minima without materializing B-by-K scores.""" + + def __init__( + self, + operand_type, + packed_integer, + tile_k, + tile_m, + stages, + mma_warpgroups, + second=False, + second_labels=False, + ): + self.second = second + self.second_labels = second_labels + self.operand_type = operand_type + self.score_type = Int32 if packed_integer else Float32 + self.packed_integer = packed_integer + self.encoded_pair = second and operand_type is Int8 + self.tile_k = tile_k + self.tile_m = tile_m + self.stages = stages + self.mma_warpgroups = mma_warpgroups + + @cute.jit + def __call__( + self, q, centroids, norms, row_norms, values, labels, second, second_labels, stream + ): + tiled_mma = hopper_utils.make_trivial_tiled_mma( + self.operand_type, + self.operand_type, + cute.nvgpu.OperandMajorMode.K, + cute.nvgpu.OperandMajorMode.K, + self.score_type, + atom_layout_mnk=(self.mma_warpgroups, 1, 1), + tiler_mn=(64, TILE_N), + ) + # FP8 uses the same per-128-coordinate FP32 promotion as stock QuACK. + # The synchronous centroid-block schedule follows. + q_layout = sm90_utils.make_smem_layout( + self.operand_type, + LayoutEnum.ROW_MAJOR, + (self.tile_m, self.tile_k), + None, + ) + c_layout = sm90_utils.make_smem_layout( + self.operand_type, + LayoutEnum.ROW_MAJOR, + (TILE_N, self.tile_k), + self.stages, + ) + n_layout = cute.make_layout( + (TILE_N, self.stages), stride=(1, TILE_N) + ) + q_bytes = cute.size_in_bytes( + self.operand_type, cute.select(q_layout, mode=[0, 1]) + ) + c_bytes = cute.size_in_bytes( + self.operand_type, cute.select(c_layout, mode=[0, 1]) + ) + n_bytes = TILE_N * self.score_type.width // 8 + q_atom, q_tensor = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), q, q_layout, + (self.tile_m, self.tile_k), + ) + c_atom, c_tensor = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), centroids, + cute.select(c_layout, mode=[0, 1]), + (TILE_N, self.tile_k), 1, + ) + n_atom, n_tensor = cpasync.make_tiled_tma_atom( + cpasync.CopyBulkTensorTileG2SOp(), norms, + cute.select(n_layout, mode=[0]), (TILE_N,), 1, + ) + + @cute.struct + class SharedStorage: + q_barriers: cute.struct.MemRange[cutlass.Int64, 2] + c_barriers: cute.struct.MemRange[cutlass.Int64, self.stages * 2] + q: cute.struct.Align[ + cute.struct.MemRange[ + self.operand_type, cute.cosize(q_layout) + ], 1024 + ] + centroids: cute.struct.Align[ + cute.struct.MemRange[ + self.operand_type, cute.cosize(c_layout) + ], 1024 + ] + norms: cute.struct.Align[ + cute.struct.MemRange[ + self.score_type, cute.cosize(n_layout) + ], 128 + ] + + self.kernel( + q_atom, + q_tensor, + c_atom, + c_tensor, + n_atom, + n_tensor, + row_norms, + values, + labels, + second, + second_labels, + tiled_mma, + q_layout, + c_layout, + n_layout, + SharedStorage, + q_bytes, + c_bytes + n_bytes, + ).launch( + grid=(cute.ceil_div(q.shape[0], self.tile_m), 1, 1), + block=( + _PRODUCER_THREADS + + self.mma_warpgroups * _WARPGROUP_THREADS, + 1, 1, + ), + stream=stream, + min_blocks_per_mp=1, + ) + + @cute.kernel + def kernel( + self, + q_atom, + q, + c_atom, + centroids, + n_atom, + norms, + row_norms, + values, + labels, + second, + second_labels, + tiled_mma, + q_layout, + c_layout, + n_layout, + SharedStorage: cutlass.Constexpr, + q_bytes: cutlass.Constexpr, + c_bytes: cutlass.Constexpr, + ): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + if warp == 0: + cpasync.prefetch_descriptor(q_atom) + cpasync.prefetch_descriptor(c_atom) + cpasync.prefetch_descriptor(n_atom) + allocator = cutlass.utils.SmemAllocator() + storage = allocator.allocate(SharedStorage) + producer = pipeline.CooperativeGroup(pipeline.Agent.Thread, 1) + consumers = pipeline.CooperativeGroup( + pipeline.Agent.Thread, + self.mma_warpgroups * _WARPGROUP_THREADS // cute.arch.WARP_SIZE, + ) + q_pipe = quack_pipeline.PipelineTmaAsync.create( + barrier_storage=storage.q_barriers.data_ptr(), + num_stages=1, + producer_group=producer, + consumer_group=consumers, + tx_count=q_bytes, + defer_sync=True, + ) + c_pipe = quack_pipeline.PipelineTmaAsync.create( + barrier_storage=storage.c_barriers.data_ptr(), + num_stages=self.stages, + producer_group=producer, + consumer_group=consumers, + tx_count=c_bytes, + defer_sync=True, + ) + pipeline_init_arrive(cluster_shape_mn=(1, 1), is_relaxed=True) + q_smem = storage.q.get_tensor(q_layout.outer, swizzle=q_layout.inner) + c_smem = storage.centroids.get_tensor( + c_layout.outer, swizzle=c_layout.inner + ) + n_smem = storage.norms.get_tensor(n_layout) + pipeline_init_wait(cluster_shape_mn=(1, 1)) + if warp < 4: + cute.arch.setmaxregister_decrease(24) + self.load( + q, + centroids, + norms, + q_smem, + c_smem, + n_smem, + q_atom, + c_atom, + n_atom, + q_pipe, + c_pipe, + ) + else: + cute.arch.setmaxregister_increase(240) + thread, _, _ = cute.arch.thread_idx() + self.mma( + q, + centroids, + row_norms, + values, + labels, + q_smem, + c_smem, + n_smem, + tiled_mma, + q_pipe, + c_pipe, + thread - _PRODUCER_THREADS, + second, + second_labels, + ) + + @cute.jit + def load( + self, + q, + centroids, + norms, + q_smem, + c_smem, + n_smem, + q_atom, + c_atom, + n_atom, + q_pipe, + c_pipe, + ): + if cute.arch.make_warp_uniform(cute.arch.warp_idx()) % 4 == 0: + row_block, _, _ = cute.arch.block_idx() + q_tile = cute.local_tile( + q, (self.tile_m, self.tile_k), (row_block, 0) + ) + c_tile = cute.local_tile( + centroids, (TILE_N, self.tile_k), (None, 0) + ) + n_tile = cute.local_tile(norms, (TILE_N,), (None,)) + load_q, _, _ = copy_utils.tma_get_copy_fn( + q_atom, 0, cute.make_layout(1), q_tile, q_smem, + single_stage=True, + ) + load_c, _, _ = copy_utils.tma_get_copy_fn( + c_atom, 0, cute.make_layout(1), c_tile, c_smem + ) + load_n, _, _ = copy_utils.tma_get_copy_fn( + n_atom, 0, cute.make_layout(1), n_tile, n_smem + ) + load_c = copy_utils.tma_producer_copy_fn(load_c, c_pipe) + load_n = copy_utils.tma_producer_copy_fn(load_n, c_pipe) + q_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, 1 + ) + q_pipe.producer_acquire(q_state) + load_q(tma_bar_ptr=q_pipe.producer_get_barrier(q_state)) + q_pipe.producer_commit(q_state) + c_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Producer, self.stages + ) + for block in cutlass.range(centroids.shape[0] // TILE_N, unroll=1): + c_pipe.producer_acquire(c_state) + load_c(src_idx=block, producer_state=c_state) + load_n(src_idx=block, producer_state=c_state) + c_pipe.producer_commit(c_state) + c_state.advance() + + @cute.jit + def fold( + self, accumulator, n_smem, coordinates, row_min, row_id, block, stage, + row_second=None, row_second_id=None, + ): + """Fold one centroid block's scores into every row slot's best.""" + values = layout_utils.reshape_acc_to_mn(accumulator) + width = const_expr(cute.size(values, mode=[1])) + if const_expr(self.packed_integer): + folded = cute.make_rmem_tensor((width,), Int32) + for column in cutlass.range_constexpr(width): + local = coordinates[0, column][1] + folded[column] = ( + n_smem[local, stage] * Int32(TILE_N) + local + ) + for row in cutlass.range_constexpr(cute.size(row_min)): + best = Int32(0x7FFFFFFF) + if const_expr(self.encoded_pair): + other = Int32(0x7FFFFFFF) + for column in cutlass.range_constexpr(width): + key = ( + folded[column] + - Int32(2 * TILE_N) * values[row, column] + ) + if const_expr(self.encoded_pair): + other = best if key < best else (key if key < other else other) + best = key if key < best else best + take = ( + (best >> Int32(LOCAL_ID_BITS)) + < (row_min[row] >> Int32(LOCAL_ID_BITS)) + ) + if const_expr(self.encoded_pair): + old_key = (row_min[row] >> Int32(LOCAL_ID_BITS)).to(Int64) * Int64(0x100000000) + old_key += row_id[row].to(Int64) * Int64(TILE_N) + (row_min[row] & Int32(TILE_N - 1)).to(Int64) + old_key = Int64(0x7FFFFFFFFFFFFFFF) if row_id[row] == 0x7FFFFFFF else old_key + best_key = (best >> Int32(LOCAL_ID_BITS)).to(Int64) * Int64(0x100000000) + best_key += block.to(Int64) * Int64(TILE_N) + (best & Int32(TILE_N - 1)).to(Int64) + other_key = (other >> Int32(LOCAL_ID_BITS)).to(Int64) * Int64(0x100000000) + other_key += block.to(Int64) * Int64(TILE_N) + (other & Int32(TILE_N - 1)).to(Int64) + other_key = Int64(0x7FFFFFFFFFFFFFFF) if other == 0x7FFFFFFF else other_key + candidate = old_key if take else best_key + current = other_key if take else row_second[row] + row_second[row] = candidate if candidate < current else current + row_min[row] = best if take else row_min[row] + row_id[row] = block if take else row_id[row] + else: + for column in cutlass.range_constexpr(width): + local = coordinates[0, column][1] + centroid = block * TILE_N + local + norm = n_smem[local, stage] + for row in cutlass.range_constexpr(cute.size(row_min)): + score = cute.math.fma( + Float32(-2.0), values[row, column], norm + ) + old_min = row_min[row] + take = score < old_min + if const_expr(self.second_labels): + # A new best demotes the old one; otherwise this column + # replaces the second when strictly nearer. Comparisons + # with a NaN are false, so a NaN adds no candidate. + nearer = score < row_second[row] + row_second[row] = old_min if take else (score if nearer else row_second[row]) + row_second_id[row] = row_id[row] if take else ( + centroid if nearer else row_second_id[row]) + row_min[row] = score if take else old_min + else: + if const_expr(self.second): + # Each column is a distinct candidate. A NaN adds none. + other = cute.arch.fmax(old_min, score, nan=False, ftz=False) + other = other if score == score else Float32.inf + row_second[row] = cute.arch.fmin( + row_second[row], other, nan=False, ftz=False) + row_min[row] = cute.arch.fmin(old_min, score) + row_id[row] = centroid if take else row_id[row] + + @cute.jit + def gemm(self, tiled_mma, accumulator, q_fragment, c_fragment, + zero_init: cutlass.Constexpr[bool] = True, + wg_wait: cutlass.Constexpr[int] = 0): + if const_expr(self.operand_type is Float8E4M3FN): + promoted = cute.make_rmem_tensor(accumulator.layout, Float32) + promoted.fill(0.0) + mma_atom = cute.make_mma_atom(tiled_mma.op) + # Four k32 atoms form stock QuACK's k128 FP8 promotion interval. + for begin in cutlass.range_constexpr(0, cute.size(q_fragment.shape[2]), 4): + cute.nvgpu.warpgroup.fence() + mma_atom.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, False) + for k in cutlass.range_constexpr(begin, min(begin + 4, cute.size(q_fragment.shape[2]))): + cute.gemm(mma_atom, accumulator, q_fragment[None, None, k], + c_fragment[None, None, k], accumulator) + mma_atom.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, True) + cute.nvgpu.warpgroup.commit_group() + cute.nvgpu.warpgroup.wait_group(0) + promoted.store(promoted.load() + accumulator.load()) + accumulator.store(promoted.load()) + else: + sm90_utils.gemm(tiled_mma, accumulator, q_fragment, c_fragment, + zero_init=zero_init, wg_wait=wg_wait) + + @cute.jit + def mma( + self, + q, + centroids, + row_norms, + output_values, + output_labels, + q_smem, + c_smem, + n_smem, + tiled_mma, + q_pipe, + c_pipe, + thread: Int32, + output_second=None, + output_second_labels=None, + ): + warpgroup = cute.arch.make_warp_uniform( + thread // _WARPGROUP_THREADS + ) + group_layout = cute.make_layout( + self.mma_warpgroups, stride=_WARPGROUP_THREADS + ) + thread_mma = tiled_mma.get_slice(thread) + group_mma = tiled_mma.get_slice(group_layout(warpgroup)) + _, q_fragment, c_fragment = sm90_utils.partition_fragment_ABC( + group_mma, + (self.tile_m, TILE_N, self.tile_k), + q_smem, + c_smem, + ) + coordinates = layout_utils.reshape_acc_to_mn( + thread_mma.partition_C( + cute.make_identity_tensor((self.tile_m, TILE_N)) + ) + ) + _assert_candidate_order(coordinates, tiled_mma, self.tile_m) + row_shape = (cute.size(coordinates, mode=[0]),) + row_min = cute.make_rmem_tensor(row_shape, self.score_type) + row_id = cute.make_rmem_tensor(row_shape, Int32) + if const_expr(self.score_type is Int32): + row_min.fill(0x7FFFFFFF) + row_id.fill(0x7FFFFFFF if const_expr(self.packed_integer) else 0) + else: + row_min.fill(Float32.inf) + row_id.fill(0) + row_second = row_second_id = None + if const_expr(self.second): + row_second = cute.make_rmem_tensor(row_shape, Int64 if const_expr(self.encoded_pair) else self.score_type) + row_second.fill(0x7FFFFFFFFFFFFFFF if const_expr(self.encoded_pair) else Float32.inf) + if const_expr(self.second_labels): + row_second_id = cute.make_rmem_tensor(row_shape, Int32) + row_second_id.fill(0) + q_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, 1 + ) + q_pipe.consumer_wait(q_state, q_pipe.consumer_try_wait(q_state)) + c_state = pipeline.make_pipeline_state( + pipeline.PipelineUserType.Consumer, self.stages + ) + for block in cutlass.range( + centroids.shape[0] // TILE_N, unroll=1 + ): + c_pipe.consumer_wait( + c_state, c_pipe.consumer_try_wait(c_state) + ) + accumulator = cute.make_rmem_tensor( + tiled_mma.partition_shape_C((self.tile_m, TILE_N)), + self.score_type, + ) + self.gemm( + tiled_mma, + accumulator, + q_fragment, + c_fragment[None, None, None, c_state.index], + zero_init=True, + wg_wait=0, + ) + self.fold( + accumulator, + n_smem, + coordinates, + row_min, + row_id, + block, + c_state.index, + row_second, + row_second_id, + ) + c_pipe.consumer_release(c_state) + c_state.advance() + for offset in (2, 1): + for row in cutlass.range_constexpr(cute.size(row_min)): + other_key = cute.arch.shuffle_sync_bfly( + row_min[row], offset=offset + ) + other_id = cute.arch.shuffle_sync_bfly( + row_id[row], offset=offset + ) + if const_expr(self.packed_integer): + other_score = other_key >> Int32(LOCAL_ID_BITS) + current_score = row_min[row] >> Int32(LOCAL_ID_BITS) + take = (other_score < current_score) | ( + (other_score == current_score) + & ( + (other_id < row_id[row]) + | ( + (other_id == row_id[row]) + & (other_key < row_min[row]) + ) + ) + ) + else: + take = (other_key < row_min[row]) | ( + (other_key == row_min[row]) + & (other_id < row_id[row]) + ) + if const_expr(self.encoded_pair): + current_first = (row_min[row] >> Int32(LOCAL_ID_BITS)).to(Int64) * Int64(0x100000000) + current_first += row_id[row].to(Int64) * Int64(TILE_N) + (row_min[row] & Int32(TILE_N - 1)).to(Int64) + other_first = (other_key >> Int32(LOCAL_ID_BITS)).to(Int64) * Int64(0x100000000) + other_first += other_id.to(Int64) * Int64(TILE_N) + (other_key & Int32(TILE_N - 1)).to(Int64) + other_second = _shuffle_key(row_second[row], offset) + left = current_first if take else row_second[row] + right = other_second if take else other_first + row_second[row] = left if left < right else right + elif const_expr(self.second_labels): + # The same union keyed by (score, ID): the losing best or + # either side's second, whichever is smallest. + other_second = cute.arch.shuffle_sync_bfly( + row_second[row], offset=offset + ) + other_second_id = cute.arch.shuffle_sync_bfly( + row_second_id[row], offset=offset + ) + loser = row_min[row] if take else other_key + loser_id = row_id[row] if take else other_id + take_second = (other_second < row_second[row]) | ( + (other_second == row_second[row]) & (other_second_id < row_second_id[row])) + best_second = other_second if take_second else row_second[row] + best_second_id = other_second_id if take_second else row_second_id[row] + take_loser = (loser < best_second) | ( + (loser == best_second) & (loser_id < best_second_id)) + row_second[row] = loser if take_loser else best_second + row_second_id[row] = loser_id if take_loser else best_second_id + elif const_expr(self.second): + # The union's second is min(max(bests), seconds). + other_second = cute.arch.shuffle_sync_bfly( + row_second[row], offset=offset + ) + row_second[row] = cute.arch.fmin( + cute.arch.fmin(row_second[row], other_second), + cute.arch.fmax(row_min[row], other_key)) + row_min[row] = other_key if take else row_min[row] + row_id[row] = other_id if take else row_id[row] + self.store(q, row_norms, output_values, output_labels, + coordinates, row_min, row_id, row_second, output_second, + row_second_id, output_second_labels) + q_pipe.consumer_release(q_state) + + @cute.jit + def store(self, q, row_norms, output_values, output_labels, + coordinates, row_min, row_id, row_second=None, output_second=None, + row_second_id=None, output_second_labels=None): + """Default native output; grouped selection overrides only this store.""" + lane = cute.arch.lane_idx() + row_block, _, _ = cute.arch.block_idx() + if lane % 4 == 0: + for local in cutlass.range_constexpr(cute.size(row_min)): + row = row_block * self.tile_m + coordinates[local, 0][0] + if row < q.shape[0]: + if const_expr(self.packed_integer): + code = ( + row_id[local] * Int32(TILE_N) + + (row_min[local] & Int32(TILE_N - 1)) + ) + score = row_min[local] >> Int32(LOCAL_ID_BITS) + distance = ( + score.to(Int64) + row_norms[row].to(Int64) + ) + output_values[row] = distance.to(output_values.element_type) + output_labels[row] = code.to(output_labels.element_type) + if const_expr(self.encoded_pair): + output_second[row] = ((row_second[local] >> Int64(32)) + row_norms[row].to(Int64)).to(output_second.element_type) + output_second_labels[row] = (row_second[local] & Int64(0xFFFFFFFF)).to(output_second_labels.element_type) + else: + output_values[row] = row_min[local].to(output_values.element_type) + output_labels[row] = row_id[local].to(output_labels.element_type) + if const_expr(self.second): + output_second[row] = row_second[local].to(output_second.element_type) + if const_expr(self.second_labels): + output_second_labels[row] = row_second_id[local].to(output_second_labels.element_type) + + +def _ceil_div(value, divisor): + return (value + divisor - 1) // divisor + + +def _required_smem(tile_k, tile_m, stages, element_bytes): + per_stage = TILE_N * tile_k * element_bytes + TILE_N * 4 + return ( + tile_m * tile_k * element_bytes + + stages * per_stage + + _SMEM_OVERHEAD + ) + + +def _operand_type(dtype): + if dtype is torch.int8: + return Int8 + if dtype is torch.bfloat16: + return BFloat16 + if dtype is torch.float8_e4m3fn: + return Float8E4M3FN + raise ValueError("row-owned operands must be BF16, E4M3 or INT8") + + +def row_owned_plan(batch, clusters, dim, device, dtype=torch.bfloat16): + """Choose an existing tile with at least one CTA per SM when possible. + + Prefer the larger row tile only when its grid covers the device and its + three-stage workspace fits. This is a conservative resource/occupancy rule, + not a measured performance crossover or a batch-size admission table. + """ + _operand_type(dtype) + if not _row_owned_shape_legal(batch, clusters, dim, dtype is torch.int8): + return None + properties = torch.cuda.get_device_properties(device) + smem = properties.shared_memory_per_block_optin + tile_k = _row_owned_tile_k(dim) + stages = 3 + tile_m = 128 if _ceil_div(batch, 128) >= properties.multi_processor_count else 64 + if _required_smem(tile_k, tile_m, stages, dtype.itemsize) > smem: + tile_m = 64 + if _required_smem(tile_k, tile_m, stages, dtype.itemsize) > smem: + return None + return tile_k, tile_m, stages + + +class PreparedRowOwned(NamedTuple): + compiled: object + rows: torch.Tensor + centroids: torch.Tensor + norms: torch.Tensor + row_norms: object + values: torch.Tensor + labels: torch.Tensor + second_scores: object = None + second_labels: object = None + + +def _validate_operand(tensor, name, device): + require_tensor(tensor, name, device=device, contiguous=False) + _operand_type(tensor.dtype) + if tensor.ndim != 2 or tensor.stride(1) != 1: + raise ValueError("%s must be rank two with unit inner stride" % name) + if ( + tensor.stride(0) < tensor.shape[1] + or tensor.stride(0) * tensor.element_size() % 16 + or tensor.data_ptr() % 16 + ): + raise ValueError("%s must retain a 16-byte-aligned row pitch" % name) + + +@torch.no_grad() +def prepare_row_owned( + rows, + prepared, + values, + labels, + plan, + *, + row_norms=None, + second_scores=None, + second_labels=None, +): + """Compile and bind one floating or native-byte row-owned operation. + + Floating operands return FP32 scores, matching the tiled floating contract. + Native bytes rank INT32 scores and return reconstructed FP32/INT64 distances. + """ + from .cute import _require_stack + + centroids = prepared.centroids + operand_type = _operand_type(rows.dtype) + packed_integer = rows.dtype is torch.int8 + _require_stack() + _validate_operand(rows, "row-owned rows", rows.device) + _validate_operand(centroids, "row-owned centroids", rows.device) + if centroids.dtype is not rows.dtype: + raise ValueError("row-owned operands must have the same dtype") + if rows.shape[1] != centroids.shape[1]: + raise ValueError("row-owned operands must have equal dimensions") + require_tensor( + prepared.norms, "row-owned centroid norms", + dtype=torch.int32 if packed_integer else torch.float32, + shape=(len(centroids),), device=rows.device, + ) + if packed_integer: + require_tensor(row_norms, "row-owned row norms", dtype=torch.int32, + shape=(len(rows),), device=rows.device) + elif row_norms is not None: + raise ValueError("floating row-owned assignment takes no row norms") + value_dtype = values.dtype + if value_dtype is not torch.float32 and not (packed_integer and value_dtype is torch.int64): + raise ValueError("row-owned values require FP32 or raw INT64") + require_tensor( + values, "row-owned values", dtype=value_dtype, + shape=(len(rows),), device=rows.device, + ) + require_tensor( + labels, "row-owned labels", dtype=torch.int64, + shape=(len(rows),), device=rows.device, + ) + if second_scores is not None: + if rows.dtype in (torch.int8, torch.float8_e4m3fn) and prepared.num_centroids < 2: + raise ValueError("encoded SECOND requires at least two centroids") + require_tensor(second_scores, "row-owned second scores", dtype=value_dtype, + shape=(len(rows),), device=rows.device) + if second_labels is not None: + if second_scores is None: + raise ValueError("row-owned second labels require second scores") + label_dtype = (torch.int64 if rows.dtype in (torch.int8, torch.float8_e4m3fn) + else torch.int32) + require_tensor(second_labels, "row-owned second labels", dtype=label_dtype, + shape=(len(rows),), device=rows.device) + if ( + prepared.norms.data_ptr() % 16 + or values.data_ptr() % values.element_size() + or labels.data_ptr() % 8 + ): + raise ValueError("row-owned tensors do not meet pointer alignment") + if ( + not isinstance(plan, tuple) + or len(plan) != 3 + or not all(isinstance(value, int) for value in plan) + ): + raise ValueError("plan does not match the row-owned operands") + tile_k, tile_m, stages = plan + if ( + not _row_owned_shape_legal(len(rows), len(centroids), rows.shape[1], packed_integer) + or tile_k != _row_owned_tile_k(rows.shape[1]) + or tile_m not in (64, 128) + or stages != 3 + ): + raise ValueError("plan does not match the row-owned operands") + properties = torch.cuda.get_device_properties(rows.device) + required_smem = _required_smem( + tile_k, tile_m, stages, rows.element_size() + ) + if required_smem > properties.shared_memory_per_block_optin: + raise ValueError("row-owned plan exceeds opt-in shared memory") + mma_warpgroups = 1 if tile_m == 64 else 2 + # Keep singleton axes in the TMA layout; static folding corrupts query loads. + tensors = ( + from_dlpack(rows, assumed_align=16).mark_layout_dynamic(leading_dim=1), + from_dlpack(centroids, assumed_align=16).mark_layout_dynamic(leading_dim=1), + from_dlpack(prepared.norms, assumed_align=16), + from_dlpack(row_norms, assumed_align=4) if packed_integer else None, + from_dlpack(values, assumed_align=values.element_size()), + from_dlpack(labels, assumed_align=8), + from_dlpack(second_scores, assumed_align=4) if second_scores is not None else None, + from_dlpack(second_labels, assumed_align=4) if second_labels is not None else None, + ) + tensors = tuple(t if i < 3 or t is None else t.mark_layout_dynamic() for i, t in enumerate(tensors)) + stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) + key = ( + rows.dtype, + tile_k, + tile_m, + stages, + centroids.shape[0], + rows.shape[1], + rows.stride(0), + centroids.stride(0), + rows.device.index, + ) + if value_dtype is torch.int64: + key += (value_dtype,) + if second_scores is not None: + key += ("second",) + if second_labels is not None: + key += ("second_labels",) + compiled = _COMPILED.get(key) + if compiled is None: + compiled = cute.compile( + _RowOwnedAssignSm90( + operand_type, + packed_integer, + tile_k, + tile_m, + stages, + mma_warpgroups, + second=second_scores is not None, + second_labels=second_labels is not None, + ), + *tensors, + stream, + options="--enable-tvm-ffi", + ) + _COMPILED[key] = compiled + while len(_COMPILED) > 8: + _COMPILED.pop(next(iter(_COMPILED))) + return PreparedRowOwned( + compiled, + rows, + centroids, + prepared.norms, + row_norms, + values, + labels, + second_scores, + second_labels, + ) + + +_COMPILED = {} + + +@torch.no_grad() +def launch_row_owned(prepared, labels_out=None, distance_out=None): + labels = prepared.labels if labels_out is None else labels_out + if labels_out is not None: + require_tensor(labels, "labels", dtype=torch.int64, + shape=prepared.labels.shape, device=prepared.labels.device) + values = prepared.values if distance_out is None else distance_out + require_tensor(values, "values", dtype=prepared.values.dtype, + shape=prepared.values.shape, device=prepared.values.device) + if values.data_ptr() % values.element_size(): + raise ValueError("row-owned values do not meet pointer alignment") + with torch.cuda.device(prepared.values.device): + prepared.compiled(prepared.rows, prepared.centroids, prepared.norms, + prepared.row_norms, values, labels, prepared.second_scores, + prepared.second_labels) diff --git a/thirdparty/faiss/contrib/e_means/e_means.py b/thirdparty/faiss/contrib/e_means/e_means.py new file mode 100644 index 000000000..b338c6a5d --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means.py @@ -0,0 +1,865 @@ +# 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. + +"""FP32 E-means clustering with NumPy and Faiss assignment.""" + +import time + +import numpy as np +import faiss + +from .base import ( + _FLOAT32_COUNT_LIMIT, + _EmeansBase, + _INIT_USAGE, + _UNUSED_THRESHOLD, + _compact_label_dtype, + _epoch_rows, + _epoch_seed, + _format_passes as _format_passes, + _resolve_recipe, + _resolve_unused_threshold, + _round_power_of_two as _round_power_of_two, + _scheduled_alpha as _scheduled_alpha, + _step_law, + _twin_reassign, +) + +# Rows per step of the closing-pass relabelling, bounding its temporaries. +_HANDOVER_CHUNK = 1 << 16 + + +__all__ = [ + "NumpyEmeans", + "_epoch_rows", + "_epoch_seed", + "_format_passes", + "_resolve_recipe", + "_round_power_of_two", + "_scheduled_alpha", + "_step_law", +] + + +def _numpy_unused_threshold(usage, k, coefficient=_UNUSED_THRESHOLD): + """Compute the threshold consistently across NumPy scalar rules.""" + total = usage.sum(dtype="float32") + scaled = np.multiply(total, np.float32(coefficient), dtype="float32") + return np.divide(scaled, np.float32(k), dtype="float32") + + +def _add_rows_at(out, labels, rows): + """out[labels[i]] += rows[i] for every i, in row order, as np.add.at. + The labels are in [0, len(out)). + + The sparse product [I | one-hot] @ [sums; rows] starts the sum of each + centroid at its row of out and adds its rows in row order, so the result + is the same as np.add.at, and much faster on 2-D rows. With fewer rows + than centroids, the sums are only the rows of out that the labels touch. + Without SciPy, or when rows cannot be cast to the dtype of out without + a loss (np.add.at then rounds to that dtype after each add), fall back to + np.add.at. + """ + if not np.can_cast(rows.dtype, out.dtype, "safe"): + np.add.at(out, labels, rows) + return + try: + import scipy.sparse + except ImportError: + np.add.at(out, labels, rows) + return + k, n = len(out), len(labels) + touched = None + if n < k: + touched, labels = np.unique(labels, return_inverse=True) + sums = out if touched is None else out[touched] + m = len(sums) + # shape: an empty chunk has no index to infer it from + product = scipy.sparse.csr_matrix( + ( + np.ones(m + n, dtype=out.dtype), + (np.concatenate([np.arange(m), labels]), np.arange(m + n)), + ), + shape=(m, m + n), + ) + result = product @ np.concatenate([sums, rows]) + if touched is None: + out[...] = result + else: + out[touched] = result + + +def _separate_splits(donor, child): + """Separate identical donor and child centroids along one coordinate. + + Zero donors become distinct subnormal operands; their squared distances + can still tie. No value scan or dynamic collapsed-row list is needed. + """ + collapsed = (donor == child).all(axis=1) + value = child[:, 0] + with np.errstate(over="ignore"): + neighbor = np.nextafter(value, np.float32(np.inf)) + neighbor = np.where( + np.isfinite(neighbor), + neighbor, + np.nextafter(value, np.float32(-np.inf)), + ) + child[:, 0] = np.where(collapsed, neighbor, value) + + +class NumpyEmeans(_EmeansBase): + """FP32 NumPy E-means with exact Faiss assignment. + + Implements Algorithm 1 of "E-Means: Scaling Laws for Mini-Batch K-Means": + https://arxiv.org/abs/2611.09501 + + ``nepochs`` is the epoch budget T and ``batch_size`` is B. ``alpha0`` is + the initial EMA step, alpha = 1 - gamma, annealed with the cosine schedule + of Equation 5. The batch law named by ``batch_law`` (``"throughput"``, or + ``"quality"`` for a batch about 8 times smaller) chooses B, and the step law + then sets alpha0 for that B. The default ``"auto"`` uses the quality law + when d <= 16 and the throughput law otherwise. A ``batch_size`` given + alone keeps the step law, and giving ``alpha0`` too sets both. + ``recipe["batch_law"]`` and ``recipe["batch_law_reason"]`` record the + resolved law. + + Each object represents one run. Call ``train`` or ``begin`` once; + create a fresh object for another run or after execution failure. + + ``train`` samples initial centroids by default and shuffles each epoch + (lines 1-4). For caller-driven training, ``begin`` initializes the state, + ``accumulate`` assigns rows and collects batch counts n_j and sums s_j + (lines 6-7), and ``update`` applies the EMA (line 8). ``_usage`` stores + masses N_j and ``_centroids`` stores positions c_j = S_j / N_j, an + algebraically equivalent form of the sum-and-count updates. Every five + updates, the default ``unused_threshold=None`` moves centroids whose + removal cost (EMA of d2 - d1 over their rows) is zero or below 0.3 times + the median to split the donors with the longest axes, until the end of + training. A split puts the two copies at c_j -/+ s_j u_j along the + donor's axis u_j, s_j = sqrt(2 ||U_j|| / (pi N_j)): the half-means of a + Gaussian along u_j. With ``closing_handover`` (default) and captured + assignments, ``train`` hands the last-pass rows such a revived centroid held + before moving to their second-nearest centroid from the same assignment, + unless it moved after them too: those rows are assigned again like a + training batch, at their share of one epoch's cost. A donor's other rows + from before its first split after them then go to the nearer of that + split's two centroids. Every centroid returns the mean of its last-pass + rows (without captured labels, of those assigned to it after its last + split). A value revives clusters below that + fraction of the mean mass instead, splitting mass-sampled donors (line 9, + Appendix J); 0 disables revival. + + ``finalize`` computes unweighted means from assignments collected while + the centroids move during the last epoch (line 12). Unassigned centroids + retain their positions. ``train`` returns centroids and last-pass labels. + For Euclidean clustering, ``obj`` reports moving-pass sums of squared + distances; use ``assign`` to + evaluate the final centroids. + + Implementation details: the initial mass is 2**-16 (the paper uses 1e-10), + remainder batches are retained, and fractional epoch budgets are supported. + ``spherical=True`` extends the algorithm to projected centroid directions. + + ``max_points_per_centroid`` caps the training set as in ``faiss.Kmeans``: + when the input has more than ``max_points_per_centroid * k`` rows, + ``train`` uses a random subset of that many rows (drawn from ``seed``) and + returns label -1 for the other rows. The default None trains on all rows. + + Input arrays are converted to contiguous FP32. Model coordinates, + statistics and closing centroids use FP32; objectives use FP64. + Use Emeans or QuantizedEmeans for tensor input. + """ + + _backend = "faiss" + + def __init__( + self, + d, + k, + nepochs=5, + batch_size=None, + alpha0=None, + batch_law="auto", + seed=1234, + verbose=False, + assignment_chunk_size=None, + capture_assignments=True, + spherical=False, + *, + unused_threshold=None, + max_points_per_centroid=None, + closing_handover=True, + ): + self.d = int(d) + self.k = int(k) + self._set_max_points_per_centroid(max_points_per_centroid) + self.closing_handover = bool(closing_handover) + nepochs = float(nepochs) + self.nepochs = int(nepochs) if nepochs.is_integer() else nepochs + self.batch_size = batch_size + self.alpha0 = alpha0 + self.batch_law = batch_law + self.unused_threshold = unused_threshold + self._unused_threshold = _resolve_unused_threshold( + unused_threshold, self.d + ) + self.seed = int(seed) + self.verbose = bool(verbose) + self.assignment_chunk_size = ( + None + if assignment_chunk_size is None + else int(assignment_chunk_size) + ) + self.capture_assignments = bool(capture_assignments) + # Closing-pass relabelling of rows held by revived centroids (train() only). + self._handover = None + self.closing_handover_stats = None + self.spherical = bool(spherical) + self.centroids = None + self.assignments = None + self.obj = None + self.iteration_stats = None + self.recipe = None + self.n_splits = 0 + self._usage = None + self._centroids = None + self._removal_stats = self._axes = None + self._pending_stats = None + self._failed = False + self._batch_accumulation = self._batch_objective = None + self._batch_centroids = None + self._batch_stats = None + self._pass_counts = self._pass_sums = self._objective = None + self._split_rng = None + self._unit_centroids = self._unit_version = None + self._unit_generation = 0 + + def _readout(self, force=False): + """Return effective FP32 centroids for assignment and inspection. + + "Readout" means converting the internal EMA positions into the + coordinates used by assignment and ``current_centroids``. Euclidean + clustering uses the stored positions directly. Spherical clustering + uses their unit directions, keeping the EMA positions unchanged; + zero vectors remain zero. + + Directions are cached and refreshed after model updates or when + ``force=True``. The returned array borrows model storage; copy it to + retain an independent snapshot. + """ + if not self.spherical: + return self._centroids + from .e_means_spherical import normalize_into + + version = None + token = (self._unit_generation, version) + if self._unit_centroids is None: + self._unit_centroids = np.empty_like(self._centroids) + if force or self._unit_version != token: + normalize_into(self._centroids, self._unit_centroids) + self._unit_version = token + return self._unit_centroids + + def current_centroids(self): + """Borrow a read-only view of the current FP32 coordinates. + + Acquire a new view after update, end_epoch or finalize. + Copy the view for an independent snapshot. Spherical mode borrows + normalized directions from a reusable cache; zero stays zero. + """ + if self._failed: + raise RuntimeError( + "create a new object after execution failure" + ) + view = self._readout().view() + view.flags.writeable = False + return view + + def _get_assignment_chunk_size(self): + return self.assignment_chunk_size or 65536 + + def _choose_splits(self, rng): + if self._unused_threshold is None: + stats, d = self._removal_stats, self.d + return self._choose_removal_splits( + stats[:, d].astype("float64"), self._usage.astype("float64"), + self._axis_scale * np.linalg.norm(stats[:, :d].astype("float64"), axis=1)) + # Sample donors without replacement in proportion to their usage. + threshold = _numpy_unused_threshold( + self._usage, self.k, self._unused_threshold + ) + unused = self._usage < threshold + donors = (~unused) & (self._usage > 0) + nsplit = min(int(unused.sum()), int(donors.sum())) + if nsplit == 0: + return None, None + + uniform = np.maximum( + rng.random_sample(self.k), np.finfo("float64").tiny + ) + keys = np.full(self.k, -np.inf) + keys[donors] = np.log(self._usage[donors]) - np.log( + -np.log(uniform[donors]) + ) + source = np.argsort(keys)[-nsplit:][::-1] + target = np.flatnonzero(unused)[:nsplit] + + return source, target + + def _apply_splits(self, source, target): + # c_j -/+ s_j u_j, s_j = sqrt(2 ||U_j|| / (pi N_j)) with N_j before + # halving, in FP64 rounded once; s_j = 0 (coincident copies, separated + # below) for a zero or non-finite ||U_j|| or N_j, or without U. + centroids = self._centroids[source].astype("float64") + offset = 0.0 + if self._removal_stats is not None: + norm = self._axis_scale * np.linalg.norm(self._removal_stats[source, :-1].astype("float64"), axis=1) + mass = self._usage[source].astype("float64") + valid = (norm > 0) & (mass > 0) & np.isfinite(norm) & np.isfinite(mass) + spread = np.sqrt(2.0 * np.where(valid, norm / np.where(valid, mass, 1.0), 0.0) / np.pi) + offset = spread[:, None] * self._axes[source].astype("float64") + donor_centroids = (centroids - offset).astype("float32") + child_centroids = (centroids + offset).astype("float32") + _separate_splits(donor_centroids, child_centroids) + half_usage = self._usage[source] / 2.0 + + self._usage[source] = half_usage + self._centroids[source] = donor_centroids + self._usage[target] = half_usage + self._centroids[target] = child_centroids + if self._removal_stats is not None: + self._removal_stats[source] /= 2 + self._removal_stats[target] = self._removal_stats[source] + self._axes[target] = self._axes[source] + if self._pass_sums is not None and self._unused_threshold is None and self._handover is None: + # Cost-based revival in the last pass, no handover: neither end keeps rows from before the split. + for v in (self._pass_sums, self._pass_counts): + v[source] = v[target] = 0 + if self._handover is not None: + # O(k): when each revived centroid moved, in closing-pass rows. + self._handover["moved_at"][np.asarray(target)] = self._handover["done"] + self._handover["events"].append((np.asarray(target), np.asarray(source), self._handover["done"])) + self.n_splits += len(source) + self._invalidate_readout() + return len(source) + + def _handover_start(self, labels, second, x): + """Begin the closing pass's handover: ``labels`` (n,) are the captured + assignments, ``second`` (n,) each row's second-nearest index from the + same assignment (-1 if unknown). A revival only records, per revived + centroid, how many closing-pass rows were assigned when it moved + (``moved_at``, O(k)); the rows are sorted out once, at the end.""" + self._handover = dict(labels=labels, second=second, x=x, done=0, events=[], + moved_at=np.full(self.k, -1, dtype="int64")) + + def _handover_finish(self, order, rows): + """One pass over the ``rows`` closing-pass rows in visiting ``order``: a + row assigned before its centroid moved takes its second-nearest unless + that centroid moved after the row's assignment too; those rows are + assigned again like a training batch (against the current centroids), + so this costs their share of one epoch. ``_close_split_centroids`` then + rebuilds the closing sums.""" + h, self._handover = self._handover, None + labels, second, x, moved_at = h["labels"], h["second"], h["x"], h["moved_at"] + handed, search = [], [] + if not (moved_at >= 0).any(): # O(k): nothing moved in this pass. + rows = 0 + for begin in range(0, rows, _HANDOVER_CHUNK): + index = order[begin:min(begin + _HANDOVER_CHUNK, rows)] + rank = np.arange(begin, begin + len(index)) + stale = rank < moved_at[labels[index]] + if not stale.any(): + continue + nearest2 = second[index].astype("int64") + usable = stale & (nearest2 >= 0) & (moved_at[np.maximum(nearest2, 0)] <= rank) + labels[index[usable]] = nearest2[usable] + handed.append(index[usable]) + search.append(index[stale & ~usable]) + handed = np.concatenate(handed) if handed else order[:0] + search = np.concatenate(search) if search else order[:0] + if len(search): + centroids = self._readout() + chunk_size = self.recipe["assignment_chunk_size"] + for begin in range(0, len(search), chunk_size): + chunk = search[begin:begin + chunk_size] + _, labels[chunk] = self._assign_rows(np.ascontiguousarray(x[chunk]), centroids) + self._close_split_centroids(order, rows, labels, x, moved_at, h["events"], + np.concatenate((handed, search))) + self.closing_handover_stats = dict(second=len(handed), searched=len(search)) + + def _close_split_centroids(self, order, rows, labels, x, moved_at, events, stale_rows): + """Twin reassignment and closing sums, as ``Emeans._close_split_centroids``.""" + if not rows: + return + target, source, born = ( + np.concatenate(v) for v in zip( + *((t, s, np.full(len(t), b)) for t, s, b in [([0], [self.k], 0)] + events) + ) + ) # Donor k: no row. + span, order = rows + 1, order[:rows] + by_donor = np.argsort(source * span + born, kind="stable") + target, source, born = target[by_donor], source[by_donor], born[by_donor] + stale, rebuild = np.zeros(len(labels), dtype=bool), np.zeros(self.k + 1, dtype=bool) + stale[stale_rows] = True + _twin_reassign(order, labels, lambda i: x[i], self._readout(), moved_at, source * span + born, + target, source, born, stale, span, _HANDOVER_CHUNK) + rebuild[source] = rebuild[np.where(source < self.k, target, self.k)] = rebuild[labels[stale_rows]] = True + rebuild = rebuild[:self.k] + self._pass_sums[rebuild] = 0 + self._pass_counts[rebuild] = 0 + index = order[rebuild[labels[order]]] + chunk = self.recipe["assignment_chunk_size"] + for begin in range(0, len(index), chunk): + part = index[begin:begin + chunk] + _add_rows_at(self._pass_sums, labels[part], x[part]) + self._pass_counts += np.bincount(labels[part], minlength=self.k).astype(self._pass_counts.dtype) + + def _assign_rows(self, x, centroids, second_out=None, second_labels_out=None): + nearest = 1 if second_out is None else 2 + if self.spherical: + similarity, labels = faiss.knn( + x, centroids, nearest, metric=faiss.METRIC_INNER_PRODUCT + ) + distance = -2 * similarity + else: + distance, labels = faiss.knn(x, centroids, nearest) + if second_out is not None: + second_out[:] = distance[:, -1] + tie = distance[:, 0] == distance[:, -1] + if second_labels_out is not None: + second_labels_out[:] = np.where(tie, labels.max(axis=1), labels[:, -1]) + # Ties keep the lowest label, as with one neighbor. + return distance[:, 0], np.where(tie, labels.min(axis=1), labels[:, 0]) + + def begin(self, global_n, init_centroids): + """Copy initial centroids and start the caller-driven loop. + + Call once on a fresh object. + Initial centroids have shape (k, d). Each epoch supplies its recipe's + row count in logical batches, including the final remainder, then + calls end_epoch. The caller owns loading and ordering rows. + """ + if self._failed or self.recipe is not None: + raise RuntimeError("create a new object for another run or after failure") + n = int(global_n) + centroids = np.ascontiguousarray(init_centroids, dtype="float32") + self._failed = True + self._centroids = self._initial_centroid_state(centroids) + self._usage = np.full(self.k, _INIT_USAGE, dtype="float32") + self._batch_stats = np.empty((self.k, self.d + 1), dtype="float32") + self._split_rng = np.random.RandomState(self.seed) + self._resolve_removal_revival() + if self._keeps_removal_stats(): + # Rows are the EMAs [U / _axis_scale | R] and the batch's + # [sum p y | sum d2 - d1]. + self._removal_stats = np.zeros((self.k, self.d + 1), dtype="float32") + self._axis_scale = 1.0 + self._batch_removal = np.zeros((self.k, self.d + 1), dtype="float32") + self._axes = self._initial_removal_axes() + self._resolve_run_recipe(n) + if self.spherical: + self.recipe.update( + spherical=True, + assignment_score="represented_inner_product", + objective="sum(2-2*represented_inner_product)", + ) + self._n = n + self._step = self._epoch = 0 + self.iteration_stats = [] + self._start_epoch() + self._start_time = time.perf_counter() + self._failed = False + self._header_due, self._quiet = True, False + + def _initial_centroid_state(self, centroids): + state = centroids.copy() + if self.spherical: + from .e_means_spherical import normalize_into + + normalize_into(state, state) + return state + + def _initial_removal_axes(self): + axes = self._split_rng.standard_normal((self.k, self.d)) + return (axes / np.linalg.norm(axes, axis=1, keepdims=True)).astype("float32") + + def _start_epoch(self): + self._epoch_steps = self._epoch_rows = 0 + self._splits_before = self.n_splits + self._pass_counts = np.zeros(self.k, dtype="float64") + self._objective = np.float64(0) + self._pass_sums = ( + np.zeros_like(self._centroids) + if self._epoch == len(self.recipe["epoch_rows"]) - 1 + else None + ) + + def accumulate(self, x): + """Accumulate rows against one fixed centroid snapshot. + + Complete statistics contain FP32 sums/counts, an FP64 objective and + the supplied row count. Supply exactly the recipe's logical batch + size before update. Partial calls return sums/counts as None. + Complete totals borrow workspace; copy them before the next call + if they must be retained. Final-pass labels, when enabled, are owned + by the caller and describe only these supplied rows. + """ + self._require_running() + try: + x = np.ascontiguousarray(x, dtype="float32") + except BaseException: + self._failed = True + raise + return self._accumulate(x) + + def _accumulate(self, x, index=None, labels_out=None, second_labels_out=None): + # Indexed matrix training gathers only assignment chunks, never B*d. + n = len(x) if index is None else len(index) + if n == 0 and self._pending_stats is not None: + stats = dict(self._pending_stats) + if ( + self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + stats["labels"] = np.empty(0, dtype="int64") + return stats + try: + # Only plain models hand rows over; subclasses keep their signature. + stats = self._accumulate_core( + x, index, labels_out=labels_out, + **({} if second_labels_out is None else {"second_labels_out": second_labels_out})) + except BaseException: + self._failed = True + self.assignments = None + raise + self._pending_stats = stats + return stats + + def _accumulate_core(self, x, index=None, labels_out=None, second_labels_out=None): + n = len(x) if index is None else len(index) + pending_n = ( + 0 if self._pending_stats is None else self._pending_stats["n"] + ) + target = self._local_batch_size() + wide = n > 0 and self._logical_batch_size() > _FLOAT32_COUNT_LIMIT + if pending_n == 0: + # Bound the whole contribution, not each supplied/assignment chunk. + self._batch_stats.fill(0) + accumulation = ( + np.zeros(self._batch_stats.shape, dtype="float64") + if wide + else self._batch_stats + ) + self._batch_objective = np.float64(0) + self._batch_centroids = self._readout() + self._batch_accumulation = accumulation + accumulation = self._batch_accumulation + objective = self._batch_objective + centroids = self._batch_centroids + sums, counts = accumulation[:, :-1], accumulation[:, -1] + captured_labels = None if labels_out is None else labels_out[:n] + if ( + captured_labels is None + and self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + captured_labels = np.empty(n, dtype="int64") + chunk_size = self.recipe["assignment_chunk_size"] + for begin in range(0, n, chunk_size): + end = min(begin + chunk_size, n) + rows = x[begin:end] if index is None else x[index[begin:end]] + # Mass-based revival reads only U: no second-nearest search, and R stays 0. + track = self._removal_stats is not None + second = (np.empty(len(rows), dtype="float32") + if track and self._unused_threshold is None else None) + second_labels = None + if second_labels_out is not None: + second_labels = second_labels_out[begin:end] + if second is None: + second_labels[:] = -1 # Mass-based revival: no handover. + second_labels = None + distance, labels = self._assign_rows(rows, centroids, second, second_labels) + if track: + # Keep the contiguous copy referenced: swig_ptr does not own it. + nearest = np.ascontiguousarray(distance) + faiss.accumulate_removal_stats( + self.d, len(rows), self.k, *map(faiss.swig_ptr, ( + rows, labels, nearest, nearest if second is None else second, + centroids, self._axes, self._batch_removal))) + if captured_labels is not None: + captured_labels[begin:end] = labels + if self.spherical: + objective += 2 * len(rows) + objective += distance.sum(dtype="float64") + if accumulation.dtype == np.float32: + if len(labels) and labels.min() < 0: + raise ValueError("faiss found no nearest centroid for some rows") + faiss.accumulate_cluster_sums(self.d, len(rows), self.k, *map( + faiss.swig_ptr, (rows, labels, accumulation))) + else: + counts += np.bincount(labels, minlength=self.k) + _add_rows_at(sums, labels, rows) + self._batch_objective = objective + total_n = pending_n + n + if total_n == target and accumulation is not self._batch_stats: + accumulation = self._complete_statistics(accumulation) + sums, counts = accumulation[:, :-1], accumulation[:, -1] + complete = total_n == target or total_n == 0 + stats = { + "sums": sums if complete else None, + "counts": counts if complete else None, + "objective": objective, + "n": total_n, + } + if self._removal_stats is not None: + stats["removal"] = self._batch_removal + if captured_labels is not None: + stats["labels"] = captured_labels + return stats + + def _prepare_statistics(self, stats, expected_n): + if "stat_schema" in stats: + raise ValueError("stat_schema is only supported by Tensor statistics") + return None, stats["sums"], stats["counts"], stats["objective"] + + def _apply_statistics( + self, ids, sums, counts, objective, alpha, decay, replace_usage=False + ): + """Apply Algorithm 1, line 8 (Equation 2), to prepared batch statistics. + + In the paper's notation, ``sums`` is s_j, ``counts`` is n_j, + ``decay`` is gamma and ``alpha`` is 1 - gamma. For occupied clusters, + the sum-and-count EMA is expressed using mass N_j and centroid c_j: + + N_new = decay * N_j + alpha * n_j + c_new = c_j + (alpha * n_j / N_new) * (s_j / n_j - c_j) + + ``_usage`` stores N_j and ``_centroids`` stores c_j = S_j / N_j. + Empty clusters keep their positions. ``replace_usage`` bypasses the + previous mass for occupied clusters when the step is one. ``ids`` + maps sparse statistics to centroid rows; None denotes the full table. + + Preserve batch counts and sums in epoch totals before the EMA for + Algorithm 1's last-epoch finalization (line 12), and add the batch + objective for reporting. The caller handles revival afterward (line 9). + See the class docstring for the paper reference. + """ + self._objective += objective + if self._removal_stats is not None: + # U decays as one scalar, _axis_scale; touched rows add sum p y + # and renew V. + stats, d = self._removal_stats, self.d + stats[:, d] = decay * stats[:, d] + alpha * self._batch_removal[:, d] + scale = self._axis_scale * decay + if not scale > 2.0**-32: + stats[:, :d] *= scale + scale = 1.0 + self._axis_scale = scale + touched = np.flatnonzero(counts) + if ids is not None: + touched = ids[touched] + faiss.update_removal_axes( + d, len(touched), faiss.swig_ptr(touched), alpha / scale, *map(faiss.swig_ptr, ( + self._batch_removal, stats, self._axes))) + if ids is None: + self._pass_counts += counts + if self._pass_sums is not None: + self._pass_sums += sums + else: + np.add.at(self._pass_counts, ids, counts) + if self._pass_sums is not None: + np.add.at(self._pass_sums, ids, sums) + touched = counts > 0 + selected = touched if ids is None else ids[touched] + if not replace_usage: + self._usage *= decay + retained = ( + self._usage[selected] + if not replace_usage + else np.zeros_like(counts[touched]) + ) + mass = retained + alpha * counts[touched] + mean = sums[touched] / counts[touched, None] + weight = alpha * counts[touched] / mass + position = self._centroids[selected] + weight[:, None] * ( + mean - self._centroids[selected] + ) + position[weight == 1] = mean[weight == 1] + self._centroids[selected] = position + self._usage[selected] = mass + self._invalidate_readout() + + def _epoch_totals(self): + return float(self._epoch_objective()), float( + np.dot(self._pass_counts, self._pass_counts) + ) + + def _spherical_closing(self): + from .e_means_spherical import normalize_into + + result = np.empty_like(self._centroids) + # Bound wide means separately from projection scratch; normalize before + # F32. + rows = max(1, (1 << 25) // (8 * self.d)) + for begin in range(0, self.k, rows): + end = min(begin + rows, self.k) + sums, counts = ( + self._pass_sums[begin:end], + self._pass_counts[begin:end], + ) + raw = self._centroids[begin:end] + mean = sums / np.maximum(counts, 1)[:, None].astype(sums.dtype) + mean = np.where((counts > 0)[:, None], mean, raw) + normalize_into(mean, result[begin:end]) + return result + + def finalize(self): + """Return closing means after the final epoch. + + Centroids without rows in that epoch retain their positions. Repeated + calls return the same result. + """ + if self._failed: + raise RuntimeError( + "create a new object after execution failure" + ) + if self.centroids is not None: + return self.centroids + self._failed = True + nonempty = self._pass_counts > 0 + centroids = ( + self._centroids if self.spherical else self._centroids.copy() + ) + objectives = [stat["obj"] for stat in self.iteration_stats] + if self.spherical: + self.centroids = self._spherical_closing() + else: + centroids[nonempty] = self._pass_sums[nonempty] / self._pass_counts[ + nonempty, None + ].astype("float32") + self.centroids = np.ascontiguousarray(centroids, dtype="float32") + self.obj = np.asarray(objectives, dtype="float64") + self._centroids = self._usage = self._batch_stats = None + self._removal_stats = self._axes = self._batch_removal = None + self._unit_centroids = self._unit_version = None + self._pass_sums = self._pass_counts = self._objective = None + self._pending_stats = None + self._batch_accumulation = self._batch_objective = None + self._batch_centroids = None + self._failed = False + return self.centroids + + def train(self, x, init_centroids=None): + """Train on x, or on a random subset when max_points_per_centroid binds. + + Return centroids and last-pass labels for every row of x (None with + capture disabled); rows left out of the subset get label -1. Only the + subset is read from x, so a memory-mapped array is not loaded whole. + """ + keep = self._training_subset(len(x)) + if keep is None: + return self._train_rows(x, init_centroids) + _, sampled = self._train_rows(x[keep], init_centroids) + if sampled is not None: + try: + labels = np.full(len(x), -1, dtype=sampled.dtype) + labels[keep] = sampled + except BaseException: + self._failed = True + self.assignments = None + raise + self.assignments = labels + return self.centroids, self.assignments + + def _train_rows(self, x, init_centroids=None): + """Train an FP32 matrix, returning centroids and captured assignments.""" + start, given_init = time.perf_counter(), init_centroids is not None + x = np.ascontiguousarray(x, dtype="float32") + n = len(x) + if init_centroids is None: + init_centroids = ( + x + if n == self.k + else x[ + np.random.RandomState(self.seed).permutation(n)[: self.k] + ] + ) + self.begin(n, init_centroids) + self._report_header_once() + if self._reports(): + self._report_preprocessing(start, given_init, n) + assignments = second_labels = None + if self.capture_assignments: + assignments = np.full(n, -1, dtype="int64") + if (self._unused_threshold is None and self.closing_handover + and type(self)._accumulate_core is NumpyEmeans._accumulate_core): + # Cost-based revival can move a centroid during the closing + # pass; captured rows it held then take their second-nearest. + second_labels = np.full(n, -1, dtype=_compact_label_dtype(self.k)) + self.recipe["closing_handover"] = ( + "second_nearest" if second_labels is not None else None) + try: + for epoch, rows in enumerate(self.recipe["epoch_rows"]): + if second_labels is not None and epoch == len(self.recipe["epoch_rows"]) - 1: + self._handover_start(assignments, second_labels, x) + order = np.random.RandomState( + _epoch_seed(self.seed, epoch) + ).permutation(n) + for begin in range(0, rows, self.recipe["batch_size"]): + batch = order[ + begin : min(begin + self.recipe["batch_size"], rows) + ] + if ( + assignments is not None + and epoch == len(self.recipe["epoch_rows"]) - 1 + ): + chunk_size = self.recipe["assignment_chunk_size"] + for offset in range(0, len(batch), chunk_size): + chunk = batch[offset : offset + chunk_size] + second = (None if second_labels is None + else np.empty(len(chunk), dtype=second_labels.dtype)) + stats = self._accumulate(x, chunk, None, second) + assignments[chunk] = stats.pop("labels") + if second is not None: + second_labels[chunk] = second + if self._handover is not None: + self._handover["done"] += len(batch) + self.update(stats) + else: + self.update(self._accumulate(x, batch)) + self.end_epoch() + if self._handover is not None: + self._handover_finish(order, self.recipe["epoch_rows"][-1]) + self.finalize() + except BaseException: + self._failed = True + self.assignments = None + self._handover = None + raise + self.assignments = assignments + return self.centroids, self.assignments + + def assign(self, x): + """Return squared L2 distances and nearest centroid IDs. + + With spherical=True, return inner-product similarities instead. + Input rows must already be normalized for spherical assignment. + """ + if self._failed: + raise RuntimeError( + "create a new object after execution failure" + ) + x = np.ascontiguousarray(x, dtype="float32") + distance = np.empty(len(x), dtype="float32") + labels = np.empty(len(x), dtype="int64") + chunk_size = self._get_assignment_chunk_size() + for begin in range(0, len(x), chunk_size): + end = min(begin + chunk_size, len(x)) + distance[begin:end], labels[begin:end] = self._assign_rows( + x[begin:end], self.centroids + ) + if self.spherical: + distance *= -0.5 + return distance, labels diff --git a/thirdparty/faiss/contrib/e_means/e_means_distributed.py b/thirdparty/faiss/contrib/e_means/e_means_distributed.py new file mode 100644 index 000000000..03571e3f8 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means_distributed.py @@ -0,0 +1,415 @@ +# 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. + +"""Replicated-centroid CPU/GPU E-means with caller-owned communication groups. + +Sparse packing/length discovery and coordinated revival can synchronize with +the host. Stock synchronous collectives order consumption on the caller's +current stream. +""" + +import copy + +import numpy as np +import torch +import torch.distributed as dist + +from .base import _divisibility_error +from .e_means_quantized import QuantizedEmeans +from .e_means import NumpyEmeans + + +def _check_group(group): + if not dist.is_initialized(): + raise RuntimeError( + "initialize the process group before DistributedEmeans" + ) + if not isinstance(group, dist.ProcessGroup) or dist.get_rank(group) < 0: + raise ValueError("group must contain the caller") + return dist.get_world_size(group) + + +_AXIS_HOST_BYTES = 1 << 25 + + +def _fill_initial_axes(axes, rng): + """Host FP64 Gaussian directions, rounded once into required FP32 state.""" + k, d = axes.shape + capacity = max(1, (_AXIS_HOST_BYTES - 8) // 24) # Gaussian, norm and conversion scratch. + numpy_state = isinstance(axes, np.ndarray) + + def write(destination, values): + rounded = values.astype("float32") + if numpy_state: + np.copyto(destination, rounded) + else: + destination.copy_(torch.from_numpy(rounded)) + + if d <= capacity: + rows = max(1, _AXIS_HOST_BYTES // (24 * d + 8)) + for begin in range(0, k, rows): + end = min(begin + rows, k) + values = rng.standard_normal((end - begin, d)) + values /= np.linalg.norm(values, axis=1, keepdims=True) + write(axes[begin:end], values) + return + # Even an oversized row has bounded scratch: replay only random draws, + # never caller data, after obtaining its host FP64 norm. + numpy_rng = isinstance(rng, np.random.RandomState) + for row in range(k): + state = rng.get_state() if numpy_rng else copy.deepcopy(rng.bit_generator.state) + square = np.float64(0) + for begin in range(0, d, capacity): + values = rng.standard_normal(min(capacity, d - begin)) + square += np.square(values).sum(dtype="float64") + del values + if numpy_rng: + rng.set_state(state) + else: + rng.bit_generator.state = state + norm = np.sqrt(square) + for begin in range(0, d, capacity): + end = min(begin + capacity, d) + write(axes[row, begin:end], rng.standard_normal(end - begin) / norm) + + +class _ReplicatedCentroids: + """E-means with equal row contributions and replicated FP32 centroids. + + ``group`` is explicit and caller-owned; ``transport`` is fixed at construction. + All ranks must establish matching recipes/codecs and collective schedules. Auto does not add partial-accumulation communication. Begin + takes same-shape/device tensors on each rank; group rank zero supplies their + values. CPU state uses Gloo and FP32 statistics; CUDA retains + its supported schemas. Use the caller-driven lifecycle, not the local trainer. + + Accumulate supplied chunks until each rank completes its equal local share + of the prescribed global batch (including the final tail). Chunk sizes and + call counts may differ across ranks; partial accumulation does not + communicate. Update reduces each completed contribution and advances the + global batch once. With capture_assignments enabled, final-pass labels + belong to each supplied chunk; this class has no dataset-wide assignments. + Floating and encoded FP8/INT8/UINT8 inputs use the local cost rule with + common CPU-initialized axes. + Caller-driven batches retain final-pass labels without local train closing handover. + """ + + def __init__(self, *args, group, transport="auto", **kwargs): + ranks = _check_group(group) + if kwargs.get("max_points_per_centroid") is not None: + raise ValueError( + "max_points_per_centroid applies to train(x); subsample the " + "rows you pass to accumulate instead" + ) + super().__init__(*args, **kwargs) + self._group, self._group_size, self._transport = group, ranks, transport + self._rank = dist.get_rank(group) + self._axis_seed = None + + def _reports(self): + return self.verbose and self._rank == 0 + + def _describe_parallel(self): + cuda = not isinstance(self._centroids, np.ndarray) and self._centroids.is_cuda + return "Using %d %s with class %s" % ( + self._group_size, "GPUs" if cuda else "CPU processes", type(self).__name__) + + def begin(self, global_n, init_centroids): + if self._failed or self.recipe is not None: + raise RuntimeError("create a new object for another run or after failure") + quantizer = getattr(self, "quantizer", None) + if quantizer is not None and not self._automatic: + from .e_means_quantized import check_codec_fit + + try: + check_codec_fit(self._group, quantizer, init_centroids.device) + except BaseException: + self._failed = True + self.assignments = None + raise + numpy_state = isinstance(self, NumpyEmeans) + device = torch.device("cpu") if numpy_state else init_centroids.device + if device.type == "cpu" and dist.get_backend(self._group) != "gloo": + self._failed = True + raise ValueError("CPU DistributedEmeans requires a Gloo group") + if (self.unused_threshold is None and self.k > 1 + and getattr(self, "_input_dtype", None) in + (None, torch.float32, torch.float16, torch.bfloat16, torch.float8_e4m3fn, + torch.int8, torch.uint8)): + try: + # Preserve existing class seed ranges, without drawing from + # either the model generator or the ambient RNG. + if numpy_state: + np.random.RandomState(self.seed) + seed = self.seed + else: + seed = torch.Generator().manual_seed(self.seed).initial_seed() + packed = torch.tensor(list(seed.to_bytes(8, "little")), + dtype=torch.uint8, device=device) + dist.broadcast(packed, src=dist.get_global_rank(self._group, 0), group=self._group) + self._axis_seed = int.from_bytes(bytes(packed.cpu().tolist()), "little") + except BaseException: + self._failed = True + self.assignments = None + raise + super().begin(global_n, init_centroids) + ranks, batch = self._group_size, self.recipe["batch_size"] + if ( + min(batch, self._n) % ranks + or self._n % ranks + or any(rows % ranks for rows in self.recipe["epoch_rows"]) + ): + self._failed = True + raise _divisibility_error(self.recipe, self._n, batch, ranks) + + def _initial_centroid_state(self, centroids): + # The superclass copy is the model's only initial-state allocation. + # Root values must be present before any genuine derived-state hook. + state = super()._initial_centroid_state(centroids) + try: + dist.broadcast(torch.from_numpy(state) if isinstance(state, np.ndarray) else state, + src=dist.get_global_rank(self._group, 0), group=self._group) + except BaseException: + self._failed = True + self.assignments = None + raise + return state + + def _local_batch_size(self): + return super()._local_batch_size() // self._group_size + + def _complete_statistics(self, accumulation): + numpy_state = isinstance(self._batch_stats, np.ndarray) + floating = (np.issubdtype(self._batch_stats.dtype, np.floating) + if numpy_state else self._batch_stats.is_floating_point()) + double = np.dtype("float64") if numpy_state else torch.float64 + return accumulation if floating and accumulation.dtype == double else super()._complete_statistics(accumulation) + + def _accumulate(self, *args, **kwargs): + stats = super()._accumulate(*args, **kwargs) + if (isinstance(self._batch_stats, torch.Tensor) and stats is self._pending_stats and stats["sums"] is not None + and stats["sums"].dtype != self._batch_stats.dtype): + stats.setdefault("stat_schema", self._batch_stats.dtype) + return stats + + def _initial_removal_axes(self): + if self._axis_seed is None: + return super()._initial_removal_axes() + numpy_state = isinstance(self._centroids, np.ndarray) + if numpy_state: + # Keep NumPy's own Gaussian stream and consumption. + self._split_rng.seed(self._axis_seed) + rng = self._split_rng + axes = np.empty((self.k, self.d), dtype="float32") + else: + # A new replica-only stream; CUDA launch geometry never defines it. + rng = np.random.Generator(np.random.PCG64(self._axis_seed)) + axes = self._centroids.new_empty((self.k, self.d)) + _fill_initial_axes(axes, rng) + return axes + + def _prepare_statistics(self, stats, expected_n): + if stats["n"] != expected_n // self._group_size: + raise ValueError("stats n must match the prescribed batch size") + _, sums, counts, objective = super()._prepare_statistics( + stats, expected_n // self._group_size + ) + try: + removal = self._batch_removal if self._removal_stats is not None else None + workspace = self._batch_stats + numpy_state = isinstance(workspace, np.ndarray) + double, integer = (np.dtype("float64"), np.dtype("int64")) if numpy_state else (torch.float64, torch.int64) + floating = np.issubdtype(workspace.dtype, np.floating) if numpy_state else workspace.is_floating_point() + if floating and workspace.dtype != double and (sums.dtype == double or counts.dtype in (double, integer)): + workspace = self._batch_accumulation + if workspace is None or workspace.dtype != double or workspace.shape != self._batch_stats.shape: + workspace = (np.empty(self._batch_stats.shape, dtype=double) if numpy_state + else self._batch_stats.new_empty(self._batch_stats.shape, dtype=double)) + self._batch_accumulation = workspace + ids, sums, counts = _combine(sums, counts, workspace, self._group, + self._transport, self.recipe["batch_size"], removal=removal) + if sums.dtype != self._batch_stats.dtype: + ready = self._batch_stats[:len(sums)] + ready[:, :-1], ready[:, -1] = sums, counts + sums, counts = ready[:, :-1], ready[:, -1] + except BaseException: + self._failed = True + raise + return ids, sums, counts, objective + + def update(self, stats): + if ( + self._pending_stats is not None + and 0 < self._pending_stats["n"] < self._local_batch_size() + ): + raise ValueError("complete the pending batch before update") + self._require_running() + if (self.unused_threshold is None and self.k > 1 + and isinstance(self._centroids, torch.Tensor) and self._input_dtype is None): + raise ValueError("unused_threshold=None needs typed input statistics from this model's accumulate") + super().update(stats) + + def finalize(self): + result = super().finalize() + self._axis_seed = None + return result + + def _revive_unused(self, rng): + return _revive(self, self._group) + + def _epoch_objective(self): + return _epoch_report(self, self._group) + + def train(self, x, init_centroids=None): + raise NotImplementedError( + "DistributedEmeans uses begin/accumulate/update/end_epoch/finalize, not train(x)" + ) + + +class DistributedEmeans(_ReplicatedCentroids, QuantizedEmeans): + """Replicated tensor E-means; use the caller-driven distributed lifecycle. + + Wide completed contributions expose authoritative FP64 S/N. Their + ``stat_schema`` declares normal Float32/Float64 statistics storage; + copies retain it and edits supply the values reduced. Without it, + external S/N dtype selects storage as usual. An already-FP64 ``double()`` + is a no-op: set the declaration to Float64 to request Float64 storage. + Ranks must supply matching raw precision and declared storage; differing + declarations may leave different schemas even if the SUM succeeds. + """ + + +class DistributedNumpyEmeans(_ReplicatedCentroids, NumpyEmeans): + """Replicated NumPy/Faiss E-means with CPU/Gloo communication. + + Numerical state remains NumPy; conversion occurs only at collective + boundaries. Recipes, equal row shares and communication match + DistributedEmeans. Use begin/accumulate/update/end_epoch/finalize. + Wide contributions expose raw FP64 S/N; global completion narrows once + into fixed FP32 storage. ``stat_schema`` is Tensor-only. + """ + + +def _select_transport(batch_size, k, d, ranks, element_size=4, *, record_bytes=None): + # Conservative initial rule: amortize sparse packing on large dense + # payloads and bound worst-case padded gather storage, including unequal + # occupancy lengths, to twice the dense table. This is not a portable + # crossover; callers can override it for their network/occupancy. No density probe. + dense_bytes = k * (element_size * (d + 1) if record_bytes is None else record_bytes) + bounded_records = ranks * min(batch_size, k) + return ( + "sparse" + if dense_bytes >= 1 << 30 and bounded_records <= 2 * k + else "dense" + ) + + +def _combine(sums, counts, workspace, group, transport, batch_size, *, removal=None): + # Reuse consumed local workspace; native accumulate's views copy to + # themselves. External statistics are packed into the same allocation. + numpy_workspace = isinstance(workspace, np.ndarray) + if numpy_workspace: + # Stage into owned storage; collectives never write caller statistics. + np.copyto(workspace[:, :-1], sums) + np.copyto(workspace[:, -1], counts) + workspace = torch.from_numpy(workspace) + else: + workspace[:, :-1].copy_(sums) + workspace[:, -1].copy_(counts) + payloads = (workspace,) if removal is None else ( + workspace, torch.from_numpy(removal) if numpy_workspace else removal) + ids, reduced = _combine_payloads(payloads, workspace[:, -1], group, transport, batch_size) + if removal is not None and ids is not None: + # The shared local removal EMA consumes a full raw table. Dense has + # already reduced it in place; sparse scatters only the merged IDs. + payloads[1].zero_().index_copy_(0, ids, reduced[1]) + merged = reduced[0] + result = (ids, merged[:, :-1], merged[:, -1]) + return tuple(None if value is None else value.numpy() for value in result) if numpy_workspace else result + + +def _combine_payloads(payloads, counts, group, transport, batch_size): + """Reduce known typed tables over one occupied-ID schedule.""" + workspace = payloads[0] + ranks = dist.get_world_size(group) + if transport == "auto": + transport = _select_transport( + batch_size, + workspace.shape[0], + workspace.shape[1] - 1, + ranks, + workspace.element_size(), + record_bytes=sum(value.shape[1] * value.element_size() for value in payloads), + ) + if transport == "dense": + for value in payloads: + dist.all_reduce(value, op=dist.ReduceOp.SUM, group=group) + return None, payloads + + ids = (counts > 0).nonzero(as_tuple=True)[0] + size = torch.tensor([len(ids)], dtype=torch.int64, device=workspace.device) + sizes = [torch.empty_like(size) for _ in range(ranks)] + dist.all_gather(sizes, size, group=group) + lengths = torch.cat(sizes).tolist() + capacity = max(max(lengths), 1) + padded_ids = torch.zeros( + capacity, dtype=torch.int64, device=workspace.device + ) + padded_ids[: len(ids)] = ids + gathered_ids = [torch.empty_like(padded_ids) for _ in lengths] + dist.all_gather(gathered_ids, padded_ids, group=group) + joined = torch.cat([part[:n] for part, n in zip(gathered_ids, lengths)]) + unique, inverse = joined.unique(sorted=True, return_inverse=True) + reduced = [] + for value in payloads: + padded = value.new_zeros((capacity, value.shape[1])) + padded[:len(ids)] = value[ids] + gathered = [torch.empty_like(padded) for _ in lengths] + dist.all_gather(gathered, padded, group=group) + merged = value.new_zeros((len(unique), value.shape[1])) + offset = 0 + # Unique within rank; ordered additions avoid cross-rank atomic order. + for part, n in zip(gathered, lengths): + merged.index_add_(0, inverse[offset:offset + n], part[:n]) + offset += n + reduced.append(merged) + return unique, tuple(reduced) + + +def _revive(model, group): + coordinator = dist.get_rank(group) == 0 + source, target = ( + model._choose_splits(model._split_rng) if coordinator else (None, None) + ) + n = len(source) if source is not None else 0 + numpy_state = isinstance(model._centroids, np.ndarray) + device = torch.device("cpu") if numpy_state else model._centroids.device + size = torch.tensor([n], device=device, dtype=torch.int64) + root = dist.get_global_rank(group, 0) + dist.broadcast(size, src=root, group=group) + n = int(size.item()) + if not n: + return 0 + if not coordinator: + source = torch.empty(n, device=size.device, dtype=torch.int64) + target = torch.empty_like(source) + elif numpy_state: + source = torch.from_numpy(np.array(source, dtype=np.int64, copy=True, order="C")) + target = torch.from_numpy(np.array(target, dtype=np.int64, copy=True, order="C")) + dist.broadcast(source, src=root, group=group) + dist.broadcast(target, src=root, group=group) + if numpy_state: + source, target = source.numpy(), target.numpy() + return model._apply_splits(source, target) + + +def _epoch_report(model, group): + # Only the local FP64 objective needs reduction. Pass counts/sums already + # contain global statistics; row contributions were checked on the host. + numpy_state = isinstance(model._centroids, np.ndarray) + objective = torch.as_tensor(model._objective) if numpy_state else model._objective + dist.all_reduce(objective, op=dist.ReduceOp.SUM, group=group) + if numpy_state: + model._objective = np.float64(objective.item()) + return model._objective diff --git a/thirdparty/faiss/contrib/e_means/e_means_grouping.py b/thirdparty/faiss/contrib/e_means/e_means_grouping.py new file mode 100644 index 000000000..296cdd60d --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means_grouping.py @@ -0,0 +1,198 @@ +# 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. + +"""CCCL-first grouping with a dependency-absent stable Torch fallback. + +Tile IDs must be in [0, n_groups); contents are not read on the host. Buffers +must not be resized/rebound while a handle or captured graph uses them. +workspace_bytes counts owned tensor storage, including queried scratch; +retained_bytes also counts borrowed keys' backing storage. Neither includes +opaque compiled state or allocator rounding. Provider selection happens only +when a grouped binding is prepared. CCCL may cache descriptors; only the handle +retains their tensor storage. Torch sort/search temporary allocation is opaque. +""" + +from functools import lru_cache +import importlib +import importlib.metadata +from numbers import Integral +from types import SimpleNamespace +from typing import NamedTuple +import warnings + + +_TORCH_WARNING = ( + "CuTe grouping is using Torch because cuda.compute is not installed; " + "measured complete-call slowdown was ~0.6–2.4%. Install cuda-cccl for " + "maximum performance." +) +_provider_warning_emitted = False + + +class _Grouping(NamedTuple): + order: object + offsets: object + workspace_bytes: int + scratch_bytes: int + retained_bytes: int + arrays: tuple + tensors: tuple + sorter: object + bounder: object + tile_ids: object + end_bit: int + provider: str + + +class _TorchGrouping(NamedTuple): + order: object + offsets: object + workspace_bytes: int + scratch_bytes: object + retained_bytes: int + tensors: tuple + pointers: tuple + sorted_keys: object + order64: object + boundaries: object + offsets64: object + provider: str + + +@lru_cache(maxsize=1) +def _grouping_provider(): + try: + module = importlib.import_module("cuda.compute") + except ModuleNotFoundError as error: + if error.name not in ("cuda", "cuda.compute"): + raise + try: + version = importlib.metadata.version("cuda-cccl") + except importlib.metadata.PackageNotFoundError: + return "torch" + raise ImportError( + "cuda-cccl %s is installed but cuda.compute is unavailable; " + "install cuda-cccl with cuda.compute support (tested 1.2.0)" + % version + ) from error + required = ("CountingIterator", "SortOrder", "make_lower_bound", "make_radix_sort") + missing = [name for name in required if not hasattr(module, name)] + if missing: + raise ImportError( + "cuda.compute is missing required grouping API: %s; " + "install cuda-cccl with cuda.compute support (tested 1.2.0)" + % ", ".join(missing) + ) + return "cuda.compute" + + +def selected_grouping_provider(*, warn=False): + """Return the stable CuTe grouping provider; optionally warn once.""" + global _provider_warning_emitted + provider = _grouping_provider() + if warn and provider == "torch" and not _provider_warning_emitted: + warnings.warn(_TORCH_WARNING, RuntimeWarning, stacklevel=2) + _provider_warning_emitted = True + return provider + + +def _array(tensor): + import numpy as np + + shape = tuple(tensor.shape) + dtype = np.dtype(str(tensor.dtype).removeprefix('torch.')) + ptr = tensor.data_ptr() + return SimpleNamespace(shape=shape, dtype=dtype, + size=tensor.numel(), nbytes=tensor.numel() * tensor.element_size(), + data_ptr=lambda: ptr, __cuda_array_interface__={ + 'shape': shape, 'strides': None, 'typestr': dtype.str, + 'data': (ptr, False), 'version': 3}) + + +def _storage_bytes(tensors): + storages = {} + for tensor in tensors: + storage = tensor.untyped_storage() + storages[(storage.device, storage.data_ptr())] = storage.nbytes() + return sum(storages.values()) + + +def prepare_grouping(keys, n_groups): + if isinstance(n_groups, bool) or not isinstance(n_groups, Integral): + raise TypeError('n_groups must be a host integer') + n_groups = int(n_groups) + if not 0 < n_groups < 2**31: + raise ValueError('n_groups must be positive and below 2**31') + import torch + + if (not isinstance(keys, torch.Tensor) or keys.ndim != 1 or not keys.is_cuda + or keys.dtype != torch.int32 or not keys.is_contiguous() + or not 0 < keys.numel() < 2**31): + raise ValueError('keys must be a nonempty contiguous CUDA INT32 vector with B < 2**31') + if selected_grouping_provider(warn=True) == "torch": + with torch.cuda.device(keys.device), torch.no_grad(): + sorted_keys = torch.empty_like(keys) + order64 = torch.empty(keys.numel(), dtype=torch.int64, device=keys.device) + order = torch.empty_like(keys) + boundaries = torch.arange(n_groups + 1, dtype=torch.int32, device=keys.device) + offsets64 = torch.empty(n_groups + 1, dtype=torch.int64, device=keys.device) + offsets = offsets64.view(torch.uint64) + tensors = (keys, sorted_keys, order64, order, offsets, boundaries) + pointers = tuple((tuple(t.shape), t.dtype, t.device, t.data_ptr()) for t in tensors) + return _TorchGrouping(order, offsets, _storage_bytes(tensors[1:]), None, + _storage_bytes(tensors), tensors, pointers, sorted_keys, order64, + boundaries, offsets64, "torch") + from cuda.compute import CountingIterator, SortOrder, make_lower_bound, make_radix_sort + import numpy as np + + with torch.cuda.device(keys.device), torch.no_grad(): + tensors = ( + keys, torch.empty_like(keys), + torch.arange(keys.numel(), dtype=torch.int32, device=keys.device), + torch.empty_like(keys), torch.empty(n_groups + 1, dtype=torch.uint64, device=keys.device)) + k, sorted_keys, rows, order, offsets = map(_array, tensors) + stream = torch.cuda.current_stream(keys.device) + sorter = make_radix_sort(d_in_keys=k, d_out_keys=sorted_keys, + d_in_values=rows, d_out_values=order, order=SortOrder.ASCENDING) + end_bit = max(1, (n_groups - 1).bit_length()) + scratch_bytes = int(sorter(temp_storage=None, d_in_keys=k, d_out_keys=sorted_keys, + d_in_values=rows, d_out_values=order, num_items=k.size, + begin_bit=0, end_bit=end_bit, stream=stream)) + tensors += (torch.empty(scratch_bytes, dtype=torch.uint8, device=keys.device),) + temp = _array(tensors[-1]) + tile_ids = CountingIterator(np.int32(0)) + bounder = make_lower_bound(d_data=sorted_keys, d_values=tile_ids, d_out=offsets) + arrays = (k, sorted_keys, rows, order, offsets, temp) + workspace_bytes = sum(t.untyped_storage().nbytes() for t in tensors[1:]) + return _Grouping(tensors[3], tensors[4], workspace_bytes, scratch_bytes, + workspace_bytes + keys.untyped_storage().nbytes(), arrays, tensors, sorter, bounder, tile_ids, end_bit, + "cuda.compute") + + +def launch_grouping(handle): + import torch + + if handle.provider == "torch": + if any((tuple(t.shape), t.dtype, t.device, t.data_ptr()) != expected + for t, expected in zip(handle.tensors, handle.pointers)): + raise ValueError('grouping buffers must not be resized or rebound') + keys = handle.tensors[0] + with torch.cuda.device(keys.device), torch.no_grad(): + torch.sort(keys, stable=True, out=(handle.sorted_keys, handle.order64)) + handle.order.copy_(handle.order64) + torch.searchsorted(handle.sorted_keys, handle.boundaries, out=handle.offsets64) + return handle.order, handle.offsets + k, sorted_keys, rows, order, offsets, temp = handle.arrays + if any(tuple(t.shape) != a.shape or t.data_ptr() != a.__cuda_array_interface__['data'][0] + for t, a in zip(handle.tensors, handle.arrays)): + raise ValueError('grouping buffers must not be resized or rebound') + with torch.cuda.device(handle.tensors[0].device): + stream = torch.cuda.current_stream(handle.tensors[0].device) + handle.sorter(temp_storage=temp, d_in_keys=k, d_out_keys=sorted_keys, + d_in_values=rows, d_out_values=order, num_items=k.size, + begin_bit=0, end_bit=handle.end_bit, stream=stream) + handle.bounder(d_data=sorted_keys, num_items=k.size, d_values=handle.tile_ids, + num_values=offsets.size, d_out=offsets, comp=None, stream=stream) + return handle.order, handle.offsets diff --git a/thirdparty/faiss/contrib/e_means/e_means_quantized.py b/thirdparty/faiss/contrib/e_means/e_means_quantized.py new file mode 100644 index 000000000..ab1b2146d --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means_quantized.py @@ -0,0 +1,847 @@ +# 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. + +"""Quantized PyTorch E-means and representation-specific execution.""" + +import torch + +from .base import _FLOAT32_COUNT_LIMIT, _same_operation +from .e_means_torch import ( + Emeans, + _accumulate_removal_rows, +) + +from .torch_backend import ( + _get_triton_assign_rows, + _check_torch_abs_bound, + _separate_splits, + _require_score_operands, +) + +__all__ = ["QuantizedEmeans"] + +_DEFAULT_QUANTIZER = object() + + +def statistics_codes(rows, prepared, backend, quantizer, *, second=False, distance_dtype=None): + """Consume this assignment's codes before its workspace is reused.""" + if backend == "cute" and quantizer is not None and quantizer.dtype == torch.float8_e4m3fn: + from .cute import _binding_key + return prepared.bindings[_binding_key(len(rows), distance_dtype, second)].workspace + return rows + + +def statistics_values(rows, codes, quantizer, *, code_units=False): + """Return code values or decoded row values for statistics.""" + if code_units: + return codes + if quantizer is not None: + return quantizer.decode(codes) + return rows + + +def _assign_cost_rows(model, rows, centroids, centroid_norm): + """One genuine assignment invocation; exact integer or completed FP32 gap.""" + if model.k < 2: + raise ValueError("encoded SECOND requires at least two centroids") + if model._input_dtype in (torch.int8, torch.uint8): + first = rows.new_empty(len(rows), dtype=torch.int64) + second = torch.empty_like(first) + distance, labels = model._assign_rows(rows, centroids, centroid_norm, first, None, second) + margin = (second - first).float() + if model.quantizer is not None: + from .quantizer import _ldexp + margin = _ldexp(margin, model.quantizer._distance_exponent) + distance = distance.float() + else: + second = rows.new_empty(len(rows), dtype=torch.float32) + distance, labels = model._assign_rows(rows, centroids, centroid_norm, None, None, second) + margin = second - distance + return distance, labels, margin + + +def check_codec_fit(group, quantizer, device): + """Check local fit readiness and agree codec parameters across ranks.""" + import torch.distributed as dist + + try: + if getattr(quantizer, "center", False): + quantizer._fit_token() + if getattr(quantizer, "device", device) != device: + raise ValueError("quantizer fit must be on the local input device") + values = [] + for name in ("shift", "_bias"): + tensor = getattr(quantizer, name, None) + if tensor is not None and tensor.device != device: + raise ValueError("quantizer fit must be on the local input device") + values.append(None if tensor is None else tuple(tensor.detach().cpu().flatten().tolist())) + fit = (str(quantizer.dtype), getattr(quantizer, "d", None), + getattr(quantizer, "center", False), getattr(quantizer, "exponent", None), + getattr(quantizer, "scale", None), *values) + state = (bool(getattr(quantizer, "is_trained", True)), fit) + except Exception as error: + state = (False, str(error)) + peers = [None] * dist.get_world_size(group) + dist.all_gather_object(peers, state, group=group) + if not all(peer[0] for peer in peers): + raise ValueError("all ranks require a valid trained quantizer on their local device") + if any(peer[1] != state[1] for peer in peers): + raise ValueError("quantizer fit differs across ranks") + + +def _get_triton_int8_functions(): + try: + from .triton_assignment import assign_int8_rows, prepare_int8_centroids + except ImportError as error: + raise ImportError( + "Triton assignment requires the triton package" + ) from error + return assign_int8_rows, prepare_int8_centroids + + +class QuantizedEmeans(Emeans): + """E-means with quantizers or native FP8/INT8/UINT8 representations. + + Omission defaults CUDA FP32 to BF16; explicit None stays native, and an + explicit quantizer keeps its representation for original and code queries. + CastQuantizer converts floating chunks to FP16/BF16. FP8 can encode + floating batches per chunk; FP8 and INT8/UINT8 execution require CUDA. + INT8 requires matching codes. + Each object represents one run; create a fresh object for another run. + Raw bytes retain numeric units and INT64 statistics; calibrated codecs + return decoded units. Model coordinates and closing centroids are FP32. + Local and replicated FP32/FP16/BF16/FP8/INT8/UINT8 use cost revival by + default. Exhaustive centroid shards retain their encoded cost integration; + IVF encoded cost activation remains separate. Explicit unused_threshold + retains mass/no-revival behavior. Local captured cost training repairs + stale labels by search and donor rows by the floating baseline twin rule, + then closes every populated centroid from its final labels. + """ + + _removal_revival = True + + def __init__(self, *args, quantizer=_DEFAULT_QUANTIZER, **kwargs): + super().__init__(*args, **kwargs) + self._automatic = quantizer is _DEFAULT_QUANTIZER + if self._automatic: + quantizer = None + self.quantizer = quantizer + self._fp8_quantizer = ( + quantizer is not None and quantizer.dtype == torch.float8_e4m3fn + ) + self._int8_quantizer = ( + quantizer is not None and quantizer.dtype == torch.int8 + ) + self._input_dtype = quantizer.dtype if quantizer is not None else None + self._fp8_peak = None + self._batch_code_units = False + self._batch_operand = self._stats_operand = None + self._centered_cast = getattr(quantizer, "center", False) + self._cast_fit_token = None + if self.spherical and self._centered_cast: + raise ValueError("spherical assignment does not support centered CastQuantizer") + + def _check_cast_fit(self): + if self._centered_cast: + token = self.quantizer._fit_token() + if self._cast_fit_token is not None and token != self._cast_fit_token: + raise RuntimeError("quantizer fit changed; create a new object before model use") + + def _resolve_removal_revival(self): + if ( + self._removal_revival + and self.unused_threshold is None + and self._input_dtype + in ( + torch.float32, + torch.float16, + torch.bfloat16, + torch.float8_e4m3fn, + torch.int8, + torch.uint8, + ) + and getattr(self, "global_k", self.k) > 1 + ): + self._unused_threshold = None + + def _plain_cast_decode(self): + from .quantizer import CastQuantizer + + q = self.quantizer + return (q is not None and not self._centered_cast + and _same_operation(q.decode, CastQuantizer.decode, q) + and _same_operation(q._matrix, CastQuantizer._matrix, q)) + + def _statistics_rows(self, rows): + # Stock uncentered decoding only widens these exact represented + # values; the statistics consumer already accumulates them in FP32. + # Real decoder/metadata-helper overrides still run through decode. + if self._plain_cast_decode(): + return rows + return statistics_values(rows, rows, self.quantizer) + + def _closing_rows(self, x): + if self.quantizer is None: + return super()._closing_rows(x) + from .quantizer import CastQuantizer + + q = self.quantizer + # Only CUDA closing can round rows in place. CPU preparation and real + # codec/caller operations still materialize a bounded row chunk. + if (x.device.type == "cuda" and x.stride(1) == 1 + and self._plain_cast_decode() + and _same_operation(q.compute_codes, CastQuantizer.compute_codes, q) + and all(_same_operation(getattr(self, name), getattr(QuantizedEmeans, name), self) + for name in ("_prepare_rows", "_statistics_rows"))): + return x, (None if x.dtype == q.dtype else q.dtype), None + return x, None, self._stage_closing_rows + + def _stage_closing_rows(self, x, index): + codes = self._prepare_rows(x[index]) + if codes.dtype != self.quantizer.dtype: + # CuTe's stock FP8 route encodes floating rows inside assignment. + # Public encoding matches those bytes; no old workspace is read. + codes = self.quantizer.compute_codes(codes) + values = self._statistics_rows(codes).contiguous() + return values, torch.arange(len(index), device=index.device) + + def _device_split_eligible(self): + # The device-count writer implements this uncentered floating split. + # Real separation/state hooks run through the ordinary split method. + return (not self._centered_cast + and _same_operation(self._apply_splits, QuantizedEmeans._apply_splits, self) + and _same_operation(self._separate_split_values, QuantizedEmeans._separate_split_values, self) + and _same_operation(self._split_removal_statistics, Emeans._split_removal_statistics, self) + and _same_operation(self._split_removal_stats, Emeans._split_removal_stats, self)) + + def begin(self, global_n, init_centroids): + if self._centered_cast: + self.quantizer._matrix(init_centroids) + if init_centroids.device.type == "cpu": + raise ValueError("CPU E-means requires quantizer=None") + self._cast_fit_token = self.quantizer._fit_token() + result = super().begin(global_n, init_centroids) + if self.quantizer is None and self._input_dtype in (torch.int8, torch.uint8): + self._select_statistics_dtype(torch.int64) + return result + + def _resolve_input_dtype(self, x): + if self._input_dtype is None and not self._automatic and self.quantizer is not None: + self._bind_input_dtype(self.quantizer.dtype) + else: + super()._resolve_input_dtype(x) + + def _bind_input_dtype(self, dtype, *, cast=False): + quantizer = self.quantizer + if self._automatic: + quantizer = None + if cast: + from .quantizer import CastQuantizer + + quantizer = CastQuantizer(self.d, dtype) + if self._batch_stats is not None: + self._select_statistics_dtype( + torch.int64 if quantizer is None + and dtype in (torch.int8, torch.uint8) else torch.float32) + super()._bind_input_dtype(dtype, cast=cast) + if self._automatic: + self.quantizer = quantizer + if self._centroids is not None: + self._resolve_removal_revival() + if self._unused_threshold is None: + if self._removal_stats is None: + self._initialize_removal_statistics() + if self.recipe is not None: + self.recipe["unused_threshold"] = None + + def _require_running(self): + super()._require_running() + self._check_cast_fit() + + def current_centroids(self): + self._check_cast_fit() + return super().current_centroids() + + def _capture_operations_match(self, owner=None): + return (super()._capture_operations_match(QuantizedEmeans) + and _same_operation(self._use_code_units, QuantizedEmeans._use_code_units, self) + and _same_operation(self._check_cast_fit, QuantizedEmeans._check_cast_fit, self)) + + def _chunked_capture_matches(self, owner=None): + return super()._chunked_capture_matches(QuantizedEmeans) + + def _finish_step(self, expected_n): + super()._finish_step(expected_n) + self._batch_operand = None + self._batch_code_units = False + + def finalize(self): + self._check_cast_fit() + result = super().finalize() + self._batch_operand = self._stats_operand = None + return result + + def _start_epoch(self): + if self._fp8_peak is not None: + self._fp8_peak.zero_() + super()._start_epoch() + + def _initial_centroid_values(self, init_centroids): + rows = self._prepare_rows(init_centroids) + # Fused CuTe JIT defers chunk encoding; seed positions still need + # codes. + if ( + self._assignment_backend == "cute" + and self._fp8_quantizer + and rows.dtype != self.quantizer.dtype + ): + rows = self.quantizer.compute_codes(rows) + return ( + self.quantizer.decode(rows) + if self.quantizer is not None + else rows.float() + ) + + def _prepare_assignment_query(self, centroids): + if self._input_dtype in (torch.int8, torch.uint8): + _check_torch_abs_bound( + "centroids", torch.finfo(torch.float32).max, centroids + ) + self._fp8_peak = None + represented, centroid_norm = self._prepare_torch_assignment(centroids) + if self._input_dtype == getattr(torch, "float8_e4m3fn", None): + from .quantizer_fp8 import _check_fp8_range + + _check_fp8_range(float(self._fp8_peak), "centroids") + + return represented, centroid_norm + + def _apply_splits(self, source, target): + separate = self._separate_split_values + # Fused splitting implements the built-in separation on the GPU. + # A custom separation callback runs through the ordinary split path. + self._execution_backend.split( + self._centroids, + self._usage, + source, + target, + self._input_dtype, + *self._split_axes(), + self.quantizer, + separate=separate, + built_in_separation=_same_operation(separate, QuantizedEmeans._separate_split_values, self), + ) + return self._finish_splits(source, target) + + def _separate_split_values(self, donor_centroids, child_centroids): + if self._input_dtype in (torch.int8, torch.uint8): + from .quantizer_int8 import representation, separate_splits + + # Encoded split positions must stay finite in model coordinates. + _check_torch_abs_bound( + "revived centroids", + torch.finfo(torch.float32).max, + donor_centroids, + child_centroids, + ) + separate_splits( + donor_centroids, + child_centroids, + representation(self._input_dtype), + self.quantizer, + ) + elif self._input_dtype == getattr(torch, "float8_e4m3fn", None): + from .quantizer_fp8 import separate_splits + + separate_splits(donor_centroids, child_centroids, self.quantizer) + else: + _separate_splits( + donor_centroids, child_centroids, self._input_dtype, + self.quantizer if self._centered_cast else None, + ) + + def _assign_rows( + self, + x, + centroids, + centroid_norm=None, + distance_out=None, + labels_out=None, + second_out=None, + second_labels_out=None, + *, + scores=False, + ): + """Private assignment; native bytes may retain exact INT64 distances.""" + if scores and self._input_dtype in (torch.int8, torch.uint8, torch.float8_e4m3fn): + raise ValueError("scores=True requires unencoded floating operands") + if scores: + _require_score_operands(x, centroids) + + if self._assignment_backend == "cute": + distance, labels = self._execution_backend.assign( + x, + centroids, + centroid_norm, + self.spherical, + distance_out, + labels_out, + second_out, + **({"second_labels_out": second_labels_out} if second_labels_out is not None else {}), + **({"scores": True} if scores else {}), + ) + if self._int8_quantizer and distance_out is not None and distance_out.dtype == torch.int64: + from .quantizer import _ldexp + distance = _ldexp(distance.float(), self.quantizer._distance_exponent) + return distance, labels + if self._assignment_backend == "triton": + + if self._input_dtype in (torch.int8, torch.uint8): + if self.spherical: + raise ValueError("Triton byte assignment supports L2 only") + from .quantizer_int8 import representation + + assign, _ = _get_triton_int8_functions() + distance, labels = assign( + x, + centroids, + centroid_norm, + representation(self._input_dtype), + distance_out, + **({"second_out": second_out} if second_out is not None else {}), + **({"second_labels_out": second_labels_out} if second_labels_out is not None else {}), + ) + else: + if x.shape[1] != centroids.shape[1]: + from .triton_assignment import _pad_columns + + x = _pad_columns( + x, 64 if centroids.dtype == torch.float8_e4m3fn else 16 + ) + distance, labels = _get_triton_assign_rows()( + x, + centroids, + centroid_norm, + **({"second_out": second_out} if second_out is not None else {}), + **({"second_labels_out": second_labels_out} if second_labels_out is not None else {}), + **({"spherical": True} if self.spherical else {}), + **({"return_score": True} if scores else {}), + ) + if self._fp8_quantizer or self._int8_quantizer: + from .quantizer import _ldexp + + if self._int8_quantizer and distance.dtype == torch.int64: + distance = distance.float() + distance = _ldexp(distance, self.quantizer._distance_exponent) + if second_out is not None and second_out.dtype == torch.float32: + second_out.copy_(_ldexp(second_out, self.quantizer._distance_exponent)) + return distance, labels + + return super()._assign_rows( + x, centroids, centroid_norm, distance_out, labels_out, second_out, + **({"second_labels_out": second_labels_out} if second_labels_out is not None else {}), + **({"scores": True} if scores else {}), + ) + + def _accumulate_core(self, x, index=None, raw=False, labels_out=None, ema=None): + if (self._removal_stats is not None + and self._input_dtype in (torch.float32, torch.float16, torch.bfloat16)): + return super()._accumulate_core(x, index, raw, labels_out, ema=ema) + # Tensor work shared by public accumulation and graph replay. + # Raw replay may consume unshifted bounded INT32 byte totals directly. + n = len(x) if index is None else len(index) + pending_n = ( + 0 if self._pending_stats is None else self._pending_stats["n"] + ) + target = self._local_batch_size() + integer_stats = self._batch_stats.dtype == torch.int64 + bound = target if integer_stats else self._logical_batch_size() + limit = 2**24 if integer_stats else _FLOAT32_COUNT_LIMIT + wide = n > 0 and bound > limit + borrowed = False + + shift = ( + integer_stats and x.dtype == torch.uint8 and 255 * target >= 2**31 + ) + borrowed = ( + raw + and integer_stats + and n > 0 + and n == target + and not wide + and not shift + ) + if pending_n == 0: + # Choose code units for the complete logical contribution. + self._batch_code_units = self._use_code_units(n, bound) + if borrowed: + # A complete private replay borrows the batch's INT32 view. + accumulation = self._batch_stats.view(torch.int32)[ + :, : self.d + 1 + ] + accumulation.zero_() + else: + accumulation = ( + self._batch_stats.new_zeros( + self._batch_stats.shape, + dtype=( + torch.int32 + if integer_stats and not wide + else torch.float64 + ), + ) + if (integer_stats and n) or wide + else self._batch_stats.zero_() + ) + self._batch_objective = self._objective.new_zeros(()) + # Retain represented operands through the whole contribution. + if self.spherical: + self._readout( + force=raw + ) # Record projection on every graph replay. + self._batch_centroids, self._batch_norm = ( + self._prepare_torch_assignment(self._centroids) + if n + else (None, None) + ) + self._batch_accumulation = accumulation + self._batch_operand = None + accumulation = self._batch_accumulation + objective, centroid_norm = self._batch_objective, self._batch_norm + centroids = self._batch_centroids + operand = self._batch_operand + q = self.quantizer + code_units = self._batch_code_units + removal = self._removal_stats is not None and self._unused_threshold is None + self._removal_folded = False + native_stats = ( + self.quantizer is None + and self._centroids.is_cuda + and self._assignment_backend in ("triton", "cute") + and n > 0 + and bound <= limit + and x.dtype in (torch.int8, torch.uint8, torch.float16) + and not torch.are_deterministic_algorithms_enabled() + ) + fp8_stats = ( + code_units + and not torch.are_deterministic_algorithms_enabled() + ) + if native_stats or fp8_stats: + from .triton_assignment import accumulate_bytes + sums, counts = accumulation[:, :-1], accumulation[:, -1] + captured_labels = None if labels_out is None else labels_out[:n] + if ( + captured_labels is None + and self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + captured_labels = x.new_empty(n, dtype=torch.int64) + chunk_size = self.recipe["assignment_chunk_size"] + for begin in range(0, n, chunk_size): + end = min(begin + chunk_size, n) + rows = x[begin:end] if index is None else x[index[begin:end]] + rows = self._prepare_rows(rows) + if removal: + distance, labels, margin = _assign_cost_rows(self, rows, centroids, centroid_norm) + else: + distance, labels = self._assign_rows(rows, centroids, centroid_norm) + codes = statistics_codes(rows, centroids, self._assignment_backend, q, second=removal) + if removal: + _accumulate_removal_rows(self, self._statistics_rows(codes), labels, margin) + if captured_labels is not None: + captured_labels[begin:end] = labels + if self.spherical: + objective += 2 * len(rows) + objective += distance.sum(dtype=torch.float64) + if self._removal_stats is not None and not removal: + # Mass-based revival reads only U (p y, y = x - c); R stays 0. + codes = statistics_codes(rows, centroids, self._assignment_backend, q) + y = statistics_values(rows, codes, q).float() - self._readout()[labels] + p = (y * self._axes[labels]).sum(1, keepdim=True) + self._batch_removal.index_add_(0, labels, torch.cat((p * y, torch.zeros_like(p)), dim=1)) + if ( + native_stats + and rows.dtype == x.dtype + and accumulate_bytes(rows, labels, accumulation, shift=shift) + ): + continue + # CuTe FP8 assignment retains these encoded rows for statistics; + # consume them on the ordered stream before another assignment. + if fp8_stats and accumulate_bytes( + codes, labels, accumulation, fp8_code_units=True + ): + continue + if operand is None: + if self._stats_operand is None: + with torch.inference_mode( + self._batch_stats.is_inference() + ): + self._stats_operand = self._centroids.new_ones( + ( + min(chunk_size, self.recipe["batch_size"]), + self.d + 1, + ), + dtype=( + torch.int32 if integer_stats else torch.float32 + ), + ) + operand = self._stats_operand.to(accumulation.dtype) + values = operand[: len(rows)] + direct_bf16 = ( + q is None + and index is not None + and type(x) is torch.Tensor + and type(values) is torch.Tensor + and rows.dtype is torch.bfloat16 + and values.dtype is torch.float32 + ) + represented = statistics_values(rows, codes, q, code_units=code_units) + values[:, :-1].copy_( + represented + if integer_stats or code_units or direct_bf16 + else represented.float() + ) + if accumulation.dtype == torch.int32 and shift: + values[:, :-1].sub_(128) + accumulation.index_add_(0, labels, values) + self._batch_objective, self._batch_operand = objective, operand + total_n = pending_n + n + if total_n == target and code_units: + sums.mul_(2.0**-q.exponent) + if ( + total_n == target + and integer_stats + and (not wide) + and (not borrowed) + ): + from .triton_assignment import copy_byte_stats + + copy_byte_stats(accumulation, self._batch_stats, unsigned=shift) + sums, counts = self._batch_stats[:, :-1], self._batch_stats[:, -1] + elif ( + total_n == target + and not borrowed + and accumulation is not self._batch_stats + ): + accumulation = self._complete_statistics(accumulation) + sums, counts = accumulation[:, :-1], accumulation[:, -1] + complete = total_n == target or total_n == 0 + stats = { + "sums": sums if complete else None, + "counts": counts if complete else None, + "objective": objective, + "n": total_n, + } + if self._removal_stats is not None: + stats["removal"] = self._batch_removal + if captured_labels is not None: + stats["labels"] = captured_labels + return stats + + def _epoch_totals(self): + + fp8 = self._input_dtype == getattr(torch, "float8_e4m3fn", None) + if fp8: + from .quantizer_fp8 import ( + _transform, + _update_fp8_peak, + _check_fp8_range, + ) + + if self._fp8_peak is None: + self._fp8_peak = self._centroids.new_zeros(()) + _update_fp8_peak( + _transform(self._centroids, self.quantizer), self._fp8_peak + ) + objective = self._epoch_objective() + report_counts = self._pass_counts.double() + totals = torch.stack( + (objective, torch.dot(report_counts, report_counts)) + + ((self._fp8_peak.double(),) if fp8 else ()) + ).tolist() + objective, count_square = totals[:2] + if fp8: + _check_fp8_range(totals[-1], "centroids") + return objective, count_square + + def _replay_representation_eligible(self): + if self.quantizer is not None: + from .quantizer import CastQuantizer + from .quantizer_fp8 import Fp8Quantizer + from .quantizer_int8 import Int8Quantizer + + if type(self.quantizer) not in ( + CastQuantizer, + Fp8Quantizer, + Int8Quantizer, + ): + return False + if any( + name in vars(self.quantizer) + for name in ("decode", "compute_codes") + ): + return False + if (_same_operation(self.quantizer.decode, CastQuantizer.decode, self.quantizer) + and not _same_operation(self.quantizer._matrix, CastQuantizer._matrix, self.quantizer)): + return False + return True + + def _use_code_units(self, n, target): + if not self._fp8_quantizer: + return False + from .quantizer_fp8 import Fp8Quantizer + + q = self.quantizer + return ( + n > 0 + and target <= _FLOAT32_COUNT_LIMIT + and type(q) is Fp8Quantizer + and q.dtype is torch.float8_e4m3fn + and q.shift is None + and -94 <= q.exponent <= 117 + and not any( + name in vars(q) for name in ("decode", "compute_codes") + ) + and not torch.are_deterministic_algorithms_enabled() + ) + + def _prepare_input(self, x): + self._check_cast_fit() + if self._centered_cast: + self.quantizer._matrix(x) + self._resolve_input_dtype(x) + self._resolve_assignment_backend(x) + if self._input_dtype in (torch.int8, torch.uint8) and self.d > 43919: + raise ValueError("INT8 assignment requires d <= 43919") + if self.recipe is not None: + self.recipe.update( + representation=str(self._input_dtype).removeprefix("torch."), + assignment_backend=self._assignment_backend, + assignment_backend_requested=self.assignment_backend, + assignment_chunk_size=self._get_assignment_chunk_size(), + ) + return x + + def _prepare_rows(self, rows, *, new_run=False): + rows = rows.detach() + if self._centered_cast: + if not new_run: + self._check_cast_fit() + self.quantizer._matrix(rows) + if self._int8_quantizer: + return rows.contiguous() + if ( + self._assignment_backend == "cute" + and self._fp8_quantizer + and rows.dtype in (torch.float32, torch.float16, torch.bfloat16) + ): + return rows.float().contiguous() + if self.quantizer is None: + return (rows.float() if rows.device.type == "cpu" else rows).contiguous() + if rows.dtype == self.quantizer.dtype: + return rows.contiguous() + return self.quantizer.compute_codes(rows) + + def _prepare_torch_assignment(self, centroids): + self._check_cast_fit() + if self.spherical and centroids is self._centroids: + centroids = self._readout() + if self._assignment_backend == "cute": + dtype = self._input_dtype or torch.bfloat16 + if dtype is torch.float8_e4m3fn and self._fp8_peak is None: + self._fp8_peak = centroids.new_zeros(()) + return self._execution_backend.prepare_centroids( + centroids, + transform=( + self.quantizer + if self._fp8_quantizer or self._int8_quantizer or self._centered_cast + else None + ), + peak_out=self._fp8_peak, + dtype=dtype, + spherical=self.spherical, + ) + dtype = self._input_dtype or torch.float32 + if dtype in (torch.int8, torch.uint8): + from .quantizer import _transform + from .quantizer_int8 import representation + + _, prepare = _get_triton_int8_functions() + value = _transform( + centroids, self.quantizer if self._int8_quantizer else None + ) + return prepare(value, representation(dtype), validate=False) + if dtype == getattr(torch, "float8_e4m3fn", None): + from .quantizer_fp8 import ( + Fp8Quantizer, + _check_fp8_support, + _transform, + _update_fp8_peak, + ) + + _check_fp8_support(centroids.device) + if self._fp8_peak is None: + self._fp8_peak = centroids.new_zeros(()) + if self._assignment_backend == "triton" and ( + self.quantizer is None or type(self.quantizer) is Fp8Quantizer + ): + from .triton_assignment import _cast_fp8_centroids + + prepared = _cast_fp8_centroids( + centroids, self.quantizer, self._fp8_peak + ) + if prepared is not None: + return prepared + transformed = _transform(centroids, self.quantizer) + _update_fp8_peak(transformed, self._fp8_peak) + represented = transformed.to(dtype) + if self.d % 64: + from .triton_assignment import _pad_columns + + represented = _pad_columns(represented, 64) + else: + represented = ( + self.quantizer.compute_codes(centroids) + if self._centered_cast else centroids.to(dtype) + ) + norm = ( + centroids.new_zeros(len(centroids)) + if self.spherical + else represented[:, : self.d].float().square().sum(dim=1) + ) + if self._assignment_backend == "triton" and dtype is torch.float32: + represented = represented.t().contiguous().t() + if ( + self._assignment_backend == "triton" + and dtype in (torch.bfloat16, torch.float16) + and self.d % 16 + ): + from .triton_assignment import _pad_columns + + represented = _pad_columns(represented, 16) + return represented, norm + + def _select_statistics_dtype(self, dtype): + # Input or external statistics select the run schema. + + if dtype == self._batch_stats.dtype: + return + if 255 * self._n > 2**53: + raise ValueError( + "integer statistics require global 255*n <= 2**53" + ) + try: + with torch.inference_mode(self._batch_stats.is_inference()): + self._batch_stats = self._batch_stats.new_empty( + self._batch_stats.shape, dtype=dtype + ) + self._pass_counts = self._pass_counts.to(dtype) + if self._pass_sums is not None: + self._pass_sums = self._pass_sums.to(dtype) + self._stats_operand = None + except BaseException: + self._failed = True + raise diff --git a/thirdparty/faiss/contrib/e_means/e_means_spherical.py b/thirdparty/faiss/contrib/e_means/e_means_spherical.py new file mode 100644 index 000000000..baad04300 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means_spherical.py @@ -0,0 +1,43 @@ +# 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. + +"""Bounded, zero-preserving centroid projection; no input preprocessing.""" + + +def normalize_into(source, out): + """Project finite rows, prescaling before the norm and before narrowing. + + Each temporary row matrix is bounded to 32 MiB (one row if wider). + Zero maps to zero. The source can alias the destination. + """ + is_torch = hasattr(source, "element_size") + itemsize = source.element_size() if is_torch else source.itemsize + rows = max(1, (1 << 25) // (source.shape[1] * itemsize)) + if is_torch: + import torch + + for begin in range(0, len(source), rows): + values, target = source[begin:begin + rows], out[begin:begin + rows] + work = target if values.dtype == target.dtype else torch.empty_like(values) + maximum = torch.linalg.vector_norm(values, ord=float("inf"), dim=1, keepdim=True) + work.copy_(values) + work.div_(torch.where(maximum > 0, maximum, 1)) + norm = torch.linalg.vector_norm(work, dim=1, keepdim=True) + work.div_(torch.where(norm > 0, norm, 1)) + if work is not target: + target.copy_(work) + else: + import numpy as np + + for begin in range(0, len(source), rows): + values, target = source[begin:begin + rows], out[begin:begin + rows] + work = target if values.dtype == target.dtype else np.empty_like(values) + maximum = np.max(np.abs(values), axis=1, keepdims=True) + np.divide(values, np.where(maximum > 0, maximum, 1), out=work) + norm = np.sqrt(np.einsum("ij,ij->i", work, work))[:, None] + np.divide(work, np.where(norm > 0, norm, 1), out=work) + if work is not target: + np.copyto(target, work, casting="unsafe") + return out diff --git a/thirdparty/faiss/contrib/e_means/e_means_torch.py b/thirdparty/faiss/contrib/e_means/e_means_torch.py new file mode 100644 index 000000000..c99d4649d --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/e_means_torch.py @@ -0,0 +1,1673 @@ +# 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. + +"""Floating PyTorch E-means on CPU and CUDA.""" + +import time + +import torch + +from .torch_backend import ( + TorchBackend, + TritonBackend, + CuteBackend, + select_backend, + default_chunk_size, + _separate_splits, + _require_score_operands, +) + +from .base import ( + _FLOAT32_COUNT_LIMIT, + _EmeansBase, + _INIT_USAGE, + _REMOVAL_THRESHOLD, + _SPLIT_GAIN, + _epoch_rows, + _epoch_seed, + _resolve_recipe, + _resolve_unused_threshold, + _round_power_of_two as _round_power_of_two, + _scheduled_alpha, + _same_operation, + _twin_reassign, +) + + +# Rows per step of the closing-pass scan, bounding its temporaries. +_HANDOVER_CHUNK = 1 << 22 +# Up to this many steps before the closing pass, the training graph records +# second labels from its first capture: cheaper than re-capturing it when the +# closing pass starts (about 1.6 ms on DINO 1M) for a few labelled steps. 32 +# covers a whole 1M-row epoch at the paper's batch (31 steps), where this is +# 1-17% faster at 1.6-1.8 epochs; at 10M (61+ steps) it is neutral or slower. +_EARLY_LABEL_STEPS = 32 + +__all__ = [ + "Emeans", + "_separate_splits", + "_epoch_rows", + "_epoch_seed", + "_resolve_recipe", + "_round_power_of_two", + "_scheduled_alpha", +] + + +def _torch_generator(device, seed): + generator = torch.Generator(device=device) + generator.manual_seed(seed) + return generator + + +def _synchronize(device): + if device.type == "cuda": + + torch.cuda.synchronize(device) + + +def _accumulate_removal_rows(model, values, labels, margin): + """The shared decoded-row Oja/removal contribution, in model FP32 units.""" + y = values.float() - model._readout()[labels] + p = (y * model._axes[labels]).sum(1, keepdim=True) + model._batch_removal.index_add_(0, labels, torch.cat( + (p * y, margin.nan_to_num(0, 0)[:, None]), dim=1)) + + +def _compact_label_dtype(k): + """Smallest signed integer type holding labels 0..k-1 and -1.""" + return torch.int8 if k <= 127 else torch.int16 if k <= 32767 else torch.int32 + + +def _closing_centroid_values(sums, counts, current): + """FP32 closing values, with immutable inputs and bounded promotion scratch.""" + dtype = torch.float64 if sums.dtype in (torch.int64, torch.float64) else torch.float32 + result = torch.empty_like(current, dtype=torch.float32, memory_format=torch.contiguous_format) + row_bytes = 32 # Clamp/cast/mask vectors, including the preceding block's last vector. + if sums.device.type == "cpu": + # CPU TensorIterator materializes common-dtype output and promoted inputs. + row_bytes += (8 * sums.shape[1]) if dtype == torch.float64 else 0 + if sums.dtype != dtype: + row_bytes += (8 if dtype == torch.float64 else 4) * sums.shape[1] + block_rows = max(1, (32 << 20) // row_bytes) + for begin in range(0, len(counts), block_rows): + end = min(begin + block_rows, len(counts)) + count = counts[begin:end] + output = result[begin:end] + # The divisor selects the original common compute dtype; out only casts the result. + torch.div(sums[begin:end], count.clamp_min(1).to(dtype)[:, None], out=output) + torch.where((count > 0)[:, None], output, current[begin:end], out=output) + return result + + +class Emeans(_EmeansBase): + """Floating tensors: CPU FP32 computation or CUDA FP32/FP16/BF16 operands. + + Implements Algorithm 1 of "E-Means: Scaling Laws for Mini-Batch K-Means": + https://arxiv.org/abs/2611.09501 + + ``nepochs`` is the epoch budget T and ``batch_size`` is B. ``alpha0`` is + the initial EMA step, alpha = 1 - gamma, annealed with the cosine schedule + of Equation 5. The batch law named by ``batch_law`` (``"throughput"``, or + ``"quality"`` for a batch about 8 times smaller) chooses B, and the step law + then sets alpha0 for that B. The default ``"auto"`` uses the quality law + when d <= 16 and the throughput law otherwise. A ``batch_size`` given + alone keeps the step law, and giving ``alpha0`` too sets both. + ``recipe["batch_law"]`` and ``recipe["batch_law_reason"]`` record the + resolved law. + + Each object represents one run. Call ``train`` or ``begin`` once; + create a fresh object for another run or after execution failure. + + ``train`` samples initial centroids by default and shuffles each epoch + (lines 1-4). For caller-driven training, ``begin`` initializes the state, + ``accumulate`` assigns rows and collects batch counts n_j and sums s_j + (lines 6-7), and ``update`` applies the EMA (line 8). ``_usage`` stores + masses N_j and ``_centroids`` stores positions c_j = S_j / N_j, an + algebraically equivalent form of the sum-and-count updates. Every five + updates, the default ``unused_threshold=None`` moves centroids whose + removal cost (EMA of d2 - d1 over their rows) is zero or below 0.3 times + the median to split the donors with the longest axes, until the end of + training. A split puts the two copies at c_j -/+ s_j u_j along the + donor's axis u_j, s_j = sqrt(2 ||U_j|| / (pi N_j)): the half-means of a + Gaussian along u_j. With ``closing_handover`` (default) and captured + assignments, ``train`` assigns again the last-pass rows such a revived + centroid held before moving, like a training batch, at their share of one + epoch's cost, or hands them to their second-nearest centroid when the + backend returns it (see ``NumpyEmeans``). A donor's other rows from before + its first split after them then go to the nearer of that split's two + centroids (FP64, ties to the lower index; not to a child moved again). + Every centroid returns the mean of its last-pass rows (without captured + labels, of those assigned to it after its last split). A value revives + clusters below that + fraction of the mean mass instead, splitting mass-sampled donors (line 9, + Appendix J); 0 disables revival. + + ``finalize`` computes unweighted means from assignments collected while + the centroids move during the last epoch (line 12). Unassigned centroids + retain their positions. ``train`` returns centroids and captured assignments. + For Euclidean clustering, ``obj`` reports moving-pass sums of squared + distances; use ``assign`` to evaluate the final centroids. + + Implementation details: the initial mass is 2**-16 (the paper uses 1e-10), + remainder batches are retained, and fractional epoch budgets are supported. + ``spherical=True`` extends the algorithm to projected centroid directions. + + ``max_points_per_centroid`` caps the training set as in ``faiss.Kmeans``: + when the input has more than ``max_points_per_centroid * k`` rows, + ``train`` uses a random subset of that many rows (drawn from ``seed``) and + returns label -1 for the other rows. The default None trains on all rows. + + Model coordinates and results are FP32. CUDA FP32 input defaults to BF16 + assignment and rounded-row statistics; CPU and native FP16/BF16 stay native. + The first typed input, including empty input, selects the representation, + not initial centroids. Use QuantizedEmeans(quantizer=None) for native CUDA + FP32; explicit quantizers and encoded formats belong to QuantizedEmeans. + """ + + _backend = "torch" + _automatic = True + + def __init__( + self, + d, + k, + nepochs=5, + batch_size=None, + alpha0=None, + batch_law="auto", + seed=1234, + verbose=False, + assignment_chunk_size=None, + centroid_chunk_size=4096, + *, + assignment_backend="auto", + capture_assignments=True, + spherical=False, + unused_threshold=None, + max_points_per_centroid=None, + closing_handover=True, + ): + self.d = int(d) + self.k = int(k) + self._set_max_points_per_centroid(max_points_per_centroid) + self.closing_handover = bool(closing_handover) + nepochs = float(nepochs) + self.nepochs = int(nepochs) if nepochs.is_integer() else nepochs + self.batch_size = batch_size + self.alpha0 = alpha0 + self.batch_law = batch_law + self.unused_threshold = unused_threshold + self._unused_threshold = _resolve_unused_threshold( + unused_threshold, self.d + ) + self.seed = int(seed) + self.verbose = bool(verbose) + self.assignment_chunk_size = ( + None + if assignment_chunk_size is None + else int(assignment_chunk_size) + ) + self.centroid_chunk_size = int(centroid_chunk_size) + self.capture_assignments = bool(capture_assignments) + self.spherical = bool(spherical) + self.assignment_backend = assignment_backend + + self.centroids = None + self.assignments = None + self.obj = None + self.iteration_stats = None + self.recipe = None + self.n_splits = 0 + self._usage = None + self._centroids = None + self._removal_stats = self._axes = None + # Closing-pass reassignment of rows held by revived centroids (train() only). + self._handover = None + self._early_labels = False + self.closing_handover_stats = None + self._axis_norms = None + self._check_graph = self._check_pool = self._check_async = self._check_splits = None + self._pending_stats = None + self._removal_folded = False + self._failed = False + self._batch_accumulation = self._batch_objective = None + self._batch_norm = None + self._batch_centroids = None + self._batch_stats = None + self._pass_counts = self._pass_sums = self._objective = None + self._split_rng = None + self._input_dtype = None + self._cast_dtype = None + self._resolved_assignment_backend = None + self.assignment_recipe = None + # A caller may begin before its first typed input. Native state setup + # requires no GPU software; the actual operation resolves on that input. + self._execution_backend = TorchBackend(self.centroid_chunk_size) + self._query_backend = None + self._unit_centroids = self._unit_version = None + self._unit_generation = 0 + + def _finish_step(self, expected_n): + super()._finish_step(expected_n) + self._batch_norm = None + + def _readout(self, force=False): + """Return effective FP32 centroids for assignment and inspection. + + "Readout" means converting the internal EMA positions into the + coordinates used by assignment and ``current_centroids``. Euclidean + clustering uses the stored positions directly. Spherical clustering + uses their unit directions, keeping the EMA positions unchanged; + zero vectors remain zero. + + Directions are cached using model updates and Torch's tensor version. + ``force=True`` recomputes them even when the cache appears current, + so CUDA graph capture records normalization for every replay. The + returned tensor borrows model storage; clone it for a snapshot. + """ + if not self.spherical: + return self._centroids + from .e_means_spherical import normalize_into + + version = None + try: + version = self._centroids._version + except ( + RuntimeError + ): # Inference tensors use explicit mutation generation. + pass + token = (self._unit_generation, version) + if self._unit_centroids is None: + self._unit_centroids = self._centroids.new_empty( + self._centroids.shape + ) + if force or self._unit_version != token: + normalize_into(self._centroids, self._unit_centroids) + self._unit_version = token + return self._unit_centroids + + def current_centroids(self): + """Borrow the active FP32 model coordinates without copying data. + + Available after begin, including completed epochs, until finalize. + Returns a detached alias on the model device. It is not immutable + or safe for concurrent mutation. + Do not write through the result. Finish readers before update, + end_epoch or finalize, then reacquire. Old handles are not valid + current-state reads after finalize. + Copy/clone explicitly for an independent snapshot. CUDA callers must + order producer, reader and subsequent mutation streams themselves; + this method adds no synchronization or collective. These are FP32 + model coordinates, not rounded or encoded assignment operands. In + spherical mode they are effective unit directions (zero stays zero), + borrowed from one reusable FP32 cache with the same read window. + """ + if self._failed: + raise RuntimeError("create a new object after execution failure") + centroids = self._readout() + return centroids.detach() + + def _get_assignment_chunk_size(self): + if self.assignment_chunk_size is not None: + return self.assignment_chunk_size + state = ( + self._centroids if self._centroids is not None else self.centroids + ) + return self._execution_backend.chunk_size(state) + + @property + def _assignment_backend(self): + return self._execution_backend.name + + def _resolve_assignment_backend(self, x): + if self._resolved_assignment_backend is not None: + return + try: + cls = select_backend(x, self._input_dtype or x.dtype, self.k, self.d, self.assignment_backend) + if not (isinstance(self._execution_backend, cls) and self._execution_backend.name == cls.name): + query = self._query_backend + self._execution_backend = ( + query.fork_query() if isinstance(query, cls) and query.name == cls.name + else cls(self.centroid_chunk_size)) + # Prediction requires assignment, not update/revival software. + self._execution_backend.require_assignment(x.device) + except BaseException: + if self.recipe is not None: + self._failed = True + self.assignments = None + raise + self._resolved_assignment_backend = cls.name + + def _bind_input_dtype(self, dtype, *, cast=False): + self._input_dtype = dtype + self._cast_dtype = dtype if cast else None + + def _resolve_input_dtype(self, x): + if self._input_dtype is None: + dtype = torch.float32 if x.device.type == "cpu" else x.dtype + cast = self._automatic and x.device.type == "cuda" and x.dtype == torch.float32 + if cast: + dtype = torch.bfloat16 + self._bind_input_dtype(dtype, cast=cast) + + def _prepare_input(self, x): + self._resolve_input_dtype(x) + self._resolve_assignment_backend(x) + if self.recipe is not None: + self.recipe.update( + representation=str(self._input_dtype).removeprefix("torch."), + assignment_backend=self._assignment_backend, + assignment_backend_requested=self.assignment_backend, + assignment_chunk_size=self._get_assignment_chunk_size(), + ) + return x + + def _prepare_rows(self, rows): + rows = rows.detach() + if rows.device.type == "cpu": + rows = rows.float() + elif self._cast_dtype is not None and rows.dtype in (torch.float16, torch.float32): + rows = rows.to(self._cast_dtype) + return rows.contiguous() + + def _initial_centroid_values(self, rows): + return self._prepare_rows(rows).float() + + def _prepare_assignment_query(self, centroids): + return self._prepare_torch_assignment(centroids) + + def _prepare_torch_assignment(self, centroids): + if self.spherical and centroids is self._centroids: + centroids = self._readout() + return self._execution_backend.prepare_centroids( + centroids, self._input_dtype, self.spherical + ) + + def _select_statistics_dtype(self, dtype): + pass + + def _choose_splits(self, rng): + if self._unused_threshold is None: + if self._device_choice_eligible(): + victims, chosen, moves = self._removal_pairs() + n = int(moves) + return (chosen[:n], victims[:n]) if n else (None, None) + stats = self._removal_stats + source, target = self._choose_removal_splits(*torch.stack(( + stats[:, -1].double(), self._usage.double(), + torch.linalg.vector_norm(stats[:, :-1], dim=1, dtype=torch.float64))).cpu().numpy()) + return (None, None) if source is None else tuple( + torch.from_numpy(ids).to(self._usage.device) for ids in (source, target)) + # Sample donors without replacement in proportion to their usage. + + threshold = self._usage.sum() * self._unused_threshold / self.k + unused = self._usage < threshold + donors = (~unused) & (self._usage > 0) + nunused, ndonors = torch.stack((unused.sum(), donors.sum())).tolist() + nsplit = min(nunused, ndonors) + if nsplit == 0: + return None, None + + uniform = torch.rand( + self.k, + dtype=self._usage.dtype, + device=self._usage.device, + generator=rng, + ).clamp_min(torch.finfo(self._usage.dtype).tiny) + if self._usage.is_cuda: + # Fixed shapes avoid compaction's host reads. + keys = torch.where( + donors, + self._usage.log() - (-uniform.log()).log(), + float("-inf"), + ) + source = torch.topk(keys, nsplit).indices + target = torch.sort( + unused.byte(), descending=True, stable=True + ).indices[:nsplit] + else: + keys = torch.full_like(self._usage, float("-inf")) + keys[donors] = ( + self._usage[donors].log() - (-uniform[donors].log()).log() + ) + source = torch.topk(keys, nsplit).indices + target = unused.nonzero(as_tuple=False).flatten()[:nsplit] + + return source, target + + def _revive_unused(self, rng): + # The local fused check belongs at the apply boundary. Coordinators + # may call the same chooser without mutating their replica first. + if (self._unused_threshold is None + and _same_operation(self._choose_splits, Emeans._choose_splits, self) + and self._device_check()): + if self._handover is not None: + self._handover["done"].fill_(self._handover["rows"]) + self._removal_check_graph() + victims, chosen, moves = self._check_pairs + if self._pass_sums is not None and self._handover is None: + live = torch.arange(len(victims), device=moves.device) < moves + hit = torch.zeros(self.k + 1, dtype=torch.bool, device=moves.device) + hit[torch.where(live, victims, self.k)] = hit[torch.where(live, chosen, self.k)] = True + self._pass_sums.masked_fill_(hit[:-1, None], 0) + self._pass_counts.masked_fill_(hit[:-1], 0) + if self._handover is not None: + self._handover["events"].append( + (victims.clone(), chosen.clone(), moves.clone(), self._handover["rows"])) + return 0 # Device counter owns these splits, as before. + return super()._revive_unused(rng) + + @property + def n_splits(self): + """Splits so far; device-side splits are read (synchronizing) on access.""" + return self._n_splits + (0 if self._check_splits is None else int(self._check_splits)) + + @n_splits.setter + def n_splits(self, value): + self._n_splits = value + if getattr(self, "_check_splits", None) is not None: + self._check_splits.zero_() + + def _device_split_eligible(self): + return (_same_operation(self._apply_splits, Emeans._apply_splits, self) + and _same_operation(self._split_removal_statistics, Emeans._split_removal_statistics, self) + and _same_operation(self._split_removal_stats, Emeans._split_removal_stats, self)) + + def _device_check(self): + """Pair and split on the device when the Triton split kernels apply.""" + backend = self._execution_backend + return (self._device_choice_eligible() and self._device_split_eligible() + and _same_operation(backend.split, TritonBackend.split, backend) + and _same_operation(backend.removal_split, TritonBackend.removal_split, backend)) + + def _device_choice_eligible(self): + """The existing device selector, independently of application hooks.""" + if self._check_async is None: + self._check_async = ( + self._usage.is_cuda + and self._input_dtype in (None, torch.float32, torch.bfloat16) and self.d <= 8192) + backend = self._execution_backend + return (self._check_async and isinstance(backend, TritonBackend) + and _same_operation(self._choose_removal_splits, _EmeansBase._choose_removal_splits, self) + and _same_operation(self._choose_removal_donors, _EmeansBase._choose_removal_donors, self)) + + def _removal_pairs(self, splits=None): + """Return device pair buffers/count; an optional fused sink counts moves.""" + + stats = self._removal_stats + removal, ids = stats[:, -1].sort(stable=True) + candidate = self._removal_candidates_device(removal.double()) + # Candidates by (R, index) first, then the rest; position = slot, or count if not one. + count = candidate.sum() + slot = torch.where(candidate, candidate.cumsum(0) - 1, count + (~candidate).cumsum(0) - 1) + order = torch.empty_like(ids).scatter_(0, slot, ids) + position = torch.empty_like(ids).scatter_(0, ids, torch.where(candidate, slot, count)) + # Pair candidates in that order with donors by (-|U|, index). + victims = order + donor = (self._usage > 0) & (position == count) + norm = torch.linalg.vector_norm(stats[:, :-1], dim=1, dtype=torch.float64) + # Norm keys are <= 0; NaN donors follow them, before ineligible +inf. + norm_key = norm.float() + gain = -norm_key + gain = torch.where(gain.isnan(), 1.0, gain) + chosen = torch.where(donor, gain, float("inf")).sort(stable=True).indices + # Admit the same ordered prefix as the host, before counting/applying. + cost = stats[victims, -1].double() + pays = (cost <= 0) | (_SPLIT_GAIN * norm_key[chosen].double() > cost) + pays &= torch.arange(len(victims), device=victims.device) < torch.minimum(count, donor.sum()) + moves = pays.long().cumprod(0).sum() + if splits is not None: + splits.add_(moves) + return victims, chosen, moves + + def _removal_check(self): + """Local choice and application, with the existing fused graph schedule.""" + from .triton_assignment import _write_float_splits, removal_split + + victims, chosen, moves = self._removal_pairs(self._check_splits) + _write_float_splits(self._centroids, self._usage, chosen, victims, self._input_dtype, + *self._split_axes(), count=moves) + removal_split(self._removal_stats, self._axes, chosen, victims, count=moves) + self._check_pairs = victims, chosen, moves + if self._handover is not None: + h = self._handover + valid = torch.arange(len(victims), device=victims.device) < moves + h["moved_at"].scatter_reduce_(0, torch.where(valid, victims, 0), + torch.where(valid, h["done"], -1), "amax") + + def _removal_candidates_device(self, removal): + median = (removal[(self.k - 1) // 2] + removal[self.k // 2]) / 2 + return (removal <= 0) | (removal < _REMOVAL_THRESHOLD * torch.where(removal[-1].isnan(), float("nan"), median)) + + def _removal_check_graph(self): + """Run ``_removal_check`` as one CUDA graph per check.""" + if self._check_graph is None: + device = self._usage.device + self._check_splits = torch.zeros((), dtype=torch.int64, device=device) + self._removal_check() # Also compiles the kernels before capture. + pairs = self._check_pairs # This check's pairs; the capture's are its replays'. + current, stream = torch.cuda.current_stream(device), torch.cuda.Stream(device) + graph, self._check_pool = torch.cuda.CUDAGraph(), torch.cuda.MemPool() # Freed at finalize. + stream.wait_stream(current) + try: + with torch.cuda.stream(stream): + graph.capture_begin(pool=self._check_pool.id, capture_error_mode="thread_local") + try: + self._removal_check() + finally: + graph.capture_end() + self._check_graph, self._graph_pairs = graph, self._check_pairs + except RuntimeError: + self._check_graph = False # Not capturable here: replay eagerly. + current.wait_stream(stream) + self._check_pairs = pairs + elif self._check_graph: + self._check_graph.replay() + self._check_pairs = self._graph_pairs + else: + self._removal_check() + self._invalidate_readout() + return None, None + + def _apply_splits(self, source, target): + self._execution_backend.split( + self._centroids, + self._usage, + source, + target, + self._input_dtype, + *self._split_axes(), + ) + return self._finish_splits(source, target) + + def _finish_splits(self, source, target): + """Commit statistics and closing records after a successful host split.""" + self._split_removal_statistics(source, target) + if self._handover is not None: + h = self._handover + h["moved_at"][torch.as_tensor(target, device=h["done"].device)] = h["rows"] + h["events"].append((target, source, None, h["rows"])) + self._n_splits += len(source) + self._invalidate_readout() + return len(source) + + def _split_removal_statistics(self, source, target): + self._split_removal_stats(source, target) + + def _split_removal_stats(self, source, target): + """The donor halves [U | R]; the moved centroid copies it and the axis. + With cost-based revival in the last pass and no handover (which rebuilds + them), neither keeps closing sums from before the split.""" + if self._pass_sums is not None and self._unused_threshold is None and self._handover is None: + for v in (self._pass_sums, self._pass_counts): + v[source] = v[target] = 0 + if self._removal_stats is not None and not ( + isinstance(self._execution_backend, TritonBackend) and self._execution_backend.removal_split( + self._removal_stats, self._axes, source, target, None)): + self._removal_stats[source] /= 2 + self._removal_stats[target] = self._removal_stats[source] + self._axes[target] = self._axes[source] + + def _split_axes(self): + """Axes and FP64 ||U|| for the Gaussian split; (None, None) without removal statistics.""" + if self._removal_stats is None: + return None, None + return self._axes, torch.linalg.vector_norm(self._removal_stats[:, :-1], dim=1, dtype=torch.float64) + + def _handover_start(self, labels, x, second=False): + """Set up the closing pass's reassignment before training starts, so + the device revival check records into it from its first capture. + ``labels`` (n,) holds the captured assignments. With ``second``, each + closing-pass row assigned while centroids can move also keeps its + second-nearest index from the same assignment, in the smallest + integer type that holds k (-1 if unknown). A revival only records, + per revived centroid, how many closing-pass rows were assigned when it + moved (``moved_at``, O(k)); records from earlier passes are cleared when + the closing pass starts, and the rows are sorted out once, at the end. + Closing-pass rows are counted on the host (``rows``) and copied to the + device (``done``) only when the device check runs.""" + device = labels.device + self._handover = dict( + labels=labels, x=x, + second=(torch.full((len(labels),), -1, dtype=_compact_label_dtype(self.k), device=device) + if second else None), + moved_at=torch.full((self.k,), -1, dtype=torch.int64, device=device), + done=torch.zeros((), dtype=torch.int64, device=device), rows=0, events=[]) + + def _handover_finish(self, order, rows): + """One pass over the ``rows`` closing-pass rows in visiting ``order`` + finds those assigned before their centroid moved. Each takes its + second-nearest from the same assignment unless that one moved after + the row's assignment too (or is unknown); the rest are assigned again + like a training batch (same backend and row count, nearest only, + against the current centroids), so this costs their share of one + epoch, in whole chunks. ``_close_split_centroids`` then rebuilds the + closing sums.""" + h, self._handover = self._handover, None + labels, x, moved_at, second = h["labels"], h["x"], h["moved_at"], h["second"] + if not bool((moved_at >= 0).any()): # O(k): nothing moved in this pass. + self.closing_handover_stats = dict(searched=0, **({} if second is None else {"second": 0})) + return + moved, searched = [], [] + for begin in range(0, rows, _HANDOVER_CHUNK): + index = order[begin:min(begin + _HANDOVER_CHUNK, rows)] + rank = torch.arange(begin, begin + len(index), device=index.device) + stale = (rank < moved_at[labels[index]]).nonzero()[:, 0] # one compaction + index, rank = index[stale], rank[stale] + if second is None: + searched.append(index) + continue + nearest2 = second[index].long() + usable = (nearest2 >= 0) & (moved_at[nearest2.clamp_min(0)] <= rank) + labels[index] = torch.where(usable, nearest2, labels[index]) + moved.append(index) + searched.append(index[~usable]) + search = torch.cat(searched) if searched else order[:0] + handed = torch.cat(moved) if moved else order[:0] # rows handed over and searched + if len(search): + centroids, centroid_norm = self._prepare_torch_assignment(self._centroids) + rows_per_chunk = min(self.recipe["assignment_chunk_size"], self.recipe["batch_size"]) + for begin in range(0, len(search), rows_per_chunk): + chunk = search[begin:begin + rows_per_chunk] + # Pad to a power of two, not to a whole training chunk: at most two call shapes. + width = min(rows_per_chunk, max(1024, 1 << (len(chunk) - 1).bit_length())) + padded = torch.cat((chunk, chunk[-1:].expand(width - len(chunk)))) + # Nearest only: second outputs cost extra launches (several on CuTe grouped) + # that an eager call, unlike graph replay, pays in full. + _, nearest = self._assign_rows(self._prepare_rows(x[padded]), centroids, centroid_norm) + labels[chunk] = nearest[:len(chunk)] + if second is None: + handed = search + self._close_split_centroids(order, rows, labels, x, moved_at, h["events"], handed) + self.closing_handover_stats = dict(searched=len(search), + **({} if second is None else {"second": len(handed) - len(search)})) + + def _close_split_centroids(self, order, rows, labels, x, moved_at, events, stale_rows): + """Twin reassignment of the rows the stale rule left (class docstring), then + closing sums rebuilt from the final rows for both ends of every split of + the pass and the centroids the stale rows joined. On CUDA: one Triton + launch per chunk and step, fixed-order sums, no host synchronization.""" + device, k, span = labels.device, self.k, rows + 1 + pieces = [torch.tensor([[0], [k], [0]], device=device)] # Unused entries get the donor k, which no row has. + for target, source, count, birth in events: + target, source = (torch.as_tensor(v, device=device).long() for v in (target, source)) + keep = torch.arange(len(target), device=device) < (len(target) if count is None else count) + pieces.append(torch.stack((torch.where(keep, target, 0), torch.where(keep, source, k), + torch.full_like(target, birth)))) + target, source, born = torch.cat(pieces, dim=1) + key, by_donor = torch.sort(source * span + born, stable=True) + target, source, born = (v[by_donor].contiguous() for v in (target, source, born)) + centroids = self._readout().float().contiguous() # Spherical: unit directions. + stale = torch.zeros(len(labels), dtype=torch.int8, device=device) + stale[stale_rows] = 1 + rebuild = torch.zeros(k + 1, dtype=torch.bool, device=device) + rebuild[source] = rebuild[torch.where(source < k, target, k)] = True + rebuild = rebuild[:k] + rebuild[labels[stale_rows]] = True + self._pass_sums.masked_fill_(rebuild[:, None], 0) + self._pass_counts.masked_fill_(rebuild, 0) + x, cast, stage = self._closing_rows(x) + # Staging bounds gathered input, codes and decoded values. Direct + # kernel reads need no row copies and use the ordinary chunk cap. + closing_chunk = (_HANDOVER_CHUNK if stage is None else + min(_HANDOVER_CHUNK, max(1, (32 << 20) // (12 * self.d)))) + if device.type == "cpu": # The NumPy class's steps, on views of the same memory. + def values_at(index): + if stage is None: + return self._statistics_rows(self._prepare_rows(x[index])) + values, row_index = stage(x, index) + return values[row_index] + + order = order[:rows] + _twin_reassign(order.numpy(), labels.numpy(), lambda i: values_at(torch.from_numpy(i)).float().numpy(), + centroids.numpy(), moved_at.numpy(), key.numpy(), target.numpy(), source.numpy(), + born.numpy(), stale.numpy() != 0, span, closing_chunk) + index = order[rebuild[labels[order]]] + chunk = self.recipe["assignment_chunk_size"] + for begin in range(0, len(index), chunk): + part = index[begin:begin + chunk] + self._pass_sums.index_add_(0, labels[part], values_at(part).to(self._pass_sums.dtype)) + self._pass_counts.index_add_(0, labels[part], self._pass_counts.new_ones(len(part))) + return + from .triton_assignment import closing_sums, twin_route + + # Each donor's splits among the sorted keys: segment[L] : segment[L + 1]. + segment = torch.searchsorted(key, torch.arange(k + 1, device=device) * span) + step = max(1, (1 << 26) // self.d) + bounds = torch.arange(k + 1, device=device, dtype=torch.int32) + for begin in range(0, rows, closing_chunk): + index = order[begin:min(begin + closing_chunk, rows)] + values, row_index = (x, None) if stage is None else stage(x, index) + twin_route(values, index, labels, stale, key, segment, target, source, born, moved_at, centroids, + begin, span, cast, row_index=row_index) + # Rows of centroids not rebuilt sort last (key k). + group = torch.where(rebuild[labels[index]], labels[index], k).int().sort(stable=True) + storage_index = index if row_index is None else row_index + closing_sums(values, storage_index[group.indices].contiguous(), + torch.searchsorted(group.values, bounds).contiguous(), + self._pass_sums, self._pass_counts, step, cast) + + def _closing_rows(self, x): + """Rows, kernel cast and optional per-chunk staging operation.""" + cast = self._cast_dtype + return x, (cast if cast is not None and x.dtype != cast else None), None + + def _assign_rows( + self, + x, + centroids, + centroid_norm=None, + distance_out=None, + labels_out=None, + second_out=None, + second_labels_out=None, + *, + scores=False, + ): + """Assign floating rows; scores=True retains the pre-row-norm keys.""" + if scores: + _require_score_operands(x, centroids) + return self._execution_backend.assign( + x, + centroids, + centroid_norm, + self.spherical, + distance_out, + labels_out, + second_out, + **({} if second_labels_out is None else {"second_labels_out": second_labels_out}), + **({"scores": True} if scores else {}), + ) + + def begin(self, global_n, init_centroids): + """Initialize a run with caller-owned batches and explicit FP32 state. + + Call once on a fresh object. + ``init_centroids`` has shape (k, d); its device selects + execution. It is copied. Each epoch must supply the resolved batch + sizes for ``recipe["epoch_rows"][epoch]``, including the final + remainder, + then call :meth:`end_epoch`. + Loading, ordering, transfers and prefetch are the caller's + responsibility. + """ + if self._failed or self.recipe is not None: + raise RuntimeError("create a new object for another run or after failure") + n = int(global_n) + centroids = init_centroids.detach().float().contiguous() + self._failed = True + self._centroids = self._initial_centroid_state(centroids) + self._usage = centroids.new_full((self.k,), _INIT_USAGE) + self._batch_stats = centroids.new_empty((self.k, self.d + 1)) + self._split_rng = _torch_generator(centroids.device, self.seed) + self._resolve_removal_revival() + if self._keeps_removal_stats(): + self._initialize_removal_statistics() + self._resolve_run_recipe(n) + self.recipe.update( + assignment_backend=self._resolved_assignment_backend, + assignment_backend_requested=self.assignment_backend, + device=str(centroids.device), + centroid_chunk_size=self.centroid_chunk_size, + ) + self._execution_backend.clear_statistics() + if self.spherical: + self.recipe.update( + spherical=True, + assignment_score="represented_inner_product", + objective="sum(2-2*represented_inner_product)", + ) + self._n = n + self._step = self._epoch = 0 + self.iteration_stats = [] + self._start_epoch() + _synchronize(centroids.device) + self._start_time = time.perf_counter() + self._failed = False + self._header_due, self._quiet = True, False + + def _initial_centroid_state(self, centroids): + """Own canonical FP32 initial positions before derived-state hooks.""" + state = centroids.clone() + if self.spherical: + from .e_means_spherical import normalize_into + + normalize_into(state, state) + return state + + def _initialize_removal_statistics(self): + # EMAs [U | R] and batch sums [p y | d2 - d1]. + centroids = self._centroids + self._removal_stats = centroids.new_zeros((self.k, self.d + 1)) + self._batch_removal = torch.zeros_like(self._removal_stats) + self._axes = self._initial_removal_axes() + + def _initial_removal_axes(self): + axes = torch.randn(self.k, self.d, dtype=torch.float32, device=self._centroids.device, + generator=self._split_rng) + return axes / axes.norm(dim=1, keepdim=True) + + def _statistics_rows(self, rows): + return rows + + def _start_epoch(self): + self._epoch_steps = self._epoch_rows = 0 + self._splits_before = self.n_splits + + if self._pass_counts is None: + self._pass_counts = self._usage.new_zeros( + self.k, dtype=torch.float64 + ) + self._objective = self._usage.new_zeros((), dtype=torch.float64) + else: + self._pass_counts.zero_() + self._objective.zero_() + self._pass_sums = ( + self._centroids.new_zeros( + (self.k, self.d), dtype=self._batch_stats.dtype + ) + if self._epoch == len(self.recipe["epoch_rows"]) - 1 + else None + ) + + def accumulate(self, x): + """Accumulate one chunk against a fixed centroid snapshot. + + Shapes, device, representation and row counts must match the run. + Complete totals borrow workspace. Objective uses FP64; sums/counts + follow the implementation's statistics dtype. CUDA rows must fit + the representation. Preparation detaches and makes rows contiguous; + CPU rows are converted to FP32. No value validation is performed. + """ + self._require_running() + x = self._prepare_input(x) + return self._accumulate(x.detach()) + + def _second_labels_supported(self): + """Whether the execution backend returns second-nearest labels + (``second_labels``); other backends, and overridden assignment or + accumulation, keep the search-only handover.""" + return getattr(self._execution_backend, "second_labels", False) and all( + _same_operation(getattr(self, name), getattr(Emeans, name), self) + for name in ("_assign_rows", "_accumulate_core")) + + def _second_labels_wanted(self): + """Closing-pass rows need their second-nearest while centroids can move. + On small runs (``_early_labels``) every step asks for them, so that eager + steps and graph replays share one assignment variant; labels from before + the closing pass are not kept.""" + h = self._handover + return (h is not None and h["second"] is not None + and (self._early_labels or self._epoch == len(self.recipe["epoch_rows"]) - 1)) + + def _accumulate(self, x, index=None, labels_out=None): + # Indexed matrix training gathers only assignment chunks, never B*d. + n = len(x) if index is None else len(index) + if n == 0 and self._pending_stats is not None: + stats = dict(self._pending_stats) + if ( + self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + stats["labels"] = x.new_empty(0, dtype=torch.int64) + return stats + try: + stats = self._accumulate_core(x, index, labels_out=labels_out) + except BaseException: + self._failed = True + self.assignments = None + raise + self._pending_stats = stats + return stats + + def _accumulate_core(self, x, index=None, raw=False, labels_out=None, ema=None, + second_labels_out=None): + n = len(x) if index is None else len(index) + pending_n = ( + 0 if self._pending_stats is None else self._pending_stats["n"] + ) + target = self._local_batch_size() + if pending_n == 0: + self._batch_accumulation = ( + self._batch_stats.new_zeros( + self._batch_stats.shape, dtype=torch.float64 + ) + if n > 0 and self._logical_batch_size() > _FLOAT32_COUNT_LIMIT + else self._batch_stats.zero_() + ) + self._batch_objective = self._objective.new_zeros(()) + if self.spherical: + self._readout(force=raw) + self._batch_centroids, self._batch_norm = ( + self._prepare_torch_assignment(self._centroids) + if n + else (None, None) + ) + self._execution_backend.begin_batch( + self._batch_stats, + min( + self.recipe["assignment_chunk_size"], + self.recipe["batch_size"], + ), + ) + accumulation = self._batch_accumulation + objective, centroid_norm = self._batch_objective, self._batch_norm + centroids = self._batch_centroids + captured_labels = None if labels_out is None else labels_out[:n] + if ( + captured_labels is None + and self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + captured_labels = x.new_empty(n, dtype=torch.int64) + # Second-nearest labels for the closing handover, int32 per row. + second_labels = None + if second_labels_out is not None: + second_labels = second_labels_out[:n] + elif self._second_labels_wanted() and (captured_labels is not None or self._early_labels): + second_labels = x.new_empty(n, dtype=torch.int32) + chunk_size = self.recipe["assignment_chunk_size"] + for begin in range(0, n, chunk_size): + end = min(begin + chunk_size, n) + rows = x[begin:end] if index is None else x[index[begin:end]] + rows = self._prepare_rows(rows) + # Mass-based revival reads only U: no second-nearest search, and R stays 0. + track = self._removal_stats is not None + second = (rows.new_empty(len(rows), dtype=torch.float32) + if track and self._unused_threshold is None else None) + distance, labels = self._assign_rows( + rows, centroids, centroid_norm, None, None, second, + None if second is None or second_labels is None else second_labels[begin:end], + ) + if track and second is None: + second = distance + values = self._statistics_rows(rows) + # A training step whose batch is one chunk may apply the removal EMA here. + backend = self._execution_backend + fold = (ema is not None and isinstance(backend, TritonBackend) + and pending_n == 0 and n == target <= chunk_size + and _same_operation(self._update_removal_statistics, Emeans._update_removal_statistics, self) + and _same_operation(backend.removal_update, TritonBackend.removal_update, backend)) + fused = False + ordinary_accumulation = any(_same_operation(backend.accumulate, method, backend) + for method in (TorchBackend.accumulate, TritonBackend.accumulate)) + if second is not None and isinstance(backend, TritonBackend) and ordinary_accumulation: + builtin = any(_same_operation(backend.accumulate_removal, method, backend) for method in + (TritonBackend.accumulate_removal, CuteBackend.accumulate_removal)) + if builtin: + fused = backend.accumulate_removal( + rows, labels, accumulation, distance, second, self._axes, self._readout(), self._batch_removal, + **({"statistics_rows": values} if values is not rows else {}), + **({"ema": ema} if fold else {})) + else: + # Existing owners consume statistical rows positionally. + # Complete encoded assignment scores before that consumer. + if isinstance(backend, CuteBackend): + backend.complete_second(rows, labels, second) + fused = backend.accumulate_removal( + values, labels, accumulation, distance, second, self._axes, self._readout(), self._batch_removal) + elif second is not None and isinstance(backend, CuteBackend): + backend.complete_second(rows, labels, second) + self._removal_folded = fused == "folded" + if second is not None and not fused: + _accumulate_removal_rows(self, values, labels, second - distance) + if captured_labels is not None: + captured_labels[begin:end] = labels + if self.spherical: + objective += 2 * len(rows) + objective += distance.sum(dtype=torch.float64) + if not fused: + self._execution_backend.accumulate( + values, + labels, + accumulation, + self._logical_batch_size(), + indexed=index is not None and type(x) is torch.Tensor, + ) + self._batch_objective = objective + total_n = pending_n + n + if total_n == target and accumulation is not self._batch_stats: + accumulation = self._complete_statistics(accumulation) + complete = total_n == target or total_n == 0 + stats = { + "sums": accumulation[:, :-1] if complete else None, + "counts": accumulation[:, -1] if complete else None, + "objective": objective, + "n": total_n, + } + if self._removal_stats is not None: + stats["removal"] = self._batch_removal + if captured_labels is not None: + stats["labels"] = captured_labels + if second_labels is not None: + stats["second_labels"] = second_labels + return stats + + def _prepare_statistics(self, stats, expected_n): + schema = stats["stat_schema"] if "stat_schema" in stats else stats["sums"].dtype + if "stat_schema" in stats: + if not isinstance(schema, torch.dtype) or schema not in (torch.float32, torch.float64): + raise ValueError("stat_schema must be torch.float32 or torch.float64") + if (not isinstance(stats["sums"], torch.Tensor) + or stats["sums"].dtype not in (torch.float32, torch.float64) + or not isinstance(stats["counts"], torch.Tensor) + or stats["counts"].dtype not in (torch.float32, torch.float64, torch.int64)): + raise ValueError("stat_schema requires floating sums and floating or exact INT64 counts") + if stats["counts"].dtype == torch.int64 and self._logical_batch_size() > 2**53: + raise ValueError("stat_schema INT64 counts require logical batch <= 2**53") + sums, counts, objective = ( + stats["sums"].detach(), + stats["counts"].detach(), + stats["objective"].detach(), + ) + self._select_statistics_dtype(schema) + return None, sums, counts, objective + + def _update_removal_statistics(self, alpha, decay): + """Try a fused removal update independently of centroid assignment.""" + norm_args = () if self._axis_norms is None else (self._axis_norms,) + return (isinstance(self._execution_backend, TritonBackend) + and self._execution_backend.removal_update( + self._removal_stats, self._batch_removal, self._axes, alpha, decay, + *norm_args)) + + def _apply_statistics( + self, ids, sums, counts, objective, alpha, decay, replace_usage=False + ): + """Apply Algorithm 1, line 8 (Equation 2), to prepared batch statistics. + + In the paper's notation, ``sums`` is s_j, ``counts`` is n_j, + ``decay`` is gamma and ``alpha`` is 1 - gamma. For occupied clusters, + the sum-and-count EMA is expressed using mass N_j and centroid c_j: + + N_new = decay * N_j + alpha * n_j + c_new = c_j + (alpha * n_j / N_new) * (s_j / n_j - c_j) + + ``_usage`` stores N_j and ``_centroids`` stores c_j = S_j / N_j. + Empty clusters keep their positions. ``replace_usage`` bypasses the + previous mass for occupied clusters when the step is one. ``ids`` + maps sparse statistics to centroid rows; None denotes the full table. + + Preserve batch counts and sums in epoch totals before the EMA for + Algorithm 1's last-epoch finalization (line 12), and add the batch + objective for reporting. The caller handles revival afterward (line 9). + See the class docstring for the paper reference. + """ + # Capture already-global statistics once before reuse/EMA/revival. + self._objective += ( + objective # Local contribution; reduced once per epoch. + ) + if ids is None: + self._pass_counts += counts + if self._pass_sums is not None: + self._pass_sums += sums + else: + self._pass_counts.index_add_( + 0, ids, counts.to(self._pass_counts.dtype) + ) + if self._pass_sums is not None: + self._pass_sums.index_add_(0, ids, sums) + if self._removal_folded: + self._removal_folded = False + elif (self._removal_stats is not None + and not self._update_removal_statistics(alpha, decay)): + self._removal_stats.mul_(decay).add_(alpha * self._batch_removal) + axis = self._removal_stats[:, :-1].double() + norm = axis.norm(dim=1, keepdim=True) # FP64: |U|^2 can overflow FP32 + if getattr(self, "_axis_norms", None) is not None: + self._axis_norms.copy_(norm.flatten()) + torch.where(norm > 0, (axis / norm).float(), self._axes, out=self._axes) + self._batch_removal.zero_() + + self._execution_backend.update( + self._centroids, + self._usage, + ids, + sums, + counts, + alpha, + decay, + replace_usage, + ) + self._invalidate_readout() + + def _epoch_totals(self): + objective = self._epoch_objective() + report_counts = self._pass_counts.double() + return torch.stack( + (objective, torch.dot(report_counts, report_counts)) + ).tolist() + + def _spherical_closing(self): + from .e_means_spherical import normalize_into + + result = self._centroids.new_empty(self._centroids.shape) + # Bound wide means separately from projection scratch; normalize before + # F32. + rows = max(1, (1 << 25) // (8 * self.d)) + for begin in range(0, self.k, rows): + end = min(begin + rows, self.k) + sums, counts = ( + self._pass_sums[begin:end], + self._pass_counts[begin:end], + ) + raw = self._centroids[begin:end] + + dtype = ( + torch.float64 if sums.dtype == torch.float64 else torch.float32 + ) + mean = sums.to(dtype) / counts.clamp_min(1).to(dtype)[:, None] + mean = torch.where((counts > 0)[:, None], mean, raw) + normalize_into(mean, result[begin:end]) + return result + + def finalize(self): + """Set and return FP32 closing means from the final pass's assignments. + + Centroids without rows in that pass keep their current positions. All + epochs must be complete; repeated finalization returns the same result. + """ + if self._failed: + raise RuntimeError("create a new object after execution failure") + if self.centroids is not None: + return self.centroids + self._failed = True + centroids = self._centroids + objectives = [stat["obj"] for stat in self.iteration_stats] + if self.spherical: + self.centroids = self._spherical_closing() + else: + self.centroids = _closing_centroid_values( + self._pass_sums, self._pass_counts, centroids, + ) + self.obj = torch.tensor( + objectives, dtype=torch.float64, device=centroids.device + ) + self._centroids = self._usage = self._batch_stats = None + self._removal_stats = self._axes = self._batch_removal = None + self._axis_norms = None + self._n_splits = self.n_splits + self._check_graph = self._check_pool = self._check_async = self._check_splits = None + self._unit_centroids = self._unit_version = None + self._pass_sums = self._pass_counts = self._objective = None + self._pending_stats = None + self._batch_accumulation = self._batch_objective = None + self._batch_norm = None + self._batch_centroids = None + self._execution_backend.clear_statistics() + self._failed = False + return self.centroids + + def _replay_representation_eligible(self): + return True + + def _capture_operations_match(self, owner=None): + # Graph replay executes recorded GPU work without these Python calls. + # Overrides use the ordinary eager call path. + owner = Emeans if owner is None else owner + return all(_same_operation(getattr(self, name), getattr(owner, name), self) + for name in ("_accumulate", "update", "_invalidate_readout", + "_prepare_statistics", "_select_statistics_dtype", + "_accumulate_core", "_apply_statistics", "_assign_rows", + "_prepare_rows", "_prepare_torch_assignment", "_statistics_rows", + "_update_removal_statistics", + "_local_batch_size", "_logical_batch_size", "_complete_statistics")) and ( + not self.spherical or _same_operation(self._readout, owner._readout, self)) + + def _chunked_capture_matches(self, owner=None): + # Chunked label capture calls accumulation for each assignment chunk, + # removes its labels, then updates once for the logical batch. + # Overrides keep the ordinary batch call and its statistics intact. + owner = Emeans if owner is None else owner + return all(_same_operation(getattr(self, name), getattr(owner, name), self) + for name in ("_accumulate", "_accumulate_core", "update", "_prepare_statistics", + "_logical_batch_size", "_complete_statistics")) + + def _replay_eligible(self, x): + # Replay requires a fitted (batch, alpha) pair and the default effective + # chunk sizes. Either fitted law qualifies, so an explicit recipe equal to + # the throughput or the quality law keeps replay whatever batch_law + # resolved to. Supporting other recipes is TODO. + if ( + not self._capture_operations_match() + or not x.is_cuda + or (self.recipe["batch_size"] > 2**24) + or (self.recipe["steps_per_pass"] < 3) + ): + return False + fitted = [ + _resolve_recipe(self._n, self.k, self.nepochs, law, None, None) + for law in ("throughput", "quality") + ] + batch, alpha = self.recipe["batch_size"], self.recipe["alpha0"] + if (batch, alpha) not in fitted: + return False + backend = self._execution_backend + # An installed backend with a different assign callback trains eagerly. + if not any(_same_operation(backend.assign, assign, backend) for assign in ( + TorchBackend.assign, TritonBackend.assign, CuteBackend.assign)): + return False + if not any(_same_operation(backend.accumulate, method, backend) for method in + (TorchBackend.accumulate, TritonBackend.accumulate)): + return False + if not any(_same_operation(backend.update, method, backend) for method in + (TorchBackend.update, TritonBackend.update)): + return False + if isinstance(backend, TritonBackend) and ( + not any(_same_operation(backend.accumulate_removal, method, backend) for method in + (TritonBackend.accumulate_removal, CuteBackend.accumulate_removal)) + or not _same_operation(backend.removal_update, TritonBackend.removal_update, backend)): + return False + if backend.name == "native" and min(self.k, backend.centroid_chunk_size) != min(self.k, 4096): + return False + if min(batch, self.recipe["assignment_chunk_size"]) != min( + batch, default_chunk_size(backend.name, self._centroids)): + return False + if not self._replay_representation_eligible(): + return False + return x.is_contiguous() + + def _capture_step( + self, x, index, rate, batches, epoch_rates, position, labels_out=None, + second_labels_out=None, + ): + current = torch.cuda.current_stream(x.device) + stream = torch.cuda.Stream(device=x.device) + graph = torch.cuda.CUDAGraph() + # Each capture gets a fresh pool that lives until its graph is retired. + pool = torch.cuda.MemPool() + cached = self._execution_backend.capture_state() + captured = False + stats = None + try: + stream.wait_stream(current) + with torch.cuda.stream(stream): + self._execution_backend.initialize_capture() + # The context manager empties process caches; use primitives. + graph.capture_begin( + pool=pool.id, capture_error_mode="thread_local" + ) + try: + torch.index_select( + batches, 0, position, out=index.unsqueeze(0) + ) + torch.index_select( + epoch_rates, 0, position, out=rate.unsqueeze(0) + ) + # Explicit staging is recorded even before the final epoch. + stats = self._accumulate_core( + x, index, raw=True, labels_out=labels_out, + **({} if self._removal_stats is None else {"ema": (self._removal_stats, rate[0], rate[1])}), + **({} if second_labels_out is None else {"second_labels_out": second_labels_out}), + ) + if second_labels_out is not None: + # Replays keep each closing-pass row's second-nearest themselves. + second = self._handover["second"] + second.index_copy_(0, index, second_labels_out.to(second.dtype)) + self._apply_statistics( + None, + stats["sums"], + stats["counts"], + stats["objective"], + rate[0], + rate[1], + ) + position.add_(1) + finally: + graph.capture_end() + captured = True + current.wait_stream(stream) + finally: + self._execution_backend.finish_capture(cached, captured) + if not captured: + # No retry/rollback of failed capture or execution errors. + stats = None + graph.reset() + + return graph, cached, pool, stats and stats["sums"] + + def train(self, x, init_centroids=None): + """Train on x, or on a random subset when max_points_per_centroid binds. + + Return centroids and last-pass labels for every row of x (None with + capture disabled); rows left out of the subset get label -1. + """ + keep = self._training_subset(len(x)) + if keep is None: + return self._train_rows(x, init_centroids) + index = torch.as_tensor(keep, device=x.device) + _, sampled = self._train_rows(x[index], init_centroids) + if sampled is not None: + try: + labels = torch.full( + (len(x),), -1, dtype=sampled.dtype, device=sampled.device + ) + labels[index.to(sampled.device)] = sampled + except BaseException: + self._failed = True + self.assignments = None + raise + self.assignments = labels + return self.centroids, self.assignments + + def _train_rows(self, x, init_centroids=None): + """Train a dense supported matrix through the same caller-driven loop. + + Return centroids and last-pass labels (None with capture disabled). + Objective history remains in obj. Initialization and epoch shuffles + use the existing local seeded policy. No whole logical batch is + gathered. + Explicit initial centroids must be on x's device. + """ + start, given_init = time.perf_counter(), init_centroids is not None + x = x.detach() + n, d = x.shape + device = x.device + self._resolve_input_dtype(x) + self._resolve_assignment_backend(x) + self._execution_backend.require_training(device) + if init_centroids is None: + init_centroids = ( + x + if n == self.k + else x[ + torch.randperm( + n, + generator=_torch_generator(device, self.seed), + device=device, + )[: self.k] + ] + ) + init_centroids = self._initial_centroid_values(init_centroids) + self.begin(n, init_centroids) + x = self._prepare_input(x) + # Cost-based revival can move a centroid during the closing pass; + # captured rows it held are then assigned again at the end. + self._handover_planned = bool( + self.closing_handover and self.capture_assignments and self._unused_threshold is None) + # Rows first try their second-nearest when assignment can return it. + second_route = self._handover_planned and self._second_labels_supported() + self.recipe["closing_handover"] = ( + ("second_nearest" if second_route else "search") if self._handover_planned else None) + self._report_header_once() + if self._reports(): + self._report_preprocessing(start, given_init, n) + rates = None + order = index = rate = epoch_rates = position = batches = None + graph_has_sums = False + graph = cached = _pool = closing = None + captured_bindings = () + assignments = batch_labels = batch_second = None + graph_second = False + self._early_labels = second_route and sum(self.recipe["epoch_steps"][:-1]) <= _EARLY_LABEL_STEPS + try: + if self._replay_eligible(x): + alphas = [ + _scheduled_alpha( + self.recipe["alpha0"], step, self.recipe["total_steps"] + ) + for step in range(self.recipe["total_steps"]) + ] + # Independently round the host-computed alpha and decay to FP32. + rates = torch.tensor( + [(a, 1.0 - a) for a in alphas], + dtype=torch.float32, + device=device, + ) + index = torch.empty( + self.recipe["batch_size"], dtype=torch.int64, device=device + ) + rate = torch.empty(2, dtype=torch.float32, device=device) + epoch_rates = rate.new_empty( + (self.recipe["steps_per_pass"], 2) + ) + position = torch.zeros(1, dtype=torch.int64, device=device) + if self.capture_assignments: + assignments = torch.empty(n, dtype=torch.int64, device=device) + if self.recipe["epoch_rows"][-1] < n or self._handover_planned: + assignments.fill_(-1) + if rates is not None: + batch_labels = torch.empty_like(index) + if second_route: + batch_second = torch.empty_like(index, dtype=torch.int32) + if self._handover_planned: + self._handover_start(assignments, x, second_route) + for epoch, rows in enumerate(self.recipe["epoch_rows"]): + closing_pass = epoch == len(self.recipe["epoch_rows"]) - 1 + handover = closing_pass and self._handover_planned + if handover: + # Records from earlier passes do not count. + self._handover["moved_at"].fill_(-1) + self._handover["events"] = [] + if self._handover["second"] is not None: + # Small runs label their earlier steps too; only closing-pass labels count. + self._handover["second"].fill_(-1) + self._handover["rows"] = 0 + shuffled = torch.randperm( + n, + generator=_torch_generator( + device, _epoch_seed(self.seed, epoch) + ), + device=device, + ) + if rates is None or order is None: + order = shuffled + else: + # Capture reads this storage; eager primes/tails use its new + # values. + order.copy_(shuffled) + shuffled = None + primed = graph is not None + if rates is not None: + # Stable storage, original epoch order and independently + # rounded rates. + batches = order[: n - n % len(index)].view(-1, len(index)) + # Fixed full-N tables survive graph reuse; only the active + # prefix is indexed during a shorter epoch. + steps = self.recipe["epoch_steps"][epoch] + epoch_rates[:steps].copy_( + rates[self._step : self._step + steps] + ) + position.zero_() + for begin in range(0, rows, self.recipe["batch_size"]): + batch = order[ + begin : min(begin + self.recipe["batch_size"], rows) + ] + replay = ( + rates is not None + and len(batch) == len(index) + and alphas[self._step] != 1 + ) + if ( + replay + and graph is not None + and not graph_second + and batch_second is not None + and self._second_labels_wanted() + ): + # The closing pass records second-nearest labels: re-capture once. + graph.reset() + graph = cached = closing = captured_bindings = _pool = None + if replay and primed: + self._require_running() + if graph is None: + graph_has_sums = self._pass_sums is not None + graph_second = batch_second is not None and self._second_labels_wanted() + graph, cached, _pool, closing = self._capture_step( + x, + index, + rate, + batches, + epoch_rates, + position, + batch_labels, + batch_second if graph_second else None, + ) + captured_bindings = ( + self._execution_backend.capture_bindings( + cached + ) + ) + self._execution_backend.validate_capture(cached) + graph.replay() + if ( + assignments is not None + and epoch == len(self.recipe["epoch_rows"]) - 1 + ): + # Consume captured row IDs before the next replay. + assignments[index] = batch_labels + if handover: + self._handover["rows"] += len(batch) + if self._pass_sums is not None and not graph_has_sums: + # Same dense ATen closing add, before revival/next + # stats zero. + self._pass_sums.add_(closing) + # Replay writes do not execute Python mutation + # notifications. + torch.autograd.graph.increment_version( + (self._centroids, self._usage) + ) + self._finish_step(len(batch)) + elif ( + self._chunked_capture_matches() + and rates is None + and assignments is not None + and epoch == len(self.recipe["epoch_rows"]) - 1 + ): + # Keep eager resident capture bounded by assignment + # chunks. + # All chunks still share one logical batch's fixed + # snapshot + # and one update; public caller labels remain caller- + # owned. + chunk_size = self.recipe["assignment_chunk_size"] + for offset in range(0, len(batch), chunk_size): + chunk = batch[offset : offset + chunk_size] + stats = self._accumulate(x, chunk) + # Move this chunk's labels from pending statistics + # to the public result. + labels = stats.pop("labels") + assignments[chunk] = labels + labels = None + second = stats.pop("second_labels", None) + if second is not None: + self._handover["second"][chunk] = second.to(self._handover["second"].dtype) + second = None + if handover: + self._handover["rows"] += len(batch) + self.update(stats) + else: + stats = self._accumulate(x, batch, batch_labels) + if assignments is not None and closing_pass: + # Before update(): a revival there must see them. + assignments[batch] = stats["labels"] + if handover: + second = stats.pop("second_labels", None) + if second is not None: + self._handover["second"][batch] = second.to( + self._handover["second"].dtype) + self._handover["rows"] += len(batch) + self.update(stats) + if rates is not None: + position.add_(1) + primed = primed or replay + self.end_epoch() + # Reporting drains work; retain the owned graph/pool for the + # next epoch. + if self._handover is not None: + self._handover_finish(order, self.recipe["epoch_rows"][-1]) + except BaseException: + self._failed = True + self.assignments = None + self._handover = None + if rates is not None: + torch.cuda.current_stream(device).synchronize() + raise + finally: + try: + if graph is not None: + graph.reset() + except BaseException: + self._failed = True + raise + finally: + del captured_bindings, _pool + graph = cached = closing = None + order = shuffled = batches = None + index = rate = epoch_rates = position = None + batch_labels = batch_second = None + self.finalize() + self.assignments = assignments + return self.centroids, self.assignments + + def assign(self, x): + """Assign in this call's representation and record assignment_recipe. + + Evaluation keeps the training recipe and captured labels unchanged. + Automatic CUDA FP32 queries use BF16. QuantizedEmeans(quantizer=None) + keeps the native query dtype; explicit codecs keep their representation. + """ + import copy + + self.assignment_recipe = None + evaluation = copy.copy(self) + evaluation._centroids = None + evaluation._input_dtype = None + evaluation._cast_dtype = None + evaluation._resolved_assignment_backend = None + evaluation._execution_backend = ( + self._query_backend or self._execution_backend.fork_query()) + evaluation.recipe = None + result = evaluation._assign(x) + self._execution_backend.finish_query(evaluation._execution_backend) + self._query_backend = evaluation._execution_backend + self.assignment_recipe = dict( + assignment_backend_requested=self.assignment_backend, + assignment_backend=evaluation._assignment_backend, + representation=str(evaluation._input_dtype).removeprefix("torch."), + device=str(x.device), + assignment_chunk_size=evaluation._get_assignment_chunk_size(), + ) + return result + + def _assign(self, x): + """Return squared L2 distances and centroid indices. + + Distances are reported in model coordinates, using the row and + centroid representations selected by the implementation. + Spherical mode returns represented inner-product similarity instead: + callers normalize input before conversion; rounded unit directions + approximate cosine without repairing represented norm drift. + """ + if self._failed: + raise RuntimeError("create a new object after execution failure") + + x = self._prepare_input(x) + centroids = self._execution_backend.query_centroids(self.centroids) + assignment_chunk_size = self._get_assignment_chunk_size() + + distance = torch.empty(len(x), dtype=torch.float32, device=x.device) + labels = torch.empty(len(x), dtype=torch.int64, device=x.device) + centroids, centroid_norm = self._prepare_assignment_query(centroids) + + for begin in range(0, len(x), assignment_chunk_size): + end = min(begin + assignment_chunk_size, len(x)) + rows = self._prepare_rows(x[begin:end]) + if self._execution_backend.writes_outputs: + self._assign_rows( + rows, + centroids, + centroid_norm, + distance[begin:end], + labels[begin:end], + ) + else: + distance[begin:end], labels[begin:end] = self._assign_rows( + rows, centroids, centroid_norm + ) + if self.spherical: + distance *= -0.5 + return distance, labels diff --git a/thirdparty/faiss/contrib/e_means/figure/emeans-wordmark-framed.png b/thirdparty/faiss/contrib/e_means/figure/emeans-wordmark-framed.png new file mode 100644 index 000000000..06eb395d9 Binary files /dev/null and b/thirdparty/faiss/contrib/e_means/figure/emeans-wordmark-framed.png differ diff --git a/thirdparty/faiss/contrib/e_means/figure/readme_figure_v6.png b/thirdparty/faiss/contrib/e_means/figure/readme_figure_v6.png new file mode 100644 index 000000000..27e7875ea Binary files /dev/null and b/thirdparty/faiss/contrib/e_means/figure/readme_figure_v6.png differ diff --git a/thirdparty/faiss/contrib/e_means/ivf_fine.py b/thirdparty/faiss/contrib/e_means/ivf_fine.py new file mode 100644 index 000000000..1141cbfe1 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_fine.py @@ -0,0 +1,263 @@ +# 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. + +"""IVF fine search and exact probe selection for IndexIVFFlat. + +search_2nn returns, for each row, the two best candidates of its probed +lists: score = norm - 2 * inner over the represented operands (FP32 +accumulation), best = smallest score with ties to the lower ID, second = +smallest score among the other IDs, and score inf / ID -1 for missing entries +(non-finite scores, from overflowing or NaN inputs, count as missing). On CUDA, +routed (row, probe) pairs are grouped by list with a stable device sort; a +work item covers up to 64 (Triton) or 128 (CuTe) pairs of one list and scans +the whole list in candidate tiles, accumulating 16-wide contraction steps in +order; one merge over the nprobe partial results gives each row its two +candidates. Pair results depend neither on the filing order +nor on the tiling, so the CuTe SM90 kernel (ivf_fine_cute, BF16 operands, used +with its required CuTe/quack dependencies) and the Triton kernel return identical +bits; the Triton kernel serves other GPUs and FP16 / FP32 operands. Other +devices and dtypes use the same search written with PyTorch operations. + +``route`` keeps the coarse scores of IndexIVFFlat.route (the same matmul per +query chunk, dis = norm - 2 * dot) and replaces torch.topk with an exact radix +select, one kernel for any nlist and nprobe: four passes over each row's +scores fix the nprobe-th score one 8-bit digit at a time, and a last pass +writes the selected lists (rows of up to 2,048 lists stay in registers across +the passes; longer rows are read in chunks of 512 lists per pass). Each row gets the same set of nprobe +lists as torch.topk, the lower list ID winning equal scores at the boundary, +ordered by score, then by list ID. +""" + +from functools import lru_cache + +import torch + +# None tunes the CuTe candidate-tile width per shape class; 128 or 256 fixes it. +DEFAULT_TILE = None +_IMAX = 0x7FFFFFFFFFFFFFFF +_ROUTE_RESIDENT = 2048 # up to this many lists, the selection keeps each row's scores in registers +_ROUTE_CHUNK = 512 # otherwise it reads them in chunks of this many lists per pass + + +@lru_cache(maxsize=1) +def _triton_kernels(): + try: + import triton + from .ivf_fine_triton import _search_kernel, _merge_kernel, _select_kernel + except ImportError as exc: + raise ImportError("IVF CUDA search and routing require Triton; install it in the selected environment") from exc + return triton, _search_kernel, _merge_kernel, _select_kernel + + +def route_eligible(index, x): + """CUDA rows (CPU routing keeps torch.topk).""" + return x.is_cuda + + +def route(index, x): + """IndexIVFFlat.route's probe lists, selected without torch.topk.""" + with torch.cuda.device(x.device): + return _route(index, x) + + +def _route(index, x): + from .ivf_flat import _dot_fp32 + + triton, _, _, _select_kernel = _triton_kernels() + + nq = x.shape[0] + P, nl = int(index.nprobe), int(index.nlist) + norms = index._current_routing_norms() + dt, xb_t = index._lowp_operands(index.centroids, "coarse") + chunk = index.query_chunk if index.implem >= 2 else nq + resident = nl <= _ROUTE_RESIDENT + CT, BR = (triton.next_power_of_2(nl), 2) if resident else (_ROUTE_CHUNK, 1) + cols = torch.empty((nq, P), dtype=torch.int32, device=x.device) + keys = torch.empty((nq, P), dtype=torch.int32, device=x.device) + for i0 in range(0, nq, max(1, chunk)): + i1 = min(i0 + chunk, nq) + rows = i1 - i0 + dot = _dot_fp32(x[i0:i1] if dt is None else x[i0:i1].to(dt), xb_t) + if dot.stride(1) != 1: + dot = dot.contiguous() + _select_kernel[(triton.cdiv(rows, BR),)](dot, norms, cols[i0:i1], keys[i0:i1], rows, nl, dot.stride(0), P, + CT=CT, BLOCK_R=BR, RESIDENT=resident, num_warps=4, enable_fp_fusion=False) + # Nearest first: back to the scores (inverse of the key map), then a stable sort keeps lower list IDs first. + scores = torch.where(keys < 0, keys & 0x7FFFFFFF, ~keys).view(torch.float32) + order = torch.sort(scores, dim=1, stable=True).indices + return torch.gather(cols, 1, order).long() + + +def _file_pairs(index, coarse_idx, BM): + """Group the routed pairs by list and cut each list's pairs into work items, without host reads. + + The item tables cover an upper bound of item slots; slots past the + device-side total have count 0. Returns (item_list, item_start, + item_count, pair_row, pair_id, slots, total). + """ + n, P = coarse_idx.shape + device = coarse_idx.device + nl = int(index.nlist) + lists = coarse_idx.reshape(-1) + # A stable device sort groups the pairs by list for any number of lists; list bounds come from a search. + sorted_lists, order = torch.sort(lists.int(), stable=True) + bounds = torch.searchsorted(sorted_lists, torch.arange(nl + 1, dtype=torch.int32, device=device)) + starts, counts = bounds[:-1], bounds[1:] - bounds[:-1] + pair_id, pair_row = order.int(), (order // P).int() + per = (counts + BM - 1) // BM + cum = torch.cumsum(per, 0) + slots = (n * P + BM - 1) // BM + nl + i = torch.arange(slots, device=device) + owner = torch.searchsorted(cum, i, right=True) + valid = owner < nl + item_list = owner.clamp(max=nl - 1) + local = i - (cum - per)[item_list] + item_start = torch.where(valid, starts[item_list] + local * BM, 0) + item_count = torch.where(valid, torch.minimum(counts[item_list] - local * BM, torch.full_like(local, BM)), 0) + return item_list, item_start, item_count, pair_row, pair_id, slots, cum[-1:] + + +def _merge(p_sc, p_id, n, P): + triton, _, _merge_kernel, _ = _triton_kernels() + scores = torch.empty((n, 2), dtype=torch.float32, device=p_sc.device) + ids = torch.empty((n, 2), dtype=torch.int32, device=p_sc.device) + BP = triton.next_power_of_2(2 * P) + BR = max(1, min(64, 1024 // BP)) + _merge_kernel[(triton.cdiv(n, BR),)](p_sc, p_id, scores, ids, n, P, BR=BR, BP=BP, num_warps=4) + return scores, ids + + +def _partials(n, P, device): + return (torch.full((n * P, 2), torch.inf, dtype=torch.float32, device=device), + torch.full((n * P, 2), _IMAX, dtype=torch.int64, device=device)) + + +def _operands(index, x): + """Represented operands of the fine search: (queries, list storage).""" + fine = index._mm_dtype("fine") + vecs = index.vectors_lowp if index.vectors_lowp is not None else index.vectors + return (x if fine is None else x.to(fine)), vecs + + +def _search_triton(index, xq, vecs, coarse_idx): + triton, _search_kernel, _, _ = _triton_kernels() + n, d = xq.shape + P = int(coarse_idx.shape[1]) + ieee = vecs.dtype == torch.float32 + BM, BN, BK, stages = (64, 64, 32, 3) if ieee else (64, 128, 64, 4) + if torch.version.hip: + stages = 2 + xq = xq.contiguous() + vecs = vecs.contiguous() + lims = index.xb_lims.to(torch.int64).contiguous() + item_list, item_start, item_count, pair_row, pair_id, slots, _ = _file_pairs(index, coarse_idx, BM) + p_sc, p_id = _partials(n, P, xq.device) + if slots: + _search_kernel[(slots,)](xq, vecs, index.vectors_norms, index.ids, lims, pair_row, pair_id, item_list, + item_start, item_count, p_sc, p_id, d, xq.stride(0), vecs.stride(0), + BM=BM, BN=BN, BK=BK, IEEE=ieee, num_warps=4, num_stages=stages) + return _merge(p_sc, p_id, n, P) + + +def _top2_merge(scores, ids, new_scores, new_ids): + """Best two (score, ID) of each row over the running pair and new entries; lower IDs first among equal scores.""" + scores, ids = torch.cat((scores, new_scores), 1), torch.cat((ids, new_ids), 1) + by_id = torch.argsort(ids, dim=1, stable=True) + scores, ids = scores.gather(1, by_id), ids.gather(1, by_id) + first = torch.sort(scores, dim=1, stable=True).indices[:, :1] + first_score, first_id = scores.gather(1, first), ids.gather(1, first) + others = torch.where(ids == first_id, torch.inf, scores) # a list probed twice repeats its candidates + second = torch.sort(others, dim=1, stable=True).indices[:, :1] + return torch.cat((first_score, others.gather(1, second)), 1), torch.cat((first_id, ids.gather(1, second)), 1) + + +def _search_torch(index, xq, vecs, coarse_idx, block=1 << 22): + """The same search with PyTorch operations (CPU and other dtypes): one probed list at a time, in blocks of at most + ``block`` scores, keeping a running top-2 per routed pair.""" + from .ivf_flat import _dot_fp32 + + n, P = coarse_idx.shape + device = xq.device + pairs = coarse_idx.reshape(-1) + order = torch.argsort(pairs, stable=True) + counts = torch.bincount(pairs, minlength=int(index.nlist)).tolist() + lims = index.xb_lims.tolist() + p_sc = torch.full((n * P, 2), torch.inf, dtype=torch.float32, device=device) + p_id = torch.full((n * P, 2), _IMAX, dtype=torch.int64, device=device) + start = 0 + for lst, count in enumerate(counts): + if not count: + continue + sel = order[start:start + count] + start += count + b0, b1 = lims[lst], lims[lst + 1] + if b1 == b0: + continue + cand = min(b1 - b0, 4096) + rows = max(1, block // cand) + for r0 in range(0, count, rows): + part = sel[r0:r0 + rows] + q = xq[part // P] + best = torch.full((len(part), 2), torch.inf, dtype=torch.float32, device=device) + best_id = torch.full((len(part), 2), _IMAX, dtype=torch.int64, device=device) + for c0 in range(b0, b1, cand): + c1 = min(c0 + cand, b1) + dis = (index.vectors_norms[c0:c1][None] - 2 * _dot_fp32(q, vecs[c0:c1].T)).float() + dis = torch.where(torch.isfinite(dis), dis, torch.inf) # non-finite: missing + top = min(2, c1 - c0) + values, cols = torch.sort(dis, dim=1, stable=True) # positions follow IDs within a list + best, best_id = _top2_merge(best, best_id, values[:, :top], index.ids[c0:c1].long()[cols[:, :top]]) + p_sc[part], p_id[part] = best, best_id + # Merge the 2 * nprobe entries of each row. + scores, ids = p_sc.view(n, 2 * P), p_id.view(n, 2 * P) + scores, ids = _top2_merge(scores[:, :0], ids[:, :0], scores, ids) + ids = torch.where(torch.isfinite(scores) & (ids != _IMAX), ids, -1) + return scores, ids.int() + + +@lru_cache(maxsize=None) +def _cute_ready(device_index): + """Select the SM90 route by capability and require its CuTe dependencies.""" + if torch.version.hip is not None or torch.cuda.get_device_capability(device_index) != (9, 0): + return False + try: + import cutlass # noqa: F401 + import cutlass.cute # noqa: F401 + from quack import copy_utils, layout_utils, sm90_utils # noqa: F401 + from quack import pipeline as quack_pipeline # noqa: F401 + from quack.compile_utils import make_fake_tensor # noqa: F401 + except ImportError as exc: + raise ImportError("IVF BF16 search on SM90 requires CuTe and quack; install their supported versions") from exc + return True + + +def search_2nn(index, x, coarse_idx, tile=None): + """Scores (n, 2) FP32 and IDs (n, 2) int32 of the two best candidates of each row of x in its routed lists. + + ``tile`` (128 or 256) fixes the CuTe candidate-tile width; None uses + DEFAULT_TILE, tuning it once per shape class when that is None too. + """ + if x.is_cuda: + with torch.cuda.device(x.device): # kernels launch on the current device + return _search_2nn(index, x, coarse_idx, tile) + return _search_2nn(index, x, coarse_idx, tile) + + +def _search_2nn(index, x, coarse_idx, tile=None): + if not len(x) or not len(index.ids): # no rows, or no candidates anywhere + return (torch.full((len(x), 2), torch.inf, dtype=torch.float32, device=x.device), + torch.full((len(x), 2), -1, dtype=torch.int32, device=x.device)) + xq, vecs = _operands(index, x) + kernel = (xq.is_cuda and xq.dtype == vecs.dtype + and vecs.dtype in (torch.bfloat16, torch.float16, torch.float32) + and index.vectors_norms.dtype == torch.float32) + if not kernel: + return _search_torch(index, xq, vecs, coarse_idx) + if vecs.dtype == torch.bfloat16 and _cute_ready(xq.device.index if xq.device.index is not None + else torch.cuda.current_device()): + from .ivf_fine_cute import search_2nn as cute_search_2nn + + return cute_search_2nn(index, xq, coarse_idx, tile if tile is not None else DEFAULT_TILE) + return _search_triton(index, xq, vecs, coarse_idx) diff --git a/thirdparty/faiss/contrib/e_means/ivf_fine_cute.py b/thirdparty/faiss/contrib/e_means/ivf_fine_cute.py new file mode 100644 index 000000000..252d900e3 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_fine_cute.py @@ -0,0 +1,305 @@ +# 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. + +"""CuTe SM90 kernel of the fused IVF fine search (see ivf_fine). + +One persistent CTA per SM walks the work items (one list, up to 128 routed +pairs). A producer warpgroup gathers the pairs' query rows with cp.async and +loads the list's candidate tile with TMA, one 64-column contraction chunk per +stage of a 4-stage ring. Two consumer warpgroups run wgmma over each chunk +(BF16 operands, FP32 accumulation, 16-wide steps in contraction order), then +fold every candidate tile into a running lexicographic top-2 per row with +score = fma(-2, inner, norm) and key (score, position); positions follow ID +order inside a list, so the order equals the (score, ID) order of the padded +BMM path. Rows and lists whose width is not a multiple of 8 are fed as copies +padded with zero columns, which add exact zeros. The candidate-tile width +(128 or 256) changes timing only and is tuned once per shape class. +""" + +import math + +import cutlass +import cutlass.cute as cute +from cutlass import BFloat16, Float32, Int32, Int64, const_expr, pipeline +from cutlass.cute.nvgpu import cpasync +from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait +from cutlass.utils import LayoutEnum +import cutlass.utils.hopper_helpers as hopper_utils +from quack import copy_utils, layout_utils, pipeline as quack_pipeline +from quack import sm90_utils +import torch + +from . import ivf_fine + +_PRODUCER_THREADS = 128 +_WARPGROUP_THREADS = 128 +_TM = 128 # routed pairs (query rows) per work item +_TN = 256 # candidates per tile +_BK = 64 # columns per K chunk +_STAGES = 4 +_IMAX32 = 0x7FFFFFFF + + +class _FineSearchSm90: + def __init__(self, w, tn=256): + self.nk = (w + _BK - 1) // _BK + self.tn = tn # the last K chunk may be partial: cp.async and TMA zero-fill past the width + + @cute.jit + def __call__(self, x, c16, cn, ids, lims, brow, porder, item_list, item_start, item_count, total, o_sc, o_id, + nsm: Int32, stream): + tiled_mma = hopper_utils.make_trivial_tiled_mma( + BFloat16, BFloat16, cute.nvgpu.OperandMajorMode.K, cute.nvgpu.OperandMajorMode.K, + Float32, atom_layout_mnk=(2, 1, 1), tiler_mn=(64, self.tn)) + q_layout = sm90_utils.make_smem_layout(BFloat16, LayoutEnum.ROW_MAJOR, (_TM, _BK), _STAGES) + c_layout = sm90_utils.make_smem_layout(BFloat16, LayoutEnum.ROW_MAJOR, (self.tn, _BK), _STAGES) + tma_atom_c, tma_c = cpasync.make_tiled_tma_atom(cpasync.CopyBulkTensorTileG2SOp(), c16, + cute.slice_(c_layout, (None, None, 0)), (self.tn, _BK)) + + @cute.struct + class SharedStorage: + barriers: cute.struct.MemRange[cutlass.Int64, _STAGES * 2] + q: cute.struct.Align[cute.struct.MemRange[BFloat16, cute.cosize(q_layout)], 1024] + c: cute.struct.Align[cute.struct.MemRange[BFloat16, cute.cosize(c_layout)], 1024] + + self.kernel(x, cn, ids, lims, brow, porder, item_list, item_start, item_count, total, o_sc, o_id, tiled_mma, q_layout, + c_layout, SharedStorage, tma_atom_c, tma_c).launch( + grid=(nsm, 1, 1), block=(_PRODUCER_THREADS + 2 * _WARPGROUP_THREADS, 1, 1), stream=stream, min_blocks_per_mp=1) + + @cute.kernel + def kernel(self, x, cn, ids, lims, brow, porder, item_list, item_start, item_count, total, o_sc, o_id, tiled_mma, + q_layout, c_layout, SharedStorage: cutlass.Constexpr, tma_atom_c, tma_c): + warp = cute.arch.make_warp_uniform(cute.arch.warp_idx()) + allocator = cutlass.utils.SmemAllocator() + storage = allocator.allocate(SharedStorage) + if warp == 0: + cpasync.prefetch_descriptor(tma_atom_c) + pipe = quack_pipeline.PipelineTmaCpAsync.create( + barrier_storage=storage.barriers.data_ptr(), num_stages=_STAGES, + producer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 1 + _PRODUCER_THREADS), + consumer_group=pipeline.CooperativeGroup(pipeline.Agent.Thread, 2 * _WARPGROUP_THREADS // cute.arch.WARP_SIZE), + tx_count=self.tn * _BK * 2, cta_layout_vmnk=cute.make_layout((1, 1, 1, 1)), defer_sync=True) + pipeline_init_arrive(cluster_shape_mn=(1, 1), is_relaxed=True) + q_smem = storage.q.get_tensor(q_layout.outer, swizzle=q_layout.inner) + c_smem = storage.c.get_tensor(c_layout.outer, swizzle=c_layout.inner) + pipeline_init_wait(cluster_shape_mn=(1, 1)) + if warp < 4: + cute.arch.setmaxregister_decrease(40) + self.produce(x, lims, brow, item_list, item_start, item_count, total, q_smem, c_smem, pipe, tma_atom_c, tma_c, warp) + else: + cute.arch.setmaxregister_increase(232) + thread, _, _ = cute.arch.thread_idx() + self.consume(cn, ids, lims, porder, item_list, item_start, item_count, total, o_sc, o_id, q_smem, c_smem, tiled_mma, + pipe, thread - _PRODUCER_THREADS) + + @cute.jit + def produce(self, x, lims, brow, item_list, item_start, item_count, total, q_smem, c_smem, pipe, tma_atom_c, tma_c, warp): + tidx = cute.arch.thread_idx()[0] + block, _, _ = cute.arch.block_idx() + grid, _, _ = cute.arch.grid_dim() + per_row = const_expr(_BK // 8) + tiled_copy = cute.make_tiled_copy_tv( + cute.make_copy_atom(cpasync.CopyG2SOp(cache_mode=cpasync.LoadCacheMode.GLOBAL), BFloat16, num_bits_per_copy=128), + cute.make_layout((_PRODUCER_THREADS // per_row, per_row), stride=(per_row, 1)), cute.make_layout((1, 8))) + thr_copy = tiled_copy.get_slice(tidx) + state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Producer, _STAGES) + for item in cutlass.range(block, total[0], grid, unroll=1): + L = item_list[item] + start = item_start[item] + count = item_count[item] + lo = lims[L] + size = lims[L + 1] - lo + qidx = cute.local_tile(cute.domain_offset((start,), brow), (_TM,), (0,)) + copy_q = copy_utils.gather_m_get_copy_fn(thr_copy, x, q_smem, qidx, limit_m=count, limit_k=x.shape[1]) + for nt in cutlass.range(((size - 1) // self.tn + 1) if size > 0 else 0, unroll=1): # no size + tn overflow + gC = cute.local_tile(cute.domain_offset((lo + nt * self.tn, 0), tma_c), (self.tn, _BK), (0, None)) + copy_c, _, _ = copy_utils.tma_get_copy_fn(tma_atom_c, 0, cute.make_layout(1), gC, c_smem) + for kc in cutlass.range(self.nk, unroll=1): + pipe.producer_acquire(state, None, warp == 0) + if warp == 0: + copy_c(kc, state.index, tma_bar_ptr=pipe.producer_get_barrier(state)) + copy_q(kc, state.index, pred=True) + pipe.producer_cpasync_commit(state) + state.advance() + + @cute.jit + def consume(self, cn, ids, lims, porder, item_list, item_start, item_count, total, o_sc, o_id, q_smem, c_smem, tiled_mma, + pipe, thread): + warpgroup = cute.arch.make_warp_uniform(thread // _WARPGROUP_THREADS) + group_layout = cute.make_layout(2, stride=_WARPGROUP_THREADS) + thread_mma = tiled_mma.get_slice(thread) + group_mma = tiled_mma.get_slice(group_layout(warpgroup)) + _, q_fragment, c_fragment = sm90_utils.partition_fragment_ABC(group_mma, (_TM, self.tn, _BK), q_smem, c_smem) + coordinates = layout_utils.reshape_acc_to_mn(thread_mma.partition_C(cute.make_identity_tensor((_TM, self.tn)))) + row_shape = (cute.size(coordinates, mode=[0]),) + block, _, _ = cute.arch.block_idx() + grid, _, _ = cute.arch.grid_dim() + lane = cute.arch.lane_idx() + state = pipeline.make_pipeline_state(pipeline.PipelineUserType.Consumer, _STAGES) + mma_atom = cute.make_mma_atom(tiled_mma.op) + mma_atom.set(cute.nvgpu.warpgroup.Field.ACCUMULATE, True) # accumulators are zeroed before each K loop + for item in cutlass.range(block, total[0], grid, unroll=1): + L = item_list[item] + start = item_start[item] + n_pairs = item_count[item] + lo = lims[L] + size = lims[L + 1] - lo + b = cute.make_rmem_tensor(row_shape, Float32) + bp = cute.make_rmem_tensor(row_shape, Int32) + s = cute.make_rmem_tensor(row_shape, Float32) + sp = cute.make_rmem_tensor(row_shape, Int32) + b.fill(Float32.inf) + bp.fill(_IMAX32) + s.fill(Float32.inf) + sp.fill(_IMAX32) + for nt in cutlass.range(((size - 1) // self.tn + 1) if size > 0 else 0, unroll=1): # no size + tn overflow + acc = cute.make_rmem_tensor(tiled_mma.partition_shape_C((_TM, self.tn)), Float32) + acc.fill(0.0) + for _kc in cutlass.range(self.nk, unroll=1): + pipe.consumer_wait(state, pipe.consumer_try_wait(state)) + cute.nvgpu.warpgroup.fence() + for k in cutlass.range_constexpr(_BK // 16): + cute.gemm(mma_atom, acc, q_fragment[None, None, k, state.index], c_fragment[None, None, k, state.index], acc) + cute.nvgpu.warpgroup.commit_group() + cute.nvgpu.warpgroup.wait_group(0) + pipe.consumer_release(state) + state.advance() + values = layout_utils.reshape_acc_to_mn(acc) + for column in cutlass.range_constexpr(cute.size(values, mode=[1])): + local = nt * self.tn + coordinates[0, column][1] + norm = cn[lo + (local if local < size else 0)] + norm = norm if local < size else Float32.inf + for row in cutlass.range_constexpr(cute.size(b)): + score = cute.math.fma(Float32(-2.0), values[row, column], norm) + fin = (score < Float32.inf) & (score > -Float32.inf) # non-finite: missing + lt_b = fin & ((score < b[row]) | ((score == b[row]) & (local < bp[row]))) + lt_s = fin & ((score < s[row]) | ((score == s[row]) & (local < sp[row]))) + s[row] = b[row] if lt_b else (score if lt_s else s[row]) + sp[row] = bp[row] if lt_b else (local if lt_s else sp[row]) + b[row] = score if lt_b else b[row] + bp[row] = local if lt_b else bp[row] + for offset in (2, 1): # quad butterfly: merge two lexicographic top-2 states (positions are unique) + for row in cutlass.range_constexpr(cute.size(b)): + ob = cute.arch.shuffle_sync_bfly(b[row], offset=offset) + obp = cute.arch.shuffle_sync_bfly(bp[row], offset=offset) + os_ = cute.arch.shuffle_sync_bfly(s[row], offset=offset) + osp = cute.arch.shuffle_sync_bfly(sp[row], offset=offset) + other_first = (ob < b[row]) | ((ob == b[row]) & (obp < bp[row])) + lb = b[row] if other_first else ob # loser of the two firsts + lbp = bp[row] if other_first else obp + nb = ob if other_first else b[row] + nbp = obp if other_first else bp[row] + # second = smallest of (loser, own second, other second) + c1 = (os_ < s[row]) | ((os_ == s[row]) & (osp < sp[row])) + ms = os_ if c1 else s[row] + msp = osp if c1 else sp[row] + c2 = (lb < ms) | ((lb == ms) & (lbp < msp)) + s[row] = lb if c2 else ms + sp[row] = lbp if c2 else msp + b[row] = nb + bp[row] = nbp + if lane % 4 == 0: + for local in cutlass.range_constexpr(cute.size(b)): + p = coordinates[local, 0][0] + if p < n_pairs: + pair = porder[start + p].to(Int64) + o_sc[pair * 2] = b[local] + o_sc[pair * 2 + 1] = s[local] + if b[local] < Float32.inf: + o_id[pair * 2] = ids[lo + bp[local]].to(Int64) + if s[local] < Float32.inf: + o_id[pair * 2 + 1] = ids[lo + sp[local]].to(Int64) + + +_COMPILED = {} +_TUNED = {} + + +def _compiled(width, tile): + from quack.compile_utils import make_fake_tensor + + if (width, tile) not in _COMPILED: + dyn = cute.sym_int + vec = lambda dtype: make_fake_tensor(dtype, (dyn(),), divisibility=1, leading_dim=0) # noqa: E731 + fakes = (make_fake_tensor(BFloat16, (dyn(), width), divisibility=8, leading_dim=1), + make_fake_tensor(BFloat16, (dyn(), width), divisibility=8, leading_dim=1), + vec(Float32), vec(Int32), vec(Int32), vec(Int32), vec(Int32), vec(Int32), vec(Int32), vec(Int32), + vec(Int32), vec(Float32), vec(Int64)) + _COMPILED[width, tile] = cute.compile( + _FineSearchSm90(width, tile), *fakes, 132, cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), + options="--enable-tvm-ffi") + return _COMPILED[width, tile] + + +def _prepare(index, x, coarse_idx, tile): + n, d = x.shape + P = int(coarse_idx.shape[1]) + device = x.device + width = (d + 7) // 8 * 8 # 16-byte rows for cp.async and TMA + x16 = x.to(torch.bfloat16).contiguous() + rows = x16 if width == d else torch.nn.functional.pad(x16, (0, width - d)) + if rows.data_ptr() % 16: # cp.async moves 16-byte row pieces: realign a view that starts mid-row + rows = rows.clone() + vecs = index.vectors_lowp if index.vectors_lowp is not None else index.vectors + nv = vecs.shape[0] + if width == d and vecs.is_contiguous() and vecs.data_ptr() % 16 == 0: # TMA zero-fills rows past the end + lists = vecs + else: + lists = torch.zeros((nv + _TN, width), dtype=torch.bfloat16, device=device) + lists[:nv, :d] = vecs + norms = torch.full((nv + _TN,), torch.inf, dtype=torch.float32, device=device) + norms[:nv] = index.vectors_norms + ids = torch.zeros((nv + _TN,), dtype=torch.int32, device=device) + ids[:nv] = index.ids.to(torch.int32) + item_list, item_start, item_count, pair_row, pair_id, slots, total = ivf_fine._file_pairs(index, coarse_idx, _TM) + p_sc, p_id = ivf_fine._partials(n, P, device) + args = None + if slots: + sms = torch.cuda.get_device_properties(device).multi_processor_count + args = (rows, lists, norms, ids, index.xb_lims.to(torch.int32), pair_row, pair_id, item_list.to(torch.int32), + item_start.to(torch.int32), item_count.to(torch.int32), total.to(torch.int32), p_sc.view(-1), p_id.view(-1), + sms) + return dict(n=n, P=P, width=width, tile=tile, args=args, p_sc=p_sc, p_id=p_id) + + +def _run(state): + if state["args"] is not None: + _compiled(state["width"], state["tile"])(*state["args"]) + + +def _tuned_tile(index, x, coarse_idx): + """Time both candidate-tile widths once per shape class and keep the faster; both give identical results.""" + n, d = x.shape + P = int(coarse_idx.shape[1]) + mean_list = int(index.vectors_norms.shape[0]) / max(1, int(index.nlist)) + key = ((d + 7) // 8 * 8, P, round(math.log2(max(1.0, mean_list))), round(math.log2(max(1, n)))) + if key not in _TUNED: + best = None + for tile in (128, 256): + times = [] + for _ in range(3): + state = _prepare(index, x, coarse_idx, tile) + start, stop = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) + start.record() + _run(state) + stop.record() + torch.cuda.synchronize() + times.append(start.elapsed_time(stop)) + elapsed = sorted(times)[1] # the first run includes compilation + if best is None or elapsed < best[0]: + best = (elapsed, tile) + _TUNED[key] = best[1] + return _TUNED[key] + + +def search_2nn(index, x, coarse_idx, tile=None): + """As ivf_fine.search_2nn, on the CuTe kernel.""" + if tile not in (None, 128, 256): + raise ValueError("tile must be None, 128 or 256") + if tile is None: + tile = _tuned_tile(index, x, coarse_idx) + state = _prepare(index, x, coarse_idx, tile) + _run(state) + return ivf_fine._merge(state["p_sc"], state["p_id"], state["n"], state["P"]) diff --git a/thirdparty/faiss/contrib/e_means/ivf_fine_triton.py b/thirdparty/faiss/contrib/e_means/ivf_fine_triton.py new file mode 100644 index 000000000..f48df4586 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_fine_triton.py @@ -0,0 +1,178 @@ +# 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. + +"""Lazily imported Triton kernels for IVF fine search and probe selection.""" + +import triton +import triton.language as tl + +@triton.jit +def _search_kernel(x16, vecs, norms, ids, lims, pair_row, pair_out, item_list, item_start, item_count, + o_sc, o_id, d, sx, sv, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, + IEEE: tl.constexpr): + """One work item: up to BM pairs of one list against the whole list.""" + imax = 0x7FFFFFFFFFFFFFFF + it = tl.program_id(0) + L = tl.load(item_list + it) + p0 = tl.load(item_start + it) + pc = tl.load(item_count + it) + rm = tl.arange(0, BM) + live = rm < pc + prow = tl.load(pair_row + p0 + rm, mask=live, other=0).to(tl.int64) + v0 = tl.load(lims + L).to(tl.int64) + v1 = tl.load(lims + L + 1).to(tl.int64) + v1 = tl.where(pc > 0, v1, v0) # unused slots of the upper-bound grid + best = tl.full([BM], float("inf"), tl.float32) + best_id = tl.full([BM], imax, tl.int64) + second = tl.full([BM], float("inf"), tl.float32) + second_id = tl.full([BM], imax, tl.int64) + for c0 in range(v0, v1, BN): + cn = c0 + tl.arange(0, BN) + cl = cn < v1 + acc = tl.zeros([BM, BN], dtype=tl.float32) + for k0 in range(0, d, BK): + rk = k0 + tl.arange(0, BK) + km = rk < d + a = tl.load(x16 + prow[:, None] * sx + rk[None, :], mask=live[:, None] & km[None, :], other=0.0) + b = tl.load(vecs + cn[:, None] * sv + rk[None, :], mask=cl[:, None] & km[None, :], other=0.0) + if IEEE: # FP32 operands: full-precision products, no TF32 + acc = tl.dot(a, tl.trans(b), acc, input_precision="ieee") + else: + acc = tl.dot(a, tl.trans(b), acc) + nm = tl.load(norms + cn, mask=cl, other=float("inf")) + cid = tl.load(ids + cn, mask=cl, other=imax).to(tl.int64) + score = nm[None, :] - 2.0 * acc + score = tl.where(cl[None, :] & (tl.abs(score) < float("inf")), score, float("inf")) # non-finite: missing + m1 = tl.min(score, axis=1) + i1 = tl.min(tl.where((score == m1[:, None]) & (tl.abs(score) < float("inf")), cid[None, :], imax), axis=1) + s2 = tl.where(cid[None, :] == i1[:, None], float("inf"), score) + m2 = tl.min(s2, axis=1) + i2 = tl.min(tl.where((s2 == m2[:, None]) & (tl.abs(s2) < float("inf")), cid[None, :], imax), axis=1) + # update_probes' merge of [tile first, tile second, old first, old second]; IDs differ across tiles. + nb = tl.minimum(tl.minimum(m1, m2), tl.minimum(best, second)) + nbid = tl.minimum(tl.minimum(tl.where(m1 == nb, i1, imax), tl.where(m2 == nb, i2, imax)), + tl.minimum(tl.where(best == nb, best_id, imax), tl.where(second == nb, second_id, imax))) + e1 = tl.where(i1 == nbid, float("inf"), m1) + e2 = tl.where(i2 == nbid, float("inf"), m2) + e3 = tl.where(best_id == nbid, float("inf"), best) + e4 = tl.where(second_id == nbid, float("inf"), second) + ot = tl.minimum(tl.minimum(e1, e2), tl.minimum(e3, e4)) + otid = tl.minimum( + tl.minimum(tl.where((e1 == ot) & (i1 != nbid), i1, imax), tl.where((e2 == ot) & (i2 != nbid), i2, imax)), + tl.minimum(tl.where((e3 == ot) & (best_id != nbid), best_id, imax), + tl.where((e4 == ot) & (second_id != nbid), second_id, imax))) + best, best_id, second, second_id = nb, nbid, ot, otid + po = tl.load(pair_out + p0 + rm, mask=live, other=0).to(tl.int64) + tl.store(o_sc + po * 2, best, mask=live) + tl.store(o_id + po * 2, best_id, mask=live) + tl.store(o_sc + po * 2 + 1, second, mask=live) + tl.store(o_id + po * 2 + 1, second_id, mask=live) + +@triton.jit +def _merge_kernel(p_sc, p_id, scores, out_ids, n, P, BR: tl.constexpr, BP: tl.constexpr): + """merge_probes over the 2 * nprobe (score, ID) entries of each row.""" + imax = 0x7FFFFFFFFFFFFFFF + row = tl.program_id(0) * BR + tl.arange(0, BR) + lane = tl.arange(0, BP) + live = (row < n)[:, None] & (lane < 2 * P)[None, :] + off = row[:, None].to(tl.int64) * (2 * P) + lane[None, :] + value = tl.load(p_sc + off, mask=live, other=float("inf")) + cand = tl.load(p_id + off, mask=live, other=imax) + first = tl.min(value, axis=1) + fid = tl.min(tl.where(value == first[:, None], cand, imax), axis=1) + second = tl.min(tl.where(cand == fid[:, None], float("inf"), value), axis=1) + sid = tl.min(tl.where((value == second[:, None]) & (cand != fid[:, None]), cand, imax), axis=1) + rr = row < n + out = row.to(tl.int64) * 2 + tl.store(scores + out, first, mask=rr) + tl.store(scores + out + 1, second, mask=rr) + tl.store(out_ids + out, tl.where(fid == imax, -1, fid).to(tl.int32), mask=rr) + tl.store(out_ids + out + 1, tl.where(sid == imax, -1, sid).to(tl.int32), mask=rr) + + +@triton.jit +def _keys(dot, norms, r64, m, col, NCOL, s_d): + """Order-preserving uint32 images of dis = norm - 2 * dot for one chunk of columns, and the valid lanes.""" + cm = col < NCOL + mask = m[:, None] & cm[None, :] + d = tl.load(dot + r64[:, None] * s_d + col[None, :], mask=mask, other=0.0) + nrm = tl.load(norms + col, mask=cm, other=float("inf")) + bits = (nrm[None, :] - 2.0 * d).to(tl.uint32, bitcast=True) + return tl.where((bits >> 31) != 0, ~bits, bits | 0x80000000), mask + +@triton.jit +def _count(key, mask, prefix, pmask, shift, rl, BLOCK_R: tl.constexpr, CT: tl.constexpr): + """Per-row counts of the 8-bit digit at ``shift`` among the keys that match the prefix found so far.""" + match = mask & ((key & pmask[:, None]) == prefix[:, None]) + digit = ((key >> shift) & 255).to(tl.int32) + binid = tl.where(match, rl[:, None] * 256 + digit, BLOCK_R * 256) + hist = tl.histogram(tl.reshape(binid, (BLOCK_R * CT,)), 2 * BLOCK_R * 256) + hh = tl.reshape(hist, (2, BLOCK_R, 256)) + return tl.sum(tl.where(tl.arange(0, 2)[:, None, None] == 0, hh, 0), axis=0) + +@triton.jit +def _pick(h, krem, prefix, pmask, shift, BLOCK_R: tl.constexpr): + """Fix the digit of the krem-th key; krem becomes its rank among the keys with the longer prefix.""" + d256 = tl.arange(0, 256) + cum = tl.cumsum(h, axis=1) + dsel = tl.min(tl.where(cum >= krem[:, None], d256[None, :], 256), axis=1) + krem = krem - tl.sum(tl.where(d256[None, :] < dsel[:, None], h, 0), axis=1) + prefix = prefix | (dsel.to(tl.uint32) << shift) + pmask = pmask | (tl.full((BLOCK_R,), 255, tl.uint32) << shift) + return krem, prefix, pmask + +@triton.jit +def _emit(key, mask, col, prefix, krem, eq_seen, sel_seen, out_col, out_key, r64, P, + BLOCK_R: tl.constexpr, CT: tl.constexpr): + """Write the selected columns of one chunk after those of the previous chunks, in column order.""" + less = mask & (key < prefix[:, None]) + eq = (mask & (key == prefix[:, None])).to(tl.int32) + eq_rank = eq_seen[:, None] + tl.cumsum(eq, axis=1) - eq + sel = (less | ((eq != 0) & (eq_rank < krem[:, None]))).to(tl.int32) + pos = sel_seen[:, None] + tl.cumsum(sel, axis=1) - sel + keep = (sel != 0) & (pos < P) + dst = r64[:, None] * P + pos + tl.store(out_col + dst, col[None, :] + tl.zeros((BLOCK_R, CT), tl.int32), mask=keep) + tl.store(out_key + dst, key.to(tl.int32, bitcast=True), mask=keep) + return eq_seen + tl.sum(eq, axis=1), sel_seen + tl.sum(sel, axis=1) + +@triton.jit +def _select_kernel(dot, norms, out_col, out_key, R, NCOL, s_d, P, CT: tl.constexpr, BLOCK_R: tl.constexpr, + RESIDENT: tl.constexpr): + """The P smallest keys of each row, lower columns first among equal keys, for any NCOL and P. + + Four counting passes over the row, in CT-wide column chunks, fix the P-th key one 8-bit digit at a time; a + last pass writes the selected columns and keys in column order. RESIDENT (NCOL <= CT): the keys are loaded + once and kept in registers across the passes. + """ + rl = tl.arange(0, BLOCK_R) + r = tl.program_id(0) * BLOCK_R + rl + m = r < R + r64 = r.to(tl.int64) + prefix = tl.zeros((BLOCK_R,), tl.uint32) + pmask = tl.zeros((BLOCK_R,), tl.uint32) + krem = tl.zeros((BLOCK_R,), tl.int32) + P + zero = tl.zeros((BLOCK_R,), tl.int32) + if RESIDENT: + col = tl.arange(0, CT) + key, mask = _keys(dot, norms, r64, m, col, NCOL, s_d) + for shift in tl.static_range(24, -1, -8): + krem, prefix, pmask = _pick(_count(key, mask, prefix, pmask, shift, rl, BLOCK_R, CT), krem, prefix, + pmask, shift, BLOCK_R) + _emit(key, mask, col, prefix, krem, zero, zero, out_col, out_key, r64, P, BLOCK_R, CT) + else: + for shift in tl.static_range(24, -1, -8): + h = tl.zeros((BLOCK_R, 256), tl.int32) + for c0 in range(0, NCOL, CT): + col = c0 + tl.arange(0, CT) + key, mask = _keys(dot, norms, r64, m, col, NCOL, s_d) + h += _count(key, mask, prefix, pmask, shift, rl, BLOCK_R, CT) + krem, prefix, pmask = _pick(h, krem, prefix, pmask, shift, BLOCK_R) + eq_seen, sel_seen = zero, zero + for c0 in range(0, NCOL, CT): + col = c0 + tl.arange(0, CT) + key, mask = _keys(dot, norms, r64, m, col, NCOL, s_d) + eq_seen, sel_seen = _emit(key, mask, col, prefix, krem, eq_seen, sel_seen, out_col, out_key, r64, P, + BLOCK_R, CT) diff --git a/thirdparty/faiss/contrib/e_means/ivf_flat.md b/thirdparty/faiss/contrib/e_means/ivf_flat.md new file mode 100644 index 000000000..cd2443cb6 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_flat.md @@ -0,0 +1,183 @@ +# Optional IVF assignment + +`EmeansShardedCentroidsIVF` keeps the centroid-owner lifecycle and uses the +faithful IVF-Flat candidate-search algorithm. It is an approximate assignment +engine: coarse routing probes `nprobe` lists, then the fine search (`ivf_fine`) +selects within those candidates. It does not replace limited probing with a +full-table assignment. + +```python +from faiss.contrib.e_means import EmeansShardedCentroidsIVF + +model = EmeansShardedCentroidsIVF( + d, global_k, group=group, nlist=256, nprobe=4, + coarse_niter=10, search_workspace_bytes=512 << 20) +model.begin(global_n, local_initial_centroids) +# Existing accumulate/update/end_epoch/finalize lifecycle. +``` + +The class is available from `faiss.contrib.e_means`, +`sharded_centroids.py`, and `sharded_centroids_ivf.py`. Package exports of the +two sharder classes are lazy, so importing the ordinary package does not require +Torch. Accessing either class requires Torch. + +Caller-owned groups, CUDA centroid shards, equal rank contributions and the base +validation/lifecycle rules remain. Quantizers are unsupported. Spherical mode +is rejected before collectives because this score is not the spherical metric. +Coarse training preserves seeded sample membership, FP16 Triton assignment and +distributed reduction. Local lists are rebuilt on the first positive transfer +of each frozen logical batch and shared by later transfers. Global occupancy is +reduced in INT64. During training, each reader routes its local rows before +gathering them. Global winner reduction retains lowest-global-ID ties. + +Fine assignment and split separation use BF16; sums/counts and SSE retain +original FP32 rows. With `unused_threshold=None`, revival uses removal costs +and Oja donor gains. Every eligible candidate moves in cost order; removal costs use +the two best distinct centroids in the probed lists, so they are approximate +when probing is limited. A missing finite second candidate contributes zero +cost, as in the base removal-statistics implementation. + +Each owner retains its removal EMA, batch removal sums and Oja axes. On CUDA, +Triton kernels handle owner accumulation and removal EMA updates even +with the default native assignment backend. The update normalizes axes and +clears batch sums in the same kernel, without a full FP64 vector temporary. +It also caches FP32 axis lengths for the next revival check. Unsupported +statistics layouts retain the ordinary Torch path. Splits invalidate the cache; +the next update refreshes it, or a check before another update recomputes it in +bounded chunks. +Selection sends three FP32 scalars per centroid only to rank 0: 192 MiB for +16M centroids, instead of replicating a 384 MiB FP64 table on every owner. +Rank 0 computes the median threshold and orders removal candidates by cost +and global ID. It selects positive-usage donors outside the candidate set, +ordered by FP32 Oja gain with lowest-global-ID ties. Selected donor and target +IDs are broadcast to the other owners. Split children receive their donor's +halved removal EMA and copied axis. Revival continues through the final pass. +The caller-driven sharder keeps final-pass labels without local `train` +closing handover; closing centroids average the retained post-split rows, and +centroids with no retained rows keep their current positions. This is ordinary +cost finalization. Explicit saved-label closing instead averages the supplied +labels without repair or search, including rows saved before a later split; +their counts must match all final-pass assignments. A fresh closing scan assigns +every supplied row against the final centroid snapshot and averages those new +assignments. +Setting `unused_threshold` explicitly selects mass-based revival (0 disables it). + +Recipe additions include `index_factory`, `nprobe`, `fine_dtype` and +`coarse_query_chunk`. The sharder uses up to 16,384 rows per coarse-routing +chunk, capped by the search workspace budget. + +## Index options and mutable precision policy + +```python +from faiss.contrib.e_means.ivf_flat import IndexIVFFlat + +index = IndexIVFFlat(coarse_centroids, nprobe=4, query_chunk=2048) +index.add(candidates) +scores, ids = index.search_1nn(queries) +# Two distinct candidates, scores/IDs shaped (len(queries), 2): +scores, ids = index.search_2nn(queries) +``` + +The mutable attributes accept only these values: + +| Attribute | Contract | +|---|---| +| `implem` | Integer 1–5. `<2` uses one full query operation; `>=2` chunks queries. `<3` selects native operands; `>=3` selects `dtype`. `>=4` stores only reduced candidates when reduced precision is active. | +| `dtype` | Exactly `"fp16"` or `"bf16"`. Native is selected with `implem < 3`, not another dtype spelling. | +| `lowp_scope` | Exactly `"all"` or `"fine"`. `"fine"` keeps coarse query helpers native while fine search uses the selected reduced precision. | + +Unsupported values, Torch dtype objects and misspellings raise `ValueError`. +Defaults remain `implem=4`, `dtype="fp16"`, `lowp_scope="all"`. + +Add membership and query routing are separate state: + +- CUDA `add` keeps fixed FP16 Triton coarse membership. CPU `add` uses the + effective coarse policy at that call. The resulting membership and list order + stay fixed until the next `add`; later selector changes never relabel rows. +- Routing norms are cached by effective query policy. The next route after an + effective policy change computes norms from the same represented coarse + operands used by its dot product, then reapplies the saved local or global + occupancy. This costs one bounded `nlist*d` norm pass and stores an `nlist` + boolean occupancy copy; it adds no host value scan or synchronization. +- Fine candidate storage records the effective representation used by `add`. + Changes that keep it compatible proceed: `1↔2`, `3↔4↔5`, and any + `lowp_scope` change. Native↔reduced changes require `add` again, as do + FP16↔BF16 changes while reduced precision is effective. Search raises a clear + rebuild error instead of reinterpreting stored bytes. Changing back to the + stored representation is compatible because those bytes were not modified. + +`search_1nn` and `search_2nn` run the fine search of `ivf_fine` on the probed +lists. On CUDA, probes are selected from the coarse scores by an exact radix +select, for any `nlist` and `nprobe` (the lists of `torch.topk`, ordered by +score, lower list IDs first among equal scores); CPU routing uses +`torch.topk`. +`_exact_1nn` and `_exact_topk` construct coherent norms when none are supplied. +Explicitly supplied norms remain caller-authoritative and are used verbatim; +the helper does not reinterpret or silently replace them after a policy change. +Supplied probe IDs likewise retain their existing shape/device conversion rules. + +## Precision and numerical limits + +The fine search accumulates the represented operands in FP32: on CUDA in +16-wide contraction steps in order (the order of a BMM over list widths padded +to multiples of 16), on CPU as FP32 products of the decoded operands. Query norms are omitted from returned scores, so +owners searching the same row can compare scores. Candidate and routing norms +use the representation of their matching dot operands. + +Bit-equal scores retain the lowest row ID. Non-finite scores, which only +overflowing or NaN inputs produce, count as missing. Limited probing and reduced operands remain approximate. +No normalization, clipping or input-value scan is added. + +Caller code that supplies helper norms is responsible for matching them to its +operands. The index guarantees coherence only for automatically constructed +query/candidate norms and its fixed add membership operation. + +## Ownership, aliasing and allocation + +Contiguous FP32 coarse input may alias index storage and must remain fixed for +the index lifetime. No clone or external-mutation detector is added. Candidate +storage is rebuilt by `add`; selector changes never convert it in place. The +index owns its occupancy copy and derived norm caches. Calls on one index share +mutable state, so callers must order stream changes and must not search it +concurrently with mutation/rebuild. + +Returned IDs are INT32 original row IDs. Prefixes/group offsets must fit signed +INT32; exact guards reject larger counts. Empty or no-local-hit search returns +`(+inf, -1)`. Stable sorting, lowest-ID merge and per-owner `ndis`/ +`coarse_ndis` accounting remain. + +The fine search allocates, per routed query/probe pair, two FP32 scores, two +INT64 IDs and the sort and filing entries (about 44 bytes), plus one item +table entry per 64 or 128 pairs. Candidate storage, query representations, coarse scores, +allocator state and base statistics are additional. CPU search uses FP32 +decode temporaries for one list at a time. + +Top-2 search computes each fine dot product once and merges both candidates +across probes. Ties use the lowest candidate ID; missing +results use `inf` and `-1`. Sharded training reduces the global first score and +ID, then performs one additional MIN reduction for the second score. Revival +adds two FP32 tables of shape `(local_k, d + 1)` and one FP32 axis table of +shape `(local_k, d)` per owner. FP8 retains its existing mass-based revival. + +On CUDA, routed pairs are filed by list; each work item scans one list for up +to 64 (Triton) or 128 (CuTe) of its pairs, fusing the distance epilogue and +the running top-2, and a final kernel merges probes once per query. Each pair +owns one result slot, so no atomics touch results. The CuTe kernel runs on SM90 +with BF16 operands and requires its CuTe/quack packages; the Triton kernel returns +the same bits elsewhere and serves FP16 and FP32 operands. CPU search runs the +same algorithm with PyTorch operations. Fine-search dispatch uses architecture +and represented dtype independently of `assignment_backend`. The training IVF +index supplies approximate first/second scores for removal statistics; no +nearest-neighbor protection is applied. + +For CUDA training with the Triton backend, one owner-statistics kernel +accumulates FP32 sums/counts, SSE and removal/Oja statistics directly from the +gathered rows. This avoids materializing owned rows and residual tables. +FP32 atomic additions may change accumulation order; SSE squares remain FP32 +and are summed in FP64. Deterministic mode, custom owner hooks, centered +quantizers and separate closing-mean buffers retain the Torch accumulation. + +The public tests cover selectors, norm coherence, representation transitions, +helpers, ownership and bounded lifecycle cases. CPU results do not qualify CUDA +capture, every deployment geometry, quality or performance. Hardware +qualification is reported separately. diff --git a/thirdparty/faiss/contrib/e_means/ivf_flat.py b/thirdparty/faiss/contrib/e_means/ivf_flat.py new file mode 100644 index 000000000..906be4581 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_flat.py @@ -0,0 +1,350 @@ +# 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. + +"""Torch IVF-Flat assignment, adapted from the reference anns_indexing.py. + +Coarse assignment uses the existing e-means Triton kernel on CUDA. Routing and +the search inside the probed lists run in ivf_fine. +""" + +import contextlib + +import numpy as np +import torch + +from .torch_backend import _get_triton_assign_rows + +def _dot_fp32(x, y): + """Keep represented operands; avoid reduced-precision dot-output rounding.""" + operation = torch.bmm if x.ndim == 3 else torch.mm + if x.dtype in (torch.float16, torch.bfloat16): + if x.is_cuda: + return operation(x, y, out_dtype=torch.float32) + return operation(x.float(), y.float()) + return operation(x, y).float() + + +def _check_int32_count(n, name): + if n > torch.iinfo(torch.int32).max: + raise ValueError(f"{name} must fit signed INT32 offsets") + + +def _assign_body(xq_lp, xb_t_lp, xb_norms): + dis = xb_norms - 2 * _dot_fp32(xq_lp, xb_t_lp) + return dis.min(dim=1) + + +def _topk_body(xq_lp, xb_t_lp, xb_norms, k): + dis = xb_norms - 2 * _dot_fp32(xq_lp, xb_t_lp) + return torch.topk(dis, k, dim=1, largest=False) + + +def _bucket_sort(idx, n): + assert idx.ndim == 1 + _check_int32_count(idx.numel(), "bucket rows") + counts = torch.bincount(idx, minlength=n) + lims = torch.empty(n + 1, dtype=torch.int32, device=idx.device) + lims[0] = 0 + torch.cumsum(counts, dim=0, out=lims[1:]) + buckets = torch.argsort(idx, stable=True) + return buckets, lims + + +class IndexIVFFlat: + """Original native/FP16/BF16 IVF-Flat assignment and list planning. + + Coarse centroids are fixed. Call ``add`` after each EMA update to rebuild + the local lists. A sharded caller supplies global occupancy before routing. + Query norms are omitted from returned scores; scores are comparable across + owners searching the same row. Accumulate SSE against FP32 winning rows. + MM/BMM reduced operands produce FP32 dots. Grouped MM retains original + output precision, including FP16 overflow and BF16 rounding limitations. + """ + + _IMPLEMS = frozenset(range(1, 6)) + _DTYPES = frozenset(("fp16", "bf16")) + _LOWP_SCOPES = frozenset(("all", "fine")) + + @property + def implem(self): + return self._implem + + @implem.setter + def implem(self, value): + if ( + isinstance(value, (bool, np.bool_)) + or not isinstance(value, (int, np.integer)) + or value not in self._IMPLEMS + ): + raise ValueError("implem must be one of 1, 2, 3, 4, or 5") + self._set_precision_selector("_implem", int(value)) + + @property + def dtype(self): + return self._dtype + + @dtype.setter + def dtype(self, value): + if type(value) is not str or value not in self._DTYPES: + raise ValueError("dtype must be 'fp16' or 'bf16'; implem < 3 selects native") + self._set_precision_selector("_dtype", value) + + @property + def lowp_scope(self): + return self._lowp_scope + + @lowp_scope.setter + def lowp_scope(self, value): + if type(value) is not str or value not in self._LOWP_SCOPES: + raise ValueError("lowp_scope must be 'all' or 'fine'") + self._set_precision_selector("_lowp_scope", value) + + def _set_precision_selector(self, name, value): + setattr(self, name, value) + + def __init__( + self, + centroids, + nprobe=4, + *, + query_chunk=2048, + ): + if centroids.ndim != 2 or not len(centroids): + raise ValueError("centroids must be a nonempty matrix") + if not 1 <= nprobe <= len(centroids): + raise ValueError("nprobe must be between 1 and nlist") + if query_chunk < 1: + raise ValueError("query_chunk must be positive") + self.centroids = centroids.float().contiguous() + self.nlist, self.d = centroids.shape + self.nprobe = nprobe + self.query_chunk = query_chunk + self._implem, self._dtype, self._lowp_scope = 4, "fp16", "all" + # Retain the original visible tensor as the fixed FP16 CUDA-add norms. + self.centroids_norms = self._sq_norms(self.centroids, "coarse") + self._query_norms_key = self._query_centroids_norms = None + self._routing_norms_key = self.routing_norms = None + self._routing_nonempty = None + self._fine_storage_key = None + self.ndis = self.coarse_ndis = 0 + self.ids = None + + def _timed(self, name): + return contextlib.nullcontext() + + def _chunk_body(self, kind): + return _assign_body if kind == "assign" else _topk_body + + def _assign_to_coarse(self, x): + if x.is_cuda: + return _get_triton_assign_rows()( + x.half(), self.centroids.half(), self.centroids_norms + )[1].long() + return self._exact_1nn( + x, + self.centroids, + xb_norms=self._current_query_norms(), + stage="coarse", + )[1] + + def search_1nn(self, x, coarse_idx=None): + """Return the scores and IDs of the nearest candidates, shaped (n,).""" + scores, ids = self.search_2nn(x, coarse_idx) + return scores[:, 0].contiguous(), ids[:, 0].contiguous() + + def search_2nn(self, x, coarse_idx=None): + """Return scores and IDs of two distinct candidates, shaped (n, 2). + + Search the routed lists once (ivf_fine), merging both results across + probes. Ties use the lower candidate ID. Missing entries have score inf + and ID -1; query norms are omitted. + """ + if self.ids is None: + raise RuntimeError("add candidates before search") + if x.ndim != 2 or x.shape[1] != self.d: + raise ValueError("queries must have shape (n, d)") + self._check_fine_storage() + _check_int32_count(x.shape[0] * self.nprobe, "routed query rows") + idx = self.route(x) if coarse_idx is None else coarse_idx + if idx.shape != (x.shape[0], self.nprobe): + raise ValueError("coarse_idx must have shape (len(x), nprobe)") + idx = idx.to(device=x.device, dtype=torch.int64) + self.ndis += self.list_sizes[idx.ravel()].sum() + from .ivf_fine import search_2nn + + return search_2nn(self, x, idx) + + def _mm_dtype(self, stage): + assert stage in ("coarse", "fine") + if self.implem < 3: + return None + if stage == "coarse" and self.lowp_scope != "all": + return None + return torch.bfloat16 if self.dtype == "bf16" else torch.float16 + + def _policy_key(self, stage): + dtype = self._mm_dtype(stage) + return "native" if dtype is None else self.dtype + + def _current_query_norms(self): + key = self._policy_key("coarse") + if self._query_norms_key != key: + self._query_centroids_norms = self._sq_norms( + self.centroids, "coarse" + ) + self._query_norms_key = key + return self._query_centroids_norms + + def _current_routing_norms(self): + if self._routing_nonempty is None: + raise RuntimeError("add candidates or set routing occupancy before route") + key = self._policy_key("coarse") + if self._routing_norms_key != key: + norms = self._current_query_norms() + self.routing_norms = torch.where( + self._routing_nonempty, + norms.float(), + torch.full_like(norms, torch.inf, dtype=torch.float32), + ) + self._routing_norms_key = key + return self.routing_norms + + def _check_fine_storage(self): + current = self._policy_key("fine") + if self._fine_storage_key != current: + raise RuntimeError( + "fine precision changed after add; call add again to rebuild " + f"candidate storage ({self._fine_storage_key} -> {current})" + ) + + def _as_computed(self, x, stage): + """Round ``x`` to the precision the selected matmul will see.""" + dt = self._mm_dtype(stage) + return x if dt is None else x.to(dt).float() + + def _sq_norms(self, x, stage): + dtype = torch.float32 if self._mm_dtype(stage) is not None else x.dtype + item_bytes = torch.empty((), dtype=dtype).element_size() + chunk_rows = max(1, (32 * 1024**2) // max(1, x.shape[1] * item_bytes)) + norms = torch.empty(x.shape[0], dtype=dtype, device=x.device) + for begin in range(0, x.shape[0], chunk_rows): + end = min(begin + chunk_rows, x.shape[0]) + norms[begin:end] = ( + self._as_computed(x[begin:end], stage) ** 2 + ).sum(1) + return norms + + def _lowp_operands(self, xb, stage): + """Cast and transpose centroids once rather than once per chunk.""" + dt = self._mm_dtype(stage) + xb_lp = xb if dt is None else xb.to(dt) + return dt, xb_lp.T.contiguous() + + def _exact_1nn(self, xq, xb, xb_norms=None, stage="fine"): + nq, d = xq.shape + nb, d2 = xb.shape + assert d2 == d + if xb_norms is None: + xb_norms = self._sq_norms(xb, stage) + dt, xb_t = self._lowp_operands(xb, stage) + body = self._chunk_body("assign") if stage == "coarse" else _assign_body + chunk_size = self.query_chunk if self.implem >= 2 else nq + if chunk_size >= nq: + return body(xq if dt is None else xq.to(dt), xb_t, xb_norms) + out_dis = torch.empty(nq, dtype=torch.float32, device=xq.device) + out_idx = torch.empty(nq, dtype=torch.int64, device=xq.device) + for i0 in range(0, nq, chunk_size): + i1 = min(i0 + chunk_size, nq) + chunk = xq[i0:i1] if dt is None else xq[i0:i1].to(dt) + out_dis[i0:i1], out_idx[i0:i1] = body(chunk, xb_t, xb_norms) + return out_dis, out_idx + + def _exact_topk(self, xq, xb, k, xb_norms=None, stage="fine"): + nq, d = xq.shape + nb, d2 = xb.shape + assert d2 == d + if xb_norms is None: + xb_norms = self._sq_norms(xb, stage) + dt, xb_t = self._lowp_operands(xb, stage) + body = self._chunk_body("topk") if stage == "coarse" else _topk_body + chunk_size = self.query_chunk if self.implem >= 2 else nq + if chunk_size >= nq: + return body(xq if dt is None else xq.to(dt), xb_t, xb_norms, k) + out_dis = torch.empty((nq, k), dtype=torch.float32, device=xq.device) + out_idx = torch.empty((nq, k), dtype=torch.int64, device=xq.device) + for i0 in range(0, nq, chunk_size): + i1 = min(i0 + chunk_size, nq) + chunk = xq[i0:i1] if dt is None else xq[i0:i1].to(dt) + out_dis[i0:i1], out_idx[i0:i1] = body(chunk, xb_t, xb_norms, k) + return out_dis, out_idx + + def add(self, x): + with self._timed("add"): + self._add(x) + + def _add(self, x): + n, d = x.shape + assert d == self.d + _check_int32_count(n, "candidate rows") + + self.coarse_ndis += int(n) * self.nlist + list_nos = self._assign_to_coarse(x) + order, lims = _bucket_sort(list_nos, self.nlist) + self.list_sizes = lims[1:] - lims[:-1] + self.set_routing_nonempty(self.list_sizes > 0) + self.xb_lims = lims.long() + self.ids = order.int() + dt = self._mm_dtype("fine") + if self.implem >= 4 and dt is not None: + self.vectors = None + self.vectors_lowp = torch.empty_like(x, dtype=dt) + self.vectors_norms = torch.empty( + n, device=x.device, dtype=torch.float32 + ) + rows = max(1, (32 << 20) // max(1, d * x.element_size())) + for begin in range(0, n, rows): + end = min(begin + rows, n) + block = x[order[begin:end]].to(dt) + self.vectors_lowp[begin:end].copy_(block) + self.vectors_norms[begin:end] = self._sq_norms(block, "fine") + else: + self.vectors = x[order] + self.vectors_norms = self._sq_norms(self.vectors, "fine") + self.vectors_lowp = None if dt is None else self.vectors.to(dt) + self._fine_storage_key = self._policy_key("fine") + + def set_routing_nonempty(self, nonempty): + """Probe only lists flagged non-empty (others get +inf distance). + + ``add`` sets the local occupancy. A centroid-sharded caller that + routes rows on one rank for all shards replaces it with the GLOBAL + occupancy (non-empty on any shard), so every shard probes the same + lists and a row still finds a candidate somewhere. + """ + nonempty = nonempty.to(device=self.centroids.device, dtype=torch.bool) + if nonempty.shape != (self.nlist,): + raise ValueError("nonempty must have shape (nlist,)") + self._routing_nonempty = nonempty.clone() + self._routing_norms_key = None + self.routing_norms = None + self._current_routing_norms() + + def route(self, x): + """Return nearest routable lists, shaped ``(n, nprobe)``.""" + self.coarse_ndis += int(x.shape[0]) * self.nlist + with self._timed("coarse"): + if type(self)._chunk_body is IndexIVFFlat._chunk_body: + from . import ivf_fine + + if ivf_fine.route_eligible(self, x): + return ivf_fine.route(self, x) + _, idx = self._exact_topk( + x, + self.centroids, + self.nprobe, + xb_norms=self._current_routing_norms(), + stage="coarse", + ) + return idx diff --git a/thirdparty/faiss/contrib/e_means/ivf_kernels.py b/thirdparty/faiss/contrib/e_means/ivf_kernels.py new file mode 100644 index 000000000..02b7bd599 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/ivf_kernels.py @@ -0,0 +1,59 @@ +# 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. + +"""CUDA per-owner statistics for the IVF-sharded centroids.""" + +import torch +import triton +import triton.language as tl + + +@triton.jit +def _owned_statistics(rows, winners, centroids, axes, stats, removal, margins, objectives, + n, d, k, centroid_begin, row_stride, stats_stride, + COST: tl.constexpr, BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr): + row = tl.program_id(0) * BLOCK_R + tl.arange(0, BLOCK_R) + winner = tl.load(winners + row, mask=row < n, other=-1) + owned = (row < n) & (winner >= centroid_begin) & (winner < centroid_begin + k) + label = (winner - centroid_begin).to(tl.int64) + col = tl.arange(0, BLOCK_D) + live = owned[:, None] & (col < d)[None, :] + value = tl.load(rows + row[:, None].to(tl.int64) * row_stride + col[None, :], mask=live, other=0.0).to(tl.float32) + center = tl.load(centroids + label[:, None] * d + col[None, :], mask=live, other=0.0) + y = value - center + tl.atomic_add(stats + label[:, None] * stats_stride + col[None, :], value, mask=live, sem="relaxed") + tl.atomic_add(stats + label * stats_stride + d, 1.0, mask=owned, sem="relaxed") + # Square in FP32, then sum in FP64, as the ordinary owner SSE. + squared = (y * y).to(tl.float64) + tl.store(objectives + tl.program_id(0), tl.sum(tl.sum(squared, axis=1), axis=0)) + if COST: + axis = tl.load(axes + label[:, None] * d + col[None, :], mask=live, other=0.0) + p = tl.sum(y * axis, axis=1) + tl.atomic_add(removal + label[:, None] * stats_stride + col[None, :], p[:, None] * y, mask=live, sem="relaxed") + margin = tl.load(margins + row, mask=owned, other=0.0) + margin = tl.where(margin == float("-inf"), -3.4028234663852886e38, margin) + margin = tl.where((margin == margin) & (margin < float("inf")), margin, 0.0) + tl.atomic_add(removal + label * stats_stride + d, margin, mask=owned, sem="relaxed") + + +def accumulate_owned(rows, winners, centroids, axes, stats, removal, objective, margins, centroid_begin): + """Accumulate owner sums/counts, SSE and Oja/removal sums in one row pass.""" + if (stats.dtype != torch.float32 or rows.dtype not in (torch.float32, torch.bfloat16) + or rows.shape[1] > 4096 or rows.stride(1) != 1 or stats.stride(1) != 1 + or torch.are_deterministic_algorithms_enabled()): + return False + block_d = triton.next_power_of_2(rows.shape[1]) + block_r = 4 if block_d <= 1024 else 1 + blocks = triton.cdiv(len(rows), block_r) + if blocks: + partial = objective.new_empty(blocks) + with torch.cuda.device(rows.device): + _owned_statistics[(blocks,)]( + rows, winners, centroids, axes, stats, removal, margins, partial, + len(rows), rows.shape[1], len(centroids), centroid_begin, rows.stride(0), stats.stride(0), + COST=margins is not None, BLOCK_R=block_r, BLOCK_D=block_d, + num_warps=4 if block_d <= 2048 else 8, enable_fp_fusion=False) + objective.add_(partial.sum()) + return True diff --git a/thirdparty/faiss/contrib/e_means/quantizer.py b/thirdparty/faiss/contrib/e_means/quantizer.py new file mode 100644 index 000000000..501f1d59f --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/quantizer.py @@ -0,0 +1,181 @@ +# 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. + +"""Torch casts and affine arithmetic for represented-value GPU E-means. + +Codes are native Torch tensors, not packed CPU bytes. Conversion and decoding +check metadata only. Call validate explicitly for finite/range checks; it may +synchronize. Helpers can execute on CPU, but CPU E-means requires quantizer=None. +""" + +import torch + + +class CastQuantizer: + """Round floating rows to FP16 or BF16, optionally after an explicit fit. + + ``center=False`` preserves the stateless cast and no-op train. With + ``center=True``, train a representative sample before encoding, then place + the fitted centre on the input device with to. Codes represent x - shift; + decode restores original FP32 coordinates before model statistics. + Matching model-input dtype means preencoded codes; compute_codes itself + always takes original coordinates, even when its input already has that + dtype. Widening rounded source data cannot recover lost information. + + The owned shift is read-only. Explicit refitting/moving invalidates models + bound to the previous fit; do it before a new run, never during a run or + while a graph/reader uses it. Calls share parameters and require ordering. + Values must be finite and fit the target after centering. Fit/conversion + do not validate values; validate explicitly. Centering is L2-only. + """ + + def __init__(self, d, dtype, *, center=False): + self.d = int(d) + if self.d < 1: + raise ValueError("d must be positive") + if dtype not in (torch.float16, torch.bfloat16): + raise ValueError("dtype must be torch.float16 or torch.bfloat16") + if not isinstance(center, bool): + raise TypeError("center must be a bool") + self.dtype = dtype + self.code_size = 2 * self.d + self._center = center + self._shift = None + self._generation = 0 + self._shift_version = None + self.is_trained = not center + + @property + def center(self): + """Whether explicit centering is enabled (independent of its values).""" + return self._center + + @property + def shift(self): + """Borrow the fitted FP32 centre; do not mutate it.""" + return self._shift + + def train(self, sample=None): + """Fit an owned centre explicitly, without numerical value checks. + + With centering disabled this remains a no-op. Prefer original FP32 + training rows. FP64 mean accumulation is narrowed once to FP32; no + automatic sampling, model-time fit or input-dependent policy is used. + Nonfinite data follows Torch reduction semantics. Call validate after + fitting for explicit finite/range checks; validation may synchronize. + """ + if not self.center: + return + self.is_trained = False + self._shift = self._shift_version = None + self._generation += 1 + sample = self._matrix(sample, fitting=True) + if not len(sample): + raise ValueError("sample must not be empty") + if sample.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("sample must be FP32, FP16 or BF16") + # Normal owned parameters retain a mutation version even if the caller + # fits inside inference_mode. Input rows are detached, never changed. + with torch.inference_mode(False), torch.no_grad(): + shift = sample.mean(dim=0, dtype=torch.float64).float().contiguous() + self._shift = shift + self._shift_version = shift._version + self.is_trained = True + + def _fit_token(self): + """Metadata-only identity of one immutable fitted parameter tensor.""" + if not self.center: + return None + if not self.is_trained or self.shift is None: + raise RuntimeError("centered quantizer must be trained explicitly") + if self.shift._version != self._shift_version: + raise RuntimeError("quantizer centre is frozen; train explicitly to refit") + return self._generation, id(self.shift), self.shift._version, self.shift.device + + def to(self, device): + """Place fitted parameters explicitly; stateless casts still return self.""" + device = torch.device(device) + if device.type not in ("cpu", "cuda"): + raise ValueError("device must be CPU or CUDA") + if self.center: + self._fit_token() + if self.shift.device != device: + with torch.inference_mode(False), torch.no_grad(): + shift = self.shift.to(device) + if shift is not self.shift: + self._shift = shift + self._generation += 1 + self._shift_version = shift._version + return self + + def _matrix(self, x, *, fitting=False): + if not isinstance(x, torch.Tensor): + raise TypeError("x must be a torch.Tensor") + if x.layout != torch.strided or x.ndim != 2 or x.shape[1] != self.d: + raise ValueError("x must be a dense (n, d) tensor") + if x.device.type not in ("cpu", "cuda"): + raise ValueError("x must be on CPU or CUDA") + if self.center and not fitting: + self._fit_token() + if x.device != self.shift.device: + raise ValueError("x and quantizer centre must be on the same device") + return x.detach() + + def _center_rows(self, x): + x = self._matrix(x) + return x.float().sub(self.shift) if self.center else x + + def compute_codes(self, x): + """Return native represented rows, without a value scan.""" + x = self._matrix(x) + if x.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("x must be FP32, FP16 or BF16") + return (x.float().sub(self.shift) if self.center else x).to(self.dtype).contiguous() + + def decode(self, codes): + """Decode matching codes to original FP32 rows; never decode model state.""" + codes = self._matrix(codes) + if codes.dtype != self.dtype: + raise TypeError("codes must have the quantizer dtype") + value = codes.float() + return (value.add_(self.shift) if self.center else value).contiguous() + + def validate(self, x): + """Check codes, or original nonmatching floats after centering. + + Matching dtype means codes, just as in model input. For original rows + already in that dtype, widen explicitly before this check. With + centering enabled, also check that the fitted centre and decoded + original FP32 rows are finite, including target-format rounding. + """ + x = self._matrix(x) + if x.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("x must be FP32, FP16 or BF16") + value = (x.float().sub(self.shift) if self.center and x.dtype != self.dtype else x.float()) + valid = (value.abs() <= torch.finfo(self.dtype).max).all() + if self.center: + codes = x if x.dtype == self.dtype else self.compute_codes(x) + valid = valid & torch.isfinite(self.shift).all() & torch.isfinite(self.decode(codes)).all() + if not bool(valid): + message = "x must be finite and fit the quantizer range" + if self.center: + message += " and decode to finite original FP32 values" + raise ValueError(message) + + +def _ldexp(value, exponent): + # Stock CUDA ldexp can launch on the current device rather than the operand's. + if value.is_cuda: + with torch.cuda.device(value.device): + return torch.ldexp(value, exponent) + return torch.ldexp(value, exponent) + + +def _transform(value, quantizer): + if quantizer is None: + return value + if quantizer._bias is None: + return value * quantizer.scale + return torch.add(quantizer._bias, value, alpha=quantizer.scale) diff --git a/thirdparty/faiss/contrib/e_means/quantizer_fp8.py b/thirdparty/faiss/contrib/e_means/quantizer_fp8.py new file mode 100644 index 000000000..326deea08 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/quantizer_fp8.py @@ -0,0 +1,246 @@ +# 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. + +"""Fit and validate the shared affine transform for E4M3 assignment.""" + +import math + +import torch + +from .quantizer import _ldexp, _transform + + +_CENTER_GAIN = 1.5 +_FIT_ROWS = 262144 +_FORMAT_MAX = 448.0 +_NEAR_PARITY = 0.001 +_PROBE_CENTROIDS = 1024 +_PROBE_ROWS = 2048 +_TARGET_PEAK = 56.0 + + +def _check_fp8_range(peak, name): + if not (float(peak) <= _FORMAT_MAX): + raise ValueError("%s exceeds the E4M3 representable range" % name) + + +def _check_fp8_support(device): + """Reject devices that cannot execute the E4M3 assignment path.""" + if getattr(torch, "float8_e4m3fn", None) is None: + raise RuntimeError("PyTorch does not provide float8_e4m3fn") + if device.type != "cuda": + raise ValueError("float8_e4m3fn assignment requires a CUDA tensor") + capability = torch.cuda.get_device_capability(device) + if ( + getattr(torch.version, "hip", None) is not None + or capability not in ((9, 0), (10, 0), (10, 3)) + ): + raise RuntimeError( + "float8_e4m3fn assignment requires an NVIDIA SM90, SM100, " + "or SM103 GPU" + ) + + +def _rounded(value, shift, scale): + if shift is not None: + value = value - shift + return (value * scale).to(torch.float8_e4m3fn).float() + + +def _excess_distortion(x, centroids, shift, scale, reference, best): + xq, cq = (_rounded(v, shift, scale).double() for v in (x, centroids)) + score = cq.square().sum(dim=1)[None, :] - 2.0 * (xq @ cq.T) + labels = score.argmin(dim=1) + row = torch.arange(len(x), device=x.device) + chosen = reference[row, labels] + x.double().square().sum(dim=1) + excess = float(chosen.clamp_min(0).sum()) - best + return excess / best if best > 0 else float(excess > 0.0) + + +class Fp8Quantizer: + """Calibrate one coordinate shift and one global power-of-two E4M3 scale. + + train uses a representative sample; to moves parameters explicitly. The + caller must not retrain or move this quantizer during an E-means run. + """ + + def __init__(self, d): + self.d = int(d) + if self.d < 1: + raise ValueError("d must be positive") + self.dtype = getattr(torch, "float8_e4m3fn", None) + self.code_size = self.d + self.is_trained = False + self.shift = self.scale = self._bias = self.exponent = None + self._decode_exponent = self._distance_exponent = None + self.device = None + + def _matrix(self, x, name, allow_empty=True): + if not isinstance(x, torch.Tensor): + raise TypeError("%s must be a torch.Tensor" % name) + if (x.layout != torch.strided or x.ndim != 2 or x.shape[1] != self.d + or (not allow_empty and not len(x))): + raise ValueError("%s must be a dense (n, d) tensor" % name) + if x.device.type not in ("cpu", "cuda"): + raise ValueError("%s must be on CPU or CUDA" % name) + return x.detach() + + def train(self, sample): + """Fit the existing bounded plain/centered quality selector.""" + self.is_trained = False + self.shift = self.scale = self._bias = self.exponent = None + self._decode_exponent = self._distance_exponent = None + self.device = None + sample = self._matrix(sample, "sample", allow_empty=False) + if sample.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("sample must be FP32, FP16 or BF16") + if self.dtype is None: + raise RuntimeError("PyTorch does not provide float8_e4m3fn") + sample = sample[:_FIT_ROWS].float() + minimum, maximum = torch.aminmax(sample, dim=0) + if not bool((torch.isfinite(minimum) & torch.isfinite(maximum)).all()): + raise ValueError("sample must be finite") + plain_peak = float(torch.maximum(minimum.abs(), maximum.abs()).max()) + shift = sample.mean(dim=0) + if not bool(torch.isfinite(shift).all()): + raise ValueError("the quantizer shift must be finite") + center_peak = float(torch.maximum( + (minimum - shift).abs(), (maximum - shift).abs() + ).max()) + if not math.isfinite(center_peak): + raise ValueError("the centered sample peak must be finite") + plain_exp, center_exp = ( + 0 if peak == 0 else math.floor(math.log2(_TARGET_PEAK / peak)) + for peak in (plain_peak, center_peak) + ) + plain_scale, center_scale = 2.0**plain_exp, 2.0**center_exp + probe = sample[:min(len(sample), _PROBE_ROWS + _PROBE_CENTROIDS)] + if len(probe) < _PROBE_ROWS: + plain_excess = centered_excess = None + centered, decision = True, "small_sample_centered" + else: + x, centroids = probe[:-_PROBE_CENTROIDS], probe[-_PROBE_CENTROIDS:] + # Reuse identical FP64 reference arithmetic for both candidates. + reference = (centroids.double().square().sum(dim=1)[None, :] + - 2.0 * (x.double() @ centroids.double().T)) + row = torch.arange(len(x), device=x.device) + best = float((reference[row, reference.argmin(dim=1)] + + x.double().square().sum(dim=1)).clamp_min(0).sum()) + plain_excess = _excess_distortion( + x, centroids, None, plain_scale, reference, best + ) + centered_excess = _excess_distortion( + x, centroids, shift, center_scale, reference, best + ) + if plain_excess * 2.0 <= _NEAR_PARITY: + centered, decision = False, "uncentered_near_parity" + elif centered_excess <= 0.0 < plain_excess: + centered, decision = True, "centered_nonpositive_excess" + elif centered_excess > 0.0 and plain_excess / centered_excess >= _CENTER_GAIN: + centered, decision = True, "centered_gain" + else: + centered, decision = False, "uncentered_insufficient_gain" + if min(plain_excess, centered_excess) > _NEAR_PARITY: + decision += ";both_above_quality_gate" + scale = center_scale if centered else plain_scale + if (center_exp if centered else plain_exp) > 127: + raise ValueError("the quantizer scale exceeds the FP32 range") + selected_shift = shift.contiguous() if centered else None + bias = None if selected_shift is None else -(selected_shift * scale) + if bias is not None and not bool(torch.isfinite(bias).all()): + raise ValueError("the quantizer bias must be finite") + self.shift, self._bias = selected_shift, bias + self.scale = scale + self.exponent = center_exp if centered else plain_exp + self.device = sample.device + # Stage two tiny scalar parameters only during calibration/placement. + self._decode_exponent = torch.tensor( + -self.exponent, dtype=torch.int32, device=self.device + ) + self._distance_exponent = 2 * self._decode_exponent + self.centered, self.decision = centered, decision + self.fit_rows = len(sample) + self.sample_peak = center_peak if centered else plain_peak + self.plain_excess, self.centered_excess = plain_excess, centered_excess + self.is_trained = True + self.validate(sample) + + def _validate(self, x, name): + if not self.is_trained: + raise RuntimeError("quantizer must be trained") + x = self._matrix(x, name) + if x.device != self.device: + raise ValueError("%s and quantizer must be on the same device" % name) + return x + + def to(self, device): + """Move calibrated parameters in place and return self.""" + if not self.is_trained: + raise RuntimeError("quantizer must be trained") + device = torch.device(device) + if device.type not in ("cpu", "cuda"): + raise ValueError("device must be CPU or CUDA") + if self.shift is not None: + self.shift = self.shift.to(device) + self._bias = self._bias.to(device) + self._decode_exponent = self._decode_exponent.to(device) + self._distance_exponent = self._distance_exponent.to(device) + self.device = self._decode_exponent.device + return self + + def compute_codes(self, x): + """Encode floating rows, without clipping or a value scan.""" + x = self._validate(x, "x") + if x.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("x must be FP32, FP16 or BF16") + return _transform(x.float(), self).to(self.dtype).contiguous() + + def decode(self, codes): + """Decode E4M3 codes or floating code coordinates to FP32 units.""" + codes = self._validate(codes, "codes") + if codes.dtype not in (self.dtype, torch.float32): + raise TypeError("codes must be E4M3 or FP32") + value = _ldexp(codes.float(), self._decode_exponent) + return value if self.shift is None else value.add(self.shift) + + def validate(self, x): + """Explicit finite/transformed-range check; may synchronize.""" + x = self._validate(x, "x") + if x.dtype == self.dtype: + value = x.float() + elif x.dtype in (torch.float32, torch.float16, torch.bfloat16): + value = _transform(x.float(), self) + else: + raise TypeError("x must be floating rows or E4M3 codes") + if len(value): + _check_fp8_range(float(value.abs().max()), "x") + + +def _update_fp8_peak(transformed, peak_out): + # Retain the existing internal-centroid guard, without scanning caller rows. + peak = transformed.abs().max() + torch.maximum(peak_out, peak, out=peak_out) + + +def separate_splits(donor, child, quantizer): + """Change child coordinate zero only for coincident E4M3 code rows.""" + donor_q, child_q = ( + _transform(x, quantizer).to(torch.float8_e4m3fn) for x in (donor, child) + ) + # Torch has no E4M3 nextafter. Move sign/magnitude bits toward +infinity, + # inward from +448, or from +/-0 to +2**-9. No dynamic row list/host read. + collapsed = (donor_q.float() == child_q.float()).all(dim=1) + bits = child_q[:, 0].contiguous().view(torch.uint8).to(torch.int16) + adjacent = torch.where(bits >= 128, bits - 1, bits + 1) + adjacent = torch.where(bits == 126, 125, adjacent) + adjacent = torch.where((bits == 0) | (bits == 128), 1, adjacent) + value = adjacent.to(torch.uint8).view(torch.float8_e4m3fn).float() + if quantizer is not None: + value = _ldexp(value, quantizer._decode_exponent) + if quantizer.shift is not None: + value = value + quantizer.shift[0] + # A finite E4M3 neighbor may decode beyond FP32 range at tiny scales. + # Retain the ordinary child when this single replacement is invalid. + child[:, 0] = torch.where(collapsed & torch.isfinite(value), value, child[:, 0]) diff --git a/thirdparty/faiss/contrib/e_means/quantizer_int8.py b/thirdparty/faiss/contrib/e_means/quantizer_int8.py new file mode 100644 index 000000000..13f1a9273 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/quantizer_int8.py @@ -0,0 +1,212 @@ +# 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. + +"""Native-byte helpers for INT8 E-means assignment. + +Floating corpora can be converted explicitly before training:: + + from faiss.contrib.e_means import QuantizedEmeans + from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer + q = Int8Quantizer(x.shape[1]) + q.train(representative_sample) + q.to(x.device) + x_i8 = q.compute_codes(x) + model = QuantizedEmeans(x.shape[1], k, quantizer=q, assignment_backend="triton") + model.train(x_i8) + source_centroids = model.centroids # already decoded FP32 + +The quantizer trains a per-coordinate FP32 shift and one global power-of-two +scale. One global scale preserves L2 geometry before rounding; separate scales +would reweight the coordinates. ``compute_codes`` processes internal chunks, +rounds, and clips to INT8. Finite outliers clip. Value checks are explicit +through validate; unchecked nonfinite values have no meaningful result. + +With quantizer=q, E-means consumes matching native INT8 codes and returns +FP32 centroids/distances in decoded units. Floating-to-INT8 JIT is unsupported. +Without q, native INT8/UINT8 define raw numeric units; in that raw-code workflow +q.decode(model.centroids) explicitly converts signed code-coordinate outputs. +Helpers execute on CPU or CUDA; CPU E-means still requires FP32/q=None. +""" + +import math + +import torch + +from .quantizer import _ldexp, _transform + + +_ENCODE_CHUNK_ELEMENTS = 8 * 1024 * 1024 +_TARGET_PEAK = 112.0 + + +def _matrix(x, name): + if not isinstance(x, torch.Tensor): + raise TypeError("%s must be a torch.Tensor" % name) + if x.layout != torch.strided or x.ndim != 2: + raise ValueError("%s must be a dense 2-D tensor" % name) + if x.shape[1] == 0: + raise ValueError("%s must not be empty" % name) + if x.device.type not in ("cpu", "cuda"): + raise ValueError("%s must be on a CPU or CUDA device" % name) + return x.detach() + + +class Int8Quantizer: + """An explicit affine preprocessor for floating-point corpora.""" + + def __init__(self, d): + self.d = int(d) + if self.d < 1: + raise ValueError("d must be positive") + self.dtype = torch.int8 + self.code_size = self.d + self.is_trained = False + self.shift = None + self.scale = None + self._bias = None + self.exponent = self._decode_exponent = self._distance_exponent = None + + def train(self, sample): + """Train from a representative floating-point sample.""" + self.is_trained = False + self.shift = None + self.scale = None + self._bias = None + self.exponent = self._decode_exponent = self._distance_exponent = None + sample = _matrix(sample, "sample") + if not len(sample): + raise ValueError("sample must not be empty") + if sample.shape[1] != self.d: + raise ValueError("sample has the wrong dimension") + if sample.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("sample must be FP32, FP16, or BF16") + sample = sample.float() + if not bool(torch.isfinite(sample).all()): + raise ValueError("sample must be finite") + shift = sample.mean(dim=0) + if not bool(torch.isfinite(shift).all()): + raise ValueError("the quantizer shift must be finite") + peak = float((sample - shift).abs().max()) + if not math.isfinite(peak): + raise ValueError("the centered sample peak must be finite") + exponent = 0 if peak == 0.0 else math.floor( + math.log2(_TARGET_PEAK / peak) + ) + if exponent > 127: + raise ValueError("the quantizer scale exceeds the FP32 range") + scale = 2.0**exponent + bias = -(shift * scale) + if not bool(torch.isfinite(bias).all()): + raise ValueError("the quantizer bias must be finite") + self.shift = shift.contiguous() + self.scale = float(scale) + self._bias = bias.contiguous() + self.exponent = exponent + self._decode_exponent = torch.tensor( + -exponent, dtype=torch.int32, device=sample.device + ) + self._distance_exponent = 2 * self._decode_exponent + self.is_trained = True + + def _validate(self, x, name): + if not self.is_trained: + raise RuntimeError("quantizer must be trained") + x = _matrix(x, name) + if x.device != self.shift.device: + raise ValueError( + "%s and quantizer must be on the same device" % name + ) + if x.shape[1] != self.d: + raise ValueError("%s has the wrong dimension" % name) + return x + + def compute_codes(self, x): + """Compute signed-byte codes in bounded internal chunks.""" + x = self._validate(x, "x") + if x.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("x must be FP32, FP16, or BF16") + codes = torch.empty(x.shape, dtype=torch.int8, device=x.device) + chunk_rows = max(1, _ENCODE_CHUNK_ELEMENTS // self.d) + for begin in range(0, len(x), chunk_rows): + end = begin + chunk_rows + value = torch.add( + self._bias, x[begin:end].float(), alpha=self.scale + ) + value.round_().clamp_(-128, 127) + codes[begin:end].copy_(value.to(torch.int8)) + return codes + + def decode(self, value): + """Restore INT8 codes or FP32 learned state to source coordinates.""" + value = self._validate(value, "value") + if value.dtype not in (torch.int8, torch.float32): + raise TypeError("value must be INT8 or FP32") + return _ldexp(value.float(), self._decode_exponent).add(self.shift) + + def to(self, device): + """Move calibrated parameters in place and return self.""" + if not self.is_trained: + raise RuntimeError("quantizer must be trained") + device = torch.device(device) + if device.type not in ("cpu", "cuda"): + raise ValueError("device must be CPU or CUDA") + self.shift = self.shift.to(device) + self._bias = self._bias.to(device) + self._decode_exponent = self._decode_exponent.to(device) + self._distance_exponent = self._distance_exponent.to(device) + return self + + def validate(self, x): + """Explicit finite-under-transform check; finite outliers may clip.""" + x = self._validate(x, "x") + if x.dtype == torch.int8: + return # Every native signed-byte code is finite. + if x.dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("x must be INT8, FP32, FP16 or BF16") + if not bool(torch.isfinite(_transform(x.float(), self)).all()): + raise ValueError("x must be finite under the quantizer transform") + + +def _check_int8_support(device): + """Reject devices outside the qualified INT8 assignment targets.""" + if device.type != "cuda": + raise ValueError("INT8 assignment requires a CUDA tensor") + capability = torch.cuda.get_device_capability(device) + if ( + getattr(torch.version, "hip", None) is not None + or capability not in ((8, 0), (9, 0), (10, 0)) + ): + raise RuntimeError( + "INT8 assignment requires an NVIDIA SM80, SM90, or SM100 GPU" + ) + + +def representation(dtype): + if dtype == torch.int8: + return "int8" + if dtype == torch.uint8: + return "uint8" + raise TypeError("INT8 assignment requires INT8 or UINT8 input") + + +def quantize(value, representation, quantizer=None): + value = _transform(value.float(), quantizer) + if representation == "uint8": + value = value - 128.0 + return value.round().clamp(-128, 127).to(torch.int8) + + +def separate_splits(donor, child, representation, quantizer=None): + """Move child coordinate zero only when signed-code rows coincide.""" + donor_q, child_q = (quantize(x, representation, quantizer) for x in (donor, child)) + collapsed = (donor_q == child_q).all(dim=1) + value = child_q[:, 0].to(torch.int16) + neighbor = torch.where(value < 127, value + 1, value - 1).float() + if quantizer is not None: + neighbor = _ldexp(neighbor, quantizer._decode_exponent) + neighbor = neighbor + quantizer.shift[0] + elif representation == "uint8": + neighbor += 128.0 + child[:, 0] = torch.where(collapsed & torch.isfinite(neighbor), neighbor, child[:, 0]) diff --git a/thirdparty/faiss/contrib/e_means/sharded_centroids.py b/thirdparty/faiss/contrib/e_means/sharded_centroids.py new file mode 100644 index 000000000..ca00d3cfb --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/sharded_centroids.py @@ -0,0 +1,977 @@ +# 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. + +"""E-means with caller-owned groups and contiguous centroid ownership.""" + +import math +import time +import inspect + +import torch +import torch.distributed as dist + +from .base import _REMOVAL_THRESHOLD, _SPLIT_GAIN, _divisibility_error, _epoch_seed, _resolve_recipe, _same_operation +from .e_means_quantized import QuantizedEmeans, check_codec_fit, statistics_values +from .e_means_torch import _accumulate_removal_rows, _closing_centroid_values, _torch_generator +from .e_means_distributed import _check_group + +# Lazy access to the moved IVF class. +__all__ = [ # noqa: F822 + "math", "torch", "dist", "EmeansShardedCentroids", + "EmeansShardedCentroidsIVF", +] + + +def __getattr__(name): + if name == "EmeansShardedCentroidsIVF": + from .sharded_centroids_ivf import EmeansShardedCentroidsIVF + return EmeansShardedCentroidsIVF + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def _removal_scalar_stats(removal_stats, usage, *, chunk_rows=None): + """Gather local [removal cost, usage, axis norm] in bounded FP64 chunks.""" + if chunk_rows is None: + # vector_norm(dtype=FP64) can widen its strided input; cap that + # temporary at 64 MiB rather than converting the full (k, d) table. + chunk_rows = max(1, (64 << 20) // (8 * (removal_stats.shape[1] - 1))) + if chunk_rows < 1: + raise ValueError("norm chunk_rows must be positive") + scalars = torch.empty( + (len(usage), 3), dtype=torch.float64, device=usage.device + ) + for begin in range(0, len(usage), chunk_rows): + end = min(begin + chunk_rows, len(usage)) + block = removal_stats[begin:end] + scalars[begin:end, 0].copy_(block[:, -1]) + scalars[begin:end, 1].copy_(usage[begin:end]) + scalars[begin:end, 2].copy_(torch.linalg.vector_norm( + block[:, :-1], dim=1, dtype=torch.float64 + )) + return scalars + + +def _removal_candidates(removal): + """Threshold by the FP64 median, sorting only candidates by cost then ID.""" + n = len(removal) + if not n: + return torch.empty(0, dtype=torch.int64, device=removal.device) + lower = torch.kthvalue(removal, (n + 1) // 2).values.double() + upper = torch.kthvalue(removal, n // 2 + 1).values.double() if n % 2 == 0 else lower + median = torch.where(removal.isnan().any(), torch.nan, (lower + upper) / 2) + candidates = torch.nonzero( + (removal <= 0) | (removal.double() < _REMOVAL_THRESHOLD * median) + ).flatten() + return candidates[torch.argsort(removal[candidates], stable=True)] + + +def _removal_version(stats): + try: + return id(stats), stats._version + except RuntimeError: # Inference tensors have no version counter. + return id(stats), None + + +def _partial_removal_donors(kept, usage, axis_norm): + """GPU partial donor selection, ordered by FP32 gain then global ID. + + Find the kth score without sorting the full table. Recover cutoff ties + in ID order before sorting only the selected donors. NaNs sort last, + matching the host stable argsort. + """ + eligible = usage > 0 + kept = torch.as_tensor(kept, dtype=torch.int64, device=usage.device) + eligible[kept] = False + n = min(len(kept), int(eligible.sum())) + if not n: + return kept.new_empty(0) + score = torch.where(eligible, -axis_norm.float(), torch.inf) + score.nan_to_num_(nan=torch.inf, posinf=torch.inf, neginf=-torch.inf) + cutoff = torch.kthvalue(score, n).values + better = torch.nonzero(eligible & (score < cutoff)).flatten() + tied = torch.nonzero(eligible & (score == cutoff)).flatten() + chosen = torch.cat((better, tied[:n - len(better)])) + # nonzero gives ascending IDs, including within the cutoff tie. Stable + # sorting preserves that order for equal gains above the cutoff too. + return chosen[torch.argsort(score[chosen], stable=True)] + + +class EmeansShardedCentroids(QuantizedEmeans): + """Train resident rank-local rows against sharded CUDA centroids. + + ``k`` at construction is global; ``k`` on the instance and ``centroids`` + describe the local shard. ``global_k`` and ``centroid_begin`` locate it. + ``begin`` takes only this rank's FP32 centroid shard. All ranks must use + identical parameters and enter the lifecycle in the same order. Row + contributions must have equal sizes; global batches, row counts and + centroid counts must be divisible by the group size. Communication uses + one full-batch all-gather; + centroid tables and EMA statistics stay with their owners. + + Accumulate matching rank-local chunks until the prescribed local share is + complete, then update once. Public statistics n counts global contributed + rows; sums/counts describe owned centroids. Last-pass labels describe only + this caller's supplied rows, using global centroid IDs. + Native None requires a common native dtype. Explicit codecs gather codes + in their shared dtype and decode them for owner statistics. Ordinary obj + is direct SSE from decoded rows to the FP32 working centroids. + All admitted representations default to removal-cost revival with + Oja-ranked donors. Custom floating _assign_rows overrides must accept the + keyword-only scores request and return its raw keys; incompatible call + signatures fail during snapshot setup. Owners compare pre-row-norm keys; + encoded integers compare raw INT64 + distances, and FP8 retains completed hierarchical candidates. Top-2 + assignment adds one MIN reduction per batch; selection gathers scalar + statistics across all centroid shards; the paying prefix moves in cost order. + Caller-driven batches retain final-pass labels without local train closing handover. + """ + + def _resolve_removal_revival(self): + super()._resolve_removal_revival() + + def __init__(self, d, k, *args, group, **kwargs): + ranks = _check_group(group) + if kwargs.get("max_points_per_centroid") is not None: + raise ValueError( + "max_points_per_centroid is not supported with sharded " + "centroids; subsample x_local before train" + ) + if k < ranks or k % ranks: + raise ValueError("k must be positive and divisible by group size") + self.global_k = int(k) + self._group, self._group_size = group, ranks + self._rank = dist.get_rank(group) + self.centroid_begin = (self.global_k // ranks) * self._rank + end = self.centroid_begin + self.global_k // ranks + super().__init__(d, end - self.centroid_begin, *args, **kwargs) + self._discarded_closing_counts = None + self._score_hooks_checked = False + + def _resolve_first_input(self, x): + """Agree the first automatic gathered row dtype before allocation. + + Every rank must allocate and interpret gathered rows using the same + dtype. This agreement prevents peer rows being read in different units. + Automatic FP32 and mixed FP32/BF16 first inputs select BF16 casting + on every rank. Uniform other dtypes stay native. Incompatible mixtures + fail together. Typed empty inputs also participate in this agreement. + """ + if not self._automatic or self._input_dtype is not None: + self._resolve_input_dtype(x) + return + try: + types = (torch.float32, torch.float16, torch.bfloat16, + torch.float8_e4m3fn, torch.int8, torch.uint8) + code = types.index(x.dtype) if x.dtype in types else -1 + peers = self._gather_local(torch.tensor([code], device=x.device)).tolist() + if -1 in peers: + raise ValueError("unsupported first automatic population representation") + seen = {types[code] for code in peers} + if torch.float32 in seen and seen <= {torch.float32, torch.bfloat16}: + self._bind_input_dtype(torch.bfloat16, cast=True) + elif len(seen) == 1: + self._bind_input_dtype(types[peers[0]]) + else: + raise ValueError("incompatible first automatic population representations") + except BaseException: + self._failed = True + self.assignments = None + raise + + def accumulate(self, x): + self._require_running() + self._resolve_first_input(x) + x = self._prepare_input(x) + return self._accumulate(x.detach()) + + def _get_assignment_chunk_size(self): + state = self._centroids if self._centroids is not None else self.centroids + if self.assignment_backend == "auto" and state.is_cuda and self.assignment_chunk_size is None: + # Keep the native compute bound, independent of compute choice. + width = max(self.d, min(self.k, self.centroid_chunk_size)) + return min(2**20, max(8192, 2**26 // width)) + return super()._get_assignment_chunk_size() + + def begin(self, global_n, init_centroids): + if self._failed or self.recipe is not None: + raise RuntimeError("create a new object for another run or after failure") + if global_n < self.global_k: + raise ValueError("global_n must be at least global_k") + if not isinstance(init_centroids, torch.Tensor) or not init_centroids.is_cuda: + raise ValueError("sharded centroids require CUDA tensors") + try: + if not self._automatic and self.quantizer is not None: + check_codec_fit(self._group, self.quantizer, init_centroids.device) + super().begin(global_n, init_centroids) + except BaseException: + self._failed = True + self.assignments = None + raise + batch, alpha = _resolve_recipe( + self._n, + self.global_k, + self.nepochs, + self._batch_law_resolved, + self.batch_size, + self.alpha0, + ) + if (self._n % self._group_size or batch % self._group_size + or any(rows % self._group_size for rows in self.recipe["epoch_rows"])): + self._failed = True + raise _divisibility_error(self.recipe, self._n, batch, self._group_size) + steps = math.ceil(self._n / batch) + epoch_steps = [math.ceil(rows / batch) for rows in self.recipe["epoch_rows"]] + self.recipe.update( + batch_size=batch, + alpha0=alpha, + steps_per_pass=steps, + epoch_steps=epoch_steps, + total_steps=sum(epoch_steps), + global_k=self.global_k, + centroid_begin=self.centroid_begin, + centroid_shards=self._group_size, + batch_transport="all_gather", + ) + + def _prepare_assignment(self): + if not self._score_hooks_checked and self._input_dtype in (torch.float32, torch.float16, torch.bfloat16): + def accepts(method, arguments, keywords): + try: + inspect.signature(method, follow_wrapped=False).bind(*arguments, **keywords) + return True + except (TypeError, ValueError): + return False + + model_ok = accepts(self._assign_rows, (None,) * 6, {"scores": True}) + if self._assignment_backend == "triton": + from .e_means_quantized import _get_triton_assign_rows + + provider_ok = accepts(_get_triton_assign_rows(), (None,) * 3, {"return_score": True}) + else: + provider_ok = accepts(self._execution_backend.assign, (None,) * 7, {"scores": True}) + verdict = torch.tensor([model_ok, provider_ok], dtype=torch.int64, device=self._centroids.device) + peers = self._gather_local(verdict).view(self._group_size, 2) + incompatible = (~peers.bool().all(dim=1)).nonzero(as_tuple=True)[0].tolist() + if incompatible: + raise TypeError("owner scores=True requires compatible assignment hooks; incompatible group ranks %s" % incompatible) + self._score_hooks_checked = True + return self._prepare_torch_assignment(self._centroids) + + def _initialize_removal_statistics(self): + super()._initialize_removal_statistics() + self._axis_norms = self._usage.new_zeros(self.k, dtype=torch.float32) + self._axis_norms_version = _removal_version(self._removal_stats) + + def _apply_statistics(self, *args, **kwargs): + super()._apply_statistics(*args, **kwargs) + if self._removal_stats is not None: + self._axis_norms_version = _removal_version(self._removal_stats) + + def _gather_removal_scalars(self): + # Normal updates write the cached norm alongside the axes. Direct + # state edits or splits invalidate it; retain bounded recomputation. + if self._axis_norms_version != _removal_version(self._removal_stats): + local = _removal_scalar_stats(self._removal_stats, self._usage).float() + self._axis_norms.copy_(local[:, 2]) + self._axis_norms_version = _removal_version(self._removal_stats) + else: + local = torch.stack((self._removal_stats[:, -1], self._usage.float(), self._axis_norms), dim=1) + full = local.new_empty((self.global_k if self._rank == 0 else 0, 3)) + # Every owner sends its FP32 scalars only to rank 0. Other ranks do + # not allocate or receive a global statistics table. + dist.all_to_all_single(full, local, + input_split_sizes=[self.k] + [0] * (self._group_size - 1), + output_split_sizes=[self.k if self._rank == 0 else 0] * self._group_size, + group=self._group) + return full + + def _choose_sharded_removal_splits(self): + scalars = self._gather_removal_scalars() + if self._rank != 0: + return None, None + # Keep the paying prefix in cost order; _revive_unused broadcasts + # only the final donor/victim pairs. + kept = _removal_candidates(scalars[:, 0]) + donors = self._choose_removal_donors(kept, scalars[:, 1], scalars[:, 2]) + n = min(len(kept), len(donors)) + donors, kept = donors[:n], kept[:n] + cost = scalars[kept, 0].double() + pays = (cost <= 0) | (_SPLIT_GAIN * scalars[donors, 2].double() > cost) + n = int(pays.long().cumprod(0).sum()) + return (donors[:n], kept[:n]) if n else (None, None) + + def _local_assignment(self, rows, prepared, second_out=None): + integer = self._input_dtype in (torch.int8, torch.uint8) + distance_out = (torch.empty(len(rows), dtype=torch.int64, device=rows.device) + if integer else None) + second = second_out + if second is not None and self.k < 2: + second.fill_(torch.iinfo(torch.int64).max if integer else torch.inf) + second = None + scored = self._input_dtype in (torch.float32, torch.float16, torch.bfloat16) + distance, labels = self._assign_rows( + rows, + *prepared, + distance_out, + None, + second, + **({"scores": True} if scored else {}), + ) + if second is not None and self._assignment_backend == "cute": + self._execution_backend.complete_second(rows, labels, second) + return (distance_out if integer else distance), labels + + def _winning_labels(self, rows, prepared, return_score=False): + distance, labels = self._local_assignment(rows, prepared) + return self._reduce_winners(distance, labels, return_score) + + def _reduce_winners(self, distance, labels, return_score=False): + sentinel = torch.iinfo(torch.int64).max + integer = distance.dtype == torch.int64 + valid = (labels >= 0) & (labels < self.k) if integer else labels >= 0 + best = torch.where(valid, distance, sentinel) if integer else distance.clone() + dist.all_reduce(best, op=dist.ReduceOp.MIN, group=self._group) + winner = torch.where( + (distance == best) & valid, + labels.long() + self.centroid_begin, + sentinel, + ) + dist.all_reduce(winner, op=dist.ReduceOp.MIN, group=self._group) + if integer: + torch._assert_async(((winner >= 0) & (winner < self.global_k) & (best != sentinel)).all(), + "integer owner assignment needs a valid global candidate") + return (winner, best) if return_score else winner + + def _reduce_top2(self, distance, labels, second): + winner, best = self._reduce_winners(distance, labels, return_score=True) + # The winning owner contributes its second candidate; every other + # owner contributes its first. One more MIN gives the global second. + other = torch.where(labels.long() + self.centroid_begin == winner, second, distance) + integer = distance.dtype == torch.int64 + if integer: + other = torch.where((labels >= 0) & (labels < self.k), other, torch.iinfo(torch.int64).max) + dist.all_reduce(other, op=dist.ReduceOp.MIN, group=self._group) + if integer: + torch._assert_async((other != torch.iinfo(torch.int64).max).all(), + "integer owner assignment needs a valid global alternative") + return winner, best, other + + def _gather_local(self, local): + fp8 = local.dtype == torch.float8_e4m3fn + if fp8: + local = local.view(torch.uint8) + rows = local.new_empty((len(local) * self._group_size, *local.shape[1:])) + if len(local): + gather = getattr(dist, "all_gather_single", None) or dist.all_gather_into_tensor + gather(rows, local, group=self._group) + return rows.view(torch.float8_e4m3fn) if fp8 else rows + + def _wire_rows(self, rows): + rows = self._prepare_rows(rows) + # CuTe FP8 alone defers local encoding until assignment. + if self._assignment_backend == "cute" and self._fp8_quantizer and rows.dtype != self._input_dtype: + rows = self.quantizer.compute_codes(rows) + if rows.dtype != self._input_dtype: + raise ValueError("source rows do not match the bound native representation") + return rows.contiguous() + + def _gather_training_rows(self, x, index=None): + if self.quantizer is None or x.dtype == self.quantizer.dtype: + local = self._wire_rows(x if index is None else x[index]) + else: + n = len(x) if index is None else len(index) + local = x.new_empty((n, self.d), dtype=self._input_dtype) + chunk = self.recipe["assignment_chunk_size"] + for begin in range(0, n, chunk): + end = min(begin + chunk, n) + rows = x[begin:end] if index is None else x[index[begin:end]] + local[begin:end].copy_(self._wire_rows(rows)) + return self._gather_local(local) + + def _gather_assignment_rows(self, x, prepared, index=None): + return self._gather_training_rows(x, index), None + + def _local_assignment_batch(self, rows, prepared, routing=None, second_out=None): + """Bound native assignment scratch while reducing winners once per batch.""" + distance = labels = None + local_n = len(rows) // self._group_size + chunk = self.recipe["assignment_chunk_size"] + for source in range(self._group_size): + for begin in range(0, local_n, chunk): + part = rows[source * local_n + begin: + source * local_n + min(local_n, begin + chunk)] + at = source * local_n + begin + second = None if second_out is None else second_out[at:at + len(part)] + score, ids = self._local_assignment(part, prepared, **({"second_out": second} if second is not None else {})) + if distance is None: + distance = score.new_empty(len(rows)) + labels = ids.new_empty(len(rows)) + distance[at:at + len(part)].copy_(score) + labels[at:at + len(part)].copy_(ids) + return distance, labels + + def _add_owned(self, rows, winner, sums, counts, objective, score=None, removal=None): + owned = (winner >= self.centroid_begin) & ( + winner < self.centroid_begin + self.k + ) + labels = winner[owned] - self.centroid_begin + values = rows[owned].to(sums.dtype) + if self._removal_stats is not None: + y = values.float() - self._readout()[labels] + p = (y * self._axes[labels]).sum(1, keepdim=True) + cost = torch.zeros_like(p) if removal is None else removal[owned].nan_to_num(0, 0)[:, None] + self._batch_removal.index_add_(0, labels, torch.cat((p * y, cost), dim=1)) + sums.index_add_(0, labels, values) + counts.index_add_( + 0, + labels, + torch.ones(len(labels), device=rows.device, dtype=counts.dtype), + ) + if self.spherical: + objective.add_(2 * len(labels) + score[owned].sum(dtype=torch.float64)) + else: + objective.add_( + (values.float() - self._centroids[labels]).square().sum(dtype=torch.float64) + ) + + def _use_fused_owned_statistics(self): + from .torch_backend import TritonBackend + + return isinstance(self._execution_backend, TritonBackend) + + def _accumulate_gathered(self, rows, prepared, sums, counts, objective, routing=None): + # IVF's existing route returns floating keys even for native byte rows. + integer = self._input_dtype in (torch.int8, torch.uint8) and not hasattr(self, "_ivf") + second = (rows.new_empty(len(rows), dtype=torch.int64 if integer else torch.float32) + if self._removal_stats is not None + and self._epoch < len(self.recipe["epoch_rows"]) + and self._unused_threshold is None else None) + distance, local_labels = self._local_assignment_batch( + rows, prepared, routing, **({"second_out": second} if second is not None else {})) + integer = distance.dtype == torch.int64 + if second is None: + winner, score = self._reduce_winners(distance, local_labels, return_score=True) + removal = None + else: + winner, score, other = self._reduce_top2(distance, local_labels, second) + removal = (other - score).float() # Integer subtraction precedes conversion. + if integer and self.quantizer is not None: + from .quantizer import _ldexp + + removal = _ldexp(removal, self.quantizer._distance_exponent) + if removal is None and self._removal_stats is not None: + removal = torch.zeros_like(score) + # Use the packed training table; callers supplying separate closing + # sums/counts or custom owner hooks retain the ordinary accumulation. + packed = self._batch_accumulation + if (rows.is_cuda and not self.spherical + and self._use_fused_owned_statistics() + and getattr(self._add_owned, "__func__", None) is EmeansShardedCentroids._add_owned + and (self.quantizer is None or self._plain_cast_decode()) + and packed is not None and sums.data_ptr() == packed.data_ptr() + and counts.data_ptr() == packed.data_ptr() + self.d * packed.element_size()): + from .ivf_kernels import accumulate_owned + + if accumulate_owned(rows, winner, self._readout(), self._axes, packed, + self._batch_removal if removal is not None else None, + objective, removal, self.centroid_begin): + return winner + # Preserve source/chunk accumulation order and bound row scratch. + local_n = len(rows) // self._group_size + chunk = self.recipe["assignment_chunk_size"] + for source in range(self._group_size): + for begin in range(0, local_n, chunk): + a = source * local_n + begin + b = source * local_n + min(local_n, begin + chunk) + values = statistics_values(rows[a:b], rows[a:b], self.quantizer) + self._add_owned( + values, winner[a:b], sums, counts, objective, + *((score[a:b],) if self.spherical else ()), + **({"removal": removal[a:b]} if removal is not None else {}), + ) + return winner + + def _local_batch_size(self): + return super()._local_batch_size() // self._group_size + + def _accumulate(self, x, index=None, labels_out=None): + stats = super()._accumulate(x, index, labels_out) + # Pending statistics count local source rows; public n counts rows + # contributed by every rank. + return dict(stats, n=stats["n"] * self._group_size) + + def _accumulate_core(self, x, index=None, raw=False, labels_out=None, ema=None): + n = len(x) if index is None else len(index) + pending_n = 0 if self._pending_stats is None else self._pending_stats["n"] + target = self._local_batch_size() + if pending_n == 0: + global_target = target * self._group_size + self._batch_accumulation = ( + self._batch_stats.new_zeros( + self._batch_stats.shape, dtype=torch.float64 + ) + if n + and global_target > 2**24 + and self._batch_stats.dtype == torch.float32 + else self._batch_stats.zero_() + ) + self._batch_objective = self._objective.new_zeros(()) + self._batch_centroids = self._prepare_assignment() if n else None + accumulation = self._batch_accumulation + sums, counts = accumulation[:, :-1], accumulation[:, -1] + objective, prepared = self._batch_objective, self._batch_centroids + labels = None if labels_out is None else labels_out[:n] + if ( + labels is None + and self.capture_assignments + and self._epoch == len(self.recipe["epoch_rows"]) - 1 + ): + labels = x.new_empty(n, dtype=torch.int64) + rows, routing = self._gather_assignment_rows(x, prepared, index) + if n: + winner = self._accumulate_gathered( + rows, prepared, sums, counts, objective, routing, + ) + if labels is not None: + labels.copy_(winner[self._rank * n:(self._rank + 1) * n]) + total_n = pending_n + n + if total_n == target and accumulation is not self._batch_stats: + self._batch_stats.copy_(accumulation) + sums, counts = self._batch_stats[:, :-1], self._batch_stats[:, -1] + complete = total_n == target or total_n == 0 + stats = { + "sums": sums if complete else None, + "counts": counts if complete else None, + "objective": objective, + "n": total_n, + } + if self._removal_stats is not None: + stats["removal"] = self._batch_removal + if labels is not None: + stats["labels"] = labels + return stats + + def _choose_removal_donors(self, kept, usage, axis_norm): + # Root ranks donors from the gathered scalar statistics. The selected + # IDs are broadcast by _revive_unused afterward. + if self._rank != 0: + return usage.new_empty(0, dtype=torch.int64) + return _partial_removal_donors(kept, usage, axis_norm) + + def _revive_unused(self, rng, *, chunk_rows=None): + # Keep global donor selection, but stage at most 32 MiB of donor rows. + # Sources are unique and disjoint from targets, so completing one + # chunk cannot change a donor needed by a later chunk. + if chunk_rows is None: + chunk_rows = max(1, (32 << 20) // (self.d * self._centroids.element_size())) + if chunk_rows < 1: + raise ValueError("revival chunk_rows must be positive") + usage = self._usage + source = target = None + if self._unused_threshold is None: + source, target = self._choose_sharded_removal_splits() + else: + parts = [torch.empty_like(usage) for _ in range(self._group_size)] + dist.all_gather(parts, usage, group=self._group) + full = torch.cat(parts) + if self._rank == 0: + local_k, local_usage = self.k, self._usage + try: + self.k, self._usage = self.global_k, full + source, target = self._choose_splits(rng) + finally: + self.k, self._usage = local_k, local_usage + root = dist.get_global_rank(self._group, 0) + size = torch.tensor( + [0 if source is None else len(source)], + dtype=torch.int64, + device=usage.device, + ) + dist.broadcast(size, src=root, group=self._group) + n = size.item() + if not n: + return 0 + if self._rank != 0: + source = torch.empty(n, dtype=torch.int64, device=usage.device) + target = torch.empty_like(source) + dist.broadcast(source, src=root, group=self._group) + dist.broadcast(target, src=root, group=self._group) + + def exchange(values, send, recv): + output = values.new_empty((sum(recv), *values.shape[1:])) + dist.all_to_all_single( + output, values.contiguous(), input_split_sizes=send, + output_split_sizes=recv, group=self._group, + ) + return output + + for begin in range(0, n, chunk_rows): + src = source[begin:begin + chunk_rows] + dst = target[begin:begin + chunk_rows] + owned = (src >= self.centroid_begin) & ( + src < self.centroid_begin + self.k + ) + src, dst = src[owned], dst[owned] + local = src - self.centroid_begin + m = len(local) + split = QuantizedEmeans(self.d, 2 * m, quantizer=self.quantizer, + spherical=self.spherical, assignment_backend=self._assignment_backend) + # Split uses the same selected operation, but no assignment/cache mutation. + split._execution_backend = self._execution_backend + split._cast_fit_token = self._cast_fit_token + # Only the source owner computes each pair. Retain the same split + # arithmetic and representation separation as the bulk path. + split._centroids = self._centroids.new_empty((2 * m, self.d)) + split._centroids[:m].copy_(self._centroids[local]) + split._centroids[m:].copy_(split._centroids[:m]) + mass = usage[local] + split._usage = torch.cat((mass, mass)) + split._input_dtype = getattr(self, "_revival_dtype", self._input_dtype) + track = self._removal_stats is not None + if track: # Gaussian split from the donor's U, axis and N before halving (QuantizedEmeans._split_axes) + split._removal_stats = torch.cat((self._removal_stats[local], self._removal_stats[local])) + split._axes = torch.cat((self._axes[local], self._axes[local])) + if m: + ids = torch.arange(m, device=usage.device) + split._apply_splits(ids, ids + m) + self._centroids[local] = split._centroids[:m] + self._usage[local] = split._usage[:m] + self._discard_split_closing(local) + if track: # both copies keep half of U and the donor's axis, as in the unsharded split + self._removal_stats[local] /= 2 + + # Send only children to their target owners. Empty senders and + # receivers still enter every collective with matching splits. + owner = dst // self.k + order = torch.argsort(owner, stable=True) + sent = torch.bincount(owner, minlength=self._group_size) + received = torch.empty_like(sent) + dist.all_to_all_single(received, sent, group=self._group) + send, recv = sent.cpu().tolist(), received.cpu().tolist() + targets = exchange(dst[order], send, recv) - self.centroid_begin + payload = self._centroids.new_empty((m, self.d + 1 + (2 * self.d + 1 if track else 0))) + payload[:, :self.d].copy_(split._centroids[m:]) + payload[:, self.d].copy_(split._usage[m:]) + if track: + payload[:, self.d + 1:2 * self.d + 2].copy_(self._removal_stats[local]) + payload[:, 2 * self.d + 2:].copy_(self._axes[local]) + children = exchange(payload[order], send, recv) + self._centroids[targets] = children[:, :self.d] + self._usage[targets] = children[:, self.d] + self._discard_split_closing(targets) + if track: + self._removal_stats[targets] = children[:, self.d + 1:2 * self.d + 2] + self._axes[targets] = children[:, 2 * self.d + 2:] + self._axis_norms_version = None + self.n_splits += n + self._invalidate_readout() + return n + + def _discard_split_closing(self, indices): + """Retain only post-split sums; save discarded counts for label validation.""" + if self._unused_threshold is not None or self._pass_sums is None or not len(indices): + return + if self._discarded_closing_counts is None: + self._discarded_closing_counts = torch.zeros_like(self._pass_counts) + self._discarded_closing_counts[indices] += self._pass_counts[indices] + self._pass_sums[indices] = 0 + self._pass_counts[indices] = 0 + + def finalize(self): + result = super().finalize() + self._discarded_closing_counts = None + return result + + def _epoch_objective(self): + dist.all_reduce(self._objective, group=self._group) + if self._input_dtype == torch.float8_e4m3fn: + # _epoch_totals initializes the peak on every rank before reduction. + dist.all_reduce(self._fp8_peak, op=dist.ReduceOp.MAX, group=self._group) + return self._objective + + def _reports(self): + return self.verbose and self._rank == 0 + + def _describe_parallel(self): + return "Using %d GPUs with class %s" % (self._group_size, type(self).__name__) + + def end_epoch(self): + self._require_running() + rows = self.recipe["epoch_rows"][self._epoch] + if ( + self._pending_stats is not None + or self._epoch_rows != rows + or self._epoch_steps != self.recipe["epoch_steps"][self._epoch] + ): + raise RuntimeError("epoch is incomplete; consume all prescribed batches") + verbose = self.verbose + self.verbose = False + try: + square = self._pass_counts.double().square().sum() + dist.all_reduce(square, group=self._group) + super().end_epoch() + stat = self.iteration_stats[-1] + stat["imbalance_factor"] = self.global_k * square.item() / rows**2 + if verbose and self._rank == 0: + self._report_epoch(stat, self._epoch - 1) + except BaseException: + self._failed = True + self.assignments = None + raise + finally: + self.verbose = verbose + + @torch.no_grad() + def _fixed_closing_mean(self, batches, assignments, chunk_rows): + """Rebuild saved owner statistics and score the returned FP32 centroids. + + The error uses the retained statistics + precision; sufficient-statistic cancellation can still lose small SSE. + """ + if chunk_rows < 1: + raise ValueError("closing chunk_rows must be positive") + if (not isinstance(assignments, torch.Tensor) + or assignments.device.type != "cpu" + or assignments.dtype not in (torch.int32, torch.int64) + or assignments.ndim != 1 + or len(assignments) != self._n // self._group_size): + raise ValueError("closing assignments must be source-row CPU integer codes") + if self.spherical: + raise ValueError("saved-assignment closing currently requires spherical=False") + started = time.perf_counter() + expected = self._pass_counts.to(torch.int64) + if self._discarded_closing_counts is not None: + expected = expected + self._discarded_closing_counts.to(torch.int64) + sums = self._pass_sums.zero_() + counts = torch.zeros_like(expected) + square = self._objective.new_zeros(()) + device = sums.device + # Release assignment workspaces; input validation still uses batch dtype. + self._batch_centroids = self._batch_accumulation = None + self._batch_operand = self._batch_norm = self._stats_operand = None + if hasattr(self, "_ivf"): + self._ivf = None + offset = 0 + + def exchange(values, send, recv): + output = values.new_empty((sum(recv), *values.shape[1:])) + dist.all_to_all_single( + output, values.contiguous(), input_split_sizes=send, + output_split_sizes=recv, group=self._group, + ) + return output + + for x in batches: + x = self._prepare_input(x) + if offset + len(x) > len(assignments): + raise ValueError("closing scan exceeds global_n") + for begin in range(0, len(x), chunk_rows): + end = min(begin + chunk_rows, len(x)) + codes = assignments[offset + begin:offset + end].to( + device=device, dtype=torch.int64 + ) + torch._assert_async( + ((codes >= -1) & (codes < self.global_k)).all(), + "saved closing assignment is outside global centroid range", + ) + valid = codes >= 0 + codes = codes[valid] + encoded = self._wire_rows(x[begin:end]) + values = statistics_values(encoded, encoded, self.quantizer) + rows = values[valid].to(sums.dtype) + owner = codes // self.k + order = torch.argsort(owner, stable=True) + sent = torch.bincount(owner, minlength=self._group_size) + received = torch.empty_like(sent) + dist.all_to_all_single(received, sent, group=self._group) + send, recv = sent.cpu().tolist(), received.cpu().tolist() + rows = exchange(rows[order], send, recv) + local = exchange(codes[order], send, recv) - self.centroid_begin + # Empty receivers must still participate in all collectives. + if len(local): + sums.index_add_(0, local, rows) + counts.index_add_(0, local, torch.ones_like(local)) + square.add_((rows * rows).sum(dtype=torch.float64)) + offset += len(x) + if offset != len(assignments): + raise ValueError("closing scan must cover global_n rows") + mismatch = torch.tensor( + [not torch.equal(counts, expected)], dtype=torch.int64, device=device + ) + dist.all_reduce(mismatch, op=dist.ReduceOp.MAX, group=self._group) + if mismatch.item(): + raise ValueError("closing counts differ from final-epoch assignments") + explained = square.new_zeros(()) + correction = square.new_zeros(()) + # At most 48*d + 64 explicit temporary bytes per row, with a one-row floor. + block_rows = max(1, (32 << 20) // (48 * self.d + 64)) + for begin in range(0, self.k, block_rows): + end = min(begin + block_rows, self.k) + block = sums[begin:end].double() + count = counts[begin:end] + divisor = count.clamp_min(1).double() + explained.add_((block.square().sum(1) / divisor).sum()) + ideal = block / divisor[:, None] + returned = _closing_centroid_values(sums[begin:end], count, self._centroids[begin:end]) + nonempty = count > 0 + delta = torch.where(nonempty[:, None], returned.double() - ideal, 0.0) + correction.add_((delta.square().sum(1) * count.double()).sum()) + del block, count, divisor, ideal, returned, nonempty, delta + # Score before finalization releases the model-owned working tables. + totals = torch.stack((square - explained + correction, counts.sum().double())) + dist.all_reduce(totals, group=self._group) + n = int(totals[1].item()) + self.closing_stats = { + "rows": n, "assignment_mse": max(0.0, totals[0].item()) / max(1, n), + "saved_assignments": True, "chunk_rows": chunk_rows, + } + self._pass_sums, self._pass_counts = sums, counts + result = self.finalize() + torch.cuda.synchronize(device) + self.closing_stats["time_s"] = time.perf_counter() - started + return result + + def final_closing_mean(self, batches, *, assignments=None, chunk_rows=65536): + """Finalize means from saved labels or a fresh frozen-assignment scan. + + With ``assignments=None``, ``batches`` supplies equal rank-local CUDA + contributions in any order, assigned against one frozen final snapshot. + Every nonempty slot installs its fresh mean, even if moved during training. + ``assignment_mse`` still scores decoded rows against the frozen FP32 + snapshot; spherical ``assignment_error`` retains the represented-IP + ``2 + score`` units. Neither is a returned-centroid error in this mode. + The caller can use a sequential SSD iterator. Every row must occur + exactly once. All training epochs must be complete and ``finalize`` + must not yet have been called. Empty clusters retain their positions. + Floating scans with global_n > 2**24 use FP64 sums (8 rather than + 4 bytes per entry); smaller scans keep FP32 and raw bytes keep INT64. + Division precedes the final FP32 conversion. This does not guarantee + stability of assignment distances or arbitrarily long reductions. + Budget for the existing training tables until the scan completes, + converted FP64 row chunks, FP64 counts/divisor and FP32 mean/output + temporaries as well as the new sum table. + + With ``assignments``, use final-epoch CPU int32/int64 global IDs in + source-row order instead. ``batches`` must scan that same order. Rows + are routed only to their saved centroid owner; no search is performed. + Labels remain as supplied, including rows saved before a later split. + These means differ from ordinary cost finalization, which retains only + rows assigned after each centroid's last split. + Existing final-pass sum storage is reused at its training precision, + and observed counts must match final-epoch assignments. ``-1`` marks rows + omitted from a partial final epoch. In this saved mode, + ``assignment_mse`` is reconstructed + against the actual returned FP32 centroids, with the existing SSE clamp. + Routing uses at most ``chunk_rows`` + source rows per rank per exchange. This mode requires spherical=False. + """ + if ( + self._failed + or self._centroids is None + or self._epoch != len(self.recipe["epoch_rows"]) + or self.centroids is not None + ): + raise RuntimeError("complete epochs before the closing scan") + if self._pending_stats is not None: + raise RuntimeError("consume pending statistics before closing") + try: + if assignments is not None: + return self._fixed_closing_mean(batches, assignments, chunk_rows) + dtype = self._batch_stats.dtype + if dtype == torch.float32 and self._n > 2**24: + dtype = torch.float64 + sums = self._centroids.new_zeros( + self._centroids.shape, dtype=dtype + ) + counts = self._usage.new_zeros( + self.k, + dtype=torch.int64 if sums.dtype == torch.int64 else torch.float64, + ) + objective = self._objective.new_zeros(()) + prepared = None + n = 0 + for x in batches: + x = self._prepare_input(x) + n += len(x) * self._group_size + if n > self._n: + raise ValueError("closing scan exceeds global_n") + if prepared is None and len(x): + prepared = self._prepare_assignment() + rows, routing = self._gather_assignment_rows(x, prepared) + if len(rows): + self._accumulate_gathered(rows, prepared, sums, counts, objective, routing) + if n != self._n: + raise ValueError("closing scan must cover global_n rows") + dist.all_reduce(objective, group=self._group) + self.closing_stats = { + "rows": n, + "assignment_error" + if self.spherical + else "assignment_mse": objective.item() / n, + } + self._pass_sums, self._pass_counts = sums, counts + return self.finalize() + except BaseException: + self._failed = True + self.assignments = None + raise + + def train(self, x, init_centroids=None): + """Train equal row shards; return local centroids and last-pass labels.""" + if self._failed or self.recipe is not None: + raise RuntimeError("create a new object for another run or after failure") + self.assignments = None + if not isinstance(x, torch.Tensor) or not x.is_cuda or x.ndim != 2: + raise ValueError("train requires a resident CUDA matrix") + self._resolve_first_input(x) + self._resolve_assignment_backend(x) + self._execution_backend.require_training(x.device) + n = len(x) * self._group_size + if init_centroids is None: + if not self._automatic and self.quantizer is not None: + try: + check_codec_fit(self._group, self.quantizer, x.device) + except BaseException: + self._failed = True + self.assignments = None + raise + ids = torch.randperm( + len(x), + device=x.device, + generator=_torch_generator(x.device, self.seed + self._rank), + )[: self.k] + init_centroids = self._initial_centroid_values(x[ids]) + self.begin(n, init_centroids) + x = self._prepare_input(x) + batch = self.recipe["batch_size"] + try: + assignments = ( + x.new_empty(len(x), dtype=torch.int64) + if self.capture_assignments + else None + ) + if assignments is not None and self.recipe["epoch_rows"][-1] < n: + assignments.fill_(-1) + for epoch, rows in enumerate(self.recipe["epoch_rows"]): + order = torch.randperm( + len(x), + device=x.device, + generator=_torch_generator(x.device, _epoch_seed(self.seed, epoch)), + ) + for start in range(0, rows, batch): + end = min(rows, start + batch) + a, b = start // self._group_size, end // self._group_size + stats = self._accumulate(x, order[a:b]) + self.update(stats) + if assignments is not None and epoch == len(self.recipe["epoch_rows"]) - 1: + assignments[order[a:b]] = stats["labels"] + self.end_epoch() + result = self.finalize() + except BaseException: + self._failed = True + self.assignments = None + raise + self.assignments = assignments + return result, self.assignments diff --git a/thirdparty/faiss/contrib/e_means/sharded_centroids_ivf.py b/thirdparty/faiss/contrib/e_means/sharded_centroids_ivf.py new file mode 100644 index 000000000..3ee5fa64b --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/sharded_centroids_ivf.py @@ -0,0 +1,194 @@ +# 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. + +"""Original IVF assignment over the current centroid-owner lifecycle. + +Index precision follows ivf_flat, including original grouped output precision +and its limitations. Each reader routes its local rows before gathering them. +""" + +import math + +import torch +import torch.distributed as dist + +from .e_means_torch import _torch_generator +from .sharded_centroids import EmeansShardedCentroids + +__all__ = ["EmeansShardedCentroidsIVF"] + + +class EmeansShardedCentroidsIVF(EmeansShardedCentroids): + """Sharded E-means using the reference Torch IVF-Flat assignment. + + All owners share a coarse quantizer trained once on a distributed sample + of the initial centroids. Candidate lists are rebuilt for every frozen + batch; query routing uses occupancy across all owners. Final means and + batch SSE use original FP32 rows and winning FP32 centroids. + Fine search and split separation use BF16. Default revival uses the + removal margin within the probed lists and Oja-ranked donors. Every + eligible candidate moves in cost order. Closing means use the final-pass + rows retained after the last split; there is no local train handover. + """ + + _revival_dtype = torch.bfloat16 + + def _use_fused_owned_statistics(self): + # IVF owns assignment; owner statistics can still use Triton kernels. + return True + + def _update_removal_statistics(self, alpha, decay): + if not self._removal_stats.is_cuda: + return False + from .triton_assignment import removal_update + + return removal_update( + self._removal_stats, self._batch_removal, self._axes, alpha, decay, + self._axis_norms) + + def _resolve_removal_revival(self): + # Fine assignment is BF16; row statistics retain original FP32 units. + if self.unused_threshold is None and self.global_k > 1: + self._unused_threshold = None + + def __init__( + self, + *args, + nlist=256, + nprobe=4, + coarse_niter=10, + search_workspace_bytes=512 << 20, + **kwargs, + ): + if kwargs.get("spherical", False): + raise ValueError("IVF does not support spherical=True") + kwargs.setdefault("quantizer", None) + if kwargs["quantizer"] is not None: + raise ValueError("IVF sharding requires quantizer=None") + super().__init__(*args, **kwargs) + if not 1 <= nprobe <= nlist <= self.global_k: + raise ValueError("require 1 <= nprobe <= nlist <= global_k") + if coarse_niter < 1 or search_workspace_bytes < 1: + raise ValueError("coarse iterations and workspace must be positive") + self.nlist, self.nprobe = int(nlist), int(nprobe) + self.coarse_niter = int(coarse_niter) + self.search_workspace_bytes = int(search_workspace_bytes) + self._coarse_query_chunk = max(1, min( + 16384, self.search_workspace_bytes // (2 * self.d + 12 * self.nlist))) + self._ivf = None + + def _resolve_assignment_backend(self, x): + if self.assignment_backend == "auto": + self._resolved_assignment_backend = "native" + else: + super()._resolve_assignment_backend(x) + + def begin(self, global_n, init_centroids): + super().begin(global_n, init_centroids) + self.recipe.update( + index_factory=f"IVF{self.nlist},Flat", nprobe=self.nprobe, + coarse_routing="reader", + fine_dtype="bf16", + coarse_query_chunk=self._coarse_query_chunk, + ) + + def _train_coarse(self): + from .torch_backend import _get_triton_assign_rows + + device = self._centroids.device + selected = torch.randperm( + self.global_k, + device="cpu", + generator=_torch_generator("cpu", self.seed), + )[: self.nlist] + coarse = self._centroids.new_empty((self.nlist, self.d)) + for rank in range(self._group_size): + mask = (selected >= rank * self.k) & ( + selected < (rank + 1) * self.k + ) + local = (selected[mask] - rank * self.k).to(device) + rows = ( + self._centroids[local].contiguous() + if rank == self._rank + else coarse.new_empty((len(local), self.d)) + ) + dist.broadcast( + rows, + src=dist.get_global_rank(self._group, rank), + group=self._group, + ) + coarse[mask.to(device)] = rows + sample_ids = torch.randperm( + self.k, + device=device, + generator=_torch_generator(device, self.seed + self._rank), + )[: min(self.k, math.ceil(20 * self.nlist / self._group_size))] + sample = self._centroids[sample_ids] + packed = coarse.new_zeros((self.nlist, self.d + 1)) + chunk = self.recipe["assignment_chunk_size"] + for _ in range(self.coarse_niter): + represented = coarse.half() + norms = represented.float().square().sum(1) + packed.zero_() + for start in range(0, len(sample), chunk): + rows = sample[start : start + chunk] + labels = _get_triton_assign_rows()( + rows.half(), represented, norms + )[1].long() + packed[:, :-1].index_add_(0, labels, rows) + packed[:, -1].index_add_(0, labels, rows.new_ones(len(rows))) + dist.all_reduce(packed, group=self._group) + counts = packed[:, -1] + coarse = torch.where( + (counts > 0)[:, None], + packed[:, :-1] / counts.clamp_min(1)[:, None], + coarse, + ) + return coarse + + def _prepare_assignment(self): + from .ivf_flat import IndexIVFFlat + + if self._ivf is None: + self._ivf = IndexIVFFlat( + self._train_coarse(), + nprobe=self.nprobe, + # Larger coarse-query blocks reduce Python/kernel launch + # overhead; cap their represented rows and score temporaries. + query_chunk=self._coarse_query_chunk, + ) + self._ivf.dtype = "bf16" + self._ivf.add(self._centroids) + occupancy = self._ivf.list_sizes.long() + dist.all_reduce(occupancy, group=self._group) + self._ivf.set_routing_nonempty(occupancy > 0) + return self._ivf + + + def _local_assignment(self, rows, prepared, second_out=None): + if second_out is None: + return prepared.search_1nn(rows) + scores, ids = prepared.search_2nn(rows) + second_out.copy_(scores[:, 1]) + return scores[:, 0], ids[:, 0] + + def _gather_assignment_rows(self, x, prepared, index=None): + local = (x if index is None else x[index]).contiguous() + if not len(local): + return self._gather_training_rows(local), None + # Preparation installs global occupancy, so all readers route against + # the same lists, including lists empty on their own centroid shard. + dtype = torch.int32 if self.nlist <= torch.iinfo(torch.int32).max else torch.int64 + routing = prepared.route(local).to(dtype) + rows = self._gather_training_rows(local) + return rows, self._gather_local(routing) + + def _local_assignment_batch(self, rows, prepared, routing=None, second_out=None): + # IVF bounds its own search workspace; plan all queries together. + if second_out is None: + return prepared.search_1nn(rows, coarse_idx=routing) + scores, ids = prepared.search_2nn(rows, coarse_idx=routing) + second_out.copy_(scores[:, 1]) + return scores[:, 0], ids[:, 0] diff --git a/thirdparty/faiss/contrib/e_means/torch_backend.py b/thirdparty/faiss/contrib/e_means/torch_backend.py new file mode 100644 index 000000000..013d6173d --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/torch_backend.py @@ -0,0 +1,666 @@ +# 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. + +"""Torch E-means execution backends with lazy optional kernel imports. + +Backends own represented centroid layouts, assignment workspace, fused kernel +selection and capture resources. E-means owns the training state and schedule. +""" + +import math + +import torch + + +def _check_torch_abs_bound(name, bound, *tensors): + extrema = torch.stack( + [value for x in tensors for value in torch.aminmax(x)] + ) + if not bool((extrema.abs() <= bound).all()): + raise ValueError(f"{name} must be finite with abs(value) <= {bound:g}") + + +def _half_mean_offsets(axes, norm, mass): + """FP64 offsets s_j u_j of a donor's split copies, c_j -/+ s_j u_j. + + s_j = sqrt(2 ||U_j|| / (pi N_j)) puts the copies at the half-means of a + Gaussian along the axis u_j, with N_j before halving. A donor whose + ||U_j|| or N_j is zero or not finite gets s_j = 0: its copies coincide and + are separated like any coincident split operands. + """ + mass = mass.double() + valid = (norm > 0) & (mass > 0) & torch.isfinite(norm) & torch.isfinite(mass) + spread = torch.sqrt(2.0 * torch.where(valid, norm / torch.where(valid, mass, 1.0), 0.0) / math.pi) + return spread[:, None] * axes.double() + + +def _separate_splits(donor, child, dtype=None, quantizer=None): + """Move one coordinate only when represented split operands coincide. + + Zero donors become distinct subnormal operands; their squared distances + can still tie. No host value read or dynamic collapsed-row list is needed. + Centered casts try original-FP32 neighbours and re-encode before repair. + If coordinate zero has no finite distinct representable code, it stays + unchanged; e.g. FP16 at an FP32 origin of 2**40. No range clamping is used. + """ + donor_q = (quantizer.compute_codes(donor) if quantizer is not None + else donor if dtype is None else donor.to(dtype)) + child_q = (quantizer.compute_codes(child) if quantizer is not None + else child if dtype is None else child.to(dtype)) + collapsed = (donor_q == child_q).all(dim=1) + value = child_q[:, 0] + neighbor = torch.nextafter(value, torch.full_like(value, float("inf"))) + inward = torch.nextafter(value, torch.full_like(value, float("-inf"))) + neighbor = torch.where(neighbor.abs() < float("inf"), neighbor, inward) + neighbor = neighbor.float() + if quantizer is not None: + # A low-format nextafter can disappear during FP32 add-back. + # Try at least one original-FP32 ULP in each direction, keeping + # the decoded code neighbour when it requires a larger move. + original = child[:, 0] + shift = quantizer.shift[0] + positive = torch.maximum(neighbor + shift, torch.nextafter( + original, torch.full_like(original, float("inf")))) + negative = torch.minimum(inward.float() + shift, torch.nextafter( + original, torch.full_like(original, float("-inf")))) + positive_q = (positive - shift).to(quantizer.dtype) + negative_q = (negative - shift).to(quantizer.dtype) + valid_positive = (torch.isfinite(positive) & torch.isfinite(positive_q) + & torch.isfinite(positive_q.float() + shift) + & (positive_q != donor_q[:, 0])) + valid_negative = (torch.isfinite(negative) & torch.isfinite(negative_q) + & torch.isfinite(negative_q.float() + shift) + & (negative_q != donor_q[:, 0])) + neighbor = torch.where(valid_positive, positive, negative) + collapsed = collapsed & (valid_positive | valid_negative) + child[:, 0] = torch.where(collapsed, neighbor, child[:, 0]) + + +def _get_triton_assign_rows(): + try: + from .triton_assignment import assign_rows + except ImportError as error: + raise ImportError( + "Triton assignment requires the triton package" + ) from error + return assign_rows + + +def _get_cute_functions(): + try: + from . import cute + except ImportError as error: + raise ImportError( + "CuTe assignment requires its pinned optional dependencies" + ) from error + return cute._assign_rows, cute._prepare_centroids, cute._check_device + + +def _require_score_operands(rows, centroids): + operands = getattr(centroids, "centroids", centroids) + floating = (torch.float32, torch.float16, torch.bfloat16) + if rows.dtype not in floating or operands.dtype not in floating: + raise ValueError("scores=True requires unencoded floating operands") + + +class TorchBackend: + """Native Torch assignment, accumulation, EMA updates and splitting.""" + + writes_outputs = False + name = "native" + # assign() can return each row's second-nearest index (second_labels_out). + second_labels = True + + def __init__(self, centroid_chunk_size): + self.centroid_chunk_size = centroid_chunk_size + self.clear_statistics() + + def clear_statistics(self): + self.statistics_operand = self.batch_operand = None + self.statistics_template = None + + def require_assignment(self, device): + pass + + def require_training(self, device): + self.require_assignment(device) + + def begin_batch(self, template, workspace_rows): + self.statistics_template = template + self.workspace_rows = workspace_rows + self.batch_operand = None + + def chunk_size(self, centroids): + return default_chunk_size(self.name, centroids, self.centroid_chunk_size) + + def query_centroids(self, centroids): + return centroids.detach() + + def fork_query(self): + import copy + + return copy.copy(self) + + def finish_query(self, backend): + pass + + def prepare_centroids(self, centroids, dtype, spherical=False): + represented = centroids.to(dtype or torch.float32) + norm = ( + centroids.new_zeros(len(centroids)) + if spherical + else represented.float().square().sum(dim=1) + ) + return represented, norm + + def assign( + self, + x, + centroids, + centroid_norm=None, + spherical=False, + distance_out=None, + labels_out=None, + second_out=None, + second_labels_out=None, + *, + scores=False, + ): + """``second_labels_out`` (int32, needs ``second_out``) receives the + index of the second-nearest centroid; on equal distances the lower + index is nearest and the next one second.""" + if scores: + _require_score_operands(x, centroids) + x_norm = None if spherical or scores else x.float().square().sum(dim=1) + best_score = torch.full( + (len(x),), float("inf"), dtype=torch.float32, device=x.device + ) + labels = torch.zeros(len(x), dtype=torch.int64, device=x.device) + if second_out is not None: + second_out.fill_(float("inf")) + if second_labels_out is not None: + second_labels_out.zero_() + + for begin in range(0, len(centroids), self.centroid_chunk_size): + end = min(begin + self.centroid_chunk_size, len(centroids)) + block = centroids[begin:end] + block_norm = ( + (block * block).sum(dim=1) + if centroid_norm is None + else centroid_norm[begin:end] + ) + # Keep the selected operand precision under ambient autocast. + with torch.autocast(x.device.type, enabled=False): + score = torch.addmm( + block_norm[None, :], + x, + block.t(), + alpha=-2.0, + **( + {"out_dtype": torch.float32} + if x.dtype != torch.float32 + else {} + ), + ) + block_score, block_label = score.min(dim=1) + better = block_score < best_score + if second_out is not None: + score.scatter_(1, block_label[:, None], float("inf")) + if second_labels_out is None: + block_second = score.amin(dim=1) + else: + block_second, block_second_label = score.min(dim=1) + # A new best demotes the old best, unless the block's own + # second is nearer; otherwise the block's best competes. + demoted = best_score <= block_second + candidate = torch.where( + better, + torch.where(demoted, labels, block_second_label + begin), + block_label + begin) + replaced = better | (block_score < second_out) + torch.where(replaced, candidate.int(), second_labels_out, + out=second_labels_out) + torch.where(better, best_score.minimum(block_second), + second_out.minimum(block_score), out=second_out) + torch.where(better, block_score, best_score, out=best_score) + torch.where(better, block_label + begin, labels, out=labels) + + if second_out is not None and not (spherical or scores): + second_out.add_(x_norm).clamp_min_(0) + return ( + best_score if spherical or scores else (best_score + x_norm).clamp_min(0) + ), labels + + def accumulate( + self, rows, labels, statistics, batch_size, indexed=False + ): + """Add sums and counts in place using the current batch scratch.""" + if self.batch_operand is None: + if self.statistics_operand is None: + with torch.inference_mode( + self.statistics_template.is_inference() + ): + self.statistics_operand = ( + self.statistics_template.new_ones( + (self.workspace_rows, statistics.shape[1]), + dtype=torch.float32, + ) + ) + self.batch_operand = self.statistics_operand.to(statistics.dtype) + values = self.batch_operand[: len(rows)] + direct_bf16 = ( + indexed + and type(values) is torch.Tensor + and rows.dtype == torch.bfloat16 + and values.dtype == torch.float32 + ) + values[:, :-1].copy_(rows if direct_bf16 else rows.float()) + statistics.index_add_(0, labels, values) + + def update( + self, + all_centroids, + all_usage, + ids, + sums, + counts, + alpha, + decay, + replace_usage, + ): + # EMA arithmetic uses FP32; the supplied statistics keep their schema. + sums, counts = sums.float(), counts.float() + touched = counts > 0 + # Fixed-shape masks avoid dynamic row selection/host reads. Inactive + # lanes divide zero by one; only touched lanes divide by statistics. + safe_counts = torch.where(touched, counts, 1) + mean = sums.clone() + mean.masked_fill_(~touched[:, None], 0) + mean /= safe_counts[:, None] + if not replace_usage: + all_usage *= decay + usage = all_usage if ids is None else all_usage[ids] + centroids = all_centroids if ids is None else all_centroids[ids] + retained = usage if not replace_usage else torch.zeros_like(usage) + mass = retained + alpha * counts + weight = alpha * counts / torch.where(touched, mass, 1) + position = mean - centroids + position.mul_(weight[:, None]).add_(centroids) + torch.where((weight == 1)[:, None], mean, position, out=position) + torch.where(touched[:, None], position, centroids, out=centroids) + torch.where(touched, mass, usage, out=usage) + if ids is not None: + all_centroids.index_copy_(0, ids, centroids) + all_usage.index_copy_(0, ids, usage) + + def split( + self, + centroids, + usage, + source, + target, + dtype, + axes=None, + norm=None, + quantizer=None, + separate=None, + built_in_separation=True, + ): + """Split positions and masses. + + ``axes`` (k, d) and ``norm`` (k,) FP64 ||U|| place the copies at + c_j -/+ s_j u_j (``_half_mean_offsets``); without them both copies + start at c_j. ``separate`` preserves distinctions in a quantized + representation. + """ + donors = centroids[source].double() + offset = 0.0 if axes is None else _half_mean_offsets(axes[source], norm[source], usage[source]) + donor_centroids = (donors - offset).float() + child_centroids = (donors + offset).float() + if dtype == torch.float16: + guarded = ( + (quantizer._center_rows(donor_centroids), quantizer._center_rows(child_centroids)) + if getattr(quantizer, "center", False) + else (donor_centroids, child_centroids) + ) + _check_torch_abs_bound( + "revived centroids", 65504.0, *guarded + ) + if separate is None: + _separate_splits(donor_centroids, child_centroids, dtype) + else: + separate(donor_centroids, child_centroids) + half_usage = usage[source] / 2.0 + usage[source] = half_usage + centroids[source] = donor_centroids + usage[target] = half_usage + centroids[target] = child_centroids + + def capture_state(self): + return None + + def initialize_capture(self): + torch.cuda.current_blas_handle() + + def finish_capture(self, state, captured): + pass + + def capture_bindings(self, state): + return () + + def validate_capture(self, state): + pass + + +class TritonBackend(TorchBackend): + """Triton layouts and assignment, with optional fused tensor operations.""" + + name = "triton" + second_labels = True + + def require_assignment(self, device): + _get_triton_assign_rows() + + def chunk_size(self, centroids): + return default_chunk_size(self.name, centroids, self.centroid_chunk_size) + + def prepare_centroids(self, centroids, dtype, spherical=False): + represented, norm = super().prepare_centroids( + centroids, dtype, spherical + ) + if represented.dtype == torch.float32: + represented = represented.t().contiguous().t() + if centroids.shape[1] % 16 and represented.dtype in ( + torch.bfloat16, + torch.float16, + ): + from .triton_assignment import _pad_columns + + represented = _pad_columns(represented, 16) + return represented, norm + + def assign( + self, + x, + centroids, + centroid_norm=None, + spherical=False, + distance_out=None, + labels_out=None, + second_out=None, + second_labels_out=None, + *, + scores=False, + ): + if scores: + _require_score_operands(x, centroids) + if x.shape[1] != centroids.shape[1]: + from .triton_assignment import _pad_columns + + x = _pad_columns(x, 16) + return _get_triton_assign_rows()( + x, + centroids, + centroid_norm, + **({"spherical": True} if spherical else {}), + **({"second_out": second_out} if second_out is not None else {}), + **({"second_labels_out": second_labels_out} if second_labels_out is not None else {}), + **({"return_score": True} if scores else {}), + ) + + def accumulate( + self, rows, labels, statistics, batch_size, indexed=False + ): + if ( + rows.is_cuda + and batch_size <= 2**24 + and rows.dtype == torch.float16 + and not torch.are_deterministic_algorithms_enabled() + ): + from .triton_assignment import accumulate_bytes + + if accumulate_bytes(rows, labels, statistics): + return + # Sorted segments beat copy + index_add on SM90 GPUs, and from d = 128 on on newer ones. + if (rows.is_cuda and rows.dtype in (torch.float32, torch.bfloat16) + and (rows.shape[1] >= 128 or torch.cuda.get_device_capability(rows.device)[0] == 9)): + from .triton_assignment import accumulate_segments + + if accumulate_segments(rows, labels, statistics): + return + super().accumulate( + rows, labels, statistics, batch_size, indexed + ) + + def accumulate_removal(self, *args, **kwargs): + """Sums, counts and the removal-revival batch statistics in one pass.""" + from .triton_assignment import accumulate_removal + + return accumulate_removal(*args, **kwargs) + + def removal_update(self, *args): + from .triton_assignment import removal_update + + return removal_update(*args) + + def removal_split(self, *args): + from .triton_assignment import removal_split + + return removal_split(*args) + + def update( + self, centroids, usage, ids, sums, counts, alpha, decay, replace_usage + ): + if ids is None and centroids.is_cuda: + from .triton_assignment import ema_update + + if ema_update( + sums, counts, centroids, usage, alpha, decay, replace_usage + ): + return + super().update( + centroids, usage, ids, sums, counts, alpha, decay, replace_usage + ) + + def split( + self, + centroids, + usage, + source, + target, + dtype, + axes=None, + norm=None, + quantizer=None, + separate=None, + built_in_separation=True, + ): + if ( + built_in_separation + and centroids.is_cuda + and centroids.shape[1] <= 1024 + and dtype + in (None, torch.float32, torch.bfloat16, torch.float8_e4m3fn) + ): + from .triton_assignment import _write_float_splits + + if _write_float_splits( + centroids, usage, source, target, dtype, axes, norm, quantizer + ): + return + super().split( + centroids, + usage, + source, + target, + dtype, + axes, + norm, + quantizer, + separate, + built_in_separation, + ) + + def initialize_capture(self): + pass + + +class CuteBackend(TritonBackend): + """CuTe centroid and row workspace, including resources held by graphs. + + Accumulation, EMA updates and split writes use inherited Triton kernels + with Torch fallbacks. + """ + + writes_outputs = True + name = "cute" + second_labels = True + + def require_assignment(self, device): + _get_cute_functions()[2](device) + + def require_training(self, device): + self.require_assignment(device) + _get_triton_assign_rows() + + def __init__(self, centroid_chunk_size): + super().__init__(centroid_chunk_size) + self.cache = None + + def query_centroids(self, centroids): + return centroids + + def finish_query(self, backend): + if isinstance(backend, CuteBackend): + self.cache = backend.cache + + def prepare_centroids( + self, centroids, dtype, spherical=False, transform=None, peak_out=None + ): + _, prepare, _ = _get_cute_functions() + self.cache = prepare( + centroids, + self.cache, + dtype=dtype or torch.bfloat16, + spherical=spherical, + transform=transform, + peak_out=peak_out, + ) + return self.cache, None + + def assign( + self, + x, + centroids, + centroid_norm=None, + spherical=False, + distance_out=None, + labels_out=None, + second_out=None, + second_labels_out=None, + *, + scores=False, + ): + if scores: + _require_score_operands(x, centroids) + assign, _, _ = _get_cute_functions() + return assign(x, centroids, distance_out, labels_out, + **({"second_out": second_out} if second_out is not None else {}), + **({"second_labels_out": second_labels_out} + if second_labels_out is not None else {}), + **({"scores": True} if scores else {})) + + def accumulate_removal(self, rows, labels, *args, **kwargs): + """Consume complete assignment scores and the declared statistical rows.""" + from .triton_assignment import accumulate_removal + + return accumulate_removal(rows, labels, *args, **kwargs) + + def complete_second(self, rows, labels, second): + """Compatibility boundary: every CuTe assignment already completes SECOND.""" + return None + + def capture_state(self): + state = self.cache + if state is not None: + # Capture must record a refresh even after an eager warmup. + state.source_version = None + return state + + def finish_capture(self, state, captured): + if state is not None: + state.source_version = None + if not captured: + self.cache = None + + def capture_bindings(self, state): + return tuple(state.bindings.values()) if state is not None else () + + def validate_capture(self, state): + if self.cache is not state: + raise RuntimeError("centroid preparation changed during replay") + + +def select_backend(x, dtype, k, d, requested="auto"): + """Select from device, dtype and extent, then require the selected software. + + Automatic selection still depends on dtype and extent as well as hardware. + Missing or broken required software raises an error for that selection. + """ + if requested == "native": + return TorchBackend + if requested == "triton": + return TritonBackend + if requested == "cute": + return CuteBackend + if requested != "auto": + raise ValueError("assignment_backend must be auto, native, triton or cute") + if x.device.type == "cpu": + return TorchBackend + capability = torch.cuda.get_device_capability(x.device) if torch.version.hip is None else (0, 0) + cuda = capability >= (8, 0) + if dtype in (torch.int8, torch.uint8): + from .quantizer_int8 import _check_int8_support + + _check_int8_support(x.device) + if d > 43919: + raise ValueError("INT8 assignment requires d <= 43919") + elif dtype == torch.float8_e4m3fn: + from .quantizer_fp8 import _check_fp8_support + + _check_fp8_support(x.device) + # SM90 BF16 selects CuTe within these padded extents. The checks below + # select Triton or native Torch for other inputs, or reject them. + padded_k, padded_d = ((k + 191) // 192) * 192, ((d + 7) // 8) * 8 + if (capability == (9, 0) and dtype is torch.bfloat16 + and k <= 2**31 - 192 and 0 < d < 2**31 + and padded_k * padded_d < 2**31): + return CuteBackend + if cuda and k <= 2**31 - 256: + return TritonBackend + floating = dtype in (torch.float32, torch.float16, torch.bfloat16) + native = dtype is torch.float32 or ( + cuda and "out_dtype" in (torch.addmm.__doc__ or "") + ) + if floating and native: + return TorchBackend + if floating: + raise RuntimeError( + "auto assignment has no compatible backend for this device and " + "representation: FP16/BF16 assignment requires an NVIDIA SM80 or " + "later GPU" + ) + raise RuntimeError( + "auto assignment has no supported operation for this device and representation; " + "use QuantizedEmeans(quantizer=None) for native FP32") + + +def default_chunk_size(backend, centroids, centroid_chunk_size=4096): + """Built-in chunk geometry, also used for equivalent-recipe replay.""" + if centroids.device.type == "cpu": + return 8192 + k, d = centroids.shape + width = max(d, min(k, centroid_chunk_size)) if backend == "native" else d + return min(2**20, max(8192, 2**26 // width)) diff --git a/thirdparty/faiss/contrib/e_means/triton_assignment.py b/thirdparty/faiss/contrib/e_means/triton_assignment.py new file mode 100644 index 000000000..7649d4169 --- /dev/null +++ b/thirdparty/faiss/contrib/e_means/triton_assignment.py @@ -0,0 +1,2477 @@ +# 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. + +"""Triton nearest-centroid assignment and dense CUDA EMA for E-means. + +Dispatch uses fixed shape and dtype rules without runtime autotuning. Kernels +stream centroid tiles with bounded score workspaces instead of materializing +the native backend's row-by-centroid score tensor. +""" + +from functools import lru_cache + +import torch + +try: + import triton + import triton.language as tl +except ImportError as error: + raise ImportError( + "Triton assignment requires the triton package" + ) from error + +try: + from triton.tools.tensor_descriptor import TensorDescriptor +except ImportError: + TensorDescriptor = None + +try: + from triton.language.extra.cuda import libdevice as _fp8_libdevice +except ImportError: + _fp8_libdevice = None + + +_INT32_MAX = 2**31 - 1 +# ROCm (10.1) Triton keeps num_stages - 1 LDS copies of each streamed tile; at three +# stages the FP16/BF16 tiles exceed the 64 KiB LDS of gfx942 (MI300X/MI325X). +_NUM_STAGES = 2 if torch.version.hip else 3 +_SPLIT_K_BLOCK_B = 64 +_SPLIT_K_BLOCK_K = 128 +_SPLIT_K_BLOCK_D = 128 +_SPLIT_K_MAX_PARTITIONS = 128 +_SPLIT_K_NUM_WARPS = 8 +_SPLIT_K_NUM_STAGES = _NUM_STAGES +# Small empirical occupancy target; not a hardware legality constraint. +_SPLIT_K_TARGET_PROGRAMS = 512 +_SPLIT_K_MIN_TILES_PER_PARTITION = 4 +_DIRECT_BLOCK_B = 64 +_DIRECT_BLOCK_K = 256 +_DIRECT_REDUCED_BLOCK_D = 64 +_DIRECT_FP32_BLOCK_D = 32 +_FLOAT8_E4M3FN = getattr(torch, "float8_e4m3fn", None) +_FULL_D_MAX_D = 128 +_FULL_D_CONFIG = (64, 128, 4, _NUM_STAGES) +_INT8_BLOCK_B = 128 +_INT8_BLOCK_K = 256 +_INT8_BLOCK_D = 128 +_INT8_PREPARE_BLOCK_D = 256 +_INT8_MAX_D = 43919 +_INT8_D_ALIGNMENT = 16 +_MAX_K = 2**31 - max( + _SPLIT_K_MAX_PARTITIONS, + _SPLIT_K_BLOCK_K, + _DIRECT_BLOCK_K, +) + + +_int8_libdevice = None + + +@lru_cache(maxsize=None) +def _cuda_assignment_device_properties(device_index): + """Read the tensor device's capability and Triton launch limit once.""" + capability = torch.cuda.get_device_capability(device_index) + properties = triton.runtime.driver.active.utils.get_device_properties(device_index) + return capability, properties["max_shared_mem"] + + +def _full_d_config(device): + if torch.version.hip is not None: + return _FULL_D_CONFIG + device_index = device.index if device.index is not None else torch.cuda.current_device() + capability, shared_limit = _cuda_assignment_device_properties(device_index) + if capability >= (8, 0) or shared_limit >= 98304: + return _FULL_D_CONFIG + # Triton 3.9's CUDA SIMT full-D dot holds FP32 B64/D128 and D128/K128 + # operand tiles (98304 bytes), independent of pipeline depth. K64 fits + # 65536 bytes without changing the full-D contraction or stage count. + if shared_limit < 65536: + raise RuntimeError( + "Triton full-D CUDA SIMT assignment (B64/K64/D128, 4 warps, %d stages) " + "requires at least 65536 bytes of shared memory on cuda:%d; " + "device limit is %d" % (_NUM_STAGES, device_index, shared_limit) + ) + block_b, _, num_warps, num_stages = _FULL_D_CONFIG + return block_b, 64, num_warps, num_stages + + +def _load_int8_libdevice(): + """Load the INT8 rounding dependency only when INT8 is selected.""" + global _int8_libdevice + if _int8_libdevice is None: + try: + from triton.language.extra import libdevice + except ImportError as error: + raise ImportError( + "INT8 assignment requires Triton libdevice support" + ) from error + if not hasattr(libdevice, "rint"): + raise ImportError( + "INT8 assignment requires Triton libdevice.rint support" + ) + _int8_libdevice = libdevice + return _int8_libdevice + + +def _centroid_offset_is_wide(shape, stride): + """Return whether any physical centroid lane needs int64.""" + physical_k = max( + triton.cdiv(shape[0], _DIRECT_BLOCK_K) * _DIRECT_BLOCK_K, + shape[0] + _SPLIT_K_BLOCK_K - 1, + ) + physical_d = ( + triton.cdiv(shape[1], _SPLIT_K_BLOCK_D) * _SPLIT_K_BLOCK_D + ) + maximum = (physical_k - 1) * stride[0] + (physical_d - 1) * stride[1] + return maximum > _INT32_MAX + + +@triton.jit +def _selected_fp8_distance( + x_ptr, centroid_ptr, row, label, D, + stride_xb, stride_xd, stride_ck, stride_cd, + row_mask, BLOCK_D: tl.constexpr, +): + distance = tl.full(row.shape, 0.0, tl.float32) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + mask = row_mask[:, None] & (column[None, :] < D) + x = tl.load( + x_ptr + row[:, None] * stride_xb + column[None, :] * stride_xd, + mask=mask, other=0.0, + ).to(tl.float32) + c = tl.load( + centroid_ptr + label[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd, + mask=mask, other=0.0, + ).to(tl.float32) + delta = x - c + distance += tl.sum(delta * delta, axis=1) + return distance + + +@triton.jit +def _merge_second(score, block_score, block_label, best_score, second): + """Running exact second-best score: a tile's best beating the best demotes it.""" + column = tl.arange(0, score.shape[1])[None, :] + block_second = tl.min(tl.where(column == block_label[:, None], float("inf"), score), axis=1) + return tl.where(block_score < best_score, tl.minimum(best_score, block_second), + tl.minimum(second, block_score)) + + +@triton.jit +def _merge_second_label(score, block_score, block_label, best_score, best_label, second, + second_label, pending, offset, DEFER: tl.constexpr = True): + """``_merge_second`` that also carries the second-best centroid index. + + The index is known in every case but one: a tile that beats the row's best + and whose own second beats the old best. That tile's own second column is + not searched here (it would cost an indexed reduction on every tile); + the row is marked ``pending`` with the tile's first centroid and its label + is resolved after the scan (``_resolve_second_kernel``), where the row's + best lies in that same tile. ``block_label`` is tile-local, ``offset`` the + tile's first centroid, ``best_label`` / ``second_label`` global indices. + + With ``DEFER`` off (wide rows, where resolving a pending row costs a whole + tile of CUDA-core work), the column is searched in the scan instead, but + only on tiles where some row of the program needs it. + """ + column = tl.arange(0, score.shape[1])[None, :] + block_second = tl.min(tl.where(column == block_label[:, None], float("inf"), score), axis=1) + better = block_score < best_score + old_best_second = best_score <= block_second + replaced = block_score < second + own = -1 + if not DEFER: + own = tl.zeros_like(second_label) + if tl.max((better & ~old_best_second).to(tl.int32), axis=0) > 0: + own = tl.min(tl.where( + (score == block_second[:, None]) & (column != block_label[:, None]), column, 2**30), + axis=1).to(tl.int32) + offset + label = tl.where(better, tl.where(old_best_second, best_label, own), + tl.where(replaced, block_label.to(tl.int32) + offset, second_label)) + if DEFER: + pending = tl.where(better, tl.where(old_best_second, -1, offset), tl.where(replaced, -1, pending)) + second = tl.where(better, tl.minimum(best_score, block_second), tl.minimum(second, block_score)) + return second, label, pending + + +@triton.jit +def _resolve_second_kernel(x_ptr, centroid_ptr, centroid_norm_ptr, label_ptr, second_label_ptr, + pending_ptr, B, K, D, stride_xb, stride_xd, stride_ck, stride_cd, + TILE: tl.constexpr, BLOCK_D: tl.constexpr, ROWS: tl.constexpr, + FP16: tl.constexpr): + """Second label of each pending row: the nearest centroid of its pending + tile other than its best (ties to the lower index). Pending rows are rare, + so a program whose rows have none returns at once.""" + first = tl.program_id(0).to(tl.int64) * ROWS + lanes = first + tl.arange(0, ROWS).to(tl.int64) + tiles = tl.load(pending_ptr + lanes, mask=lanes < B, other=-1) + if tl.max(tiles, axis=0) >= 0: + for r in range(ROWS): + row = first + r + tile = tl.load(pending_ptr + row, mask=row < B, other=-1) + if tile >= 0: + centroid = tile + tl.arange(0, TILE) + valid = centroid < K + score = tl.zeros((TILE,), tl.float32) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + xr = tl.load(x_ptr + row * stride_xb + column * stride_xd, mask=column < D, other=0.0) + xr = (xr.to(tl.float16) if FP16 else xr.to(tl.bfloat16)).to(tl.float32) + c = tl.load(centroid_ptr + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :] * stride_cd, + mask=valid[:, None] & (column[None, :] < D), other=0.0) + score += tl.sum(c.to(tl.float32) * xr[None, :], axis=1) + best = tl.load(label_ptr + row).to(tl.int32) + score = tl.load(centroid_norm_ptr + centroid, mask=valid, other=float("inf")) - 2.0 * score + score = tl.where((centroid == best) | ~valid, float("inf"), score) + _, local = tl.min(score, axis=0, return_indices=True, return_indices_tie_break_left=True) + tl.store(second_label_ptr + row, tile + local.to(tl.int32)) + + +@triton.jit +def _merge_second_id(score, block_score, block_local, start, best_score, best_label, second, second_label): + column = tl.arange(0, score.shape[1])[None, :] + other_score, other_local = tl.min( + tl.where(column != block_local[:, None], score, float("inf")), + axis=1, + return_indices=True, + return_indices_tie_break_left=True, + ) + other_label = other_local.to(tl.int32) + start + block_label = block_local.to(tl.int32) + start + improves = block_score < best_score + left, left_label = tl.where(improves, best_score, second), tl.where(improves, best_label, second_label) + right, right_label = tl.where(improves, other_score, block_score), tl.where(improves, other_label, block_label) + take_right = (right < left) | ((right == left) & (right_label < left_label)) + return tl.where(take_right, right, left), tl.where(take_right, right_label, left_label) + + +@triton.jit +def _assign_kernel( + x_ptr, + centroid_ptr, + centroid_norm_ptr, + distance_ptr, + label_ptr, + B, + K, + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + BLOCK_B: tl.constexpr, + BLOCK_K: tl.constexpr, + BLOCK_D: tl.constexpr, + FULL_D: tl.constexpr, + REDUCED: tl.constexpr, + FP16: tl.constexpr, + FP8: tl.constexpr, + WIDE_CENTROID: tl.constexpr, + x_desc=None, + centroid_desc=None, + SPHERICAL: tl.constexpr = False, + second_ptr=None, + SECOND: tl.constexpr = 0, + second_label_ptr=None, + SECOND_LABEL: tl.constexpr = 0, + pending_ptr=None, + DEFER_SECOND_LABEL: tl.constexpr = True, +): + row_program = tl.program_id(0).to(tl.int64) + lane = tl.arange(0, BLOCK_B).to(tl.int64) + row = row_program * BLOCK_B + lane + row_mask = row < B + row_norm = tl.zeros((BLOCK_B,), tl.float32) + + if FULL_D: + column = tl.arange(0, BLOCK_D) + full_x = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & (column[None, :] < D), + other=0.0, + ) + if REDUCED and not FP8: + full_x = ( + full_x.to(tl.float16) if FP16 else full_x.to(tl.bfloat16) + ) + if not FP8 and not SPHERICAL: + x_float = full_x.to(tl.float32) + row_norm = tl.sum(x_float * x_float, axis=1) + elif not FP8 and not SPHERICAL: + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + x = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & (column[None, :] < D), + other=0.0, + ) + if REDUCED and not FP8: + x = x.to(tl.float16) if FP16 else x.to(tl.bfloat16) + x = x.to(tl.float32) + row_norm += tl.sum(x * x, axis=1) + + best_score = tl.full((BLOCK_B,), float("inf"), tl.float32) + best_label = tl.zeros((BLOCK_B,), tl.int32) + second = best_score + second_label = tl.full((BLOCK_B,), 2147483647 if FP8 and SECOND else -1, tl.int32) + pending = tl.full((BLOCK_B,), -1, tl.int32) + # Only paired-descriptor FP8 uses two halves; pointer tiles stay unchanged. + halves: tl.constexpr = FP8 and not FULL_D and centroid_desc is not None + score_k: tl.constexpr = BLOCK_K // 2 if halves else BLOCK_K + for k0 in range(0, K, BLOCK_K): + centroid = k0 + tl.arange(0, score_k) + centroid_mask = centroid < K + if FULL_D: + column = tl.arange(0, BLOCK_D) + column_mask = column < D + if WIDE_CENTROID: + centroid_offset = ( + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd + ) + else: + centroid_offset = ( + centroid[:, None] * stride_ck + + column[None, :] * stride_cd + ) + c = tl.load( + centroid_ptr + centroid_offset, + mask=centroid_mask[:, None] & column_mask[None, :], + other=0.0, + ) + if FP8: + score = tl.dot( + full_x, + tl.trans(c), + out_dtype=tl.float32, + max_num_imprecise_acc=max(32, BLOCK_D), + ) + else: + score = tl.dot( + full_x, + tl.trans(c), + out_dtype=tl.float32, + ) + else: + score = tl.zeros((BLOCK_B, score_k), tl.float32) + if halves: + upper_score = tl.zeros((BLOCK_B, score_k), tl.float32) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + column_mask = column < D + if x_desc is not None: + x = x_desc.load([(row_program * BLOCK_B).to(tl.int32), d0]) + c = centroid_desc.load([k0, d0]) + else: + x = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & column_mask[None, :], + other=0.0, + ) + if WIDE_CENTROID: + centroid_offset = ( + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd + ) + else: + centroid_offset = ( + centroid[:, None] * stride_ck + + column[None, :] * stride_cd + ) + c = tl.load( + centroid_ptr + centroid_offset, + mask=centroid_mask[:, None] & column_mask[None, :], + other=0.0, + ) + if REDUCED and not FP8: + x = x.to(tl.float16) if FP16 else x.to(tl.bfloat16) + if FP8: + score = tl.dot( + x, + tl.trans(c), + acc=score, + out_dtype=tl.float32, + max_num_imprecise_acc=max(32, BLOCK_D), + ) + if halves: + u = centroid_desc.load([k0 + BLOCK_K // 2, d0]) + upper_score = tl.dot( + x, tl.trans(u), acc=upper_score, out_dtype=tl.float32, + max_num_imprecise_acc=max(32, BLOCK_D), + ) + elif REDUCED: + score = tl.dot( + x, + tl.trans(c), + acc=score, + out_dtype=tl.float32, + ) + else: + score = tl.dot( + x, + tl.trans(c), + acc=score, + input_precision="ieee", + out_dtype=tl.float32, + ) + + for half in tl.static_range(0, 2 if halves else 1): + if halves: + if half == 1: + score = upper_score + centroid = k0 + half * score_k + tl.arange(0, score_k) + centroid_mask = centroid < K + norm = tl.load( + centroid_norm_ptr + centroid, + mask=centroid_mask, + other=float("inf"), + ) + score = norm[None, :] - 2.0 * score + block_score, block_label = tl.min( + score, + axis=1, + return_indices=True, + return_indices_tie_break_left=True, + ) + if SECOND and FP8: + second, second_label = _merge_second_id( + score, block_score, block_label, k0 + half * score_k if halves else k0, + best_score, best_label, second, second_label) + elif SECOND_LABEL: + tile_offset = k0 + if halves: + tile_offset += half * score_k + second, second_label, pending = _merge_second_label( + score, block_score, block_label, best_score, best_label, second, + second_label, pending, tile_offset, DEFER_SECOND_LABEL) + elif SECOND: + second = _merge_second(score, block_score, block_label, + best_score, second) + block_label = block_label.to(tl.int32) + k0 + if halves: + block_label += half * score_k + better = block_score < best_score + best_score = tl.where(better, block_score, best_score) + best_label = tl.where(better, block_label, best_label) + + if SPHERICAL: + distance = best_score + elif FP8: + distance = _selected_fp8_distance( + x_ptr, centroid_ptr, row, best_label, D, + stride_xb, stride_xd, stride_ck, stride_cd, row_mask, BLOCK_D, + ) + else: + distance = tl.maximum(best_score + row_norm, 0.0) + tl.store(distance_ptr + row, distance, mask=row_mask) + tl.store(label_ptr + row, best_label.to(tl.int64), mask=row_mask) + if SECOND: + if FP8: + second = _selected_fp8_distance( + x_ptr, + centroid_ptr, + row, + second_label, + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + row_mask, + BLOCK_D, + ) + if second_label_ptr is not None: + tl.store(second_label_ptr + row, second_label.to(tl.int64), mask=row_mask) + elif not SPHERICAL: + second = tl.maximum(second + row_norm, 0.0) + tl.store(second_ptr + row, second, mask=row_mask) + if SECOND_LABEL: + tl.store(second_label_ptr + row, second_label, mask=row_mask) + tl.store(pending_ptr + row, pending, mask=row_mask) + + +@triton.jit +def _assign_split_k_kernel( + x_ptr, + centroid_ptr, + centroid_norm_ptr, + partial_score_ptr, + partial_label_ptr, + B, + K, + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + PARTITIONS: tl.constexpr, + BLOCK_B: tl.constexpr, + BLOCK_K: tl.constexpr, + BLOCK_D: tl.constexpr, + FP16: tl.constexpr, + FP8: tl.constexpr, + WIDE_CENTROID: tl.constexpr, + partial_second_ptr=None, + SECOND: tl.constexpr = 0, + partial_second_label_ptr=None, + SECOND_LABEL: tl.constexpr = 0, + partial_pending_ptr=None, + DEFER_SECOND_LABEL: tl.constexpr = True, +): + row_program = tl.program_id(0).to(tl.int64) + partition = tl.program_id(1) + lane = tl.arange(0, BLOCK_B).to(tl.int64) + row = row_program * BLOCK_B + lane + row_mask = row < B + partition_size = (K - 1) // PARTITIONS + 1 + centroid_start = partition * partition_size + centroid_end = tl.minimum(centroid_start + partition_size, K) + best_score = tl.full((BLOCK_B,), float("inf"), tl.float32) + best_label = tl.zeros((BLOCK_B,), tl.int32) + second = best_score + second_label = tl.full((BLOCK_B,), 2147483647 if FP8 and SECOND else -1, tl.int32) + pending = tl.full((BLOCK_B,), -1, tl.int32) + + k0 = centroid_start + while k0 < centroid_end: + centroid = k0 + tl.arange(0, BLOCK_K) + centroid_mask = centroid < centroid_end + score = tl.zeros((BLOCK_B, BLOCK_K), tl.float32) + + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + column_mask = column < D + x = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & column_mask[None, :], + other=0.0, + ) + if not FP8: + x = x.to(tl.float16) if FP16 else x.to(tl.bfloat16) + if WIDE_CENTROID: + centroid_offset = ( + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd + ) + else: + centroid_offset = ( + centroid[:, None] * stride_ck + + column[None, :] * stride_cd + ) + c = tl.load( + centroid_ptr + centroid_offset, + mask=centroid_mask[:, None] & column_mask[None, :], + other=0.0, + ) + if FP8: + score = tl.dot( + x, + tl.trans(c), + acc=score, + out_dtype=tl.float32, + max_num_imprecise_acc=max(32, BLOCK_D), + ) + else: + score = tl.dot( + x, + tl.trans(c), + acc=score, + out_dtype=tl.float32, + ) + + norm = tl.load( + centroid_norm_ptr + centroid, + mask=centroid_mask, + other=float("inf"), + ) + score = norm[None, :] - 2.0 * score + block_score, block_label = tl.min( + score, + axis=1, + return_indices=True, + return_indices_tie_break_left=True, + ) + if SECOND and FP8: + second, second_label = _merge_second_id( + score, block_score, block_label, k0, best_score, best_label, second, second_label) + elif SECOND_LABEL: + second, second_label, pending = _merge_second_label( + score, block_score, block_label, best_score, best_label, second, second_label, + pending, k0, DEFER_SECOND_LABEL) + elif SECOND: + second = _merge_second(score, block_score, block_label, + best_score, second) + block_label = block_label.to(tl.int32) + k0 + better = block_score < best_score + best_score = tl.where(better, block_score, best_score) + best_label = tl.where(better, block_label, best_label) + k0 += BLOCK_K + + offset = row * PARTITIONS + partition + tl.store(partial_score_ptr + offset, best_score, mask=row_mask) + tl.store(partial_label_ptr + offset, best_label, mask=row_mask) + if SECOND: + tl.store(partial_second_ptr + offset, second, mask=row_mask) + if SECOND and FP8: + tl.store(partial_second_label_ptr + offset, second_label, mask=row_mask) + if SECOND_LABEL: + tl.store(partial_second_label_ptr + offset, second_label, mask=row_mask) + tl.store(partial_pending_ptr + offset, pending, mask=row_mask) + + +@triton.jit +def _reduce_split_k_kernel( + x_ptr, + centroid_ptr, + partial_score_ptr, + partial_label_ptr, + distance_ptr, + label_ptr, + B, + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + PARTITIONS: tl.constexpr, + BLOCK_PARTITIONS: tl.constexpr, + BLOCK_D: tl.constexpr, + FP16: tl.constexpr, + FP8: tl.constexpr, + SPHERICAL: tl.constexpr = False, + partial_second_ptr=None, + second_ptr=None, + SECOND: tl.constexpr = 0, + partial_second_label_ptr=None, + second_label_ptr=None, + SECOND_LABEL: tl.constexpr = 0, + partial_pending_ptr=None, + pending_ptr=None, +): + row = tl.program_id(0).to(tl.int64) + if not FP8 and not SPHERICAL: + row_norm = tl.zeros((), tl.float32) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + x = tl.load( + x_ptr + row * stride_xb + column * stride_xd, + mask=column < D, + other=0.0, + ) + x = x.to(tl.float16) if FP16 else x.to(tl.bfloat16) + x = x.to(tl.float32) + row_norm += tl.sum(x * x, axis=0) + + partition = tl.arange(0, BLOCK_PARTITIONS) + mask = partition < PARTITIONS + offset = row * PARTITIONS + partition + score = tl.load( + partial_score_ptr + offset, + mask=mask, + other=float("inf"), + ) + # Partitions are in centroid order, so a left tie is the lowest label. + best_score, best_partition = tl.min( + score, + axis=0, + return_indices=True, + return_indices_tie_break_left=True, + ) + partial_label = tl.load(partial_label_ptr + offset, mask=mask, other=0) + best_label = tl.sum( + tl.where(partition == best_partition, partial_label, 0), axis=0 + ) + if SPHERICAL: + distance = best_score + elif FP8: + rows = row + tl.arange(0, 1).to(tl.int64) + labels = best_label + tl.arange(0, 1) + distance = tl.sum(_selected_fp8_distance( + x_ptr, centroid_ptr, rows, labels, D, + stride_xb, stride_xd, stride_ck, stride_cd, rows < B, BLOCK_D, + ), axis=0) + else: + distance = tl.maximum(best_score + row_norm, 0.0) + tl.store(distance_ptr + row, distance) + tl.store(label_ptr + row, best_label.to(tl.int64)) + if SECOND: + # Exact merge: the winner's own second, or another partition's best. + second = tl.min(tl.where(partition == best_partition, tl.load( + partial_second_ptr + offset, mask=mask, other=float("inf")), score), axis=0) + if FP8: + alternate_scores = tl.where(partition == best_partition, tl.load( + partial_second_ptr + offset, mask=mask, other=float("inf")), score) + alternate_labels = tl.where(partition == best_partition, tl.load( + partial_second_label_ptr + offset, mask=mask, other=2147483647), partial_label) + second_label = tl.min(tl.where(mask & (alternate_scores == second), alternate_labels, 2147483647), axis=0) + second = tl.sum( + _selected_fp8_distance( + x_ptr, + centroid_ptr, + rows, + second_label + tl.arange(0, 1), + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + rows < B, + BLOCK_D, + ), + axis=0, + ) + if second_label_ptr is not None: + tl.store(second_label_ptr + row, second_label.to(tl.int64)) + elif not SPHERICAL: + second = tl.maximum(second + row_norm, 0.0) + tl.store(second_ptr + row, second) + if SECOND_LABEL: + # The partition holding the second: the winner's own second, or another partition's best. + own_label = tl.load(partial_second_label_ptr + offset, mask=mask, other=-1) + _, second_partition = tl.min( + tl.where(partition == best_partition, tl.load( + partial_second_ptr + offset, mask=mask, other=float("inf")), score), + axis=0, return_indices=True, return_indices_tie_break_left=True) + second_label = tl.sum(tl.where(partition == second_partition, tl.where( + partition == best_partition, own_label, partial_label), 0), axis=0) + own_pending = tl.load(partial_pending_ptr + offset, mask=mask, other=-1) + pending = tl.sum(tl.where((partition == second_partition) & (partition == best_partition), + own_pending + 1, 0), axis=0) - 1 + tl.store(second_label_ptr + row, second_label) + tl.store(pending_ptr + row, pending) + + +@triton.jit +def _stage_int8_rows_kernel( + x_ptr, + prepared_ptr, + D, + stride_xb, + stride_xd, + stride_pb, + UNSIGNED: tl.constexpr, + BLOCK_D: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + mask = column < D + value = tl.load( + x_ptr + row * stride_xb + column * stride_xd, + mask=mask, + other=0, + ) + if UNSIGNED: + value = value.to(tl.int16) - 128 + value = tl.where(mask, value, 0).to(tl.int8) + tl.store( + prepared_ptr + row * stride_pb + column, + value, + mask=column < stride_pb, + ) + + +@triton.jit +def _prepare_int8_kernel( + centroid_ptr, + prepared_ptr, + norm_ptr, + D, + stride_ck, + stride_cd, + stride_pk, + UNSIGNED: tl.constexpr, + BLOCK_D: tl.constexpr, +): + centroid = tl.program_id(0).to(tl.int64) + norm = tl.zeros((), tl.int32) + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + mask = column < D + value = tl.load( + centroid_ptr + centroid * stride_ck + column * stride_cd, + mask=mask, + other=0.0, + ) + if UNSIGNED: + value = _int8_libdevice.rint(value - 128.0) + else: + value = _int8_libdevice.rint(value) + value = tl.maximum(-128.0, tl.minimum(127.0, value)) + value = tl.where(mask, value, 0).to(tl.int8) + tl.store( + prepared_ptr + centroid * stride_pk + column, + value, + mask=column < stride_pk, + ) + value = value.to(tl.int32) + norm += tl.sum(value * value, axis=0) + tl.store(norm_ptr + centroid, norm) + + +@triton.jit +def _assign_int8_kernel( + x_ptr, + centroid_ptr, + centroid_norm_ptr, + distance_ptr, + label_ptr, + B, + K, + D, + stride_xb, + stride_xd, + stride_ck, + stride_cd, + UNSIGNED: tl.constexpr, + BLOCK_B: tl.constexpr, + BLOCK_K: tl.constexpr, + BLOCK_D: tl.constexpr, + WIDE_CENTROID: tl.constexpr, + FULL_D: tl.constexpr, + PACKED: tl.constexpr, + second_ptr=None, + second_label_ptr=None, + SECOND: tl.constexpr = False, + x_desc=None, + centroid_desc=None, +): + row_program = tl.program_id(0).to(tl.int64) + lane = tl.arange(0, BLOCK_B).to(tl.int64) + row = row_program * BLOCK_B + lane + row_mask = row < B + row_norm = tl.zeros((BLOCK_B,), tl.int32) + + for d0 in range(0, D, BLOCK_D): + column = d0 + tl.arange(0, BLOCK_D) + column_mask = column < D + value = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & column_mask[None, :], + other=0, + ) + if UNSIGNED: + value = value.to(tl.int16) - 128 + value = tl.where(column_mask[None, :], value, 0).to(tl.int8) + value = value.to(tl.int32) + row_norm += tl.sum(value * value, axis=1) + + if FULL_D: + # Keep the narrow row operand resident across the centroid search. + column = tl.arange(0, BLOCK_D) + full_x = tl.load( + x_ptr + row[:, None] * stride_xb + column[None, :] * stride_xd, + mask=row_mask[:, None] & (column[None, :] < D), other=0, + ) + if UNSIGNED: + full_x = full_x.to(tl.int16) - 128 + full_x = tl.where(column[None, :] < D, full_x, 0).to(tl.int8) + + best_score = tl.full((BLOCK_B,), 2147483647, tl.int32) + best_label = tl.zeros((BLOCK_B,), tl.int32) + if SECOND: + second_key = tl.full((BLOCK_B,), 9223372036854775807, tl.int64) + for k0 in tl.range(0, K, BLOCK_K, flatten=x_desc is not None): + centroid = k0 + tl.arange(0, BLOCK_K) + centroid_mask = centroid < K + score = tl.zeros((BLOCK_B, BLOCK_K), tl.int32) + if FULL_D: + column = tl.arange(0, BLOCK_D) + if WIDE_CENTROID: + centroid_offset = ( + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd + ) + else: + centroid_offset = ( + centroid[:, None] * stride_ck + column[None, :] * stride_cd + ) + c = tl.load( + centroid_ptr + centroid_offset, + mask=centroid_mask[:, None] & (column[None, :] < D), other=0, + ) + score = tl.dot(full_x, tl.trans(c), out_dtype=tl.int32) + else: + for d0 in range(0, D, BLOCK_D): + if x_desc is None: + column = d0 + tl.arange(0, BLOCK_D) + column_mask = column < D + value = tl.load( + x_ptr + + row[:, None] * stride_xb + + column[None, :] * stride_xd, + mask=row_mask[:, None] & column_mask[None, :], + other=0, + ) + if UNSIGNED: + value = value.to(tl.int16) - 128 + value = tl.where(column_mask[None, :], value, 0).to(tl.int8) + if WIDE_CENTROID: + centroid_offset = ( + centroid[:, None].to(tl.int64) * stride_ck + + column[None, :].to(tl.int64) * stride_cd + ) + else: + centroid_offset = ( + centroid[:, None] * stride_ck + + column[None, :] * stride_cd + ) + c = tl.load( + centroid_ptr + centroid_offset, + mask=centroid_mask[:, None] & column_mask[None, :], + other=0, + ) + else: + value = x_desc.load([tl.program_id(0) * BLOCK_B, d0]) + c = centroid_desc.load([k0, d0]) + if UNSIGNED: + # Unstaged UINT8: zero-filled centroid tails cancel -128. + value = (value.to(tl.int16) - 128).to(tl.int8) + score = tl.dot( + value, + tl.trans(c), + acc=score, + out_dtype=tl.int32, + ) + + norm = tl.load( + centroid_norm_ptr + centroid, + mask=centroid_mask, + other=0 if PACKED else 2147483647, + ) + if PACKED: + # Masked norms are zero, so every intermediate stays in range. + base = tl.where(centroid_mask, + norm * BLOCK_K + tl.arange(0, BLOCK_K), 2147483647) + packed = base[None, :] - 2 * BLOCK_K * score + key = tl.min(packed, axis=1) + local = key & (BLOCK_K - 1) + block_score = (key - local) // BLOCK_K + block_label = local + k0 + if SECOND: + other = tl.min( + tl.where( + centroid_mask[None, :] + & (tl.arange(0, BLOCK_K)[None, :] != local[:, None]), + packed, + 2147483647, + ), + axis=1, + ) + other_local = other & (BLOCK_K - 1) + other_score = (other - other_local) // BLOCK_K + other_label = other_local + k0 + other_valid = other != 2147483647 + else: + score = norm[None, :] - 2 * score + block_score, block_label = tl.min( + score, + axis=1, + return_indices=True, + return_indices_tie_break_left=True, + ) + if SECOND: + other_score, other_local = tl.min( + tl.where( + centroid_mask[None, :] + & ( + tl.arange(0, BLOCK_K)[None, :] + != block_label[:, None] + ), + score, + 2147483647, + ), + axis=1, + return_indices=True, + return_indices_tie_break_left=True, + ) + other_label = other_local.to(tl.int32) + k0 + other_valid = other_score != 2147483647 + block_label = block_label.to(tl.int32) + k0 + better = block_score < best_score + if SECOND: + # Signed score in the high word, global ID in the low word: exact order. + previous_key = tl.where( + best_score != 2147483647, + best_score.to(tl.int64) * 4294967296 + best_label.to(tl.int64), + 9223372036854775807, + ) + block_key = block_score.to(tl.int64) * 4294967296 + block_label.to(tl.int64) + other_key = tl.where( + other_valid, + other_score.to(tl.int64) * 4294967296 + + other_label.to(tl.int64), + 9223372036854775807, + ) + second_key = tl.where(better, tl.minimum(previous_key, other_key), + tl.minimum(second_key, block_key)) + best_score = tl.where(better, block_score, best_score) + best_label = tl.where(better, block_label, best_label) + + distance = best_score.to(tl.int64) + row_norm.to(tl.int64) + distance = tl.maximum(distance, 0).to(distance_ptr.dtype.element_ty) + tl.store(distance_ptr + row, distance, mask=row_mask) + tl.store(label_ptr + row, best_label.to(tl.int64), mask=row_mask) + if SECOND: + # The caller rejects K<2, so every valid row has a second logical candidate. + second_score = second_key >> 32 + second_distance = tl.maximum(second_score + row_norm.to(tl.int64), 0) + tl.store(second_ptr + row, second_distance.to(second_ptr.dtype.element_ty), mask=row_mask) + if second_label_ptr is not None: + tl.store(second_label_ptr + row, second_key & 0xFFFFFFFF, mask=row_mask) + + +def _use_split_k(b, k, d, is_reduced, direct_block_d=_DIRECT_REDUCED_BLOCK_D): + """Add parallelism only to a small grid after accounting for padding work.""" + if not is_reduced or _split_k_partitions(b, k) == 1: + return False + rows = triton.cdiv(b, _DIRECT_BLOCK_B) + direct_span = triton.cdiv(d, direct_block_d) * direct_block_d + split_span = triton.cdiv(d, _SPLIT_K_BLOCK_D) * _SPLIT_K_BLOCK_D + # About one wave of the original four-wave target. A wider reduction tile + # can double work for short rows; avoid it on an already adequate row grid. + return rows * split_span < (_SPLIT_K_TARGET_PROGRAMS // 4) * direct_span + + +def _split_k_partitions(b, k): + """Bound parallelism and ensure each partition has several K tiles. + + The program target amortizes the extra reduction launch on undersubscribed + row grids; four tiles per partition avoid trivial partial searches. Both + are conservative performance defaults, not a measured portable crossover. + """ + k_blocks = triton.cdiv(k, _SPLIT_K_BLOCK_K) + b_blocks = triton.cdiv(b, _SPLIT_K_BLOCK_B) + maximum = max(1, min( + k_blocks // _SPLIT_K_MIN_TILES_PER_PARTITION, _SPLIT_K_MAX_PARTITIONS + )) + partitions = 1 + while (2 * partitions <= maximum + and b_blocks * partitions < _SPLIT_K_TARGET_PROGRAMS): + partitions *= 2 + return partitions + + +def _descriptor_layout(tensor): + byte_pitch = tensor.stride(0) * tensor.element_size() + return (tensor.stride(1) == 1 and tensor.data_ptr() % 16 == 0 + and 0 < byte_pitch < 2**40 and byte_pitch % 16 == 0 + and all(0 < dim <= 2**31 for dim in tensor.shape)) + + +def _descriptor_from_tensor(): + factory = getattr(TensorDescriptor, "from_tensor", None) + if not callable(factory): + raise ImportError("selected Triton assignment requires callable " + "triton.tools.tensor_descriptor.TensorDescriptor.from_tensor") + return factory + + +_RESOLVE_ROWS = 32 # Rows per resolve program: about 2x faster than 128 at k = 16384. +# Pending second labels are resolved after the scan up to the direct kernel's full-d +# width (_FULL_D_MAX_D), so the switch follows an existing kernel boundary. Searching +# in the scan instead costs +10% at d = 96, +0.5..0.8% at d = 256, and wins at +# d = 1024. +_DEFER_SECOND_LABEL_MAX_D = _FULL_D_MAX_D + + +def _resolve_pending(x, centroids, centroid_norm, labels, second_label, pending, tile, fp16): + """Second labels the scan left pending (see ``_merge_second_label``).""" + b, d = x.shape + # One centroid tile leaves every finite row pending. Give each row its + # own program instead of serializing 32 dense rescans in one program. + rows = 1 if len(centroids) <= tile else _RESOLVE_ROWS + _resolve_second_kernel[(triton.cdiv(b, rows),)]( + x, centroids, centroid_norm, labels, second_label, pending, b, centroids.shape[0], d, + x.stride(0), x.stride(1), centroids.stride(0), centroids.stride(1), + TILE=tile, BLOCK_D=min(128, triton.next_power_of_2(d)), ROWS=rows, FP16=fp16, + num_warps=4) + + +def _launch_assignment( + x, centroids, centroid_norm, distance, labels, wide_centroid, spherical=False, + second=None, second_label=None, +): + b, d = x.shape + k = centroids.shape[0] + is_reduced = centroids.dtype != torch.float32 + is_fp16 = centroids.dtype == torch.float16 + # Second labels left pending by the scan are resolved after it, up to d = 128; + # wider rows search the column in the scan (see _merge_second_label). + defer = d <= _DEFER_SECOND_LABEL_MAX_D + pending = None if second_label is None else torch.empty(b, dtype=torch.int32, device=x.device) + is_fp8 = centroids.dtype == _FLOAT8_E4M3FN + if is_fp8 and second is not None and second_label is None: + second_label = torch.empty(b, dtype=torch.int32, device=x.device) + direct_block_d = _DIRECT_REDUCED_BLOCK_D if is_reduced else _DIRECT_FP32_BLOCK_D + # E4M3 benefits from a wider contraction tile when it adds no padded work. + # This replaces the old fitted D>=512 gate with the actual padded span. + if (is_fp8 and triton.cdiv(d, 128) * 128 + == triton.cdiv(d, _DIRECT_REDUCED_BLOCK_D) * _DIRECT_REDUCED_BLOCK_D): + direct_block_d = 128 + split_k = _use_split_k(b, k, d, is_reduced, direct_block_d) + if not split_k: + full_d = ( + is_reduced + and _DIRECT_REDUCED_BLOCK_D < d <= _FULL_D_MAX_D + ) + use_descriptors = ( + not full_d + and is_reduced + and d > _FULL_D_MAX_D + and x.dtype == centroids.dtype + and torch.cuda.get_device_capability(x.device) == (9, 0) + and all( + t.stride(0) >= t.shape[1] and _descriptor_layout(t) + for t in (x, centroids) + ) + ) + if full_d: + block_b, block_k, num_warps, num_stages = _full_d_config(x.device) + block_d = max(16, triton.next_power_of_2(d)) + else: + # Match Triton's D/element-stride divisibility and pointer alignment. + block_b = (128 if is_reduced and not is_fp8 and d > _FULL_D_MAX_D and d % 16 == 0 + and all(t.stride(1) == 1 and t.stride(0) % 16 == 0 + and t.data_ptr() % 16 == 0 for t in (x, centroids)) + else _DIRECT_BLOCK_B) + block_k = _DIRECT_BLOCK_K if is_reduced else 128 + block_d = direct_block_d + num_warps = 8 + num_stages = _NUM_STAGES + if is_fp8 and use_descriptors: + block_b = 128 + descriptors = {} + if use_descriptors: + from_tensor = _descriptor_from_tensor() + descriptors = dict( + x_desc=from_tensor(x, [block_b, block_d]), + centroid_desc=from_tensor( + centroids, [block_k // 2 if is_fp8 else block_k, block_d], + ), + ) + _assign_kernel[(triton.cdiv(b, block_b),)]( + x, + centroids, + centroid_norm, + distance, + labels, + b, + k, + d, + x.stride(0), + x.stride(1), + centroids.stride(0), + centroids.stride(1), + BLOCK_B=block_b, + BLOCK_K=block_k, + BLOCK_D=block_d, + FULL_D=full_d, + REDUCED=is_reduced, + FP16=is_fp16, + FP8=is_fp8, + WIDE_CENTROID=wide_centroid, + SPHERICAL=spherical, + second_ptr=second, + SECOND=second is not None, + second_label_ptr=second_label, + SECOND_LABEL=second_label is not None and not is_fp8, + pending_ptr=pending, + DEFER_SECOND_LABEL=defer, + **descriptors, + num_warps=num_warps, + num_stages=num_stages, + ) + if second_label is not None and defer and not is_fp8: + _resolve_pending(x, centroids, centroid_norm, labels, second_label, pending, + block_k // 2 if is_fp8 and use_descriptors else block_k, is_fp16) + return + + partitions = _split_k_partitions(b, k) + partial_score = torch.empty( + (b, partitions), dtype=torch.float32, device=x.device + ) + partial_label = torch.empty( + (b, partitions), dtype=torch.int32, device=x.device + ) + partial_second = None if second is None else torch.empty_like(partial_score) + partial_second_label = None if second_label is None else torch.empty_like(partial_label) + partial_pending = None if second_label is None else torch.empty_like(partial_label) + _assign_split_k_kernel[ + (triton.cdiv(b, _SPLIT_K_BLOCK_B), partitions) + ]( + x, + centroids, + centroid_norm, + partial_score, + partial_label, + b, + k, + d, + x.stride(0), + x.stride(1), + centroids.stride(0), + centroids.stride(1), + PARTITIONS=partitions, + BLOCK_B=_SPLIT_K_BLOCK_B, + BLOCK_K=_SPLIT_K_BLOCK_K, + BLOCK_D=_SPLIT_K_BLOCK_D, + FP16=is_fp16, + FP8=is_fp8, + WIDE_CENTROID=wide_centroid, + partial_second_ptr=partial_second, + SECOND=second is not None, + partial_second_label_ptr=partial_second_label, + SECOND_LABEL=second_label is not None and not is_fp8, + partial_pending_ptr=partial_pending, + DEFER_SECOND_LABEL=defer, + num_warps=_SPLIT_K_NUM_WARPS, + num_stages=_SPLIT_K_NUM_STAGES, + ) + _reduce_split_k_kernel[(b,)]( + x, + centroids, + partial_score, + partial_label, + distance, + labels, + b, + d, + x.stride(0), + x.stride(1), + centroids.stride(0), + centroids.stride(1), + PARTITIONS=partitions, + BLOCK_PARTITIONS=triton.next_power_of_2(partitions), + BLOCK_D=128, + FP16=is_fp16, + FP8=is_fp8, + SPHERICAL=spherical, + partial_second_ptr=partial_second, + second_ptr=second, + SECOND=second is not None, + partial_second_label_ptr=partial_second_label, + second_label_ptr=second_label, + SECOND_LABEL=second_label is not None and not is_fp8, + partial_pending_ptr=partial_pending, + pending_ptr=pending, + num_warps=4, + ) + if second_label is not None and defer and not is_fp8: + _resolve_pending(x, centroids, centroid_norm, labels, second_label, pending, _SPLIT_K_BLOCK_K, is_fp16) + + +def _pad_columns(value, multiple): + """Return unit-stride rows whose width and stride are multiples.""" + if value.stride(1) == 1 and not (value.shape[1] % multiple or value.stride(0) % multiple): + return value + d = value.shape[1] + result = value.new_zeros((len(value), d + -d % multiple)) + result[:, :d] = value + return result + + +def _int8_unsigned(source): + if source == "int8": + return False + if source == "uint8": + return True + raise ValueError("unsupported INT8 representation %r" % source) + + +def _int8_physical_d(d): + return ( + (d + _INT8_D_ALIGNMENT - 1) + // _INT8_D_ALIGNMENT + * _INT8_D_ALIGNMENT + ) + + +def _check_int8_source(x, source): + from .quantizer_int8 import _check_int8_support + + _check_int8_support(x.device) + return _int8_unsigned(source) + + +def prepare_int8_centroids(centroids, representation, *, validate=True): + """Return signed-byte centroids and their matched INT32 norms.""" + unsigned = _check_int8_source(centroids, representation) + _load_int8_libdevice() + if centroids.dtype != torch.float32 or centroids.ndim != 2: + raise TypeError("INT8 centroid preparation requires an FP32 matrix") + if validate and not bool(torch.isfinite(centroids).all()): + raise ValueError("INT8 centroids must be finite") + k, d = centroids.shape + if d > _INT8_MAX_D: + raise ValueError("INT8 assignment requires d <= 43919") + with torch.cuda.device(centroids.device): + physical_d = _int8_physical_d(d) + prepared = torch.empty( + (k, physical_d), dtype=torch.int8, device=centroids.device + ) + norm = torch.empty(k, dtype=torch.int32, device=centroids.device) + _prepare_int8_kernel[(k,)]( + centroids, + prepared, + norm, + d, + centroids.stride(0), + centroids.stride(1), + prepared.stride(0), + UNSIGNED=unsigned, + BLOCK_D=_INT8_PREPARE_BLOCK_D, + num_warps=4, + ) + return prepared, norm + + +def assign_int8_rows( + x, + centroids, + centroid_norm, + representation, + distance_out=None, + second_out=None, + second_labels_out=None, +): + """Return exact-ranking INT8 distances and centroid indices. + + centroid_norm must be the squared norms of the matching signed-byte centroids. + Distances default to FP32; a caller INT64 vector retains exact integer values. + Optional SECOND uses the same raw-distance dtype and may retain its distinct ID. + Encoded SECOND requires at least two logical centroids. + """ + if ( + x.device.type != "cuda" + or centroids.device != x.device + or centroid_norm.device != x.device + ): + raise ValueError( + "Triton assignment requires tensors on one CUDA device" + ) + unsigned = _check_int8_source(x, representation) + expected_dtype = { + "int8": (torch.int8,), + "uint8": (torch.uint8,), + }[representation] + if x.dtype not in expected_dtype or centroids.dtype != torch.int8: + raise TypeError( + "INT8 assignment input does not match its representation" + ) + if centroid_norm.dtype != torch.int32: + raise TypeError("INT8 centroid norms must be int32") + if x.ndim != 2 or centroids.ndim != 2 or centroid_norm.ndim != 1: + raise ValueError("INT8 assignment expects matrices and a norm vector") + b, d = x.shape + k, centroid_d = centroids.shape + if second_labels_out is not None and second_out is None: + raise ValueError("second labels require second distances") + if second_out is not None and k < 2: + raise ValueError("encoded SECOND requires at least two centroids") + if d > _INT8_MAX_D: + raise ValueError("INT8 assignment requires d <= 43919") + if k > _MAX_K: + raise ValueError("Triton assignment requires k <= 2**31 - 256") + physical_d = _int8_physical_d(d) + if physical_d != centroid_d or centroid_norm.shape[0] != k: + raise ValueError("INT8 assignment shapes do not match") + if not centroid_norm.is_contiguous(): + raise ValueError("centroid_norm must be contiguous") + if distance_out is not None and ( + distance_out.dtype not in (torch.float32, torch.int64) + or distance_out.device != x.device + or distance_out.shape != (b,) + or not distance_out.is_contiguous() + ): + raise ValueError("distance output must be a same-device contiguous FP32/INT64 vector") + distance_dtype = torch.float32 if distance_out is None else distance_out.dtype + if second_out is not None and ( + second_out.dtype != distance_dtype or second_out.device != x.device + or second_out.shape != (b,) or not second_out.is_contiguous() + ): + raise ValueError("second distance output must match the first raw FP32/INT64 vector") + if second_labels_out is not None and ( + second_labels_out.dtype != torch.int64 or second_labels_out.device != x.device + or second_labels_out.shape != (b,) or not second_labels_out.is_contiguous() + ): + raise ValueError("second labels must be a same-device contiguous INT64 vector") + + stage_rows = physical_d != d + full_d = physical_d <= 256 + # The staged width is bounded and16-aligned by _int8_physical_d; + # its CUDA allocation has aligned unit-stride rows. Check before staging. + use_descriptors = (not full_d + and torch.cuda.get_device_capability(x.device) == (9, 0) + and _descriptor_layout(centroids) + and (0 < b <= 2**31 if stage_rows else _descriptor_layout(x))) + from_tensor = _descriptor_from_tensor() if use_descriptors else None + + with torch.cuda.device(x.device): + if stage_rows: + staged = torch.empty( + (b, physical_d), dtype=torch.int8, device=x.device + ) + _stage_int8_rows_kernel[(b,)]( + x, + staged, + d, + x.stride(0), + x.stride(1), + staged.stride(0), + UNSIGNED=unsigned, + BLOCK_D=_INT8_PREPARE_BLOCK_D, + num_warps=4, + ) + x = staged + unsigned = False + distance = (torch.empty(b, dtype=torch.float32, device=x.device) + if distance_out is None else distance_out) + labels = torch.empty(b, dtype=torch.int64, device=x.device) + wide_centroid = _centroid_offset_is_wide( + centroids.shape, centroids.stride() + ) + # Wider operands retain the original launch configuration. + block_b, block_k, num_warps = ( + (128, 128, 4) if full_d else (_INT8_BLOCK_B, _INT8_BLOCK_K, 8) + ) + descriptors = {} + if use_descriptors: + descriptors = dict( + x_desc=from_tensor(x, [block_b, _INT8_BLOCK_D]), + centroid_desc=from_tensor(centroids, [block_k, _INT8_BLOCK_D]), + ) + _assign_int8_kernel[(triton.cdiv(b, block_b),)]( + x, + centroids, + centroid_norm, + distance, + labels, + b, + k, + physical_d, + x.stride(0), + x.stride(1), + centroids.stride(0), + centroids.stride(1), + UNSIGNED=unsigned, + BLOCK_B=block_b, + BLOCK_K=block_k, + BLOCK_D=(triton.next_power_of_2(max(_INT8_BLOCK_D, physical_d)) + if full_d else _INT8_BLOCK_D), + WIDE_CENTROID=wide_centroid, + FULL_D=full_d, + PACKED=48896 * physical_d * block_k + block_k - 1 < 2**31, + second_ptr=second_out, + second_label_ptr=second_labels_out, + SECOND=second_out is not None, + **descriptors, + num_warps=num_warps, + num_stages=3, + ) + return distance, labels + + +# Triton 3.8 mispacks E4M3 stores when d == 1 is specialized as a constant. +@triton.jit(do_not_specialize=["d"]) +def _cast_fp8_centroids_kernel( + source, + out, + squares, + peak, + bias, + k, + d, + width: tl.constexpr, + scale, + QUANTIZED: tl.constexpr, + AFFINE: tl.constexpr, + BLOCK: tl.constexpr, +): + lane = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK).to(tl.int64) + row, column = lane // width, lane % width + mask = (row < k) & (column < d) + value = tl.load(source + row * d + column, mask=mask, other=0.0) + if AFFINE: + shift = tl.load(bias + column, mask=mask, other=0.0) + value = tl.inline_asm_elementwise( + "fma.rn.f32 $0, $1, $2, $3;", + constraints="=f,f,f,f", + args=[value, scale, shift], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + elif QUANTIZED: + value = tl.inline_asm_elementwise( + "mul.rn.f32 $0, $1, $2;", + constraints="=f,f,f", + args=[value, scale], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + value = tl.where(mask, value, 0.0) + # Absolute finite bits are ordered; unsigned maximum also retains any prior NaN. + maximum = tl.max(tl.abs(value).to(tl.uint32, bitcast=True), 0) + tl.atomic_max(peak.to(tl.pointer_type(tl.uint32)), maximum) + code = value.to(out.dtype.element_ty, fp_downcast_rounding="rtne") + tl.store(out + lane, code, mask=row < k) + code = code.to(tl.float32) + tl.store(squares + row * d + column, code * code, mask=mask) + + +def _cast_fp8_centroids(source, quantizer, peak): + """FP8-only preparation; logical contiguous squares retain the ATen reduction.""" + if (type(source) is not torch.Tensor or not source.is_cuda + or source.dtype is not torch.float32 or not source.is_contiguous()): + return None + k, d = source.shape + bias = None if quantizer is None else quantizer._bias + if ( + quantizer is not None and type(quantizer.scale) is not float + ) or ( + bias is not None + and ( + type(bias) is not torch.Tensor + or bias.dtype is not torch.float32 + or bias.device != source.device + or bias.shape != (d,) + or not bias.is_contiguous() + ) + ): + return None + width = d + (-d % 64) + out, squares = source.new_empty((k, width), dtype=_FLOAT8_E4M3FN), source.new_empty((k, d)) + with torch.cuda.device(source.device): + _cast_fp8_centroids_kernel[(triton.cdiv(k * width, 2048),)]( + source, out, squares, peak.view(torch.int32), source if bias is None else bias, + k, d, width, 1.0 if quantizer is None else quantizer.scale, + QUANTIZED=quantizer is not None, AFFINE=bias is not None, + BLOCK=2048, num_warps=4, enable_fp_fusion=False) + torch.autograd.graph.increment_version(peak) + return out, squares.sum(dim=1) + + +@triton.jit +def _byte_stats_kernel(rows, labels, stats, n, d: tl.constexpr, row_stride, label_stride, + stats_stride, SHIFT: tl.constexpr, BLOCK: tl.constexpr): + lane = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK).to(tl.int64) + row, col = lane // (d + 1), lane % (d + 1) + valid = row < n + label = tl.load(labels + row * label_stride, mask=valid, other=0).to(tl.int64) + value = tl.load(rows + row * row_stride + col, + mask=valid & (col < d), other=0.0).to(stats.dtype.element_ty) + if SHIFT: + value -= 128 + value = tl.where(col == d, 1, value) + tl.atomic_add(stats + label * stats_stride + col, value, + mask=valid, sem="relaxed") + + +def accumulate_bytes(rows, labels, stats, *, fp8_code_units=False, shift=False): + """Add admitted typed rows to packed stats under whole-batch bounds. + + Internal assignment labels are valid; unit inner stride is required. + Whole-batch n<=2**24 keeps counts exact. INT8 n<=131072 or UINT8 n<=65793 + makes every FP32 sum addition exact. Raw bytes use bounded INT32 scratch; + shift subtracts 128 from UINT8 when 255*n could exceed INT32. + Finite native FP16 remains lattice-safe. + These lattices never reach FP32 subnormals. The caller excludes quantizers + and deterministic mode. + Opt-in finite E4M3 code units require a zeroed table and whole-batch n<=2**24; + FP32 RN sums have unspecified addition order, while counts remain exact. + """ + if ((rows.dtype not in (torch.int8, torch.uint8, torch.float16) + and not (fp8_code_units and rows.dtype is torch.float8_e4m3fn)) + or rows.stride(1) != 1): + return False + n, d = rows.shape + with torch.cuda.device(rows.device): + _byte_stats_kernel[(triton.cdiv(n * (d + 1), 512),)]( + rows, labels, stats, n, d, rows.stride(0), labels.stride(0), stats.stride(0), + SHIFT=shift, BLOCK=512, + ) + torch.autograd.graph.increment_version(stats) + return True + + +@triton.jit +def _copy_byte_stats_kernel(source, out, k, d: tl.constexpr, source_stride, out_stride, + UNSIGNED: tl.constexpr, BLOCK: tl.constexpr): + lane = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK).to(tl.int64) + row, col = lane // (d + 1), lane % (d + 1) + valid = row < k + value = tl.load(source + row * source_stride + col, mask=valid, other=0).to(tl.int64) + if UNSIGNED: + count = tl.load(source + row * source_stride + d, mask=valid, other=0).to(tl.int64) + value += tl.where(col < d, 128 * count, 0) + tl.store(out + row * out_stride + col, value, mask=valid) + + +def copy_byte_stats(source, out, *, unsigned): + """Reconstruct raw totals from disjoint bounded INT32 sums/counts.""" + k, width = source.shape + with torch.cuda.device(source.device): + _copy_byte_stats_kernel[(triton.cdiv(k * width, 512),)]( + source, out, k, width - 1, source.stride(0), out.stride(0), + UNSIGNED=unsigned, BLOCK=512) + torch.autograd.graph.increment_version(out) + + +@triton.jit +def _ema_update_kernel( + sums, counts, centroids, usage, k, d, sum_stride, count_stride, + alpha, decay, DECAY: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, + SCALARS: tl.constexpr = False, +): + if SCALARS: + alpha = tl.load(alpha) + decay = tl.load(decay) + row = (tl.program_id(0) * BLOCK_K + tl.arange(0, BLOCK_K)).to(tl.int64) + valid = row < k + count = tl.load(counts + row * count_stride, mask=valid, other=0.0).to(tl.float32) + old_usage = tl.load(usage + row, mask=valid, other=0.0) + touched = count > 0 + # Explicit RN operations preserve subnormals without FMA/reassociation. + retained = tl.inline_asm_elementwise( + "mul.rn.f32 $0, $1, $2;", constraints="=f,f,f", + args=[old_usage, decay], dtype=tl.float32, is_pure=True, pack=1, + ) if DECAY else 0.0 + step, mass = tl.inline_asm_elementwise( + "{ .reg .f32 increment, total; mul.rn.f32 increment, $2, $3; " + "add.rn.f32 total, $4, increment; mov.b32 $0, increment; mov.b32 $1, total; }", + constraints="=f,=f,f,f,f", args=[alpha, count, retained], + dtype=(tl.float32, tl.float32), is_pure=True, pack=1, + ) + weight = tl.math.div_rn(step, tl.where(touched, mass, 1.0)) + divisor = tl.where(touched, count, 1.0)[:, None] + for begin in range(0, d, BLOCK_D): + col = (begin + tl.arange(0, BLOCK_D)).to(tl.int64) + moving = valid[:, None] & touched[:, None] & (col < d)[None, :] + value = tl.load(sums + row[:, None] * sum_stride + col[None, :], + mask=moving, other=0.0).to(tl.float32) + offset = row[:, None] * d + col[None, :] + centroid = tl.load(centroids + offset, mask=moving, other=0.0) + mean = tl.math.div_rn(value, divisor) + position = tl.inline_asm_elementwise( + "{ .reg .f32 delta, scaled; sub.rn.f32 delta, $1, $2; " + "mul.rn.f32 scaled, delta, $3; add.rn.f32 $0, scaled, $2; }", + constraints="=f,f,f,f", args=[mean, centroid, weight[:, None]], + dtype=tl.float32, is_pure=True, pack=1, + ) + tl.store(centroids + offset, tl.where((weight == 1)[:, None], mean, position), + mask=moving) + # Retained usage can be reloaded per layout: finish every read before writing. + tl.debug_barrier() + tl.store(usage + row, tl.where(touched, mass, retained if DECAY else old_usage), + mask=valid) + + +def ema_update(sums, counts, centroids, usage, alpha, decay, replace_usage): + """Apply FP32 CUDA EMA from FP32, raw INT64 or bounded INT32 replay statistics. + + State is owned/contiguous; statistics have checked shape/dtype/device. + Rates are independently computed host floats or owned 0-dim FP32 device views. + Device rates are loaded in the kernel; no GPU values are scanned. + """ + if sums.stride(1) != 1: + return False + mutable = {centroids.untyped_storage().data_ptr(), usage.untyped_storage().data_ptr()} + if any(value.untyped_storage().data_ptr() in mutable for value in (sums, counts)): + return False + k, d = centroids.shape + block_d = min(triton.next_power_of_2(d), 1024) + block_k = max(1, 2048 // block_d) + sms = torch.cuda.get_device_properties(centroids.device).multi_processor_count + while block_k > 1 and triton.cdiv(k, block_k) < 2 * sms: + block_k //= 2 + with torch.cuda.device(centroids.device): + _ema_update_kernel[(triton.cdiv(k, block_k),)]( + sums, counts, centroids, usage, k, d, sums.stride(0), counts.stride(0), + alpha, decay, DECAY=not replace_usage, SCALARS=isinstance(alpha, torch.Tensor), + BLOCK_K=block_k, BLOCK_D=block_d, + num_warps=4, enable_fp_fusion=False, + ) + torch.autograd.graph.increment_version((centroids, usage)) + return True + + +@triton.jit +def _write_float_splits_kernel( + centroids, + usage, + source, + target, + axes, + norm, + d, + scale, + decode_exponent, + AXES: tl.constexpr, + BF16: tl.constexpr, + FP8: tl.constexpr, + SCALED: tl.constexpr, + BLOCK_D: tl.constexpr, + count=None, +): + # One pair owns both rows; hold donor operands in SSA until final stores. + # With a device count, programs past it write nothing. + live = True if count is None else tl.program_id(0) < tl.load(count) + donor = tl.load(source + tl.program_id(0)).to(tl.int64) + child = tl.load(target + tl.program_id(0)).to(tl.int64) + col = tl.arange(0, BLOCK_D).to(tl.int64) + value = tl.load(centroids + donor * d + col, mask=(col < d) & live, other=0.0) + low, high = value, value + if AXES: + # c_j -/+ s_j u_j as _half_mean_offsets: FP64, rounded once to FP32, N_j + # before halving. PyTorch CUDA divides by a host scalar through its + # reciprocal, so "/ pi" is "* fl(1 / pi)" here. + mass = tl.load(usage + donor, mask=live, other=0.0).to(tl.float64) + size = tl.load(norm + donor, mask=live, other=0.0) + valid = (size > 0) & (mass > 0) & (size < float("inf")) & (mass < float("inf")) + step = tl.inline_asm_elementwise( + "{ .reg .f64 t; div.rn.f64 t, $1, $2; mul.rn.f64 t, t, 0d4000000000000000; " + "mul.rn.f64 t, t, 0d3FD45F306DC9C883; sqrt.rn.f64 $0, t; }", + constraints="=d,d,d", args=[tl.where(valid, size, 0.0), tl.where(valid, mass, 1.0)], + dtype=tl.float64, is_pure=True, pack=1, + ) + axis = tl.load(axes + donor * d + col, mask=(col < d) & live, other=0.0) + low, high = tl.inline_asm_elementwise( + "{ .reg .f64 c, u, o, a, b; cvt.f64.f32 c, $2; cvt.f64.f32 u, $3; mul.rn.f64 o, $4, u; " + "sub.rn.f64 a, c, o; add.rn.f64 b, c, o; cvt.rn.f32.f64 $0, a; cvt.rn.f32.f64 $1, b; }", + constraints="=f,=f,f,f,d", args=[value, axis, step], + dtype=(tl.float32, tl.float32), is_pure=True, pack=1, + ) + if FP8: + low_code, high_code = low, high + if SCALED: + low_code = tl.inline_asm_elementwise( + "mul.rn.f32 $0, $1, $2;", + constraints="=f,f,f", + args=[low, scale], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + high_code = tl.inline_asm_elementwise( + "mul.rn.f32 $0, $1, $2;", + constraints="=f,f,f", + args=[high, scale], + dtype=tl.float32, + is_pure=True, + pack=1, + ) + low_bits = low_code.to(tl.float8e4nv, fp_downcast_rounding="rtne").to(tl.uint8, bitcast=True).to(tl.uint32) + high_bits = high_code.to(tl.float8e4nv, fp_downcast_rounding="rtne").to(tl.uint8, bitcast=True).to(tl.uint32) + elif BF16: + low_bits, high_bits = tl.inline_asm_elementwise( + "cvt.rn.bf16.f32 $0, $2; cvt.rn.bf16.f32 $1, $3;", + constraints="=h,=h,f,f", args=[low, high], + dtype=(tl.uint16, tl.uint16), is_pure=True, pack=1, + ) + low_bits, high_bits = low_bits.to(tl.uint32), high_bits.to(tl.uint32) + else: + low_bits, high_bits = low.to(tl.uint32, bitcast=True), high.to(tl.uint32, bitcast=True) + sign: tl.constexpr = 0x80 if FP8 else (0x8000 if BF16 else 0x80000000) + magnitude: tl.constexpr = sign - 1 + infinity: tl.constexpr = 0x7F if FP8 else (0x7F80 if BF16 else 0x7F800000) + low_abs, high_abs = low_bits & magnitude, high_bits & magnitude + equal = ((low_bits == high_bits) | ((low_abs == 0) & (high_abs == 0))) + equal = equal & (low_abs <= infinity) & (high_abs <= infinity) + if FP8: + equal = equal & (low_abs < infinity) & (high_abs < infinity) + collapsed = tl.sum(tl.where((col < d) & ~equal, 1, 0), 0) == 0 + # Represented nextafter toward +inf, otherwise inward; keep NaNs as NaNs. + negative = (high_bits & sign) != 0 + up = tl.where(high_abs == 0, 1, tl.where(negative, high_bits - 1, high_bits + 1)) + inward = tl.where(high_abs == 0, sign | 1, + tl.where(negative, high_bits + 1, high_bits - 1)) + moved = tl.where((up & magnitude) < infinity, up, inward) + moved = tl.where(high_abs > infinity, high_bits, moved) + if FP8: + neighbor = moved.to(tl.uint8).to(tl.float8e4nv, bitcast=True).to(tl.float32) + if SCALED: + neighbor = _fp8_libdevice.ldexp(neighbor, tl.load(decode_exponent)) + collapsed = collapsed & (tl.abs(neighbor) < float("inf")) + else: + neighbor = (moved << 16 if BF16 else moved).to(tl.float32, bitcast=True) + high = tl.where((col == 0) & collapsed, neighbor, high) + half = tl.inline_asm_elementwise( + "div.rn.f32 $0, $1, 0f40000000;", constraints="=f,f", + args=[tl.load(usage + donor, mask=live, other=0.0)], dtype=tl.float32, is_pure=True, pack=1, + ) + tl.store(centroids + donor * d + col, low, mask=(col < d) & live) + tl.store(centroids + child * d + col, high, mask=(col < d) & live) + tl.store(usage + donor, half, mask=live) + tl.store(usage + child, half, mask=live) + + +def _write_float_splits(centroids, usage, source, target, dtype, axes=None, norm=None, quantizer=None, count=None): + fp8 = _FLOAT8_E4M3FN is not None and dtype is _FLOAT8_E4M3FN + if axes is not None and (axes.shape != centroids.shape or axes.dtype != torch.float32 or norm.dtype != torch.float64 + or not axes.is_contiguous() or not norm.is_contiguous()): + return False + if quantizer is not None: + from .quantizer_fp8 import Fp8Quantizer + + if (not fp8 or type(quantizer) is not Fp8Quantizer + or quantizer.shift is not None or quantizer._bias is not None + or any(name in vars(quantizer) for name in ("compute_codes", "decode"))): + return False + if (dtype not in (None, torch.float32, torch.bfloat16, _FLOAT8_E4M3FN) + or not centroids.is_cuda or centroids.shape[1] > 8192 + or centroids.dtype != torch.float32 or usage.dtype != torch.float32 + or not centroids.is_contiguous() or not usage.is_contiguous()): + return False + if quantizer is not None and not callable(getattr(_fp8_libdevice, "ldexp", None)): + raise ImportError("scaled FP8 centroid splitting requires callable " + "triton.language.extra.cuda.libdevice.ldexp") + with torch.cuda.device(centroids.device): + _write_float_splits_kernel[(len(source),)]( + centroids, usage, source, target, axes, norm, centroids.shape[1], + 1.0 if quantizer is None else quantizer.scale, + None if quantizer is None else quantizer._decode_exponent, + AXES=axes is not None, BF16=dtype is torch.bfloat16, FP8=fp8, SCALED=quantizer is not None, + BLOCK_D=triton.next_power_of_2(centroids.shape[1]), + count=count, num_warps=max(4, triton.next_power_of_2(centroids.shape[1]) // 256), enable_fp_fusion=False, + ) + torch.autograd.graph.increment_version((centroids, usage)) + return True + + +def assign_rows(x, centroids, centroid_norm, *, spherical=False, return_score=False, + second_out=None, second_labels_out=None): + """Return nearest-centroid squared distances and indices. + + ``second_out`` receives the second distance. E4M3 retains approximate + selection and completes both selected represented distances identically. + It must be a same-device contiguous FP32 vector of length ``len(x)``. + ``second_labels_out`` (with ``second_out``) receives the second-nearest + indices, -1 when there is none: a same-device contiguous int32 vector. + + ``return_score=True`` returns the ranking score ``||c||² - 2*x.c`` + without adding the row norm or clamping. This preserves cross-shard + ranking, including negative scores, when evaluation recomputes distances + from the selected original FP32 operands. Centroid norms are supplied by + the caller in both modes. + """ + if ( + x.device.type != "cuda" + or centroids.device != x.device + or centroid_norm.device != x.device + ): + raise ValueError( + "Triton assignment requires tensors on one CUDA device" + ) + if x.dtype not in (torch.float32, centroids.dtype) or centroids.dtype not in ( + torch.float32, + torch.float16, + torch.bfloat16, + _FLOAT8_E4M3FN, + ): + raise TypeError( + "Triton rows must be FP32 or match floating centroid dtype; E4M3 must match" + ) + is_fp8 = centroids.dtype == _FLOAT8_E4M3FN + if return_score and is_fp8: + raise ValueError("ranking scores require unencoded floating operands") + if spherical and is_fp8: + raise ValueError("spherical Triton requires unencoded floating operands") + if is_fp8: + from .quantizer_fp8 import _check_fp8_support + + _check_fp8_support(x.device) + if x.dtype != _FLOAT8_E4M3FN: + raise TypeError("FP8 assignment requires native E4M3 rows") + if centroid_norm.dtype != torch.float32: + raise TypeError("centroid_norm must be float32") + if x.ndim != 2 or centroids.ndim != 2 or centroid_norm.ndim != 1: + raise ValueError("Triton assignment expects matrices and a norm vector") + b, d = x.shape + k, centroid_d = centroids.shape + if is_fp8 and second_out is not None and k < 2: + raise ValueError("encoded SECOND requires at least two centroids") + if k > _MAX_K: + raise ValueError("Triton assignment requires k <= 2**31 - 256") + if not centroid_norm.is_contiguous(): + raise ValueError("centroid_norm must be contiguous") + if d != centroid_d or centroid_norm.shape[0] != k: + raise ValueError("Triton assignment shapes do not match") + if second_out is not None: + if not isinstance(second_out, torch.Tensor): + raise TypeError("second output must be a tensor") + if (second_out.dtype != torch.float32 or second_out.device != x.device + or second_out.shape != (b,) or not second_out.is_contiguous()): + raise ValueError("second output must be a same-device contiguous FP32 vector of shape (%d,)" % b) + if second_labels_out is not None: + if second_out is None: + raise ValueError("second labels require second_out") + label_dtypes = (torch.int32, torch.int64) if x.dtype == torch.float8_e4m3fn else (torch.int32,) + if (not isinstance(second_labels_out, torch.Tensor) or second_labels_out.dtype not in label_dtypes + or second_labels_out.device != x.device or second_labels_out.shape != (b,) + or not second_labels_out.is_contiguous()): + raise ValueError("second labels must be a same-device contiguous integer vector of shape (%d,) with dtype %s" % (b, label_dtypes)) + with torch.cuda.device(x.device): + if is_fp8 or (d % 16 and centroids.dtype != torch.float32): + # Zero columns add exact zeros at unchanged tile positions. + x = _pad_columns(x, 64 if is_fp8 else 16) + centroids = _pad_columns(centroids, 64 if is_fp8 else 16) + distance = torch.empty(b, dtype=torch.float32, device=x.device) + labels = torch.empty(b, dtype=torch.int64, device=x.device) + wide_centroid = _centroid_offset_is_wide( + centroids.shape, centroids.stride() + ) + _launch_assignment( + x, + centroids, + centroid_norm, + distance, + labels, + wide_centroid, + # The kernel's spherical flag only suppresses row norms/clamping; + # the supplied centroid norms still determine L2 ranking. + spherical=spherical or return_score, + second=second_out, + second_label=second_labels_out, + ) + return distance, labels + + +@triton.jit +def _mul_rn(a, b): # FP32, never contracted to an FMA (as removal_update's enable_fp_fusion=False) + return tl.inline_asm_elementwise("mul.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, + is_pure=True, pack=1) + + +@triton.jit +def _add_rn(a, b): + return tl.inline_asm_elementwise("add.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, + is_pure=True, pack=1) + + +@triton.jit +def _removal_stats_kernel(rows, order, offsets, distance, second, axes, centroids, stats, removal, d, + row_stride, stats_stride, removal_stride, alpha, decay, BLOCK_R: tl.constexpr, + BLOCK_D: tl.constexpr, EMA: tl.constexpr, SCALARS: tl.constexpr, LONG: tl.constexpr): + # Centroid j owns its segment of label-sorted rows (one read of each row, no atomics) and + # adds [x | 1] to stats and [p y | d2 - d1] to removal, y = x - c, p = y.v; with EMA, removal is + # the EMA itself: [U | R] <- decay [U | R] + alpha (0 + this batch), V <- U / |U| where |U| > 0, + # for every centroid (as removal_update on a zero batch table). More than LONG rows: _long_pieces_kernel. + j = tl.program_id(0).to(tl.int64) + start = tl.load(offsets + j) + end = tl.load(offsets + j + 1) + col = tl.arange(0, BLOCK_D) + cmask = col < d + axis = tl.load(axes + j * d + col, mask=cmask, other=0.0) + oja = tl.zeros((BLOCK_D,), tl.float32) + margin = tl.zeros((BLOCK_R,), tl.float32) + short = end - start <= LONG + if (start < end) & short: + center = tl.load(centroids + j * d + col, mask=cmask, other=0.0) + total = tl.zeros((BLOCK_D,), tl.float32) + for begin in range(start, end, BLOCK_R): + lane = begin + tl.arange(0, BLOCK_R) + rmask = lane < end + row = tl.load(order + lane, mask=rmask, other=0).to(tl.int64) + value = tl.load(rows + row[:, None] * row_stride + col[None, :], + mask=rmask[:, None] & cmask[None, :], other=0.0).to(tl.float32) + total += tl.sum(value, axis=0) + y = tl.where(rmask[:, None] & cmask[None, :], value - center[None, :], 0.0) + oja += tl.sum(tl.sum(y * axis[None, :], axis=1)[:, None] * y, axis=0) + gap = tl.load(second + row, mask=rmask, other=0.0) - tl.load(distance + row, mask=rmask, other=0.0) + gap = tl.where(gap == float("-inf"), -3.4028234663852886e38, gap) # as nan_to_num(0, 0) + margin += tl.where(rmask & (gap == gap) & (gap < float("inf")), gap, 0.0) + out = stats + j * stats_stride + tl.store(out + col, tl.load(out + col, mask=cmask) + total, mask=cmask) + tl.store(out + d, tl.load(out + d) + (end - start).to(tl.float32)) + if not EMA: + out = removal + j * removal_stride + tl.store(out + col, tl.load(out + col, mask=cmask) + oja, mask=cmask) + tl.store(out + d, tl.load(out + d) + tl.sum(margin)) + if EMA: + if SCALARS: + alpha = tl.load(alpha) + decay = tl.load(decay) + if short: + out = removal + j * removal_stride + u = _add_rn(_mul_rn(tl.load(out + col, mask=cmask, other=0.0), decay), _mul_rn(alpha, 0.0 + oja)) + tl.store(out + col, u, mask=cmask) + tl.store(out + d, _add_rn(_mul_rn(tl.load(out + d), decay), _mul_rn(alpha, 0.0 + tl.sum(margin)))) + u = tl.where(cmask, u, 0.0).to(tl.float64) # FP64: |U|^2 can overflow FP32 + norm = tl.sqrt(tl.sum(u * u)) + tl.store(axes + j * d + col, (u / norm).to(tl.float32), mask=cmask & (norm > 0)) + + +def accumulate_removal(rows, labels, stats, distance, second, axes, centroids, removal, ema=None, + statistics_rows=None): + """Add [x | 1] to FP32 stats and [p y | d2 - d1] to removal by label (y = x - centroids, + p = y.axes), deterministically, from label-sorted rows. + + ema = (state, alpha, decay), only for a batch accumulated in this one call into a zero `removal` table + (left untouched): removal_update's EMA is applied to state and axes, and the result is "folded" (up to + d = 2048; above, True and removal_update as usual). alpha and decay are floats or 0-d tensors.""" + if statistics_rows is not None: + rows = statistics_rows + k, width = stats.shape + fits = not (not rows.is_cuda or not rows.dtype.is_floating_point or rows.stride(1) != 1 or width > 4097 + or width != rows.shape[1] + 1 or stats.stride(1) != 1 or removal.stride(1) != 1 + or not stats.dtype == removal.dtype == axes.dtype == centroids.dtype == torch.float32 + or not axes.is_contiguous() or not centroids.is_contiguous()) + if not fits: + return False + dtype = torch.int16 if k < 2**15 else torch.int32 # positions run to k inclusive + sorted_labels, order = torch.sort(labels.to(dtype)) + offsets = torch.searchsorted(sorted_labels, torch.arange(k + 1, device=rows.device, dtype=dtype)) + with torch.cuda.device(rows.device): + block_d = triton.next_power_of_2(rows.shape[1]) + # Short segments are latency-bound: small programs keep more of them in flight. + block_r, warps = (4, 1) if block_d <= 128 else (2, 2 if block_d <= 512 else 4 if block_d <= 2048 else 8) + # Same arithmetic as removal_update; from 4 warps (d > 512) its batch sums may differ by an ULP. + fold = ema is not None and block_d <= 2048 + state, alpha, decay = ema if fold else (removal, 0.0, 0.0) + scalars = isinstance(alpha, torch.Tensor) + _removal_stats_kernel[(k,)]( + rows, order, offsets, distance, second, axes, centroids, stats, state, rows.shape[1], + rows.stride(0), stats.stride(0), state.stride(0), alpha, decay, BLOCK_R=block_r, + BLOCK_D=block_d, EMA=fold, SCALARS=scalars, LONG=_LONG_SEGMENT, num_warps=warps) + pieces, partial, counter = _pieces(rows, stats, 2 * block_d + 1) + _long_pieces_kernel[(pieces,)]( + rows, order, offsets, sorted_labels, partial, counter, distance, second, axes, centroids, stats, state, + rows.shape[1], len(rows), rows.stride(0), stats.stride(0), state.stride(0), alpha, decay, + BLOCK_R=block_r, BLOCK_D=block_d, LONG=_LONG_SEGMENT, EMA=fold, SCALARS=scalars, num_warps=warps) + torch.autograd.graph.increment_version((stats, state, axes) if fold else (stats, removal)) + return "folded" if fold else True + + +@triton.jit +def _removal_update_kernel(stats, batch, axes, alpha, decay, k, d, stats_stride, batch_stride, + ROWS: tl.constexpr, BLOCK_W: tl.constexpr, SCALARS: tl.constexpr, + axis_norms=None): + # [U | R] <- decay [U | R] + alpha [sum p y | sum d2 - d1], which is then zeroed for the next + # batch; V <- U / |U| where |U| > 0. + if SCALARS: + alpha = tl.load(alpha) + decay = tl.load(decay) + j = tl.program_id(0).to(tl.int64) * ROWS + tl.arange(0, ROWS) + col = tl.arange(0, BLOCK_W) + live = (j < k)[:, None] & (col <= d)[None, :] + s = stats + j[:, None] * stats_stride + col[None, :] + b = batch + j[:, None] * batch_stride + col[None, :] + value = tl.load(s, mask=live) * decay + alpha * tl.load(b, mask=live) + tl.store(s, value, mask=live) + tl.store(b, tl.zeros_like(value), mask=live) + axis = tl.where(col[None, :] < d, value, 0.0).to(tl.float64) # FP64: |U|^2 can overflow FP32 + norm = tl.sqrt(tl.sum(axis * axis, axis=1)) + if axis_norms is not None: + tl.store(axis_norms + j, norm.to(tl.float32), mask=j < k) + tl.store(axes + j[:, None] * d + col[None, :], (axis / norm[:, None]).to(tl.float32), + mask=live & (col < d)[None, :] & (norm > 0)[:, None]) + + +def removal_update(stats, batch, axes, alpha, decay, axis_norms=None): + """Fused removal-statistics EMA, zeroing batch: stats bitwise as the torch ops; V from an FP64 |U|.""" + if not (stats.is_cuda and stats.dtype == batch.dtype == axes.dtype == torch.float32 + and stats.stride(1) == batch.stride(1) == 1 and axes.is_contiguous() and stats.shape[1] <= 8193): + return False + block_w = triton.next_power_of_2(stats.shape[1]) + rows = max(1, 2048 // block_w) + with torch.cuda.device(stats.device): + _removal_update_kernel[(triton.cdiv(len(stats), rows),)]( + stats, batch, axes, alpha, decay, len(stats), axes.shape[1], stats.stride(0), batch.stride(0), + ROWS=rows, BLOCK_W=block_w, SCALARS=isinstance(alpha, torch.Tensor), num_warps=4, + axis_norms=axis_norms, enable_fp_fusion=False) + torch.autograd.graph.increment_version((stats, batch, axes) + (() if axis_norms is None else (axis_norms,))) + return True + + +@triton.jit +def _removal_split_kernel(stats, axes, source, target, width, d, stats_stride, + BLOCK_W: tl.constexpr, BLOCK_D: tl.constexpr, count=None): + # Donor halves its removal statistics; the moved centroid copies them and the axis. + pair = tl.program_id(0) + live = True if count is None else pair < tl.load(count) + s = tl.load(source + pair).to(tl.int64) + t = tl.load(target + pair).to(tl.int64) + col = tl.arange(0, BLOCK_W) + half = tl.load(stats + s * stats_stride + col, mask=(col < width) & live) / 2 + tl.store(stats + s * stats_stride + col, half, mask=(col < width) & live) + tl.store(stats + t * stats_stride + col, half, mask=(col < width) & live) + dim = tl.arange(0, BLOCK_D) + tl.store(axes + t * d + dim, tl.load(axes + s * d + dim, mask=(dim < d) & live), mask=(dim < d) & live) + + +def removal_split(stats, axes, source, target, count): + """stats[source] /= 2; stats[target] = stats[source]; axes[target] = axes[source] (disjoint ids). + + A device ``count`` limits the pairs to source[:count], target[:count] (None: all pairs).""" + if not (stats.is_cuda and stats.stride(1) == 1 and axes.is_contiguous() + and stats.dtype == axes.dtype == torch.float32 and stats.shape[1] <= 8194): + return False + with torch.cuda.device(stats.device): + _removal_split_kernel[(len(source),)]( + stats, axes, source, target, stats.shape[1], axes.shape[1], stats.stride(0), + BLOCK_W=triton.next_power_of_2(stats.shape[1]), BLOCK_D=triton.next_power_of_2(axes.shape[1]), + count=count, num_warps=4) + torch.autograd.graph.increment_version((stats, axes)) + return True + + +@triton.jit +def _long_pieces(rows, order, offsets, sorted_labels, partial, counter, stats, d, n, row_stride, stats_stride, + BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr, LONG: tl.constexpr, + distance=None, second=None, axes=None, centroids=None, removal=None, removal_stride=0, + alpha=0.0, decay=0.0, REMOVAL: tl.constexpr = False, EMA: tl.constexpr = False): + # Program q takes the pieces of segments longer than LONG in label-sorted rows q LONG..(q + 1) LONG (the + # first and last segments there); the last of a segment's pieces adds them up in row order and flushes them + # as the per-centroid programs would: deterministic. + # REMOVAL: also [p y | d2 - d1] to removal, as _removal_stats_kernel. + # With EMA: removal_update's EMA of removal instead. + q = tl.program_id(0).to(tl.int64) + lo = q * LONG + hi = tl.minimum(lo + LONG, n) + col = tl.arange(0, BLOCK_D) + cmask = col < d + width = 2 * BLOCK_D + 1 if REMOVAL else BLOCK_D # partial sums per piece + first = tl.load(sorted_labels + lo) + for side in tl.static_range(2): # the chunk's first segment, then its last if another one + j = tl.load(sorted_labels + lo + side * (hi - 1 - lo)) + start = tl.load(offsets + j) + end = tl.load(offsets + j + 1) + j = j.to(tl.int64) + if (end - start > LONG) & ((side == 0) | (j != first)): + total = tl.zeros((BLOCK_D,), tl.float32) + if REMOVAL: + axis = tl.load(axes + j * d + col, mask=cmask, other=0.0) + center = tl.load(centroids + j * d + col, mask=cmask, other=0.0) + oja = tl.zeros((BLOCK_D,), tl.float32) + margin = tl.zeros((BLOCK_R,), tl.float32) + for begin in range(tl.maximum(start, lo), tl.minimum(end, hi), BLOCK_R): + lane = begin + tl.arange(0, BLOCK_R) + rmask = lane < tl.minimum(end, hi) + row = tl.load(order + lane, mask=rmask, other=0).to(tl.int64) + value = tl.load(rows + row[:, None] * row_stride + col[None, :], + mask=rmask[:, None] & cmask[None, :], other=0.0).to(tl.float32) + total += tl.sum(value, axis=0) + if REMOVAL: + y = tl.where(rmask[:, None] & cmask[None, :], value - center[None, :], 0.0) + oja += tl.sum(tl.sum(y * axis[None, :], axis=1)[:, None] * y, axis=0) + gap = tl.load(second + row, mask=rmask, other=0.0) - tl.load(distance + row, mask=rmask, other=0.0) + gap = tl.where(gap == float("-inf"), -3.4028234663852886e38, gap) # as nan_to_num(0, 0) + margin += tl.where(rmask & (gap == gap) & (gap < float("inf")), gap, 0.0) + # Piece slots: 2 p for chunks p = start // LONG..(end - 1) // LONG, 2 p + 1 if it starts inside chunk p. + slot = partial + (q * 2 + (start > lo).to(tl.int64)) * width + tl.store(slot + col, total) + if REMOVAL: + tl.store(slot + BLOCK_D + col, oja) + tl.store(slot + 2 * BLOCK_D, tl.sum(margin)) + # This condition is CTA-uniform: publish only after every warp's stores. + tl.debug_barrier() + if tl.atomic_add(counter + j, 1) == (end - 1) // LONG - start // LONG: # the last piece + total = tl.zeros((BLOCK_D,), tl.float32) + if REMOVAL: + oja = tl.zeros((BLOCK_D,), tl.float32) + gaps = 0.0 + for p in range(start // LONG, (end - 1) // LONG + 1): + slot = partial + (p * 2 + (start > p * LONG).to(tl.int64)) * width + total += tl.load(slot + col) + if REMOVAL: + oja += tl.load(slot + BLOCK_D + col) + gaps += tl.load(slot + 2 * BLOCK_D) + out = stats + j * stats_stride + tl.store(out + col, tl.load(out + col, mask=cmask) + total, mask=cmask) + tl.store(out + d, tl.load(out + d) + (end - start).to(tl.float32)) + if REMOVAL: + out = removal + j * removal_stride + if EMA: + u = _add_rn(_mul_rn(tl.load(out + col, mask=cmask, other=0.0), decay), + _mul_rn(alpha, 0.0 + oja)) + tl.store(out + col, u, mask=cmask) + tl.store(out + d, _add_rn(_mul_rn(tl.load(out + d), decay), _mul_rn(alpha, 0.0 + gaps))) + u = tl.where(cmask, u, 0.0).to(tl.float64) # FP64: |U|^2 can overflow FP32 + norm = tl.sqrt(tl.sum(u * u)) + tl.store(axes + j * d + col, (u / norm).to(tl.float32), mask=cmask & (norm > 0)) + else: + tl.store(out + col, tl.load(out + col, mask=cmask) + oja, mask=cmask) + tl.store(out + d, tl.load(out + d) + gaps) + + +@triton.jit +def _long_pieces_kernel(rows, order, offsets, sorted_labels, partial, counter, distance, second, axes, centroids, + stats, removal, d, n, row_stride, stats_stride, removal_stride, alpha, decay, + BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr, LONG: tl.constexpr, EMA: tl.constexpr, + SCALARS: tl.constexpr): + # accumulate_removal's long segments, in a launch of their own: inside _removal_stats_kernel, _long_pieces' + # registers would cost the per-centroid programs occupancy. + if EMA: + if SCALARS: + alpha = tl.load(alpha) + decay = tl.load(decay) + _long_pieces(rows, order, offsets, sorted_labels, partial, counter, stats, d, n, row_stride, stats_stride, BLOCK_R, + BLOCK_D, LONG, distance, second, axes, centroids, removal, removal_stride, alpha, decay, True, EMA) + + +_LONG_SEGMENT = 256 # rows; longer segments are summed in pieces (no single-program tail) + + +def _pieces(rows, stats, width): + """(number of LONG-row pieces, their partial sums, zeroed per-centroid piece counters of this call).""" + pieces = triton.cdiv(len(rows), _LONG_SEGMENT) + return pieces, stats.new_empty(2 * pieces, width), torch.zeros(len(stats), dtype=torch.int32, device=rows.device) + + +@triton.jit +def _segment_sums_kernel(rows, order, offsets, sorted_labels, partial, counter, stats, d, n, pieces, row_stride, + stats_stride, BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr, LONG: tl.constexpr): + # Program pieces + j: centroid j owns its segment of label-sorted rows (one read of each row, no atomics) + # unless it has more than LONG rows: programs < pieces sum those (_long_pieces). + if tl.program_id(0) < pieces: + _long_pieces(rows, order, offsets, sorted_labels, partial, counter, stats, d, n, row_stride, stats_stride, + BLOCK_R, BLOCK_D, LONG) + return + j = (tl.program_id(0) - pieces).to(tl.int64) + start = tl.load(offsets + j) + end = tl.load(offsets + j + 1) + if (start < end) & (end - start <= LONG): + col = tl.arange(0, BLOCK_D) + total = tl.zeros((BLOCK_D,), tl.float32) + for begin in range(start, end, BLOCK_R): + lane = begin + tl.arange(0, BLOCK_R) + row = tl.load(order + lane, mask=lane < end, other=0).to(tl.int64) + total += tl.sum(tl.load(rows + row[:, None] * row_stride + col[None, :], + mask=(lane < end)[:, None] & (col < d)[None, :], other=0.0).to(tl.float32), 0) + out = stats + j * stats_stride + tl.store(out + col, tl.load(out + col, mask=col < d) + total, mask=col < d) + tl.store(out + d, tl.load(out + d) + (end - start).to(tl.float32)) + + +def accumulate_segments(rows, labels, stats): + """Add [x | 1] rows to FP32 stats by label, deterministically: rows sorted by label.""" + k, width = stats.shape + if (not rows.is_cuda or stats.dtype != torch.float32 or not rows.dtype.is_floating_point + or rows.stride(1) != 1 or stats.stride(1) != 1 or width != rows.shape[1] + 1 or width > 4097): + return False + dtype = torch.int16 if k < 2**15 else torch.int32 # positions run to k inclusive + sorted_labels, order = torch.sort(labels.to(dtype)) + offsets = torch.searchsorted(sorted_labels, torch.arange(k + 1, device=rows.device, dtype=dtype)) + block_d = triton.next_power_of_2(rows.shape[1]) + # Short segments are latency-bound: small programs keep more of them in flight. + block_r, warps = ((16, 4) if len(rows) >= 8 * k else (4, 1) if block_d <= 128 + else (2, 2 if block_d <= 512 else 4)) + pieces, partial, counter = _pieces(rows, stats, block_d) + with torch.cuda.device(rows.device): + _segment_sums_kernel[(pieces + k,)]( + rows, order, offsets, sorted_labels, partial, counter, stats, rows.shape[1], len(rows), pieces, + rows.stride(0), stats.stride(0), BLOCK_R=block_r, BLOCK_D=block_d, LONG=_LONG_SEGMENT, num_warps=warps) + torch.autograd.graph.increment_version(stats) + return True + + +@triton.jit(do_not_specialize=["stride_inner"]) +def _closing_partials_kernel(x, stride_x, stride_inner, index, starts, offsets, owner, left, right, k, step, + d, PIECE: tl.constexpr, BLOCK_D: tl.constexpr, UNROLL: tl.constexpr, + CAST: tl.constexpr, UNIT_INNER: tl.constexpr): + # Piece p of centroid c: its sorted rows in [max(start, s * PIECE), min(end, (s + 1) * PIECE)), + # summed in FP64 in index order, split at a multiple of ``step`` if one falls inside. + p = tl.program_id(0) + if p < tl.load(offsets + k): + c = tl.load(owner + p) + start = tl.load(starts + c) + end = tl.load(starts + c + 1) + s = start // PIECE + (p - tl.load(offsets + c)) + lo = tl.maximum(start, s * PIECE) + hi = tl.minimum(end, (s + 1) * PIECE) + boundary = (lo // step + 1) * step + cols = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D) + live = cols < d + acc_l = tl.zeros([BLOCK_D], dtype=tl.float64) + acc_r = tl.zeros([BLOCK_D], dtype=tl.float64) + for q in range(lo, hi, UNROLL): + for u in tl.static_range(UNROLL): + valid = q + u < hi + row = tl.load(index + q + u, mask=valid, other=0) + value = tl.load(x + row * stride_x + (cols if UNIT_INNER else cols.to(tl.int64) * stride_inner), + mask=live & valid, other=0.0) + if CAST == 1: + value = value.to(tl.bfloat16) + elif CAST == 2: + value = value.to(tl.float16) + if value.dtype == tl.float8e4nv: + # Triton lowers FP8 widening through FP32, not directly + # to FP64. Every finite FP8 value is exact in FP32. + value = value.to(tl.float32) + value = tl.where(valid, value.to(tl.float64), 0.0) + before = q + u < boundary + acc_l += tl.where(before, value, 0.0) + acc_r += tl.where(before, 0.0, value) + tl.store(left + p * d + cols, acc_l, mask=live) + tl.store(right + p * d + cols, acc_r, mask=live) + + +@triton.jit +def _closing_flush_kernel(starts, offsets, left, right, sums, stride_s, counts, step, d, + PIECE: tl.constexpr, BLOCK_D: tl.constexpr): + # Centroid c: its piece partials in order, flushed into the sums at every + # multiple of ``step`` sorted positions, as a per-segment loop over blocks of + # ``step`` rows does. + c = tl.program_id(0) + start = tl.load(starts + c) + end = tl.load(starts + c + 1) + if start < end: + cols = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D) + live = cols < d + out = tl.load(sums + c * stride_s + cols, mask=live, other=0.0) + acc = tl.zeros([BLOCK_D], dtype=tl.float64) + cur = start // step + first = tl.load(offsets + c) + for p in range(first, tl.load(offsets + c + 1)): + s = start // PIECE + (p - first) + lo = tl.maximum(start, s * PIECE) + hi = tl.minimum(end, (s + 1) * PIECE) + block = lo // step + flush = block != cur + out = tl.where(flush, out + acc.to(out.dtype), out) + acc = tl.where(flush, 0.0, acc) + cur = block + acc += tl.load(left + p * d + cols, mask=live, other=0.0) + split = (block + 1) * step < hi + out = tl.where(split, out + acc.to(out.dtype), out) + acc = tl.where(split, tl.load(right + p * d + cols, mask=live, other=0.0), acc) + cur = tl.where(split, block + 1, cur) + out = out + acc.to(out.dtype) + tl.store(sums + c * stride_s + cols, out, mask=live) + if tl.program_id(1) == 0: + tl.store(counts + c, tl.load(counts + c) + (end - start).to(tl.float64)) + + +_CLOSING_CAST = {None: 0, torch.bfloat16: 1, torch.float16: 2} +_CLOSING_PIECE = 2048 + + +def closing_sums(x, index, starts, sums, counts, step, cast=None): + """Add to ``sums`` (k, d) and ``counts`` (k,) the rows ``x[index[starts[c] + : starts[c + 1]]]`` of each centroid c, ``index`` grouped by centroid in + ascending order: FP64 sums of fixed pieces of each run (in parallel), added + in order and converted to the sums' dtype at every multiple of ``step`` + positions of ``index`` (FP64 per-segment sums over blocks of ``step`` sorted + rows). ``cast`` rounds each row to that dtype first, as the model's row + preparation does. Deterministic: no atomics, a fixed reduction order, and + no host synchronization.""" + k, d = sums.shape + starts = starts.long() + end, begin = starts[1:], starts[:-1] + pieces = torch.where(end > begin, (end + _CLOSING_PIECE - 1) // _CLOSING_PIECE - begin // _CLOSING_PIECE, 0) + offsets = torch.cat((pieces.new_zeros(1), pieces.cumsum(0))) + bound = len(index) // _CLOSING_PIECE + 2 * k + 1 + # Piece -> its centroid (the last c with offsets[c] <= piece), on the device. + owner = torch.searchsorted(offsets, torch.arange(bound, device=sums.device), right=True) - 1 + left = torch.empty((bound, d), dtype=torch.float64, device=sums.device) + right = torch.empty_like(left) + block = min(128, triton.next_power_of_2(d)) + warps = 1 if block <= 32 else 2 if block <= 64 else 4 + _closing_partials_kernel[(bound, triton.cdiv(d, block))]( + x, x.stride(0), x.stride(1), index, starts, offsets, owner, left, right, k, step, d, + UNIT_INNER=x.stride(1) == 1, PIECE=_CLOSING_PIECE, BLOCK_D=block, UNROLL=8, CAST=_CLOSING_CAST[cast], num_warps=warps) + _closing_flush_kernel[(k, triton.cdiv(d, block))]( + starts, offsets, left, right, sums, sums.stride(0), counts, step, d, + PIECE=_CLOSING_PIECE, BLOCK_D=block, num_warps=warps) + + +@triton.jit(do_not_specialize=["stride_inner"]) +def _twin_route_kernel(x, stride_x, stride_inner, index, row_index, labels, stale, key, target, source, born, moved_at, + centroids, stride_c, n, begin, span, n_events, segment, d, + BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr, CAST: tl.constexpr, + LOCAL_ROWS: tl.constexpr, UNIT_INNER: tl.constexpr): + # Rows index[r] of one closing-pass chunk (visit rank begin + r): a row of + # donor L, not stale, goes to the nearer of L and the child of L's first + # split after the row (FP32 differences, squared and summed in FP64, ties + # to the lower id); a child moved again after that split does not count. + r = tl.program_id(0) * BLOCK_R + tl.arange(0, BLOCK_R) + live = r < n + idx = tl.load(index + r, mask=live, other=0) + storage_row = tl.load(row_index + r, mask=live, other=0) if LOCAL_ROWS else idx + rank = r.to(tl.int64) + begin + lab = tl.load(labels + idx, mask=live, other=0) + stale_row = tl.load(stale + idx, mask=live, other=1) != 0 + value = lab * span + rank + # searchsorted(key, value, right=True), within the row's donor's own splits + # (segment[L] : segment[L + 1] of the sorted keys): the same position. + lo = tl.load(segment + lab, mask=live, other=0) + hi = tl.load(segment + lab + 1, mask=live, other=0) + while tl.max(hi - lo, axis=0) > 0: + go = lo < hi + mid = (lo + hi) // 2 + at = tl.load(key + mid, mask=live & go, other=0) + below = at <= value + lo = tl.where(go & below, mid + 1, lo) + hi = tl.where(go & ~below, mid, hi) + split = tl.minimum(lo, n_events - 1) + donor = tl.load(source + split, mask=live, other=-1) + birth = tl.load(born + split, mask=live, other=0) + child = tl.load(target + split, mask=live, other=0) + child_moved = tl.load(moved_at + child, mask=live, other=-1) + twin = live & ~stale_row & (donor == lab) & (birth > rank) & (child_moved == birth) + if tl.max(twin.to(tl.int32), axis=0) > 0: # Tiles without a routed row stop here. + _twin_distances(x, stride_x, stride_inner, idx, storage_row, lab, child, twin, centroids, stride_c, + labels, d, BLOCK_R, BLOCK_D, CAST, UNIT_INNER) + + +@triton.jit(do_not_specialize=["stride_inner"]) +def _twin_distances(x, stride_x, stride_inner, idx, storage_row, lab, child, twin, centroids, stride_c, labels, d, + BLOCK_R: tl.constexpr, BLOCK_D: tl.constexpr, CAST: tl.constexpr, + UNIT_INNER: tl.constexpr): + near_own = tl.zeros([BLOCK_R], dtype=tl.float64) + near_child = tl.zeros([BLOCK_R], dtype=tl.float64) + for start in range(0, d, BLOCK_D): + cols = start + tl.arange(0, BLOCK_D) + m = twin[:, None] & (cols < d)[None, :] + row = tl.load(x + storage_row[:, None] * stride_x + + (cols[None, :] if UNIT_INNER else cols[None, :].to(tl.int64) * stride_inner), mask=m, other=0.0) + if CAST == 1: + row = row.to(tl.bfloat16) + elif CAST == 2: + row = row.to(tl.float16) + row = row.to(tl.float32) + own = tl.load(centroids + lab[:, None] * stride_c + cols[None, :], mask=m, other=0.0) + twin_c = tl.load(centroids + child[:, None] * stride_c + cols[None, :], mask=m, other=0.0) + a = (row - own).to(tl.float64) + b = (row - twin_c).to(tl.float64) + near_own += tl.sum(a * a, axis=1) + near_child += tl.sum(b * b, axis=1) + new = tl.where((near_child < near_own) | ((near_child == near_own) & (child < lab)), child, lab) + tl.store(labels + idx, new, mask=twin) + + +def twin_route(x, index, labels, stale, key, segment, target, source, born, moved_at, centroids, begin, span, + cast=None, *, row_index=None): + """Twin reassignment of one closing-pass chunk, in place on ``labels``, in + one launch: no host sync, no temporaries. ``key`` (sorted donor * span + + birth), ``target``, ``source``, ``born`` describe the pass's splits; + ``stale`` (n,) marks rows the stale-row rule handled.""" + n, d = len(index), x.shape[1] + events = len(key) + if not n or not events: + return + block_d = min(128, triton.next_power_of_2(d)) + block_r = 16 + _twin_route_kernel[(triton.cdiv(n, block_r),)]( + x, x.stride(0), x.stride(1), index, index if row_index is None else row_index, + labels, stale, key, target, source, born, moved_at, + centroids, centroids.stride(0), n, begin, span, events, segment, d, + BLOCK_R=block_r, BLOCK_D=block_d, CAST=_CLOSING_CAST[cast], + LOCAL_ROWS=row_index is not None, UNIT_INNER=x.stride(1) == 1, num_warps=4) diff --git a/thirdparty/faiss/contrib/exhaustive_search.py b/thirdparty/faiss/contrib/exhaustive_search.py index 1041c6b96..bd45efde3 100644 --- a/thirdparty/faiss/contrib/exhaustive_search.py +++ b/thirdparty/faiss/contrib/exhaustive_search.py @@ -31,8 +31,7 @@ def knn_ground_truth( if ngpu: LOG.info("running on %d GPUs" % ngpu) - co = faiss.GpuMultipleClonerOptions() - co.shard = shard + co = _multiple_cloner_options(shard) index = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu) # compute ground-truth by blocks, and add to heaps @@ -177,8 +176,7 @@ def range_ground_truth( ngpu = faiss.get_num_gpus() if ngpu: LOG.info("running on %d GPUs" % ngpu) - co = faiss.GpuMultipleClonerOptions() - co.shard = shard + co = _multiple_cloner_options(shard) index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu) # compute ground-truth by blocks @@ -308,8 +306,7 @@ def range_search_max_results( if ngpu: LOG.info("running on %d GPUs" % ngpu) - co = faiss.GpuMultipleClonerOptions() - co.shard = shard + co = _multiple_cloner_options(shard) index_gpu = faiss.index_cpu_to_all_gpus(index, co=co, ngpu=ngpu) else: index_gpu = None @@ -392,3 +389,12 @@ def exponential_query_iterator(xq, start_bs=32, max_bs=20000): if bs < max_bs: bs *= 2 i += len(xqi) + + +def _multiple_cloner_options(shard): + # The Metal backend reports a GPU but has no multi-device cloner options. + if not hasattr(faiss, "GpuMultipleClonerOptions"): + return None + co = faiss.GpuMultipleClonerOptions() + co.shard = shard + return co diff --git a/thirdparty/faiss/contrib/ivf_tools.py b/thirdparty/faiss/contrib/ivf_tools.py index beb068324..22a0700da 100644 --- a/thirdparty/faiss/contrib/ivf_tools.py +++ b/thirdparty/faiss/contrib/ivf_tools.py @@ -38,17 +38,14 @@ def search_preassigned(index_ivf, xq, k, list_nos, coarse_dis=None): n, d = xq.shape if isinstance(index_ivf, faiss.IndexBinaryIVF): d *= 8 - dis_type = "int32" - else: - dis_type = "float32" assert d == index_ivf.d assert list_nos.shape == (n, index_ivf.nprobe) - # the coarse distances are used in IVFPQ with L2 distance and - # by_residual=True otherwise we provide dummy coarse_dis + # the coarse distances enter the result for some indexes (eg. IVFPQ, + # IVF with inner product), so compute them if they are not provided if coarse_dis is None: - coarse_dis = np.zeros((n, index_ivf.nprobe), dtype=dis_type) + coarse_dis = _coarse_distances(index_ivf, xq, list_nos) else: assert coarse_dis.shape == (n, index_ivf.nprobe) @@ -63,20 +60,16 @@ def range_search_preassigned(index_ivf, x, radius, list_nos, coarse_dis=None): n, d = x.shape if isinstance(index_ivf, faiss.IndexBinaryIVF): d *= 8 - dis_type = "int32" - else: - dis_type = "float32" - # the coarse distances are used in IVFPQ with L2 distance and - # by_residual=True otherwise we provide dummy coarse_dis + assert d == index_ivf.d + assert list_nos.shape == (n, index_ivf.nprobe) + + # see search_preassigned if coarse_dis is None: - coarse_dis = np.zeros((n, index_ivf.nprobe), dtype=dis_type) + coarse_dis = _coarse_distances(index_ivf, x, list_nos) else: assert coarse_dis.shape == (n, index_ivf.nprobe) - assert d == index_ivf.d - assert list_nos.shape == (n, index_ivf.nprobe) - res = faiss.RangeSearchResult(n) sp = faiss.swig_ptr @@ -142,3 +135,23 @@ def sort_invlists_by_size(index_ivf): invlist_sizes = get_invlist_sizes(index_ivf.invlists) perm = np.argsort(invlist_sizes) permute_invlists(index_ivf, perm) + + +def _coarse_distances(index_ivf, x, list_nos): + """Distances between x and the centroids of list_nos, as a search in the + coarse quantizer returns them.""" + n, nprobe = list_nos.shape + if isinstance(index_ivf, faiss.IndexBinaryIVF): + return np.zeros((n, nprobe), dtype="int32") + quantizer = index_ivf.quantizer + centroids = quantizer.reconstruct_n(0, quantizer.ntotal) + x = np.ascontiguousarray(x, dtype="float32") + list_nos = np.ascontiguousarray(list_nos, dtype="int64") + dis = np.empty((n, nprobe), dtype="float32") + if quantizer.metric_type == faiss.METRIC_INNER_PRODUCT: + by_idx = faiss.fvec_inner_products_by_idx + else: + by_idx = faiss.fvec_L2sqr_by_idx + sp = faiss.swig_ptr + by_idx(sp(dis), sp(x), sp(centroids), sp(list_nos), x.shape[1], n, nprobe) + return dis diff --git a/thirdparty/faiss/contrib/torch_utils.py b/thirdparty/faiss/contrib/torch_utils.py index af4efbbd4..cc5a902af 100644 --- a/thirdparty/faiss/contrib/torch_utils.py +++ b/thirdparty/faiss/contrib/torch_utils.py @@ -148,7 +148,9 @@ def torch_replace_method( def handle_torch_Index(the_class): def torch_replacement_add(self, x, numeric_type=faiss.Float32): - if type(x) is np.ndarray: + if type(x) is np.ndarray or ( + hasattr(faiss, "Dataset") and isinstance(x, faiss.Dataset) + ): # forward to faiss __init__.py base method return self.add_numpy(x) @@ -243,7 +245,9 @@ def torch_replacement_assign(self, x, k, labels=None): return labels def torch_replacement_train(self, x, numeric_type=faiss.Float32): - if type(x) is np.ndarray: + if type(x) is np.ndarray or ( + hasattr(faiss, "Dataset") and isinstance(x, faiss.Dataset) + ): # forward to faiss __init__.py base method return self.train_numpy(x) diff --git a/thirdparty/faiss/demos/README.md b/thirdparty/faiss/demos/README.md index 71a23f272..905247824 100644 --- a/thirdparty/faiss/demos/README.md +++ b/thirdparty/faiss/demos/README.md @@ -10,6 +10,44 @@ demo_auto_tune.py Demonstrates the auto-tuning functionality of Faiss +demo_e_means.py +--------------- + +Runs the DEEP1M e-means quality experiment on a PyTorch device and reports the +median held-out MSE over ten seeds. Download Deep1B as described in +`../benchs/README.md` and pass the directory containing `deep1b/`: + + python demos/demo_e_means.py --data-dir /path/to/data + +The final line reports the measured median test MSE for that run. + +demo_e_means_distributed.py +--------------------------- + +Runs synchronous row-distributed CPU/GPU training on generated rank-local batches, +with replicated centroids and the same public numerical lifecycle: + + torchrun --standalone --nproc-per-node=2 demos/demo_e_means_distributed.py + +Use `--transport dense` or `--transport sparse` to override the conservative +automatic choice. No dataset download is required. This is an integration +example, not a disk-loading or performance measurement. + + +demo_e_means_sharded.py +---------------------- + +Small CUDA/NCCL centroid-ownership example with two ranks. Each rank keeps +only its contiguous centroid shard, and supplies equal row contributions. +Several partial accumulations complete one prescribed local share before +update; the last batch has a real tail. No dataset download is required. + + torchrun --standalone --nproc-per-node=2 demos/demo_e_means_sharded.py + +Add `--stream` to generate bounded chunks instead of keeping the small local +row matrix. This illustrates the public lifecycle, not disk IO or performance. + + demo_ondisk_ivf.py ------------------ diff --git a/thirdparty/faiss/demos/demo_e_means.py b/thirdparty/faiss/demos/demo_e_means.py new file mode 100644 index 000000000..a010c0782 --- /dev/null +++ b/thirdparty/faiss/demos/demo_e_means.py @@ -0,0 +1,57 @@ +# 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. + +"""Run the DEEP1M e-means quality experiment.""" + +import argparse +import os + +import numpy as np +import torch + +from faiss.contrib import datasets +from faiss.contrib.e_means import Emeans + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--data-dir", + help="directory containing deep1b/base.fvecs and its query file", + ) + default_device = "cuda" if torch.cuda.is_available() else "cpu" + parser.add_argument("--device", default=default_device) + args = parser.parse_args() + + if args.data_dir: + datasets.set_dataset_basedir(os.path.join(args.data_dir, "")) + + dataset = datasets.DatasetDeep1B(nb=1_000_000) + train = torch.from_numpy(dataset.get_database()).to(args.device) + queries = dataset.get_queries() + # Evaluate on a deterministic half of the query set. + order = np.random.RandomState(1234).permutation(len(queries)) + test = torch.from_numpy(queries[order[len(queries) // 2 :]]).to(args.device) + + mse = [] + for seed in range(10): + kmeans = Emeans( + dataset.d, + 16_384, + nepochs=3, + batch_law="throughput", + seed=seed, + verbose=True, + ) + kmeans.train(train) + distance, _ = kmeans.assign(test) + mse.append(distance.mean().item()) + print("seed %d test MSE %.6f" % (seed, mse[-1])) + + print("median test MSE %.6f" % np.median(mse)) + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/demos/demo_e_means_distributed.py b/thirdparty/faiss/demos/demo_e_means_distributed.py new file mode 100644 index 000000000..78d31a85e --- /dev/null +++ b/thirdparty/faiss/demos/demo_e_means_distributed.py @@ -0,0 +1,77 @@ +# 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. + +"""Row-distributed E-means on generated, rank-local FP32 batches. + +Run: torchrun --standalone --nproc-per-node=2 demos/demo_e_means_distributed.py +Uses CUDA/NCCL by default, or CPU/Gloo with --device cpu. +Each rank keeps all centroids; the population is generated +one equal local contribution at a time. Global batches and the final tail must +divide evenly by rank count. This demonstrates loading/collective ordering, +not disk-loading or training performance. + +For CPU/Gloo, add --device cpu; add --numpy for NumPy/Faiss CPU assignment. +""" + +import argparse +import os + +import torch +import torch.distributed as dist + +from faiss.contrib.e_means import DistributedEmeans, DistributedNumpyEmeans + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--n", type=int, default=96) + parser.add_argument("--k", type=int, default=4) + parser.add_argument("--d", type=int, default=8) + parser.add_argument("--epochs", type=int, default=2) + parser.add_argument("--transport", choices=("auto", "dense", "sparse"), default="auto") + parser.add_argument("--device", choices=("cpu", "cuda"), default="cuda") + parser.add_argument("--numpy", action="store_true", help="NumPy state/rows on CPU") + args = parser.parse_args() + if args.numpy and args.device != "cpu": + parser.error("--numpy requires --device cpu") + local_rank = int(os.environ["LOCAL_RANK"]) + if args.device == "cuda": + torch.cuda.set_device(local_rank) + dist.init_process_group("nccl" if args.device == "cuda" else "gloo") + try: + rank, ranks = dist.get_rank(), dist.get_world_size() + device = torch.device("cuda", local_rank) if args.device == "cuda" else torch.device("cpu") + offset = torch.arange(args.d, device=device, dtype=torch.float32) / 64 + initial = torch.arange(args.k, device=device, dtype=torch.float32)[:, None] + offset + if args.numpy: + initial = initial.numpy() + model_class = DistributedNumpyEmeans if args.numpy else DistributedEmeans + model = model_class(args.d, args.k, nepochs=args.epochs, + group=dist.group.WORLD, transport=args.transport) + model.begin(args.n, initial) + batch_size = model.recipe["batch_size"] + for _epoch in range(args.epochs): + for begin in range(0, args.n, batch_size): + n = min(batch_size, args.n - begin) + local_n = n // ranks + local_begin = begin + local_n * rank + local_end = local_begin + local_n + ids = torch.arange(local_begin, local_end, device=device) + rows = (ids % args.k).float()[:, None] + offset + if args.numpy: + rows = rows.numpy() + stats = model.accumulate(rows) + model.update(stats) + model.end_epoch() + centroids = model.finalize() + if rank == 0: + print("rows=%d ranks=%d batch_size=%d objective=%.6g centroids=%s" + % (args.n, ranks, batch_size, model.obj[-1].item(), tuple(centroids.shape))) + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/demos/demo_e_means_sharded.py b/thirdparty/faiss/demos/demo_e_means_sharded.py new file mode 100644 index 000000000..72dc8deee --- /dev/null +++ b/thirdparty/faiss/demos/demo_e_means_sharded.py @@ -0,0 +1,72 @@ +# 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. + +"""Small caller-driven CUDA centroid sharding, with resident or generated rows. + +Run: torchrun --standalone --nproc-per-node=2 demos/demo_e_means_sharded.py +Add --stream to generate each bounded contribution instead of keeping local rows. +No disk loader or performance measurement is involved. +""" +import argparse +import datetime +import os + +import torch +import torch.distributed as dist + +from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--stream", action="store_true") + args = parser.parse_args() + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + dist.init_process_group("nccl", timeout=datetime.timedelta(seconds=60)) + try: + rank, ranks = dist.get_rank(), dist.get_world_size() + if ranks != 2: + raise ValueError("this small example requires exactly two CUDA ranks") + device = torch.device("cuda", int(os.environ["LOCAL_RANK"])) + n, k, d, batch, supplied_chunk = 100, 4, 8, 16, 3 + offset = torch.arange(d, dtype=torch.float32, device=device) / 64 + initial = torch.arange(k, dtype=torch.float32, device=device)[:, None] + offset + + def rows(begin, end): + ids = torch.arange(begin, end, device=device) + return (ids % k).float()[:, None] + offset + + resident = None if args.stream else rows(rank * (n // ranks), (rank + 1) * (n // ranks)) + model = EmeansShardedCentroids( + d, + k, + group=dist.group.WORLD, + nepochs=2, + batch_size=batch, + alpha0=0.5, + ) + model.begin(n, initial[rank * (k // ranks):(rank + 1) * (k // ranks)]) + for _ in range(model.nepochs): + for begin in range(0, n // ranks, batch // ranks): + end = min(begin + batch // ranks, n // ranks) + for a in range(begin, end, supplied_chunk): + b = min(a + supplied_chunk, end) + contribution = (rows(rank * (n // ranks) + a, rank * (n // ranks) + b) + if args.stream else resident[a:b]) + stats = model.accumulate(contribution) + model.update(stats) # Exactly one update for the completed local share. + model.end_epoch() + active_snapshot = model.current_centroids().clone() + closed = model.finalize() + print("rank=%d centroid_begin=%d local_shape=%s objective=%g mode=%s" + % (rank, model.centroid_begin, tuple(closed.shape), model.obj[-1].item(), + "generated chunks" if args.stream else "resident rows")) + assert active_snapshot.dtype == closed.dtype == torch.float32 + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/thirdparty/faiss/demos/offline_ivf/tests/test_iterate_input.py b/thirdparty/faiss/demos/offline_ivf/tests/test_iterate_input.py index 372c349c8..4141ae1a3 100644 --- a/thirdparty/faiss/demos/offline_ivf/tests/test_iterate_input.py +++ b/thirdparty/faiss/demos/offline_ivf/tests/test_iterate_input.py @@ -13,21 +13,14 @@ DIMENSION: int = 768 SMALL_FILE_SIZES: List[int] = [100, 210, 450] -LARGE_FILE_SIZES: List[int] = [1253, 3459, 890] TEST_BATCH_SIZE: int = 500 SMALL_SAMPLE_SIZE: int = 1000 NUM_FILES: int = 3 class TestUtilsMethods(unittest.TestCase): - """ - Unit tests for iterate and decreasing_matrix methods. - """ def test_iterate_input_file_smaller_than_batch(self): - """ - Tests when batch size is larger than the file size. - """ with tempfile.TemporaryDirectory() as tmpdirname: data_creator = TestDataCreator( tempdir=tmpdirname, @@ -51,39 +44,7 @@ def test_iterate_input_file_smaller_than_batch(self): vecs.shape[0], sum(SMALL_FILE_SIZES) - TEST_BATCH_SIZE ) - def test_iterate_input_file_larger_than_batch(self): - """ - Tests when batch size is smaller than the file size. - """ - with tempfile.TemporaryDirectory() as tmpdirname: - data_creator = TestDataCreator( - tempdir=tmpdirname, - dimension=DIMENSION, - data_type=np.float16, - file_sizes=LARGE_FILE_SIZES, - ) - data_creator.create_test_data() - args = data_creator.setup_cli() - cfg = load_config(args.config) - db_iterator = create_dataset_from_oivf_config(cfg, args.xb).iterate( - 0, TEST_BATCH_SIZE, np.float32 - ) - - for i in range(len(LARGE_FILE_SIZES) - 1): - vecs = next(db_iterator) - if i != 9: - self.assertEqual(vecs.shape[0], TEST_BATCH_SIZE) - else: - self.assertEqual( - vecs.shape[0], - sum(LARGE_FILE_SIZES) - TEST_BATCH_SIZE * 9, - ) - def test_get_vs_iterate(self) -> None: - """ - Loads vectors with iterator and get, and checks that they match, - non-aligned by file size case. - """ with tempfile.TemporaryDirectory() as tmpdirname: data_creator = TestDataCreator( tempdir=tmpdirname, @@ -103,29 +64,6 @@ def test_get_vs_iterate(self) -> None: ) vecs_by_get = ds.get(list(range(vecs_by_iterator.shape[0]))) self.assertTrue(np.all(vecs_by_iterator == vecs_by_get)) - - def test_iterate_back(self) -> None: - """ - Loads vectors with iterator and get, and checks that they match, - non-aligned by file size case. - """ - with tempfile.TemporaryDirectory() as tmpdirname: - data_creator = TestDataCreator( - tempdir=tmpdirname, - dimension=DIMENSION, - data_type=np.float16, - file_size=SMALL_SAMPLE_SIZE, - num_files=NUM_FILES, - normalise=True, - ) - data_creator.create_test_data() - args = data_creator.setup_cli() - cfg = load_config(args.config) - ds = create_dataset_from_oivf_config(cfg, args.xb) - vecs_by_iterator = np.vstack(list(ds.iterate(0, 317, np.float32))) - self.assertEqual( - vecs_by_iterator.shape[0], SMALL_SAMPLE_SIZE * NUM_FILES - ) vecs_chunk = np.vstack( [ next(ds.iterate(i, 543, np.float32)) diff --git a/thirdparty/faiss/demos/offline_ivf/tests/test_offline_ivf.py b/thirdparty/faiss/demos/offline_ivf/tests/test_offline_ivf.py index 7958a4d9f..47a309960 100644 --- a/thirdparty/faiss/demos/offline_ivf/tests/test_offline_ivf.py +++ b/thirdparty/faiss/demos/offline_ivf/tests/test_offline_ivf.py @@ -36,10 +36,6 @@ class TestOIVF(unittest.TestCase): - """ - Unit tests for OIVF. Some of these unit tests first copy the required test - data objects and puts them in the tempdir created by the context manager. - """ def assert_file_exists(self, filepath: str) -> None: path = pl.Path(filepath) @@ -55,13 +51,10 @@ def test_consistency_check(self) -> None: tempdir=tmpdirname, dimension=8, data_type=np.float16, - index_factory=["OPQ4,IVF256,PQ4"], - training_sample=9984, num_files=3, file_size=10000, nprobe=2, k=2, - metric="METRIC_L2", ) data_creator.create_test_data() test_args = data_creator.setup_cli("consistency_check") @@ -69,81 +62,6 @@ def test_consistency_check(self) -> None: AssertionError, process_options_and_run_jobs, test_args ) - def test_train_index(self) -> None: - """ - Test the OIVF train index step, that it correctly produces the - empty.faissindex template file. - """ - with tempfile.TemporaryDirectory() as tmpdirname: - data_creator = TestDataCreator( - tempdir=tmpdirname, - dimension=8, - data_type=np.float16, - index_factory=["OPQ4,IVF256,PQ4"], - training_sample=9984, - num_files=3, - file_size=10000, - nprobe=2, - k=2, - metric="METRIC_L2", - ) - data_creator.create_test_data() - test_args = data_creator.setup_cli("train_index") - cfg = load_config(test_args.config) - process_options_and_run_jobs(test_args) - empty_index = ( - cfg["output"] - + "/my_test_data/" - + cfg["index"]["prod"][-1].replace(",", "_") - + ".empty.faissindex" - ) - self.assert_file_exists(empty_index) - - def test_index_shard_equal_file_sizes(self) -> None: - """ - Test the case where the shard size is a divisor of the database size - and it is equal to the first file size. - """ - - with tempfile.TemporaryDirectory() as tmpdirname: - index_shard_size = 10000 - num_files = 3 - file_size = 10000 - xb_ds_size = num_files * file_size - data_creator = TestDataCreator( - tempdir=tmpdirname, - dimension=8, - data_type=np.float16, - index_factory=["IVF256,PQ4"], - training_sample=9984, - num_files=num_files, - file_size=file_size, - nprobe=2, - k=2, - metric="METRIC_L2", - index_shard_size=index_shard_size, - query_batch_size=1000, - evaluation_sample=100, - ) - data_creator.create_test_data() - test_args = data_creator.setup_cli("train_index") - process_options_and_run_jobs(test_args) - test_args = data_creator.setup_cli("index_shard") - cfg = load_config(test_args.config) - process_options_and_run_jobs(test_args) - num_shards = xb_ds_size // index_shard_size - if xb_ds_size % index_shard_size != 0: - num_shards += 1 - print(f"number of shards:{num_shards}") - for i in range(num_shards): - index_shard_file = ( - cfg["output"] - + "/my_test_data/" - + cfg["index"]["prod"][-1].replace(",", "_") - + f".shard_{i}" - ) - self.assert_file_exists(index_shard_file) - def test_index_shard_unequal_file_sizes(self) -> None: """ Test the case where the shard size is not a divisor of the database @@ -151,20 +69,16 @@ def test_index_shard_unequal_file_sizes(self) -> None: """ with tempfile.TemporaryDirectory() as tmpdirname: file_sizes = [20000, 15001, 13990] - xb_ds_size = sum(file_sizes) index_shard_size = 30000 data_creator = TestDataCreator( tempdir=tmpdirname, dimension=8, data_type=np.float16, index_factory=["IVF256,PQ4"], - training_sample=9984, file_sizes=file_sizes, nprobe=2, k=2, - metric="METRIC_L2", index_shard_size=index_shard_size, - evaluation_sample=100, ) data_creator.create_test_data() test_args = data_creator.setup_cli("train_index") @@ -172,10 +86,7 @@ def test_index_shard_unequal_file_sizes(self) -> None: test_args = data_creator.setup_cli("index_shard") cfg = load_config(test_args.config) process_options_and_run_jobs(test_args) - num_shards = xb_ds_size // index_shard_size - if xb_ds_size % index_shard_size != 0: - num_shards += 1 - print(f"number of shards:{num_shards}") + num_shards = 2 for i in range(num_shards): index_shard_file = ( cfg["output"] @@ -186,31 +97,19 @@ def test_index_shard_unequal_file_sizes(self) -> None: self.assert_file_exists(index_shard_file) def test_search(self) -> None: - """ - Test search step using test data objects to bypass dependencies on - previous steps. - """ with tempfile.TemporaryDirectory() as tmpdirname: - num_files = 3 - file_size = 10000 query_batch_size = 10000 - total_batches = num_files * file_size // query_batch_size - if num_files * file_size % query_batch_size != 0: - total_batches += 1 data_creator = TestDataCreator( tempdir=tmpdirname, dimension=8, data_type=np.float32, index_factory=["IVF256,PQ4"], - training_sample=9984, num_files=3, file_size=10000, nprobe=2, k=2, - metric="METRIC_L2", index_shard_size=10000, query_batch_size=query_batch_size, - evaluation_sample=100, ) data_creator.create_test_data() test_args = data_creator.setup_cli("train_index") @@ -220,7 +119,6 @@ def test_search(self) -> None: test_args = data_creator.setup_cli("search") cfg = load_config(test_args.config) process_options_and_run_jobs(test_args) - # TODO: add check that there are number of batches total of files knn_file = cfg["output"] + KNN_RESULTS_FILE self.assert_file_exists(knn_file) @@ -235,15 +133,12 @@ def test_evaluate_without_margin(self) -> None: dimension=8, data_type=np.float32, index_factory=["IVF256,PQ4"], - training_sample=9984, num_files=3, file_size=10000, nprobe=2, k=2, - metric="METRIC_L2", index_shard_size=10000, query_batch_size=10000, - evaluation_sample=100, with_queries_ds=True, ) data_creator.create_test_data() @@ -261,25 +156,19 @@ def test_evaluate_without_margin(self) -> None: self.assert_file_exists(file_to_check) def test_evaluate_without_margin_OPQ(self) -> None: - """ - Test evaluate step using test data objects, no margin evaluation, - single index. - """ + """Same as test_evaluate_without_margin, with an OPQ pretransform.""" with tempfile.TemporaryDirectory() as tmpdirname: data_creator = TestDataCreator( tempdir=tmpdirname, dimension=8, data_type=np.float32, index_factory=["OPQ4,IVF256,PQ4"], - training_sample=9984, num_files=3, file_size=10000, nprobe=200, k=2, - metric="METRIC_L2", index_shard_size=10000, query_batch_size=10000, - evaluation_sample=100, with_queries_ds=True, ) data_creator.create_test_data() diff --git a/thirdparty/faiss/demos/offline_ivf/tests/testing_utils.py b/thirdparty/faiss/demos/offline_ivf/tests/testing_utils.py index 427c35e68..b1f3184ed 100644 --- a/thirdparty/faiss/demos/offline_ivf/tests/testing_utils.py +++ b/thirdparty/faiss/demos/offline_ivf/tests/testing_utils.py @@ -44,7 +44,6 @@ def __init__( metric: Optional[str] = "METRIC_L2", normalise: Optional[bool] = False, with_queries_ds: Optional[bool] = False, - evaluate_by_margin: Optional[bool] = False, ) -> None: self.tempdir = tempdir self.dimension = dimension @@ -68,7 +67,6 @@ def __init__( self.config_file = self.tempdir + "/config_test.yaml" self.ds_name = "my_test_data" self.qs_name = "my_queries_data" - self.evaluate_by_margin = evaluate_by_margin self.with_queries_ds = with_queries_ds def create_test_data(self) -> None: @@ -105,21 +103,19 @@ def create_test_data(self) -> None: } }, } - if self.evaluate_by_margin: - config_for_yaml["evaluate_by_margin"] = self.evaluate_by_margin - q_datafiles = self._create_data_files("my_q_data") - q_files_info = [] - - for i, file in enumerate(q_datafiles): - q_files_info.append( - { - "dtype": self.data_type, - "format": "npy", - "name": file, - "size": self.file_sizes[i], - } - ) if self.with_queries_ds: + q_datafiles = self._create_data_files("my_q_data") + q_files_info = [] + + for i, file in enumerate(q_datafiles): + q_files_info.append( + { + "dtype": self.data_type, + "format": "npy", + "name": file, + "size": self.file_sizes[i], + } + ) config_for_yaml["datasets"][self.qs_name] = { "root": self.tempdir, "size": sum(self.file_sizes), @@ -156,16 +152,8 @@ def setup_cli(self, command="consistency_check") -> argparse.Namespace: ) def _create_data_files(self, name_of_file="my_data") -> List[str]: - """ - Creates a dataset "my_test_data" with number of files (num_files), - using padding in the files name. If self.with_queries is True, it adds - an extra dataset "my_queries_data" with the same number of files as the - "my_test_data". The default name for embeddings files is "my_data" + - .npy. - """ filenames = [] for i, file_size in enumerate(self.file_sizes): - # np.random.seed(i) db_vectors = np.random.random((file_size, self.dimension)).astype( self.data_type ) @@ -175,9 +163,6 @@ def _create_data_files(self, name_of_file="my_data") -> List[str]: return filenames def _create_config_yaml(self, dict_file: Dict[str, str]) -> None: - """ - Creates a yaml file in dir (can be a temporary dir for tests). - """ filename = self.tempdir + "/config_test.yaml" with open(filename, "w") as file: yaml.dump(dict_file, file, default_flow_style=False) diff --git a/thirdparty/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h b/thirdparty/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h index c52f57f24..757fa76b9 100644 --- a/thirdparty/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h +++ b/thirdparty/faiss/demos/rocksdb_ivf/RocksDBInvertedLists.h @@ -24,7 +24,6 @@ struct RocksDBInvertedListsIterator : faiss::InvertedListsIterator { virtual void next() override; virtual std::pair get_id_and_codes() override; - private: std::unique_ptr it; size_t list_no; size_t code_size; @@ -60,7 +59,6 @@ struct RocksDBInvertedLists : faiss::InvertedLists { size_t list_no, void* inverted_list_context) const override; - private: std::unique_ptr db_; }; diff --git a/thirdparty/faiss/faiss/CMakeLists.txt b/thirdparty/faiss/faiss/CMakeLists.txt index b007e3296..d3eed7e9a 100644 --- a/thirdparty/faiss/faiss/CMakeLists.txt +++ b/thirdparty/faiss/faiss/CMakeLists.txt @@ -1,4 +1,9 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. +# Portions 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. + +# Portions Copyright 2026 Arm Limited and/or its affiliates # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. @@ -11,12 +16,14 @@ set(FAISS_SIMD_AVX2_SRC impl/fast_scan/impl-avx2.cpp impl/hnsw/avx2.cpp + impl/nndescent/gram-avx2.cpp impl/result_handler/avx2.cpp impl/pq_code_distance/avx2.cpp impl/scalar_quantizer/sq-avx2.cpp impl/approx_topk/avx2.cpp impl/binary_hamming/avx2.cpp utils/simd_impl/distances_avx2.cpp + utils/simd_impl/fp16_kernels_avx2.cpp utils/hamming_distance/hamming_avx2.cpp utils/simd_impl/partitioning_avx2.cpp utils/distances_fused/simdlib_based.cpp @@ -27,12 +34,14 @@ set(FAISS_SIMD_AVX2_SRC set(FAISS_SIMD_AVX512_SRC impl/fast_scan/impl-avx512.cpp impl/hnsw/avx512.cpp + impl/nndescent/gram-avx512.cpp impl/result_handler/avx512.cpp impl/pq_code_distance/avx512.cpp impl/polysemous_training/avx512.cpp impl/scalar_quantizer/sq-avx512.cpp impl/binary_hamming/avx512.cpp utils/simd_impl/distances_avx512.cpp + utils/simd_impl/fp16_kernels_avx512.cpp utils/distances_fused/avx512.cpp utils/hamming_distance/hamming_avx512.cpp impl/scalar_quantizer/EDENQuantizer-avx512.cpp @@ -55,8 +64,10 @@ set(FAISS_SIMD_NEON_SRC impl/scalar_quantizer/sq-neon.cpp impl/approx_topk/neon.cpp impl/binary_hamming/neon.cpp + impl/nndescent/gram-neon.cpp impl/pq_code_distance/neon.cpp utils/simd_impl/distances_aarch64.cpp + utils/simd_impl/fp16_kernels_neon.cpp utils/hamming_distance/hamming_neon.cpp utils/simd_impl/partitioning_neon.cpp utils/distances_fused/simdlib_based_neon.cpp @@ -75,6 +86,7 @@ set(FAISS_SIMD_RVV_SRC utils/simd_impl/distances_rvv.cpp utils/hamming_distance/hamming_rvv.cpp utils/simd_impl/rabitq_rvv.cpp + utils/distances_fused/rvv.cpp ) # Select SIMD sources based on target architecture if(CMAKE_SYSTEM_PROCESSOR MATCHES "(x86_64|amd64|AMD64)") @@ -133,6 +145,7 @@ set(FAISS_SRC IndexAdditiveQuantizerFastScan.cpp IndexIVFIndependentQuantizer.cpp IndexPQFastScan.cpp + IndexPiPNN.cpp IndexPreTransform.cpp IndexRaBitQ.cpp IndexRaBitQFastScan.cpp @@ -152,6 +165,7 @@ set(FAISS_SRC index_factory.cpp impl/AdSampling.cpp impl/AuxIndexStructures.cpp + impl/DistanceComputer.cpp impl/VisitedTable.cpp impl/ClusteringInitialization.cpp impl/ClusteringHelpers.cpp @@ -164,6 +178,10 @@ set(FAISS_SRC impl/hnsw/MinimaxHeap.cpp impl/result_handler/ResultHandler.cpp impl/NSG.cpp + impl/PiPNN.cpp + impl/pipnn/HashPrune.cpp + impl/pipnn/Partition.cpp + impl/pipnn/kernels.cpp impl/PolysemousTraining.cpp impl/ProductQuantizer.cpp impl/pq_code_distance/pq_code_distance-generic.cpp @@ -187,6 +205,7 @@ set(FAISS_SRC impl/fast_scan/fast_scan.cpp impl/residual_quantizer_encode_steps.cpp impl/zerocopy_io.cpp + impl/DeterministicNNDescent.cpp impl/NNDescent.cpp impl/Panorama.cpp impl/PanoramaStats.cpp @@ -226,6 +245,14 @@ if(FAISS_ENABLE_SVS) ) endif() +if(FAISS_ENABLE_DISK_IVF) + list(APPEND FAISS_SRC + IndexIVFRaBitQSSD.cpp + invlists/DiskIOBackend.cpp + invlists/RaBitQSSDInvertedLists.cpp + ) +endif() + set(FAISS_HEADERS AutoTune.h Clustering.h @@ -268,6 +295,7 @@ set(FAISS_HEADERS IndexFastScan.h IndexAdditiveQuantizerFastScan.h IndexPQFastScan.h + IndexPiPNN.h IndexPreTransform.h IndexRefine.h IndexReplicas.h @@ -309,11 +337,17 @@ set(FAISS_HEADERS impl/fast_scan/LookupTableScaler.h impl/fast_scan/FastScanDistancePostProcessing.h impl/maybe_owned_vector.h + impl/DeterministicNNDescent.h impl/NNDescent.h impl/NSG.h + impl/pipnn/HashPrune.h + impl/pipnn/Partition.h + impl/nndescent/gram.h + impl/pipnn/kernels.h impl/Panorama.h impl/PanoramaStats.h impl/PdxLayout.h + impl/PiPNN.h impl/PolysemousTraining.h impl/polysemous_training/dispatch.h impl/ProductQuantizer-inl.h @@ -331,6 +365,10 @@ set(FAISS_HEADERS impl/scalar_quantizer/quantizers.h impl/scalar_quantizer/scanners.h impl/scalar_quantizer/similarities.h + impl/pq_code_distance/pq_rvv_kernel.h + impl/scalar_quantizer/sq8_coefficients.h + impl/scalar_quantizer/sq8_rvv_kernel.h + utils/simd_impl/distances_rvv_kernel.h impl/scalar_quantizer/sq-dispatch.h impl/scalar_quantizer/training.h impl/ThreadedIndex-inl.h @@ -347,6 +385,7 @@ set(FAISS_HEADERS impl/fast_scan/dispatching.h impl/fast_scan/fast_scan.h impl/fast_scan/decompose_qbs.h + impl/fast_scan/kernels_neon.h impl/fast_scan/kernels_simd256.h impl/fast_scan/kernels_simd512.h impl/fast_scan/rabitq_dispatching.h @@ -382,6 +421,7 @@ set(FAISS_HEADERS utils/hamming.h utils/ordered_key_value.h utils/partitioning.h + utils/popcount.h utils/prefetch.h utils/quantize_lut.h utils/rabitq_simd.h @@ -418,9 +458,13 @@ set(FAISS_HEADERS utils/simd_impl/distances_simdlib256.h utils/hamming_distance/hamming_impl.h utils/simd_impl/exhaustive_L2sqr_blas_cmax.h + utils/simd_impl/fp16_kernels.h utils/simd_impl/super_kmeans_dispatch.h utils/simd_impl/super_kmeans_kernels.h utils/simd_impl/IVFFlatScanner-inl.h + utils/simd_impl/masked_sum.h + utils/simd_impl/masked_sum-avx2.h + utils/simd_impl/masked_sum-avx512.h utils/simd_impl/distances_sse-inl.h ) @@ -436,6 +480,13 @@ if(FAISS_ENABLE_SVS) ) endif() +if(FAISS_ENABLE_DISK_IVF) + list(APPEND FAISS_HEADERS + IndexIVFRaBitQSSD.h + invlists/RaBitQSSDInvertedLists.h + ) +endif() + if(NOT WIN32) list(APPEND FAISS_SRC invlists/OnDiskInvertedLists.cpp) list(APPEND FAISS_HEADERS invlists/OnDiskInvertedLists.h) @@ -564,24 +615,24 @@ if(FAISS_OPT_LEVEL STREQUAL "dd") # Per-file SIMD flags (GCC/Clang) set_source_files_properties(${FAISS_SIMD_AVX2_SRC} TARGET_DIRECTORY faiss - PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c;-mpopcnt" + PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c;-mpopcnt;-mbmi2" ) set_source_files_properties(${FAISS_SIMD_AVX512_SRC} TARGET_DIRECTORY faiss PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mfma;-mf16c;-mpopcnt" + "-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mfma;-mf16c;-mpopcnt;-mbmi2" ) # VPOPCNT sources require VPOPCNTDQ and BITALG on top of baseline AVX-512. set_source_files_properties(${FAISS_SIMD_AVX512_VPOPCNT_SRC} TARGET_DIRECTORY faiss PROPERTIES COMPILE_OPTIONS - "-mavx2;-mfma;-mf16c;-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mavx512vpopcntdq;-mavx512bitalg;-mpopcnt" + "-mavx2;-mfma;-mf16c;-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mavx512vpopcntdq;-mavx512bitalg;-mpopcnt;-mbmi2" ) # The remaining SPR sources require the full SPR feature set. set_source_files_properties(${FAISS_SIMD_AVX512_SPR_SRC} TARGET_DIRECTORY faiss PROPERTIES COMPILE_OPTIONS - "-mavx2;-mfma;-mf16c;-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mavx512vpopcntdq;-mavx512bitalg;-mpopcnt;-mavx512vnni;-mavx512fp16;-mavx512bf16" + "-mavx2;-mfma;-mf16c;-mavx512f;-mavx512cd;-mavx512vl;-mavx512dq;-mavx512bw;-mavx512vpopcntdq;-mavx512bitalg;-mpopcnt;-mavx512vnni;-mavx512fp16;-mavx512bf16;-mbmi2" ) else() # Per-file SIMD flags (MSVC) @@ -633,9 +684,16 @@ endif() if(CMAKE_SYSTEM_PROCESSOR MATCHES "(aarch64|arm64|ARM64)" AND NOT MSVC) target_compile_definitions(faiss PRIVATE COMPILE_SIMD_ARM_NEON) target_sources(faiss PRIVATE ${FAISS_SIMD_NEON_SRC}) + # GCC requires +fp16 for the vector conversion intrinsics in this source. + set_source_files_properties(utils/simd_impl/fp16_kernels_neon.cpp + TARGET_DIRECTORY faiss + PROPERTIES COMPILE_OPTIONS "-march=armv8.2-a+fp16" + ) endif() -# RVV is the baseline SIMD on rv64 builds compiled with rv64gcv. Compile RVV +# RVV is the baseline SIMD on rv64 builds; the RVV translation units require +# rv64gcv + Zvfhmin (see the RISCV_RVV contract in utils/simd_levels.h), so +# they are compiled with -march=rv64gcv_zvfhmin. Compile RVV # sources into the main faiss target, mirroring the ARM NEON story on aarch64. # Guard against DD mode: in dd builds, FAISS_SIMD_SRC already contains # FAISS_SIMD_RVV_SRC and is added via target_sources above, so we must not @@ -663,6 +721,13 @@ if(FAISS_ENABLE_SVS) install(DIRECTORY ${svs_SOURCE_DIR}/lib/ DESTINATION ${CMAKE_INSTALL_LIBDIR} FILES_MATCHING PATTERN "libsvs_runtime.so*") endif() +if(FAISS_ENABLE_DISK_IVF) + find_package(LibAIO REQUIRED) + foreach(t faiss faiss_avx2 faiss_avx512 faiss_avx512_spr faiss_sve) + target_link_libraries(${t} PRIVATE LibAIO::LibAIO) + endforeach() +endif() + # Handle `#include `. target_include_directories(faiss PUBLIC $) @@ -684,6 +749,20 @@ set_target_properties(faiss faiss_avx2 faiss_avx512 faiss_avx512_spr faiss_sve P WINDOWS_EXPORT_ALL_SYMBOLS ON ) +if(FAISS_WARNINGS_AS_ERRORS) + if(MSVC) + message(FATAL_ERROR "FAISS_WARNINGS_AS_ERRORS is not supported with MSVC") + endif() + foreach(t faiss faiss_avx2 faiss_avx512 faiss_avx512_spr faiss_sve) + # Subclasses of Index and IndexBinary hide some overloads of virtual + # functions, and GCC 13 and later report this in -Wall. + # -Wmaybe-uninitialized depends on the GCC version, the target and the + # optimization level, so it stays a warning. + target_compile_options(${t} PRIVATE + $<$:-Wall -Wextra -Wshadow -Wno-overloaded-virtual -Werror -Wno-error=maybe-uninitialized>) + endforeach() +endif() + if(WIN32) target_compile_definitions(faiss PRIVATE FAISS_MAIN_LIB) target_compile_definitions(faiss_avx2 PRIVATE FAISS_MAIN_LIB) @@ -700,6 +779,14 @@ if(FAISS_ENABLE_SVS) target_compile_definitions(faiss_sve PRIVATE FAISS_ENABLE_SVS FAISS_SVS_RUNTIME_VERSION=${FAISS_SVS_RUNTIME_VERSION}) endif() +if(FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss_avx2 PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss_avx512 PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss_avx512_spr PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss_sve PRIVATE FAISS_ENABLE_DISK_IVF) +endif() + if(WIN32) set_target_properties(faiss PROPERTIES LINK_FLAGS "-Wl,--export-all-symbols") endif() @@ -831,14 +918,22 @@ write_basic_package_version_file( COMPATIBILITY AnyNewerVersion ) +# A static library leaves its private dependencies to the consumer's link: +# faiss-config.cmake finds the ones that are imported targets. +get_target_property(FAISS_LIBRARY_TYPE faiss TYPE) configure_file(${PROJECT_SOURCE_DIR}/cmake/faiss-config.cmake.in ${PROJECT_BINARY_DIR}/cmake/faiss-config.cmake - COPYONLY + @ONLY ) install(FILES ${PROJECT_BINARY_DIR}/cmake/faiss-config.cmake ${PROJECT_BINARY_DIR}/cmake/faiss-config-version.cmake DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/faiss ) +if(FAISS_ENABLE_DISK_IVF) + install(FILES ${PROJECT_SOURCE_DIR}/cmake/FindLibAIO.cmake + DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/faiss + ) +endif() install(EXPORT faiss-targets DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/faiss diff --git a/thirdparty/faiss/faiss/Clustering.cpp b/thirdparty/faiss/faiss/Clustering.cpp index b82b1be40..2358fc3ed 100644 --- a/thirdparty/faiss/faiss/Clustering.cpp +++ b/thirdparty/faiss/faiss/Clustering.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -63,6 +64,47 @@ void Clustering::train_encoded( const Index* codec, Index& index, const float* weights) { + train_impl(nx, x_in, codec, NumericType::Float32, index, weights); +} + +void Clustering::train_ex( + idx_t nx, + const void* x_in, + NumericType numeric_type, + Index& index, + const float* weights) { + if (numeric_type == NumericType::Float32) { + train(nx, static_cast(x_in), index, weights); + return; + } + FAISS_THROW_IF_NOT_MSG( + numeric_type == NumericType::Float16, + "Clustering::train_ex: unsupported numeric type"); + train_impl( + nx, + static_cast(x_in), + nullptr, + numeric_type, + index, + weights); +} + +void Clustering::train_impl( + idx_t nx, + const uint8_t* x_in, + const Index* codec, + NumericType numeric_type, + Index& index, + const float* weights) { + FAISS_THROW_IF_NOT_MSG( + codec || numeric_type == NumericType::Float32 || + numeric_type == NumericType::Float16, + "unsupported numeric type for clustering"); + // packed IEEE binary16 rows, consumed without a codec + const bool fp16 = !codec && numeric_type == NumericType::Float16; + // rows that are not fp32 are widened by blocks for the assignment index + const bool encoded = codec || fp16; + FAISS_THROW_IF_NOT_FMT( nx >= static_cast(k), "Number of training points (%" PRId64 @@ -70,6 +112,7 @@ void Clustering::train_encoded( "as large as number of clusters (%zd)", nx, k); + FAISS_THROW_IF_NOT_MSG(x_in, "training data must not be null"); FAISS_THROW_IF_NOT_FMT( (!codec || static_cast(codec->d) == d), @@ -83,23 +126,46 @@ void Clustering::train_encoded( int(index.d), int(d)); + FAISS_THROW_IF_NOT_MSG( + !encoded || decode_block_size > 0, + "decode_block_size must be positive"); + double t0 = getmillisecs(); if (!codec && check_input_data_for_NaNs) { // Check for NaNs in input data. Normally it is the user's - // responsibility, but it may spare us some hard-to-debug - // reports. - const float* x = reinterpret_cast(x_in); - for (size_t i = 0; i < nx * d; i++) { + // responsibility, but it may spare us some hard-to-debug reports. + if (fp16) { FAISS_THROW_IF_NOT_MSG( - std::isfinite(x[i]), "input contains NaN's or Inf's"); + detail::fp16_all_finite( + nx * d, reinterpret_cast(x_in)), + "input contains NaN's or Inf's"); + } else { + const float* x = reinterpret_cast(x_in); + for (size_t i = 0; i < nx * d; i++) { + FAISS_THROW_IF_NOT_MSG( + std::isfinite(x[i]), "input contains NaN's or Inf's"); + } } } const uint8_t* x = x_in; std::unique_ptr del1; std::unique_ptr del3; - size_t line_size = codec ? codec->sa_code_size() : sizeof(float) * d; + size_t line_size = codec ? codec->sa_code_size() + : fp16 ? sizeof(uint16_t) * d + : sizeof(float) * d; + + // widen n consecutive training rows to fp32 + auto decode_rows = [&](size_t n, const uint8_t* rows, float* out) { + if (codec) { + codec->sa_decode(n, rows, out); + } else if (fp16) { + fp16_to_fp32(n * d, reinterpret_cast(rows), out); + } else { + memcpy(out, rows, n * line_size); + } + }; if (static_cast(nx) > k * max_points_per_centroid) { uint8_t* x_new; @@ -129,11 +195,7 @@ void Clustering::train_encoded( nx); } centroids.resize(d * k); - if (!codec) { - memcpy(centroids.data(), x_in, sizeof(float) * d * k); - } else { - codec->sa_decode(nx, x_in, centroids.data()); - } + decode_rows(k, x_in, centroids.data()); // one fake iteration... ClusteringIterationStats stats = {0.0, 0.0, 0.0, 1.0, 0}; @@ -153,9 +215,8 @@ void Clustering::train_encoded( k, nredo, niter); - if (codec) { - printf("Input data encoded in %zd bytes per vector\n", - codec->sa_code_size()); + if (encoded) { + printf("Input data encoded in %zd bytes per vector\n", line_size); } } @@ -191,8 +252,10 @@ void Clustering::train_encoded( // initialize seed const uint64_t actual_seed = detail::get_actual_rng_seed(seed); - // temporary buffer to decode vectors during the optimization - std::vector decode_buffer(codec ? d * decode_block_size : 0); + // temporary buffer to decode codec-encoded vectors during the optimization + std::vector decode_buffer( + codec ? d * std::min(static_cast(nx), decode_block_size) + : 0); for (int redo = 0; redo < nredo; redo++) { if (verbose && nredo > 1) { @@ -210,41 +273,44 @@ void Clustering::train_encoded( std::vector perm(nx); rand_perm(perm.data(), nx, actual_seed + 1 + redo * 15486557L); for (size_t i = 0; i < k_to_init; i++) { - if (!codec) { - memcpy(centroids.data() + (n_input_centroids + i) * d, - x + perm[n_input_centroids + i] * line_size, - line_size); - } else { - codec->sa_decode( - 1, - x + perm[n_input_centroids + i] * line_size, - centroids.data() + (n_input_centroids + i) * d); - } + decode_rows( + 1, + x + perm[n_input_centroids + i] * line_size, + centroids.data() + (n_input_centroids + i) * d); } } else { - // For k-means++ and AFK-MC², we need all vectors decoded - const float* x_float = nullptr; - std::vector x_decoded; - - if (!codec) { - x_float = reinterpret_cast(x); - } else { - // Decode all vectors for initialization - x_decoded.resize(nx * d); - codec->sa_decode(nx, x, x_decoded.data()); - x_float = x_decoded.data(); - } - ClusteringInitialization initializer(d, k_to_init); initializer.method = init_method; initializer.seed = actual_seed + 1 + redo * 15486557L; initializer.afkmc2_chain_length = afkmc2_chain_length; - initializer.init_centroids( - nx, - x_float, - centroids.data() + n_input_centroids * d, - n_input_centroids, - n_input_centroids > 0 ? centroids.data() : nullptr); + + if (fp16) { + detail::init_centroids_fp16( + initializer, + nx, + reinterpret_cast(x), + centroids.data() + n_input_centroids * d, + n_input_centroids, + n_input_centroids > 0 ? centroids.data() : nullptr); + } else { + const float* x_float = nullptr; + std::vector x_decoded; + + if (!encoded) { + x_float = reinterpret_cast(x); + } else { + x_decoded.resize(nx * d); + decode_rows(nx, x, x_decoded.data()); + x_float = x_decoded.data(); + } + + initializer.init_centroids( + nx, + x_float, + centroids.data() + n_input_centroids * d, + n_input_centroids, + n_input_centroids > 0 ? centroids.data() : nullptr); + } } } @@ -268,7 +334,7 @@ void Clustering::train_encoded( for (int i = 0; i < niter; i++) { double t0s = getmillisecs(); - if (!codec) { + if (!encoded) { index.search( nx, reinterpret_cast(x), @@ -277,15 +343,26 @@ void Clustering::train_encoded( assign.get()); } else { // search by blocks of decode_block_size vectors - size_t code_size = codec->sa_code_size(); for (size_t i0 = 0; i0 < static_cast(nx); i0 += decode_block_size) { size_t i1 = i0 + decode_block_size; if (i1 > static_cast(nx)) { i1 = nx; } - codec->sa_decode( - i1 - i0, x + code_size * i0, decode_buffer.data()); + if (fp16) { + // the index consumes fp16 queries itself (natively + // if it can, see Index::search_ex) + index.search_ex( + i1 - i0, + x + line_size * i0, + NumericType::Float16, + 1, + dis.get() + i0, + assign.get() + i0); + continue; + } + decode_rows( + i1 - i0, x + line_size * i0, decode_buffer.data()); index.search( i1 - i0, decode_buffer.data(), @@ -308,17 +385,30 @@ void Clustering::train_encoded( std::vector hassign(k); size_t k_frozen = frozen_centroids ? n_input_centroids : 0; - detail::compute_centroids( - d, - k, - nx, - k_frozen, - x, - codec, - assign.get(), - weights, - hassign.data(), - centroids.data()); + if (fp16) { + detail::compute_centroids_fp16( + d, + k, + nx, + k_frozen, + reinterpret_cast(x), + assign.get(), + weights, + hassign.data(), + centroids.data()); + } else { + detail::compute_centroids( + d, + k, + nx, + k_frozen, + x, + codec, + assign.get(), + weights, + hassign.data(), + centroids.data()); + } int nsplit = detail::split_clusters( d, k, nx, k_frozen, hassign.data(), centroids.data()); diff --git a/thirdparty/faiss/faiss/Clustering.h b/thirdparty/faiss/faiss/Clustering.h index abb124681..3185fbfdb 100644 --- a/thirdparty/faiss/faiss/Clustering.h +++ b/thirdparty/faiss/faiss/Clustering.h @@ -148,11 +148,40 @@ struct Clustering : ClusteringParameters { Index& index, const float* weights = nullptr); + /** run k-means on vectors of the given numeric type + * + * Float32 is the same as train(). Float16 takes packed IEEE binary16 + * vectors (n * d uint16_t) and runs k-means natively on them: the NaN + * check, subsampling, initialization and centroid updates read the fp16 + * rows directly, and the assignment step passes blocks of at most + * decode_block_size fp16 rows to index.search_ex(Float16). Indexes with a + * native fp16 search consume them directly; the Index::search_ex default + * widens them block by block. There is no fp32 copy of the training set, + * unless init_method needs one. Centroids are fp32. + */ + void train_ex( + idx_t n, + const void* x, + NumericType numeric_type, + Index& index, + const float* weights = nullptr); + /// Post-process the centroids after each centroid update. /// includes optional L2 normalization and nearest integer rounding void post_process_centroids(); virtual ~Clustering() {} + + protected: + /// k-means on rows encoded by `codec` or, if codec is null, stored as + /// `numeric_type` (Float32 or Float16) + void train_impl( + idx_t nx, + const uint8_t* x_in, + const Index* codec, + NumericType numeric_type, + Index& index, + const float* weights); }; /** Exact 1D clustering algorithm diff --git a/thirdparty/faiss/faiss/IVFlib.cpp b/thirdparty/faiss/faiss/IVFlib.cpp index c5a182c73..e5df2ae51 100644 --- a/thirdparty/faiss/faiss/IVFlib.cpp +++ b/thirdparty/faiss/faiss/IVFlib.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -20,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -407,6 +409,103 @@ void search_with_parameters( } } +namespace { + +template +void scan_one_query_per_code( + const IndexIVF& index_ivf, + InvertedListScanner& scanner, + const idx_t* keys, + const float* coarse_dis, + size_t nprobe, + idx_t k, + float* distances, + idx_t* labels) { + heap_heapify(k, distances, labels); + const InvertedLists* invlists = index_ivf.invlists; + for (size_t j = 0; j < nprobe; j++) { + const idx_t key = keys[j]; + if (key < 0) { + continue; + } + scanner.set_list(key, coarse_dis[j]); + const size_t list_size = invlists->list_size(key); + InvertedLists::ScopedCodes codes(invlists, key); + InvertedLists::ScopedIds ids(invlists, key); + const uint8_t* code = codes.get(); + for (size_t i = 0; i < list_size; i++, code += index_ivf.code_size) { + const float dis = scanner.distance_to_code(code); + if (C::cmp(distances[0], dis)) { + heap_replace_top(k, distances, labels, dis, ids[i]); + } + } + } + heap_reorder(k, distances, labels); +} + +} // namespace + +void search_with_distance_to_code( + const Index* index, + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + size_t nprobe) { + std::unique_ptr del; + if (auto ip = dynamic_cast(index)) { + const float* xt = ip->apply_chain(n, x); + if (xt != x) { + del.reset(xt); + } + x = xt; + index = ip->index; + } + const IndexIVF* index_ivf = dynamic_cast(index); + FAISS_THROW_IF_NOT(index_ivf); + nprobe = std::min(nprobe, index_ivf->nlist); + + std::vector Iq(nprobe * n); + std::vector Dq(nprobe * n); + index_ivf->quantizer->search(n, x, nprobe, Dq.data(), Iq.data()); + +#pragma omp parallel + { + std::unique_ptr scanner( + index_ivf->get_InvertedListScanner()); +#pragma omp for + for (idx_t q = 0; q < n; q++) { + scanner->set_query(x + q * index_ivf->d); + const idx_t* keys = Iq.data() + q * nprobe; + const float* coarse_dis = Dq.data() + q * nprobe; + float* D = distances + q * k; + idx_t* I = labels + q * k; + if (scanner->keep_max) { + scan_one_query_per_code>( + *index_ivf, + *scanner, + keys, + coarse_dis, + nprobe, + k, + D, + I); + } else { + scan_one_query_per_code>( + *index_ivf, + *scanner, + keys, + coarse_dis, + nprobe, + k, + D, + I); + } + } + } +} + void range_search_with_parameters( const Index* index, idx_t n, @@ -561,35 +660,58 @@ int64_t DefaultShardingFunction::operator()(int64_t i, int64_t shard_count) { return i % shard_count; } +namespace { + +/// Returns the IndexIVF of an index that shard_ivf_index_centroids accepts: +/// an IndexIVF, or an IndexPreTransform whose sub-index is an IndexIVF. +/// Returns nullptr for any other index. +IndexIVF* get_shardable_ivf(Index* index) { + auto* pt = dynamic_cast(index); + return dynamic_cast(pt ? pt->index : index); +} + +template +void check_sharding_args( + const QuantizerType* quantizer, + const std::string& filename_template) { + FAISS_THROW_IF_MSG(quantizer->ntotal == 0, "No centroids to shard."); + FAISS_THROW_IF_MSG( + filename_template.find("%d") == std::string::npos, + "Invalid filename_template. Must contain format specifier for shard count."); +} + +} // namespace + void handle_ivf( - faiss::IndexIVF* index, + faiss::Index* index, int64_t shard_count, const std::string& filename_template, ShardingFunction* sharding_function, bool generate_ids) { + const faiss::Index* quantizer = get_shardable_ivf(index)->quantizer; // assign centroids to each sharded Index based on sharding_function, and // add them to the quantizer of each sharded index std::vector> sharded_centroids(shard_count); std::vector> xids(shard_count); - for (int64_t i = 0; i < index->quantizer->ntotal; i++) { + for (int64_t i = 0; i < quantizer->ntotal; i++) { int64_t shard_id = (*sharding_function)(i, shard_count); // Since the quantizer does not natively support add_with_ids, we simply // generate them. xids[shard_id].push_back(i); - float* reconstructed = new float[index->quantizer->d]; - index->quantizer->reconstruct(i, reconstructed); + float* reconstructed = new float[quantizer->d]; + quantizer->reconstruct(i, reconstructed); sharded_centroids[shard_id].insert( sharded_centroids[shard_id].end(), &reconstructed[0], - &reconstructed[index->quantizer->d]); + &reconstructed[quantizer->d]); delete[] reconstructed; } - auto clone = static_cast(faiss::clone_index(index)); - clone->quantizer->reset(); + std::unique_ptr clone(faiss::clone_index(index)); + get_shardable_ivf(clone.get())->quantizer->reset(); for (int64_t i = 0; i < shard_count; i++) { - auto sharded_index = - static_cast(faiss::clone_index(clone)); + std::unique_ptr sharded(faiss::clone_index(clone.get())); + faiss::IndexIVF* sharded_index = get_shardable_ivf(sharded.get()); if (generate_ids) { // Assume the quantizer does not natively support add_with_ids. // The IDMap wraps the cloned quantizer; own_fields makes it delete @@ -599,12 +721,12 @@ void handle_ivf( id_quantizer->own_fields = true; sharded_index->quantizer = id_quantizer; sharded_index->quantizer->add_with_ids( - sharded_centroids[i].size() / index->quantizer->d, + sharded_centroids[i].size() / quantizer->d, sharded_centroids[i].data(), xids[i].data()); } else { sharded_index->quantizer->add( - sharded_centroids[i].size() / index->quantizer->d, + sharded_centroids[i].size() / quantizer->d, sharded_centroids[i].data()); } char fname[256]; @@ -616,10 +738,8 @@ void handle_ivf( #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif - faiss::write_index(sharded_index, fname); - delete sharded_index; + faiss::write_index(sharded.get(), fname); } - delete clone; } void handle_binary_ivf( @@ -686,51 +806,24 @@ void handle_binary_ivf( delete clone; } -template -void sharding_helper( - IndexType* index, +void shard_ivf_index_centroids( + faiss::Index* index, int64_t shard_count, const std::string& filename_template, ShardingFunction* sharding_function, bool generate_ids) { - FAISS_THROW_IF_MSG(index->quantizer->ntotal == 0, "No centroids to shard."); + const faiss::IndexIVF* index_ivf = get_shardable_ivf(index); FAISS_THROW_IF_MSG( - filename_template.find("%d") == std::string::npos, - "Invalid filename_template. Must contain format specifier for shard count."); + index_ivf == nullptr, + "index must be an IndexIVF, or an IndexPreTransform whose sub-index is an IndexIVF."); + check_sharding_args(index_ivf->quantizer, filename_template); DefaultShardingFunction default_sharding_function; - if (sharding_function == nullptr) { - sharding_function = &default_sharding_function; - } - - if (typeid(IndexType) == typeid(faiss::IndexIVF)) { - handle_ivf( - dynamic_cast(index), - shard_count, - filename_template, - sharding_function, - generate_ids); - } else if (typeid(IndexType) == typeid(faiss::IndexBinaryIVF)) { - handle_binary_ivf( - dynamic_cast(index), - shard_count, - filename_template, - sharding_function, - generate_ids); - } -} - -void shard_ivf_index_centroids( - faiss::IndexIVF* index, - int64_t shard_count, - const std::string& filename_template, - ShardingFunction* sharding_function, - bool generate_ids) { - sharding_helper( + handle_ivf( index, shard_count, filename_template, - sharding_function, + sharding_function ? sharding_function : &default_sharding_function, generate_ids); } @@ -740,11 +833,14 @@ void shard_binary_ivf_index_centroids( const std::string& filename_template, ShardingFunction* sharding_function, bool generate_ids) { - sharding_helper( + check_sharding_args(index->quantizer, filename_template); + + DefaultShardingFunction default_sharding_function; + handle_binary_ivf( index, shard_count, filename_template, - sharding_function, + sharding_function ? sharding_function : &default_sharding_function, generate_ids); } diff --git a/thirdparty/faiss/faiss/IVFlib.h b/thirdparty/faiss/faiss/IVFlib.h index e85ce1314..6a839be9f 100644 --- a/thirdparty/faiss/faiss/IVFlib.h +++ b/thirdparty/faiss/faiss/IVFlib.h @@ -136,6 +136,21 @@ void search_with_parameters( size_t* nb_dis = nullptr, double* ms_per_stage = nullptr); +/** search an IndexIVF, possibly embedded in an IndexPreTransform, scoring + * every code with InvertedListScanner::distance_to_code, one call per code, + * as callers that run their own scan loop do (search() uses scan_codes, + * which batches codes). Meant for benchmarking that path. Each query is + * scanned by one thread; queries run in parallel. + */ +void search_with_distance_to_code( + const Index* index, + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + size_t nprobe); + /** same as search_with_parameters but for range search */ void range_search_with_parameters( const Index* index, @@ -186,7 +201,11 @@ struct DefaultShardingFunction : ShardingFunction { * the index to the path given by filename_generator. The centroids must already * be added to the index quantizer. * - * @param index The IVF index containing centroids to shard. + * @param index The IVF index containing centroids to shard: an + * IndexIVF, or an IndexPreTransform whose sub-index + * is an IndexIVF. Each shard of an IndexPreTransform + * is an IndexPreTransform with a copy of the + * transform chain. * @param shard_count Number of shards. * @param filename_template Template for shard filenames. * @param sharding_function The function to shard by. The default is ith vector @@ -196,7 +215,7 @@ struct DefaultShardingFunction : ShardingFunction { * @return The number of shards written. */ void shard_ivf_index_centroids( - IndexIVF* index, + Index* index, int64_t shard_count = 20, const std::string& filename_template = "shard.%d.index", ShardingFunction* sharding_function = nullptr, diff --git a/thirdparty/faiss/faiss/Index.cpp b/thirdparty/faiss/faiss/Index.cpp index a9a8413b0..c443f63ce 100644 --- a/thirdparty/faiss/faiss/Index.cpp +++ b/thirdparty/faiss/faiss/Index.cpp @@ -13,8 +13,11 @@ #include #include #include +#include +#include #include +#include namespace faiss { @@ -24,6 +27,14 @@ void Index::train(idx_t /*n*/, const float* /*x*/) { // does nothing by default } +void Index::train_dataset(const gpu::Dataset&) { + FAISS_THROW_MSG("Dataset training not implemented for this type of index"); +} + +void Index::add_dataset(const gpu::Dataset&) { + FAISS_THROW_MSG("Dataset addition not implemented for this type of index"); +} + void Index::train_with_queries( idx_t /*n*/, const float* /*x*/, @@ -123,6 +134,39 @@ void Index::search_subset( FAISS_THROW_MSG("search_subset not implemented for this type of index"); } +void Index::search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + if (numeric_type == NumericType::Float32) { + search(n, static_cast(x), k, distances, labels, params); + return; + } + FAISS_THROW_IF_NOT_MSG( + numeric_type == NumericType::Float16, + "Index::search: unsupported numeric type"); + FAISS_THROW_IF_NOT(d > 0); + // widen blocks of at most 64 MiB of fp32 queries + const idx_t bs = std::max( + 1, idx_t(64) * 1024 * 1024 / (sizeof(float) * idx_t(d))); + const uint16_t* x16 = static_cast(x); + std::vector buffer(size_t(std::min(n, bs)) * d); + for (idx_t i0 = 0; i0 < n; i0 += bs) { + const idx_t i1 = std::min(n, i0 + bs); + fp16_to_fp32(size_t(i1 - i0) * d, x16 + i0 * d, buffer.data()); + search(i1 - i0, + buffer.data(), + k, + distances + i0 * k, + labels + i0 * k, + params); + } +} + void Index::search1(const float*, ResultHandler&, SearchParameters*) const { FAISS_THROW_MSG("search1 not implemented for this type of index"); } diff --git a/thirdparty/faiss/faiss/Index.h b/thirdparty/faiss/faiss/Index.h index 97edfe644..2fcf2963e 100644 --- a/thirdparty/faiss/faiss/Index.h +++ b/thirdparty/faiss/faiss/Index.h @@ -16,8 +16,8 @@ #include #define FAISS_VERSION_MAJOR 1 -#define FAISS_VERSION_MINOR 15 -#define FAISS_VERSION_PATCH 1 +#define FAISS_VERSION_MINOR 16 +#define FAISS_VERSION_PATCH 0 // Macro to combine the version components into a single string #ifndef FAISS_STRINGIFY @@ -49,6 +49,10 @@ namespace faiss { +namespace gpu { +class Dataset; +} + /// Forward declarations see impl/AuxIndexStructures.h, impl/IDSelector.h /// and impl/DistanceComputer.h struct IDSelector; @@ -131,6 +135,9 @@ struct Index { */ virtual void train(idx_t n, const float* x); + /// Train from caller-controlled storage. Unsupported by default. + virtual void train_dataset(const gpu::Dataset& dataset); + /** Perform training on a representative set of vectors and a representative * set of queries * @@ -163,6 +170,9 @@ struct Index { */ virtual void add(idx_t n, const float* x) = 0; + /// Add caller-controlled storage. Unsupported by default. + virtual void add_dataset(const gpu::Dataset& dataset); + virtual void add_ex(idx_t n, const void* x, NumericType numeric_type) { if (numeric_type == NumericType::Float32) { add(n, static_cast(x)); @@ -212,6 +222,12 @@ struct Index { idx_t* labels, const SearchParameters* params = nullptr) const = 0; + /** search() for queries of the given numeric type + * + * Float32 calls search(). By default, Float16 queries (packed IEEE + * binary16, size n * d) are widened to fp32 in bounded blocks and passed + * to search(); indexes with a native fp16 search override this. + */ virtual void search_ex( idx_t n, const void* x, @@ -219,18 +235,7 @@ struct Index { idx_t k, float* distances, idx_t* labels, - const SearchParameters* params = nullptr) const { - if (numeric_type == NumericType::Float32) { - search(n, - static_cast(x), - k, - distances, - labels, - params); - } else { - FAISS_THROW_MSG("Index::search: unsupported numeric type"); - } - } + const SearchParameters* params = nullptr) const; /** search one vector with a custom result handler */ virtual void search1( diff --git a/thirdparty/faiss/faiss/IndexBinary.cpp b/thirdparty/faiss/faiss/IndexBinary.cpp index 9962e9410..1923426f6 100644 --- a/thirdparty/faiss/faiss/IndexBinary.cpp +++ b/thirdparty/faiss/faiss/IndexBinary.cpp @@ -29,6 +29,14 @@ void IndexBinary::train(idx_t, const uint8_t*) { // Does nothing by default. } +void IndexBinary::train_dataset(const gpu::Dataset&) { + FAISS_THROW_MSG("Dataset training not implemented for this type of index"); +} + +void IndexBinary::add_dataset(const gpu::Dataset&) { + FAISS_THROW_MSG("Dataset addition not implemented for this type of index"); +} + void IndexBinary::range_search( idx_t, const uint8_t*, diff --git a/thirdparty/faiss/faiss/IndexBinary.h b/thirdparty/faiss/faiss/IndexBinary.h index 2ce811762..bf1aa19ad 100644 --- a/thirdparty/faiss/faiss/IndexBinary.h +++ b/thirdparty/faiss/faiss/IndexBinary.h @@ -52,6 +52,10 @@ struct IndexBinary { * @param x training vectors, size n * d / 8 */ virtual void train(idx_t n, const uint8_t* x); + + /// Train from caller-controlled storage. Unsupported by default. + virtual void train_dataset(const gpu::Dataset& dataset); + virtual void train_ex(idx_t n, const void* x, NumericType numeric_type) { if (numeric_type == NumericType::UInt8) { train(n, static_cast(x)); @@ -66,6 +70,10 @@ struct IndexBinary { * @param x input matrix, size n * d / 8 */ virtual void add(idx_t n, const uint8_t* x) = 0; + + /// Add caller-controlled storage. Unsupported by default. + virtual void add_dataset(const gpu::Dataset& dataset); + virtual void add_ex(idx_t n, const void* x, NumericType numeric_type) { if (numeric_type == NumericType::UInt8) { add(n, static_cast(x)); diff --git a/thirdparty/faiss/faiss/IndexBinaryFlat.cpp b/thirdparty/faiss/faiss/IndexBinaryFlat.cpp index 22c395ff9..d5774c1da 100644 --- a/thirdparty/faiss/faiss/IndexBinaryFlat.cpp +++ b/thirdparty/faiss/faiss/IndexBinaryFlat.cpp @@ -100,6 +100,7 @@ size_t IndexBinaryFlat::remove_ids(const IDSelector& sel) { } void IndexBinaryFlat::reconstruct(idx_t key, uint8_t* recons) const { + FAISS_THROW_IF_NOT(key >= 0 && key < ntotal); memcpy(recons, &(xb[code_size * key]), sizeof(*recons) * code_size); } diff --git a/thirdparty/faiss/faiss/IndexBinaryHNSW.cpp b/thirdparty/faiss/faiss/IndexBinaryHNSW.cpp index c512f2443..885e85968 100644 --- a/thirdparty/faiss/faiss/IndexBinaryHNSW.cpp +++ b/thirdparty/faiss/faiss/IndexBinaryHNSW.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include @@ -121,9 +122,8 @@ void IndexBinaryHNSW::search( } } -#pragma omp critical - { - hnsw_stats.combine({n1, n2, ndis, nhops}); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic({n1, n2, ndis, nhops}); } #pragma omp parallel for @@ -176,6 +176,84 @@ DistanceComputer* IndexBinaryHNSW::get_distance_computer() const { }); } +namespace { + +// The sample of an IndexBinaryHNSW. Hamming distances are integers, so a +// nearer node has a strictly smaller distance. +struct BinaryLinkSample : HNSWLinkSampleSearch { + const IndexBinaryHNSW& index; + const uint8_t* x; + + BinaryLinkSample( + const IndexBinaryHNSW& index_in, + idx_t n_in, + const uint8_t* x_in) + : index(index_in), x(x_in) { + n = n_in; + } + + std::vector gather(size_t m, const idx_t* ids) const { + const size_t cs = index.code_size; + std::vector rows(m * cs); + for (size_t j = 0; j < m; j++) { + memcpy(rows.data() + j * cs, x + ids[j] * cs, cs); + } + return rows; + } + + void search( + const SearchParametersHNSW* params, + size_t m, + const idx_t* ids, + idx_t* labels) const override { + std::vector distances(m); + if (!ids) { + index.search(m, x, 1, distances.data(), labels, params); + return; + } + index.search( + m, gather(m, ids).data(), 1, distances.data(), labels, params); + } + + void search_exact( + size_t m, + const idx_t* ids, + const idx_t* found, + idx_t* exact, + uint8_t* nearer) const override { + const size_t cs = index.code_size; + const std::vector rows = gather(m, ids); + std::vector distances(m); + index.storage->search(m, rows.data(), 1, distances.data(), exact); +#pragma omp parallel + { + std::unique_ptr dis( + index.get_distance_computer()); +#pragma omp for schedule(static) + for (int64_t j = 0; j < static_cast(m); j++) { + if (exact[j] < 0 || exact[j] == found[j]) { + continue; + } + dis->set_query( + reinterpret_cast(rows.data() + j * cs)); + nearer[j] = (*dis)(exact[j]) < (*dis)(found[j]); + } + } + } +}; + +} // namespace + +HNSWLevel0LinkStats IndexBinaryHNSW::add_level_0_links_from_sample( + idx_t n, + const uint8_t* x, + const HNSWLevel0LinkParameters& params) { + const BinaryLinkSample sample(*this, n, x); + std::unique_ptr dis(get_distance_computer()); + return hnsw_add_level_0_links_from_sample( + hnsw, ntotal, *dis, false, sample, params); +} + /************************************************************** * IndexBinaryHNSWCagra implementation **************************************************************/ @@ -272,10 +350,10 @@ void IndexBinaryHNSWCagra::search( params); res.end(); + vt->advance(); } -#pragma omp critical - { - hnsw_stats.combine(search_stats); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic(search_stats); } } diff --git a/thirdparty/faiss/faiss/IndexBinaryHNSW.h b/thirdparty/faiss/faiss/IndexBinaryHNSW.h index 9bca05a31..524bb0bd6 100644 --- a/thirdparty/faiss/faiss/IndexBinaryHNSW.h +++ b/thirdparty/faiss/faiss/IndexBinaryHNSW.h @@ -40,6 +40,14 @@ struct IndexBinaryHNSW : IndexBinary { // used when GpuIndexBinaryCagra::copyFrom(IndexBinaryHNSW*) is called. bool keep_max_size_level0 = false; + // When this index is the coarse quantizer of an IndexBinaryIVF, + // IndexBinaryIVF::train() calls add_level_0_links_from_sample() after it + // adds the centroids. The sample is the first + // min(n, level_0_link_samples_per_node * ntotal) training vectors. 0 + // disables the call. Training does not call it when the quantizer is + // already trained. The index format does not store this value. + int level_0_link_samples_per_node = 3; + explicit IndexBinaryHNSW(); explicit IndexBinaryHNSW(int d, int M = 32); explicit IndexBinaryHNSW(IndexBinary* storage, int M = 32); @@ -65,6 +73,17 @@ struct IndexBinaryHNSW : IndexBinary { void reconstruct(idx_t key, uint8_t* recons) const override; void reset() override; + + /** Adds level-0 links so that the search no longer stops at "sinks": + * nodes where it stops for many vectors whose nearest node is elsewhere. + * See IndexHNSW::add_level_0_links_from_sample(). x holds n binary + * vectors. Call this function after the last add(). + */ + HNSWLevel0LinkStats add_level_0_links_from_sample( + idx_t n, + const uint8_t* x, + const HNSWLevel0LinkParameters& params = + HNSWLevel0LinkParameters()); }; struct IndexBinaryHNSWCagra : IndexBinaryHNSW { diff --git a/thirdparty/faiss/faiss/IndexBinaryIVF.cpp b/thirdparty/faiss/faiss/IndexBinaryIVF.cpp index 0f9e3cd1b..5aebbac36 100644 --- a/thirdparty/faiss/faiss/IndexBinaryIVF.cpp +++ b/thirdparty/faiss/faiss/IndexBinaryIVF.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -156,7 +157,7 @@ void IndexBinaryIVF::search( coarse_dis.get(), idx.get(), params ? params->quantizer_params : nullptr); - indexIVF_stats.quantization_time += getmillisecs() - t0; + double quantization_time = getmillisecs() - t0; t0 = getmillisecs(); invlists->prefetch_lists(idx.get(), static_cast(n * nprobe_)); @@ -171,7 +172,7 @@ void IndexBinaryIVF::search( labels, false, params); - indexIVF_stats.search_time += getmillisecs() - t0; + add_search_times(quantization_time, getmillisecs() - t0); } void IndexBinaryIVF::reconstruct(idx_t key, uint8_t* recons) const { @@ -254,6 +255,21 @@ void IndexBinaryIVF::reconstruct_from_offset( idx_t list_no, idx_t offset, uint8_t* recons) const { + FAISS_THROW_IF_NOT_FMT( + list_no >= 0 && + static_cast(list_no) < + static_cast(nlist), + "Invalid list_no %" PRId64 " (nlist=%zd)", + list_no, + nlist); + FAISS_THROW_IF_NOT_FMT( + offset >= 0 && + static_cast(offset) < + static_cast(invlists->list_size(list_no)), + "Invalid offset %" PRId64 " for list %" PRId64 " (size=%zd)", + offset, + list_no, + invlists->list_size(list_no)); memcpy(recons, InvertedLists::ScopedCodes(invlists, list_no, offset).get(), code_size); @@ -308,6 +324,24 @@ void IndexBinaryIVF::train(idx_t n, const uint8_t* x) { quantizer->add(clus.k, x_b.get()); quantizer->is_trained = true; + + auto* hnsw = dynamic_cast(quantizer); + if (hnsw && hnsw->level_0_link_samples_per_node > 0) { + const idx_t samples = std::min( + n, idx_t(hnsw->level_0_link_samples_per_node) * nlist); + const HNSWLevel0LinkStats stats = + hnsw->add_level_0_links_from_sample(samples, x); + if (verbose) { + printf("HNSW quantizer level-0 links from %" PRId64 + " samples: %zd sinks found, %zd remaining, %zd links " + "added, %zd replaced\n", + samples, + stats.n_sinks_found, + stats.n_sinks_remaining, + stats.n_links_added, + stats.n_links_replaced); + } + } } is_trained = true; @@ -449,10 +483,7 @@ void search_knn_hamming_heap( } // parallel for } // parallel - indexIVF_stats.nq += n; - indexIVF_stats.nlist += nlistv; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nheap_updates += nheap; + add_search_stats(n, nlistv, ndis, nheap); } } // anonymous namespace @@ -522,14 +553,14 @@ void IndexBinaryIVF::range_search( double t0 = getmillisecs(); quantizer->search(n, x, nprobe_2, coarse_dis.get(), idx.get()); - indexIVF_stats.quantization_time += getmillisecs() - t0; + double quantization_time = getmillisecs() - t0; t0 = getmillisecs(); invlists->prefetch_lists(idx.get(), static_cast(n * nprobe_2)); range_search_preassigned(n, x, radius, idx.get(), coarse_dis.get(), res); - indexIVF_stats.search_time += getmillisecs() - t0; + add_search_times(quantization_time, getmillisecs() - t0); } void IndexBinaryIVF::range_search_preassigned( @@ -594,9 +625,7 @@ void IndexBinaryIVF::range_search_preassigned( pres.finalize(); } - indexIVF_stats.nq += n; - indexIVF_stats.nlist += nlistv; - indexIVF_stats.ndis += ndis; + add_search_stats(n, nlistv, ndis); } IndexBinaryIVF::~IndexBinaryIVF() { diff --git a/thirdparty/faiss/faiss/IndexFastScan.cpp b/thirdparty/faiss/faiss/IndexFastScan.cpp index bd7ed4838..98e540d15 100644 --- a/thirdparty/faiss/faiss/IndexFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexFastScan.cpp @@ -55,7 +55,7 @@ IndexFastScan::IndexFastScan() void IndexFastScan::reset() { codes.resize(0); - ntotal = 0; + ntotal = ntotal2 = 0; } void IndexFastScan::add(idx_t n, const float* x) { @@ -194,7 +194,7 @@ void estimators_from_tables_generic( } if (nscale) { - for (size_t m = 0; m < nscale; m++) { + for (int m = 0; m < nscale; m++) { uint64_t c = bsr.read(static_cast(index.nbits)); dis += dt[c] * context.pq2x4_scale; dt += index.ksub; @@ -267,15 +267,16 @@ void IndexFastScan::search( float* distances, idx_t* labels, const SearchParameters* params) const { - FAISS_THROW_IF_MSG(params, "search params not supported for this index"); FAISS_THROW_IF_NOT(k > 0); + const IDSelector* sel = params ? params->sel : nullptr; FastScanDistancePostProcessing empty_context{}; if (metric_type == METRIC_L2) { - search_dispatch_implem(n, x, k, distances, labels, empty_context); + search_dispatch_implem( + n, x, k, distances, labels, empty_context, sel); } else { search_dispatch_implem( - n, x, k, distances, labels, empty_context); + n, x, k, distances, labels, empty_context, sel); } } @@ -286,7 +287,8 @@ void IndexFastScan::search_dispatch_implem( idx_t k, float* distances, idx_t* labels, - const FastScanDistancePostProcessing& context) const { + const FastScanDistancePostProcessing& context, + const IDSelector* sel) const { using Cfloat = typename std::conditional< is_max, CMax, @@ -317,6 +319,10 @@ void IndexFastScan::search_dispatch_implem( FAISS_THROW_MSG("not implemented"); } else if (implem == 2 || implem == 3 || implem == 4) { FAISS_THROW_IF_NOT(orig_codes); + FAISS_THROW_IF_MSG( + sel, + "IDSelector is not supported by implem 2/3/4; leave implem at " + "0 so a selector-aware kernel is chosen"); search_implem_234(n, x, k, distances, labels, context); } else if (impl >= 12 && impl <= 15) { FAISS_THROW_IF_NOT(ntotal < INT_MAX); @@ -328,9 +334,11 @@ void IndexFastScan::search_dispatch_implem( // - OpenMP disabled (omp_get_max_threads() = 1) if (nt < 2) { if (impl == 12 || impl == 13) { - search_implem_12(n, x, k, distances, labels, impl, context); + search_implem_12( + n, x, k, distances, labels, impl, context, sel); } else { - search_implem_14(n, x, k, distances, labels, impl, context); + search_implem_14( + n, x, k, distances, labels, impl, context, sel); } } else { // explicitly slice over threads @@ -355,7 +363,8 @@ void IndexFastScan::search_dispatch_implem( dis_i, lab_i, impl, - thread_context); + thread_context, + sel); } else { search_implem_14( i1 - i0, @@ -364,7 +373,8 @@ void IndexFastScan::search_dispatch_implem( dis_i, lab_i, impl, - thread_context); + thread_context, + sel); } } } @@ -440,7 +450,8 @@ void IndexFastScan::search_implem_12( float* distances, idx_t* labels, int impl, - const FastScanDistancePostProcessing& context) const { + const FastScanDistancePostProcessing& context, + const IDSelector* sel) const { FAISS_THROW_IF_NOT(bbs == 32); // handle qbs2 blocking by recursive call @@ -460,7 +471,8 @@ void IndexFastScan::search_implem_12( distances + i0 * k, labels + i0 * k, impl, - sub_context); + sub_context, + sel); } return; } @@ -492,7 +504,7 @@ void IndexFastScan::search_implem_12( FAISS_THROW_IF_NOT(LUT_nq == n); auto scanner = make_knn_scanner( - C::is_max, n, k, ntotal, distances, labels, nullptr, impl, context); + C::is_max, n, k, ntotal, distances, labels, sel, impl, context); auto* rh = scanner->handler(); rh->normalizers = normalizers.get(); // Note: skip & 2 previously set handler->disable (run kernel, @@ -525,7 +537,8 @@ void IndexFastScan::search_implem_14( float* distances, idx_t* labels, int impl, - const FastScanDistancePostProcessing& context) const { + const FastScanDistancePostProcessing& context, + const IDSelector* sel) const { FAISS_THROW_IF_NOT(bbs % 32 == 0); // The accumulate loop dispatch table only instantiates certain @@ -553,7 +566,8 @@ void IndexFastScan::search_implem_14( distances + i0 * k, labels + i0 * k, impl, - sub_context); + sub_context, + sel); } return; } @@ -577,7 +591,7 @@ void IndexFastScan::search_implem_14( LUT.get()); auto scanner = make_knn_scanner( - C::is_max, n, k, ntotal, distances, labels, nullptr, impl, context); + C::is_max, n, k, ntotal, distances, labels, sel, impl, context); auto* rh = scanner->handler(); rh->normalizers = normalizers.get(); // Note: skip & 2 previously set handler->disable (run kernel, @@ -606,7 +620,8 @@ template void IndexFastScan::search_dispatch_implem( idx_t k, float* distances, idx_t* labels, - const FastScanDistancePostProcessing& context) const; + const FastScanDistancePostProcessing& context, + const IDSelector* sel) const; template void IndexFastScan::search_dispatch_implem( idx_t n, @@ -614,7 +629,8 @@ template void IndexFastScan::search_dispatch_implem( idx_t k, float* distances, idx_t* labels, - const FastScanDistancePostProcessing& context) const; + const FastScanDistancePostProcessing& context, + const IDSelector* sel) const; void IndexFastScan::reconstruct(idx_t key, float* recons) const { FAISS_THROW_IF_NOT_FMT( diff --git a/thirdparty/faiss/faiss/IndexFastScan.h b/thirdparty/faiss/faiss/IndexFastScan.h index 8f73e4322..e323cd1a6 100644 --- a/thirdparty/faiss/faiss/IndexFastScan.h +++ b/thirdparty/faiss/faiss/IndexFastScan.h @@ -155,7 +155,8 @@ struct IndexFastScan : Index { idx_t k, float* distances, idx_t* labels, - const FastScanDistancePostProcessing& context) const; + const FastScanDistancePostProcessing& context, + const IDSelector* sel = nullptr) const; template void search_implem_234( @@ -174,7 +175,8 @@ struct IndexFastScan : Index { float* distances, idx_t* labels, int impl, - const FastScanDistancePostProcessing& context) const; + const FastScanDistancePostProcessing& context, + const IDSelector* sel = nullptr) const; template void search_implem_14( @@ -184,7 +186,8 @@ struct IndexFastScan : Index { float* distances, idx_t* labels, int impl, - const FastScanDistancePostProcessing& context) const; + const FastScanDistancePostProcessing& context, + const IDSelector* sel = nullptr) const; /** Reconstruct a vector from its code * diff --git a/thirdparty/faiss/faiss/IndexFlat.cpp b/thirdparty/faiss/faiss/IndexFlat.cpp index 7204bc748..fda3465ca 100644 --- a/thirdparty/faiss/faiss/IndexFlat.cpp +++ b/thirdparty/faiss/faiss/IndexFlat.cpp @@ -59,6 +59,40 @@ void IndexFlat::search( } } +void IndexFlat::search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + if (numeric_type != NumericType::Float16 || + (metric_type != METRIC_L2 && metric_type != METRIC_INNER_PRODUCT)) { + Index::search_ex(n, x, numeric_type, k, distances, labels, params); + return; + } + FAISS_THROW_IF_NOT(k > 0); + const IDSelector* sel = params ? params->sel : nullptr; + const uint16_t* x16 = static_cast(x); + if (metric_type == METRIC_INNER_PRODUCT) { + knn_inner_product_fp16( + x16, get_xb(), d, n, ntotal, k, distances, labels, sel); + } else { + knn_L2sqr_fp16( + x16, + get_xb(), + d, + n, + ntotal, + k, + distances, + labels, + nullptr, + sel); + } +} + void IndexFlat::range_search( idx_t n, const float* x, @@ -282,7 +316,7 @@ FlatCodesDistanceComputer* IndexFlat::get_FlatCodesDistanceComputer() const { } void IndexFlat::reconstruct(idx_t key, float* recons) const { - FAISS_THROW_IF_NOT(key < ntotal); + FAISS_THROW_IF_NOT(key >= 0 && key < ntotal); memcpy(recons, &(codes[key * code_size]), code_size); } @@ -446,6 +480,17 @@ void IndexFlat1D::reset() { perm.clear(); } +void IndexFlat1D::search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + Index::search_ex(n, x, numeric_type, k, distances, labels, params); +} + void IndexFlat1D::search( idx_t n, const float* x, @@ -670,6 +715,17 @@ void IndexFlatPanorama::add(idx_t n, const float* x) { pano.compute_cumulative_sums(cum_sums.data(), offset, n, x); } +void IndexFlatPanorama::search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + Index::search_ex(n, x, numeric_type, k, distances, labels, params); +} + void IndexFlatPanorama::search( idx_t n, const float* x, diff --git a/thirdparty/faiss/faiss/IndexFlat.h b/thirdparty/faiss/faiss/IndexFlat.h index 7c8fb889f..52547ef1e 100644 --- a/thirdparty/faiss/faiss/IndexFlat.h +++ b/thirdparty/faiss/faiss/IndexFlat.h @@ -31,6 +31,17 @@ struct IndexFlat : IndexFlatCodes { idx_t* labels, const SearchParameters* params = nullptr) const override; + /// Float16 queries with METRIC_L2 / METRIC_INNER_PRODUCT are searched + /// natively (knn_L2sqr_fp16 / knn_inner_product_fp16). + void search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; + void range_search( idx_t n, const float* x, @@ -135,6 +146,16 @@ struct IndexFlatPanorama : IndexFlat { idx_t* labels, const SearchParameters* params = nullptr) const override; + /// widens Float16 queries for search() (Index::search_ex default) + void search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; + void range_search( idx_t n, const float* x, @@ -221,6 +242,16 @@ struct IndexFlat1D : IndexFlatL2 { float* distances, idx_t* labels, const SearchParameters* params = nullptr) const override; + + /// widens Float16 queries for search() (Index::search_ex default) + void search_ex( + idx_t n, + const void* x, + NumericType numeric_type, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; }; } // namespace faiss diff --git a/thirdparty/faiss/faiss/IndexFlatCodes.cpp b/thirdparty/faiss/faiss/IndexFlatCodes.cpp index 889afe4a7..459c3d443 100644 --- a/thirdparty/faiss/faiss/IndexFlatCodes.cpp +++ b/thirdparty/faiss/faiss/IndexFlatCodes.cpp @@ -45,7 +45,12 @@ void IndexFlatCodes::add_sa_codes( } void IndexFlatCodes::reset() { - codes.clear(); + if (codes.is_owned) { + codes.clear(); + } else { + // a view (mmap / zero-copy load) cannot be cleared in place + codes = MaybeOwnedVector(); + } ntotal = 0; } diff --git a/thirdparty/faiss/faiss/IndexHNSW.cpp b/thirdparty/faiss/faiss/IndexHNSW.cpp index f44304dde..e2b924093 100644 --- a/thirdparty/faiss/faiss/IndexHNSW.cpp +++ b/thirdparty/faiss/faiss/IndexHNSW.cpp @@ -9,8 +9,10 @@ #include +#include #include #include +#include #include #include #include @@ -32,8 +34,10 @@ #include #include #include +#include #include #include +#include namespace faiss { @@ -42,6 +46,13 @@ using NodeDistFarther = HNSW::NodeDistFarther; HNSWStats hnsw_stats; +void HNSWStats::combine_atomic(const HNSWStats& other) { + detail::atomic_fetch_add_relaxed(n1, other.n1); + detail::atomic_fetch_add_relaxed(n2, other.n2); + detail::atomic_fetch_add_relaxed(ndis, other.ndis); + detail::atomic_fetch_add_relaxed(nhops, other.nhops); +} + /************************************************************** * add / search blocks of descriptors **************************************************************/ @@ -429,6 +440,7 @@ void hnsw_search( idx_t check_period = InterruptCallback::get_period_hint( hnsw.max_level * index->d * efSearch); + check_period *= omp_get_max_threads(); for (idx_t i0 = 0; i0 < n; i0 += check_period) { idx_t i1 = std::min(i0 + check_period, n); @@ -466,6 +478,9 @@ void hnsw_search( rq->stats.reset(); } + // HNSW::search owns the per-query generation advance. The + // reusable-table acquisition above only clears stale TLS + // state before this thread starts processing queries. HNSWStats stats = hnsw.search(*dis, index, *res, *vt, params); n1 += stats.n1; @@ -477,7 +492,6 @@ void hnsw_search( n_rabitq_refine += rq->stats.n_refine; } res->end(); - vt->advance(); } catch (...) { omp_capture_exception(ex, [&] { interrupt = true; }); } @@ -487,10 +501,9 @@ void hnsw_search( InterruptCallback::check(); } -#pragma omp critical - { - hnsw_stats.combine({n1, n2, ndis, nhops}); - rabitq_stats.add({n_rabitq_1bit, n_rabitq_refine}); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic({n1, n2, ndis, nhops}); + rabitq_stats.add_atomic({n_rabitq_1bit, n_rabitq_refine}); } } @@ -702,10 +715,9 @@ void IndexHNSW::search_level_0( omp_capture_exception(ex, [&] { interrupt = true; }); } } -#pragma omp critical - { - hnsw_stats.combine(search_stats); - rabitq_stats.add(rq_search_stats); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic(search_stats); + rabitq_stats.add_atomic(rq_search_stats); } } omp_rethrow_if_exception(ex); @@ -775,7 +787,7 @@ void IndexHNSW::init_level_0_from_entry_points( storage_distance_computer(storage)); std::vector vec(storage->d); -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (int i = 0; i < n; i++) { storage_idx_t pt_id = points[i]; storage_idx_t nearest = nearests[i]; @@ -898,6 +910,436 @@ IndexHNSWFlat::IndexHNSWFlat(int d_in, int M, MetricType metric) is_trained = true; } +/************************************************************** + * IndexHNSW::add_level_0_links_from_sample + **************************************************************/ + +namespace { + +// Relative difference below which two distances are equal: float rounding, +// or near-duplicate nodes. Exact duplicates give equal distances already. +constexpr float kSinkDistanceTolerance = 1e-5f; + +// True when distance (or similarity) a is better than b by more than the +// tolerance. +bool is_better(float a, float b, bool similarity) { + const float tolerance = + kSinkDistanceTolerance * std::max(std::fabs(a), std::fabs(b)); + return similarity ? a > b + tolerance : a < b - tolerance; +} + +constexpr size_t kSinkChunk = 16384; + +struct SinkScan { + size_t n_exact_searches = 0; + std::vector sinks; // sorted + // For each sink, the nearest nodes of its wrong vectors with their + // counts, most frequent first. Ties go to the smaller node ID. + std::vector>> targets; +}; + +// Finds the sinks from the HNSW labels of the sample vectors. Searches the +// vectors that arrive at candidate sinks also with the exact search, unless +// their exact result is already known. exact[i] is the nearer node that the +// exact search found for labels[i], or labels[i] if none (-1: not computed). +SinkScan find_sinks( + size_t ntotal, + const HNSWLinkSampleSearch& sample, + const HNSWLevel0LinkParameters& params, + const std::vector& labels, + std::vector& exact) { + const idx_t n = sample.n; + std::vector counts(ntotal, 0); + for (idx_t i = 0; i < n; i++) { + if (labels[i] >= 0) { + counts[labels[i]]++; + } + } + + const double min_count = + std::max(2.0, params.min_mean_factor * double(n) / ntotal); + // candidates: vectors that arrive at candidate sinks + std::vector candidates, unknown, found; + candidates.reserve(n); + for (idx_t i = 0; i < n; i++) { + if (labels[i] >= 0 && counts[labels[i]] >= min_count) { + candidates.push_back(i); + if (exact[i] < 0) { + unknown.push_back(i); + found.push_back(labels[i]); + } + } + } + std::vector exact_labels(unknown.size()); + std::vector nearer(unknown.size(), 0); + sample.search_exact( + unknown.size(), + unknown.data(), + found.data(), + exact_labels.data(), + nearer.data()); + for (size_t j = 0; j < unknown.size(); j++) { + exact[unknown[j]] = nearer[j] ? exact_labels[j] : found[j]; + } + + // (sink candidate, nearest node) for each vector with a nearer node + std::vector> wrong; + wrong.reserve(candidates.size()); + std::vector closer(ntotal, 0); + for (size_t j = 0; j < candidates.size(); j++) { + const idx_t i = candidates[j]; + if (exact[i] != labels[i]) { + closer[labels[i]]++; + wrong.emplace_back(labels[i], exact[i]); + } + } + std::sort(wrong.begin(), wrong.end()); + + SinkScan scan; + scan.n_exact_searches = unknown.size(); + for (size_t a = 0; a < wrong.size();) { + const idx_t sink = wrong[a].first; + size_t b = a; + while (b < wrong.size() && wrong[b].first == sink) { + b++; + } + if (closer[sink] >= params.min_closer_fraction * counts[sink]) { + std::vector> targets; + for (size_t c = a; c < b;) { + size_t e = c; + while (e < b && wrong[e].second == wrong[c].second) { + e++; + } + targets.emplace_back(wrong[c].second, e - c); + c = e; + } + std::sort( + targets.begin(), + targets.end(), + [](const auto& p, const auto& q) { + return p.second != q.second ? p.second > q.second + : p.first < q.first; + }); + scan.sinks.push_back(sink); + scan.targets.push_back(std::move(targets)); + } + a = b; + } + return scan; +} + +// Gives `sink` level-0 links to up to `max_links` targets that it does not +// link to yet: first in free slots, then in place of its farthest links. It +// keeps at least half of its links. Returns (links added, links replaced). +std::pair link_sink( + HNSW& hnsw, + DistanceComputer& dis, + HNSW::storage_idx_t sink, + const std::vector>& targets, + int max_links, + bool similarity) { + size_t begin, end; + hnsw.neighbor_range(sink, 0, &begin, &end); + size_t degree = 0; + while (begin + degree < end && hnsw.neighbors[begin + degree] >= 0) { + degree++; + } + + std::vector fresh; + for (const auto& [target, count] : targets) { + if (static_cast(fresh.size()) >= max_links) { + break; + } + bool linked = target == sink; + for (size_t k = begin; k < begin + degree && !linked; k++) { + linked = hnsw.neighbors[k] == target; + } + if (!linked) { + fresh.push_back(static_cast(target)); + } + } + + const size_t added = std::min(fresh.size(), (end - begin) - degree); + for (size_t k = 0; k < added; k++) { + hnsw.neighbors[begin + degree + k] = fresh[k]; + } + + size_t replaced = 0; + if (added < fresh.size()) { + // (distance from the sink, slot), farthest first + std::vector> links; + for (size_t k = begin; k < begin + degree; k++) { + links.emplace_back(dis.symmetric_dis(sink, hnsw.neighbors[k]), k); + } + std::sort( + links.begin(), links.end(), [&](const auto& p, const auto& q) { + if (p.first != q.first) { + return similarity ? p.first < q.first + : p.first > q.first; + } + return p.second < q.second; + }); + const size_t replaceable = degree / 2; + for (size_t k = added; k < fresh.size() && replaced < replaceable; + k++, replaced++) { + hnsw.neighbors[links[replaced].second] = fresh[k]; + } + } + return {added, replaced}; +} + +// The sample of an IndexHNSW: fp32 or packed fp16 rows, or rows encoded by a +// codec. +struct IndexHNSWLinkSample : HNSWLinkSampleSearch { + const IndexHNSW& index; + const uint8_t* x; + NumericType numeric_type; + const Index* codec; + + IndexHNSWLinkSample( + const IndexHNSW& index_in, + idx_t n_in, + const uint8_t* x_in, + NumericType numeric_type_in, + const Index* codec_in) + : index(index_in), + x(x_in), + numeric_type(numeric_type_in), + codec(codec_in) { + n = n_in; + } + + size_t line_size() const { + return codec ? codec->sa_code_size() + : get_numeric_type_size(numeric_type) * index.d; + } + + // Decodes m contiguous rows to fp32. + void decode(size_t m, const uint8_t* rows, float* out) const { + if (codec) { + codec->sa_decode(m, rows, out); + } else if (numeric_type == NumericType::Float16) { + fp16_to_fp32( + m * index.d, reinterpret_cast(rows), out); + } else { + memcpy(out, rows, m * index.d * sizeof(float)); + } + } + + void decode_rows( + size_t begin, + size_t m, + const idx_t* ids, + std::vector& rows, + float* out) const { + const size_t ls = line_size(); + if (!ids) { + decode(m, x + begin * ls, out); + return; + } + if (!codec && numeric_type == NumericType::Float32) { + for (size_t j = 0; j < m; j++) { + memcpy(out + j * index.d, x + ids[begin + j] * ls, ls); + } + return; + } + rows.resize(m * ls); + for (size_t j = 0; j < m; j++) { + memcpy(rows.data() + j * ls, x + ids[begin + j] * ls, ls); + } + decode(m, rows.data(), out); + } + + // Decodes the sample vectors by blocks of kSinkChunk. + void search( + const SearchParametersHNSW* params, + size_t m_total, + const idx_t* ids, + idx_t* labels) const override { + if (!ids && !codec && numeric_type == NumericType::Float32) { + std::vector distances(m_total); + index.search( + m_total, + reinterpret_cast(x), + 1, + distances.data(), + labels, + params); + return; + } + std::vector rows; + std::vector block, distances(kSinkChunk); + for (size_t i0 = 0; i0 < m_total; i0 += kSinkChunk) { + const size_t m = std::min(kSinkChunk, m_total - i0); + block.resize(m * index.d); + decode_rows(i0, m, ids, rows, block.data()); + index.search( + m, block.data(), 1, distances.data(), labels + i0, params); + } + } + + void search_exact( + size_t m_total, + const idx_t* ids, + const idx_t* found, + idx_t* exact, + uint8_t* nearer) const override { + const size_t d = index.d; + const bool similarity = is_similarity_metric(index.metric_type); + std::vector exact_distances(kSinkChunk); + std::vector rows; + std::vector chunk; + for (size_t begin = 0; begin < m_total; begin += kSinkChunk) { + const size_t m = std::min(kSinkChunk, m_total - begin); + chunk.resize(m * d); + decode_rows(begin, m, ids, rows, chunk.data()); + index.storage->search( + m, chunk.data(), 1, exact_distances.data(), exact + begin); + + // Compute both distances again with the same distance function. + // The batched exact search and the HNSW search round + // differently, which can make a node look nearer when the two + // distances are almost equal. +#pragma omp parallel + { + std::unique_ptr dis( + storage_distance_computer(index.storage)); +#pragma omp for schedule(static) + for (int64_t j = 0; j < static_cast(m); j++) { + const idx_t e = exact[begin + j], f = found[begin + j]; + if (e < 0 || e == f) { + continue; + } + dis->set_query(chunk.data() + j * d); + nearer[begin + j] = + is_better((*dis)(e), (*dis)(f), similarity); + } + } + } + } +}; + +HNSWLevel0LinkStats add_level_0_links_impl( + IndexHNSW& index, + const IndexHNSWLinkSample& sample, + const HNSWLevel0LinkParameters& params) { + FAISS_THROW_IF_NOT_MSG( + index.storage, "add_level_0_links_from_sample needs storage"); + std::unique_ptr dis( + storage_distance_computer(index.storage)); + return hnsw_add_level_0_links_from_sample( + index.hnsw, + index.ntotal, + *dis, + is_similarity_metric(index.metric_type), + sample, + params); +} + +} // namespace + +HNSWLevel0LinkStats hnsw_add_level_0_links_from_sample( + HNSW& hnsw, + size_t ntotal, + DistanceComputer& dis, + bool similarity, + const HNSWLinkSampleSearch& sample, + const HNSWLevel0LinkParameters& params) { + FAISS_THROW_IF_NOT(params.max_rounds >= 0 && params.max_links_per_sink > 0); + HNSWLevel0LinkStats stats; + if (ntotal == 0 || sample.n == 0) { + return stats; + } + std::vector labels(sample.n), exact(sample.n, -1); + sample.search(params.search_params, sample.n, nullptr, labels.data()); + for (int round = 0;; round++) { + const SinkScan scan = find_sinks(ntotal, sample, params, labels, exact); + stats.n_exact_searches += scan.n_exact_searches; + if (round == 0) { + stats.n_sinks_found = scan.sinks.size(); + } + stats.n_sinks_remaining = scan.sinks.size(); + if (scan.sinks.empty() || round == params.max_rounds) { + break; + } + size_t changed = 0; + for (size_t i = 0; i < scan.sinks.size(); i++) { + const auto [added, replaced] = link_sink( + hnsw, + dis, + static_cast(scan.sinks[i]), + scan.targets[i], + params.max_links_per_sink, + similarity); + stats.n_links_added += added; + stats.n_links_replaced += replaced; + changed += added + replaced; + } + if (changed == 0) { + break; + } + stats.n_rounds++; + + // The new links leave from the sinks, so search again only the + // vectors that arrived at a sink. + // Approximate: searches that only pass through a sink can change too. + std::vector ids; + for (idx_t i = 0; i < sample.n; i++) { + if (std::binary_search( + scan.sinks.begin(), scan.sinks.end(), labels[i])) { + ids.push_back(i); + } + } + std::vector found(ids.size()); + sample.search( + params.search_params, ids.size(), ids.data(), found.data()); + for (size_t j = 0; j < ids.size(); j++) { + if (labels[ids[j]] != found[j]) { + labels[ids[j]] = found[j]; + exact[ids[j]] = -1; + } + } + } + return stats; +} + +HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample( + idx_t n, + const float* x, + const HNSWLevel0LinkParameters& params) { + return add_level_0_links_from_sample_ex(n, x, NumericType::Float32, params); +} + +HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample_ex( + idx_t n, + const void* x, + NumericType numeric_type, + const HNSWLevel0LinkParameters& params) { + FAISS_THROW_IF_NOT_MSG( + numeric_type == NumericType::Float32 || + numeric_type == NumericType::Float16, + "add_level_0_links_from_sample_ex supports Float32 and Float16"); + const IndexHNSWLinkSample sample( + *this, n, static_cast(x), numeric_type, nullptr); + return add_level_0_links_impl(*this, sample, params); +} + +HNSWLevel0LinkStats IndexHNSW::add_level_0_links_from_sample_encoded( + idx_t n, + const uint8_t* x, + const Index* codec, + const HNSWLevel0LinkParameters& params) { + FAISS_THROW_IF_NOT_MSG( + codec, "add_level_0_links_from_sample_encoded needs a codec"); + FAISS_THROW_IF_NOT_FMT( + codec->d == d, + "codec dimension %d is not the index dimension %d", + int(codec->d), + int(d)); + const IndexHNSWLinkSample sample(*this, n, x, NumericType::Float32, codec); + return add_level_0_links_impl(*this, sample, params); +} + /************************************************************** * IndexHNSWFlatPanorama implementation **************************************************************/ @@ -1012,11 +1454,11 @@ IndexRaBitQ* make_hnsw_rabitq_storage( } // namespace IndexHNSWRaBitQ::IndexHNSWRaBitQ( - int d, + int d_in, int M, uint8_t nb_bits, MetricType metric) - : IndexHNSW(make_hnsw_rabitq_storage(d, nb_bits, metric), M) { + : IndexHNSW(make_hnsw_rabitq_storage(d_in, nb_bits, metric), M) { own_fields = true; is_trained = storage->is_trained; // 1-bit codes store plain SignBitFactors with no f_error, so there is no @@ -1233,9 +1675,8 @@ void IndexHNSW2Level::search( } omp_rethrow_if_exception(ex); -#pragma omp critical - { - hnsw_stats.combine({n1, n2, ndis, nhops}); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic({n1, n2, ndis, nhops}); } } } @@ -1390,7 +1831,6 @@ void IndexHNSWCagra::range_search( } auto run = [&]() { - const HNSW& hnsw = this->hnsw; size_t n1 = 0, n2 = 0, ndis = 0, nhops = 0; RangeSearchPartialResult pres(result); @@ -1438,9 +1878,8 @@ void IndexHNSWCagra::range_search( result->do_allocation(); pres.copy_result(); -#pragma omp critical - { - hnsw_stats.combine({n1, n2, ndis, nhops}); + if (get_search_stats_enabled()) { + hnsw_stats.combine_atomic({n1, n2, ndis, nhops}); } }; diff --git a/thirdparty/faiss/faiss/IndexHNSW.h b/thirdparty/faiss/faiss/IndexHNSW.h index ab13715b7..586430fef 100644 --- a/thirdparty/faiss/faiss/IndexHNSW.h +++ b/thirdparty/faiss/faiss/IndexHNSW.h @@ -49,6 +49,15 @@ struct IndexHNSW : Index { // used when GpuIndexCagra::copyFrom(IndexHNSWCagra*) is invoked. bool keep_max_size_level0 = false; + // When this index is the coarse quantizer of an IndexIVF, IndexIVF::train() + // calls add_level_0_links_from_sample() after it adds the centroids. The + // sample is the first min(n, level_0_link_samples_per_node * ntotal) + // training vectors, in the numeric type or encoding of the training data. + // 0 disables the call. Training does not call it when + // quantizer_trains_alone == 1 or when the quantizer is already trained. + // The index format does not store this value. + int level_0_link_samples_per_node = 3; + // See impl/VisitedTable.h. std::optional use_visited_hashset; @@ -123,6 +132,35 @@ struct IndexHNSW : Index { void link_singletons(); + /** Adds level-0 links so that the search no longer stops at "sinks": + * nodes where it stops for many vectors whose nearest node is elsewhere. + * With a small efSearch, HNSW as a coarse quantizer will overfill the + * IVF lists. Call this function after adding all centroids to this + * quantizer. Called automatically through IndexIVF::train. + */ + HNSWLevel0LinkStats add_level_0_links_from_sample( + idx_t n, + const float* x, + const HNSWLevel0LinkParameters& params = + HNSWLevel0LinkParameters()); + + /// add_level_0_links_from_sample() for Float32 or packed Float16 vectors + HNSWLevel0LinkStats add_level_0_links_from_sample_ex( + idx_t n, + const void* x, + NumericType numeric_type, + const HNSWLevel0LinkParameters& params = + HNSWLevel0LinkParameters()); + + /// add_level_0_links_from_sample() for n vectors that `codec` encoded with + /// sa_encode() + HNSWLevel0LinkStats add_level_0_links_from_sample_encoded( + idx_t n, + const uint8_t* x, + const Index* codec, + const HNSWLevel0LinkParameters& params = + HNSWLevel0LinkParameters()); + virtual void permute_entries(const idx_t* perm); DistanceComputer* get_distance_computer() const override; @@ -231,12 +269,9 @@ struct IndexHNSWRaBitQ : IndexHNSW { IndexHNSWRaBitQ& operator=(const IndexHNSWRaBitQ&) = delete; - private: - // clone_index() replaces the shallow-copied storage with a deep copy - // before returning it. Keep ordinary C++ copies from sharing ownership. - IndexHNSWRaBitQ(const IndexHNSWRaBitQ&) = default; #ifndef SWIG - friend IndexHNSW* clone_IndexHNSW(const IndexHNSW* index); + // The copy shares the storage. clone_index() replaces it with a deep copy. + IndexHNSWRaBitQ(const IndexHNSWRaBitQ&) = default; #endif }; diff --git a/thirdparty/faiss/faiss/IndexIDMap.cpp b/thirdparty/faiss/faiss/IndexIDMap.cpp index 1520f19ab..de8a80723 100644 --- a/thirdparty/faiss/faiss/IndexIDMap.cpp +++ b/thirdparty/faiss/faiss/IndexIDMap.cpp @@ -96,11 +96,18 @@ void IndexIDMapTemplate::train( component_t_to_numeric()); } +template +void IndexIDMapTemplate::train_dataset(const gpu::Dataset& dataset) { + index->train_dataset(dataset); + this->is_trained = index->is_trained; +} + template void IndexIDMapTemplate::reset() { index->reset(); id_map.clear(); this->ntotal = 0; + this->is_trained = index->is_trained; } template @@ -128,6 +135,20 @@ void IndexIDMapTemplate::add_with_ids( xids); } +template +void IndexIDMapTemplate::add_with_ids( + const gpu::Dataset& dataset, + const idx_t* xids) { + index->add_dataset(dataset); + FAISS_THROW_IF_NOT(index->ntotal >= this->ntotal); + // CAGRA may already have built the graph during train_dataset(dataset). + for (idx_t i = 0; i < index->ntotal - this->ntotal; i++) { + id_map.push_back(xids[i]); + } + this->ntotal = index->ntotal; + this->is_trained = index->is_trained; +} + template size_t IndexIDMapTemplate::sa_code_size() const { return index->sa_code_size(); @@ -335,6 +356,17 @@ void IndexIDMap2Template::add_with_ids( xids); } +template +void IndexIDMap2Template::add_with_ids( + const gpu::Dataset& dataset, + const idx_t* xids) { + idx_t prev_ntotal = this->ntotal; + IndexIDMapTemplate::add_with_ids(dataset, xids); + for (idx_t i = prev_ntotal; i < this->ntotal; i++) { + rev_map[this->id_map[i]] = i; + } +} + template void IndexIDMap2Template::add_sa_codes( idx_t n, diff --git a/thirdparty/faiss/faiss/IndexIDMap.h b/thirdparty/faiss/faiss/IndexIDMap.h index a8a4527c8..4a80b83a6 100644 --- a/thirdparty/faiss/faiss/IndexIDMap.h +++ b/thirdparty/faiss/faiss/IndexIDMap.h @@ -37,6 +37,10 @@ struct IndexIDMapTemplate : IndexT { NumericType numeric_type, const idx_t* xids) override; + /// Add a Dataset and assign one xids entry per unmapped vector, including + /// vectors already built by train_dataset(dataset). + virtual void add_with_ids(const gpu::Dataset& dataset, const idx_t* xids); + /// this will fail. Use add_with_ids void add(idx_t n, const component_t* x) override; void add_ex(idx_t n, const void* x, NumericType numeric_type) override; @@ -58,6 +62,7 @@ struct IndexIDMapTemplate : IndexT { const SearchParameters* params = nullptr) const override; void train(idx_t n, const component_t* x) override; + void train_dataset(const gpu::Dataset& dataset) override; void train_ex(idx_t n, const void* x, NumericType numeric_type) override; void reset() override; @@ -102,6 +107,8 @@ struct IndexIDMap2Template : IndexIDMapTemplate { /// make the rev_map from scratch void construct_rev_map(); + void add_with_ids(const gpu::Dataset& dataset, const idx_t* xids) override; + void add_with_ids(idx_t n, const component_t* x, const idx_t* xids) override; void add_with_ids_ex( diff --git a/thirdparty/faiss/faiss/IndexIVF.cpp b/thirdparty/faiss/faiss/IndexIVF.cpp index cda998889..21642ee83 100644 --- a/thirdparty/faiss/faiss/IndexIVF.cpp +++ b/thirdparty/faiss/faiss/IndexIVF.cpp @@ -17,16 +17,20 @@ #include #include #include +#include +#include #include #include +#include #include #include #include #include #include #include +#include namespace faiss { @@ -53,28 +57,89 @@ Level1Quantizer::~Level1Quantizer() { } } -void Level1Quantizer::train_q1( +namespace { + +void add_hnsw_quantizer_links( + IndexHNSW& hnsw, size_t n, - const float* x, + const uint8_t* x, + NumericType numeric_type, + const Index* codec, + bool verbose) { + const size_t samples = std::min( + n, + size_t(hnsw.level_0_link_samples_per_node) * size_t(hnsw.ntotal)); + const HNSWLevel0LinkStats stats = codec + ? hnsw.add_level_0_links_from_sample_encoded(samples, x, codec) + : hnsw.add_level_0_links_from_sample_ex(samples, x, numeric_type); + if (verbose) { + printf("HNSW quantizer level-0 links from %zd samples: %zd sinks found, " + "%zd remaining, %zd links added, %zd replaced\n", + samples, + stats.n_sinks_found, + stats.n_sinks_remaining, + stats.n_links_added, + stats.n_links_replaced); + } +} + +/** Trains `q1` on rows encoded by `codec` or, if codec is null, stored as + * `numeric_type`. */ +void train_q1_impl( + Level1Quantizer& q1, + size_t n, + const uint8_t* x, + NumericType numeric_type, + const Index* codec, bool verbose, MetricType metric_type) { + Index* quantizer = q1.quantizer; + const size_t nlist = q1.nlist; + const ClusteringParameters& cp = q1.cp; + Index* clustering_index = q1.clustering_index; + + auto add_quantizer_links = [&]() { + auto* hnsw = dynamic_cast(quantizer); + if (hnsw && hnsw->level_0_link_samples_per_node > 0) { + add_hnsw_quantizer_links(*hnsw, n, x, numeric_type, codec, verbose); + } + }; + + // k-means on the training rows, with `assigner` as assignment index + auto train_clustering = [&](Clustering& clus, Index& assigner) { + if (codec) { + clus.train_encoded(n, x, codec, assigner); + } else { + clus.train_ex(n, x, numeric_type, assigner); + } + }; + FAISS_THROW_IF_NOT_MSG(quantizer, "IVF quantizer must not be null"); size_t d = quantizer->d; + FAISS_THROW_IF_NOT_FMT( + !codec || static_cast(codec->d) == d, + "Codec dimension %d not the same as quantizer dimension %d", + codec ? codec->d : 0, + int(d)); if (quantizer->is_trained && (static_cast(quantizer->ntotal) == nlist)) { if (verbose) { printf("IVF quantizer does not need training.\n"); } - } else if (quantizer_trains_alone == 1) { + } else if (q1.quantizer_trains_alone == 1) { + FAISS_THROW_IF_MSG( + codec, + "encoded training is not supported when the IVF quantizer " + "trains alone"); if (verbose) { printf("IVF quantizer trains alone...\n"); } quantizer->verbose = verbose; - quantizer->train(n, x); + quantizer->train_ex(n, x, numeric_type); FAISS_THROW_IF_NOT_MSG( static_cast(quantizer->ntotal) == nlist, "nlist not consistent with quantizer size"); - } else if (quantizer_trains_alone == 0) { + } else if (q1.quantizer_trains_alone == 0) { if (verbose) { printf("Training level-1 quantizer on %zd vectors in %zdD\n", n, d); } @@ -83,6 +148,16 @@ void Level1Quantizer::train_q1( cp.use_super_kmeans && clustering_index, "cp.use_super_kmeans is incompatible with a user-provided " "clustering_index: SuperKMeans assigns with its own index"); + FAISS_THROW_IF_MSG( + cp.use_super_kmeans && codec, + "SuperKMeans does not support encoded training data"); + FAISS_THROW_IF_MSG( + cp.use_super_kmeans && + !(metric_type == METRIC_L2 || + (metric_type == METRIC_INNER_PRODUCT && + cp.spherical)), + "SuperKMeans requires L2 or spherical inner-product " + "clustering"); quantizer->reset(); if (cp.use_super_kmeans) { @@ -90,19 +165,20 @@ void Level1Quantizer::train_q1( static_cast(super_cp) = cp; SuperKMeans clus( static_cast(d), static_cast(nlist), super_cp); - clus.train(n, x); + clus.train_ex(n, x, numeric_type); quantizer->add(nlist, clus.centroids.data()); } else { Clustering clus(static_cast(d), static_cast(nlist), cp); if (clustering_index) { - clus.train(n, x, *clustering_index); + train_clustering(clus, *clustering_index); quantizer->add(nlist, clus.centroids.data()); } else { - clus.train(n, x, *quantizer); + train_clustering(clus, *quantizer); } } quantizer->is_trained = true; - } else if (quantizer_trains_alone == 2) { + add_quantizer_links(); + } else if (q1.quantizer_trains_alone == 2) { if (verbose) { printf("Training L2 quantizer on %zd vectors in %zdD%s\n", n, @@ -118,9 +194,9 @@ void Level1Quantizer::train_q1( Clustering clus(static_cast(d), static_cast(nlist), cp); if (!clustering_index) { IndexFlatL2 assigner(d); - clus.train(n, x, assigner); + train_clustering(clus, assigner); } else { - clus.train(n, x, *clustering_index); + train_clustering(clus, *clustering_index); } if (verbose) { printf("Adding centroids to quantizer\n"); @@ -132,9 +208,46 @@ void Level1Quantizer::train_q1( quantizer->train(nlist, clus.centroids.data()); } quantizer->add(nlist, clus.centroids.data()); + add_quantizer_links(); } } +} // namespace + +void Level1Quantizer::train_q1( + size_t n, + const float* x, + bool verbose, + MetricType metric_type) { + train_q1_ex(n, x, NumericType::Float32, verbose, metric_type); +} + +void Level1Quantizer::train_q1_ex( + size_t n, + const void* x, + NumericType numeric_type, + bool verbose, + MetricType metric_type) { + train_q1_impl( + *this, + n, + static_cast(x), + numeric_type, + nullptr, + verbose, + metric_type); +} + +void Level1Quantizer::train_q1_encoded( + size_t n, + const uint8_t* x, + const Index* codec, + bool verbose, + MetricType metric_type) { + train_q1_impl( + *this, n, x, NumericType::Float32, codec, verbose, metric_type); +} + size_t Level1Quantizer::coarse_code_size() const { size_t nl = nlist - 1; size_t nbyte = 0; @@ -384,7 +497,6 @@ void IndexIVF::search( #pragma omp parallel for if (nt > 1) for (idx_t slice = 0; slice < nt; slice++) { try { - IndexIVFStats local_stats; idx_t i0 = n * slice / nt; idx_t i1 = n * (slice + 1) / nt; if (i1 > i0) { @@ -403,13 +515,17 @@ void IndexIVF::search( omp_rethrow_if_exception(ex); // collect stats + IndexIVFStats search_stats; for (idx_t slice = 0; slice < nt; slice++) { - indexIVF_stats.add(stats[slice]); + search_stats.add(stats[slice]); } + indexIVF_stats.add(search_stats); } else { // handle parallelization at level below (or don't run in parallel at // all) - sub_search_func(n, x, distances, labels, &indexIVF_stats); + IndexIVFStats search_stats; + sub_search_func(n, x, distances, labels, &search_stats); + indexIVF_stats.add(search_stats); } } @@ -437,19 +553,21 @@ void IndexIVF::search_preassigned( const bool ensure_topk_full = params ? params->ensure_topk_full : false; IDSelector* sel = params ? params->sel : nullptr; + FAISS_THROW_IF_NOT_MSG( + !(sel && store_pairs), + "selector and store_pairs cannot be combined"); + const IDSelectorRange* selr = dynamic_cast(sel); if (selr) { - if (selr->assume_sorted) { + // The sorted-range shortcut bounds a section of an array-backed list, + // so an iterable list has to keep the selector and filter per entry. + if (selr->assume_sorted && !invlists->use_iterator) { sel = nullptr; // use special IDSelectorRange processing } else { selr = nullptr; // use generic processing } } - FAISS_THROW_IF_NOT_MSG( - !(sel && store_pairs), - "selector and store_pairs cannot be combined"); - FAISS_THROW_IF_NOT_MSG( !invlists->use_iterator || (cur_max_codes == 0 && store_pairs == false), @@ -502,6 +620,10 @@ void IndexIVF::search_preassigned( try { std::unique_ptr scanner( get_InvertedListScanner(store_pairs, sel, params)); + // max_codes counts codes passing the selector, so test it first. + scanner->sel_after_distance = params && + params->sel_after_distance && + cur_max_codes == unlimited_list_size; /***************************************************** * Depending on parallel_mode, there are two possible ways @@ -568,10 +690,9 @@ void IndexIVF::search_preassigned( return (size_t)0; } - scanner->set_list(key, coarse_dis_i); - nlistv++; if (invlists->use_iterator) { + scanner->set_list(key, coarse_dis_i); size_t list_size = 0; std::unique_ptr it( invlists->get_iterator(key, inverted_list_context)); @@ -586,31 +707,30 @@ void IndexIVF::search_preassigned( list_size = static_cast(list_size_max); } - InvertedLists::ScopedCodes scodes(invlists, key); - const uint8_t* codes = scodes.get(); - - std::unique_ptr sids; + std::optional sids; const idx_t* ids = nullptr; - if (!store_pairs) { - sids = std::make_unique( - invlists, key); + sids.emplace(invlists, key); ids = sids->get(); } + size_t jmin = 0; if (selr) { // IDSelectorRange // restrict search to a section of the inverted list - size_t jmin, jmax; + size_t jmax; selr->find_sorted_ids_bounds( list_size, ids, &jmin, &jmax); list_size = jmax - jmin; if (list_size == 0) { return (size_t)0; } - codes += jmin * code_size; ids += jmin; } + scanner->set_list(key, coarse_dis_i); + InvertedLists::ScopedCodes scodes(invlists, key); + const uint8_t* codes = scodes.get() + jmin * code_size; + size_t old_scan_cnt = 0; size_t old_heap_updates = 0; if (is_similarity_metric(metric_type)) { @@ -692,7 +812,7 @@ void IndexIVF::search_preassigned( scanner->set_query(x + i * d); init_result(local_dis.data(), local_idx.data()); -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (idx_t ik = 0; ik < cur_nprobe; ik++) { try { ndis += scan_one_list( @@ -734,7 +854,7 @@ void IndexIVF::search_preassigned( init_result(distances + i * k, labels + i * k); } -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (int64_t ij = 0; ij < n * cur_nprobe; ij++) { try { size_t i = ij / cur_nprobe; @@ -773,13 +893,7 @@ void IndexIVF::search_preassigned( omp_rethrow_if_exception(ex); - if (ivf_stats == nullptr) { - ivf_stats = &indexIVF_stats; - } - ivf_stats->nq += n; - ivf_stats->nlist += nlistv; - ivf_stats->ndis += ndis; - ivf_stats->nheap_updates += nheap; + add_search_stats(n, nlistv, ndis, nheap, ivf_stats); } void IndexIVF::range_search( @@ -805,23 +919,15 @@ void IndexIVF::range_search( double t0 = getmillisecs(); quantizer->search( nx, x, cur_nprobe, coarse_dis.get(), keys.get(), quantizer_params); - indexIVF_stats.quantization_time += getmillisecs() - t0; + double quantization_time = getmillisecs() - t0; t0 = getmillisecs(); invlists->prefetch_lists(keys.get(), static_cast(nx * cur_nprobe)); range_search_preassigned( - nx, - x, - radius, - keys.get(), - coarse_dis.get(), - result, - false, - params, - &indexIVF_stats); + nx, x, radius, keys.get(), coarse_dis.get(), result, false, params); - indexIVF_stats.search_time += getmillisecs() - t0; + add_search_times(quantization_time, getmillisecs() - t0); } void IndexIVF::range_search_preassigned( @@ -957,7 +1063,7 @@ void IndexIVF::range_search_preassigned( RangeQueryResult& qres = pres.new_result(i); -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (int64_t ik = 0; ik < cur_nprobe; ik++) { try { scan_list_func(i, ik, qres); @@ -969,7 +1075,7 @@ void IndexIVF::range_search_preassigned( } else if (parallel_mode == 2) { RangeQueryResult* qres = nullptr; -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (idx_t iik = 0; iik < nx * (idx_t)cur_nprobe; iik++) { try { idx_t i = iik / (idx_t)cur_nprobe; @@ -1002,12 +1108,7 @@ void IndexIVF::range_search_preassigned( omp_rethrow_if_exception(ex); - if (stats == nullptr) { - stats = &indexIVF_stats; - } - stats->nq += nx; - stats->nlist += nlistv; - stats->ndis += ndis; + add_search_stats(nx, nlistv, ndis, 0, stats); } void IndexIVF::search1( @@ -1030,7 +1131,7 @@ void IndexIVF::search1( double t0 = getmillisecs(); quantizer->search( nx, x, cur_nprobe, coarse_dis.get(), keys.get(), quantizer_params); - indexIVF_stats.quantization_time += getmillisecs() - t0; + double quantization_time = getmillisecs() - t0; t0 = getmillisecs(); invlists->prefetch_lists(keys.get(), static_cast(nx * cur_nprobe)); @@ -1058,7 +1159,7 @@ void IndexIVF::search1( scanner->scan_codes(list_size, scodes.get(), ids.get(), handler); } - indexIVF_stats.search_time += getmillisecs() - t0; + add_search_times(quantization_time, getmillisecs() - t0); } InvertedListScanner* IndexIVF::get_InvertedListScanner( @@ -1160,7 +1261,13 @@ void IndexIVF::search_and_reconstruct( std::unique_ptr idx(new idx_t[n * cur_nprobe]); std::unique_ptr coarse_dis(new float[n * cur_nprobe]); - quantizer->search(n, x, cur_nprobe, coarse_dis.get(), idx.get()); + quantizer->search( + n, + x, + cur_nprobe, + coarse_dis.get(), + idx.get(), + params ? params->quantizer_params : nullptr); invlists->prefetch_lists(idx.get(), static_cast(n * cur_nprobe)); @@ -1209,6 +1316,9 @@ void IndexIVF::search_and_return_codes( params = dynamic_cast(params_in); FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type"); } + FAISS_THROW_IF_MSG( + invlists->code_size == InvertedLists::INVALID_CODE_SIZE, + "search_and_return_codes not supported for these inverted lists"); const size_t cur_nprobe = std::min(nlist, params ? params->nprobe : this->nprobe); FAISS_THROW_IF_NOT(cur_nprobe > 0); @@ -1216,7 +1326,13 @@ void IndexIVF::search_and_return_codes( std::unique_ptr idx(new idx_t[n * cur_nprobe]); std::unique_ptr coarse_dis(new float[n * cur_nprobe]); - quantizer->search(n, x, cur_nprobe, coarse_dis.get(), idx.get()); + quantizer->search( + n, + x, + cur_nprobe, + coarse_dis.get(), + idx.get(), + params ? params->quantizer_params : nullptr); invlists->prefetch_lists(idx.get(), static_cast(n * cur_nprobe)); @@ -1308,6 +1424,125 @@ void IndexIVF::update_vectors(int n, const idx_t* new_ids, const float* x) { invlists, n, new_ids, assign.data(), flat_codes.data()); } +namespace { + +/** Trains the encoder of `ivf` on training rows that are not fp32. + * + * Only the train_encoder_num_vectors() rows sampled for the encoder are + * widened to fp32. `decode_rows(n, rows, out)` widens n consecutive rows of + * `row_size` bytes. + */ +template +void train_encoder_on_encoded_rows( + IndexIVF& ivf, + idx_t n, + const uint8_t* x, + size_t row_size, + const DecodeRows& decode_rows) { + const size_t d = ivf.d; + idx_t max_nt = ivf.train_encoder_num_vectors(); + if (max_nt <= 0 || n <= max_nt) { + max_nt = n; + } + + std::vector decoded(static_cast(max_nt) * d); + if (max_nt == n) { + decode_rows(n, x, decoded.data()); + } else { + FAISS_THROW_IF_NOT_FMT( + n <= static_cast(std::numeric_limits::max()), + "Dataset too large (%" PRId64 ") for standard subsampling", + n); + if (ivf.verbose) { + printf(" Input training set too big (max size is %" PRId64 + "), sampling %" PRId64 " / %" PRId64 " vectors\n", + max_nt, + max_nt, + n); + } + std::vector subset(static_cast(n)); + rand_perm(subset.data(), n, 1234); + for (idx_t i = 0; i < max_nt; ++i) { + decode_rows( + 1, + x + static_cast(subset[i]) * row_size, + decoded.data() + static_cast(i) * d); + } + } + n = max_nt; + + if (ivf.by_residual) { + FAISS_THROW_IF_NOT_MSG(ivf.quantizer, "IVF quantizer must not be null"); + std::vector assign(n); + ivf.quantizer->assign(n, decoded.data(), assign.data()); + + std::vector residuals(static_cast(n) * d); + ivf.quantizer->compute_residual_n( + n, decoded.data(), residuals.data(), assign.data()); + + ivf.train_encoder(n, residuals.data(), assign.data()); + } else { + ivf.train_encoder(n, decoded.data(), nullptr); + } +} + +} // namespace + +void IndexIVF::train_ex(idx_t n, const void* x, NumericType numeric_type) { + if (numeric_type != NumericType::Float16) { + Index::train_ex(n, x, numeric_type); + return; + } + FAISS_THROW_IF_NOT_MSG(x, "training data must not be null"); + if (verbose) { + printf("Training level-1 quantizer on fp16 data\n"); + } + + train_q1_ex(n, x, numeric_type, verbose, metric_type); + + if (verbose) { + printf("Training IVF residual\n"); + } + + const size_t dim = d; + train_encoder_on_encoded_rows( + *this, + n, + static_cast(x), + sizeof(uint16_t) * dim, + [dim](idx_t ni, const uint8_t* rows, float* out) { + fp16_to_fp32( + ni * dim, reinterpret_cast(rows), out); + }); + + is_trained = true; +} + +void IndexIVF::train_encoded(idx_t n, const uint8_t* x, const Index* codec) { + FAISS_THROW_IF_NOT_MSG(codec, "encoded training requires a codec"); + FAISS_THROW_IF_NOT_MSG(x, "encoded training data must not be null"); + if (verbose) { + printf("Training level-1 quantizer\n"); + } + + train_q1_encoded(n, x, codec, verbose, metric_type); + + if (verbose) { + printf("Training IVF residual\n"); + } + + train_encoder_on_encoded_rows( + *this, + n, + x, + codec->sa_code_size(), + [codec](idx_t ni, const uint8_t* rows, float* out) { + codec->sa_decode(ni, rows, out); + }); + + is_trained = true; +} + void IndexIVF::train(idx_t n, const float* x) { if (verbose) { printf("Training level-1 quantizer\n"); @@ -1438,16 +1673,44 @@ void IndexIVFStats::reset() { } void IndexIVFStats::add(const IndexIVFStats& other) { - nq += other.nq; - nlist += other.nlist; - ndis += other.ndis; - nheap_updates += other.nheap_updates; - quantization_time += other.quantization_time; - search_time += other.search_time; + detail::atomic_fetch_add_relaxed(nq, other.nq); + detail::atomic_fetch_add_relaxed(nlist, other.nlist); + detail::atomic_fetch_add_relaxed(ndis, other.ndis); + detail::atomic_fetch_add_relaxed(nheap_updates, other.nheap_updates); + detail::atomic_fetch_add_relaxed( + quantization_time, other.quantization_time); + detail::atomic_fetch_add_relaxed(search_time, other.search_time); } IndexIVFStats indexIVF_stats; +void add_search_stats( + size_t nq, + size_t nlist, + size_t ndis, + size_t nheap_updates, + IndexIVFStats* stats) { + if (stats == nullptr) { + stats = &indexIVF_stats; + } + detail::atomic_fetch_add_relaxed(stats->nq, nq); + detail::atomic_fetch_add_relaxed(stats->nlist, nlist); + detail::atomic_fetch_add_relaxed(stats->ndis, ndis); + detail::atomic_fetch_add_relaxed(stats->nheap_updates, nheap_updates); +} + +void add_search_times( + double quantization_time, + double search_time, + IndexIVFStats* stats) { + if (stats == nullptr) { + stats = &indexIVF_stats; + } + detail::atomic_fetch_add_relaxed( + stats->quantization_time, quantization_time); + detail::atomic_fetch_add_relaxed(stats->search_time, search_time); +} + /************************************************************************* * InvertedListScanner *************************************************************************/ @@ -1462,6 +1725,15 @@ size_t InvertedListScanner::scan_codes( return run_scan_codes(*this, list_size, codes, ids, handler); } +void InvertedListScanner::distances_to_codes( + size_t n, + const uint8_t* codes, + float* distances) const { + for (size_t j = 0; j < n; j++) { + distances[j] = distance_to_code(codes + j * code_size); + } +} + void InvertedListScanner::set_list(idx_t list_no_in, float /* coarse_dis */) { this->list_no = list_no_in; } @@ -1498,6 +1770,9 @@ size_t InvertedListScanner::iterate_codes( if (!keep_max) { for (; it->is_available(); it->next()) { auto id_and_codes = it->get_id_and_codes(); + if (sel && !sel->is_member(id_and_codes.first)) { + continue; + } float dis = distance_to_code(id_and_codes.second); if (has_cb) { it->on_distance_computed(id_and_codes.first, dis); @@ -1514,6 +1789,9 @@ size_t InvertedListScanner::iterate_codes( } else { for (; it->is_available(); it->next()) { auto id_and_codes = it->get_id_and_codes(); + if (sel && !sel->is_member(id_and_codes.first)) { + continue; + } float dis = distance_to_code(id_and_codes.second); if (has_cb) { it->on_distance_computed(id_and_codes.first, dis); @@ -1561,6 +1839,9 @@ void InvertedListScanner::iterate_codes_range( list_size = 0; for (; it->is_available(); it->next()) { auto id_and_codes = it->get_id_and_codes(); + if (sel && !sel->is_member(id_and_codes.first)) { + continue; + } float dis = distance_to_code(id_and_codes.second); bool keep = !keep_max ? dis < radius diff --git a/thirdparty/faiss/faiss/IndexIVF.h b/thirdparty/faiss/faiss/IndexIVF.h index a58ecf765..ce60bca3a 100644 --- a/thirdparty/faiss/faiss/IndexIVF.h +++ b/thirdparty/faiss/faiss/IndexIVF.h @@ -46,13 +46,41 @@ struct Level1Quantizer { /// to override index used during clustering Index* clustering_index = nullptr; - /// Trains the quantizer and calls train_residual to train sub-quantizers + /// Trains the level-1 quantizer from fp32 vectors. void train_q1( size_t n, const float* x, bool verbose, MetricType metric_type); + /** Trains the level-1 quantizer from Float32 or packed Float16 vectors. + * + * Float16 runs k-means natively on the fp16 rows (see + * Clustering::train_ex). With quantizer_trains_alone == 1 the data is + * passed on to quantizer->train_ex(). SuperKMeans supports raw Float32 + * and Float16 input, but not vectors decoded through a codec. + */ + void train_q1_ex( + size_t n, + const void* x, + NumericType numeric_type, + bool verbose, + MetricType metric_type); + + /** Trains the level-1 quantizer from vectors encoded by `codec`. + * + * The codec must remain alive for the duration of this call and decode + * each input row to `quantizer->d` floats. Encoded training is supported + * when clustering trains the quantizer (quantizer_trains_alone 0 or 2) + * without SuperKMeans. + */ + void train_q1_encoded( + size_t n, + const uint8_t* x, + const Index* codec, + bool verbose, + MetricType metric_type); + /// compute the number of bytes required to store list ids size_t coarse_code_size() const; void encode_listno(idx_t list_no, uint8_t* code) const; @@ -87,6 +115,20 @@ struct SearchParametersIVF : SearchParameters { /// uses implementation 10 for this option. size_t max_empty_result_buckets = 0; + /// k-NN only: test the IDSelector only on codes whose distance would enter + /// the result heap. Faster when the selector costs more than a distance + /// and accepts most codes; slower when it rejects most codes. + /// + /// is_member must return the same answer for an id during the whole + /// search. Then the results are the same with or without this option, so + /// a scan that does not implement it ignores it. With it, + /// IndexIVFStats::ndis counts every scanned code. + /// + /// Only the batched IVF-SQ scan implements it, and only with unlimited + /// max_codes. The uniform, TurboQuant and 0-bit SQ types and the other + /// IVF indexes test the selector first. + bool sel_after_distance = false; + SearchParameters* quantizer_params = nullptr; /// context object to pass to InvertedLists void* inverted_list_context = nullptr; @@ -236,6 +278,23 @@ struct IndexIVF : Index, IndexIVFInterface { /// Trains the quantizer and calls train_encoder to train sub-quantizers void train(idx_t n, const float* x) override; + /** Train from vectors decoded on demand by `codec`. + * + * Coarse quantizer training decodes in bounded batches. Subclasses with a + * trainable encoder decode at most train_encoder_num_vectors() rows into + * fp32; IndexIVFFlat overrides this method and needs no fp32 corpus buffer. + */ + virtual void train_encoded(idx_t n, const uint8_t* x, const Index* codec); + + /** Supports Float32 and packed IEEE binary16 (Float16) inputs. + * + * Float16 trains natively without a codec: the coarse quantizer runs + * fp16 k-means (Clustering::train_ex) and only the + * train_encoder_num_vectors() rows sampled for the encoder are widened + * to fp32. IndexIVFFlat overrides this and widens no rows at all. + */ + void train_ex(idx_t n, const void* x, NumericType numeric_type) override; + /// Calls add_with_ids with NULL ids void add(idx_t n, const float* x) override; @@ -411,7 +470,7 @@ struct IndexIVF : Index, IndexIVFInterface { * include the list ids in the code (in this case add * ceil(log8(nlist)) to the code size) */ - void search_and_return_codes( + virtual void search_and_return_codes( idx_t n, const float* x, idx_t k, @@ -504,6 +563,9 @@ struct InvertedListScanner { /// search in this subset of ids const IDSelector* sel; + /// see SearchParametersIVF::sel_after_distance + bool sel_after_distance = false; + InvertedListScanner( bool store_pairs_in = false, const IDSelector* sel_in = nullptr) @@ -521,6 +583,13 @@ struct InvertedListScanner { /// compute a single query-to-code distance virtual float distance_to_code(const uint8_t* code) const = 0; + /** compute the distances to n consecutive codes of code_size bytes. A + * distance can differ in the last bits from distance_to_code. */ + virtual void distances_to_codes( + size_t n, + const uint8_t* codes, + float* distances) const; + /** scan a set of codes, compute distances to current query, and * update heap of results if necessary. Default implementation * calls distance_to_code. @@ -592,12 +661,31 @@ struct IndexIVFStats { reset(); } void reset(); + /** Adds the counters of other to this one. The adds are atomic, so + * several threads can add to the same IndexIVFStats at once. This is + * what makes concurrent searches safe on the global indexIVF_stats. */ void add(const IndexIVFStats& other); }; // global var that collects them all FAISS_API extern IndexIVFStats indexIVF_stats; +/** Adds the counters of one search call to stats, or to indexIVF_stats if + * stats is null. The adds are atomic, as in IndexIVFStats::add. */ +void add_search_stats( + size_t nq, + size_t nlist, + size_t ndis, + size_t nheap_updates = 0, + IndexIVFStats* stats = nullptr); + +/** Adds the times of one search call to stats, or to indexIVF_stats if + * stats is null. The adds are atomic, as in IndexIVFStats::add. */ +void add_search_times( + double quantization_time, + double search_time, + IndexIVFStats* stats = nullptr); + } // namespace faiss #endif diff --git a/thirdparty/faiss/faiss/IndexIVFFastScan.cpp b/thirdparty/faiss/faiss/IndexIVFFastScan.cpp index e40d7e717..f3f70f1ff 100644 --- a/thirdparty/faiss/faiss/IndexIVFFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexIVFFastScan.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -646,8 +647,23 @@ void IndexIVFFastScan::search_dispatch_implem( search_implem_14( n, x, k, distances, labels, cq, impl, context, params); } else { + // Size each thread's LUT here, on the calling thread: a + // heap-profiler sample taken on an OpenMP worker unwinds + // through libomp, which is very slow on aarch64. The tables + // keep their capacity, so smaller slices do not reallocate. + std::vector> thread_dis_tables( + omp_get_max_threads()); + const size_t max_slice_n = (n + nslice - 1) / nslice; + const size_t lut_per_query = + ksub * M2 * (lookup_table_is_3d() ? cur_nprobe : 1); + for (auto& t : thread_dis_tables) { + t.keep_capacity = true; + t.resize(max_slice_n * lut_per_query); + } #pragma omp parallel for reduction(+ : ndis, nlist_visited) for (int slice = 0; slice < nslice; slice++) { + AlignedTable* dis_tables_buf = + &thread_dis_tables.at(omp_get_thread_num()); idx_t i0 = n * slice / nslice; idx_t i1 = n * (slice + 1) / nslice; float* dis_i = distances + i0 * k; @@ -663,6 +679,9 @@ void IndexIVFFastScan::search_dispatch_implem( if (thread_context.query_factors != nullptr) { thread_context.query_factors += i0 * cur_nprobe; } + if (thread_context.rotated_q != nullptr) { + thread_context.rotated_q += i0 * cur_nprobe * d; + } auto scanner = make_knn_scanner( is_max, @@ -684,7 +703,8 @@ void IndexIVFFastScan::search_dispatch_implem( &nlist_visited, thread_context, params, - *scanner); + *scanner, + dis_tables_buf); } else { search_implem_10( i1 - i0, @@ -696,14 +716,13 @@ void IndexIVFFastScan::search_dispatch_implem( &nlist_visited, thread_context, params, - *scanner); + *scanner, + dis_tables_buf); } } } } - indexIVF_stats.nq += n; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nlist += nlist_visited; + add_search_stats(n, nlist_visited, ndis); } else { FAISS_THROW_FMT("implem %d does not exist", implem); } @@ -848,9 +867,7 @@ void IndexIVFFastScan::range_search_dispatch_implem( } } - indexIVF_stats.nq += n; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nlist += nlist_visited; + add_search_stats(n, nlist_visited, ndis); } template @@ -919,9 +936,7 @@ void IndexIVFFastScan::search_implem_1( } heap_reorder(k, heap_dis, heap_ids); } - indexIVF_stats.nq += n; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nlist += nlist_visited; + add_search_stats(n, nlist_visited, ndis); } template @@ -1005,9 +1020,7 @@ void IndexIVFFastScan::search_implem_2( } } } - indexIVF_stats.nq += n; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nlist += nlist_visited; + add_search_stats(n, nlist_visited, ndis); } void IndexIVFFastScan::search_implem_10( @@ -1020,9 +1033,12 @@ void IndexIVFFastScan::search_implem_10( size_t* nlist_out, const FastScanDistancePostProcessing& context, const IVFSearchParameters* params, - FastScanCodeScanner& scanner) const { + FastScanCodeScanner& scanner, + AlignedTable* dis_tables_buf) const { size_t dim12 = ksub * M2; - AlignedTable dis_tables; + AlignedTable local_dis_tables; + AlignedTable& dis_tables = + dis_tables_buf ? *dis_tables_buf : local_dis_tables; AlignedTable biases; std::unique_ptr normalizers(new float[2 * n]); @@ -1060,6 +1076,7 @@ void IndexIVFFastScan::search_implem_10( // Allocate probe_map once and reuse it std::vector probe_map; probe_map.reserve(1); + const size_t block_stride = get_block_stride(); for (idx_t i = 0; i < n; i++) { const uint8_t* LUT = nullptr; @@ -1134,7 +1151,7 @@ void IndexIVFFastScan::search_implem_10( codes.get(), LUT, context.pq2x4_scale, - get_block_stride()); + block_stride); ndis += ls; nlist_visited++; @@ -1172,14 +1189,17 @@ void IndexIVFFastScan::search_implem_12( size_t* nlist_out, const FastScanDistancePostProcessing& context, const IVFSearchParameters* /* params */, - FastScanCodeScanner& scanner) const { + FastScanCodeScanner& scanner, + AlignedTable* dis_tables_buf) const { if (n == 0) { // does not work well with reservoir return; } FAISS_THROW_IF_NOT(bbs == 32); size_t dim12 = ksub * M2; - AlignedTable dis_tables; + AlignedTable local_dis_tables; + AlignedTable& dis_tables = + dis_tables_buf ? *dis_tables_buf : local_dis_tables; AlignedTable biases; std::unique_ptr normalizers(new float[2 * n]); @@ -1196,6 +1216,7 @@ void IndexIVFFastScan::search_implem_12( size_t cur_nprobe = cq.nprobe; std::vector qcs; + qcs.reserve(n * cur_nprobe); { size_t ij = 0; for (idx_t i = 0; i < n; i++) { @@ -1226,6 +1247,9 @@ void IndexIVFFastScan::search_implem_12( // Allocate vectors once and reuse them std::vector probe_map; probe_map.reserve(actual_qbs2); + std::vector q_map(actual_qbs2), lut_entries(actual_qbs2); + AlignedTable LUT(actual_qbs2 * dim12); + const size_t block_stride = get_block_stride(); size_t i0 = 0; uint64_t t_copy_pack = 0, t_scan = 0; @@ -1252,8 +1276,6 @@ void IndexIVFFastScan::search_implem_12( // re-organize LUTs and biases into the right order int nc = static_cast(i1 - i0); - std::vector q_map(nc), lut_entries(nc); - AlignedTable LUT(nc * dim12); memset(LUT.get(), -1, nc * dim12); int qbs_for_list = pq4_preferred_qbs(nc); @@ -1303,7 +1325,7 @@ void IndexIVFFastScan::search_implem_12( codes.get(), LUT.get(), context.pq2x4_scale, - get_block_stride()); + block_stride); // prepare for next loop i0 = i1; } @@ -1351,6 +1373,7 @@ void IndexIVFFastScan::search_implem_14( size_t cur_nprobe = cq.nprobe; std::vector qcs; + qcs.reserve(n * cur_nprobe); { size_t ij = 0; for (idx_t i = 0; i < n; i++) { @@ -1461,8 +1484,11 @@ void IndexIVFFastScan::search_implem_14( // Allocate probe_map once per thread and reuse it std::vector probe_map; probe_map.reserve(actual_qbs2); + std::vector q_map(actual_qbs2), lut_entries(actual_qbs2); + AlignedTable LUT(actual_qbs2 * dim12); + const size_t block_stride = get_block_stride(); -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (idx_t cluster = 0; cluster < static_cast(ses.size()); cluster++) { size_t i0 = ses[cluster].start; @@ -1474,8 +1500,6 @@ void IndexIVFFastScan::search_implem_14( // re-organize LUTs and biases into the right order int nc = static_cast(i1 - i0); - std::vector q_map(nc), lut_entries(nc); - AlignedTable LUT(nc * dim12); memset(LUT.get(), -1, nc * dim12); int qbs_for_list = pq4_preferred_qbs(nc); @@ -1526,7 +1550,7 @@ void IndexIVFFastScan::search_implem_14( codes.get(), LUT.get(), context.pq2x4_scale, - get_block_stride()); + block_stride); } // labels is in-place for HeapHC @@ -1565,9 +1589,7 @@ void IndexIVFFastScan::search_implem_14( } } - indexIVF_stats.nq += n; - indexIVF_stats.ndis += ndis; - indexIVF_stats.nlist += nlist_visited; + add_search_stats(n, nlist_visited, ndis); } void IndexIVFFastScan::reconstruct_from_offset( diff --git a/thirdparty/faiss/faiss/IndexIVFFastScan.h b/thirdparty/faiss/faiss/IndexIVFFastScan.h index 7f052f7d6..2d6d3610d 100644 --- a/thirdparty/faiss/faiss/IndexIVFFastScan.h +++ b/thirdparty/faiss/faiss/IndexIVFFastScan.h @@ -303,7 +303,8 @@ struct IndexIVFFastScan : IndexIVF { size_t* nlist_out, const FastScanDistancePostProcessing& context, const IVFSearchParameters* params, - FastScanCodeScanner& scanner) const; + FastScanCodeScanner& scanner, + AlignedTable* dis_tables_buf = nullptr) const; void search_implem_12( idx_t n, @@ -314,7 +315,8 @@ struct IndexIVFFastScan : IndexIVF { size_t* nlist_out, const FastScanDistancePostProcessing& context, const IVFSearchParameters* params, - FastScanCodeScanner& scanner) const; + FastScanCodeScanner& scanner, + AlignedTable* dis_tables_buf = nullptr) const; // implem 14 is multithreaded internally across nprobes and queries void search_implem_14( diff --git a/thirdparty/faiss/faiss/IndexIVFFlat.cpp b/thirdparty/faiss/faiss/IndexIVFFlat.cpp index ea37e6d0d..93992d00e 100644 --- a/thirdparty/faiss/faiss/IndexIVFFlat.cpp +++ b/thirdparty/faiss/faiss/IndexIVFFlat.cpp @@ -57,6 +57,25 @@ IndexIVFFlat::IndexIVFFlat() { by_residual = false; } +void IndexIVFFlat::train_encoded( + idx_t n, + const uint8_t* x, + const Index* codec) { + FAISS_THROW_IF_NOT_MSG(codec, "encoded training requires a codec"); + train_q1_encoded(n, x, codec, verbose, metric_type); + is_trained = true; +} + +void IndexIVFFlat::train_ex(idx_t n, const void* x, NumericType numeric_type) { + if (numeric_type != NumericType::Float16) { + IndexIVF::train_ex(n, x, numeric_type); + return; + } + FAISS_THROW_IF_NOT_MSG(x, "training data must not be null"); + train_q1_ex(n, x, numeric_type, verbose, metric_type); + is_trained = true; +} + void IndexIVFFlat::add_core( idx_t n, const float* x, @@ -186,6 +205,20 @@ IndexIVFFlatDedup::IndexIVFFlatDedup( metric_type_in, own_invlists_in) {} +void IndexIVFFlatDedup::train_encoded(idx_t, const uint8_t*, const Index*) { + FAISS_THROW_MSG("encoded training is not supported by IndexIVFFlatDedup"); +} + +void IndexIVFFlatDedup::train_ex( + idx_t n, + const void* x, + NumericType numeric_type) { + FAISS_THROW_IF_NOT_MSG( + numeric_type == NumericType::Float32, + "only fp32 training is supported by IndexIVFFlatDedup"); + train(n, static_cast(x)); +} + void IndexIVFFlatDedup::train(idx_t n, const float* x) { std::unordered_map map; std::unique_ptr x2(new float[n * d]); diff --git a/thirdparty/faiss/faiss/IndexIVFFlat.h b/thirdparty/faiss/faiss/IndexIVFFlat.h index 1665a06e6..5a07fc1c8 100644 --- a/thirdparty/faiss/faiss/IndexIVFFlat.h +++ b/thirdparty/faiss/faiss/IndexIVFFlat.h @@ -29,6 +29,16 @@ struct IndexIVFFlat : IndexIVF { MetricType = METRIC_L2, bool own_invlists = true); + /** Train the coarse quantizer from vectors decoded on demand by `codec`. + * + * IndexIVFFlat has no trainable residual encoder, so this avoids a + * corpus-sized decoded buffer. The codec must remain alive for this call. + */ + void train_encoded(idx_t n, const uint8_t* x, const Index* codec) override; + + /// Float16 trains only the coarse quantizer, natively on the fp16 rows. + void train_ex(idx_t n, const void* x, NumericType numeric_type) override; + void add_core( idx_t n, const float* x, @@ -68,10 +78,10 @@ struct IVFFlatScanner : InvertedListScanner { using C = typename VectorDistance::C; IVFFlatScanner( - const VectorDistance& vd, - bool store_pairs, - const IDSelector* sel) - : InvertedListScanner(store_pairs, sel), vd(vd) { + const VectorDistance& vd_in, + bool store_pairs_in, + const IDSelector* sel_in) + : InvertedListScanner(store_pairs_in, sel_in), vd(vd_in) { keep_max = vd.is_similarity; code_size = vd.d * sizeof(float); } @@ -81,8 +91,8 @@ struct IVFFlatScanner : InvertedListScanner { this->xi = query; } - void set_list(idx_t list_no, float /* coarse_dis */) override { - this->list_no = list_no; + void set_list(idx_t list_no_in, float /* coarse_dis */) override { + list_no = list_no_in; } float distance_to_code(const uint8_t* code) const final; @@ -110,6 +120,12 @@ struct IndexIVFFlatDedup : IndexIVFFlat { /// also dedups the training set void train(idx_t n, const float* x) override; + /// Encoded training cannot preserve the byte-exact deduplication contract. + void train_encoded(idx_t n, const uint8_t* x, const Index* codec) override; + + /// Non-fp32 input is rejected for the same reason as train_encoded. + void train_ex(idx_t n, const void* x, NumericType numeric_type) override; + /// implemented for all IndexIVF* classes void add_with_ids(idx_t n, const float* x, const idx_t* xids) override; diff --git a/thirdparty/faiss/faiss/IndexIVFPQFastScan.cpp b/thirdparty/faiss/faiss/IndexIVFPQFastScan.cpp index 412be73e4..be892436f 100644 --- a/thirdparty/faiss/faiss/IndexIVFPQFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexIVFPQFastScan.cpp @@ -334,6 +334,7 @@ struct IVFPQFastScanScanner : InvertedListScanner { const IDSelector* sel_in) : InvertedListScanner(store_pairs_in, sel_in), index(index_in) { this->keep_max = is_similarity_metric(index_in.metric_type); + this->code_size = index_in.code_size; residual.resize(index_in.d); } @@ -367,7 +368,7 @@ struct IVFPQFastScanScanner : InvertedListScanner { // implemented for all vector distances, although only L2 and IP are // supported by FastScan with_VectorDistance(pq.dsub, index.metric_type, 0.0, [&](auto vd) { - int m; + size_t m; for (m = 0; m + 1 < pq.M; m += 2) { const float* cent; uint8_t c = *code++; diff --git a/thirdparty/faiss/faiss/IndexIVFRaBitQ.cpp b/thirdparty/faiss/faiss/IndexIVFRaBitQ.cpp index 0afaf7e67..d9cd76d6b 100644 --- a/thirdparty/faiss/faiss/IndexIVFRaBitQ.cpp +++ b/thirdparty/faiss/faiss/IndexIVFRaBitQ.cpp @@ -162,8 +162,7 @@ struct RaBitInvertedListScanner : InvertedListScanner { std::vector query_vector; std::unique_ptr dc; - RaBitQDistanceComputer* rabitq_dc = - nullptr; // For multi-bit adaptive filtering + RaBitQDistanceComputer* rabitq_dc = nullptr; uint8_t qb = 0; bool centered = false; @@ -205,30 +204,15 @@ struct RaBitInvertedListScanner : InvertedListScanner { return dc->distance_to_code(code); } - // redefiniing the scan_codes allows to inline the distance_to_code - // (this is unlikely to matter because it contains a virtual function call) - size_t scan_codes_1bit( - size_t list_size, - const uint8_t* codes, - const idx_t* ids, - ResultHandler& handler) const { - return run_scan_codes(*this, list_size, codes, ids, handler); - } - - /// Override scan_codes to implement adaptive filtering for multi-bit codes size_t scan_codes( size_t list_size, const uint8_t* codes, const idx_t* ids, ResultHandler& handler) const override { - size_t ex_bits = ivf_rabitq.rabitq.nb_bits - 1; - - // For 1-bit codes, use default implementation - if (ex_bits == 0 || rabitq_dc == nullptr) { - return scan_codes_1bit(list_size, codes, ids, handler); + if (qb == 0 && ivf_rabitq.rabitq.nb_bits == 1) { + return run_scan_codes(*this, list_size, codes, ids, handler); } - // Multi-bit: Two-stage search with adaptive filtering return rabitq_dc->scan_codes_multibit( list_size, codes, @@ -247,7 +231,6 @@ struct RaBitInvertedListScanner : InvertedListScanner { if (!dc) { dc.reset(ivf_rabitq.rabitq.get_distance_computer( qb, nullptr, centered)); - // Try to cast to RaBitQDistanceComputer for multi-bit support rabitq_dc = dynamic_cast(dc.get()); FAISS_THROW_IF_NOT(rabitq_dc); } diff --git a/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.cpp b/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.cpp index 8b6ba6207..450f305a8 100644 --- a/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.cpp @@ -19,9 +19,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -33,6 +35,7 @@ using rabitq_utils::QueryFactorsData; using rabitq_utils::round_nonnegative_to_uint16; using rabitq_utils::SignBitFactors; using rabitq_utils::SignBitFactorsWithError; +using rabitq_utils::write_subset_sum_lut; inline size_t roundup(size_t a, size_t b) { return (a + b - 1) / b * b; @@ -366,32 +369,6 @@ bool IndexIVFRaBitQFastScan::lookup_table_is_3d() const { return true; } -// out[code] = base + sum of v_i for each set bit in code. -inline void write_subset_sum_lut( - float* out, - float base, - float v0, - float v1, - float v2, - float v3) { - out[0] = base; - out[1] = base + v0; - out[2] = base + v1; - out[3] = base + v0 + v1; - out[4] = base + v2; - out[5] = base + v0 + v2; - out[6] = base + v1 + v2; - out[7] = base + v0 + v1 + v2; - out[8] = base + v3; - out[9] = base + v0 + v3; - out[10] = base + v1 + v3; - out[11] = base + v0 + v1 + v3; - out[12] = base + v2 + v3; - out[13] = base + v0 + v2 + v3; - out[14] = base + v1 + v2 + v3; - out[15] = base + v0 + v1 + v2 + v3; -} - // Computes lookup table for residual vectors in RaBitQ FastScan format void IndexIVFRaBitQFastScan::compute_residual_LUT( const float* query, @@ -401,12 +378,14 @@ void IndexIVFRaBitQFastScan::compute_residual_LUT( uint8_t qb_param, bool centered_param, std::vector& rotated_q, - std::vector& centroid_buf) const { + std::vector& centroid_buf, + std::vector& rotated_qq, + float* rotated_q_out) const { const size_t d_val = static_cast(d); FAISS_THROW_IF_NOT(d_val > 0); rotated_q.resize(d_val); centroid_buf.resize(d_val); - std::vector rotated_qq(d_val); + rotated_qq.resize(d_val); // Compute residual quantizer->reconstruct(centroid_id, centroid_buf.data()); @@ -414,7 +393,9 @@ void IndexIVFRaBitQFastScan::compute_residual_LUT( rotated_q[i] = query[i] - centroid_buf[i]; } - // Compute query factors using shared utility + // Keep the caller's rotated_q capacity across the assignment below, so a + // reused QueryFactorsData does not reallocate on every call. + std::vector rotated_q_keep = std::move(query_factors.rotated_q); query_factors = rabitq_utils::compute_query_factors( rotated_q.data(), d_val, @@ -432,7 +413,12 @@ void IndexIVFRaBitQFastScan::compute_residual_LUT( } if (rabitq.nb_bits > 1) { - query_factors.rotated_q = rotated_q; + if (rotated_q_out != nullptr) { + std::copy(rotated_q.begin(), rotated_q.end(), rotated_q_out); + } else { + rotated_q_keep.assign(rotated_q.begin(), rotated_q.end()); + query_factors.rotated_q = std::move(rotated_q_keep); + } } // Build LUT using branchless subset-sum construction @@ -528,8 +514,15 @@ void IndexIVFRaBitQFastScan::search_preassigned( } std::vector query_factors_storage(n * cur_nprobe); + // One block for the multi-bit rotated queries, allocated here rather than + // per (query, probe) on OpenMP workers: under jemalloc heap profiling on + // aarch64, worker-thread allocations are very expensive to sample. + // Left uninitialised; every slot read is written by compute_LUT first. + std::unique_ptr rotated_q_storage( + rabitq.nb_bits > 1 ? new float[n * cur_nprobe * d] : nullptr); FastScanDistancePostProcessing context; context.query_factors = query_factors_storage.data(); + context.rotated_q = rotated_q_storage.get(); context.nprobe = cur_nprobe; context.qb = used_qb; context.centered = used_centered; @@ -570,6 +563,7 @@ void IndexIVFRaBitQFastScan::compute_LUT( { std::vector rotated_q(d); std::vector centroid_buf(d); + std::vector rotated_qq(d); #pragma omp for for (idx_t ij = 0; ij < static_cast(n * cq_nprobe); ij++) { @@ -587,7 +581,10 @@ void IndexIVFRaBitQFastScan::compute_LUT( used_qb, used_centered, rotated_q, - centroid_buf); + centroid_buf, + rotated_qq, + context.rotated_q ? context.rotated_q + ij * d + : nullptr); if (context.query_factors != nullptr) { context.query_factors[ij] = std::move(query_factors_data); @@ -628,10 +625,12 @@ void IndexIVFRaBitQFastScan::compute_LUT_uint8( AlignedTable lut_float(cur_nprobe * dim12); std::vector rotated_q(d); std::vector centroid_buf(d); + std::vector rotated_qq(d); std::vector all_mins(cur_nprobe * M); std::vector probe_b(cur_nprobe); + std::vector probe_span(cur_nprobe); -#pragma omp for schedule(dynamic) +#pragma omp for schedule(FAISS_OMP_DYNAMIC) for (int64_t i = 0; i < static_cast(n); i++) { const float* xi = x + i * d; @@ -650,10 +649,13 @@ void IndexIVFRaBitQFastScan::compute_LUT_uint8( used_qb, used_centered, rotated_q, - centroid_buf); + centroid_buf, + rotated_qq, + context.rotated_q ? context.rotated_q + ij * d + : nullptr); if (context.query_factors != nullptr) { - context.query_factors[ij] = qf; + context.query_factors[ij] = std::move(qf); } } else { memset(lut_float.get() + j * dim12, @@ -686,13 +688,18 @@ void IndexIVFRaBitQFastScan::compute_LUT_uint8( span_j += span; } probe_b[j2] = b_j; - glob_max_dis = std::max(glob_max_dis, span_j); + probe_span[j2] = span_j; glob_b = std::min(glob_b, b_j); } - a = std::min( - 255.0f / glob_max_span, - 65535.0f / glob_max_dis); + for (size_t j2 = 0; j2 < cur_nprobe; j2++) { + glob_max_dis = std::max( + glob_max_dis, + probe_span[j2] + probe_b[j2] - glob_b); + } + + a = quantize_lut::fastscan_lut_scale( + glob_max_span, glob_max_dis, M + 1); // Second pass: quantize LUT and compute biasq. uint8_t* out_base = @@ -721,6 +728,28 @@ void IndexIVFRaBitQFastScan::compute_LUT_uint8( } } +namespace { + +/// Decode a FastScan code to a RaBitQ residual vector of dimension d. +void decode_fastscan_to_residual( + size_t d, + const uint8_t* fastscan_code, + float* residual, + float dp_multiplier) { + memset(residual, 0, sizeof(float) * d); + + const float inv_d_sqrt = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d)); + + for (size_t j = 0; j < d; j++) { + bool bit_value = rabitq_utils::extract_bit_fastscan(fastscan_code, j); + + float bit_as_float = bit_value ? 1.0f : 0.0f; + residual[j] = (bit_as_float - 0.5f) * dp_multiplier * 2 * inv_d_sqrt; + } +} + +} // namespace + void IndexIVFRaBitQFastScan::reconstruct_from_offset( int64_t list_no, int64_t offset, @@ -768,7 +797,7 @@ void IndexIVFRaBitQFastScan::reconstruct_from_offset( // Decode residual directly using dp_multiplier std::vector residual(d); decode_fastscan_to_residual( - fastscan_code.data(), residual.data(), dp_multiplier); + d, fastscan_code.data(), residual.data(), dp_multiplier); // Reconstruct: x = centroid + residual for (size_t j = 0; j < static_cast(d); j++) { @@ -806,7 +835,10 @@ void IndexIVFRaBitQFastScan::sa_decode(idx_t n, const uint8_t* bytes, float* x) *reinterpret_cast(factors_ptr); decode_fastscan_to_residual( - fastscan_code, residual.data(), base_factors.dp_multiplier); + d, + fastscan_code, + residual.data(), + base_factors.dp_multiplier); for (size_t j = 0; j < static_cast(d); j++) { x_i[j] = centroid[j] + residual[j]; @@ -817,22 +849,6 @@ void IndexIVFRaBitQFastScan::sa_decode(idx_t n, const uint8_t* bytes, float* x) } } -void IndexIVFRaBitQFastScan::decode_fastscan_to_residual( - const uint8_t* fastscan_code, - float* residual, - float dp_multiplier) const { - memset(residual, 0, sizeof(float) * d); - - const float inv_d_sqrt = (d == 0) ? 1.0f : (1.0f / std::sqrt((float)d)); - - for (size_t j = 0; j < static_cast(d); j++) { - bool bit_value = rabitq_utils::extract_bit_fastscan(fastscan_code, j); - - float bit_as_float = bit_value ? 1.0f : 0.0f; - residual[j] = (bit_as_float - 0.5f) * dp_multiplier * 2 * inv_d_sqrt; - } -} - std::unique_ptr IndexIVFRaBitQFastScan::make_knn_scanner( bool is_max, idx_t n, @@ -872,6 +888,7 @@ struct IVFRaBitQFastScanScanner : InvertedListScanner { AlignedTable lut_float; std::vector rotated_q; std::vector centroid_buf; + std::vector rotated_qq; QueryFactorsData query_factors; FastScanDistancePostProcessing context; std::vector probe_map; @@ -893,6 +910,7 @@ struct IVFRaBitQFastScanScanner : InvertedListScanner { lut_float(16 * index_in.M), rotated_q(index_in.d), centroid_buf(index_in.d), + rotated_qq(index_in.d), probe_map({0}), mins_buf(index_in.M) { this->keep_max = is_similarity_metric(index_in.metric_type); @@ -924,7 +942,9 @@ struct IVFRaBitQFastScanScanner : InvertedListScanner { qb, centered, rotated_q, - centroid_buf); + centroid_buf, + rotated_qq, + nullptr); // Single-probe quantization (simplified inline, no OMP, no 3D) const size_t M = index.M; @@ -952,7 +972,7 @@ struct IVFRaBitQFastScanScanner : InvertedListScanner { b += mn; } - a = std::min(255.0f / max_span, 65535.0f / max_dis); + a = quantize_lut::fastscan_lut_scale(max_span, max_dis, M); for (size_t m = 0; m < M; m++) { const float* tab = lut_float.get() + m * ksub; rabitq::lut_quantize_16_to_uint8( diff --git a/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.h b/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.h index 51d6761c9..d62e7384d 100644 --- a/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.h +++ b/thirdparty/faiss/faiss/IndexIVFRaBitQFastScan.h @@ -131,17 +131,10 @@ struct IndexIVFRaBitQFastScan : IndexIVFFastScan { uint8_t qb_param, bool centered_param, std::vector& rotated_q, - std::vector& centroid_buf) const; + std::vector& centroid_buf, + std::vector& rotated_qq, + float* rotated_q_out) const; - private: - /// Decode FastScan code to RaBitQ residual vector with explicit - /// dp_multiplier - void decode_fastscan_to_residual( - const uint8_t* fastscan_code, - float* residual, - float dp_multiplier) const; - - public: /// Implementation methods for IVFRaBitQFastScan specialization bool lookup_table_is_3d() const override; @@ -203,10 +196,10 @@ IVFRaBitQHeapHandler::IVFRaBitQHeapHandler( size_t k_val, float* distances, int64_t* labels, - const IDSelector* sel, + const IDSelector* sel_in, const FastScanDistancePostProcessing* ctx, bool multibit) - : ResultHandlerCompare(nq_val, 0, sel), + : ResultHandlerCompare(nq_val, 0, sel_in), index(idx), heap_distances(distances), heap_labels(labels), @@ -399,7 +392,8 @@ float IVFRaBitQHeapHandler::compute_full_multibit_distance( unpack_buf.data(), ex_code, ex_fac, - query_factors.rotated_q.data(), + context->rotated_q ? context->rotated_q + storage_idx_val * dim + : query_factors.rotated_q.data(), is_similarity ? query_factors.q_dot_c : query_factors.qr_to_c_L2sqr, dim, ex_bits, diff --git a/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.cpp b/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.cpp new file mode 100644 index 000000000..afb5ccda6 --- /dev/null +++ b/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.cpp @@ -0,0 +1,1694 @@ +/* + * 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. + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace faiss { + +/* Distance estimates. For a vector o in a list of center c, with + * residual r = o - c and sign bits x_u[i] = (r[i] > 0), the RaBitQ estimator + * of uses the code vector xb[i] = x_u[i] * 2^ex_bits + ex[i] + cb + * with cb = -(2^ex_bits - 1/2): + * + * ~ |r|^2 / + * + * The terms that depend on c are folded into per-vector factors, so that the + * estimate is affine in and a query needs a single look-up table: + * + * dist(q, o) ~ g_add + f_add_ex + f_rescale_ex * + * + * L2: dist = |q - o|^2, g_add = |q - c|^2, + * f_add_ex = |r|^2 - f_rescale_ex * , + * f_rescale_ex = -2 |r|^2 / + * IP: dist = -, g_add = -, + * f_add_ex = - - f_rescale_ex * , + * f_rescale_ex = -|r|^2 / + * + * The in-memory estimate uses the sign bits of dimensions [0, mem_dim) only: + * with x1 = x_u - 1/2, f_add, f_rescale and replace the above, with + * and summed over [0, mem_dim), over [0, d), and an + * extra factor d / mem_dim in f_rescale. Its error is bounded by + * f_error * |q - c|, with f_error = k * epsilon * |r| / sqrt(mem_dim) (k = 2 + * for L2, 1 for IP, epsilon = 1.9). + */ + +IndexIVFRaBitQSSDStats indexIVFRaBitQSSD_stats; + +void IndexIVFRaBitQSSDStats::reset() { + n_pages_read = 0; + n_reranked = 0; +} + +void IndexIVFRaBitQSSDStats::add(const IndexIVFRaBitQSSDStats& other) { + n_pages_read += other.n_pages_read; + n_reranked += other.n_reranked; +} + +namespace { + +using Lists = RaBitQSSDInvertedLists; + +constexpr size_t kBatchSize = Lists::kBatchSize; + +/// vectors encoded at once when adding to a list +constexpr size_t kAddChunk = 4096; + +/********************************************************* + * Encoding + *********************************************************/ + +/// Split the RaBitQuantizer code of one vector into its in-memory part (the +/// sign bits of [0, mem_dim) and kMemFactors factors) and its file record. +void split_code( + const Lists& il, + MetricType metric, + const float* x, + const float* centroid, + const uint8_t* code, + idx_t id, + uint8_t* mem_code, + float* mem_factors, + uint8_t* record) { + const size_t d = il.d; + const size_t mem_dim = il.mem_dim; + const size_t ex_bits = il.ex_bits; + // RaBitQuantizer code layout for nb_bits > 1: + // [sign bits][SignBitFactorsWithError][ex code][ExtraBitsFactors] + const uint8_t* sign_bits = code; + const uint8_t* ex_code = + code + d / 8 + sizeof(rabitq_utils::SignBitFactorsWithError); + const double cb = -(double(1 << ex_bits) - 0.5); + + double r_norm2 = 0, ip_r_c = 0; + double ip_r_x1 = 0, ip_c_x1_mem = 0; // with the 1-bit code x_u - 1/2 + double ip_r_xb = 0, ip_c_xb = 0; // with the full code xb + for (size_t i = 0; i < d; i++) { + const double ci = centroid[i]; + const double r = double(x[i]) - ci; + const int bit = (sign_bits[i / 8] >> (i % 8)) & 1; + r_norm2 += r * r; + ip_r_c += r * ci; + const double x1 = bit - 0.5; + ip_r_x1 += r * x1; + if (i < mem_dim) { + ip_c_x1_mem += ci * x1; + } + const int ex = rabitq_utils::extract_code_inline(ex_code, i, ex_bits); + const double xb = double((bit << ex_bits) + ex) + cb; + ip_r_xb += r * xb; + ip_c_xb += ci * xb; + } + const double k = metric == METRIC_L2 ? 2 : 1; + const double f_base = metric == METRIC_L2 ? r_norm2 : -ip_r_c; + + // ip_r_x1 = sum |r[i]| / 2, and every term of ip_r_xb has the sign of + // r[i], so they are 0 only for r = 0 + const double f_rescale = + ip_r_x1 > 0 ? -k * r_norm2 * (double(d) / mem_dim) / ip_r_x1 : 0; + mem_factors[0] = float(f_base - f_rescale * ip_c_x1_mem); + mem_factors[1] = float(f_rescale); + mem_factors[2] = float( + k * rabitq_utils::kConstEpsilon * std::sqrt(r_norm2 / mem_dim)); + memcpy(mem_code, sign_bits, mem_dim / 8); + + // record: [sign bits mem_dim..d) [ex code] [f_add_ex f_rescale_ex] [id] + uint8_t* p = record; + memcpy(p, sign_bits + mem_dim / 8, (d - mem_dim) / 8); + p += (d - mem_dim) / 8; + memcpy(p, ex_code, d * ex_bits / 8); + p += d * ex_bits / 8; + const double f_rescale_ex = ip_r_xb != 0 ? -k * r_norm2 / ip_r_xb : 0; + rabitq_utils::ExtraBitsFactors ex_factors; + ex_factors.f_add_ex = float(f_base - f_rescale_ex * ip_c_xb); + ex_factors.f_rescale_ex = float(f_rescale_ex); + memcpy(p, &ex_factors, sizeof(ex_factors)); + p += sizeof(ex_factors); + memcpy(p, &id, sizeof(id)); +} + +/// Add the vectors x[members[i]] to list list_no, by increasing distance to +/// the center of the list, ties broken by id. +void add_to_list( + const IndexIVFRaBitQSSD& index, + Lists& il, + idx_t list_no, + const idx_t* members, + size_t n, + const float* x, + const idx_t* xids) { + const size_t d = index.d; + std::vector centroid(d); + index.quantizer->reconstruct(list_no, centroid.data()); + if (!index.centroid_scales.empty()) { + const float s = index.centroid_scales[list_no]; + for (float& v : centroid) { + v *= s; + } + } + + std::vector ids(n); + std::vector key(n); + for (size_t i = 0; i < n; i++) { + const idx_t j = members[i]; + ids[i] = xids ? xids[j] : index.ntotal + j; + const float* xj = x + j * d; + double acc = 0; + for (size_t t = 0; t < d; t++) { + if (index.metric_type == METRIC_L2) { + const double diff = double(xj[t]) - double(centroid[t]); + acc += diff * diff; + } else { + acc -= double(xj[t]) * double(centroid[t]); + } + } + key[i] = acc; + } + std::vector order(n); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) { + const bool a_nan = std::isnan(key[a]); + const bool b_nan = std::isnan(key[b]); + if (a_nan != b_nan) { + return !a_nan; + } + if (key[a] < key[b]) { + return true; + } + if (key[a] > key[b]) { + return false; + } + return ids[a] < ids[b]; + }); + + il.reserve(list_no, n); + const size_t chunk = std::min(n, kAddChunk); + const size_t code_size = index.rabitq.code_size; + std::vector xbuf(chunk * d); + std::vector codes(chunk * code_size); + std::vector mem_codes(chunk * il.mem_dim / 8); + std::vector mem_factors(chunk * Lists::kMemFactors); + std::vector records(chunk * il.record_size); + + for (size_t i0 = 0; i0 < n; i0 += chunk) { + const size_t i1 = std::min(n, i0 + chunk); + for (size_t i = i0; i < i1; i++) { + memcpy(xbuf.data() + (i - i0) * d, + x + members[order[i]] * d, + sizeof(float) * d); + } + index.rabitq.compute_codes_core( + xbuf.data(), codes.data(), i1 - i0, centroid.data()); + for (size_t i = i0; i < i1; i++) { + const size_t j = i - i0; + split_code( + il, + index.metric_type, + xbuf.data() + j * d, + centroid.data(), + codes.data() + j * code_size, + ids[order[i]], + mem_codes.data() + j * il.mem_dim / 8, + mem_factors.data() + j * Lists::kMemFactors, + records.data() + j * il.record_size); + } + il.append( + list_no, + i1 - i0, + mem_codes.data(), + mem_factors.data(), + records.data()); + } +} + +/********************************************************* + * Search + *********************************************************/ + +/// The k best results so far, sorted by increasing distance, so that +/// pruning_threshold reads the drain_alpha-quantile in O(1) at each read +/// decision of the drain. Against a heap of utils/Heap.h (vench, wiki-10M, +/// k = 10 to 1000): the same QPS, as the reads bound the search, and the same +/// CPU time up to k = 100. At k = 1000 the heap took up to 25% fewer cycles +/// with drain_alpha = 1 and up to 52% more with drain_alpha = 0.4, where it +/// recomputes the quantile after each change. +struct TopKBuffer { + struct Entry { + float distance; + idx_t id; + }; + std::vector data; // capacity + 1 entries + size_t size = 0; + size_t capacity = 0; + + void reset(size_t k) { + capacity = k; + size = 0; + data.resize(k + 1); + } + + bool is_full() const { + return size == capacity; + } + + float top_dist() const { + return is_full() ? data[size - 1].distance + : std::numeric_limits::max(); + } + + void insert(idx_t id, float dist) { + if (dist > top_dist()) { + return; + } + // before the entries with the same distance + const size_t lo = std::lower_bound( + data.begin(), + data.begin() + size, + dist, + [](const Entry& e, float v) { + return e.distance < v; + }) - + data.begin(); + memmove(&data[lo + 1], &data[lo], (size - lo) * sizeof(Entry)); + data[lo] = Entry{dist, id}; + size += size < capacity; + } +}; + +/// The pruning threshold: the alpha-quantile of the results, e.g. the 90th +/// distance for k = 100 and alpha = 0.9. With alpha >= 1, or until there are +/// k results, the k-th distance. +float pruning_threshold(const TopKBuffer& results, float alpha) { + if (alpha >= 1.0f || !results.is_full()) { + return results.top_dist(); + } + const long topk = long(results.capacity); + long rank = std::lround(alpha * double(topk)); + rank = std::min(std::max(rank, 1L), topk); + return results.data[rank - 1].distance; +} + +/// Per query: the look-up table of the in-memory scan, and sums of the query +/// components. +struct QueryLUT { + /// packed for FastScan; with 16-bit entries, the low bytes of the + /// table, then the high bytes (as expected by accumulate_hacc) + std::vector table; + /// over [0, mem_dim) = delta * (sum of entries) + sum_vl + float delta = 0; + float sum_vl = 0; + float k1xsumq = 0; ///< -1/2 sum of q over [0, mem_dim) + float q_sum = 0; ///< sum of q over [0, d) + + void build(const float* q, size_t mem_dim, size_t d, bool use_hacc) { + const size_t nsq = mem_dim / 4; + // entry c of table t: the sum of q over the dimensions 4t..4t+3 + // whose bit is set in c + std::vector lut_float(nsq * 16); + for (size_t t = 0; t < nsq; t++) { + rabitq_utils::write_subset_sum_lut( + lut_float.data() + t * 16, + 0.0f, + q[4 * t], + q[4 * t + 1], + q[4 * t + 2], + q[4 * t + 3]); + } + const auto [vl_it, vr_it] = + std::minmax_element(lut_float.begin(), lut_float.end()); + const float vl = *vl_it, vr = *vr_it; + const uint32_t max_entry = use_hacc ? 65535 : 255; + delta = (vr - vl) / max_entry; + if (delta == 0) { // all entries equal: they quantize to 0 + delta = 1; + } + const float one_over_delta = 1.0f / delta; + std::vector lo(nsq * 16), hi(use_hacc ? nsq * 16 : 0); + for (size_t i = 0; i < nsq * 16; i++) { + const long e = std::lrint((lut_float[i] - vl) * one_over_delta); + const uint32_t entry = + uint32_t(std::min(std::max(e, 0L), long(max_entry))); + lo[i] = entry & 0xff; + if (use_hacc) { + hi[i] = entry >> 8; + } + } + table.resize((use_hacc ? 2 : 1) * nsq * 16); + pq4_pack_LUT(1, nsq, lo.data(), table.data()); + if (use_hacc) { + pq4_pack_LUT(1, nsq, hi.data(), table.data() + nsq * 16); + } + sum_vl = vl * float(nsq); + + float q_sum_mem = 0; + for (size_t i = 0; i < mem_dim; i++) { + q_sum_mem += q[i]; + } + k1xsumq = -0.5f * q_sum_mem; + q_sum = q_sum_mem; + for (size_t i = mem_dim; i < d; i++) { + q_sum += q[i]; + } + } +}; + +/// a vector to re-rank, in a page to read +struct Candidate { + size_t offset; ///< in its list + int in_page_idx; ///< record number in the page + float mem_low_dist; + float mem_est_dist; + float mem_ip_x0_qr; ///< over [0, mem_dim) +}; + +/// a page to read, with its candidates +struct CandidatePage { + float page_lower_bound = 0; ///< smallest lower bound of its candidates + size_t probe_idx = 0; + size_t page_no = 0; ///< in its list + uint16_t candidate_num = 0; +}; + +using SlotID = uint32_t; +constexpr SlotID kSlotMax = std::numeric_limits::max(); + +/// The pages waiting to be read, sorted by lower bound. +struct PendingPages { + struct Entry { + SlotID slot_id; + float key; + }; + std::vector entries; + size_t head = 0; + + void reset() { + entries.clear(); + head = 0; + } + + bool empty() const { + return size() == 0; + } + + size_t size() const { + return entries.size() - head; + } + + void insert(SlotID slot_id, float key) { + compact_if_needed(); + const auto it = std::lower_bound( + entries.begin() + head, + entries.end(), + key, + [](const Entry& e, float value) { return e.key < value; }); + entries.insert(it, Entry{slot_id, key}); + } + + SlotID front_slot() const { + return entries[head].slot_id; + } + + void pop_front() { + ++head; + compact_if_needed(); + } + + /// remove the entries with a key above threshold, appending them to pruned + void prune_greater(float threshold, std::vector& pruned) { + const auto it = std::upper_bound( + entries.begin() + head, + entries.end(), + threshold, + [](float value, const Entry& e) { return value < e.key; }); + for (auto cur = it; cur != entries.end(); ++cur) { + pruned.push_back(cur->slot_id); + } + entries.erase(it, entries.end()); + if (head == entries.size()) { + entries.clear(); + head = 0; + return; + } + compact_if_needed(); + } + + void compact_if_needed() { + if (head >= 256 && head * 2 >= entries.size()) { + entries.erase(entries.begin(), entries.begin() + head); + head = 0; + } + } +}; + +/// Scan position in the list being scanned. A page can span several batches. +struct ListScanState { + int64_t last_page = -1; + SlotID cur_page_slot_id = kSlotMax; + int64_t cur_inner_pid = -1; + size_t cur_page = 0; + int in_page_idx = 0; + int remaining_in_page = 0; + const uint8_t* mem_data = nullptr; +}; + +/// Per-thread search state. Each query is searched by +/// search_one(). +template +struct RaBitQSSDSearcher { + static constexpr size_t kMaxReadsInFlight = + IndexIVFRaBitQSSD::kMaxReadsInFlight; + static constexpr size_t kInitialPageSlots = kMaxReadsInFlight + 1; + + const IndexIVFRaBitQSSD& index; + const Lists& il; + const size_t d, mem_dim, ex_bits; + const bool is_ip; // metric of the index + const bool coarse_is_ip; // metric of the coarse distances + const bool has_scales; // centroid_scales is set + const bool use_hacc; + const float drain_alpha; + const size_t qd_cap; + const IDSelector* sel; + const bool store_pairs; + const int fd; + const float cb; // -(2^ex_bits - 1/2) + const size_t suffix_bytes; + + // query + const float* q = nullptr; + QueryLUT lut; + std::vector g_adds, g_errors; // per probe + std::vector probe_lists; // per probe + std::vector centroid; // see set_list_terms + TopKBuffer results; + + // estimates of one batch + int32_t accu_arr[kBatchSize]; + uint16_t accu16[kBatchSize]; + float est_distance[kBatchSize]; + float low_distance[kBatchSize]; + float ip_x0_qr[kBatchSize]; + + // pages to read, with their candidates + size_t page_candidate_capacity; + std::vector page_slots; + std::vector candidate_storage; + std::vector free_page_slots; + + // read requests, one buffer of page_size bytes each + struct ReadRequest { + size_t offset = 0; + size_t len = 0; + uint8_t* buf = nullptr; + }; + AlignedTableTightAlloc read_buffers; + std::array requests; + std::array req_slot_owner; + std::vector free_req_slots; + std::vector completed_slots; + + // I/O queue + PendingPages pending; + /// 1 from the submission of a page slot's read to its completion + std::vector slot_inflight; + std::vector slot_req_slot; + size_t inflight_count = 0; + std::vector pruned_slots; + std::array io_ud; + std::array io_res; + std::unique_ptr io; + + // statistics + size_t n_lists = 0, n_codes = 0, n_knn_inserts = 0; + IndexIVFRaBitQSSDStats disk_stats; + + RaBitQSSDSearcher( + const IndexIVFRaBitQSSD& index_in, + const Lists& il_in, + bool use_hacc_in, + float drain_alpha_in, + size_t qd_in, + const IDSelector* sel_in, + bool store_pairs_in) + : index(index_in), + il(il_in), + d(il_in.d), + mem_dim(il_in.mem_dim), + ex_bits(il_in.ex_bits), + is_ip(index_in.metric_type == METRIC_INNER_PRODUCT), + coarse_is_ip( + index_in.quantizer->metric_type == METRIC_INNER_PRODUCT), + has_scales(!index_in.centroid_scales.empty()), + use_hacc(use_hacc_in), + drain_alpha(drain_alpha_in), + qd_cap(qd_in), + sel(sel_in), + store_pairs(store_pairs_in), + fd(il_in.fd), + cb(-(float(1 << il_in.ex_bits) - 0.5f)), + suffix_bytes((il_in.d - il_in.mem_dim) / 8), + page_candidate_capacity(il_in.records_per_page), + read_buffers(qd_in * il_in.page_size) { + FAISS_THROW_IF_MSG( + fd < 0, "RaBitQSSDInvertedLists: the file is not open"); + io = il_in.acquire_io(int(qd_in)); + if (has_scales && !coarse_is_ip) { + centroid.resize(d); + } + reserve_page_slots(kInitialPageSlots); + reset(); + } + + ~RaBitQSSDSearcher() { + // after an exception, reads can still be in flight into + // read_buffers: wait for them before the buffers are freed, and + // give the context back for the next searches. If waiting fails, the + // destructor of the context waits instead. + if (io && io->wait_all()) { + il.release_io(std::move(io)); + } + io.reset(); + } + + /*********** page slots and read requests ***********/ + + void reserve_page_slots(size_t target_slots) { + if (page_slots.size() >= target_slots) { + return; + } + const size_t old_size = page_slots.size(); + page_slots.resize(target_slots); + candidate_storage.resize(target_slots * page_candidate_capacity); + for (size_t i = target_slots; i > old_size; --i) { + free_page_slots.push_back(SlotID(i - 1)); + } + slot_inflight.resize(target_slots, 0); + slot_req_slot.resize(target_slots, -1); + } + + void reset() { + free_page_slots.clear(); + for (size_t i = page_slots.size(); i > 0; --i) { + page_slots[i - 1] = CandidatePage(); + free_page_slots.push_back(SlotID(i - 1)); + } + free_req_slots.clear(); + completed_slots.clear(); + for (int req_slot = int(qd_cap); req_slot > 0; --req_slot) { + requests[req_slot - 1] = ReadRequest(); + req_slot_owner[req_slot - 1] = kSlotMax; + free_req_slots.push_back(req_slot - 1); + } + pending.reset(); + inflight_count = 0; + std::fill(slot_inflight.begin(), slot_inflight.end(), 0); + std::fill(slot_req_slot.begin(), slot_req_slot.end(), -1); + } + + uint8_t* read_buffer(int req_slot) { + return read_buffers.get() + size_t(req_slot) * il.page_size; + } + + Candidate* page_candidates(SlotID slot_id) { + return candidate_storage.data() + + size_t(slot_id) * page_candidate_capacity; + } + + /*********** pending pages and reads ***********/ + + bool reads_done() const { + return pending.empty() && inflight_count == 0; + } + + SlotID acquire_page_slot() { + if (free_page_slots.empty()) { + const size_t old_size = page_slots.size(); + reserve_page_slots( + old_size + std::max(old_size, kInitialPageSlots)); + } + const SlotID slot_id = free_page_slots.back(); + free_page_slots.pop_back(); + page_slots[slot_id] = CandidatePage(); + return slot_id; + } + + void release_page_slot(SlotID slot_id) { + page_slots[slot_id] = CandidatePage(); + slot_inflight[slot_id] = 0; + slot_req_slot[slot_id] = -1; + free_page_slots.push_back(slot_id); + } + + void prune_pending(float threshold) { + if (pending.empty()) { + return; + } + pruned_slots.clear(); + pending.prune_greater(threshold, pruned_slots); + for (SlotID slot_id : pruned_slots) { + release_page_slot(slot_id); + } + } + + void enqueue_page(SlotID slot_id) { + pending.insert(slot_id, page_slots[slot_id].page_lower_bound); + } + + void prepare_read(SlotID slot_id, int req_slot) { + CandidatePage& cand = page_slots[slot_id]; + requests[req_slot] = ReadRequest{ + il.page_offset(probe_lists[cand.probe_idx], cand.page_no), + il.page_size, + read_buffer(req_slot)}; + req_slot_owner[req_slot] = slot_id; + slot_req_slot[slot_id] = req_slot; + } + + /// submit up to budget pending pages, smallest lower bound first, after + /// dropping the pending pages whose lower bound exceeds threshold + void submit_reads(size_t budget, float threshold) { + if (budget == 0 || pending.empty()) { + return; + } + prune_pending(threshold); + int submitted = 0; + while (budget > 0 && !pending.empty() && !free_req_slots.empty()) { + const SlotID slot_id = pending.front_slot(); + pending.pop_front(); + const int req_slot = free_req_slots.back(); + free_req_slots.pop_back(); + prepare_read(slot_id, req_slot); + ReadRequest& req = requests[req_slot]; + io->stage(fd, req.buf, req.len, req.offset, &req); + slot_inflight[slot_id] = 1; + inflight_count++; + submitted++; + disk_stats.n_pages_read++; + --budget; + } + if (submitted > 0) { + io->submit(); + } + } + + /// collect the completed reads into completed_slots, waiting for at + /// least min_nr of them + void poll_reads(int min_nr = 0) { + completed_slots.clear(); + if (inflight_count == 0) { + return; + } + const int ret = + io->reap(io_ud.data(), io_res.data(), int(qd_cap), min_nr); + for (int i = 0; i < ret; ++i) { + // re-ranking the stale bytes of a failed or short read would + // silently return wrong results + FAISS_THROW_IF_NOT_FMT( + io_res[i] >= 0, + "read of %s failed: %s", + il.filename.c_str(), + strerror(-io_res[i])); + const ReadRequest* req = static_cast(io_ud[i]); + FAISS_THROW_IF_NOT_FMT( + size_t(io_res[i]) == req->len, + "short read of %s at offset %zu: %ld of %zu bytes", + il.filename.c_str(), + req->offset, + io_res[i], + req->len); + const int req_slot = int(req - requests.data()); + const SlotID slot_id = req_slot_owner[req_slot]; + if (slot_id == kSlotMax || !slot_inflight[slot_id]) { + continue; + } + slot_inflight[slot_id] = 0; + inflight_count--; + completed_slots.push_back(slot_id); + } + } + + void release_read(SlotID slot_id) { + const int req_slot = slot_req_slot[slot_id]; + if (req_slot != -1) { + requests[req_slot] = ReadRequest(); + req_slot_owner[req_slot] = kSlotMax; + free_req_slots.push_back(req_slot); + } + release_page_slot(slot_id); + } + + /*********** scan and re-rank ***********/ + + /// FastScan over the in-memory bits of one batch of a list + void estimate_batch(const uint8_t* batch, size_t probe_idx) { + const size_t nsq = mem_dim / 4; + if (use_hacc) { + // Reuse the search's SIMD level, with compile-time fallback. + dispatch_with_fallback( + [&]() { + accumulate_hacc_impl( + 1, + kBatchSize, + nsq, + batch, + lut.table.data(), + accu_arr); + }); + } else { + // a segment of D dimensions sums D / 4 entries of at most 255 + // into a uint16, so (D / 4) * 255 must stay below 2^16 + constexpr size_t kNoHaccSegmentSq = 256; + std::fill(accu_arr, accu_arr + kBatchSize, 0); + dispatch_with_fallback( + [&]() { + for (size_t sq0 = 0; sq0 < nsq; + sq0 += kNoHaccSegmentSq) { + const size_t nsq_s = + std::min(kNoHaccSegmentSq, nsq - sq0); + accumulate_to_mem_impl( + 1, + kBatchSize, + int(nsq_s), + batch + 16 * sq0, + lut.table.data() + 16 * sq0, + accu16); + for (size_t i = 0; i < kBatchSize; ++i) { + accu_arr[i] += accu16[i]; + } + } + }); + } + + const float* f_add = reinterpret_cast( + batch + kBatchSize * mem_dim / 8); + const float* f_rescale = f_add + kBatchSize; + const float* f_error = f_rescale + kBatchSize; + const float g_add = g_adds[probe_idx]; + const float g_error = g_errors[probe_idx]; + for (size_t i = 0; i < kBatchSize; ++i) { + ip_x0_qr[i] = lut.delta * float(accu_arr[i]) + lut.sum_vl; + est_distance[i] = f_add[i] + g_add + + f_rescale[i] * (ip_x0_qr[i] + lut.k1xsumq); + low_distance[i] = est_distance[i] - f_error[i] * g_error; + } + } + + /// scan batch iter of a list of n vectors: the vectors whose lower bound + /// does not exceed threshold become candidates of their page, and each page + /// is queued once the scan has moved past it + void scan_batch( + size_t n, + size_t probe_idx, + float threshold, + ListScanState& state, + size_t iter) { + const size_t batch_size = std::min(kBatchSize, n - iter * kBatchSize); + estimate_batch(state.mem_data, probe_idx); + + for (size_t idx = 0; idx < batch_size; ++idx) { + ++state.cur_inner_pid; + if (state.remaining_in_page == 0) { + state.cur_page += 1; + state.remaining_in_page = int(il.records_per_page); + state.in_page_idx = 0; + } + const size_t cur_page_id = state.cur_page; + const int cur_in_page_idx = state.in_page_idx; + --state.remaining_in_page; + ++state.in_page_idx; + + if (low_distance[idx] > threshold) { + continue; + } + + if (int64_t(cur_page_id) != state.last_page) { + if (state.last_page != -1) { + enqueue_page(state.cur_page_slot_id); + } + state.last_page = cur_page_id; + state.cur_page_slot_id = acquire_page_slot(); + CandidatePage& page_cand = page_slots[state.cur_page_slot_id]; + page_cand.probe_idx = probe_idx; + page_cand.page_no = cur_page_id; + page_cand.candidate_num = 0; + page_cand.page_lower_bound = low_distance[idx]; + } + + CandidatePage& page_cand = page_slots[state.cur_page_slot_id]; + Candidate& cand = page_candidates( + state.cur_page_slot_id)[page_cand.candidate_num++]; + cand.offset = size_t(state.cur_inner_pid); + cand.in_page_idx = cur_in_page_idx; + cand.mem_low_dist = low_distance[idx]; + cand.mem_est_dist = est_distance[idx]; + cand.mem_ip_x0_qr = ip_x0_qr[idx]; + page_cand.page_lower_bound = + std::min(page_cand.page_lower_bound, low_distance[idx]); + } + state.mem_data += il.batch_bytes; + } + + /// queue the last page of a list + void finish_list(ListScanState& state) { + if (state.last_page != -1) { + enqueue_page(state.cur_page_slot_id); + } + } + + /// re-rank the candidates of a page whose read completed + void rerank_page(SlotID slot_id) { + const CandidatePage& page_cand = page_slots[slot_id]; + const uint8_t* data = requests[slot_req_slot[slot_id]].buf; + const size_t probe_idx = page_cand.probe_idx; + const idx_t list_no = probe_lists[probe_idx]; + const float g_add = g_adds[probe_idx]; + const Candidate* candidates = page_candidates(slot_id); + + float threshold = results.top_dist(); + for (size_t cidx = 0; cidx < page_cand.candidate_num; ++cidx) { + const Candidate& cand = candidates[cidx]; + if (cand.mem_low_dist > threshold) { + continue; + } + const uint8_t* rec = data + cand.in_page_idx * il.record_size; + idx_t id; + memcpy(&id, rec + il.record_size - sizeof(idx_t), sizeof(id)); + if (sel && !sel->is_member(id)) { + continue; + } + + float sign_ip = cand.mem_ip_x0_qr; + if (d > mem_dim) { + sign_ip += fvec_masked_sum::value>( + q + mem_dim, rec, d - mem_dim); + } + const float ip = dispatch_with_fallback< + rabitq::multibit::RABITQ_SPLIT_IP_SIMD_LEVELS, + SL>([&]() { + return rabitq::multibit::compute_inner_product_with_sign_ip( + rec + suffix_bytes, + q, + d, + ex_bits, + cb, + sign_ip, + lut.q_sum); + }); + rabitq_utils::ExtraBitsFactors ex_factors; + memcpy(&ex_factors, + rec + suffix_bytes + d * ex_bits / 8, + sizeof(ex_factors)); + const float full_dist = + ex_factors.f_add_ex + g_add + ex_factors.f_rescale_ex * ip; + disk_stats.n_reranked++; + + if (full_dist > threshold) { + continue; + } + const idx_t label = + store_pairs ? idx_t(lo_build(list_no, cand.offset)) : id; + results.insert(label, full_dist); + n_knn_inserts++; + threshold = results.top_dist(); + } + release_read(slot_id); + } + + /// re-rank the pages read since the last call + void rerank_read_pages(int min_nr = 0) { + poll_reads(min_nr); + for (SlotID slot_id : completed_slots) { + rerank_page(slot_id); + } + } + + /// and |q - c|^2 for the center c of list_no + void set_list_terms( + size_t probe_idx, + idx_t list_no, + float coarse_dis, + float q_norm2) { + float qc_dist2, qc_ip = 0; + if (has_scales) { + // the center is s times the centroid u + const float s = index.centroid_scales[list_no]; + float qu_ip = coarse_dis; + if (!coarse_is_ip) { + // not from the L2 coarse distance: s would amplify the + // rounding error of the difference of two large numbers + index.quantizer->reconstruct(list_no, centroid.data()); + qu_ip = fvec_inner_product(q, centroid.data(), d); + } + qc_ip = s * qu_ip; + qc_dist2 = + q_norm2 + s * s * index.centroid_norms[list_no] - 2 * qc_ip; + } else if (!is_ip && !coarse_is_ip) { + qc_dist2 = coarse_dis; + } else { + const float c_norm2 = index.centroid_norms[list_no]; + if (coarse_is_ip) { + qc_ip = coarse_dis; + qc_dist2 = q_norm2 + c_norm2 - 2 * coarse_dis; + } else { + qc_dist2 = coarse_dis; + qc_ip = 0.5f * (q_norm2 + c_norm2 - coarse_dis); + } + } + qc_dist2 = std::max(qc_dist2, 0.0f); + g_adds[probe_idx] = is_ip ? -qc_ip : qc_dist2; + g_errors[probe_idx] = std::sqrt(qc_dist2); + } + + /// search one query + void search_one( + const float* query, + idx_t k, + size_t nprobe, + const idx_t* assign, + const float* coarse_dis, + float* distances, + idx_t* labels) { + reset(); + q = query; + results.reset(k); + lut.build(q, mem_dim, d, use_hacc); + const float q_norm2 = (is_ip || coarse_is_ip || has_scales) + ? fvec_norm_L2sqr(q, d) + : 0.0f; + g_adds.resize(nprobe); + g_errors.resize(nprobe); + probe_lists.assign(assign, assign + nprobe); + + for (size_t i = 0; i < nprobe; ++i) { + const idx_t list_no = assign[i]; + if (list_no < 0) { + continue; + } + FAISS_THROW_IF_NOT_FMT( + list_no < idx_t(index.nlist), + "invalid list number %" PRId64, + list_no); + const size_t n = il.list_size(list_no); + if (n == 0) { + continue; + } + n_lists++; + n_codes += n; + set_list_terms(i, list_no, coarse_dis[i], q_norm2); + + // for each batch: scan it, re-rank the pages read so far and + // submit the best pending pages. The search over the lists does + // not prune beyond the k-th distance (alpha = 1). + const size_t n_iter = (n + kBatchSize - 1) / kBatchSize; + ListScanState state; + state.remaining_in_page = int(il.records_per_page); + state.mem_data = il.mem_data[list_no].get(); + for (size_t iter = 0; iter < n_iter; ++iter) { + scan_batch(n, i, pruning_threshold(results, 1.0f), state, iter); + rerank_read_pages(); + if (inflight_count < qd_cap) { + submit_reads( + qd_cap - inflight_count, + pruning_threshold(results, 1.0f)); + } + } + finish_list(state); + } + + // drain: read the remaining pages, pruning with the + // drain_alpha-quantile of the results. When no page can be + // submitted, there is nothing else to do until a read completes, so + // wait instead of polling. + while (!reads_done()) { + rerank_read_pages( + pending.empty() || inflight_count >= qd_cap ? 1 : 0); + if (inflight_count < qd_cap) { + submit_reads( + qd_cap - inflight_count, + pruning_threshold(results, drain_alpha)); + } + } + + for (size_t j = 0; j < size_t(k); j++) { + if (j < results.size) { + labels[j] = results.data[j].id; + // the search uses - for the inner product + distances[j] = is_ip ? -results.data[j].distance + : results.data[j].distance; + } else { + labels[j] = -1; + distances[j] = is_ip ? std::numeric_limits::lowest() + : std::numeric_limits::max(); + } + } + } +}; + +/// settings of one search, from the index and the search parameters +struct SearchSettings { + size_t nprobe = 0; + bool use_hacc = true; + float drain_alpha = 1.0f; + size_t qd = 0; + const IDSelector* sel = nullptr; +}; + +SearchSettings get_search_settings( + const IndexIVFRaBitQSSD& index, + const IVFSearchParameters* params, + bool store_pairs) { + FAISS_THROW_IF_NOT_MSG(index.quantizer, "IVF quantizer must not be null"); + FAISS_THROW_IF_NOT_MSG(index.is_trained, "IVF index is not trained"); + SearchSettings s; + s.nprobe = std::min(index.nlist, params ? params->nprobe : index.nprobe); + FAISS_THROW_IF_NOT(s.nprobe > 0); + FAISS_THROW_IF_NOT_MSG( + (params ? params->max_codes : index.max_codes) == 0, + "IndexIVFRaBitQSSD: max_codes not supported"); + FAISS_THROW_IF_MSG( + params && params->max_lists_num != 0, + "IndexIVFRaBitQSSD: max_lists_num not supported"); + FAISS_THROW_IF_MSG( + params && params->ensure_topk_full, + "IndexIVFRaBitQSSD: ensure_topk_full not supported"); + FAISS_THROW_IF_MSG( + params && params->max_empty_result_buckets != 0, + "IndexIVFRaBitQSSD: max_empty_result_buckets not supported"); + s.sel = params ? params->sel : nullptr; + FAISS_THROW_IF_MSG( + s.sel && store_pairs, + "selector and store_pairs cannot be combined"); + s.use_hacc = index.use_hacc; + s.drain_alpha = index.drain_alpha; + s.qd = index.qd_per_thread; + if (auto p = dynamic_cast(params)) { + s.use_hacc = p->use_hacc; + s.drain_alpha = p->drain_alpha; + s.qd = p->qd_per_thread; + } + FAISS_THROW_IF_NOT_FMT( + s.drain_alpha >= 0 && s.drain_alpha <= 1, + "drain_alpha=%g must be in [0, 1]", + s.drain_alpha); + FAISS_THROW_IF_NOT_FMT( + s.qd >= 1 && s.qd <= IndexIVFRaBitQSSD::kMaxReadsInFlight, + "qd_per_thread=%zu must be in [1, %zu]", + s.qd, + IndexIVFRaBitQSSD::kMaxReadsInFlight); + FAISS_THROW_IF_MSG( + index.parallel_mode & index.PARALLEL_MODE_NO_HEAP_INIT, + "IndexIVFRaBitQSSD: PARALLEL_MODE_NO_HEAP_INIT not supported"); + const MetricType coarse_metric = index.quantizer->metric_type; + FAISS_THROW_IF_NOT_MSG( + coarse_metric == METRIC_L2 || coarse_metric == METRIC_INNER_PRODUCT, + "IndexIVFRaBitQSSD: the coarse quantizer must use METRIC_L2 or " + "METRIC_INNER_PRODUCT"); + FAISS_THROW_IF_NOT_MSG( + index.centroid_scales.empty() || + index.centroid_scales.size() == index.nlist, + "IndexIVFRaBitQSSD: centroid_scales must be empty or have one " + "entry per list"); + // the norms are needed to convert the coarse distances, except for L2 + // with an L2 quantizer and no scales + FAISS_THROW_IF_NOT_MSG( + (index.metric_type == METRIC_L2 && coarse_metric == METRIC_L2 && + index.centroid_scales.empty()) || + index.centroid_norms.size() == index.nlist || + index.ntotal == 0, + "IndexIVFRaBitQSSD: centroid norms missing, call " + "update_centroid_norms()"); + return s; +} + +/** Search n queries. Without assign and centroid_dis, the thread that + * searches a query first runs the coarse quantizer on it, so that the coarse + * search of one query overlaps the reads of the others. */ +template +void search_impl( + const IndexIVFRaBitQSSD& index, + const Lists& il, + idx_t n, + const float* x, + idx_t k, + const idx_t* assign, + const float* centroid_dis, + const SearchParameters* quantizer_params, + float* distances, + idx_t* labels, + bool store_pairs, + const SearchSettings& s, + [[maybe_unused]] bool do_parallel, + IndexIVFStats* ivf_stats) { + if (n == 0) { + return; + } + const size_t nprobe = s.nprobe; + size_t nlistv = 0, ndis = 0, nheap = 0, npages = 0, nreranked = 0; + double quantization_ms = 0, search_ms = 0; + std::exception_ptr ex; + std::atomic interrupt{false}; + + auto capture = [&]() { + omp_capture_exception(ex, [&] { interrupt = true; }); + }; + +#pragma omp parallel if (do_parallel) \ + num_threads(int(std::min(n, omp_get_max_threads()))) \ + reduction(+ : nlistv, ndis, nheap, npages, nreranked) \ + reduction(+ : quantization_ms, search_ms) + { + // every thread must reach the omp for, even if its setup fails + std::unique_ptr> searcher; + std::vector q_assign; + std::vector q_dis; + try { + searcher = std::make_unique>( + index, + il, + s.use_hacc, + s.drain_alpha, + s.qd, + s.sel, + store_pairs); + if (!assign) { + q_assign.resize(nprobe); + q_dis.resize(nprobe); + } + } catch (...) { + capture(); + } + +#pragma omp for schedule(FAISS_OMP_DYNAMIC, 1) + for (idx_t i = 0; i < n; i++) { + if (interrupt) { + continue; + } + try { + const float* xi = x + i * index.d; + if (assign) { + searcher->search_one( + xi, + k, + nprobe, + assign + i * nprobe, + centroid_dis + i * nprobe, + distances + i * k, + labels + i * k); + } else { + const double t0 = getmillisecs(); + index.quantizer->search( + 1, + xi, + nprobe, + q_dis.data(), + q_assign.data(), + quantizer_params); + const double t1 = getmillisecs(); + searcher->search_one( + xi, + k, + nprobe, + q_assign.data(), + q_dis.data(), + distances + i * k, + labels + i * k); + quantization_ms += t1 - t0; + search_ms += getmillisecs() - t0; + } + } catch (...) { + capture(); + } + } + if (searcher) { + nlistv += searcher->n_lists; + ndis += searcher->n_codes; + nheap += searcher->n_knn_inserts; + npages += searcher->disk_stats.n_pages_read; + nreranked += searcher->disk_stats.n_reranked; + } + } + omp_rethrow_if_exception(ex); + + add_search_stats(n, nlistv, ndis, nheap, ivf_stats); + add_search_times(quantization_ms, search_ms, ivf_stats); + detail::atomic_fetch_add_relaxed( + indexIVFRaBitQSSD_stats.n_pages_read, npages); + detail::atomic_fetch_add_relaxed( + indexIVFRaBitQSSD_stats.n_reranked, nreranked); +} + +} // namespace + +/********************************************************* + * IndexIVFRaBitQSSD + *********************************************************/ + +IndexIVFRaBitQSSD::IndexIVFRaBitQSSD( + Index* quantizer_in, + size_t d_in, + size_t nlist_in, + size_t mem_dim_in, + uint8_t nb_bits, + MetricType metric) + : IndexIVF(quantizer_in, d_in, nlist_in, 0, metric, false), + rabitq(d_in, metric, nb_bits), + mem_dim(mem_dim_in) { + FAISS_THROW_IF_NOT_FMT( + d_in > 0 && d_in % 64 == 0 && d_in < (size_t(1) << 31), + "d=%zu must be a positive multiple of 64", + d_in); + FAISS_THROW_IF_NOT_FMT( + mem_dim >= 64 && mem_dim <= d_in && mem_dim % 64 == 0, + "mem_dim=%zu must be a multiple of 64 in [64, d=%zu]", + mem_dim, + d_in); + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT, + "IndexIVFRaBitQSSD supports METRIC_L2 and " + "METRIC_INNER_PRODUCT only"); + // with nb_bits = 1, either the file holds no code, or the in-memory + // estimate has no extra bits to be refined with + FAISS_THROW_IF_NOT_FMT( + nb_bits >= 2 && nb_bits <= 9, + "IndexIVFRaBitQSSD: nb_bits=%d must be in [2, 9]", + int(nb_bits)); + code_size = rabitq.code_size; + by_residual = true; + if (metric == METRIC_INNER_PRODUCT) { + // not trained until train() sets centroid_scales, even if the + // quantizer is filled + is_trained = false; + } +} + +IndexIVFRaBitQSSD::IndexIVFRaBitQSSD() { + by_residual = true; +} + +void IndexIVFRaBitQSSD::attach_file(const char* filename) { + // the new file is empty: the vectors of the current lists would be lost + FAISS_THROW_IF_MSG( + ntotal > 0, + "IndexIVFRaBitQSSD: attach_file() needs an empty index"); + replace_invlists( + new RaBitQSSDInvertedLists( + nlist, d, mem_dim, rabitq.nb_bits - 1, filename), + true); +} + +RaBitQSSDInvertedLists* IndexIVFRaBitQSSD::get_ssd_invlists() const { + FAISS_THROW_IF_NOT_MSG( + invlists, + "IndexIVFRaBitQSSD has no inverted lists: call attach_file()"); + auto* il = dynamic_cast(invlists); + FAISS_THROW_IF_NOT_MSG( + il, "IndexIVFRaBitQSSD needs RaBitQSSDInvertedLists"); + FAISS_THROW_IF_NOT_MSG( + il->d == size_t(d) && il->mem_dim == mem_dim && + il->ex_bits + 1 == rabitq.nb_bits, + "IndexIVFRaBitQSSD: the inverted lists do not match the index"); + return il; +} + +void IndexIVFRaBitQSSD::reset() { + if (invlists) { + IndexIVF::reset(); + } else { + direct_map.clear(); + ntotal = 0; + } + centroid_norms.clear(); +} + +void IndexIVFRaBitQSSD::train_encoder( + idx_t n, + const float* x, + const idx_t* assign) { + update_centroid_norms(); + if (metric_type != METRIC_INNER_PRODUCT || ntotal > 0) { + // the codes of a non-empty index are relative to the current centers + return; + } + // x holds o - u, the training vectors minus their centroid u. The + // multiple of u closest to the mean of the vectors of a list is s * u, + // with s = 1 + / |u|^2. + FAISS_THROW_IF_NOT_MSG( + assign, "IndexIVFRaBitQSSD: by_residual must stay set"); + FAISS_THROW_IF_NOT_MSG( + n > 0, + "IndexIVFRaBitQSSD: training vectors are needed to set " + "centroid_scales"); + + // training vectors of each list + std::vector list_begin(nlist + 1, 0); + for (idx_t i = 0; i < n; i++) { + FAISS_THROW_IF_NOT_FMT( + assign[i] >= 0 && assign[i] < idx_t(nlist), + "invalid list number %" PRId64, + assign[i]); + list_begin[assign[i] + 1]++; + } + for (size_t l = 0; l < nlist; l++) { + list_begin[l + 1] += list_begin[l]; + } + std::vector order(n); + { + std::vector next(list_begin.begin(), list_begin.end() - 1); + for (idx_t i = 0; i < n; i++) { + order[next[assign[i]]++] = i; + } + } + + std::vector scales(nlist, 1.0f); + const size_t bs = 4096; + std::vector centroids(std::min(nlist, bs) * d); + for (size_t l0 = 0; l0 < nlist; l0 += bs) { + const size_t l1 = std::min(nlist, l0 + bs); + quantizer->reconstruct_n(l0, l1 - l0, centroids.data()); +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (int64_t l = l0; l < int64_t(l1); l++) { + const size_t n_l = list_begin[l + 1] - list_begin[l]; + if (n_l == 0 || centroid_norms[l] == 0) { + continue; + } + const float* u = centroids.data() + (l - l0) * d; + double ip = 0; + for (size_t j = list_begin[l]; j < list_begin[l + 1]; j++) { + ip += fvec_inner_product(x + order[j] * d, u, d); + } + scales[l] = float(1 + ip / (double(n_l) * centroid_norms[l])); + } + } + + // lists without training vectors: the mean scale of the others + double scale_sum = 0; + size_t n_empty = 0; + for (size_t l = 0; l < nlist; l++) { + if (list_begin[l + 1] > list_begin[l]) { + scale_sum += scales[l]; + } else { + n_empty++; + } + } + if (n_empty > 0) { + const float fill = float(scale_sum / (nlist - n_empty)); + for (size_t l = 0; l < nlist; l++) { + if (list_begin[l + 1] == list_begin[l]) { + scales[l] = fill; + } + } + } + centroid_scales = std::move(scales); +} + +void IndexIVFRaBitQSSD::update_centroid_norms() { + std::vector norms(nlist); + const size_t bs = 4096; + std::vector centroids(std::min(nlist, bs) * d); + for (size_t i0 = 0; i0 < nlist; i0 += bs) { + const size_t i1 = std::min(nlist, i0 + bs); + quantizer->reconstruct_n(i0, i1 - i0, centroids.data()); + fvec_norms_L2sqr(norms.data() + i0, centroids.data(), d, i1 - i0); + } + centroid_norms = std::move(norms); +} + +void IndexIVFRaBitQSSD::add_core( + idx_t n, + const float* x, + const idx_t* xids, + const idx_t* coarse_idx, + void* /*inverted_list_context*/) { + FAISS_THROW_IF_NOT_MSG( + is_trained || metric_type != METRIC_INNER_PRODUCT, + "IndexIVFRaBitQSSD: an inner-product index must be trained even " + "if its quantizer is filled: train() sets centroid_scales"); + FAISS_THROW_IF_NOT(is_trained); + FAISS_THROW_IF_NOT(coarse_idx); + FAISS_THROW_IF_NOT_MSG(quantizer, "IVF quantizer must not be null"); + FAISS_THROW_IF_NOT_MSG( + direct_map.no(), "IndexIVFRaBitQSSD does not support direct maps"); + RaBitQSSDInvertedLists* il = get_ssd_invlists(); + FAISS_THROW_IF_NOT_MSG( + centroid_scales.size() == + (metric_type == METRIC_INNER_PRODUCT ? nlist : 0), + "IndexIVFRaBitQSSD: centroid_scales must have one entry per list " + "with METRIC_INNER_PRODUCT and be empty otherwise"); + if (centroid_norms.size() != nlist) { + update_centroid_norms(); + } + + // vectors of each list, in input order + std::vector list_begin(nlist + 1, 0); + for (idx_t i = 0; i < n; i++) { + const idx_t list_no = coarse_idx[i]; + if (list_no >= 0) { + FAISS_THROW_IF_NOT_FMT( + list_no < idx_t(nlist), + "invalid list number %" PRId64, + list_no); + list_begin[list_no + 1]++; + } + } + std::vector lists; + for (size_t l = 0; l < nlist; l++) { + if (list_begin[l + 1] > 0) { + lists.push_back(l); + } + list_begin[l + 1] += list_begin[l]; + } + std::vector members(list_begin[nlist]); + { + std::vector pos(list_begin.begin(), list_begin.end() - 1); + for (idx_t i = 0; i < n; i++) { + if (coarse_idx[i] >= 0) { + members[pos[coarse_idx[i]]++] = i; + } + } + } + + std::exception_ptr ex; + std::atomic interrupt{false}; +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (idx_t j = 0; j < idx_t(lists.size()); j++) { + if (interrupt) { + continue; + } + const idx_t list_no = lists[j]; + try { + add_to_list( + *this, + *il, + list_no, + members.data() + list_begin[list_no], + list_begin[list_no + 1] - list_begin[list_no], + x, + xids); + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + omp_rethrow_if_exception(ex); + ntotal += n; +} + +void IndexIVFRaBitQSSD::encode_vectors( + idx_t, + const float*, + const idx_t*, + uint8_t*, + bool) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: encode_vectors not supported"); +} + +void IndexIVFRaBitQSSD::search_preassigned( + idx_t n, + const float* x, + idx_t k, + const idx_t* assign, + const float* centroid_dis, + float* distances, + idx_t* labels, + bool store_pairs, + const IVFSearchParameters* params, + IndexIVFStats* stats) const { + FAISS_THROW_IF_NOT(k > 0); + const SearchSettings s = get_search_settings(*this, params, store_pairs); + const RaBitQSSDInvertedLists* il = get_ssd_invlists(); + + // queries are processed in parallel, unless the caller already does it + // (parallel_mode 0, as in IndexIVF::search) + const bool do_parallel = omp_get_max_threads() >= 2 && n > 1 && + (parallel_mode & ~PARALLEL_MODE_NO_HEAP_INIT) != 0; + + with_simd_level_with_vpopcnt([&]() { + search_impl( + *this, + *il, + n, + x, + k, + assign, + centroid_dis, + nullptr, + distances, + labels, + store_pairs, + s, + do_parallel, + stats); + }); +} + +void IndexIVFRaBitQSSD::search( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params_in) const { + FAISS_THROW_IF_NOT(k > 0); + const IVFSearchParameters* params = nullptr; + if (params_in) { + params = dynamic_cast(params_in); + FAISS_THROW_IF_NOT_MSG(params, "IndexIVF params have incorrect type"); + } + const SearchSettings s = get_search_settings(*this, params, false); + const RaBitQSSDInvertedLists* il = get_ssd_invlists(); + + // IndexIVF::search runs the coarse quantizer on all the queries before + // searching the lists, which leaves the SSD idle meanwhile. Here each + // thread runs it on its own query, while the other threads read. + const bool do_parallel = omp_get_max_threads() >= 2 && n > 1; + + with_simd_level_with_vpopcnt([&]() { + search_impl( + *this, + *il, + n, + x, + k, + nullptr, + nullptr, + params ? params->quantizer_params : nullptr, + distances, + labels, + false, + s, + do_parallel, + &indexIVF_stats); + }); +} + +void IndexIVFRaBitQSSD::range_search( + idx_t, + const float*, + float, + RangeSearchResult*, + const SearchParameters*) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: range search not supported"); +} + +void IndexIVFRaBitQSSD::range_search_preassigned( + idx_t, + const float*, + float, + const idx_t*, + const float*, + RangeSearchResult*, + bool, + const IVFSearchParameters*, + IndexIVFStats*) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: range search not supported"); +} + +void IndexIVFRaBitQSSD::reconstruct(idx_t, float*) const { + // IndexIVF::reconstruct would first ask for a direct map + FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported"); +} + +void IndexIVFRaBitQSSD::reconstruct_n(idx_t, idx_t, float*) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported"); +} + +void IndexIVFRaBitQSSD::search_and_reconstruct( + idx_t, + const float*, + idx_t, + float*, + idx_t*, + float*, + const SearchParameters*) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported"); +} + +void IndexIVFRaBitQSSD::search_and_return_codes( + idx_t, + const float*, + idx_t, + float*, + idx_t*, + uint8_t*, + bool, + const SearchParameters*) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: search_and_return_codes not supported"); +} + +void IndexIVFRaBitQSSD::reconstruct_from_offset(int64_t, int64_t, float*) + const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: reconstruct not supported"); +} + +size_t IndexIVFRaBitQSSD::remove_ids(const IDSelector&) { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: remove_ids not supported"); +} + +void IndexIVFRaBitQSSD::update_vectors(int, const idx_t*, const float*) { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: update_vectors not supported"); +} + +void IndexIVFRaBitQSSD::merge_from(Index&, idx_t) { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: merge_from not supported"); +} + +void IndexIVFRaBitQSSD::copy_subset_to( + IndexIVF&, + InvertedLists::subset_type_t, + idx_t, + idx_t) const { + FAISS_THROW_MSG("IndexIVFRaBitQSSD: copy_subset_to not supported"); +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.h b/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.h new file mode 100644 index 000000000..725fdcf2b --- /dev/null +++ b/thirdparty/faiss/faiss/IndexIVFRaBitQSSD.h @@ -0,0 +1,288 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +#include +#include + +namespace faiss { + +struct RaBitQSSDInvertedLists; + +struct IVFRaBitQSSDSearchParameters : IVFSearchParameters { + /// overrides IndexIVFRaBitQSSD::use_hacc + bool use_hacc = true; + /// overrides IndexIVFRaBitQSSD::drain_alpha + float drain_alpha = 1.0f; + /// overrides IndexIVFRaBitQSSD::qd_per_thread + size_t qd_per_thread = 16; +}; + +/** IVF index whose RaBitQ codes are split between memory and an SSD + * (RaBitQ-SSD). + * + * Reference: "RaBitQ-SSD: Split Codes and Pipelined I/O for SSD-Resident + * Vector Search", Yuexuan Xu et al. + * + * Vectors are encoded with RaBitQuantizer relative to the center of their + * list, with nb_bits bits per dimension: a sign bit and nb_bits - 1 extra + * bits. The sign bits of the first mem_dim dimensions stay in memory; the + * other sign bits, the extra bits and the vector ids are stored in a file, + * see RaBitQSSDInvertedLists. + * + * The center of a list is its centroid in the coarse quantizer, times + * centroid_scales[list_no] with METRIC_INNER_PRODUCT. With this metric, + * IndexIVF trains the quantizer with spherical k-means, so the centroids + * have norm 1. When the norms of the vectors are far from 1, the residuals + * to such centroids are large and the error bound is loose. train() + * therefore sets the scale of each list: its center is the multiple of the + * centroid closest to the mean of the list's training vectors. The centroids + * are not rescaled. An inner-product index must be trained even if the + * caller filled its quantizer. + * + * Search. Each search thread takes one query at a time, runs the coarse + * quantizer on it and scans the probed lists in batches of 32 vectors. For + * each vector, FastScan over its in-memory bits gives a distance estimate and + * a lower bound (the RaBitQ error bound). Vectors whose lower bound does not + * exceed the current k-th distance are grouped by page, and the pages are + * queued by their smallest lower bound. Between batches, the search re-ranks + * the pages whose reads completed and submits the most promising queued + * pages, keeping at most qd_per_thread reads in flight. After the last list, + * the remaining reads are drained. + * + * The distance estimates assume randomly rotated vectors, as for all RaBitQ + * indexes: use the index inside an IndexPreTransform with + * HadamardRotation(d, seed, false). + * + * The index is created without inverted lists: call attach_file() before + * adding or searching vectors. index_factory accepts + * "IVF,RaBitQSSD_", usually after the rotation: + * "HRk,IVF,RaBitQSSD_". Unlike in "RaBitQfs_", + * the number after the underscore is mem_dim, not a block size. + * + * The index works only with RaBitQSSDInvertedLists, whose layout (sign bits + * in memory, records in pages of a file) is the point of the index. These + * lists hold no flat codes, so the IVF operations that move codes between + * inverted lists are not supported: merge_from, copy_subset_to, and the + * HStack, VStack and Slice inverted-lists wrappers. + * + * Not supported either: remove_ids, update_vectors, range search, + * reconstruction, search_and_return_codes and standalone codes (sa_encode). + * Search parameters max_codes, max_lists_num, ensure_topk_full and + * max_empty_result_buckets throw; inverted_list_context is not used. + * read_index supports IO_FLAG_READ_ONLY and IO_FLAG_ONDISK_SAME_DIR, + * and rejects IO_FLAG_SKIP_IVF_DATA and IO_FLAG_MMAP. + */ +struct IndexIVFRaBitQSSD : IndexIVF { + /// most SSD reads a search thread can have in flight + static constexpr size_t kMaxReadsInFlight = 200; + + /// encodes the vectors; its nb_bits is the total number of bits per + /// dimension, in [2, 9] + RaBitQuantizer rabitq; + + /// dimensions whose sign bits stay in memory: a multiple of 64 in [64, d] + size_t mem_dim = 0; + + /// use 16-bit look-up tables for the in-memory scan (accumulate_hacc); + /// if false, 8-bit tables + bool use_hacc = true; + + /// after the last list, pages whose lower bound exceeds the + /// drain_alpha-quantile of the current results are not read. 1 keeps + /// the k-th distance as the threshold. Below 1, recall depends on the + /// load: only the pages still waiting to be read when the last list is + /// scanned are pruned this way, and more of them wait when the SSD is + /// saturated, so recall measured at low load overestimates it at high + /// load. + float drain_alpha = 1.0f; + + /// SSD reads in flight per search thread, at most kMaxReadsInFlight + size_t qd_per_thread = 16; + + /// squared norms of the centroids, needed to derive and |q - c| + /// from the coarse distances when the index or the quantizer uses the + /// inner product. Set by train() and add(). + std::vector centroid_norms; + + /// METRIC_INNER_PRODUCT only, empty otherwise: the codes of list l are + /// relative to centroid_scales[l] times centroid l of the quantizer. Set + /// by train() on an empty index. Reset the index and train it again + /// after changing the centroids. + std::vector centroid_scales; + + /** @param quantizer coarse quantizer, which must implement reconstruct. + * Tested with IndexFlat and IndexHNSWFlat. Raise the + * efSearch of an IndexHNSWFlat (e.g. to 256) before + * train() and add(): with the default, some vectors + * go to lists other than their nearest, which lowers + * recall at any nprobe short of nlist. + * @param d dimensionality, a multiple of 64 + * @param nlist number of lists + * @param mem_dim dimensions whose sign bits stay in memory + * @param nb_bits bits per dimension, in [2, 9] + * @param metric METRIC_L2 or METRIC_INNER_PRODUCT + */ + IndexIVFRaBitQSSD( + Index* quantizer, + size_t d, + size_t nlist, + size_t mem_dim, + uint8_t nb_bits, + MetricType metric = METRIC_L2); + + IndexIVFRaBitQSSD(); + + IndexIVFRaBitQSSD(const IndexIVFRaBitQSSD&) = delete; + IndexIVFRaBitQSSD& operator=(const IndexIVFRaBitQSSD&) = delete; + + /** Store the disk-resident part in a new file (created or truncated), + * replacing the inverted lists of an empty index. Its file system must + * support O_DIRECT. + */ + void attach_file(const char* filename); + + /// the inverted lists, or an exception if they are not of the right type + RaBitQSSDInvertedLists* get_ssd_invlists() const; + + /// empty the index, including when inverted lists have not been attached + void reset() override; + + /// sets centroid_norms and, for an empty METRIC_INNER_PRODUCT index, + /// centroid_scales + void train_encoder(idx_t n, const float* x, const idx_t* assign) override; + + void add_core( + idx_t n, + const float* x, + const idx_t* xids, + const idx_t* precomputed_idx, + void* inverted_list_context = nullptr) override; + + /// not supported: the codes are not stored as flat codes + void encode_vectors( + idx_t n, + const float* x, + const idx_t* list_nos, + uint8_t* codes, + bool include_listnos = false) const override; + + /** Unlike IndexIVF::search, which runs the coarse quantizer on all the + * queries first, each search thread runs it on its own query, so that it + * overlaps the reads of the other threads. The queries are searched in + * parallel whatever the parallel_mode. + */ + void search( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; + + void search_preassigned( + idx_t n, + const float* x, + idx_t k, + const idx_t* assign, + const float* centroid_dis, + float* distances, + idx_t* labels, + bool store_pairs, + const IVFSearchParameters* params = nullptr, + IndexIVFStats* stats = nullptr) const override; + + /// not supported + void range_search( + idx_t n, + const float* x, + float radius, + RangeSearchResult* result, + const SearchParameters* params = nullptr) const override; + + /// not supported + void range_search_preassigned( + idx_t nx, + const float* x, + float radius, + const idx_t* keys, + const float* coarse_dis, + RangeSearchResult* result, + bool store_pairs = false, + const IVFSearchParameters* params = nullptr, + IndexIVFStats* stats = nullptr) const override; + + /// not supported: the vectors are not stored, and their codes are + /// split between memory and the file + void reconstruct(idx_t key, float* recons) const override; + + /// not supported, see reconstruct + void reconstruct_n(idx_t i0, idx_t ni, float* recons) const override; + + /// not supported, see reconstruct + void search_and_reconstruct( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + float* recons, + const SearchParameters* params = nullptr) const override; + + /// not supported, see reconstruct + void search_and_return_codes( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + uint8_t* recons, + bool include_listno = false, + const SearchParameters* params = nullptr) const override; + + /// not supported, see reconstruct + void reconstruct_from_offset(int64_t list_no, int64_t offset, float* recons) + const override; + + /// not supported + size_t remove_ids(const IDSelector& sel) override; + + /// not supported + void update_vectors(int nv, const idx_t* idx, const float* v) override; + + /// not supported + void merge_from(Index& otherIndex, idx_t add_id) override; + + /// not supported + void copy_subset_to( + IndexIVF& other, + InvertedLists::subset_type_t subset_type, + idx_t a1, + idx_t a2) const override; + + /// recompute centroid_norms from the quantizer + void update_centroid_norms(); +}; + +/// Counters of IndexIVFRaBitQSSD searches, summed over all searches since +/// the last reset(). +struct IndexIVFRaBitQSSDStats { + size_t n_pages_read = 0; ///< pages read from the file + size_t n_reranked = 0; ///< vectors re-ranked with their full code + + void reset(); + void add(const IndexIVFRaBitQSSDStats& other); +}; + +FAISS_API extern IndexIVFRaBitQSSDStats indexIVFRaBitQSSD_stats; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/IndexIVFSQFastScan.cpp b/thirdparty/faiss/faiss/IndexIVFSQFastScan.cpp index 855fed48d..37c992d6f 100644 --- a/thirdparty/faiss/faiss/IndexIVFSQFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexIVFSQFastScan.cpp @@ -6,6 +6,7 @@ */ #include +#include #include @@ -29,107 +30,7 @@ namespace faiss { -namespace { - -size_t roundup(size_t a, size_t b) { - return (a + b - 1) / b * b; -} - -bool is_native_4bit(ScalarQuantizer::QuantizerType qtype) { - return qtype == ScalarQuantizer::QT_4bit || - qtype == ScalarQuantizer::QT_4bit_uniform; -} - -bool needs_rerank(ScalarQuantizer::QuantizerType qtype) { - return qtype == ScalarQuantizer::QT_6bit || - qtype == ScalarQuantizer::QT_8bit || - qtype == ScalarQuantizer::QT_8bit_uniform || - qtype == ScalarQuantizer::QT_8bit_direct || - qtype == ScalarQuantizer::QT_8bit_direct_signed; -} - -bool is_fallback(ScalarQuantizer::QuantizerType qtype) { - return !is_native_4bit(qtype) && !needs_rerank(qtype); -} - -bool is_uniform_range(ScalarQuantizer::QuantizerType qtype) { - return qtype == ScalarQuantizer::QT_8bit_uniform || - qtype == ScalarQuantizer::QT_8bit_direct || - qtype == ScalarQuantizer::QT_8bit_direct_signed; -} - -void get_uniform_range(const ScalarQuantizer& sq, float& vmin, float& vdiff) { - if (sq.qtype == ScalarQuantizer::QT_8bit_direct) { - vmin = 0; - vdiff = 255; - } else if (sq.qtype == ScalarQuantizer::QT_8bit_direct_signed) { - vmin = -128; - vdiff = 255; - } else { - vmin = sq.trained[0]; - vdiff = sq.trained[1]; - } -} - -void float_to_4bit_nibbles( - const float* x, - uint8_t* nibbles, - idx_t n, - int d, - int M2, - const ScalarQuantizer& sq) { - const bool is_uniform = is_uniform_range(sq.qtype) || - sq.qtype == ScalarQuantizer::QT_4bit_uniform; - const float* vmin_arr = nullptr; - const float* vdiff_arr = nullptr; - float vmin_s = 0, inv_vdiff_s = 0; - - if (is_uniform) { - float vdiff; - get_uniform_range(sq, vmin_s, vdiff); - inv_vdiff_s = (vdiff > 0) ? (1.0f / vdiff) : 0; - } else { - vmin_arr = sq.trained.data(); - vdiff_arr = sq.trained.data() + d; - } - - const int half = M2 / 2; - for (idx_t i = 0; i < n; i++) { - const float* xi = x + i * d; - uint8_t* dst = nibbles + i * half; - memset(dst, 0, half); - for (int m = 0; m + 1 < d; m += 2) { - float f0, f1; - if (is_uniform) { - f0 = (xi[m] - vmin_s) * inv_vdiff_s; - f1 = (xi[m + 1] - vmin_s) * inv_vdiff_s; - } else { - f0 = (vdiff_arr[m] > 0) ? (xi[m] - vmin_arr[m]) / vdiff_arr[m] - : 0; - f1 = (vdiff_arr[m + 1] > 0) - ? (xi[m + 1] - vmin_arr[m + 1]) / vdiff_arr[m + 1] - : 0; - } - uint8_t lo = (uint8_t)std::min(15, std::max(0, (int)(f0 * 15.0f))); - uint8_t hi = (uint8_t)std::min(15, std::max(0, (int)(f1 * 15.0f))); - dst[m / 2] = lo | (hi << 4); - } - if (d & 1) { - float f; - if (is_uniform) { - f = (xi[d - 1] - vmin_s) * inv_vdiff_s; - } else { - f = (vdiff_arr[d - 1] > 0) - ? (xi[d - 1] - vmin_arr[d - 1]) / vdiff_arr[d - 1] - : 0; - } - dst[(d - 1) / 2] = - (uint8_t)std::min(15, std::max(0, (int)(f * 15.0f))); - } - } -} - -} // anonymous namespace +using namespace faiss::sq_fastscan; // ----------------------------------------------------------------------- // Constructors @@ -174,8 +75,8 @@ IndexIVFSQFastScan::IndexIVFSQFastScan( new BlockInvertedLists(nlist_in, get_CodePacker()), true); if (needs_rerank(qtype)) { - orig_codes_invlists = - new ArrayInvertedLists(nlist_in, sq.code_size); + lo_codes_invlists = + new ArrayInvertedLists(nlist_in, sq_rerank_size(d, qtype)); direct_map.set_type(DirectMap::Hashtable, invlists, 0); } } @@ -235,7 +136,7 @@ IndexIVFSQFastScan::IndexIVFSQFastScan( replace_invlists(new BlockInvertedLists(nlist, get_CodePacker()), true); if (needs_rerank(sq.qtype)) { - orig_codes_invlists = new ArrayInvertedLists(nlist, sq.code_size); + lo_codes_invlists = new ArrayInvertedLists(nlist, lo_code_size()); direct_map.set_type(DirectMap::Hashtable, invlists, 0); } @@ -248,15 +149,7 @@ IndexIVFSQFastScan::IndexIVFSQFastScan( InvertedLists::ScopedCodes orig_codes(orig.invlists, list_no); InvertedLists::ScopedIds orig_ids(orig.invlists, list_no); - if (needs_rerank(sq.qtype)) { - orig_codes_invlists->add_entries( - list_no, list_size, orig_ids.get(), orig_codes.get()); - for (size_t j = 0; j < list_size; j++) { - direct_map.add_single_id(orig_ids.get()[j], list_no, j); - } - } - - // Decode to float and re-quantize to 4-bit. + // Decode to float and re-encode for the scan. std::vector recon(list_size * d); sq.decode(orig_codes.get(), recon.data(), list_size); @@ -264,8 +157,21 @@ IndexIVFSQFastScan::IndexIVFSQFastScan( if (is_native_4bit(sq.qtype)) { sq.compute_codes(recon.data(), flat4.data(), list_size); } else { - float_to_4bit_nibbles( - recon.data(), flat4.data(), list_size, d, M2, sq); + // Top 4 bits feed the scan, the rest are kept for rerank. + std::vector lo(list_size * lo_code_size(), 0); + float_to_split_codes( + recon.data(), + flat4.data(), + lo.data(), + list_size, + d, + M2, + sq); + lo_codes_invlists->add_entries( + list_no, list_size, orig_ids.get(), lo.data()); + for (size_t j = 0; j < list_size; j++) { + direct_map.add_single_id(orig_ids.get()[j], list_no, j); + } } BlockInvertedLists* bil = dynamic_cast(invlists); @@ -279,7 +185,7 @@ IndexIVFSQFastScan::IndexIVFSQFastScan( } IndexIVFSQFastScan::~IndexIVFSQFastScan() { - delete orig_codes_invlists; + delete lo_codes_invlists; } // ----------------------------------------------------------------------- @@ -328,7 +234,10 @@ void IndexIVFSQFastScan::encode_vectors( } else if (is_native_4bit(sq.qtype)) { sq.compute_codes(to_encode, codes_out, n); } else { - float_to_4bit_nibbles(to_encode, codes_out, n, d, M2, sq); + // add_core keeps the leftover bits in lo_codes_invlists. + std::vector lo_scratch(size_t(n) * lo_code_size()); + float_to_split_codes( + to_encode, codes_out, lo_scratch.data(), n, d, M2, sq); } if (include_listnos) { @@ -444,6 +353,34 @@ void IndexIVFSQFastScan::sa_decode(idx_t n, const uint8_t* bytes, float* x) } } +void IndexIVFSQFastScan::recombine_code( + int64_t list_no, + int64_t offset, + uint8_t* scratch, + int* values, + uint8_t* code_out) const { + // Interleaved for SIMD, so read one sub-quantizer at a time. + memset(scratch, 0, size_t(M2) / 2); + InvertedLists::ScopedCodes list_codes(invlists, list_no); + BitstringWriter bsw(scratch, M2 / 2); + for (size_t m = 0; m < M; m++) { + bsw.write( + pq4_get_packed_element(list_codes.get(), bbs, M2, offset, m), + 4); + } + InvertedLists::ScopedCodes lo(lo_codes_invlists, list_no); + split_to_codes( + scratch, lo.get() + offset * lo_code_size(), d, sq.qtype, values); + // BitstringWriter matches Codec6bit/Codec8bit, so distance_to_code reads + // it. + memset(code_out, 0, sq.code_size); + BitstringWriter out(code_out, sq.code_size); + const int bits = sq_bits(sq.qtype); + for (int m = 0; m < d; m++) { + out.write(values[m], bits); + } +} + void IndexIVFSQFastScan::reconstruct_from_offset( int64_t list_no, int64_t offset, @@ -452,10 +389,13 @@ void IndexIVFSQFastScan::reconstruct_from_offset( // Fallback: codes stored directly in invlists. InvertedLists::ScopedCodes codes(invlists, list_no); sq.decode(codes.get() + offset * sq.code_size, recons, 1); - } else if (orig_codes_invlists) { - // Rerank: use original full-precision codes for reconstruction. - InvertedLists::ScopedCodes codes(orig_codes_invlists, list_no); - sq.decode(codes.get() + offset * sq.code_size, recons, 1); + } else if (lo_codes_invlists) { + // Rerank: rebuild the original code from its two nibble halves. + std::vector scratch(M2 / 2), code(sq.code_size); + std::vector values(d); + recombine_code( + list_no, offset, scratch.data(), values.data(), code.data()); + sq.decode(code.data(), recons, 1); } else { // Native 4-bit: unpack from block inverted lists. std::vector code(M2 / 2, 0); @@ -500,10 +440,10 @@ void IndexIVFSQFastScan::search( if (is_fallback(sq.qtype)) { IndexIVF::search(n, x, k, distances, labels, params); } else if (needs_rerank(sq.qtype)) { - idx_t k_coarse = idx_t(k * rerank_factor); - if (k_coarse < k) { - k_coarse = k; - } + idx_t k_coarse = idx_t(double(k) * rerank_factor); + FAISS_THROW_IF_NOT(k_coarse >= k); + FAISS_THROW_IF_NOT_MSG( + n <= INT64_MAX / k_coarse, "n * k_coarse would overflow int64"); std::vector coarse_dis(n * k_coarse); std::vector coarse_ids(n * k_coarse); @@ -515,6 +455,8 @@ void IndexIVFSQFastScan::search( { std::unique_ptr dc( sq.get_distance_computer(metric_type)); + std::vector scratch(M2 / 2), code(sq.code_size); + std::vector values(d); #pragma omp for for (idx_t i = 0; i < n; i++) { @@ -540,10 +482,13 @@ void IndexIVFSQFastScan::search( idx_t list_no = lo_listno(lo); idx_t offset = lo_offset(lo); - InvertedLists::ScopedCodes codes( - orig_codes_invlists, list_no); - float dis = dc->distance_to_code( - codes.get() + offset * sq.code_size); + recombine_code( + list_no, + offset, + scratch.data(), + values.data(), + code.data()); + float dis = dc->distance_to_code(code.data()); if (metric_type == METRIC_L2) { if (dis < heap_dis[0]) { @@ -592,10 +537,10 @@ void IndexIVFSQFastScan::search_preassigned( params, stats); } else if (needs_rerank(sq.qtype)) { - idx_t k_coarse = idx_t(k * rerank_factor); - if (k_coarse < k) { - k_coarse = k; - } + idx_t k_coarse = idx_t(double(k) * rerank_factor); + FAISS_THROW_IF_NOT(k_coarse >= k); + FAISS_THROW_IF_NOT_MSG( + n <= INT64_MAX / k_coarse, "n * k_coarse would overflow int64"); std::vector coarse_dis(n * k_coarse); std::vector coarse_ids(n * k_coarse); @@ -615,6 +560,8 @@ void IndexIVFSQFastScan::search_preassigned( { std::unique_ptr dc( sq.get_distance_computer(metric_type)); + std::vector scratch(M2 / 2), code(sq.code_size); + std::vector values(d); #pragma omp for for (idx_t i = 0; i < n; i++) { @@ -639,19 +586,27 @@ void IndexIVFSQFastScan::search_preassigned( idx_t lo = direct_map.get(id); idx_t list_no = lo_listno(lo); idx_t offset = lo_offset(lo); - - InvertedLists::ScopedCodes codes( - orig_codes_invlists, list_no); - float dis = dc->distance_to_code( - codes.get() + offset * sq.code_size); + // callers that ask for store_pairs (eg. + // search_and_reconstruct) expect (list_no, offset) pairs + idx_t label = store_pairs ? lo : id; + + recombine_code( + list_no, + offset, + scratch.data(), + values.data(), + code.data()); + float dis = dc->distance_to_code(code.data()); if (metric_type == METRIC_L2) { if (dis < heap_dis[0]) { - maxheap_replace_top(k, heap_dis, heap_ids, dis, id); + maxheap_replace_top( + k, heap_dis, heap_ids, dis, label); } } else { if (dis > heap_dis[0]) { - minheap_replace_top(k, heap_dis, heap_ids, dis, id); + minheap_replace_top( + k, heap_dis, heap_ids, dis, label); } } } @@ -710,6 +665,8 @@ void IndexIVFSQFastScan::range_search( std::unique_ptr dc( sq.get_distance_computer(metric_type)); + std::vector scratch(M2 / 2), code(sq.code_size); + std::vector values(d); #pragma omp for for (idx_t i = 0; i < n; i++) { @@ -721,20 +678,23 @@ void IndexIVFSQFastScan::range_search( if (list_no < 0) { continue; } - size_t list_size = orig_codes_invlists->list_size(list_no); + size_t list_size = lo_codes_invlists->list_size(list_no); if (list_size == 0) { continue; } - InvertedLists::ScopedCodes codes( - orig_codes_invlists, list_no); - InvertedLists::ScopedIds ids(orig_codes_invlists, list_no); + InvertedLists::ScopedIds ids(lo_codes_invlists, list_no); for (size_t j = 0; j < list_size; j++) { if (sel && !sel->is_member(ids[j])) { continue; } - float dis = dc->distance_to_code( - codes.get() + j * sq.code_size); + recombine_code( + list_no, + j, + scratch.data(), + values.data(), + code.data()); + float dis = dc->distance_to_code(code.data()); if (metric_type == METRIC_L2) { if (dis < radius) { qres.add(dis, ids[j]); @@ -800,28 +760,28 @@ void IndexIVFSQFastScan::add_with_ids( AlignedTable flat_codes(n * code_size); encode_vectors(n, x, idx.get(), flat_codes.get()); - // Store original SQ codes for rerank types - std::vector orig_flat_codes; + // Same quantisation as encode_vectors, or the halves disagree. + std::vector lo_flat_codes; if (needs_rerank(sq.qtype)) { - orig_flat_codes.resize(n * sq.code_size); + std::vector to_encode(size_t(n) * d); for (idx_t i = 0; i < n; i++) { - if (idx[i] < 0) { - continue; - } - if (by_residual) { - std::vector residual(d); - quantizer->compute_residual(x + i * d, residual.data(), idx[i]); - sq.compute_codes( - residual.data(), - orig_flat_codes.data() + i * sq.code_size, - 1); + if (by_residual && idx[i] >= 0) { + quantizer->compute_residual( + x + i * d, to_encode.data() + i * d, idx[i]); } else { - sq.compute_codes( - x + i * d, - orig_flat_codes.data() + i * sq.code_size, - 1); + memcpy(to_encode.data() + i * d, x + i * d, sizeof(float) * d); } } + lo_flat_codes.assign(size_t(n) * lo_code_size(), 0); + std::vector hi_discard(size_t(n) * (M2 / 2)); + float_to_split_codes( + to_encode.data(), + hi_discard.data(), + lo_flat_codes.data(), + n, + d, + M2, + sq); } // Sort by list assignment @@ -862,10 +822,10 @@ void IndexIVFSQFastScan::add_with_ids( code_size); if (needs_rerank(sq.qtype)) { - orig_codes_invlists->add_entry( + lo_codes_invlists->add_entry( list_no, id, - orig_flat_codes.data() + order[i] * sq.code_size); + lo_flat_codes.data() + order[i] * lo_code_size()); direct_map.add_single_id(id, list_no, ofs); } } @@ -889,9 +849,9 @@ void IndexIVFSQFastScan::add_with_ids( void IndexIVFSQFastScan::reset() { IndexIVFFastScan::reset(); - if (orig_codes_invlists) { + if (lo_codes_invlists) { for (size_t i = 0; i < nlist; i++) { - orig_codes_invlists->resize(i, 0); + lo_codes_invlists->resize(i, 0); } direct_map.clear(); } diff --git a/thirdparty/faiss/faiss/IndexIVFSQFastScan.h b/thirdparty/faiss/faiss/IndexIVFSQFastScan.h index a1a0b1397..c3c4ace16 100644 --- a/thirdparty/faiss/faiss/IndexIVFSQFastScan.h +++ b/thirdparty/faiss/faiss/IndexIVFSQFastScan.h @@ -10,6 +10,7 @@ #include #include #include +#include namespace faiss { @@ -29,10 +30,8 @@ namespace faiss { * ScalarQuantizer's own SIMD-optimised InvertedListScanner (same * behavior as IndexIVFScalarQuantizer, no fast-scan acceleration). * - * For reranked types, both the original full-precision codes and the - * packed 4-bit codes are stored in the inverted lists. The block - * inverted lists hold packed 4-bit codes; original codes are stored - * in a parallel ArrayInvertedLists (orig_codes_invlists). + * For reranked types the block inverted lists hold the packed high nibbles + * and a parallel ArrayInvertedLists (lo_codes_invlists) holds the low ones. */ struct IndexIVFSQFastScan : IndexIVFFastScan { ScalarQuantizer sq; @@ -40,10 +39,25 @@ struct IndexIVFSQFastScan : IndexIVFFastScan { /// Overselection ratio for reranking (default 2). float rerank_factor = 2; - /// Parallel inverted lists storing original SQ codes (for rerank - /// types). Owned by this index. nullptr for native 4-bit and - /// fallback types. - InvertedLists* orig_codes_invlists = nullptr; + /// Parallel inverted lists holding the leftover low bits of each code. + /// The top 4 bits of every code live in the packed scan blocks. + /// Owned by this index. nullptr for native 4-bit and fallback types. + InvertedLists* lo_codes_invlists = nullptr; + + /// Bytes per vector in lo_codes_invlists: the bits of each code left + /// over once the scan has taken the top 4. + size_t lo_code_size() const { + return sq_fastscan::sq_rerank_size(d, sq.qtype); + } + + /// Rebuild the code at (list_no, offset) from its two halves. `scratch` + /// needs M2 / 2 bytes, `code_out` needs sq.code_size. + void recombine_code( + int64_t list_no, + int64_t offset, + uint8_t* scratch, + int* values, + uint8_t* code_out) const; IndexIVFSQFastScan( Index* quantizer, diff --git a/thirdparty/faiss/faiss/IndexNNDescent.cpp b/thirdparty/faiss/faiss/IndexNNDescent.cpp index 0df622bfd..f2a950407 100644 --- a/thirdparty/faiss/faiss/IndexNNDescent.cpp +++ b/thirdparty/faiss/faiss/IndexNNDescent.cpp @@ -14,11 +14,9 @@ #include #include -#ifdef __SSE__ -#endif - #include #include +#include #include #include @@ -176,6 +174,26 @@ void IndexNNDescent::add(idx_t n, const float* x) { storage->add(n, x); ntotal = storage->ntotal; + if (nndescent.deterministic) { + FAISS_THROW_IF_NOT_FMT( + ntotal > nndescent.K, + "IndexNNDescent: need more than K = %d vectors", + nndescent.K); + // NNDescent::search indexes final_graph with int + FAISS_THROW_IF_NOT_MSG( + ntotal * nndescent.K < (idx_t(1) << 31), + "IndexNNDescent: ntotal * K must be < 2^31"); + DeterministicNNDescent dnd; + dnd.K = nndescent.K; + dnd.max_rounds = nndescent.iter; + dnd.seed = nndescent.random_seed; + dnd.verbose = verbose; + dnd.build(*storage); + nndescent.final_graph = std::move(dnd.ids); + nndescent.ntotal = static_cast(ntotal); + nndescent.has_built = true; + return; + } std::unique_ptr dis(storage_distance_computer(storage)); nndescent.build(*dis, static_cast(ntotal), verbose); } diff --git a/thirdparty/faiss/faiss/IndexPiPNN.cpp b/thirdparty/faiss/faiss/IndexPiPNN.cpp new file mode 100644 index 000000000..549e874b3 --- /dev/null +++ b/thirdparty/faiss/faiss/IndexPiPNN.cpp @@ -0,0 +1,201 @@ +/* + * 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. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace faiss { + +IndexPiPNN::IndexPiPNN() = default; + +IndexPiPNN::IndexPiPNN(Index* storage_in, int R) + : pipnn(R), storage(storage_in) { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + check_storage_supported(*storage); + d = storage->d; + metric_type = storage->metric_type; + is_trained = storage->is_trained; + ntotal = storage->ntotal; +} + +IndexPiPNN::~IndexPiPNN() { + if (own_fields) { + delete storage; + } +} + +void IndexPiPNN::train(idx_t n, const float* x) { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + storage->train(n, x); + is_trained = storage->is_trained; +} + +void IndexPiPNN::add(idx_t n, const float* x) { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + FAISS_THROW_IF_MSG( + is_built(), "IndexPiPNN does not support incremental addition"); + storage->add(n, x); + ntotal = storage->ntotal; + if (!defer_build && ntotal > 0) { + build(); + } +} + +void IndexPiPNN::build() { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + check_storage_supported(*storage); + FAISS_THROW_IF_NOT_MSG( + storage->ntotal > 0, "IndexPiPNN: cannot build over 0 vectors"); + pipnn.build(*storage, verbose); + ntotal = storage->ntotal; +} + +void IndexPiPNN::search( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + FAISS_THROW_IF_NOT(k > 0); + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + FAISS_THROW_IF_NOT_MSG( + storage->is_trained, + "IndexPiPNN: storage must be trained before search()"); + FAISS_THROW_IF_NOT_MSG( + pipnn.ntotal == ntotal && storage->ntotal == ntotal, + "IndexPiPNN: the index is not built over its storage; call " + "build()"); + const auto* pipnn_params = + dynamic_cast(params); + const int search_L = pipnn_params && pipnn_params->search_L != 0 + ? pipnn_params->search_L + : pipnn.search_L; + const IDSelector* sel = params ? params->sel : nullptr; + const bool negate = metric_type == METRIC_INNER_PRODUCT; + + const idx_t check_period = + InterruptCallback::get_period_hint( + size_t(d) * size_t(std::max(idx_t(search_L), k))) * + omp_get_max_threads(); + + for (idx_t i0 = 0; i0 < n; i0 += check_period) { + const idx_t i1 = std::min(i0 + check_period, n); + std::exception_ptr ex; + std::atomic interrupt{false}; + +#pragma omp parallel if (i1 - i0 > 1) + { + VisitedTable* vt = nullptr; + std::unique_ptr dis; + try { + vt = &VisitedTable::get_reusable(ntotal, use_visited_hashset); + dis.reset( + negate ? new NegativeDistanceComputer( + storage->get_distance_computer()) + : storage->get_distance_computer()); + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + +#pragma omp for schedule(guided) + for (idx_t i = i0; i < i1; i++) { + if (interrupt.load(std::memory_order_relaxed)) { + continue; + } + try { + dis->set_query(x + i * d); + pipnn.search( + *dis, + search_L, + k, + labels + i * k, + distances + i * k, + *vt, + sel); + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + } + omp_rethrow_if_exception(ex); + InterruptCallback::check(); + } + + if (negate) { + for (idx_t i = 0; i < n * k; i++) { + distances[i] = -distances[i]; + } + } +} + +void IndexPiPNN::reconstruct(idx_t key, float* recons) const { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + storage->reconstruct(key, recons); +} + +void IndexPiPNN::reset() { + FAISS_THROW_IF_NOT_MSG(storage, "IndexPiPNN has no storage"); + storage->reset(); + pipnn.reset(); + ntotal = 0; +} + +void IndexPiPNN::check_storage_supported(const Index& storage) { + const std::type_info& t = typeid(storage); + bool ok = t == typeid(IndexFlat) || t == typeid(IndexFlatL2) || + t == typeid(IndexFlatIP); + if (t == typeid(IndexScalarQuantizer)) { + const auto qt = + static_cast(storage).sq.qtype; + ok = qt != ScalarQuantizer::QT_0bit && + !ScalarQuantizer::TurboQuantRefine::is_turboq_full(qt); + } + ok = ok && + (storage.metric_type == METRIC_L2 || + storage.metric_type == METRIC_INNER_PRODUCT); + FAISS_THROW_IF_NOT_FMT( + ok, + "IndexPiPNN: unsupported storage %s; use IndexFlat or " + "IndexScalarQuantizer (not QT_0bit or QT_*bit_tq), L2 or IP", + demangle_cpp_symbol(t.name()).c_str()); +} + +IndexPiPNNFlat::IndexPiPNNFlat() = default; + +IndexPiPNNFlat::IndexPiPNNFlat(int d_in, int R, MetricType metric) + : IndexPiPNN(new IndexFlat(d_in, metric), R) { + own_fields = true; +} + +IndexPiPNNSQ::IndexPiPNNSQ() = default; + +IndexPiPNNSQ::IndexPiPNNSQ( + int d_in, + ScalarQuantizer::QuantizerType qtype, + int R, + MetricType metric) + : IndexPiPNN(new IndexScalarQuantizer(d_in, qtype, metric), R) { + own_fields = true; +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/IndexPiPNN.h b/thirdparty/faiss/faiss/IndexPiPNN.h new file mode 100644 index 000000000..d0c8bffba --- /dev/null +++ b/thirdparty/faiss/faiss/IndexPiPNN.h @@ -0,0 +1,83 @@ +/* + * 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. + */ + +#pragma once + +#include + +#include +#include +#include + +namespace faiss { + +struct SearchParametersPiPNN : SearchParameters { + /// beam width L; if 0, pipnn.search_L is used + int search_L = 0; +}; + +/** The PiPNN index is a normal random-access index with a PiPNN graph built + * on top of a flat storage (IndexFlat or IndexScalarQuantizer). */ +struct IndexPiPNN : Index { + PiPNN pipnn; + Index* storage = nullptr; + bool own_fields = false; + /// if true, add() only appends to storage; call build() afterwards + bool defer_build = false; + /// See impl/VisitedTable.h. + std::optional use_visited_hashset; + + IndexPiPNN(); + IndexPiPNN(Index* storage, int R = 64); + + ~IndexPiPNN() override; + + void train(idx_t n, const float* x) override; + + void add(idx_t n, const float* x) override; + + /// Builds the graph over all vectors in storage. + void build(); + + bool is_built() const { + return pipnn.ntotal > 0; + } + + void search( + idx_t n, + const float* x, + idx_t k, + float* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; + + void reconstruct(idx_t key, float* recons) const override; + + /// Empties storage (whatever own_fields says) and drops the graph. + void reset() override; + + /// Throws unless IndexPiPNN supports the type and metric of `storage`. + static void check_storage_supported(const Index& storage); +}; + +/// IndexPiPNN over an owned IndexFlat. +struct IndexPiPNNFlat : IndexPiPNN { + IndexPiPNNFlat(); + IndexPiPNNFlat(int d, int R, MetricType metric = METRIC_L2); +}; + +/// IndexPiPNN over an owned IndexScalarQuantizer. +struct IndexPiPNNSQ : IndexPiPNN { + IndexPiPNNSQ(); + IndexPiPNNSQ( + int d, + ScalarQuantizer::QuantizerType qtype, + int R, + MetricType metric = METRIC_L2); +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/IndexRaBitQ.cpp b/thirdparty/faiss/faiss/IndexRaBitQ.cpp index a41133fa4..36b621fc2 100644 --- a/thirdparty/faiss/faiss/IndexRaBitQ.cpp +++ b/thirdparty/faiss/faiss/IndexRaBitQ.cpp @@ -81,12 +81,175 @@ FlatCodesDistanceComputer* IndexRaBitQ::get_quantized_distance_computer( namespace { +// Whether resi.add_result would keep dis +template +bool beats_threshold(const ResultHandlerT& resi, float dis) { + return C::cmp(resi.threshold, dis); +} + +// Single-stage search: the estimate is the distance. It is the full distance +// for the multi-bit codes that range_search scans this way. +template +struct OneStage { + RaBitQDistanceComputer& dc; + ResultHandler& resi; + const uint8_t* codes; + size_t code_size; + + const uint8_t* code(size_t i) const { + return codes + i * code_size; + } + + float estimate(size_t i) { + return dc.nb_bits == 1 ? dc.distance_to_code_1bit(code(i)) + : dc.distance_to_code_full(code(i)); + } + + void estimate_batch_4(size_t i, float* dis) { + if (dc.nb_bits > 1) { + for (size_t j = 0; j < 4; j++) { + dis[j] = estimate(i + j); + } + return; + } + const uint8_t* batch[4] = { + code(i), code(i + 1), code(i + 2), code(i + 3)}; + dc.distance_to_code_1bit_batch_4(batch, dis); + } + + bool passes(size_t, float dis) const { + return beats_threshold(resi, dis); + } + + void add(size_t i, float dis) { + resi.add_result(dis, i); + } +}; + +// Two-stage search of multi-bit codes: the full distance is computed only +// when the error bound of the 1-bit estimate reaches past the threshold. +template +struct TwoStage { + RaBitQDistanceComputer& dc; + ResultHandler& resi; + const uint8_t* codes; + size_t code_size; + bool is_similarity; + + const uint8_t* code(size_t i) const { + return codes + i * code_size; + } + + float estimate(size_t i) { + return dc.distance_to_code_1bit(code(i)); + } + + void estimate_batch_4(size_t i, float* dis) { + const uint8_t* batch[4] = { + code(i), code(i + 1), code(i + 2), code(i + 3)}; + dc.distance_to_code_1bit_batch_4(batch, dis); + } + + bool passes(size_t i, float est_distance) const { + return dc.should_refine( + code(i), est_distance, resi.threshold, is_similarity); + } + + void add(size_t i, float) { + resi.add_result(dc.distance_to_code_full(code(i)), i); + } +}; + +// Search without a selector, estimating four codes at a time +template +void scan_all(size_t ntotal, Stage& stage) { + size_t i = 0; + for (; i + 4 <= ntotal; i += 4) { + float dis[4]; + stage.estimate_batch_4(i, dis); + for (size_t j = 0; j < 4; j++) { + if (stage.passes(i + j, dis[j])) { + stage.add(i + j, dis[j]); + } + } + } + for (; i < ntotal; i++) { + float dis = stage.estimate(i); + if (stage.passes(i, dis)) { + stage.add(i, dis); + } + } +} + +// Search that tests the selector before each estimate +template +void scan_sel_first( + size_t ntotal, + const InSelection& in_selection, + Stage& stage) { + for (size_t i = 0; i < ntotal; i++) { + if (in_selection(i)) { + float dis = stage.estimate(i); + if (stage.passes(i, dis)) { + stage.add(i, dis); + } + } + } +} + +// Search that tests the selector after the estimate while at most a third of +// the estimates in the last window passed, and before it otherwise. Testing +// after skips the selector for the codes that fail, but estimates codes that +// the selector would reject. The results are the same either way. Until the +// results fill up, every estimate passes, so the selector starts first. +// Testing after, codes are estimated four at a time; the window is a multiple +// of four, so the batches end on window boundaries. +template +void scan_sel_after_distance( + size_t ntotal, + const InSelection& in_selection, + Stage& stage) { + constexpr size_t window = 64; + bool sel_after = false; + size_t estimated = 0; + size_t passed = 0; + auto take = [&](size_t i, float dis) { + estimated++; + if (stage.passes(i, dis)) { + passed++; + if (!sel_after || in_selection(i)) { + stage.add(i, dis); + } + } + }; + for (size_t i = 0; i < ntotal;) { + if (sel_after && i + 4 <= ntotal) { + float dis[4]; + stage.estimate_batch_4(i, dis); + for (size_t j = 0; j < 4; j++, i++) { + take(i, dis[j]); + } + } else { + if (sel_after || in_selection(i)) { + take(i, stage.estimate(i)); + } + i++; + } + if (estimated >= window) { + sel_after = 3 * passed <= window; + estimated = 0; + passed = 0; + } + } +} + struct Run_search_with_dc_res { using T = void; uint8_t qb = 0; bool centered = false; uint8_t nb_bits = 1; // Number of bits per dimension + bool sel_after_distance = false; template void f(BlockResultHandler& res, const IndexRaBitQ* index, const float* xq) { @@ -95,11 +258,24 @@ struct Run_search_with_dc_res { typename BlockResultHandler::SingleResultHandler; const int d = index->d; size_t ex_bits = nb_bits - 1; + auto in_selection = [&res](size_t i) { return res.is_in_selection(i); }; + auto scan = [&](auto& stage) { + if (res.sel == nullptr) { + scan_all(ntotal, stage); + } else if (sel_after_distance) { + scan_sel_after_distance(ntotal, in_selection, stage); + } else { + scan_sel_first(ntotal, in_selection, stage); + } + }; #pragma omp parallel { std::unique_ptr dc_base( index->get_quantized_distance_computer(qb, centered)); + auto* dc = dynamic_cast(dc_base.get()); + FAISS_ASSERT_MSG( + dc, "Failed to cast to RaBitQDistanceComputer for search"); SingleResultHandler resi(res); #pragma omp for for (int64_t q = 0; q < static_cast(res.nq); q++) { @@ -108,56 +284,25 @@ struct Run_search_with_dc_res { if (ex_bits == 0) { // 1-bit: Standard single-stage search - for (size_t i = 0; i < ntotal; i++) { - if (res.is_in_selection(i)) { - float dis = (*dc_base)(i); - resi.add_result(dis, i); - } - } + OneStage stage{ + *dc, resi, index->codes.data(), index->code_size}; + scan(stage); } else { // Multi-bit: Two-stage search with adaptive filtering // Note: Even with query quantization (qb > 0), ex-bits // distance computation uses the float query to maintain // consistency with encoding-time factor computation. See // RaBitQuantizer.cpp for details. - auto* dc = dynamic_cast( - dc_base.get()); - FAISS_THROW_IF_MSG( - dc == nullptr, - "Failed to cast to RaBitQDistanceComputer for two-stage search"); - bool is_similarity = is_similarity_metric(index->metric_type); - for (size_t i = 0; i < ntotal; i++) { - if (res.is_in_selection(i)) { - const uint8_t* code = - index->codes.data() + i * index->code_size; - - float est_distance = - dc->distance_to_code_1bit(code); - - size_t code_size_base = (index->d + 7) / 8; - const rabitq_utils::SignBitFactorsWithError* - base_fac = reinterpret_cast< - const rabitq_utils:: - SignBitFactorsWithError*>( - code + code_size_base); - - bool should_refine = - rabitq_utils::should_refine_candidate( - est_distance, - base_fac->f_error, - dc->g_error, - resi.threshold, - is_similarity); - if (should_refine) { - float dist_full = - dc->distance_to_code_full(code); - resi.add_result(dist_full, i); - } - } - } + TwoStage stage{ + *dc, + resi, + index->codes.data(), + index->code_size, + is_similarity}; + scan(stage); } resi.end(); @@ -180,9 +325,11 @@ void IndexRaBitQ::search( // Extract search parameters uint8_t used_qb = qb; bool used_centered = centered; + bool sel_after_distance = false; if (auto params = dynamic_cast(params_in)) { used_qb = params->qb; used_centered = params->centered; + sel_after_distance = params->sel_after_distance; } const IDSelector* sel = (params_in != nullptr) ? params_in->sel : nullptr; @@ -192,6 +339,7 @@ void IndexRaBitQ::search( r.qb = used_qb; r.centered = used_centered; r.nb_bits = rabitq.nb_bits; // Pass multi-bit info to functor + r.sel_after_distance = sel_after_distance; // Use Faiss framework for all cases (single-stage and two-stage) dispatch_knn_ResultHandler( diff --git a/thirdparty/faiss/faiss/IndexRaBitQ.h b/thirdparty/faiss/faiss/IndexRaBitQ.h index e6a48a6e0..2c33e1341 100644 --- a/thirdparty/faiss/faiss/IndexRaBitQ.h +++ b/thirdparty/faiss/faiss/IndexRaBitQ.h @@ -15,6 +15,11 @@ namespace faiss { struct RaBitQSearchParameters : SearchParameters { uint8_t qb = 4; bool centered = false; + // test sel after a code's distance rather than before it, while at most a + // third of the distances beat the threshold. Same results; it pays off + // when sel costs about 1.5x a distance or more. Used by search, not + // range_search. qb and centered above replace the index's own values. + bool sel_after_distance = false; }; struct IndexRaBitQ : IndexFlatCodes { diff --git a/thirdparty/faiss/faiss/IndexRaBitQFastScan.cpp b/thirdparty/faiss/faiss/IndexRaBitQFastScan.cpp index 8dacbd6a5..4a49a6a6f 100644 --- a/thirdparty/faiss/faiss/IndexRaBitQFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexRaBitQFastScan.cpp @@ -92,7 +92,7 @@ size_t IndexRaBitQFastScan::remove_ids(const IDSelector& sel) { if (last_pos > 0) { const size_t last_block = ntotal / bbs; std::vector zero_code(code_size, 0); - for (size_t pos = last_pos; pos < bbs; pos++) { + for (size_t pos = last_pos; pos < static_cast(bbs); pos++) { packer->pack_1( zero_code.data(), last_block * bbs + pos, codes.data()); } @@ -512,7 +512,8 @@ void IndexRaBitQFastScan::search( float* distances, idx_t* labels, const SearchParameters* params) const { - FAISS_THROW_IF_MSG(params, "search params not supported for this index"); + // The kernel applies the selector after each SIMD block. + const IDSelector* rabitq_sel = params ? params->sel : nullptr; // Create query factors array on stack - memory managed by caller std::vector query_factors_storage(n); @@ -523,9 +524,11 @@ void IndexRaBitQFastScan::search( FastScanDistancePostProcessing context; context.query_factors = query_factors_storage.data(); if (metric_type == METRIC_L2) { - search_dispatch_implem(n, x, k, distances, labels, context); + search_dispatch_implem( + n, x, k, distances, labels, context, rabitq_sel); } else { - search_dispatch_implem(n, x, k, distances, labels, context); + search_dispatch_implem( + n, x, k, distances, labels, context, rabitq_sel); } } diff --git a/thirdparty/faiss/faiss/IndexRaBitQFastScan.h b/thirdparty/faiss/faiss/IndexRaBitQFastScan.h index 8a1891cd6..e671ab86f 100644 --- a/thirdparty/faiss/faiss/IndexRaBitQFastScan.h +++ b/thirdparty/faiss/faiss/IndexRaBitQFastScan.h @@ -195,16 +195,19 @@ struct RaBitQHeapHandler float* const heap_dis = heap_distances + q * k; int64_t* const heap_ids = heap_labels + q * k; - rabitq_utils::QueryFactorsData query_factors_data = {}; - if (context && context->query_factors != nullptr) { - query_factors_data = context->query_factors[q]; - } + // Not a copy: QueryFactorsData owns a std::vector (malloc per block). + static const rabitq_utils::QueryFactorsData kNoQueryFactors{}; + const rabitq_utils::QueryFactorsData& query_factors_data = + (context && context->query_factors != nullptr) + ? context->query_factors[q] + : kNoQueryFactors; const float one_a = normalizers ? (1.0f / normalizers[2 * q]) : 1.0f; const float bias = normalizers ? normalizers[2 * q + 1] : 0.0f; const size_t base_db_idx = this->j0 + b * 32; - const size_t max_vectors = (base_db_idx < rabitq_index->ntotal) + const size_t max_vectors = + (base_db_idx < static_cast(rabitq_index->ntotal)) ? std::min(32, rabitq_index->ntotal - base_db_idx) : 0; @@ -218,6 +221,10 @@ struct RaBitQHeapHandler for (size_t i = 0; i < max_vectors; i++) { const size_t db_idx = base_db_idx + i; + if (this->sel != nullptr && + !this->sel->is_member(static_cast(db_idx))) { + continue; + } const float normalized_distance = d32tab[i] * one_a + bias; const uint8_t* base_ptr = aux_base + i * storage_size; @@ -288,7 +295,6 @@ struct RaBitQHeapHandler } } - private: float compute_full_multibit_distance(size_t db_idx, size_t q) { const size_t ex_bits = rabitq_index->rabitq.nb_bits - 1; const size_t dim = rabitq_index->d; diff --git a/thirdparty/faiss/faiss/IndexReplicas.cpp b/thirdparty/faiss/faiss/IndexReplicas.cpp index 96ec2ac0f..05d46ec30 100644 --- a/thirdparty/faiss/faiss/IndexReplicas.cpp +++ b/thirdparty/faiss/faiss/IndexReplicas.cpp @@ -111,6 +111,26 @@ void IndexReplicasTemplate::add(idx_t n, const component_t* x) { syncWithSubIndexes(); } +template +void IndexReplicasTemplate::add_with_ids( + idx_t n, + const component_t* x, + const idx_t* xids) { + this->runOnIndex([n, x, xids](int, IndexT* index) { + index->add_with_ids(n, x, xids); + }); + syncWithSubIndexes(); +} + +template +size_t IndexReplicasTemplate::remove_ids(const IDSelector& sel) { + const idx_t before = this->ntotal; + this->runOnIndex([&sel](int, IndexT* index) { index->remove_ids(sel); }); + // Throws when the replicas removed different counts. + syncWithSubIndexes(); + return before - this->ntotal; +} + template void IndexReplicasTemplate::reconstruct(idx_t n, component_t* x) const { FAISS_THROW_IF_NOT_MSG(this->count() > 0, "no replicas in index"); diff --git a/thirdparty/faiss/faiss/IndexReplicas.h b/thirdparty/faiss/faiss/IndexReplicas.h index c3430eef2..e22aa0641 100644 --- a/thirdparty/faiss/faiss/IndexReplicas.h +++ b/thirdparty/faiss/faiss/IndexReplicas.h @@ -56,6 +56,15 @@ class IndexReplicasTemplate : public ThreadedIndex { /// All indices receive the same call void add(idx_t n, const component_t* x) override; + /// faiss::Index API + /// All indices receive the same call + void add_with_ids(idx_t n, const component_t* x, const idx_t* xids) + override; + + /// faiss::Index API + /// All indices receive the same call + size_t remove_ids(const IDSelector& sel) override; + /// faiss::Index API /// Query is partitioned into a slice for each sub-index /// split by ceil(n / #indices) for our sub-indices diff --git a/thirdparty/faiss/faiss/IndexSQFastScan.cpp b/thirdparty/faiss/faiss/IndexSQFastScan.cpp index 0fbf66e3c..591a87cec 100644 --- a/thirdparty/faiss/faiss/IndexSQFastScan.cpp +++ b/thirdparty/faiss/faiss/IndexSQFastScan.cpp @@ -6,6 +6,7 @@ */ #include +#include #include @@ -14,7 +15,6 @@ #include #include -#include #include #include #include @@ -24,24 +24,12 @@ #include #include #include -#include #include #include namespace faiss { -namespace { - -size_t roundup(size_t a, size_t b) { - return (a + b - 1) / b * b; -} - -bool is_native_4bit(ScalarQuantizer::QuantizerType qtype) { - return qtype == ScalarQuantizer::QT_4bit || - qtype == ScalarQuantizer::QT_4bit_uniform; -} - -} // anonymous namespace +using namespace faiss::sq_fastscan; // ----------------------------------------------------------------------- // Constructors @@ -54,10 +42,10 @@ IndexSQFastScan::IndexSQFastScan( int bbs_in) : sq(d_in, qtype) { FAISS_THROW_IF_NOT_MSG( - is_native_4bit(qtype), - "IndexSQFastScan only supports QT_4bit and QT_4bit_uniform. " - "For higher-precision types, use " - "IndexRefine(IndexSQFastScan(...), IndexScalarQuantizer(...))."); + !is_fallback(qtype), + "IndexSQFastScan supports the native 4-bit and the reranked " + "types. QT_fp16 and QT_bf16 have no fast-scan path; use " + "IndexScalarQuantizer for those."); init_fastscan(d_in, d_in, 4, metric, bbs_in); } @@ -66,17 +54,39 @@ IndexSQFastScan::IndexSQFastScan() = default; IndexSQFastScan::IndexSQFastScan(const IndexScalarQuantizer& orig, int bbs_in) : sq(orig.sq) { FAISS_THROW_IF_NOT_MSG( - is_native_4bit(sq.qtype), - "IndexSQFastScan conversion constructor only supports " - "QT_4bit and QT_4bit_uniform."); + !is_fallback(sq.qtype), + "IndexSQFastScan conversion constructor supports the native " + "4-bit and the reranked types only."); init_fastscan(orig.d, orig.d, 4, orig.metric_type, bbs_in); ntotal = orig.ntotal; is_trained = orig.is_trained; ntotal2 = roundup(ntotal, bbs_in); codes.resize(ntotal2 * M2 / 2); - pq4_pack_codes( - orig.codes.data(), ntotal, M, ntotal2, bbs_in, M2, codes.get()); + if (is_native_4bit(sq.qtype)) { + pq4_pack_codes( + orig.codes.data(), ntotal, M, ntotal2, bbs_in, M2, codes.get()); + } else { + // High nibbles feed the scan, low nibbles the rerank. + std::vector nibbles(ntotal * (M2 / 2)); + const int bits = sq_bits(sq.qtype), lo_bits = bits - 4; + const size_t half = sq_rerank_size(d, sq.qtype); + lo_codes.assign(size_t(ntotal) * half, 0); + for (idx_t i = 0; i < ntotal; i++) { + const uint8_t* src = orig.codes.data() + size_t(i) * sq.code_size; + uint8_t* hi = nibbles.data() + size_t(i) * (M2 / 2); + BitstringReader bsr(src, sq.code_size); + BitstringWriter bsw(lo_codes.data() + size_t(i) * half, half); + for (int m = 0; m < d; m++) { + const int code = int(bsr.read(bits)); + const int h = code >> lo_bits; + hi[m / 2] |= (m & 1) ? uint8_t(h << 4) : uint8_t(h); + bsw.write(code & ((1 << lo_bits) - 1), lo_bits); + } + } + pq4_pack_codes( + nibbles.data(), ntotal, M, ntotal2, bbs_in, M2, codes.get()); + } } // ----------------------------------------------------------------------- @@ -93,10 +103,31 @@ void IndexSQFastScan::train(idx_t n, const float* x) { void IndexSQFastScan::add(idx_t n, const float* x) { FAISS_THROW_IF_NOT(is_trained); + const size_t before = lo_codes.size(); IndexFastScan::add(n, x); + if (!needs_rerank(sq.qtype) || lo_codes.size() != before) { + // IndexFastScan::add blocks a large batch and re-enters this override + // once per block, so the blocks have already appended the low bits. + return; + } + const int bits = sq_bits(sq.qtype), lo_bits = bits - 4; + const size_t stride = sq_rerank_size(d, sq.qtype); + lo_codes.resize(before + size_t(n) * stride, 0); + const SQRanges ranges(sq, d); + for (idx_t i = 0; i < n; i++) { + const float* xi = x + i * d; + uint8_t* dst = lo_codes.data() + before + size_t(i) * stride; + BitstringWriter bsw(dst, stride); + for (int m = 0; m < d; m++) { + const int code = + sq_code_of(xi[m], ranges.vmin(m), ranges.vdiff(m), bits); + bsw.write(code & ((1 << lo_bits) - 1), lo_bits); + } + } } void IndexSQFastScan::reset() { + lo_codes.clear(); IndexFastScan::reset(); } @@ -113,42 +144,82 @@ void IndexSQFastScan::search( const SearchParameters* params) const { FAISS_THROW_IF_NOT(k > 0); FAISS_THROW_IF_NOT(is_trained); - - const IDSelector* sel = params ? params->sel : nullptr; - - if (!sel) { - IndexFastScan::search(n, x, k, distances, labels, nullptr); + // The kernel applies the selector itself, so no generic-scanner fallback. + if (!needs_rerank(sq.qtype)) { + IndexFastScan::search(n, x, k, distances, labels, params); return; } - // IDSelector path: unpack codes and use SQ scanner - std::vector flat_codes(ntotal * sq.code_size); - { - std::unique_ptr packer(get_CodePacker()); - for (idx_t i = 0; i < ntotal; i++) { - packer->unpack_1( - codes.data(), i, flat_codes.data() + i * sq.code_size); - } - } + // The 4-bit scan is a shortlist. rerank_factor bounds the recall. + idx_t k_coarse = idx_t(double(k) * rerank_factor); + FAISS_THROW_IF_NOT(k_coarse >= k); + FAISS_THROW_IF_NOT_MSG( + n <= INT64_MAX / k_coarse, "n * k_coarse would overflow int64"); + std::vector coarse_dis(n * k_coarse); + std::vector coarse_ids(n * k_coarse); + IndexFastScan::search( + n, x, k_coarse, coarse_dis.data(), coarse_ids.data(), params); + const bool is_max = metric_type == METRIC_L2; #pragma omp parallel { - std::unique_ptr scanner( - sq.select_InvertedListScanner(metric_type, nullptr, true, sel)); - scanner->list_no = 0; - + std::unique_ptr packer(get_CodePacker()); + std::vector hi_buf(M2 / 2); + std::vector code_buf(d); + const size_t lo_stride = sq_rerank_size(d, sq.qtype); + const int maxv = (1 << sq_bits(sq.qtype)) - 1; + const SQRanges ranges(sq, d); #pragma omp for for (idx_t i = 0; i < n; i++) { - float* D = distances + k * i; - idx_t* I = labels + k * i; - if (metric_type == METRIC_L2) { + float* D = distances + i * k; + idx_t* I = labels + i * k; + if (is_max) { maxheap_heapify(k, D, I); } else { minheap_heapify(k, D, I); } - scanner->set_query(x + i * d); - scanner->scan_codes(ntotal, flat_codes.data(), nullptr, D, I, k); - if (metric_type == METRIC_L2) { + for (idx_t j = 0; j < k_coarse; j++) { + idx_t id = coarse_ids[i * k_coarse + j]; + if (id < 0) { + continue; + } + float dis; + { + // Recombine the two halves into the original code. + packer->unpack_1(codes.get(), id, hi_buf.data()); + split_to_codes( + hi_buf.data(), + lo_codes.data() + size_t(id) * lo_stride, + d, + sq.qtype, + code_buf.data()); + const float* xi = x + i * d; + float acc = 0; + for (int m = 0; m < d; m++) { + // Matches Codec*bit::decode_component: (c+0.5)/maxv. + const float v = ranges.vmin(m) + + ((code_buf[m] + 0.5f) / float(maxv)) * + ranges.vdiff(m); + if (is_max) { + const float df = xi[m] - v; + acc += df * df; + } else { + acc += xi[m] * v; + } + } + dis = acc; + } + if (is_max) { + if (dis < D[0]) { + maxheap_replace_top(k, D, I, dis, id); + } + } else { + if (dis > D[0]) { + minheap_replace_top(k, D, I, dis, id); + } + } + } + if (is_max) { maxheap_reorder(k, D, I); } else { minheap_reorder(k, D, I); @@ -163,7 +234,14 @@ void IndexSQFastScan::search( void IndexSQFastScan::compute_codes(uint8_t* out_codes, idx_t n, const float* x) const { - sq.compute_codes(x, out_codes, n); + if (is_native_4bit(sq.qtype)) { + sq.compute_codes(x, out_codes, n); + } else { + // The scanned nibble is the top half. lo_codes holds the bottom. + std::vector lo_discard( + size_t(n) * sq_rerank_size(d, sq.qtype)); + float_to_split_codes(x, out_codes, lo_discard.data(), n, d, M2, sq); + } } // ----------------------------------------------------------------------- @@ -178,15 +256,21 @@ void IndexSQFastScan::compute_float_LUT( const size_t dim = d; const size_t ksub_val = 16; - bool is_uniform = (sq.qtype == ScalarQuantizer::QT_4bit_uniform); + bool is_uniform = (sq.qtype == ScalarQuantizer::QT_4bit_uniform) || + is_uniform_range(sq.qtype); std::vector recon_table(dim * ksub_val); + const float lut_step = float(1 << sq_rerank_bits(sq.qtype)); + const float lut_offset = lut_step / 2.0f; + const float lut_scale = float((1 << sq_bits(sq.qtype)) - 1); + if (is_uniform) { - float vmin = sq.trained[0]; - float vdiff = sq.trained[1]; + float vmin, vdiff; + get_uniform_range(sq, vmin, vdiff); for (size_t c = 0; c < ksub_val; c++) { - float recon = vmin + ((c + 0.5f) / 15.0f) * vdiff; + float recon = + vmin + ((c * lut_step + lut_offset) / lut_scale) * vdiff; for (size_t m = 0; m < dim; m++) { recon_table[m * ksub_val + c] = recon; } @@ -197,8 +281,8 @@ void IndexSQFastScan::compute_float_LUT( const float* vdiff = sq.trained.data() + dim; for (size_t m = 0; m < dim; m++) { for (size_t c = 0; c < ksub_val; c++) { - recon_table[m * ksub_val + c] = - vmin[m] + ((c + 0.5f) / 15.0f) * vdiff[m]; + recon_table[m * ksub_val + c] = vmin[m] + + ((c * lut_step + lut_offset) / lut_scale) * vdiff[m]; } } } @@ -237,11 +321,37 @@ void IndexSQFastScan::sa_decode(idx_t n, const uint8_t* bytes, float* x) const { sq.decode(bytes, x, n); } +void IndexSQFastScan::fill_sa_code( + const CodePacker& packer, + idx_t id, + uint8_t* scratch, + int* values, + uint8_t* code_out) const { + packer.unpack_1(codes.data(), id, scratch); + if (lo_codes.empty()) { + memcpy(code_out, scratch, sq.code_size); + return; + } + split_to_codes( + scratch, + lo_codes.data() + size_t(id) * sq_rerank_size(d, sq.qtype), + d, + sq.qtype, + values); + memset(code_out, 0, sq.code_size); + BitstringWriter out(code_out, sq.code_size); + const int bits = sq_bits(sq.qtype); + for (int m = 0; m < d; m++) { + out.write(values[m], bits); + } +} + void IndexSQFastScan::reconstruct(idx_t key, float* recons) const { FAISS_THROW_IF_NOT(key >= 0 && key < ntotal); std::unique_ptr packer(get_CodePacker()); - std::vector flat_code(sq.code_size); - packer->unpack_1(codes.data(), key, flat_code.data()); + std::vector scratch(M2 / 2), flat_code(sq.code_size); + std::vector values(d); + fill_sa_code(*packer, key, scratch.data(), values.data(), flat_code.data()); sq.decode(flat_code.data(), recons, 1); } @@ -269,9 +379,15 @@ void IndexSQFastScan::sa_encode(idx_t n, const float* x, uint8_t* bytes) const { void IndexSQFastScan::reconstruct_n(idx_t i0, idx_t ni, float* recons) const { FAISS_THROW_IF_NOT(i0 >= 0 && i0 + ni <= ntotal); std::unique_ptr packer(get_CodePacker()); - std::vector flat_code(sq.code_size); + std::vector scratch(M2 / 2), flat_code(sq.code_size); + std::vector values(d); for (idx_t i = 0; i < ni; i++) { - packer->unpack_1(codes.data(), i0 + i, flat_code.data()); + fill_sa_code( + *packer, + i0 + i, + scratch.data(), + values.data(), + flat_code.data()); sq.decode(flat_code.data(), recons + i * d, 1); } } @@ -288,7 +404,7 @@ void IndexSQFastScan::add_sa_codes( // Decode to float then re-add via IndexFastScan for SIMD packing std::vector recon(n * d); sq.decode(code, recon.data(), n); - IndexFastScan::add(n, recon.data()); + add(n, recon.data()); } // ----------------------------------------------------------------------- @@ -314,6 +430,17 @@ void IndexSQFastScan::permute_entries(const idx_t* perm) { code_sz); } pq4_pack_codes(flat_new.data(), ntotal, M, ntotal2, bbs, M2, codes.get()); + + if (!lo_codes.empty()) { + const size_t lo_sz = sq_rerank_size(d, sq.qtype); + std::vector lo_new(size_t(ntotal) * lo_sz); + for (idx_t i = 0; i < ntotal; i++) { + memcpy(lo_new.data() + size_t(i) * lo_sz, + lo_codes.data() + size_t(perm[i]) * lo_sz, + lo_sz); + } + lo_codes.swap(lo_new); + } } // ----------------------------------------------------------------------- @@ -369,8 +496,15 @@ FlatCodesDistanceComputer* IndexSQFastScan::get_FlatCodesDistanceComputer() std::unique_ptr packer(get_CodePacker()); size_t cs = sq.code_size; std::vector flat(ntotal * cs); + std::vector scratch(M2 / 2); + std::vector values(d); for (idx_t i = 0; i < ntotal; i++) { - packer->unpack_1(codes.data(), i, flat.data() + i * cs); + fill_sa_code( + *packer, + i, + scratch.data(), + values.data(), + flat.data() + i * cs); } ScalarQuantizer::SQDistanceComputer* dc = @@ -401,9 +535,15 @@ void IndexSQFastScan::range_search( std::vector flat_codes(ntotal * sq.code_size); { std::unique_ptr packer(get_CodePacker()); + std::vector scratch(M2 / 2); + std::vector values(d); for (idx_t i = 0; i < ntotal; i++) { - packer->unpack_1( - codes.data(), i, flat_codes.data() + i * sq.code_size); + fill_sa_code( + *packer, + i, + scratch.data(), + values.data(), + flat_codes.data() + i * sq.code_size); } } @@ -478,6 +618,10 @@ void IndexSQFastScan::check_compatible_for_merge( void IndexSQFastScan::merge_from(Index& otherIndex, idx_t add_id) { check_compatible_for_merge(otherIndex); + const IndexSQFastScan* other = + static_cast(&otherIndex); + lo_codes.insert( + lo_codes.end(), other->lo_codes.begin(), other->lo_codes.end()); IndexFastScan::merge_from(otherIndex, add_id); } diff --git a/thirdparty/faiss/faiss/IndexSQFastScan.h b/thirdparty/faiss/faiss/IndexSQFastScan.h index dca370291..22ae63327 100644 --- a/thirdparty/faiss/faiss/IndexSQFastScan.h +++ b/thirdparty/faiss/faiss/IndexSQFastScan.h @@ -16,28 +16,33 @@ namespace faiss { -/** Fast scan version of IndexScalarQuantizer for native 4-bit types. +/** Fast scan version of IndexScalarQuantizer. * * Supported quantizer types: * - QT_4bit, QT_4bit_uniform: native 4-bit codes mapped onto the - * PQ4 FastScan SIMD infrastructure (vpshufb / equivalent). - * No precision loss. + * PQ4 FastScan SIMD (vpshufb / equivalent). * - * For higher-precision types (QT_8bit, QT_6bit, etc.), use - * IndexRefine(IndexSQFastScan(QT_4bit), IndexScalarQuantizer(QT_8bit)) - * to get fast-scan with reranking. For fallback types (QT_fp16, - * QT_bf16), use IndexScalarQuantizer directly. + * - QT_6bit, QT_8bit, QT_8bit_uniform, QT_8bit_direct, + * QT_8bit_direct_signed: re-quantised to 4-bit for the scan, reranked + * against the originals in orig_codes. * - * M = d subquantizers with 16 levels and uint16 SIMD accumulators - * (safe for d <= 257). + * - All other types (QT_fp16, QT_bf16): use IndexScalarQuantizer directly. */ struct IndexSQFastScan : IndexFastScan { ScalarQuantizer sq; + /// Overselection ratio for reranking. + float rerank_factor = 2; + + /// Low nibbles of the 8-bit codes, two dimensions per byte, indexed by + /// id. The high nibbles live in the packed scan codes. Empty for the + /// native 4-bit types, which need no rerank. + std::vector lo_codes; + /** Constructor. * * @param d dimensionality of input vectors - * @param qtype QT_4bit or QT_4bit_uniform only + * @param qtype any native 4-bit or reranked type (see above) * @param metric distance metric (METRIC_L2 or METRIC_INNER_PRODUCT) * @param bbs block size for SIMD processing (multiple of 32) */ @@ -49,7 +54,7 @@ struct IndexSQFastScan : IndexFastScan { IndexSQFastScan(); - /// Build from an existing IndexScalarQuantizer (must be QT_4bit*) + /// Build from an existing IndexScalarQuantizer explicit IndexSQFastScan(const IndexScalarQuantizer& orig, int bbs = 32); void train(idx_t n, const float* x) override; @@ -111,6 +116,13 @@ struct IndexSQFastScan : IndexFastScan { size_t sa_code_size() const override; + void fill_sa_code( + const CodePacker& packer, + idx_t id, + uint8_t* scratch, + int* values, + uint8_t* code_out) const; + size_t fast_scan_code_size() const override; }; diff --git a/thirdparty/faiss/faiss/IndexShards.cpp b/thirdparty/faiss/faiss/IndexShards.cpp index f8143b299..8a34388fb 100644 --- a/thirdparty/faiss/faiss/IndexShards.cpp +++ b/thirdparty/faiss/faiss/IndexShards.cpp @@ -193,6 +193,16 @@ void IndexShardsTemplate::add_with_ids( syncWithSubIndexes(); } +template +size_t IndexShardsTemplate::remove_ids(const IDSelector& sel) { + FAISS_THROW_IF_MSG( + successive_ids, "remove_ids needs successive_ids = false"); + const idx_t before = this->ntotal; + this->runOnIndex([&sel](int, IndexT* index) { index->remove_ids(sel); }); + syncWithSubIndexes(); + return before - this->ntotal; +} + template void IndexShardsTemplate::search( idx_t n, diff --git a/thirdparty/faiss/faiss/IndexShards.h b/thirdparty/faiss/faiss/IndexShards.h index 75c716e1c..04855e03b 100644 --- a/thirdparty/faiss/faiss/IndexShards.h +++ b/thirdparty/faiss/faiss/IndexShards.h @@ -91,6 +91,11 @@ struct IndexShardsTemplate : public ThreadedIndex { void train(idx_t n, const component_t* x) override; + /// Removes the ids from every shard, and returns the sum of the counts. + /// Needs successive_ids = false: with successive ids, the ids of a shard + /// depend on the sizes of the shards before it. + size_t remove_ids(const IDSelector& sel) override; + bool successive_ids; /// Synchronize the top-level index (IndexShards) with data in the diff --git a/thirdparty/faiss/faiss/SuperKMeans.cpp b/thirdparty/faiss/faiss/SuperKMeans.cpp index fc96a90f5..5cee15351 100644 --- a/thirdparty/faiss/faiss/SuperKMeans.cpp +++ b/thirdparty/faiss/faiss/SuperKMeans.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -276,10 +277,13 @@ void setup_train_state( int d, int k, idx_t n, - const float* x) { - const size_t line_size = sizeof(float) * static_cast(d); + const void* x, + NumericType numeric_type) { + const bool fp16 = numeric_type == NumericType::Float16; + const size_t line_size = + (fp16 ? sizeof(uint16_t) : sizeof(float)) * static_cast(d); idx_t nx = n; - const uint8_t* x_bytes = reinterpret_cast(x); + const uint8_t* x_bytes = static_cast(x); std::unique_ptr sampled_x_owner; if (static_cast(nx) > static_cast(k) * cp.max_points_per_centroid) { @@ -298,7 +302,6 @@ void setup_train_state( sampled_x_owner.reset(x_new); x_bytes = x_new; } - const float* x_sampled = reinterpret_cast(x_bytes); FAISS_THROW_IF_NOT_MSG( nx <= static_cast(std::numeric_limits::max()), @@ -315,7 +318,27 @@ void setup_train_state( } state.X_tilde.resize(static_cast(state.n) * d); - state.R->apply_noalloc(state.n, x_sampled, state.X_tilde.data()); + if (!fp16) { + state.R->apply_noalloc( + state.n, + reinterpret_cast(x_bytes), + state.X_tilde.data()); + } else { + const size_t block_size = + std::min(static_cast(state.n), cp.decode_block_size); + std::vector decoded(block_size * d); + const uint16_t* x16 = reinterpret_cast(x_bytes); + for (size_t i0 = 0; i0 < static_cast(state.n); + i0 += block_size) { + const size_t i1 = + std::min(static_cast(state.n), i0 + block_size); + fp16_to_fp32((i1 - i0) * d, x16 + i0 * d, decoded.data()); + state.R->apply_noalloc( + static_cast(i1 - i0), + decoded.data(), + state.X_tilde.data() + i0 * d); + } + } sampled_x_owner.reset(); // Forgy init: pick k random rows from the rotated pool as initial @@ -368,8 +391,8 @@ void untransform_centroids( } // namespace -SuperKMeans::SuperKMeans(int d, int k, const SuperKMeansParameters& cp_in) - : cp(cp_in), d(d), k(k) { +SuperKMeans::SuperKMeans(int d_in, int k_in, const SuperKMeansParameters& cp_in) + : cp(cp_in), d(d_in), k(k_in) { FAISS_THROW_IF_NOT_MSG(d > 0, "SuperKMeans: d must be positive"); FAISS_THROW_IF_NOT_MSG(k > 0, "SuperKMeans: k must be positive"); FAISS_THROW_IF_NOT_MSG( @@ -410,15 +433,36 @@ SuperKMeans::SuperKMeans(int d, int k, const SuperKMeansParameters& cp_in) } void SuperKMeans::train(idx_t n, const float* x) { + train_ex(n, x, NumericType::Float32); +} + +void SuperKMeans::train_ex(idx_t n, const void* x, NumericType numeric_type) { + FAISS_THROW_IF_NOT_MSG( + numeric_type == NumericType::Float32 || + numeric_type == NumericType::Float16, + "SuperKMeans::train_ex: unsupported numeric type"); FAISS_THROW_IF_NOT_MSG(n > 0, "SuperKMeans: n must be positive"); FAISS_THROW_IF_MSG(x == nullptr, "SuperKMeans: x must not be null"); FAISS_THROW_IF_NOT_MSG( n >= static_cast(k), "SuperKMeans: n must be >= k"); + const bool fp16 = numeric_type == NumericType::Float16; + FAISS_THROW_IF_NOT_MSG( + !fp16 || cp.decode_block_size > 0, + "SuperKMeans: decode_block_size must be positive"); if (cp.check_input_data_for_NaNs) { - for (size_t i = 0; i < static_cast(n) * d; i++) { + const size_t num_values = static_cast(n) * d; + if (fp16) { FAISS_THROW_IF_NOT_MSG( - std::isfinite(x[i]), + detail::fp16_all_finite( + num_values, static_cast(x)), "SuperKMeans: input contains NaN's or Inf's"); + } else { + const float* x32 = static_cast(x); + for (size_t i = 0; i < num_values; i++) { + FAISS_THROW_IF_NOT_MSG( + std::isfinite(x32[i]), + "SuperKMeans: input contains NaN's or Inf's"); + } } } if (cp.verbose && n < static_cast(k) * cp.min_points_per_centroid) { @@ -434,7 +478,7 @@ void SuperKMeans::train(idx_t n, const float* x) { std::vector labels64; SuperKMeansAssignScratch assign_scratch; std::vector hassign; - setup_train_state(state, labels64, hassign, cp, d, k, n, x); + setup_train_state(state, labels64, hassign, cp, d, k, n, x, numeric_type); iteration_stats.clear(); iteration_stats.reserve(cp.niter); @@ -623,7 +667,7 @@ void super_kmeans_assign_iteration( [[maybe_unused]] const int omp_chunk_local = cp.omp_chunk; int64_t tile_total = 0; int64_t tile_pruned = 0; -#pragma omp parallel for schedule(dynamic, omp_chunk_local) \ +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC, omp_chunk_local) \ reduction(+ : tile_total) reduction(+ : tile_pruned) for (int i = 0; i < bx; ++i) { const float xnp_i = x_norms_partial[xi + i]; diff --git a/thirdparty/faiss/faiss/SuperKMeans.h b/thirdparty/faiss/faiss/SuperKMeans.h index c91a9bb44..174ff2a4f 100644 --- a/thirdparty/faiss/faiss/SuperKMeans.h +++ b/thirdparty/faiss/faiss/SuperKMeans.h @@ -89,11 +89,16 @@ struct SuperKMeans { SuperKMeans(int d, int k, const SuperKMeansParameters& cp = {}); - /// Train on `n` row-major vectors of dimension `d`. Honors the applicable - /// ClusteringParameters fields (niter, seed, verbose, - /// max_points_per_centroid, use_faster_subsampling, - /// check_input_data_for_NaNs). + /// Train on `n` row-major fp32 vectors of dimension `d`. void train(idx_t n, const float* x); + + /** Train on vectors of the given numeric type. + * + * Float32 is the same as train(). Float16 takes packed IEEE binary16 + * vectors and widens bounded blocks while rotating them into the fp32 + * training workspace. Centroids and all iteration state remain fp32. + */ + void train_ex(idx_t n, const void* x, NumericType numeric_type); }; /// Reusable scratch for super_kmeans_assign_iteration; pass one instance across diff --git a/thirdparty/faiss/faiss/VectorTransform.cpp b/thirdparty/faiss/faiss/VectorTransform.cpp index 61365149d..21d46b0f7 100644 --- a/thirdparty/faiss/faiss/VectorTransform.cpp +++ b/thirdparty/faiss/faiss/VectorTransform.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -423,13 +424,85 @@ static int next_power_of_2(int n) { return p; } -// Generate three sign-flip vectors from the given seed. +// Smallest multiple of 64 >= n. +static int next_multiple_of_64(int n) { + return (n + 63) / 64 * 64; +} + +static bool is_power_of_2(size_t n) { + return n > 0 && (n & (n - 1)) == 0; +} + +// Largest power of 2 <= n, for n > 0. +static size_t prev_power_of_2(size_t n) { + size_t p = 1; + while (p * 2 <= n) { + p *= 2; + } + return p; +} + +// Butterfly between the two halves of x (p even): +// (x_j, x_{j + p/2}) -> (x_j + x_{j + p/2}, x_j - x_{j + p/2}). +// Scales norms by sqrt(2). +static void kac_butterfly(float* x, size_t p) { + const size_t half = p / 2; + for (size_t j = 0; j < half; j++) { + float a = x[j]; + float b = x[j + half]; + x[j] = a + b; + x[j + half] = a - b; + } +} + +// One round of the FHT-Kac rotation of a vector of p components: sign flips, +// normalized FWHT of the t components starting at offset, then the butterfly. +static void fht_kac_round( + float* x, + size_t p, + size_t t, + size_t offset, + const float* signs, + float fwht_scale) { + for (size_t j = 0; j < p; j++) { + x[j] *= signs[j]; + } + fwht_inplace(x + offset, t); + for (size_t j = offset; j < offset + t; j++) { + x[j] *= fwht_scale; + } + kac_butterfly(x, p); +} + +// Inverse of fht_kac_round, up to the sqrt(2) scaling of the butterfly: the +// butterfly, the normalized FWHT and the sign flips are each their own +// inverse, so they are applied in reverse order. +static void fht_kac_inverse_round( + float* x, + size_t p, + size_t t, + size_t offset, + const float* signs, + float fwht_scale) { + kac_butterfly(x, p); + fwht_inplace(x + offset, t); + for (size_t j = offset; j < offset + t; j++) { + x[j] *= fwht_scale; + } + for (size_t j = 0; j < p; j++) { + x[j] *= signs[j]; + } +} + +// Generate three sign-flip vectors from the given seed, and a fourth one +// after them if s4 is not null. static void generate_signs( uint32_t seed, size_t p, std::vector& s1, std::vector& s2, - std::vector& s3) { + std::vector& s3, + std::vector* s4) { FAISS_THROW_IF_NOT_MSG( p > 0, "number of Hadamard factors p must be positive"); SplitMix64RandomGenerator rng(seed); @@ -445,17 +518,36 @@ static void generate_signs( for (size_t j = 0; j < p; j++) { s3[j] = (rng.rand_int(2) == 0) ? -1.0f : 1.0f; } + if (s4) { + s4->resize(p); + for (size_t j = 0; j < p; j++) { + (*s4)[j] = (rng.rand_int(2) == 0) ? -1.0f : 1.0f; + } + } } -HadamardRotation::HadamardRotation(int d, uint32_t seed_in) - : VectorTransform(d, next_power_of_2(d)), seed(seed_in) { +HadamardRotation::HadamardRotation( + int d, + uint32_t seed_in, + bool pad_to_power_of_2_in) + : VectorTransform( + d, + pad_to_power_of_2_in ? next_power_of_2(d) + : next_multiple_of_64(d)), + seed(seed_in), + pad_to_power_of_2(pad_to_power_of_2_in) { init(seed_in); } void HadamardRotation::init(uint32_t seed_in) { seed = seed_in; is_trained = true; - generate_signs(seed, d_out, signs1, signs2, signs3); + if (is_power_of_2(d_out)) { + generate_signs(seed, d_out, signs1, signs2, signs3, nullptr); + signs4.clear(); + } else { + generate_signs(seed, d_out, signs1, signs2, signs3, &signs4); + } } void HadamardRotation::train(idx_t, const float*) { @@ -477,11 +569,40 @@ void HadamardRotation::apply_noalloc(idx_t n, const float* x, float* xt) const { signs3.size() == p, "sign-flip vector 3 size must match output dimension"); + if (!is_power_of_2(p)) { + // FHT-Kac rotation (pad_to_power_of_2 == false), see the header. + FAISS_THROW_IF_NOT_MSG( + signs4.size() == p, + "sign-flip vector 4 size must match output dimension"); + const size_t t = prev_power_of_2(p); + const float fwht_scale = 1.0f / std::sqrt(static_cast(t)); + +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (idx_t i = 0; i < n; i++) { + const float* xi = x + i * d; + float* xo = xt + i * p; + + std::memcpy(xo, xi, d * sizeof(float)); + for (size_t j = d; j < p; j++) { + xo[j] = 0.0f; + } + fht_kac_round(xo, p, t, 0, signs1.data(), fwht_scale); + fht_kac_round(xo, p, t, p - t, signs2.data(), fwht_scale); + fht_kac_round(xo, p, t, 0, signs3.data(), fwht_scale); + fht_kac_round(xo, p, t, p - t, signs4.data(), fwht_scale); + // The four butterflies scaled norms by sqrt(2)^4 = 4. + for (size_t j = 0; j < p; j++) { + xo[j] *= 0.25f; + } + } + return; + } + // Each unnormalized FWHT scales norms by sqrt(p). // Three rounds scale by p^(3/2). Normalize once at the end. float total_scale = 1.0f / (p * std::sqrt(static_cast(p))); -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) for (idx_t i = 0; i < n; i++) { const float* xi = x + i * d; float* xo = xt + i * p; @@ -521,12 +642,36 @@ void HadamardRotation::reverse_transform(idx_t n, const float* xt, float* x) "HadamardRotation inverse requires equal input/output dimensions"); const size_t p = d_out; + + if (!is_power_of_2(p)) { + // Reverse of the FHT-Kac rotation: the rounds in reverse order. + FAISS_THROW_IF_NOT_MSG( + signs4.size() == p, + "sign-flip vector 4 size must match output dimension"); + const size_t t = prev_power_of_2(p); + const float fwht_scale = 1.0f / std::sqrt(static_cast(t)); + +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (idx_t i = 0; i < n; i++) { + float* xo = x + i * p; + std::memcpy(xo, xt + i * p, p * sizeof(float)); + fht_kac_inverse_round(xo, p, t, p - t, signs4.data(), fwht_scale); + fht_kac_inverse_round(xo, p, t, 0, signs3.data(), fwht_scale); + fht_kac_inverse_round(xo, p, t, p - t, signs2.data(), fwht_scale); + fht_kac_inverse_round(xo, p, t, 0, signs1.data(), fwht_scale); + for (size_t j = 0; j < p; j++) { + xo[j] *= 0.25f; + } + } + return; + } + // Reverse of apply_noalloc: three unnormalized FWHT rounds scale norms // by (sqrt(p))^3 = p*sqrt(p); the forward pass cancels this with // total_scale = 1/(p*sqrt(p)), so the inverse applies the same factor. const float inverse_scale = 1.0f / (p * std::sqrt(static_cast(p))); -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) for (idx_t i = 0; i < n; i++) { const float* xi = xt + i * p; float* xo = x + i * p; @@ -561,6 +706,9 @@ void HadamardRotation::check_identical(const VectorTransform& other) const { "HadamardRotation output dimensions must match"); FAISS_THROW_IF_NOT_MSG( seed == hr->seed, "HadamardRotation seeds must match"); + FAISS_THROW_IF_NOT_MSG( + pad_to_power_of_2 == hr->pad_to_power_of_2, + "HadamardRotation padding modes must match"); } /********************************************* @@ -718,7 +866,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) { } std::vector covd(d_in * d_in); - for (size_t i = 0; i < d_in * d_in; i++) { + for (size_t i = 0; i < static_cast(d_in) * d_in; i++) { covd[i] = cov[i]; } @@ -726,7 +874,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) { eig(d_in, covd.data(), eigenvaluesd.data(), verbose); - for (size_t i = 0; i < d_in * d_in; i++) { + for (size_t i = 0; i < static_cast(d_in) * d_in; i++) { PCAMat[i] = covd[i]; } eigenvalues.resize(d_in); @@ -773,7 +921,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) { } std::vector gramd(n * n); - for (size_t i = 0; i < n * n; i++) { + for (idx_t i = 0; i < n * n; i++) { gramd[i] = gram[i]; } @@ -785,7 +933,7 @@ void PCAMatrix::train(idx_t n, const float* x_in) { PCAMat.resize(d_in * n); - for (size_t i = 0; i < n * n; i++) { + for (idx_t i = 0; i < n * n; i++) { gram[i] = gramd[i]; } diff --git a/thirdparty/faiss/faiss/VectorTransform.h b/thirdparty/faiss/faiss/VectorTransform.h index 0dd6f26ba..d6f0f700c 100644 --- a/thirdparty/faiss/faiss/VectorTransform.h +++ b/thirdparty/faiss/faiss/VectorTransform.h @@ -129,14 +129,37 @@ struct RandomRotationMatrix : LinearTransform { /** Three rounds of random sign-flip + Fast Walsh-Hadamard Transform. * Produces a pseudo-random rotation in O(d log d) time. * d_out is the smallest power of 2 >= d_in (zero-padded as needed). + * + * With pad_to_power_of_2 = false, d_out is the smallest multiple of 64 >= d_in + * instead, which avoids e.g. padding d = 1536 to 2048. When that d_out is not + * a power of 2, the transform runs four rounds. Each round flips the signs of + * all d_out components, applies a normalized FWHT to the first (rounds 1 and + * 3) or the last (rounds 2 and 4) t of them, t being the largest power of 2 + * <= d_out, and then mixes the two halves of the vector with the butterfly + * (x_j, x_{j + d_out/2}) -> (x_j + x_{j + d_out/2}, x_j - x_{j + d_out/2}) + * / sqrt(2). This is the FHT-Kac rotation of the RaBitQ library. + * + * In index_factory: "HR" (power of 2) or "HRk" (multiple of 64), optionally + * followed by the seed, e.g. "HRk7". */ struct HadamardRotation : VectorTransform { uint32_t seed{}; + /// d_out is the smallest power of 2 >= d_in if true (the default), the + /// smallest multiple of 64 >= d_in if false + bool pad_to_power_of_2 = true; + /// Sign-flip vectors, each of size d_out, generated from seed. std::vector signs1, signs2, signs3; - explicit HadamardRotation(int d, uint32_t seed = 12345); + /// Sign-flip vector of the fourth round. Only used, and only non-empty, + /// when d_out is not a power of 2. + std::vector signs4; + + explicit HadamardRotation( + int d, + uint32_t seed = 12345, + bool pad_to_power_of_2 = true); void init(uint32_t seed_in); diff --git a/thirdparty/faiss/faiss/clone_index.cpp b/thirdparty/faiss/faiss/clone_index.cpp index 76dbdd829..83f4a214f 100644 --- a/thirdparty/faiss/faiss/clone_index.cpp +++ b/thirdparty/faiss/faiss/clone_index.cpp @@ -9,6 +9,8 @@ #include +#include + #include #include @@ -37,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -170,6 +173,17 @@ IndexNSG* clone_IndexNSG(const IndexNSG* insg) { } } +static IndexPiPNN* clone_IndexPiPNN(const IndexPiPNN* ipipnn) { + TRYCLONE(IndexPiPNNFlat, ipipnn) + TRYCLONE(IndexPiPNNSQ, ipipnn) { + FAISS_THROW_IF_NOT_FMT( + typeid(*ipipnn) == typeid(IndexPiPNN), + "clone not supported for this type of IndexPiPNN: %s", + typeid(*ipipnn).name()); + return new IndexPiPNN(*ipipnn); + } +} + IndexRowwiseMinMaxBase* clone_IndexRowwiseMinMax( const IndexRowwiseMinMaxBase* irmmb) { TRYCLONE(IndexRowwiseMinMaxFP16, irmmb) @@ -356,6 +370,16 @@ Index* Cloner::clone_Index(const Index* index) { res->own_fields = true; res->storage = clone_Index(insg->storage); return res; + } else if ( + const IndexPiPNN* ipipnn = dynamic_cast(index)) { + // make sure we don't get a GPU index here + std::unique_ptr storage( + ipipnn->storage ? Cloner::clone_Index(ipipnn->storage) + : nullptr); + IndexPiPNN* res = clone_IndexPiPNN(ipipnn); + res->storage = storage.release(); + res->own_fields = true; + return res; } else if ( const IndexNNDescent* innd = dynamic_cast(index)) { diff --git a/thirdparty/faiss/faiss/docs/simd_dynamic_dispatch_migration.md b/thirdparty/faiss/faiss/docs/simd_dynamic_dispatch_migration.md index 66c45521a..dab501c78 100644 --- a/thirdparty/faiss/faiss/docs/simd_dynamic_dispatch_migration.md +++ b/thirdparty/faiss/faiss/docs/simd_dynamic_dispatch_migration.md @@ -137,13 +137,11 @@ void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c); ### Step 2: Split into per-SIMD translation units -Move SIMD specializations into per-ISA `.cpp` files, each guarded by -`#ifdef COMPILE_SIMD_*`. The original file retains only the `NONE` (scalar) -specialization and the dispatch wrapper. +Move SIMD specializations into per-ISA `.cpp` files. The original file +retains only the `NONE` (scalar) specialization and the dispatch wrapper. ```cpp -// functions_avx2.cpp — compiled with -mavx2 -#ifdef COMPILE_SIMD_AVX2 +// functions_avx2.cpp — compiled with -mavx2, only in builds with AVX2 #include "functions.h" #include @@ -152,7 +150,6 @@ void fvec_madd( size_t n, const float* a, float bf, const float* b, float* c) { // AVX2 intrinsics implementation } -#endif ``` ```cpp @@ -180,15 +177,16 @@ void fvec_madd(size_t n, const float* a, float bf, const float* b, float* c) { **Key rules for per-SIMD TUs:** -- Guard the entire file with `#ifdef COMPILE_SIMD_AVX2` (not `#ifdef __AVX2__`). - `COMPILE_SIMD_*` is a build-system define — a **link-time promise** that the +- Do not guard the file. Register it in `FAISS_SIMD_AVX2_SRC` in + `CMakeLists.txt` and in `SIMD_FILES` in `xplat.bzl` (Step 4). The build + compiles it only with the AVX2 flags, and only in builds that define + `COMPILE_SIMD_AVX2`. +- `COMPILE_SIMD_*` is a build-system define — a **link-time promise** that the specialization will be available when linking. `__AVX2__` is a compiler define that says intrinsics are available in this TU. Both are true for SIMD TUs, but only `COMPILE_SIMD_*` is true for common TUs in DD mode. This is what allows the common TU to reference `fvec_madd` without defining it — `COMPILE_SIMD_AVX2` promises the linker will find it. -- Include the ISA-specific intrinsic headers (``, - ``, ``) inside the guard. - Never pass SIMD data types (`__m256`, `float32x4_t`) across TU boundaries. The public interface uses plain `float*`, `uint8_t*`, etc. @@ -414,6 +412,78 @@ void my_kernel(...) { ``` +## SIMD guard rules + +Two kinds of macros select SIMD code, and `utils/simd_levels.h` combines them: + +| Macro | Defined by | Meaning | Defined in | +|---|---|---|---| +| `COMPILE_SIMD_` (`COMPILE_SIMD_AVX2`, `COMPILE_SIMD_ARM_NEON`, ...) | Faiss build files | The library contains code for level L. | Every file of the `faiss` target. Not in code outside Faiss. | +| `__AVX2__`, `__AVX512F__`, `__F16C__`, `__aarch64__`, `__ARM_FEATURE_SVE`, ... | The compiler | The current file can use these instructions. | Only files with the matching flags. | +| `FAISS_SIMD_TU(L)` | `utils/simd_levels.h` | Both of the above are true. | Any file that includes `simd_levels.h`. | + +Example: an x86 DD build that includes AVX512. + +| File | `COMPILE_SIMD_AVX512` | `__AVX512F__` | `FAISS_SIMD_TU(AVX512)` | +|---|---|---|---| +| `utils/distances.cpp` (common file, baseline flags) | defined | not defined | 0 | +| `utils/simd_impl/distances_avx512.cpp` (per-level file) | defined | defined | 1 | +| A program outside Faiss | not defined | not defined | 0 | + +Rules: + +1. **Per-level code** lives in a per-level `.cpp` file (`*_avx512.cpp`, + `*-neon.cpp`), or in a header that only per-level files include and whose + name contains the level (`hamming_computer-avx2.h`). Such a header has no + guard. Register the `.cpp` file in `FAISS_SIMD__SRC` in `CMakeLists.txt` + and in `SIMD_FILES` in `xplat.bzl` (RVV files: CMake only). The `.cpp` file + has no whole-file guard: the build compiles it only with the flags of L, and + only in builds that define `COMPILE_SIMD_`, so such a guard is always + true. The compiler flags of a level must not exceed what the runtime + detection checks. +2. **Common code** uses `COMPILE_SIMD_` only to declare, reference or dispatch + to per-level code, never around intrinsics. Declare every per-level + specialization in its header under `COMPILE_SIMD_`. Example: + `fp16_kernels.h` declares `fp16_madd` only under + `COMPILE_SIMD_AVX512`. Without the guard, a build without + `fp16_kernels_avx512.cpp` does not link. With `__AVX512F__`, common files + never see the declaration, so dispatch never uses the AVX512 kernel. Only + the common files in `COMPILE_SIMD_FILES` in `tests/test_simd_registry.py` + test `COMPILE_SIMD_`. Add a file there only after review. +3. **Fallback** is the dispatch mask only. To make AVX512 machines use the AVX2 + version, leave AVX512 out of the mask (for example + `AVAILABLE_SIMD_LEVELS_BASE_NO_AVX512`). Do not write forwarding + specializations. Common code reaches per-level code only through + `with_simd_level` and `with_selected_simd_levels`, not through + `foo`. +4. **Level code in a header that common files include** uses + `#if FAISS_SIMD_TU(L)`, for example `#if FAISS_SIMD_TU(AVX512)` in + `kernels_simd512.h`. Raw compiler macros for SIMD features are allowed only in + the headers listed in `tests/test_simd_registry.py`. Example: `fp16.h` uses + `__F16C__`, so an AVX2 file (`-mf16c`) gets F16C instructions and a common + file gets plain C. +5. **Linkage.** The linker keeps one copy of an inline or template function. If + files with different flags compile different code under one name, a baseline + caller can run AVX2 or AVX-512 instructions. A function whose code differs + between files therefore has internal linkage (`static inline` or an anonymous + namespace), or a `SIMDLevel` template parameter that only files of that level + instantiate. This also applies to every external-linkage function that inlines + such code, and to these cases: + - A default virtual function is defined in a common `.cpp` file, not in the + header, for example `DistanceComputer::distances_batch_4`. + - A standard container in per-level code has an element or hash type that + differs per level, for example `ReservoirHandler::Reservoir`. +6. **Architecture code** that is not a SIMD level (prefetch, CPU detection) uses + `__x86_64__`/`_M_X64` or `__aarch64__`. Keep a branch only if its code is + different from the other branches. +7. **A higher level needs its whole fallback chain** in the same build: + AVX512_SPR → AVX512_VPOPCNT → AVX512 → AVX2, and ARM_SVE → ARM_NEON. The build + files do this. Users only select `FAISS_OPT_LEVEL` or the Buck dynamic + dispatch setting. + +`tests/test_simd_registry.py` checks rules 1, 2 and 4, and that CMake and Buck +list the same per-level files. + ## Key Principles 1. **Static dispatch is zero-overhead.** In static mode, `with_simd_level` @@ -424,8 +494,8 @@ void my_kernel(...) { 3. **`COMPILE_SIMD_*` over compiler macros.** Use `COMPILE_SIMD_AVX2` (build system control) instead of `__AVX2__` (compiler feature detection) for - dispatch guards. Lower-level headers like `simdlib.h` still use compiler - macros for intrinsic type selection. + dispatch guards, and `FAISS_SIMD_TU(L)` for level code in shared headers. + See [SIMD guard rules](#simd-guard-rules). 4. **Dispatch once, outside the loop.** Call `with_simd_level` at the factory/constructor boundary. The constructed object carries its @@ -442,7 +512,8 @@ void my_kernel(...) { in `utils/simd_levels.h`. 7. **Build system parity.** Every change must be reflected in both - CMakeLists.txt and Buck's xplat.bzl. + CMakeLists.txt and Buck's xplat.bzl. `tests/test_simd_registry.py` checks + the per-level file lists. ## Conversion approach diff --git a/thirdparty/faiss/faiss/factory_tools.cpp b/thirdparty/faiss/faiss/factory_tools.cpp index 096abddb4..7c2b7232e 100644 --- a/thirdparty/faiss/faiss/factory_tools.cpp +++ b/thirdparty/faiss/faiss/factory_tools.cpp @@ -20,10 +20,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -124,6 +126,11 @@ std::string reverse_index_factory(const faiss::Index* index) { dynamic_cast( ivf_index)) { return prefix + "," + sq_types.at(sq_index->sq.qtype); + } else if ( + const faiss::IndexIVFPQR* ivfpqr_index = + dynamic_cast(ivf_index)) { + return prefix + ",PQ" + std::to_string(ivfpqr_index->pq.M) + "+" + + std::to_string(ivfpqr_index->refine_pq.M); } else if ( const faiss::IndexIVFPQ* ivfpq_index = dynamic_cast(ivf_index)) { @@ -178,12 +185,23 @@ std::string reverse_index_factory(const faiss::Index* index) { } else if ( const faiss::IndexHNSW* hnsw_index = dynamic_cast(index)) { - return "HNSW" + std::to_string(get_hnsw_M(hnsw_index)); + std::string hnsw_prefix = + "HNSW" + std::to_string(get_hnsw_M(hnsw_index)); + const faiss::Index* storage = hnsw_index->storage; + if (!storage || dynamic_cast(storage)) { + return hnsw_prefix; + } + return hnsw_prefix + "," + reverse_index_factory(storage); } else if ( const faiss::IndexNSG* nsg_index = dynamic_cast(index)) { return "NSG" + std::to_string(nsg_index->nsg.R) + "," + reverse_index_factory(nsg_index->storage); + } else if ( + const faiss::IndexPiPNN* pipnn_index = + dynamic_cast(index)) { + return "PiPNN" + std::to_string(pipnn_index->pipnn.R) + "," + + reverse_index_factory(pipnn_index->storage); } else if ( const faiss::IndexRefine* refine_index = dynamic_cast(index)) { diff --git a/thirdparty/faiss/faiss/gpu/CMakeLists.txt b/thirdparty/faiss/faiss/gpu/CMakeLists.txt index 2387eada1..dfb0aa022 100644 --- a/thirdparty/faiss/faiss/gpu/CMakeLists.txt +++ b/thirdparty/faiss/faiss/gpu/CMakeLists.txt @@ -201,7 +201,7 @@ function(generate_ivf_interleaved_code) "128|1|1" "128|128|3" "128|256|4" - "128|32|2" + "64|32|2" "128|512|8" "128|64|3" "64|2048|8" @@ -252,6 +252,7 @@ generate_ivf_interleaved_code() if(FAISS_ENABLE_CUVS) list(APPEND FAISS_GPU_HEADERS + Dataset.h GpuIndexBinaryCagra.h GpuIndexCagra.h impl/BinaryCuvsCagra.cuh @@ -263,6 +264,7 @@ if(FAISS_ENABLE_CUVS) utils/CuvsFilterConvert.h utils/CuvsUtils.h) list(APPEND FAISS_GPU_SRC + Dataset.cu GpuIndexBinaryCagra.cu GpuIndexCagra.cu impl/BinaryCuvsCagra.cu diff --git a/thirdparty/faiss/faiss/gpu/Dataset.cu b/thirdparty/faiss/faiss/gpu/Dataset.cu new file mode 100644 index 000000000..fb6cf1674 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu/Dataset.cu @@ -0,0 +1,456 @@ +/* + * 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. + */ + +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace faiss { +namespace gpu { +namespace { + +void checkCuda(cudaError_t error) { + FAISS_THROW_IF_NOT_FMT( + error == cudaSuccess, + "Dataset CUDA operation failed: %s", + cudaGetErrorString(error)); +} + +size_t elementSize(NumericType numericType) { + switch (numericType) { + case NumericType::Float32: + return sizeof(float); + case NumericType::Float16: + return sizeof(half); + case NumericType::Int8: + case NumericType::UInt8: + return 1; + default: + FAISS_THROW_MSG("Unsupported Dataset numeric type"); + } +} + +void validateMetadata( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride) { + const size_t size = elementSize(numericType); + FAISS_THROW_IF_NOT_MSG( + numRows >= 0, "Dataset row count must be nonnegative"); + FAISS_THROW_IF_NOT_MSG(dim > 0, "Dataset dimension must be positive"); + FAISS_THROW_IF_NOT_MSG( + rowStride >= dim && + rowStride <= std::numeric_limits::max(), + "Dataset row stride must be at least dim and fit in uint32_t"); + FAISS_THROW_IF_NOT_MSG( + numRows == 0 || data != nullptr, + "A nonempty Dataset requires a data pointer"); + FAISS_THROW_IF_NOT_MSG( + reinterpret_cast(data) % size == 0, + "Dataset pointer must be aligned for its numeric type"); + FAISS_THROW_IF_NOT_MSG( + static_cast(numRows) <= + static_cast( + std::numeric_limits::max()) / + static_cast(rowStride) / size, + "Dataset storage size overflows the address space"); +} + +void validateHostPointer(const void* data, idx_t numRows) { + if (numRows == 0) { + return; + } + cudaPointerAttributes attributes{}; + checkCuda(cudaPointerGetAttributes(&attributes, data)); + FAISS_THROW_IF_NOT_MSG( + attributes.type != cudaMemoryTypeDevice, + "Dataset::viewHost requires host-accessible memory"); +} + +void validateDevicePointer(const void* data, idx_t numRows, int device) { + FAISS_THROW_IF_NOT_MSG( + device >= 0 && device < getNumDevices(), + "Dataset requires a valid CUDA device"); + if (numRows == 0) { + return; + } + DeviceScope scope(device); + cudaPointerAttributes attributes{}; + checkCuda(cudaPointerGetAttributes(&attributes, data)); + FAISS_THROW_IF_NOT_MSG( + attributes.type == cudaMemoryTypeDevice || + attributes.type == cudaMemoryTypeManaged || + attributes.devicePointer == data, + "Dataset::viewDevice requires device-accessible memory"); + FAISS_THROW_IF_NOT_MSG( + attributes.type != cudaMemoryTypeDevice || + attributes.device == device, + "Dataset pointer belongs to a different CUDA device"); +} + +void validateBBQQuantizer( + const BBQQuantizer& quantizer, + idx_t numRows, + int dim, + NumericType numericType, + int device) { + namespace bbq = cuvs::preprocessing::quantize::bbq; + validateMetadata(quantizer.centroid, 1, dim, numericType, dim); + validateDevicePointer(quantizer.centroid, 1, device); + FAISS_THROW_IF_NOT_MSG( + quantizer.codeLayout >= BBQCodeLayout::Packed1Bit && + quantizer.codeLayout <= BBQCodeLayout::Packed8Bit, + "Invalid BBQ code layout"); + const auto rowLength = bbq::get_encoded_row_length( + dim, static_cast(quantizer.codeLayout)); + validateMetadata( + quantizer.codes, numRows, rowLength, NumericType::UInt8, rowLength); + FAISS_THROW_IF_NOT_MSG( + reinterpret_cast(quantizer.codes) % alignof(uint32_t) == + 0, + "BBQ codes require a 4-byte aligned device pointer"); + validateDevicePointer(quantizer.codes, numRows, device); + for (const float* values : + {quantizer.lowerIntervals, + quantizer.upperIntervals, + quantizer.additionalCorrections, + quantizer.dequantDelta, + quantizer.dequantSumDelta, + quantizer.rowNorm}) { + validateMetadata(values, numRows, 1, NumericType::Float32, 1); + validateDevicePointer(values, numRows, device); + } + const auto sumsAddress = + reinterpret_cast(quantizer.quantizedComponentSums); + FAISS_THROW_IF_NOT_MSG( + (numRows == 0 || quantizer.quantizedComponentSums != nullptr) && + sumsAddress % alignof(int32_t) == 0, + "BBQ component sums require an aligned int32 device pointer"); + validateDevicePointer(quantizer.quantizedComponentSums, numRows, device); +} + +struct DatasetStorage { + virtual ~DatasetStorage() = default; + virtual const void* getData() const = 0; +}; + +template +struct TypedDatasetStorage : DatasetStorage { + explicit TypedDatasetStorage(Storage value) : value_(std::move(value)) {} + + const void* getData() const override { + return value_.view().data_handle(); + } + + Storage value_; +}; + +template +std::unique_ptr makeOwnedStorage( + GpuResources* resources, + const Dataset& source, + int device) { + auto& handle = resources->getRaftHandle(device); + const auto* data = static_cast(source.getData()); + const auto rows = source.getNumRows(); + const auto dim = static_cast(source.getDim()); + const auto stride = source.getRowStride(); + auto owner = source.isDevice() + ? cuvs::neighbors::make_device_padded_dataset( + handle, + raft::make_device_strided_matrix_view( + data, rows, dim, stride)) + : cuvs::neighbors::make_device_padded_dataset( + handle, + raft::make_host_strided_matrix_view( + data, rows, dim, stride)); + using Owner = cuvs::neighbors::device_padded_dataset; + return std::make_unique>(std::move(*owner)); +} + +} // namespace + +struct Dataset::Impl { + const void* data; + idx_t numRows; + int dim; + idx_t rowStride; + NumericType numericType; + int device; + Layout layout; + std::optional bbq; + std::optional secondaryBbq; + // Declared before storage so resources outlive the allocation. + std::shared_ptr resources; + std::unique_ptr storage; + + Impl(const void* ptr, + idx_t rows, + int columns, + idx_t stride, + NumericType type, + int gpu, + Layout l) + : data(ptr), + numRows(rows), + dim(columns), + rowStride(stride), + numericType(type), + device(gpu), + layout(l) {} + + ~Impl() { + if (storage) { + DeviceScope scope(device); + storage.reset(); + } + } +}; + +Dataset::Dataset(std::unique_ptr impl) : impl_(std::move(impl)) {} +Dataset::~Dataset() = default; +Dataset::Dataset(Dataset&&) noexcept = default; +Dataset& Dataset::operator=(Dataset&&) noexcept = default; + +const Dataset::Impl& Dataset::getImpl() const { + FAISS_THROW_IF_NOT_MSG(impl_, "Cannot access a moved-from Dataset"); + return *impl_; +} + +Dataset Dataset::viewHost( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride) { + validateMetadata(data, numRows, dim, numericType, rowStride); + validateHostPointer(data, numRows); + auto impl = std::make_unique( + data, numRows, dim, rowStride, numericType, -1, Layout::Standard); + return Dataset(std::move(impl)); +} + +Dataset Dataset::viewDevice( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride, + int device) { + validateMetadata(data, numRows, dim, numericType, rowStride); + validateDevicePointer(data, numRows, device); + auto impl = std::make_unique( + data, + numRows, + dim, + rowStride, + numericType, + device, + Layout::Standard); + return Dataset(std::move(impl)); +} + +Dataset Dataset::viewDevicePadded( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride, + int device) { + auto result = + viewDevice(data, numRows, dim, numericType, rowStride, device); + FAISS_THROW_IF_NOT_MSG( + result.isCagraCompatible(), + "A padded Dataset requires 16-byte base alignment and the exact " + "CAGRA row stride"); + result.impl_->layout = Layout::Padded; + return result; +} + +Dataset Dataset::viewDeviceBBQ( + const BBQQuantizer& source, + idx_t numRows, + int dim, + NumericType numericType, + int device, + const BBQQuantizer* secondary) { + validateBBQQuantizer(source, numRows, dim, numericType, device); + if (secondary) { + validateBBQQuantizer(*secondary, numRows, dim, numericType, device); + } + auto impl = std::make_unique( + nullptr, numRows, dim, 0, numericType, device, Layout::BBQ); + impl->bbq = source; + if (secondary) { + impl->secondaryBbq = *secondary; + } + return Dataset(std::move(impl)); +} + +Dataset Dataset::makeDevicePadded( + GpuResourcesProvider* resources, + const Dataset& source, + int device) { + FAISS_THROW_IF_NOT_MSG(resources, "Dataset requires GPU resources"); + FAISS_THROW_IF_NOT_MSG( + device >= 0 && device < getNumDevices(), + "Dataset requires a valid CUDA device"); + const auto& src = source.getImpl(); + FAISS_THROW_IF_NOT_MSG( + src.layout != Layout::BBQ, + "Dataset::makeDevicePadded requires a dense Dataset"); + const auto stride = cuvs::neighbors::cagra_required_row_width( + src.dim, elementSize(src.numericType)); + validateMetadata( + source.getData(), src.numRows, src.dim, src.numericType, stride); + auto impl = std::make_unique( + nullptr, + src.numRows, + src.dim, + stride, + src.numericType, + device, + Layout::Padded); + impl->resources = resources->getResources(); + FAISS_THROW_IF_NOT_MSG(impl->resources, "Dataset requires GPU resources"); + + DeviceScope scope(device); + switch (src.numericType) { + case NumericType::Float32: + impl->storage = makeOwnedStorage( + impl->resources.get(), source, device); + break; + case NumericType::Float16: + impl->storage = makeOwnedStorage( + impl->resources.get(), source, device); + break; + case NumericType::Int8: + impl->storage = makeOwnedStorage( + impl->resources.get(), source, device); + break; + case NumericType::UInt8: + impl->storage = makeOwnedStorage( + impl->resources.get(), source, device); + break; + default: + FAISS_THROW_MSG("Unsupported Dataset numeric type"); + } + return Dataset(std::move(impl)); +} + +const void* Dataset::getData() const { + const auto& impl = getImpl(); + FAISS_THROW_IF_NOT_MSG( + impl.layout != Layout::BBQ, + "A BBQ Dataset has no dense data pointer"); + return impl.storage ? impl.storage->getData() : impl.data; +} +idx_t Dataset::getNumRows() const { + return getImpl().numRows; +} +int Dataset::getDim() const { + return getImpl().dim; +} +idx_t Dataset::getRowStride() const { + const auto& impl = getImpl(); + FAISS_THROW_IF_NOT_MSG( + impl.layout != Layout::BBQ, + "A BBQ Dataset has no dense row stride"); + return impl.rowStride; +} +NumericType Dataset::getNumericType() const { + return getImpl().numericType; +} +int Dataset::getDevice() const { + return getImpl().device; +} +Dataset::Layout Dataset::getLayout() const { + return getImpl().layout; +} +bool Dataset::isDevice() const { + return getImpl().device >= 0; +} +bool Dataset::ownsData() const { + return bool(getImpl().storage); +} +bool Dataset::isCagraCompatible() const { + const auto& impl = getImpl(); + return impl.layout != Layout::BBQ && isDevice() && + reinterpret_cast(getData()) % 16 == 0 && + impl.rowStride == + cuvs::neighbors::cagra_required_row_width( + impl.dim, elementSize(impl.numericType)); +} + +Dataset Dataset::view() const { + const auto& src = getImpl(); + auto impl = std::make_unique( + src.layout == Layout::BBQ ? nullptr : getData(), + src.numRows, + src.dim, + src.rowStride, + src.numericType, + src.device, + src.layout); + impl->bbq = src.bbq; + impl->secondaryBbq = src.secondaryBbq; + return Dataset(std::move(impl)); +} + +const BBQQuantizer* Dataset::getBBQQuantizer(bool secondary) const { + const auto& impl = getImpl(); + const auto& quantizer = secondary ? impl.secondaryBbq : impl.bbq; + return quantizer ? &*quantizer : nullptr; +} + +void Dataset::copyToHost(void* destination) const { + const auto& impl = getImpl(); + FAISS_THROW_IF_NOT_MSG( + impl.layout != Layout::BBQ, + "Dataset::copyToHost requires a dense Dataset"); + if (impl.numRows == 0) { + return; + } + FAISS_THROW_IF_NOT_MSG(destination, "Dataset copy requires a destination"); + const size_t size = elementSize(impl.numericType); + const size_t width = impl.dim * size; + const size_t pitch = impl.rowStride * size; + if (isDevice()) { + DeviceScope scope(impl.device); + checkCuda(cudaDeviceSynchronize()); + checkCuda(cudaMemcpy2D( + destination, + width, + getData(), + pitch, + width, + impl.numRows, + cudaMemcpyDefault)); + } else { + const auto* input = static_cast(getData()); + auto* output = static_cast(destination); + for (idx_t row = 0; row < impl.numRows; ++row) { + std::memcpy(output + row * width, input + row * pitch, width); + } + } +} + +} // namespace gpu +} // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu/Dataset.h b/thirdparty/faiss/faiss/gpu/Dataset.h new file mode 100644 index 000000000..9f66f118f --- /dev/null +++ b/thirdparty/faiss/faiss/gpu/Dataset.h @@ -0,0 +1,164 @@ +/* + * 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. + */ + +#pragma once + +#include + +#include +#include + +namespace faiss { +namespace gpu { +class GpuResourcesProvider; + +enum class BBQCodeLayout { + Packed1Bit, + Transposed2Bit, + Transposed4Bit, + Packed4Bit, + Packed7Bit, + Packed8Bit +}; + +/** Precomputed BBQ codes and corrections in caller-owned device buffers. + * + * Codes are packed rows in codeLayout with a 4-byte aligned base pointer. Each + * correction array has one entry per row; centroid has dim entries of the + * Dataset numeric type. Corrections must have been generated for metric. All + * buffers must outlive uses of the Dataset. + */ +struct BBQQuantizer { + const uint8_t* codes = nullptr; + const float* lowerIntervals = nullptr; + const float* upperIntervals = nullptr; + const float* additionalCorrections = nullptr; + const int32_t* quantizedComponentSums = nullptr; + const void* centroid = nullptr; + const float* dequantDelta = nullptr; + const float* dequantSumDelta = nullptr; + const float* rowNorm = nullptr; + BBQCodeLayout codeLayout = BBQCodeLayout::Packed1Bit; + MetricType metric = METRIC_L2; + float centroidNormSquared = 0; +}; + +/** Caller-controlled vector storage for cuVS CAGRA. + * + * Dense dimensions and row strides are in elements, with contiguous columns. + * Binary vectors use UInt8, and their dimension is the number of bytes, not + * bits. Views never own or copy their allocation. An owning Dataset controls + * the allocation's lifetime; CAGRA always borrows it. Keep the backing + * allocation alive and unchanged until all indexes using it and queued GPU work + * finish. Moving an owning Dataset preserves its allocation and existing + * borrowed views. + */ +class Dataset { + public: + enum class Layout { Standard, Padded, BBQ }; + + ~Dataset(); + Dataset(Dataset&&) noexcept; + Dataset& operator=(Dataset&&) noexcept; + Dataset(const Dataset&) = delete; + Dataset& operator=(const Dataset&) = delete; + + /// Borrow host storage. rowStride must be at least dim. + static Dataset viewHost( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride); + + /// Borrow storage accessible on device. A Standard view can also be + /// CAGRA-compatible when its physical stride and alignment satisfy padding. + /// When used by CAGRA, elements between dim and rowStride must be zero. + static Dataset viewDevice( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride, + int device); + + /// Borrow CAGRA-compatible device storage without copying. The base address + /// must be 16-byte aligned and rowStride must equal dim rounded up to a + /// 16-byte row width. The caller must zero elements between dim and + /// rowStride, including for compatible Standard views used by CAGRA. + static Dataset viewDevicePadded( + const void* data, + idx_t numRows, + int dim, + NumericType numericType, + idx_t rowStride, + int device); + + /// Borrow one symmetric or two asymmetric BBQ quantizers without copying + /// their buffers. Both quantizers describe the same vectors, numeric type, + /// and metric. BBQ supports NN-descent graph construction; attach dense + /// padded storage with CAGRA updateDataset before searching. + static Dataset viewDeviceBBQ( + const BBQQuantizer& source, + idx_t numRows, + int dim, + NumericType numericType, + int device, + const BBQQuantizer* secondary = nullptr); + + /// Create padded device storage using cuVS make_device_padded_dataset. + /// Device/managed input whose stride already matches the required padding + /// is rejected; use a view for that storage. Copies logical columns and + /// zeroes padding asynchronously on the resource's stream. Source data must + /// be ready on that stream and stay alive and unchanged until copying + /// finishes. Order subsequent use on that stream. Retains the resources + /// needed to release the allocation. + static Dataset makeDevicePadded( + GpuResourcesProvider* resources, + const Dataset& source, + int device); + + /// Dense storage only; BBQ has separate code and correction buffers. + const void* getData() const; + idx_t getNumRows() const; + int getDim() const; + /// Dense storage only, in elements. + idx_t getRowStride() const; + NumericType getNumericType() const; + int getDevice() const; // -1 for host storage + Layout getLayout() const; + bool isDevice() const; + bool ownsData() const; + + /// Reports dense device residency, alignment, and exact required row + /// stride. Returns false for BBQ. Does not inspect padding values; zero + /// padding is a caller contract. + bool isCagraCompatible() const; + + /// Create a non-owning view of the same storage by copying its metadata. + /// Does not retain ownership of the backing allocation. + Dataset view() const; + + /// Copy dense logical columns into packed host storage. destination must + /// have numRows * dim * sizeof(element) bytes. Completes all device work + /// using the source device before copying and returns with the host data + /// ready. + void copyToHost(void* destination) const; + + private: + template + friend class CuvsCagra; + + struct Impl; + explicit Dataset(std::unique_ptr impl); + const Impl& getImpl() const; + const BBQQuantizer* getBBQQuantizer(bool secondary) const; + std::unique_ptr impl_; +}; + +} // namespace gpu +} // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu/GpuCloner.cpp b/thirdparty/faiss/faiss/gpu/GpuCloner.cpp index bff038357..57d0a4264 100644 --- a/thirdparty/faiss/faiss/gpu/GpuCloner.cpp +++ b/thirdparty/faiss/faiss/gpu/GpuCloner.cpp @@ -14,7 +14,7 @@ #include #include -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS #include #include #endif @@ -28,7 +28,7 @@ #include #include #include -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS #include #include #endif @@ -92,7 +92,7 @@ Index* ToCPUCloner::clone_Index(const Index* index) { // (inverse op of ToGpuClonerMultiple) } -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS else if (auto icg = dynamic_cast(index)) { IndexHNSWCagra* res = new IndexHNSWCagra(); if (icg->get_numeric_type() != faiss::NumericType::Float32) { @@ -171,6 +171,7 @@ Index* ToGpuCloner::clone_Index(const Index* index) { config.flatConfig.useFloat16 = useFloat16CoarseQuantizer; config.use_cuvs = use_cuvs; config.allowCpuCoarseQuantizer = allowCpuCoarseQuantizer; + config.deterministic_tie_break = deterministic_tie_break; GpuIndexIVFFlat* res = new GpuIndexIVFFlat( provider, ifl->d, ifl->nlist, ifl->metric_type, config); @@ -189,6 +190,7 @@ Index* ToGpuCloner::clone_Index(const Index* index) { config.flatConfig.useFloat16 = useFloat16CoarseQuantizer; config.use_cuvs = use_cuvs; config.allowCpuCoarseQuantizer = allowCpuCoarseQuantizer; + config.deterministic_tie_break = deterministic_tie_break; GpuIndexIVFScalarQuantizer* res = new GpuIndexIVFScalarQuantizer( provider, @@ -224,6 +226,7 @@ Index* ToGpuCloner::clone_Index(const Index* index) { config.use_cuvs = use_cuvs; config.interleavedLayout = use_cuvs; config.allowCpuCoarseQuantizer = allowCpuCoarseQuantizer; + config.deterministic_tie_break = deterministic_tie_break; GpuIndexIVFPQ* res = new GpuIndexIVFPQ(provider, ipq, config); @@ -233,14 +236,14 @@ Index* ToGpuCloner::clone_Index(const Index* index) { return res; } -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS else if (auto icg = dynamic_cast(index)) { GpuIndexCagraConfig config; config.device = device; - GpuIndexCagra* res = - new GpuIndexCagra(provider, icg->d, icg->metric_type, config); - res->copyFrom_ex(icg, icg->get_numeric_type()); - return res; + auto res = std::make_unique( + provider, icg->d, icg->metric_type, config); + res->copyFrom(icg); + return res.release(); } #endif else { @@ -533,7 +536,7 @@ faiss::IndexBinary* index_binary_gpu_to_cpu( ii->copyTo(ret); return ret; } -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS else if (auto ii = dynamic_cast(gpu_index)) { IndexBinaryHNSWCagra* ret = new IndexBinaryHNSWCagra(); ii->copyTo(ret); @@ -555,15 +558,15 @@ faiss::IndexBinary* index_binary_cpu_to_gpu( config.device = device; return new GpuIndexBinaryFlat(provider, ii, config); } -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#if defined USE_NVIDIA_CUVS else if ( auto ii = dynamic_cast(index)) { GpuIndexCagraConfig config; config.device = device; - GpuIndexBinaryCagra* res = - new GpuIndexBinaryCagra(provider, ii->d, config); + auto res = + std::make_unique(provider, ii->d, config); res->copyFrom(ii); - return res; + return res.release(); } #endif else { diff --git a/thirdparty/faiss/faiss/gpu/GpuCloner.h b/thirdparty/faiss/faiss/gpu/GpuCloner.h index d92d81ffe..b3b4c2a00 100644 --- a/thirdparty/faiss/faiss/gpu/GpuCloner.h +++ b/thirdparty/faiss/faiss/gpu/GpuCloner.h @@ -70,6 +70,8 @@ struct ToGpuClonerMultiple : faiss::Cloner, GpuMultipleClonerOptions { faiss::Index* index_gpu_to_cpu(const faiss::Index* gpu_index); /// converts any CPU index that can be converted to GPU +/// CAGRA clones contain only the graph. Call updateDataset with caller-owned, +/// compatible device storage before searching. faiss::Index* index_cpu_to_gpu( GpuResourcesProvider* provider, int device, @@ -105,6 +107,8 @@ faiss::IndexBinary* index_binary_gpu_to_cpu( const faiss::IndexBinary* gpu_index); /// converts any CPU index that can be converted to GPU +/// CAGRA clones contain only the graph. Call updateDataset with caller-owned, +/// compatible device storage before searching. faiss::IndexBinary* index_binary_cpu_to_gpu( GpuResourcesProvider* provider, int device, diff --git a/thirdparty/faiss/faiss/gpu/GpuClonerOptions.h b/thirdparty/faiss/faiss/gpu/GpuClonerOptions.h index fb7ab183a..14741a643 100644 --- a/thirdparty/faiss/faiss/gpu/GpuClonerOptions.h +++ b/thirdparty/faiss/faiss/gpu/GpuClonerOptions.h @@ -42,6 +42,9 @@ struct GpuClonerOptions { /// Use the cuVS implementation. Opt-in: see GpuIndexConfig::use_cuvs. bool use_cuvs = false; + /// IVF indexes only: see GpuIndexIVFConfig::deterministic_tie_break. + bool deterministic_tie_break = false; + /// This flag controls the CPU fallback logic for coarse quantizer /// component of the index. When set to false (default), the cloner will /// throw an exception for indices not implemented on GPU. When set to diff --git a/thirdparty/faiss/faiss/gpu/GpuDistance.cu b/thirdparty/faiss/faiss/gpu/GpuDistance.cu index 76f5e6537..112d9cce1 100644 --- a/thirdparty/faiss/faiss/gpu/GpuDistance.cu +++ b/thirdparty/faiss/faiss/gpu/GpuDistance.cu @@ -233,10 +233,7 @@ void bfKnn(GpuResourcesProvider* prov, const GpuDistanceParams& args) { "limitation: both vectorType and queryType must currently " "be the same (F32 / F16 / BF16"); -// cuVS brute-force (flat) lives in the full cuVS build only; the aarch64 -// cuvs-ivfpq subset omits neighbors/brute_force, so FAISS_CUVS_NO_FLAT compiles -// this branch out and bfKnn falls back to faiss's own kernels below. -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_FLAT) +#if defined USE_NVIDIA_CUVS // Note: For now, cuVS bfknn requires queries and vectors to be same layout if (should_use_cuvs(args) && args.queriesRowMajor == args.vectorsRowMajor && args.outIndicesType == IndicesDataType::I64 && diff --git a/thirdparty/faiss/faiss/gpu/GpuIndex.cu b/thirdparty/faiss/faiss/gpu/GpuIndex.cu index a2e41cd34..2fd8e612e 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndex.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndex.cu @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -475,6 +476,33 @@ void GpuIndex::search_and_reconstruct( reconstruct_batch(n * k, labels, recons); } +void GpuIndex::searchImpl_ex_( + idx_t n, + const void* x, + NumericType numeric_type, + int k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + if (numeric_type == NumericType::Float32) { + searchImpl_( + n, static_cast(x), k, distances, labels, params); + } else if (numeric_type == NumericType::Float16) { + // The fp16 queries were copied to the device at half the cost of + // float32; widen them there so that any index can search them + auto stream = resources_->getDefaultStream(config_.device); + + Tensor queries( + const_cast(static_cast(x)), {n, this->d}); + auto queriesFloat = convertTensorTemporary( + resources_.get(), stream, queries); + + searchImpl_(n, queriesFloat.data(), k, distances, labels, params); + } else { + FAISS_THROW_MSG("GpuIndex::searchImpl_: unsupported numeric type"); + } +} + void GpuIndex::searchNonPaged_ex_( idx_t n, const void* x, diff --git a/thirdparty/faiss/faiss/gpu/GpuIndex.h b/thirdparty/faiss/faiss/gpu/GpuIndex.h index b688d6270..f0e621c83 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndex.h +++ b/thirdparty/faiss/faiss/gpu/GpuIndex.h @@ -213,6 +213,9 @@ class GpuIndex : public faiss::Index { idx_t* labels, const SearchParameters* params) const = 0; + /// Search with queries of the given numeric type; all data is guaranteed + /// to be resident on our device. The default handles Float32 and widens + /// Float16 queries to float32 on the device before calling searchImpl_ virtual void searchImpl_ex_( idx_t n, const void* x, @@ -220,19 +223,7 @@ class GpuIndex : public faiss::Index { int k, float* distances, idx_t* labels, - const SearchParameters* params) const { - if (numeric_type == NumericType::Float32) { - searchImpl_( - n, - static_cast(x), - k, - distances, - labels, - params); - } else { - FAISS_THROW_MSG("GpuIndex::searchImpl_: unsupported numeric type"); - } - } + const SearchParameters* params) const; private: /// Calls addImpl_ for a single page of GPU-resident data diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.cu b/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.cu index d2d560f43..31ac435c8 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.cu @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,8 @@ #include #include +#include +#include #include #include "GpuResources.h" @@ -67,7 +70,9 @@ GpuIndexBinaryCagra::GpuIndexBinaryCagra( this->is_trained = false; } -GpuIndexBinaryCagra::~GpuIndexBinaryCagra() {} +GpuIndexBinaryCagra::~GpuIndexBinaryCagra() { + reset(); +} int GpuIndexBinaryCagra::getDevice() const { return cagraConfig_.device; @@ -77,40 +82,75 @@ std::shared_ptr GpuIndexBinaryCagra::getResources() { return resources_; } -void GpuIndexBinaryCagra::train(idx_t n, const uint8_t* x) { - // The config is shared with the float index; there is no binary - // multi-GPU build, so reject rather than silently ignoring the request. +void GpuIndexBinaryCagra::train(idx_t, const uint8_t*) { + FAISS_THROW_MSG( + "GpuIndexBinaryCagra requires train(const Dataset&); " + "construct a caller-owned Dataset first"); +} + +void GpuIndexBinaryCagra::add(idx_t, const uint8_t*) { + FAISS_THROW_MSG( + "GpuIndexBinaryCagra requires add(const Dataset&); " + "construct a caller-owned Dataset first"); +} + +void GpuIndexBinaryCagra::train(const Dataset& dataset) { + if (is_trained) { + return; + } + FAISS_THROW_IF_MSG( + dataset.getLayout() == Dataset::Layout::BBQ, + "BBQ datasets do not support binary CAGRA Hamming distance"); FAISS_THROW_IF_MSG( cagraConfig_.devices.size() > 1, "binary CAGRA has no multi-GPU build; " "GpuIndexCagraConfig::devices must name at most one device"); - - DeviceScope scope(cagraConfig_.device); - if (this->is_trained) { - FAISS_ASSERT(index_); - return; - } - FAISS_ASSERT(!index_); + FAISS_THROW_IF_NOT_MSG( + dataset.getDim() == this->d / 8 && + dataset.getNumericType() == NumericType::UInt8, + "Binary CAGRA requires a UInt8 Dataset with dim equal to d / 8"); + FAISS_THROW_IF_NOT_MSG( + dataset.getNumRows() > 0 && + dataset.getNumRows() <= + std::numeric_limits::max(), + "Binary CAGRA requires between 1 and UINT32_MAX dataset rows"); + FAISS_THROW_IF_NOT_MSG( + !dataset.isDevice() || dataset.getDevice() == getDevice(), + "Dataset device must match the CAGRA index device"); - index_ = std::make_shared( - this->resources_.get(), + DeviceScope scope(cagraConfig_.device); + auto built = std::make_shared( + resources_.get(), this->d, cagraConfig_.intermediate_graph_degree, cagraConfig_.graph_degree, static_cast(cagraConfig_.build_algo), cagraConfig_.nn_descent_niter, - cagraConfig_.store_dataset, INDICES_64_BIT); + built->train(dataset); + index_ = std::move(built); + this->is_trained = true; + this->ntotal = dataset.getNumRows(); +} - index_->train(n, x); +void GpuIndexBinaryCagra::add(const Dataset& dataset) { + train(dataset); +} - this->is_trained = true; - this->ntotal = n; +void GpuIndexBinaryCagra::updateDataset(const Dataset& dataset) { + FAISS_THROW_IF_NOT_MSG( + is_trained && index_, + "Build the CAGRA graph before attaching data"); + FAISS_THROW_IF_NOT_MSG( + dataset.isDevice() && dataset.getDevice() == getDevice(), + "Search Dataset must reside on the CAGRA index device"); + DeviceScope scope(cagraConfig_.device); + index_->updateDataset(dataset); } -void GpuIndexBinaryCagra::add(idx_t n, const uint8_t* x) { - train(n, x); +bool GpuIndexBinaryCagra::isSearchReady() const { + return is_trained && index_ && index_->isSearchReady(); } void GpuIndexBinaryCagra::search( @@ -127,7 +167,9 @@ void GpuIndexBinaryCagra::search( return; } - // validateKSelect(k); + FAISS_THROW_IF_NOT_MSG( + isSearchReady(), + "CAGRA has no search Dataset; call updateDataset with compatible device storage"); // The input vectors may be too large for the GPU, but we still // assume that the output distances and labels are not. @@ -274,53 +316,108 @@ void GpuIndexBinaryCagra::searchImpl_( } } -void GpuIndexBinaryCagra::copyFrom(const faiss::IndexBinaryHNSWCagra* index) { - FAISS_ASSERT(index); +void GpuIndexBinaryCagra::copyFrom( + const faiss::IndexBinaryHNSWCagra* index, + Dataset* dataset) { + FAISS_THROW_IF_NOT(index); + FAISS_THROW_IF_MSG( + cagraConfig_.devices.size() > 1, + "binary CAGRA does not support multi-GPU graph import"); + FAISS_THROW_IF_NOT_MSG( + index->is_trained && index->ntotal > 0 && + index->ntotal <= std::numeric_limits::max(), + "CPU HNSW must contain a trained, nonempty CAGRA graph"); + FAISS_THROW_IF_NOT_MSG( + index->d > 0 && index->d % 8 == 0, + "CPU binary HNSW dimension must be a positive multiple of 8"); + const IndexBinaryFlat* cpuStorage = nullptr; + if (dataset) { + FAISS_THROW_IF_NOT_MSG( + dataset->getDim() == index->d / 8 && + dataset->getNumRows() == index->ntotal && + dataset->getNumericType() == NumericType::UInt8, + "Dataset shape and type must match the CPU binary HNSW index"); + FAISS_THROW_IF_NOT_MSG( + dataset->isCagraCompatible() && + dataset->getDevice() == getDevice(), + "Destination Dataset must be compatible storage on the CAGRA device"); + cpuStorage = dynamic_cast(index->storage); + FAISS_THROW_IF_NOT_MSG( + cpuStorage && cpuStorage->d == index->d && + cpuStorage->ntotal == index->ntotal && + cpuStorage->xb.size() >= + static_cast(index->ntotal) * + (index->d / 8), + "CPU binary HNSW vector storage does not match its metadata"); + } DeviceScope scope(cagraConfig_.device); - - this->d = index->d; - FAISS_THROW_IF_NOT(this->d % 8 == 0); - this->code_size = index->d / 8; - this->ntotal = index->ntotal; - this->is_trained = index->is_trained; - - IndexBinaryFlat* flat_storage = - dynamic_cast(index->storage); - FAISS_ASSERT(flat_storage); - fprintf(stderr, - "WARNING: GpuIndexBinaryCagra::copyFrom uses non-owning CPU " - "storage. Keep the source IndexBinaryHNSWCagra alive for the " - "lifetime of the GpuIndexBinaryCagra.\n"); - - auto hnsw = index->hnsw; - // copy level 0 to a dense knn graph matrix - std::vector knn_graph; - knn_graph.resize(index->ntotal * hnsw.nb_neighbors(0)); + const auto& hnsw = index->hnsw; + const auto graphDegree = hnsw.nb_neighbors(0); + FAISS_THROW_IF_NOT_MSG( + graphDegree > 0 && + hnsw.offsets.size() == + static_cast(index->ntotal) + 1, + "CPU HNSW has no complete base-layer graph"); + std::vector knnGraph(index->ntotal * graphDegree); #pragma omp parallel for - for (size_t i = 0; i < index->ntotal; ++i) { + for (idx_t i = 0; i < index->ntotal; ++i) { size_t begin, end; hnsw.neighbor_range(i, 0, &begin, &end); for (size_t j = begin; j < end; j++) { - knn_graph[i * hnsw.nb_neighbors(0) + (j - begin)] = - hnsw.neighbors[j]; + // Empty HNSW slots become self-edges; every CAGRA edge must name + // a valid node. + const auto neighbor = hnsw.neighbors[j]; + knnGraph[i * graphDegree + (j - begin)] = + neighbor < 0 ? i : neighbor; } } - index_ = std::make_shared( - this->resources_.get(), - this->d, + // Allocate replacement graph state before modifying caller storage. + auto imported = std::make_shared( + resources_.get(), + index->d, index->ntotal, - hnsw.nb_neighbors(0), - flat_storage->xb.data(), - knn_graph.data(), + graphDegree, + dataset, + knnGraph.data(), INDICES_64_BIT); - + // Finish previous uses before overwriting caller storage or replacing + // the old graph. Other users of the destination must also be quiescent. + resources_->syncDefaultStream(getDevice()); + if (dataset) { + // Dataset* is an explicit writable-destination contract; views do not + // track the constness of their underlying allocation. + auto* destination = + static_cast(const_cast(dataset->getData())); + const size_t width = index->d / 8; + const size_t pitch = dataset->getRowStride(); + const auto stream = resources_->getDefaultStream(getDevice()); + CUDA_VERIFY(cudaMemsetAsync( + destination, + 0, + static_cast(index->ntotal) * pitch, + stream)); + raft::copy_matrix( + destination, + pitch, + cpuStorage->xb.data(), + width, + width, + index->ntotal, + stream); + } + resources_->syncDefaultStream(getDevice()); + index_ = std::move(imported); + this->d = index->d; + this->code_size = index->d / 8; + this->ntotal = index->ntotal; this->is_trained = true; } void GpuIndexBinaryCagra::copyTo(faiss::IndexBinaryHNSWCagra* index) const { FAISS_ASSERT(index_ && this->is_trained && index); + const auto& dataset = index_->getDataset(); DeviceScope scope(cagraConfig_.device); @@ -347,12 +444,8 @@ void GpuIndexBinaryCagra::copyTo(faiss::IndexBinaryHNSWCagra* index) const { index->hnsw.set_default_probas(M, 1.0 / log(M)); auto n_train = this->ntotal; - auto stream = resources_->getDefaultStream(cagraConfig_.device); - - auto train_dataset = toHost( - const_cast(index_->get_training_dataset()), - stream, - {idx_t(n_train), this->d / 8}); + std::vector train_dataset(n_train * (this->d / 8)); + dataset.copyToHost(train_dataset.data()); // turn off as level 0 is copied from CAGRA graph index->init_level0 = false; @@ -382,18 +475,17 @@ void GpuIndexBinaryCagra::copyTo(faiss::IndexBinaryHNSWCagra* index) const { void GpuIndexBinaryCagra::reset() { DeviceScope scope(cagraConfig_.device); - if (index_) { - index_->reset(); - this->ntotal = 0; - this->is_trained = false; - } else { - FAISS_ASSERT(this->ntotal == 0); + resources_->getRaftHandleCurrentDevice().sync_stream(); } + index_.reset(); + this->ntotal = 0; + this->is_trained = false; } std::vector GpuIndexBinaryCagra::get_knngraph() const { FAISS_ASSERT(index_ && this->is_trained); + DeviceScope scope(cagraConfig_.device); return index_->get_knngraph(); } diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.h b/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.h index 0c943ef72..713e0fdd1 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.h +++ b/thirdparty/faiss/faiss/gpu/GpuIndexBinaryCagra.h @@ -33,6 +33,7 @@ namespace faiss { namespace gpu { class BinaryCuvsCagra; +class Dataset; struct GpuIndexBinaryCagra : public IndexBinary { public: @@ -49,22 +50,40 @@ struct GpuIndexBinaryCagra : public IndexBinary { /// stream and handle resources on the GPU std::shared_ptr getResources(); - /// Trains CAGRA based on the given vector data and add them along with ids. - /// NB: The use of the add function here is to build the CAGRA graph on - /// the base dataset. Use this function when you want to add vectors with - /// ids. Ref: https://github.com/facebookresearch/faiss/issues/4107 + /// Pointer-based construction is unsupported. Use a caller-owned Dataset. void add(idx_t n, const uint8_t* x) override; - - /// Trains CAGRA based on the given vector data. - /// NB: The use of the train function here is to build the CAGRA graph on - /// the base dataset and is currently the only function to add the full set - /// of vectors (without IDs) to the index. There is no external quantizer to - /// be trained here. void train(idx_t n, const uint8_t* x) override; - /// Initialize ourselves from the given CPU index; will overwrite - /// all data in ourselves - void copyFrom(const faiss::IndexBinaryHNSWCagra* index); + /// Build the full graph, borrowing UInt8 vectors with dim == d / 8. + /// The backing storage must remain alive and unchanged until all index + /// operations have completed. Does nothing if already trained; call reset() + /// before building again. + void train(const Dataset& dataset); + void add(const Dataset& dataset); + void train_dataset(const Dataset& dataset) override { + train(dataset); + } + void add_dataset(const Dataset& dataset) override { + add(dataset); + } + + /// Rebind search storage without changing the graph. The vectors and their + /// ordering must match the training data. Requires compatible device data; + /// any padding must be zero and the caller retains ownership. Previous + /// work on the index stream completes before rebinding. + void updateDataset(const Dataset& dataset); + bool isSearchReady() const; + + /// Copy the CPU graph. Without a Dataset, import only the graph and + /// metadata; attach vectors with updateDataset before search or copyTo. + /// If provided, dataset must describe writable, compatible storage on this + /// device with the CPU index's shape and UInt8 type. Copy CPU vectors into + /// that allocation, zero padding, and borrow it for search. The caller owns + /// the allocation and must keep it alive through index use. Copies complete + /// before return, so the CPU index can be released in either case. + void copyFrom( + const faiss::IndexBinaryHNSWCagra* index, + Dataset* dataset = nullptr); /// Copy ourselves to the given CPU index; will overwrite all data /// in the index instance diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexCagra.cu b/thirdparty/faiss/faiss/gpu/GpuIndexCagra.cu index 0eac9f875..32070fcdf 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexCagra.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexCagra.cu @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -37,6 +38,7 @@ #include #include #include +#include // clang-format off #if __has_include() // Some cuVS versions put helpers::optimize in its own header. @@ -52,6 +54,7 @@ namespace { +#if defined(FAISS_CAGRA_DEVICE_OPTIMIZE) // all_neighbors emits int64 indices, optimize consumes uint32. Narrowing on // device lets the graph stay there. __global__ void kern_narrow_indices( @@ -65,6 +68,8 @@ __global__ void kern_narrow_indices( } } +#endif + } // anonymous namespace namespace faiss { @@ -80,12 +85,35 @@ GpuIndexCagra::GpuIndexCagra( this->is_trained = false; } -void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { +GpuIndexCagra::~GpuIndexCagra() { + reset(); +} + +void GpuIndexCagra::train(const Dataset& dataset) { + if (is_trained) { + return; + } + FAISS_THROW_IF_NOT_MSG( + dataset.getDim() == d, "Dataset dimension does not match CAGRA"); + FAISS_THROW_IF_NOT_MSG( + dataset.getNumRows() > 0 && + dataset.getNumRows() <= + std::numeric_limits::max(), + "CAGRA requires a nonempty Dataset with at most UINT32_MAX rows"); + FAISS_THROW_IF_NOT_MSG( + !dataset.isDevice() || dataset.getDevice() == config_.device, + "Dataset device does not match CAGRA device"); + const auto n = dataset.getNumRows(); + const auto numeric_type = dataset.getNumericType(); + DeviceScope scope(config_.device); if (cagraConfig_.devices.size() > 1) { FAISS_THROW_IF_NOT_MSG( numeric_type == NumericType::Float32, "multi-GPU CAGRA build only supports Float32"); - trainAllNeighbors_(n, static_cast(x)); + FAISS_THROW_IF_NOT_MSG( + !dataset.isDevice() && dataset.getRowStride() == d, + "multi-GPU CAGRA build requires packed host Float32 Dataset"); + trainAllNeighbors_(dataset); return; } @@ -94,15 +122,8 @@ void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { "graph_build_algo::BRUTE_FORCE is only available on the multi-GPU " "build path (set GpuIndexCagraConfig::devices)"); - numeric_type_ = numeric_type; bool index_is_initialized = !std::holds_alternative(index_); - DeviceScope scope(config_.device); - if (this->is_trained) { - FAISS_ASSERT(index_is_initialized); - return; - } - // CuvsCagra not initialized FAISS_ASSERT(!index_is_initialized); @@ -142,14 +163,13 @@ void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { } if (numeric_type == NumericType::Float32) { - index_ = std::make_shared>( + auto impl = std::make_shared>( this->resources_.get(), this->d, cagraConfig_.intermediate_graph_degree, cagraConfig_.graph_degree, static_cast(cagraConfig_.build_algo), cagraConfig_.nn_descent_niter, - cagraConfig_.store_dataset, this->metric_type, this->metric_arg, INDICES_64_BIT, @@ -157,17 +177,16 @@ void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { ivf_pq_search_params, cagraConfig_.refine_rate, cagraConfig_.guarantee_connectivity); - std::get>>(index_)->train( - n, static_cast(x)); + impl->train(dataset); + index_ = std::move(impl); } else if (numeric_type == NumericType::Float16) { - index_ = std::make_shared>( + auto impl = std::make_shared>( this->resources_.get(), this->d, cagraConfig_.intermediate_graph_degree, cagraConfig_.graph_degree, static_cast(cagraConfig_.build_algo), cagraConfig_.nn_descent_niter, - cagraConfig_.store_dataset, this->metric_type, this->metric_arg, INDICES_64_BIT, @@ -175,17 +194,16 @@ void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { ivf_pq_search_params, cagraConfig_.refine_rate, cagraConfig_.guarantee_connectivity); - std::get>>(index_)->train( - n, static_cast(x)); + impl->train(dataset); + index_ = std::move(impl); } else if (numeric_type == NumericType::Int8) { - index_ = std::make_shared>( + auto impl = std::make_shared>( this->resources_.get(), this->d, cagraConfig_.intermediate_graph_degree, cagraConfig_.graph_degree, static_cast(cagraConfig_.build_algo), cagraConfig_.nn_descent_niter, - cagraConfig_.store_dataset, this->metric_type, this->metric_arg, INDICES_64_BIT, @@ -193,26 +211,82 @@ void GpuIndexCagra::train_ex(idx_t n, const void* x, NumericType numeric_type) { ivf_pq_search_params, cagraConfig_.refine_rate, cagraConfig_.guarantee_connectivity); - std::get>>(index_)->train( - n, static_cast(x)); + impl->train(dataset); + index_ = std::move(impl); } else { FAISS_THROW_MSG("GpuIndexCagra::train unsupported data type"); } + numeric_type_ = numeric_type; this->is_trained = true; this->ntotal = n; } -void GpuIndexCagra::train(idx_t n, const float* x) { - train_ex(n, static_cast(x), NumericType::Float32); +void GpuIndexCagra::add(const Dataset& dataset) { + train(dataset); } -void GpuIndexCagra::add_ex(idx_t n, const void* x, NumericType numeric_type) { - train_ex(n, x, numeric_type); +void GpuIndexCagra::train(idx_t, const float*) { + FAISS_THROW_MSG( + "CAGRA requires caller-owned Dataset input; use train(const Dataset&)"); } -void GpuIndexCagra::add(idx_t n, const float* x) { - add_ex(n, x, NumericType::Float32); +void GpuIndexCagra::train_ex(idx_t, const void*, NumericType) { + FAISS_THROW_MSG( + "CAGRA requires caller-owned Dataset input; use train(const Dataset&)"); +} + +void GpuIndexCagra::add_ex(idx_t, const void*, NumericType) { + FAISS_THROW_MSG( + "CAGRA requires caller-owned Dataset input; use add(const Dataset&)"); +} + +void GpuIndexCagra::add(idx_t, const float*) { + FAISS_THROW_MSG( + "CAGRA requires caller-owned Dataset input; use add(const Dataset&)"); +} + +void GpuIndexCagra::updateDataset(const Dataset& dataset) { + FAISS_THROW_IF_NOT_MSG( + merged_knngraph_.empty(), + "Multi-GPU CAGRA supports graph build and CPU export only"); + FAISS_THROW_IF_NOT_MSG( + is_trained, "CAGRA must be trained before updateDataset"); + FAISS_THROW_IF_NOT_MSG( + dataset.getNumRows() == ntotal && dataset.getDim() == d, + "Dataset shape does not match the CAGRA graph"); + FAISS_THROW_IF_NOT_MSG( + dataset.getNumericType() == numeric_type_, + "Dataset numeric type does not match CAGRA"); + FAISS_THROW_IF_NOT_MSG( + dataset.isDevice() && dataset.getDevice() == config_.device, + "Dataset must reside on the CAGRA device"); + FAISS_THROW_IF_NOT_MSG( + dataset.isCagraCompatible(), + "CAGRA search requires compatible device storage; use Dataset::makeDevicePadded"); + DeviceScope scope(config_.device); + std::visit( + [&](auto& impl) { + using T = std::decay_t; + if constexpr (!std::is_same_v) { + impl->updateDataset(dataset); + } + }, + index_); +} + +bool GpuIndexCagra::isSearchReady() const { + return is_trained && + std::visit( + [](const auto& impl) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return false; + } else { + return impl->isSearchReady(); + } + }, + index_); } bool GpuIndexCagra::addImplRequiresIDs_() const { @@ -239,21 +313,22 @@ void GpuIndexCagra::searchImpl_ex_( float* distances, idx_t* labels, const SearchParameters* search_params) const { - FAISS_ASSERT( - this->is_trained && - !std::holds_alternative(index_)); + FAISS_THROW_IF_NOT_MSG( + merged_knngraph_.empty(), + "Multi-GPU CAGRA supports graph build and CPU export only"); + FAISS_THROW_IF_NOT_MSG( + isSearchReady(), + "CAGRA has no search-compatible Dataset; attach one with updateDataset"); FAISS_ASSERT(n > 0); FAISS_THROW_IF_NOT_MSG( numeric_type == numeric_type_, "Inconsistent numeric type for train and search"); - SearchParametersCagra* params; - if (search_params) { - params = dynamic_cast( - const_cast(search_params)); - } else { - params = new SearchParametersCagra{}; - } + const SearchParametersCagra defaults; + const auto* params = search_params + ? dynamic_cast(search_params) + : &defaults; + FAISS_THROW_IF_NOT_MSG(params, "CAGRA requires SearchParametersCagra"); Tensor outDistances(distances, {n, k}); Tensor outLabels(const_cast(labels), {n, k}); @@ -332,10 +407,6 @@ void GpuIndexCagra::searchImpl_ex_( } else { FAISS_THROW_MSG("GpuIndexCagra::searchImpl_ unsupported data type"); } - - if (not search_params) { - delete params; - } } void GpuIndexCagra::searchImpl_( @@ -355,7 +426,9 @@ void GpuIndexCagra::searchImpl_( search_params); } -void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { +void GpuIndexCagra::trainAllNeighbors_(const Dataset& input) { + const auto n = input.getNumRows(); + const auto* x = static_cast(input.getData()); FAISS_THROW_IF_MSG(is_trained, "index is already trained"); const auto& devices = cagraConfig_.devices; @@ -373,8 +446,13 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { // Allocated off the clique so it survives the clique's destruction below. CUDA_VERIFY(cudaSetDevice(devices[0])); raft::device_resources single_gpu_res; +#if defined(FAISS_CAGRA_DEVICE_OPTIMIZE) auto d_knn = raft::make_device_matrix( single_gpu_res, n, intermediate_degree); +#else + auto h_knn = + raft::make_host_matrix(n, intermediate_degree); +#endif // Build the knn graph across all devices. The clique is scoped: optimize // hangs intermittently if multi-GPU state is still alive when it runs. @@ -453,8 +531,16 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { auto dataset = raft::make_host_matrix_view( x, n, static_cast(this->d)); - auto d_indices = raft::make_device_matrix( +#if defined(FAISS_CAGRA_DEVICE_OPTIMIZE) + auto indices = raft::make_device_matrix( clique, n, static_cast(intermediate_degree)); +#else + // The public optimizer consumes a host graph. Build directly into host + // output: this avoids a device round trip and cuVS's concurrent + // multi-GPU merge into managed memory, which can leave invalid rows. + auto indices = raft::make_host_matrix( + n, static_cast(intermediate_degree)); +#endif fprintf(stderr, " [trainAllNeighbors] Building kNN graph: n=%ld, " @@ -470,7 +556,7 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { : 0.0f); cuvs::neighbors::all_neighbors::build( - clique, an_params, dataset, d_indices.view()); + clique, an_params, dataset, indices.view()); auto t_now = std::chrono::high_resolution_clock::now(); fprintf(stderr, @@ -478,19 +564,35 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { std::chrono::duration(t_now - t_phase).count()); t_phase = t_now; +#if defined(FAISS_CAGRA_DEVICE_OPTIMIZE) + // all_neighbors publishes its final graph asynchronously on the + // clique stream. Complete that copy before consuming it from the + // independent resource that owns d_knn. + raft::resource::sync_stream(clique); CUDA_VERIFY(cudaSetDevice(devices[0])); constexpr int kThreads = 256; const int blocks = (int)std::min( (knn_count + kThreads - 1) / kThreads, 65535); - kern_narrow_indices<<>>( - d_indices.data_handle(), d_knn.data_handle(), knn_count); + auto narrowStream = cuda::stream_ref{raft::resource::get_cuda_stream( + single_gpu_res)} + .get(); + kern_narrow_indices<<>>( + indices.data_handle(), d_knn.data_handle(), knn_count); CUDA_VERIFY(cudaGetLastError()); - CUDA_VERIFY(cudaDeviceSynchronize()); - } // clique + d_indices destroyed here, freeing all GPU resources + // indices and the clique must remain alive until narrowing finishes. + raft::resource::sync_stream(single_gpu_res); +#else +#pragma omp parallel for + for (size_t i = 0; i < knn_count; ++i) { + h_knn.data_handle()[i] = + static_cast(indices.data_handle()[i]); + } +#endif + } // clique and temporary graph storage are released before optimization auto t_now = std::chrono::high_resolution_clock::now(); fprintf(stderr, - " [trainAllNeighbors] narrow to uint32 (device): %.2f seconds\n", + " [trainAllNeighbors] narrow graph indices to uint32: %.2f seconds\n", std::chrono::duration(t_now - t_phase).count()); t_phase = t_now; @@ -499,18 +601,7 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { std::vector h_cagra(out_count); #if !defined(FAISS_CAGRA_DEVICE_OPTIMIZE) - // Public API: host matrices only, so the graph makes a round trip it does - // not need. Some cuVS versions also read the input as host memory whatever - // accessor you hand them, so passing device pointers here is not an option. - auto h_knn = - raft::make_host_matrix(n, intermediate_degree); - raft::copy( - h_knn.data_handle(), - d_knn.data_handle(), - knn_count, - raft::resource::get_cuda_stream(single_gpu_res)); - raft::resource::sync_stream(single_gpu_res); - + // Public API: optimize the host graph built above. auto h_cagra_view = raft::make_host_matrix_view( h_cagra.data(), n, graph_degree); cuvs::neighbors::cagra::helpers::optimize( @@ -550,7 +641,7 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { merged_knngraph_[i] = static_cast(h_cagra[i]); } - multi_gpu_dataset_ = x; + multiGpuDataset_.emplace(input.view()); this->is_trained = true; this->ntotal = n; @@ -563,105 +654,160 @@ void GpuIndexCagra::trainAllNeighbors_(idx_t n, const float* x) { std::chrono::duration(t_now - t_start).count()); } -void GpuIndexCagra::copyFrom_ex( +void GpuIndexCagra::copyFrom( const faiss::IndexHNSWCagra* index, - NumericType numeric_type) { - FAISS_ASSERT(index); - numeric_type_ = numeric_type; - + Dataset* dataset) { + FAISS_THROW_IF_NOT_MSG( + index && index->is_trained && index->d > 0 && index->ntotal > 0 && + index->ntotal <= std::numeric_limits::max(), + "CPU HNSW must contain a trained, nonempty CAGRA graph"); + FAISS_THROW_IF_NOT_MSG( + cagraConfig_.devices.size() <= 1, + "CPU graph import requires single-device CAGRA"); + const auto numericType = index->get_numeric_type(); + FAISS_THROW_IF_NOT_MSG( + numericType == NumericType::Float32 || + numericType == NumericType::Float16 || + numericType == NumericType::Int8, + "GpuIndexCagra::copyFrom unsupported data type"); + const size_t elementBytes = numericType == NumericType::Float32 + ? sizeof(float) + : numericType == NumericType::Float16 ? sizeof(half) + : 1; + const void* sourceData = nullptr; + std::vector decoded; + if (dataset) { + FAISS_THROW_IF_NOT_MSG( + dataset->getNumRows() == index->ntotal && + dataset->getDim() == index->d && + dataset->getNumericType() == numericType, + "Dataset shape and type must match the CPU HNSW index"); + FAISS_THROW_IF_NOT_MSG( + dataset->isCagraCompatible() && + dataset->getDevice() == config_.device, + "copyFrom requires writable CAGRA-compatible device Dataset storage on the index device"); + FAISS_THROW_IF_NOT_MSG( + index->storage && index->storage->ntotal == index->ntotal && + index->storage->d == index->d, + "CPU HNSW vector storage does not match index metadata"); + const size_t count = static_cast(index->ntotal) * index->d; + if (numericType == NumericType::Float32) { + const auto* flat = dynamic_cast(index->storage); + FAISS_THROW_IF_NOT_MSG( + flat && flat->codes.size() >= count * elementBytes, + "Float32 HNSW import requires complete flat vector storage"); + sourceData = flat->get_xb(); + } else { + const auto* sq = + dynamic_cast(index->storage); + const auto encoding = numericType == NumericType::Float16 + ? ScalarQuantizer::QT_fp16 + : ScalarQuantizer::QT_8bit_direct_signed; + FAISS_THROW_IF_NOT_MSG( + sq && sq->sq.qtype == encoding && + sq->codes.size() >= count * elementBytes, + "CPU HNSW scalar storage does not match its numeric type"); + sourceData = sq->codes.data(); + if (numericType == NumericType::Int8) { + decoded.resize(count); + for (size_t i = 0; i < count; ++i) { + decoded[i] = static_cast( + static_cast(sq->codes[i]) - 128); + } + sourceData = decoded.data(); + } + } + } DeviceScope scope(config_.device); - - GpuIndex::copyFrom(index); - - auto hnsw = index->hnsw; - - // copy level 0 to a dense knn graph matrix - std::vector knn_graph; - knn_graph.resize(index->ntotal * hnsw.nb_neighbors(0)); + const auto& hnsw = index->hnsw; + const int graphDegree = hnsw.nb_neighbors(0); + FAISS_THROW_IF_NOT_MSG( + graphDegree > 0 && + hnsw.offsets.size() == + static_cast(index->ntotal) + 1, + "CPU HNSW has no complete base-layer graph"); + std::vector graph(static_cast(index->ntotal) * graphDegree); #pragma omp parallel for - for (size_t i = 0; i < index->ntotal; ++i) { + for (idx_t i = 0; i < index->ntotal; ++i) { size_t begin, end; hnsw.neighbor_range(i, 0, &begin, &end); - for (size_t j = begin; j < end; j++) { - // knn_graph.push_back(hnsw.neighbors[j]); - knn_graph[i * hnsw.nb_neighbors(0) + (j - begin)] = - hnsw.neighbors[j]; + for (size_t j = begin; j < end; ++j) { + // HNSW permits empty slots; CAGRA requires every edge to name a + // valid node. A self-edge preserves the meaning of an empty slot. + const idx_t neighbor = hnsw.neighbors[j]; + graph[static_cast(i) * graphDegree + j - begin] = + neighbor < 0 ? i : neighbor; } } - if (numeric_type == NumericType::Float32) { - auto base_index = dynamic_cast(index->storage); - FAISS_ASSERT(base_index); - auto dataset = base_index->get_xb(); - fprintf(stderr, - "WARNING: GpuIndexCagra::copyFrom uses non-owning CPU storage. " - "Keep the source IndexHNSWCagra alive for the lifetime of the " - "GpuIndexCagra.\n"); - - index_ = std::make_shared>( - this->resources_.get(), - this->d, + // Build replacement state first so invalid input does not destroy the + // existing index. Supplied vector storage remains owned by the caller. + decltype(index_) replacement; + if (numericType == NumericType::Float32) { + replacement = std::make_shared>( + resources_.get(), + index->d, index->ntotal, - hnsw.nb_neighbors(0), + graphDegree, dataset, - knn_graph.data(), - this->metric_type, - this->metric_arg, + graph.data(), + index->metric_type, + index->metric_arg, INDICES_64_BIT); - } else if (numeric_type == NumericType::Float16) { - auto base_index = dynamic_cast(index->storage); - FAISS_ASSERT(base_index); - auto dataset = reinterpret_cast(base_index->codes.data()); - fprintf(stderr, - "WARNING: GpuIndexCagra::copyFrom uses non-owning CPU storage. " - "Keep the source IndexHNSWCagra alive for the lifetime of the " - "GpuIndexCagra.\n"); - - index_ = std::make_shared>( - this->resources_.get(), - this->d, + } else if (numericType == NumericType::Float16) { + replacement = std::make_shared>( + resources_.get(), + index->d, index->ntotal, - hnsw.nb_neighbors(0), + graphDegree, dataset, - knn_graph.data(), - this->metric_type, - this->metric_arg, + graph.data(), + index->metric_type, + index->metric_arg, INDICES_64_BIT); - } else if (numeric_type == NumericType::Int8) { - auto base_index = dynamic_cast(index->storage); - FAISS_ASSERT(base_index); - auto dataset = (uint8_t*)base_index->codes.data(); - fprintf(stderr, - "WARNING: GpuIndexCagra::copyFrom uses non-owning CPU storage. " - "Keep the source IndexHNSWCagra alive for the lifetime of the " - "GpuIndexCagra.\n"); - - int8_t* decoded_train_dataset = new int8_t[index->ntotal * index->d]; - for (int i = 0; i < index->ntotal * this->d; i++) { - decoded_train_dataset[i] = dataset[i] - 128; - } - - index_ = std::make_shared>( - this->resources_.get(), - this->d, + } else if (numericType == NumericType::Int8) { + replacement = std::make_shared>( + resources_.get(), + index->d, index->ntotal, - hnsw.nb_neighbors(0), - decoded_train_dataset, - knn_graph.data(), - this->metric_type, - this->metric_arg, + graphDegree, + dataset, + graph.data(), + index->metric_type, + index->metric_arg, INDICES_64_BIT); - delete[] decoded_train_dataset; } else { FAISS_THROW_MSG("GpuIndexCagra::copyFrom unsupported data type"); } - - this->is_trained = true; -} - -void GpuIndexCagra::copyFrom(const faiss::IndexHNSWCagra* index) { - copyFrom_ex(index, NumericType::Float32); + if (dataset) { + auto& handle = resources_->getRaftHandleCurrentDevice(); + const auto stream = handle.get_stream(); + // Finish previous uses before overwriting a possibly reused buffer. + handle.sync_stream(); + auto* destination = + static_cast(const_cast(dataset->getData())); + const size_t width = static_cast(index->d) * elementBytes; + const size_t pitch = dataset->getRowStride() * elementBytes; + CUDA_VERIFY(cudaMemsetAsync( + destination, 0, index->ntotal * pitch, stream.get())); + raft::copy_matrix( + destination, + pitch, + static_cast(sourceData), + width, + width, + index->ntotal, + stream); + // The CPU source and any decoded Int8 temporary may now be released. + handle.sync_stream(); + } + index_ = std::move(replacement); + merged_knngraph_.clear(); + merged_knngraph_degree_ = 0; + multiGpuDataset_.reset(); + GpuIndex::copyFrom(index); + numeric_type_ = numericType; } void GpuIndexCagra::copyTo(faiss::IndexHNSWCagra* index) const { @@ -674,6 +820,21 @@ void GpuIndexCagra::copyTo(faiss::IndexHNSWCagra* index) const { this->is_trained && index); DeviceScope scope(config_.device); + const auto& dataset = std::visit( + [](const auto& impl) -> const Dataset& { + using T = std::decay_t; + if constexpr (std::is_same_v) { + FAISS_THROW_MSG("CAGRA has no Dataset to export"); + } else { + return impl->getDataset(); + } + }, + index_); + FAISS_THROW_IF_MSG( + dataset.getLayout() == Dataset::Layout::BBQ, + "BBQ codes cannot be exported as CPU vectors; " + "attach dense storage with updateDataset before copyTo"); + // // Index information // @@ -728,118 +889,46 @@ void GpuIndexCagra::copyTo(faiss::IndexHNSWCagra* index) const { index->hnsw.cum_nneighbor_per_level.clear(); index->hnsw.set_default_probas(M, 1.0 / log(M)); - auto n_train = this->ntotal; - bool allocation = false; - + const auto n_train = this->ntotal; + // Always materialize logical columns in independent CPU storage. This + // honors device row pitch and never changes the caller's signed data. + index->init_level0 = false; if (numeric_type_ == NumericType::Float32) { - float* train_dataset; - const float* dataset = - std::get>>(index_) - ->get_training_dataset(); - if (getDeviceForAddress(dataset) >= 0) { - train_dataset = new float[n_train * index->d]; - allocation = true; - raft::copy( - train_dataset, - dataset, - n_train * index->d, - this->resources_->getRaftHandleCurrentDevice() - .get_stream()); - } else { - train_dataset = const_cast(dataset); - } - - // turn off as level 0 is copied from CAGRA graph - index->init_level0 = false; + std::vector packed(static_cast(n_train) * d); + dataset.copyToHost(packed.data()); if (!index->base_level_only) { - index->add(n_train, train_dataset); + index->add(n_train, packed.data()); } else { index->hnsw.prepare_level_tab(n_train, false); - index->storage->add(n_train, train_dataset); + index->storage->add(n_train, packed.data()); index->ntotal = n_train; } - if (allocation) { - delete[] train_dataset; - } } else if (numeric_type_ == NumericType::Float16) { - half* train_dataset; - const half* dataset = std::get>>(index_) - ->get_training_dataset(); - if (getDeviceForAddress(dataset) >= 0) { - train_dataset = new half[n_train * index->d]; - allocation = true; - raft::copy( - train_dataset, - dataset, - n_train * index->d, - this->resources_->getRaftHandleCurrentDevice() - .get_stream()); - } else { - train_dataset = const_cast(dataset); - } - - index->init_level0 = false; - if (!index->base_level_only) { - FAISS_THROW_MSG( - "Only base level copy is supported for FP16 types in GpuIndexCagra::copyTo"); - } else { - index->hnsw.prepare_level_tab(n_train, false); - index->storage->add_sa_codes( - n_train, (uint8_t*)train_dataset, nullptr); - index->ntotal = n_train; - } - - if (allocation) { - delete[] train_dataset; - } + FAISS_THROW_IF_NOT_MSG( + index->base_level_only, + "Only base level copy is supported for FP16 types in GpuIndexCagra::copyTo"); + std::vector packed(static_cast(n_train) * d); + dataset.copyToHost(packed.data()); + index->hnsw.prepare_level_tab(n_train, false); + index->storage->add_sa_codes( + n_train, + reinterpret_cast(packed.data()), + nullptr); + index->ntotal = n_train; } else if (numeric_type_ == NumericType::Int8) { - int8_t* train_dataset; - const int8_t* dataset = - std::get>>(index_) - ->get_training_dataset(); - if (getDeviceForAddress(dataset) >= 0) { - train_dataset = new int8_t[n_train * index->d]; - allocation = true; - raft::copy( - train_dataset, - dataset, - n_train * index->d, - this->resources_->getRaftHandleCurrentDevice() - .get_stream()); - } else { - train_dataset = const_cast(dataset); - } - - index->init_level0 = false; - if (!index->base_level_only) { - FAISS_THROW_MSG( - "Only base level copy is supported for Int8 types in GpuIndexCagra::copyTo"); - } else { - index->hnsw.prepare_level_tab(n_train, false); - // Directly update train_dataset with encoding of - // Quantizer8bitDirectSigned - for (int64_t i = 0; i < ((int64_t)n_train) * index->d; ++i) { - train_dataset[i] = static_cast( - static_cast(train_dataset[i]) + 128); - } - - index->storage->add_sa_codes( - n_train, - reinterpret_cast(train_dataset), - nullptr); - - index->ntotal = n_train; - } - - if (allocation) { - delete[] train_dataset; - } else { - // Recover after appending - for (int64_t i = 0; i < ((int64_t)n_train) * index->d; ++i) { - train_dataset[i] = static_cast( - static_cast(train_dataset[i]) - 128); - } + FAISS_THROW_IF_NOT_MSG( + index->base_level_only, + "Only base level copy is supported for Int8 types in GpuIndexCagra::copyTo"); + std::vector packed(static_cast(n_train) * d); + dataset.copyToHost(packed.data()); + std::vector encoded(packed.size()); + for (size_t i = 0; i < packed.size(); ++i) { + encoded[i] = + static_cast(static_cast(packed[i]) + 128); } + index->hnsw.prepare_level_tab(n_train, false); + index->storage->add_sa_codes(n_train, encoded.data(), nullptr); + index->ntotal = n_train; } auto graph = get_knngraph(); @@ -919,7 +1008,8 @@ void GpuIndexCagra::buildHnswUpperLevelsGpu_( #pragma omp parallel for for (idx_t a = 0; a < n_lvl; a++) { memcpy(sub_x.data() + (size_t)a * this->d, - multi_gpu_dataset_ + (size_t)ids[a] * this->d, + static_cast(multiGpuDataset_->getData()) + + (size_t)ids[a] * this->d, this->d * sizeof(float)); } @@ -933,7 +1023,6 @@ void GpuIndexCagra::buildHnswUpperLevelsGpu_( upper_degree, sub_algo, cagraConfig_.nn_descent_niter, - /*store_dataset=*/false, this->metric_type, this->metric_arg, INDICES_64_BIT, @@ -941,7 +1030,13 @@ void GpuIndexCagra::buildHnswUpperLevelsGpu_( std::nullopt, cagraConfig_.refine_rate, cagraConfig_.gpu_hnsw_guarantee_connectivity); - sub.train(n_lvl, sub_x.data()); + auto subDataset = Dataset::viewHost( + sub_x.data(), + n_lvl, + this->d, + NumericType::Float32, + this->d); + sub.train(subDataset); sub_graph = sub.get_knngraph(); } @@ -1009,12 +1104,16 @@ void GpuIndexCagra::copyToMultiGpu_(faiss::IndexHNSWCagra* index) const { index->init_level0 = false; if (index->base_level_only) { index->hnsw.prepare_level_tab(n_train, false); - index->storage->add(n_train, multi_gpu_dataset_); + index->storage->add( + n_train, + static_cast(multiGpuDataset_->getData())); index->ntotal = n_train; } else if (cagraConfig_.gpu_hnsw_upper_levels) { auto t0 = std::chrono::high_resolution_clock::now(); int max_lvl = index->hnsw.prepare_level_tab(n_train, false); - index->storage->add(n_train, multi_gpu_dataset_); + index->storage->add( + n_train, + static_cast(multiGpuDataset_->getData())); index->ntotal = n_train; buildHnswUpperLevelsGpu_(index, max_lvl); fprintf(stderr, @@ -1023,7 +1122,9 @@ void GpuIndexCagra::copyToMultiGpu_(faiss::IndexHNSWCagra* index) const { std::chrono::high_resolution_clock::now() - t0) .count()); } else { - index->add(n_train, multi_gpu_dataset_); + index->add( + n_train, + static_cast(multiGpuDataset_->getData())); } #pragma omp parallel for @@ -1041,36 +1142,20 @@ void GpuIndexCagra::copyToMultiGpu_(faiss::IndexHNSWCagra* index) const { void GpuIndexCagra::reset() { DeviceScope scope(config_.device); - - bool had_multi_gpu = !merged_knngraph_.empty(); + // Finish uses of borrowed storage before clearing the binding. + resources_->getRaftHandleCurrentDevice().sync_stream(); + index_ = std::monostate{}; merged_knngraph_.clear(); merged_knngraph_degree_ = 0; - multi_gpu_dataset_ = nullptr; - - if (!std::holds_alternative(index_)) { - std::visit( - [](auto& index_ptr) { - using IndexPtrT = std::decay_t; - if constexpr (std::is_same_v) { - FAISS_THROW_MSG( - "CuvsCagra not initialized when calling GpuIndexCagra::reset"); - } else { - return index_ptr->reset(); - } - }, - index_); - this->ntotal = 0; - this->is_trained = false; - } else if (had_multi_gpu) { - this->ntotal = 0; - this->is_trained = false; - } else { - FAISS_ASSERT(this->ntotal == 0); - } + multiGpuDataset_.reset(); + ntotal = 0; + is_trained = false; + numeric_type_ = NumericType::Float32; } std::vector GpuIndexCagra::get_knngraph() const { FAISS_ASSERT(this->is_trained); + DeviceScope scope(config_.device); if (!merged_knngraph_.empty()) { return merged_knngraph_; diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexCagra.h b/thirdparty/faiss/faiss/gpu/GpuIndexCagra.h index 0ec56b4e1..53f2b8c30 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexCagra.h +++ b/thirdparty/faiss/faiss/gpu/GpuIndexCagra.h @@ -27,6 +27,11 @@ #include #include +#ifndef SWIG +#include +#include +#endif + #include #include #include "faiss/Index.h" @@ -216,7 +221,6 @@ struct GpuIndexCagraConfig : public GpuIndexConfig { std::shared_ptr ivf_pq_params{nullptr}; std::shared_ptr ivf_pq_search_params{nullptr}; float refine_rate = 2.0f; - bool store_dataset = true; /// Whether to use MST optimization to guarantee graph connectivity. bool guarantee_connectivity = false; @@ -309,28 +313,49 @@ struct GpuIndexCagra : public GpuIndex { faiss::MetricType metric = faiss::METRIC_L2, GpuIndexCagraConfig config = GpuIndexCagraConfig()); - /// Trains CAGRA based on the given vector data and add them along with ids. - /// NB: The use of the add function here is to build the CAGRA graph on - /// the base dataset. Use this function when you want to add vectors with - /// ids. Ref: https://github.com/facebookresearch/faiss/issues/4107 + ~GpuIndexCagra() override; + + /// Build the full graph while borrowing dataset storage. The backing + /// allocation must remain alive and unchanged through index use and all + /// outstanding GPU work. Does nothing if already trained; call reset() + /// before building again. + void train(const Dataset& dataset); + void train_dataset(const Dataset& dataset) override { + train(dataset); + } + + /// Equivalent to train(dataset); incremental insertion is unsupported. + void add(const Dataset& dataset); + void add_dataset(const Dataset& dataset) override { + add(dataset); + } + + /// Attach search-compatible device storage without changing the graph. + /// Shape, dtype and vector ordering must match the trained dataset. The + /// values must be the same; this method does not rebuild for changed data. + /// Previous work on this index's stream completes before rebinding. + void updateDataset(const Dataset& dataset); + bool isSearchReady() const; + + /// Copy the CPU graph and metadata. With no dataset, import only the + /// graph: no vector storage is retained and GPU search is unavailable. + /// When supplied, dataset must describe writable CAGRA-compatible device + /// storage with matching shape and dtype on this index's device. Its + /// contents are overwritten with CPU vectors and its padding is zeroed. + /// The index borrows that allocation and becomes search-ready. The caller + /// retains ownership and must keep the allocation alive through index use + /// and queued GPU work. Copies finish before return, so the CPU index may + /// then be released in either mode. + void copyFrom( + const faiss::IndexHNSWCagra* index, + Dataset* dataset = nullptr); + + /// Legacy pointer entry points throw: use the Dataset overloads. void add(idx_t n, const float* x) override; void add_ex(idx_t n, const void* x, NumericType numeric_type) override; - - /// Trains CAGRA based on the given vector data. - /// NB: The use of the train function here is to build the CAGRA graph on - /// the base dataset and is currently the only function to add the full set - /// of vectors (without IDs) to the index. There is no external quantizer to - /// be trained here. void train(idx_t n, const float* x) override; void train_ex(idx_t n, const void* x, NumericType numeric_type) override; - /// Initialize ourselves from the given CPU index; will overwrite - /// all data in ourselves - void copyFrom(const faiss::IndexHNSWCagra* index); - void copyFrom_ex( - const faiss::IndexHNSWCagra* index, - NumericType numeric_type); - /// Copy ourselves to the given CPU index; will overwrite all data /// in the index instance void copyTo(faiss::IndexHNSWCagra* index) const; @@ -372,7 +397,9 @@ struct GpuIndexCagra : public GpuIndex { /// more than one device: cuVS `all_neighbors` knn graph construction over /// overlapping clusters, followed by graph pruning. Leaves the result in /// merged_knngraph_ for copyTo(); index_ stays empty. - void trainAllNeighbors_(idx_t n, const float* x); +#ifndef SWIG + void trainAllNeighbors_(const Dataset& dataset); +#endif /// Populate HNSW levels >= 1 of `index` by building a CAGRA graph over /// each level's node subset on the GPU. Requires the level table to be @@ -385,9 +412,9 @@ struct GpuIndexCagra : public GpuIndex { /// Our configuration options const GpuIndexCagraConfig cagraConfig_; - faiss::NumericType numeric_type_; + faiss::NumericType numeric_type_ = NumericType::Float32; - /// Instance that we own; contains the inverted lists + /// Instance that owns the CAGRA graph and borrows dataset storage std::variant< std::monostate, std::shared_ptr>, @@ -398,7 +425,9 @@ struct GpuIndexCagra : public GpuIndex { /// Multi-GPU state: populated by trainAllNeighbors_(), used by copyTo() std::vector merged_knngraph_; idx_t merged_knngraph_degree_ = 0; - const float* multi_gpu_dataset_ = nullptr; +#ifndef SWIG + std::optional multiGpuDataset_; +#endif }; } // namespace gpu diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexFlat.cu b/thirdparty/faiss/faiss/gpu/GpuIndexFlat.cu index 0a57e1dc9..4b29896dd 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexFlat.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexFlat.cu @@ -18,7 +18,7 @@ #include #include -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_FLAT) +#if defined USE_NVIDIA_CUVS #include #endif @@ -93,7 +93,7 @@ GpuIndexFlat::GpuIndexFlat( GpuIndexFlat::~GpuIndexFlat() {} void GpuIndexFlat::resetIndex_(int dims) { -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_FLAT) +#if defined USE_NVIDIA_CUVS if (should_use_cuvs(config_)) { data_.reset(new CuvsFlatIndex( @@ -102,17 +102,12 @@ void GpuIndexFlat::resetIndex_(int dims) { flatConfig_.useFloat16, config_.memorySpace)); } else -#elif !defined(USE_NVIDIA_CUVS) +#else if (should_use_cuvs(config_)) { FAISS_THROW_MSG( "cuVS has not been compiled into the current version so it cannot be used."); } else #endif - // When cuVS is compiled in but the cuVS flat backend is pruned - // (FAISS_CUVS_NO_FLAT — e.g. the cuVS 26.02 IVF-PQ-only build on aarch64, - // whose cuvs-ivfpq-2602 dep omits neighbors/brute_force), should_use_cuvs - // may still be true; fall back to the classic GPU FlatIndex - // (bfKnnOnDevice), which is functionally equivalent for brute-force search. { data_.reset(new FlatIndex( resources_.get(), @@ -241,6 +236,41 @@ void GpuIndexFlat::searchImpl_( sel); } +void GpuIndexFlat::searchImpl_ex_( + idx_t n, + const void* x, + NumericType numeric_type, + int k, + float* distances, + idx_t* labels, + const SearchParameters* params) const { + if (numeric_type != NumericType::Float16 || !flatConfig_.useFloat16) { + // float32 storage: fp16 queries are widened on the device + GpuIndex::searchImpl_ex_( + n, x, numeric_type, k, distances, labels, params); + return; + } + + // current device already set + // n/k already validated + // Input and output data are already resident on the GPU + Tensor queries( + const_cast(static_cast(x)), {n, this->d}); + Tensor outDistances(distances, {n, k}); + Tensor outLabels(labels, {n, k}); + + const IDSelector* sel = params ? params->sel : nullptr; + data_->query( + queries, + k, + metric_type, + metric_arg, + outDistances, + outLabels, + true, + sel); +} + void GpuIndexFlat::reconstruct(idx_t key, float* out) const { DeviceScope scope(config_.device); diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexFlat.h b/thirdparty/faiss/faiss/gpu/GpuIndexFlat.h index ee4c14466..9912fa9ed 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexFlat.h +++ b/thirdparty/faiss/faiss/gpu/GpuIndexFlat.h @@ -131,6 +131,17 @@ class GpuIndexFlat : public GpuIndex { idx_t* labels, const SearchParameters* params) const override; + /// Called from GpuIndex for search; Float16 queries are searched without + /// conversion against float16 storage + void searchImpl_ex_( + idx_t n, + const void* x, + NumericType numeric_type, + int k, + float* distances, + idx_t* labels, + const SearchParameters* params) const override; + protected: /// Our configuration options const GpuIndexFlatConfig flatConfig_; diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexIVF.cu b/thirdparty/faiss/faiss/gpu/GpuIndexIVF.cu index ccab7d8e0..7c2316d37 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexIVF.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexIVF.cu @@ -401,6 +401,7 @@ void GpuIndexIVF::searchImpl_( const IDSelector* sel = params ? params->sel : nullptr; + baseIndex_->setDeterministicTieBreak(ivfConfig_.deterministic_tie_break); baseIndex_->search( quantizer, queries, use_nprobe, k, outDistances, outLabels, sel); } @@ -472,6 +473,7 @@ void GpuIndexIVF::search_preassigned( auto outIndicesDevice = toDeviceTemporary( resources_.get(), config_.device, labels, stream, {n, k}); + baseIndex_->setDeterministicTieBreak(ivfConfig_.deterministic_tie_break); baseIndex_->searchPreassigned( quantizer, vecsDevice, diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexIVF.h b/thirdparty/faiss/faiss/gpu/GpuIndexIVF.h index 2c18c72db..d5b0dacf4 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexIVF.h +++ b/thirdparty/faiss/faiss/gpu/GpuIndexIVF.h @@ -32,6 +32,12 @@ struct GpuIndexIVFConfig : public GpuIndexConfig { /// throw an exception for indices not implemented on GPU. When set to /// true, it will fallback to a CPU implementation. bool allowCpuCoarseQuantizer = false; + + /// Break a distance tie on the smaller id, so a search repeats. Honoured + /// by GpuIndexIVFFlat and GpuIndexIVFScalarQuantizer with the interleaved + /// layout for k up to 1024, and by the cuVS GpuIndexIVFScalarQuantizer + /// and GpuIndexIVFPQ for k and nprobe up to 256. + bool deterministic_tie_break = false; }; /// Base class of all GPU IVF index types. This (for now) deliberately does not diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexIVFFlat.cu b/thirdparty/faiss/faiss/gpu/GpuIndexIVFFlat.cu index b2a3766fa..de40dc89f 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexIVFFlat.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexIVFFlat.cu @@ -267,7 +267,7 @@ void GpuIndexIVFFlat::train(idx_t n, const float* x) { // transfer centroids to host auto host_centroids = toHost( cuvs_ivfflat_index.value().centers().data_handle(), - raft_handle.get_stream(), + raft_handle.get_stream().get(), {idx_t(nlist), this->d}); quantizer->train(nlist, host_centroids.data()); quantizer->add(nlist, host_centroids.data()); diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexIVFPQ.cu b/thirdparty/faiss/faiss/gpu/GpuIndexIVFPQ.cu index 12df056cb..21355a2ba 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexIVFPQ.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexIVFPQ.cu @@ -431,7 +431,7 @@ void GpuIndexIVFPQ::train(idx_t n, const float* x) { // transfer centroids to host auto host_centroids = toHost( cluster_centers.data_handle(), - raft_handle.get_stream(), + raft_handle.get_stream().get(), {idx_t(nlist), this->d}); quantizer->train(nlist, host_centroids.data()); quantizer->add(nlist, host_centroids.data()); diff --git a/thirdparty/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu b/thirdparty/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu index 39c5f01b0..2223720e9 100644 --- a/thirdparty/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu +++ b/thirdparty/faiss/faiss/gpu/GpuIndexIVFScalarQuantizer.cu @@ -13,7 +13,7 @@ #include #include -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_IVFSQ) +#if defined USE_NVIDIA_CUVS #include #include #include @@ -124,15 +124,9 @@ void GpuIndexIVFScalarQuantizer::verifySQSettings_() const { } bool GpuIndexIVFScalarQuantizer::shouldUseCuvs_() const { -#if defined(FAISS_CUVS_NO_IVFSQ) - // cuVS IVF-SQ backend compiled out (e.g. against cuVS 26.02, which has no - // ivf_sq); fall back to the classic (non-cuVS) GPU scalar-quantizer impl. - return false; -#else return should_use_cuvs(config_) && sq.qtype == faiss::ScalarQuantizer::QT_8bit && by_residual && ivfSQConfig_.indicesOptions == INDICES_64_BIT; -#endif } void GpuIndexIVFScalarQuantizer::setIndex_( @@ -147,7 +141,7 @@ void GpuIndexIVFScalarQuantizer::setIndex_( IndicesOptions indicesOptions, MemorySpace space) { if (shouldUseCuvs_()) { -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_IVFSQ) +#if defined USE_NVIDIA_CUVS if (!ivfSQConfig_.interleavedLayout) { fprintf(stderr, "WARN: interleavedLayout is set to False with cuVS enabled. This will be ignored.\n"); @@ -251,7 +245,7 @@ void GpuIndexIVFScalarQuantizer::copyTo( GpuIndexIVF::copyTo(index); auto sqCopy = sq; -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_IVFSQ) +#if defined USE_NVIDIA_CUVS if (index_) { auto cuvsIndex = dynamic_cast(index_.get()); if (cuvsIndex) { @@ -334,7 +328,7 @@ void GpuIndexIVFScalarQuantizer::train(idx_t n, const float* x) { if (shouldUseCuvs_() && !(quantizer->is_trained && quantizer->ntotal == nlist)) { -#if defined(USE_NVIDIA_CUVS) && !defined(FAISS_CUVS_NO_IVFSQ) +#if defined USE_NVIDIA_CUVS setIndex_( resources_.get(), this->d, @@ -379,7 +373,7 @@ void GpuIndexIVFScalarQuantizer::train(idx_t n, const float* x) { } else { auto host_centroids = toHost( cuvs_ivfsq_index.value().centers().data_handle(), - raft_handle.get_stream(), + raft_handle.get_stream().get(), {idx_t(nlist), this->d}); quantizer->train(nlist, host_centroids.data()); quantizer->add(nlist, host_centroids.data()); diff --git a/thirdparty/faiss/faiss/gpu/hipify.sh b/thirdparty/faiss/faiss/gpu/hipify.sh index 46916b15c..9ce52c82f 100755 --- a/thirdparty/faiss/faiss/gpu/hipify.sh +++ b/thirdparty/faiss/faiss/gpu/hipify.sh @@ -76,6 +76,8 @@ function hipify_dir() # replace thrust::cuda::par with thrust::hip::par # adjust header path location for hipblas.h to avoid unnecessary deprecation warnings # adjust header path location for hiprand_kernel.h to avoid unnecessary deprecation warnings + # ROCm 7.2.x hipify-perl emits a doubled hip/hip/ prefix for device_functions.h; + # undo it (harmless no-op on later versions, which emit the correct path) for ext in hip cuh h cpp c do while IFS= read -r -d '' src @@ -83,6 +85,7 @@ function hipify_dir() sed -i 's@thrust::cuda::par@thrust::hip::par@' "$src" sed -i 's@#include @#include @' "$src" sed -i 's@#include @#include @' "$src" + sed -i 's@#include @#include @' "$src" done < <(find ./gpu -name "*.$ext.tmp" -print0) done diff --git a/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cu b/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cu index 4be7cebb8..826837ce6 100644 --- a/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cu +++ b/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cu @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -47,11 +48,9 @@ BinaryCuvsCagra::BinaryCuvsCagra( idx_t graph_degree, faiss::cagra_build_algo graph_build_algo, size_t nn_descent_niter, - bool store_dataset, IndicesOptions indicesOptions) : resources_(resources), dim_(dim), - store_dataset_(store_dataset), graph_build_algo_(graph_build_algo), nn_descent_niter_(nn_descent_niter) { FAISS_THROW_IF_NOT_MSG( @@ -60,7 +59,6 @@ BinaryCuvsCagra::BinaryCuvsCagra( index_params_.intermediate_graph_degree = intermediate_graph_degree; index_params_.graph_degree = graph_degree; - index_params_.attach_dataset_on_build = store_dataset; index_params_.metric = cuvs::distance::DistanceType::BitwiseHamming; @@ -79,7 +77,7 @@ BinaryCuvsCagra::BinaryCuvsCagra( int dim, idx_t n, int graph_degree, - const uint8_t* train_dataset, + const Dataset* dataset, const idx_t* knn_graph, IndicesOptions indicesOptions) : resources_(resources), dim_(dim) { @@ -87,72 +85,30 @@ BinaryCuvsCagra::BinaryCuvsCagra( indicesOptions == faiss::gpu::INDICES_64_BIT, "only INDICES_64_BIT is supported for cuVS CAGRA index"); - bool distances_on_gpu = getDeviceForAddress(train_dataset) >= 0; - bool knn_graph_on_gpu = getDeviceForAddress(knn_graph) >= 0; + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); + auto graph = raft::make_host_matrix(n, graph_degree); + std::copy(knn_graph, knn_graph + n * graph_degree, graph.data_handle()); + auto graphView = raft::make_const_mdspan(graph.view()); - FAISS_ASSERT(distances_on_gpu == knn_graph_on_gpu); - - storage_ = train_dataset; + cuvs_index = std::make_shared< + cuvs::neighbors::cagra::device_padded_index>( + raft_handle, cuvs::distance::DistanceType::BitwiseHamming); + cuvs_index->update_graph(raft_handle, graphView); + raft_handle.sync_stream(); n_ = n; - - const raft::device_resources& raft_handle = - resources_->getRaftHandleCurrentDevice(); - - if (distances_on_gpu && knn_graph_on_gpu) { - raft_handle.sync_stream(); - // Copying to host so that cuvs::neighbors::cagra::index - // creates an owning copy of the knn graph on device - auto knn_graph_copy = - raft::make_host_matrix(n, graph_degree); - thrust::copy( - thrust::device_ptr(knn_graph), - thrust::device_ptr(knn_graph + (n * graph_degree)), - knn_graph_copy.data_handle()); - - auto dataset_mds = - raft::make_device_matrix_view( - train_dataset, n, dim / 8); - - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - raft_handle, - cuvs::distance::DistanceType::BitwiseHamming, - dataset_mds, - raft::make_const_mdspan(knn_graph_copy.view())); - } else if (!distances_on_gpu && !knn_graph_on_gpu) { - // copy idx_t (int64_t) host knn_graph to uint32_t host knn_graph - auto knn_graph_copy = - raft::make_host_matrix(n, graph_degree); - std::copy( - knn_graph, - knn_graph + (n * graph_degree), - knn_graph_copy.data_handle()); - - auto dataset_mds = raft::make_host_matrix_view( - train_dataset, n, dim / 8); - - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - raft_handle, - cuvs::distance::DistanceType::BitwiseHamming, - dataset_mds, - raft::make_const_mdspan(knn_graph_copy.view())); - } else { - FAISS_THROW_MSG( - "distances and knn_graph must both be in device or host memory"); + if (dataset) { + updateDataset(*dataset); } } -void BinaryCuvsCagra::train(idx_t n, const uint8_t* x) { - storage_ = x; - n_ = n; +void BinaryCuvsCagra::train(const Dataset& dataset) { + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); - const raft::device_resources& raft_handle = - resources_->getRaftHandleCurrentDevice(); - - // IVF-PQ is not supported as the graph building algorithm - if (graph_build_algo_ == faiss::cagra_build_algo::NN_DESCENT || - graph_build_algo_ == faiss::cagra_build_algo::IVF_PQ) { + // IVF-PQ is not supported as the graph building algorithm. + const bool useNNDescent = + graph_build_algo_ == faiss::cagra_build_algo::NN_DESCENT || + graph_build_algo_ == faiss::cagra_build_algo::IVF_PQ; + if (useNNDescent) { cuvs::neighbors::cagra::graph_build_params::nn_descent_params graph_build_params(index_params_.intermediate_graph_degree); graph_build_params.max_iterations = nn_descent_niter_; @@ -170,21 +126,81 @@ void BinaryCuvsCagra::train(idx_t n, const uint8_t* x) { } } - if (getDeviceForAddress(x) >= 0) { - auto dataset = raft::make_device_matrix_view( - x, n, dim_ / 8); - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( + const auto n = dataset.getNumRows(); + const auto* data = static_cast(dataset.getData()); + using CuvsIndex = + cuvs::neighbors::cagra::device_padded_index; + auto buildGraph = [&](auto datasetView) { + return std::make_shared( + raft_handle, cuvs::neighbors::cagra::build( - raft_handle, index_params_, dataset)); + raft_handle, index_params_, datasetView), + cuvs::neighbors:: + device_padded_dataset_view{}); + }; + if (dataset.isCagraCompatible()) { + auto physical = raft::make_device_matrix_view( + data, n, dataset.getRowStride()); + auto view = + cuvs::neighbors::device_padded_dataset_view( + physical, dataset.getDim()); + cuvs_index = std::make_shared(cuvs::neighbors::cagra::build( + raft_handle, index_params_, view)); + } else if ( + dataset.getRowStride() != dataset.getDim() && + !(dataset.isDevice() && useNNDescent)) { + // Host row gaps may be nonzero; pack them for graph construction. + // Device NN-descent consumes the original rows with their required + // zero-filled gaps, independently of CAGRA search compatibility. + std::vector packed(n * dataset.getDim()); + dataset.copyToHost(packed.data()); + auto physical = raft::make_host_matrix_view( + packed.data(), n, dataset.getDim()); + cuvs_index = buildGraph( + cuvs::neighbors::make_host_standard_dataset_view(physical)); + raft_handle.sync_stream(); + } else if (dataset.isDevice()) { + auto physical = raft::make_device_matrix_view( + data, n, dataset.getRowStride()); + cuvs_index = buildGraph( + cuvs::neighbors::device_standard_dataset_view( + physical, dataset.getDim())); } else { - auto dataset = raft::make_host_matrix_view( - x, n, dim_ / 8); - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - cuvs::neighbors::cagra::build( - raft_handle, index_params_, dataset)); + auto physical = raft::make_host_matrix_view( + data, n, dataset.getDim()); + cuvs_index = buildGraph( + cuvs::neighbors::make_host_standard_dataset_view(physical)); } + dataset_.emplace(dataset.view()); + n_ = n; +} + +void BinaryCuvsCagra::updateDataset(const Dataset& dataset) { + FAISS_THROW_IF_NOT_MSG( + cuvs_index, "Build the CAGRA graph before attaching data"); + FAISS_THROW_IF_NOT_MSG( + dataset.getNumRows() == n_ && dataset.getDim() == dim_ / 8 && + dataset.getNumericType() == NumericType::UInt8, + "Dataset shape or type does not match the binary CAGRA graph"); + FAISS_THROW_IF_NOT_MSG( + dataset.isCagraCompatible(), + "Search requires a compatible device Dataset; use Dataset::makeDevicePadded"); + auto borrowed = dataset.view(); + auto physical = raft::make_device_matrix_view( + static_cast(dataset.getData()), + dataset.getNumRows(), + dataset.getRowStride()); + auto view = cuvs::neighbors::device_padded_dataset_view( + physical, dataset.getDim()); + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); + raft_handle.sync_stream(); + *cuvs_index = cuvs::neighbors::cagra::update_dataset( + raft_handle, std::move(*cuvs_index), view); + dataset_.emplace(std::move(borrowed)); +} + +bool BinaryCuvsCagra::isSearchReady() const { + return cuvs_index && dataset_ && dataset_->isCagraCompatible(); } void BinaryCuvsCagra::search( @@ -218,19 +234,9 @@ void BinaryCuvsCagra::search( FAISS_ASSERT(numQueries > 0); FAISS_ASSERT(cols == dim_ / 8); - if (!store_dataset_) { - if (getDeviceForAddress(storage_) >= 0) { - auto dataset = - raft::make_device_matrix_view( - storage_, n_, dim_ / 8); - cuvs_index->update_dataset(raft_handle, dataset); - } else { - auto dataset = raft::make_host_matrix_view( - storage_, n_, dim_ / 8); - cuvs_index->update_dataset(raft_handle, dataset); - } - store_dataset_ = true; - } + FAISS_THROW_IF_NOT_MSG( + isSearchReady(), + "CAGRA has no search Dataset; call updateDataset with compatible device storage"); auto indices_view = raft::make_device_matrix_view( outIndices.data(), numQueries, k_); @@ -307,6 +313,8 @@ void BinaryCuvsCagra::search( void BinaryCuvsCagra::reset() { cuvs_index.reset(); + dataset_.reset(); + n_ = 0; } idx_t BinaryCuvsCagra::get_knngraph_degree() const { @@ -336,8 +344,11 @@ std::vector BinaryCuvsCagra::get_knngraph() const { return host_graph; } -const uint8_t* BinaryCuvsCagra::get_training_dataset() const { - return storage_; +const Dataset& BinaryCuvsCagra::getDataset() const { + FAISS_THROW_IF_NOT_MSG( + dataset_.has_value(), + "CAGRA has no Dataset to export; attach one with updateDataset before copyTo"); + return *dataset_; } } // namespace gpu } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cuh b/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cuh index 3c7a9eb68..9918eddf0 100644 --- a/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cuh +++ b/thirdparty/faiss/faiss/gpu/impl/BinaryCuvsCagra.cuh @@ -23,17 +23,20 @@ #pragma once +#include #include #include #include #include #include +#include #include #include #include #include +#include namespace faiss { @@ -48,7 +51,6 @@ class BinaryCuvsCagra { idx_t graph_degree, faiss::cagra_build_algo graph_build_algo, size_t nn_descent_niter, - bool store_dataset, IndicesOptions indicesOptions); BinaryCuvsCagra( @@ -56,13 +58,15 @@ class BinaryCuvsCagra { int dim, idx_t n, int graph_degree, - const uint8_t* train_dataset, + const Dataset* dataset, const idx_t* knn_graph, IndicesOptions indicesOptions); ~BinaryCuvsCagra() = default; - void train(idx_t n, const uint8_t* x); + void train(const Dataset& dataset); + void updateDataset(const Dataset& dataset); + bool isSearchReady() const; void search( Tensor& queries, @@ -90,35 +94,30 @@ class BinaryCuvsCagra { std::vector get_knngraph() const; - const uint8_t* get_training_dataset() const; + const Dataset& getDataset() const; private: /// Collection of GPU resources that we use GpuResources* resources_; - /// Training dataset - const uint8_t* storage_; - int n_; + /// Borrowed metadata only; vector storage remains owned by the caller. + std::optional dataset_; + idx_t n_ = 0; /// Expected dimensionality of the vectors const int dim_; - /// Controls the underlying cuVS index if it should store the dataset in - /// device memory. Default set to true for enabling search capabilities on - /// the index. - /// NB: This is also required to be set to true for deserializing - /// an IndexHNSWCagra object. - bool store_dataset_ = true; - /// Parameters to build cuVS CAGRA index - faiss::cagra_build_algo graph_build_algo_; + faiss::cagra_build_algo graph_build_algo_ = + faiss::cagra_build_algo::NN_DESCENT; cuvs::neighbors::cagra::index_params index_params_; /// Parameters to build CAGRA graph using NN Descent size_t nn_descent_niter_ = 20; /// Instance of trained cuVS CAGRA index - std::shared_ptr> + std::shared_ptr< + cuvs::neighbors::cagra::device_padded_index> cuvs_index{nullptr}; }; diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cu b/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cu index 6ff3419b7..171bc94c6 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cu +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cu @@ -32,6 +32,7 @@ #include #include #include +#include #include #include @@ -48,7 +49,6 @@ CuvsCagra::CuvsCagra( idx_t graph_degree, faiss::cagra_build_algo graph_build_algo, size_t nn_descent_niter, - bool store_dataset, faiss::MetricType metric, float metricArg, IndicesOptions indicesOptions, @@ -61,7 +61,6 @@ CuvsCagra::CuvsCagra( dim_(dim), graph_build_algo_(graph_build_algo), nn_descent_niter_(nn_descent_niter), - store_dataset_(store_dataset), metric_(metric), metricArg_(metricArg), index_params_(), @@ -78,7 +77,6 @@ CuvsCagra::CuvsCagra( index_params_.intermediate_graph_degree = intermediate_graph_degree; index_params_.graph_degree = graph_degree; - index_params_.attach_dataset_on_build = store_dataset; index_params_.guarantee_connectivity = guarantee_connectivity; if (!ivf_pq_search_params_) { @@ -96,7 +94,7 @@ CuvsCagra::CuvsCagra( int dim, idx_t n, int graph_degree, - const data_t* dataset, + const Dataset* dataset, const idx_t* knn_graph, faiss::MetricType metric, float metricArg, @@ -112,73 +110,50 @@ CuvsCagra::CuvsCagra( indicesOptions == faiss::gpu::INDICES_64_BIT, "only INDICES_64_BIT is supported for cuVS CAGRA index"); - auto dataset_on_gpu = getDeviceForAddress(dataset) >= 0; - auto knn_graph_on_gpu = getDeviceForAddress(knn_graph) >= 0; - - FAISS_ASSERT(dataset_on_gpu == knn_graph_on_gpu); - - storage_ = dataset; - n_ = n; - - const raft::device_resources& raft_handle = - resources_->getRaftHandleCurrentDevice(); - - if (dataset_on_gpu && knn_graph_on_gpu) { + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); + auto graph = raft::make_host_matrix(n, graph_degree); + if (getDeviceForAddress(knn_graph) >= 0) { raft_handle.sync_stream(); - // Copying to host so that cuvs::neighbors::cagra::index - // creates an owning copy of the knn graph on device - auto knn_graph_copy = - raft::make_host_matrix(n, graph_degree); thrust::copy( thrust::device_ptr(knn_graph), - thrust::device_ptr(knn_graph + (n * graph_degree)), - knn_graph_copy.data_handle()); - - auto dataset_mds = raft::make_device_matrix_view( - dataset, n, dim); - - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - raft_handle, - metricFaissToCuvs(metric_, false), - dataset_mds, - raft::make_const_mdspan(knn_graph_copy.view())); - } else if (!dataset_on_gpu && !knn_graph_on_gpu) { - // copy idx_t (int64_t) host knn_graph to uint32_t host knn_graph - auto knn_graph_copy = - raft::make_host_matrix(n, graph_degree); - std::copy( - knn_graph, - knn_graph + (n * graph_degree), - knn_graph_copy.data_handle()); - - auto dataset_mds = raft::make_host_matrix_view( - dataset, n, dim); - - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - raft_handle, - metricFaissToCuvs(metric_, false), - dataset_mds, - raft::make_const_mdspan(knn_graph_copy.view())); + thrust::device_ptr(knn_graph + n * graph_degree), + graph.data_handle()); } else { - FAISS_THROW_MSG( - "dataset and knn_graph must both be in device or host memory"); + std::copy(knn_graph, knn_graph + n * graph_degree, graph.data_handle()); } -} -template -void CuvsCagra::train(idx_t n, const data_t* x) { - storage_ = x; + // A host graph makes cuVS allocate graph storage owned by the index. + cuvs_index = std::make_shared< + cuvs::neighbors::cagra::device_padded_index>( + raft_handle, metricFaissToCuvs(metric_, false)); + cuvs_index->update_graph( + raft_handle, raft::make_const_mdspan(graph.view())); + if (dataset) { + auto view = + cuvs::neighbors::device_padded_dataset_view( + raft::make_device_matrix_view( + static_cast(dataset->getData()), + n, + dataset->getRowStride()), + dataset->getDim()); + *cuvs_index = cuvs::neighbors::cagra::update_dataset( + raft_handle, std::move(*cuvs_index), view); + dataset_.emplace(dataset->view()); + } + // The host graph is temporary; finish its upload before releasing it. + raft_handle.sync_stream(); n_ = n; +} - const raft::device_resources& raft_handle = - resources_->getRaftHandleCurrentDevice(); +template +void CuvsCagra::train(const Dataset& dataset) { + const auto n = dataset.getNumRows(); + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); if (!ivf_pq_params_) { ivf_pq_params_ = cuvs::neighbors::ivf_pq::index_params::from_dataset( raft::make_extents( - static_cast(n_), static_cast(dim_)), + static_cast(n), static_cast(dim_)), metricFaissToCuvs(metric_, false)); } if (graph_build_algo_ == faiss::cagra_build_algo::IVF_PQ) { @@ -203,21 +178,141 @@ void CuvsCagra::train(idx_t n, const data_t* x) { index_params_.graph_build_params = graph_build_params; } - if (getDeviceForAddress(x) >= 0) { - auto dataset = raft::make_device_matrix_view( - x, n, dim_); - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - cuvs::neighbors::cagra::build( - raft_handle, index_params_, dataset)); + using CuvsIndex = + cuvs::neighbors::cagra::device_padded_index; + if (dataset.getLayout() == Dataset::Layout::BBQ) { + FAISS_THROW_IF_NOT_MSG( + graph_build_algo_ == faiss::cagra_build_algo::NN_DESCENT, + "BBQ datasets require NN-descent graph construction"); + namespace bbq = cuvs::preprocessing::quantize::bbq; + auto quantizerView = [&](const BBQQuantizer& quantizer) { + FAISS_THROW_IF_NOT_MSG( + quantizer.metric == metric_, + "BBQ corrections must match the CAGRA metric"); + auto layout = + static_cast(quantizer.codeLayout); + auto floats = [n](const float* data) { + return raft::make_device_vector_view( + data, n); + }; + return bbq::quantizer_view( + raft::make_device_matrix_view( + quantizer.codes, + n, + bbq::get_encoded_row_length(dim_, layout)), + floats(quantizer.lowerIntervals), + floats(quantizer.upperIntervals), + floats(quantizer.additionalCorrections), + raft::make_device_vector_view( + quantizer.quantizedComponentSums, n), + raft::make_device_vector_view( + static_cast(quantizer.centroid), + dim_), + floats(quantizer.dequantDelta), + floats(quantizer.dequantSumDelta), + floats(quantizer.rowNorm), + layout, + metricFaissToCuvs(quantizer.metric, false), + quantizer.centroidNormSquared); + }; + cuvs::neighbors::device_bbq_dataset_view view; + view.add_quantizer(quantizerView(*dataset.getBBQQuantizer(false))); + if (const auto* secondary = dataset.getBBQQuantizer(true)) { + view.add_quantizer(quantizerView(*secondary)); + } + // BBQ builds a graph but has no CAGRA search kernels. Keep the graph + // in the same empty padded index used for other graph-only builds. + cuvs_index = std::make_shared( + raft_handle, + cuvs::neighbors::cagra::build(raft_handle, index_params_, view), + cuvs::neighbors::device_padded_dataset_view{}); + dataset_.emplace(dataset.view()); + n_ = n; + return; + } + const auto* data = static_cast(dataset.getData()); + auto rowStride = dataset.getRowStride(); + bool deviceInput = dataset.isDevice(); + const bool nnDescentDeviceInput = deviceInput && + graph_build_algo_ == faiss::cagra_build_algo::NN_DESCENT; + std::vector packed; + if (!nnDescentDeviceInput && !dataset.isCagraCompatible() && + rowStride != dim_) { + // NN-descent reads device rows directly: the Dataset contract requires + // zero row gaps, which do not change distances. Its graph build does + // not require CAGRA's search alignment or exact padded row width. + // Pack logical columns for host input and other graph builders. + packed.resize(static_cast(n) * dim_); + dataset.copyToHost(packed.data()); + data = packed.data(); + rowStride = dim_; + deviceInput = false; + } + if (deviceInput) { + auto physical = raft::make_device_matrix_view( + data, n, rowStride); + if (dataset.isCagraCompatible()) { + auto view = cuvs::neighbors:: + device_padded_dataset_view( + physical, dataset.getDim()); + cuvs_index = + std::make_shared(cuvs::neighbors::cagra::build( + raft_handle, index_params_, view)); + } else { + auto view = cuvs::neighbors:: + device_standard_dataset_view( + physical, dataset.getDim()); + cuvs_index = std::make_shared( + raft_handle, + cuvs::neighbors::cagra::build( + raft_handle, index_params_, view), + cuvs::neighbors:: + device_padded_dataset_view{}); + } } else { - auto dataset = - raft::make_host_matrix_view(x, n, dim_); - cuvs_index = std::make_shared< - cuvs::neighbors::cagra::index>( - cuvs::neighbors::cagra::build( - raft_handle, index_params_, dataset)); + auto physical = raft::make_host_matrix_view( + data, n, rowStride); + auto view = + cuvs::neighbors::host_standard_dataset_view( + physical, dataset.getDim()); + cuvs_index = std::make_shared( + raft_handle, + cuvs::neighbors::cagra::build(raft_handle, index_params_, view), + cuvs::neighbors::device_padded_dataset_view{}); + } + if (!packed.empty()) { + raft_handle.sync_stream(); } + dataset_.emplace(dataset.view()); + n_ = n; +} + +template +void CuvsCagra::updateDataset(const Dataset& dataset) { + FAISS_THROW_IF_NOT_MSG( + cuvs_index, "CAGRA must be trained before updateDataset"); + FAISS_THROW_IF_NOT_MSG( + dataset.isCagraCompatible(), + "CAGRA search requires compatible device storage; use Dataset::makeDevicePadded"); + auto borrowed = dataset.view(); + const auto& raft_handle = resources_->getRaftHandleCurrentDevice(); + auto view = cuvs::neighbors::device_padded_dataset_view( + raft::make_device_matrix_view( + static_cast(dataset.getData()), + dataset.getNumRows(), + dataset.getRowStride()), + dataset.getDim()); + // Wait for previous searches before rebinding. On return the caller may + // release the old allocation, provided no other index is using it. + raft_handle.sync_stream(); + *cuvs_index = cuvs::neighbors::cagra::update_dataset( + raft_handle, std::move(*cuvs_index), view); + dataset_.emplace(std::move(borrowed)); +} + +template +bool CuvsCagra::isSearchReady() const { + return cuvs_index && dataset_ && dataset_->isCagraCompatible(); } template @@ -250,18 +345,9 @@ void CuvsCagra::search( FAISS_ASSERT(numQueries > 0); FAISS_ASSERT(cols == dim_); - if (!store_dataset_) { - if (getDeviceForAddress(storage_) >= 0) { - auto dataset = raft::make_device_matrix_view( - storage_, n_, dim_); - cuvs_index->update_dataset(raft_handle, dataset); - } else { - auto dataset = raft::make_host_matrix_view( - storage_, n_, dim_); - cuvs_index->update_dataset(raft_handle, dataset); - } - store_dataset_ = true; - } + FAISS_THROW_IF_NOT_MSG( + isSearchReady(), + "CAGRA has no search-compatible Dataset; attach one with updateDataset"); auto queries_view = raft::make_device_matrix_view( queries.data(), numQueries, cols); @@ -326,6 +412,8 @@ void CuvsCagra::search( template void CuvsCagra::reset() { cuvs_index.reset(); + dataset_.reset(); + n_ = 0; } template @@ -358,8 +446,11 @@ std::vector CuvsCagra::get_knngraph() const { } template -const data_t* CuvsCagra::get_training_dataset() const { - return storage_; +const Dataset& CuvsCagra::getDataset() const { + FAISS_THROW_IF_NOT_MSG( + dataset_, + "CAGRA has no Dataset; attach vectors with updateDataset before CPU export"); + return *dataset_; } template class CuvsCagra; diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cuh b/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cuh index b4c1989c6..aa04123ba 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cuh +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsCagra.cuh @@ -23,10 +23,12 @@ #pragma once +#include #include #include #include #include +#include #include #include @@ -34,6 +36,7 @@ #include #include +#include namespace faiss { @@ -61,7 +64,6 @@ class CuvsCagra { idx_t graph_degree, faiss::cagra_build_algo graph_build_algo, size_t nn_descent_niter, - bool store_dataset, faiss::MetricType metric, float metricArg, IndicesOptions indicesOptions, @@ -77,7 +79,7 @@ class CuvsCagra { int dim, idx_t n, int graph_degree, - const data_t* dataset, + const Dataset* dataset, const idx_t* knn_graph, faiss::MetricType metric, float metricArg, @@ -85,7 +87,11 @@ class CuvsCagra { ~CuvsCagra() = default; - void train(idx_t n, const data_t* x); + void train(const Dataset& dataset); + + void updateDataset(const Dataset& dataset); + + bool isSearchReady() const; void search( Tensor& queries, @@ -113,26 +119,19 @@ class CuvsCagra { std::vector get_knngraph() const; - const data_t* get_training_dataset() const; + const Dataset& getDataset() const; private: /// Collection of GPU resources that we use GpuResources* resources_; - /// Training dataset - const data_t* storage_; - int n_; + /// Borrowed metadata only; the caller owns the backing allocation. + std::optional dataset_; + idx_t n_ = 0; /// Expected dimensionality of the vectors const int dim_; - /// Controls the underlying cuVS index if it should store the dataset in - /// device memory. Default set to true for enabling search capabilities on - /// the index. - /// NB: This is also required to be set to true for deserializing - /// an IndexHNSWCagra object. - bool store_dataset_ = true; - /// Metric type of the index faiss::MetricType metric_; @@ -155,8 +154,9 @@ class CuvsCagra { bool guarantee_connectivity_ = false; /// Instance of trained cuVS CAGRA index - std::shared_ptr> cuvs_index{ - nullptr}; + std::shared_ptr< + cuvs::neighbors::cagra::device_padded_index> + cuvs_index{nullptr}; }; } // namespace gpu } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsFlatIndex.cu b/thirdparty/faiss/faiss/gpu/impl/CuvsFlatIndex.cu index d4a2d99fe..fd364add0 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsFlatIndex.cu +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsFlatIndex.cu @@ -30,7 +30,7 @@ #include #include -#include +#include #include #include #include diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFFlat.cu b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFFlat.cu index 59ccb2178..8ccf92803 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFFlat.cu +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFFlat.cu @@ -435,7 +435,14 @@ void CuvsIVFFlat::copyInvertedListsFrom(const InvertedLists* ivf) { (uint32_t)0); } - // Update the pointers and the sizes + raft::update_device( + cuvs_index->list_sizes().data_handle(), + list_sizes_.data(), + nlist, + raft_handle.get_stream()); + + // Recompute accumulated list sizes after uploading the actual sizes. + // cuVS uses them to size the search workspace for large k. cuvs::neighbors::ivf_flat::helpers::recompute_internal_state( raft_handle, cuvs_index.get()); @@ -445,12 +452,6 @@ void CuvsIVFFlat::copyInvertedListsFrom(const InvertedLists* ivf) { i, ivf->get_codes(i), ivf->get_ids(i), listSize); } - raft::update_device( - cuvs_index->list_sizes().data_handle(), - list_sizes_.data(), - nlist, - raft_handle.get_stream()); - // Precompute the centers vector norms for L2Expanded distance if (this->metric_ == faiss::METRIC_L2) { cuvs_index->allocate_center_norms(raft_handle); @@ -459,7 +460,7 @@ void CuvsIVFFlat::copyInvertedListsFrom(const InvertedLists* ivf) { cuvs_index->centers().data_handle(), cuvs_index->dim(), (uint32_t)nlist, - raft_handle.get_stream()); + raft_handle.get_stream().get()); } } diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFPQ.cu b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFPQ.cu index 1711b2f27..7ecb9b1b0 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFPQ.cu +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFPQ.cu @@ -33,9 +33,14 @@ #include #include #include +#include +#include + +#include #include #include +#include #include namespace faiss { @@ -379,6 +384,13 @@ void CuvsIVFPQ::search( cuvs::neighbors::ivf_pq::search_params pams; pams.n_probes = nprobe; pams.lut_dtype = useFloat16LookupTables_ ? CUDA_R_16F : CUDA_R_32F; +#if defined(FAISS_CUVS_HAS_STABLE_SELECT) + // The warp-sort selector caps at k = 256. Above that raft has no + // reproducible selector. + if (deterministicTieBreak_ && k <= 256 && nprobe <= 256) { + pams.select_algo = raft::matrix::SelectAlgo::kWarpDistributedShmStable; + } +#endif auto queries_view = raft::make_device_matrix_view( queries.data(), (idx_t)numQueries, (idx_t)cols); @@ -450,18 +462,116 @@ idx_t CuvsIVFPQ::addVectors( Index* coarseQuantizer, Tensor& vecs, Tensor& indices) { - /// NB: The coarse quantizer is ignored here. The user is assumed to have - /// called updateQuantizer() to update the cuVS index if the quantizer was - /// modified externally - FAISS_ASSERT(cuvs_index); const raft::device_resources& raft_handle = resources_->getRaftHandleCurrentDevice(); + auto stream = resources_->getDefaultStreamCurrentDevice(); /// Remove rows containing NaNs idx_t n_rows_valid = inplaceGatherFilteredRows(resources_, vecs, indices); + if (n_rows_valid == 0) { + return 0; + } + + if (metric_ == faiss::METRIC_INNER_PRODUCT) { + // cuVS classifies vectors with L2 during IVF-PQ extend even when the + // index metric is inner product. A Faiss index imported here uses its + // inner-product coarse quantizer, so bulk extend would place newly + // added vectors in different lists from the existing vectors. Preserve + // the Faiss assignments and let cuVS encode each assigned list. + DeviceTensor unusedIVFDistances( + resources_, + makeTempAlloc(AllocType::Other, stream), + {n_rows_valid, 1}); + DeviceTensor ivfAssignments( + resources_, + makeTempAlloc(AllocType::Other, stream), + {n_rows_valid, 1}); + + Tensor validVecs(vecs.data(), {n_rows_valid, dim_}); + searchCoarseQuantizer_( + coarseQuantizer, + 1, + validVecs, + unusedIVFDistances, + ivfAssignments, + nullptr, + nullptr); + + auto assignments = ivfAssignments.copyToVector(stream); + std::vector gatherIndices(n_rows_valid); + std::iota(gatherIndices.begin(), gatherIndices.end(), 0); + std::stable_sort( + gatherIndices.begin(), + gatherIndices.end(), + [&assignments](idx_t a, idx_t b) { + return assignments[a] < assignments[b]; + }); + + std::vector sortedAssignments(n_rows_valid); + for (idx_t i = 0; i < n_rows_valid; ++i) { + sortedAssignments[i] = assignments[gatherIndices[i]]; + FAISS_THROW_IF_NOT_FMT( + sortedAssignments[i] >= 0 && + sortedAssignments[i] < numLists_, + "IVF list id %ld is out of bounds (nlist %ld)", + sortedAssignments[i], + numLists_); + } + + auto gatherIndicesDevice = raft::make_device_vector( + raft_handle, n_rows_valid); + raft::update_device( + gatherIndicesDevice.data_handle(), + gatherIndices.data(), + n_rows_valid, + raft_handle.get_stream()); + auto sortedVecs = raft::make_device_matrix( + raft_handle, n_rows_valid, dim_); + raft::matrix::gather( + raft_handle, + raft::make_device_matrix_view( + vecs.data(), n_rows_valid, dim_), + raft::make_const_mdspan(gatherIndicesDevice.view()), + sortedVecs.view()); + + auto sortedIndices = raft::make_device_vector( + raft_handle, n_rows_valid); + thrust::gather( + raft_handle.get_thrust_policy(), + gatherIndicesDevice.data_handle(), + gatherIndicesDevice.data_handle() + n_rows_valid, + indices.data(), + sortedIndices.data_handle()); + + for (idx_t begin = 0; begin < n_rows_valid;) { + idx_t end = begin + 1; + while (end < n_rows_valid && + sortedAssignments[end] == sortedAssignments[begin]) { + ++end; + } + + FAISS_THROW_IF_NOT( + end - begin <= std::numeric_limits::max()); + auto count = static_cast(end - begin); + cuvs::neighbors::ivf_pq::helpers::codepacker::extend_list( + raft_handle, + cuvs_index.get(), + raft::make_device_matrix_view( + sortedVecs.data_handle() + begin * dim_, + count, + dim_), + raft::make_device_vector_view( + sortedIndices.data_handle() + begin, count), + static_cast(sortedAssignments[begin])); + begin = end; + } + + return n_rows_valid; + } + cuvs::neighbors::ivf_pq::extend( raft_handle, raft::make_device_matrix_view( diff --git a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFSQ.cu b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFSQ.cu index 7fa3f4d3a..1a5be4a39 100644 --- a/thirdparty/faiss/faiss/gpu/impl/CuvsIVFSQ.cu +++ b/thirdparty/faiss/faiss/gpu/impl/CuvsIVFSQ.cu @@ -185,6 +185,13 @@ void CuvsIVFSQ::search( resources_->getRaftHandleCurrentDevice(); cuvs::neighbors::ivf_sq::search_params pams; pams.n_probes = nprobe; +#if defined(FAISS_CUVS_HAS_STABLE_SELECT) + // The warp-sort selector caps at k = 256. Above that raft has no + // reproducible selector. + if (deterministicTieBreak_ && k <= 256 && nprobe <= 256) { + pams.select_algo = raft::matrix::SelectAlgo::kWarpDistributedShmStable; + } +#endif auto queries_view = raft::make_device_matrix_view( queries.data(), (idx_t)numQueries, (idx_t)cols); @@ -742,7 +749,7 @@ void CuvsIVFSQ::computeCenterNorms_() { cuvs_index->centers().data_handle(), cuvs_index->dim(), static_cast(numLists_), - raft_handle.get_stream()); + raft_handle.get_stream().get()); } void CuvsIVFSQ::recomputeListState_(const std::vector& listSizes) { diff --git a/thirdparty/faiss/faiss/gpu/impl/IVFBase.cuh b/thirdparty/faiss/faiss/gpu/impl/IVFBase.cuh index bb3340f1c..9b18a7923 100644 --- a/thirdparty/faiss/faiss/gpu/impl/IVFBase.cuh +++ b/thirdparty/faiss/faiss/gpu/impl/IVFBase.cuh @@ -41,6 +41,11 @@ class IVFBase { virtual ~IVFBase(); + /// See GpuIndexIVFConfig::deterministic_tie_break. + void setDeterministicTieBreak(bool on) { + deterministicTieBreak_ = on; + } + /// Reserve GPU memory in our inverted lists for this number of vectors virtual void reserveMemory(idx_t numVecs); @@ -253,6 +258,8 @@ class IVFBase { /// How are user indices stored on the GPU? const IndicesOptions indicesOptions_; + bool deterministicTieBreak_ = false; + /// What memory space our inverted list storage is in const MemorySpace space_; diff --git a/thirdparty/faiss/faiss/gpu/impl/IVFFlat.cu b/thirdparty/faiss/faiss/gpu/impl/IVFFlat.cu index 77b298793..98b0d13f2 100644 --- a/thirdparty/faiss/faiss/gpu/impl/IVFFlat.cu +++ b/thirdparty/faiss/faiss/gpu/impl/IVFFlat.cu @@ -358,6 +358,7 @@ void IVFFlat::searchImpl_( k, metric_, useResidual_, + deterministicTieBreak_, ivfCentroids, scalarQ_.get(), outDistances, diff --git a/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cu b/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cu index fc99a4916..46d29d5ec 100644 --- a/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cu +++ b/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cu @@ -20,10 +20,12 @@ __global__ void ivfInterleavedScan2( Tensor distanceIn, Tensor indicesIn, Tensor listIds, + idx_t* listLengths, int k, void** listIndices, IndicesOptions opt, bool dir, + bool tieBreak, Tensor distanceOut, Tensor indicesOut) { if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) { @@ -46,7 +48,7 @@ __global__ void ivfInterleavedScan2( float, uint32_t, false, - Comparator, + IVFScanComparator, NumWarpQ, NumThreadQ, ThreadsPerBlock> @@ -74,9 +76,10 @@ __global__ void ivfInterleavedScan2( // together into a uint32_t uint32_t index = (curProbe << 16) | (curK & (uint32_t)0xffff); - // The IDs reported from the list may be -1, if a particular IVF - // list doesn't even have k entries in it - if (listIds[queryId][curProbe] != -1) { + // Reject pass-1 padding: a short list leaves padded slots, and + // the tie-break can select them. + idx_t listId = listIds[queryId][curProbe]; + if (listId != -1 && (idx_t)curK < listLengths[listId]) { // Adjust the value we are selecting based on the sorting order heap.addThreadQ(distanceBase[i] * adj, index); } @@ -91,7 +94,7 @@ __global__ void ivfInterleavedScan2( uint32_t index = (curProbe << 16) | (curK & (uint32_t)0xffff); idx_t listId = listIds[queryId][curProbe]; - if (listId != -1) { + if (listId != -1 && (idx_t)curK < listLengths[listId]) { heap.addThreadQ(distanceBase[i] * adj, index); } } @@ -114,14 +117,19 @@ __global__ void ivfInterleavedScan2( uint32_t curK = packedIndex & 0xffff; idx_t listId = listIds[queryId][curProbe]; - idx_t listOffset = indicesIn[queryId][curProbe][curK]; + idx_t stored = indicesIn[queryId][curProbe][curK]; - if (opt == INDICES_32_BIT) { - index = (idx_t)((int*)listIndices[listId])[listOffset]; - } else if (opt == INDICES_64_BIT) { - index = ((idx_t*)listIndices[listId])[listOffset]; + // With the tie-break, pass 1 already resolved the user id. + if (opt == INDICES_32_BIT || opt == INDICES_64_BIT) { + if (tieBreak) { + index = stored; + } else if (opt == INDICES_64_BIT) { + index = ((idx_t*)listIndices[listId])[stored]; + } else { + index = (idx_t)((int*)listIndices[listId])[stored]; + } } else { - index = (listId << 32 | (idx_t)listOffset); + index = (listId << 32 | (idx_t)stored); } } @@ -134,10 +142,12 @@ void runIVFInterleavedScan2( Tensor& distanceIn, Tensor& indicesIn, Tensor& listIds, + DeviceVector& listLengths, int k, DeviceVector& listIndices, IndicesOptions indicesOptions, bool dir, + bool tieBreak, Tensor& distanceOut, Tensor& indicesOut, cudaStream_t stream) { @@ -147,10 +157,12 @@ void runIVFInterleavedScan2( distanceIn, \ indicesIn, \ listIds, \ + listLengths.data(), \ k, \ listIndices.data(), \ indicesOptions, \ dir, \ + tieBreak, \ distanceOut, \ indicesOut) @@ -186,6 +198,7 @@ void runIVFInterleavedScan( int k, faiss::MetricType metric, bool useResidual, + bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, // output @@ -195,6 +208,9 @@ void runIVFInterleavedScan( GpuResources* res) { // caught for exceptions at a higher level FAISS_ASSERT(k <= GPU_MAX_SELECTION_K); + // Both passes must agree: with the tie break, pass 1 stores ids, not + // list offsets. + tieBreak = tieBreak && k <= kMaxTieBreakK; const auto ivf_interleaved_call = [&](const auto func) { func(queries, @@ -206,6 +222,7 @@ void runIVFInterleavedScan( k, metric, useResidual, + tieBreak, residualBase, scalarQ, outDistances, @@ -216,7 +233,7 @@ void runIVFInterleavedScan( if (k == 1) { ivf_interleaved_call(ivfInterleavedScanImpl<128, 1, 1>); } else if (k <= 32 && getWarpSizeCurrentDevice() == 32) { - ivf_interleaved_call(ivfInterleavedScanImpl<128, 32, 2>); + ivf_interleaved_call(ivfInterleavedScanImpl<64, 32, 2>); } else if (k <= 64) { ivf_interleaved_call(ivfInterleavedScanImpl<128, 64, 3>); } else if (k <= 128) { diff --git a/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cuh b/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cuh index 1b7fbbe7a..68c8b2629 100644 --- a/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cuh +++ b/thirdparty/faiss/faiss/gpu/impl/IVFInterleaved.cuh @@ -24,10 +24,43 @@ #include #include #include +#include namespace faiss { namespace gpu { +/// The largest k for which the scan breaks a distance tie on the id. The +/// kernels for a larger k keep `Comparator`, because the tie break in their +/// large unrolled merge networks costs much code size. +constexpr int kMaxTieBreakK = 1024; + +/// The comparator of a scan kernel that selects `NumWarpQ` elements. +template +using IVFScanComparator = std::conditional_t< + NumWarpQ <= kMaxTieBreakK, + TieBreakComparator, + Comparator>; + +/// The value that the first-pass k-selection breaks a distance tie on. +/// +/// The value is the user id when the ids are on the device. If they are not, +/// the value is the position in the list, which follows insertion order. So +/// `INDICES_CPU` and `INDICES_IVF` do not repeat a tie. +/// `runIVFInterleavedScan2` tests the same condition to find whether its input +/// holds ids. +__device__ __forceinline__ idx_t ivfSelectionKey( + void** allListIndices, + IndicesOptions opt, + idx_t listId, + idx_t vec) { + if (opt == INDICES_64_BIT) { + return ((idx_t*)allListIndices[listId])[vec]; + } else if (opt == INDICES_32_BIT) { + return (idx_t)((int*)allListIndices[listId])[vec]; + } + return vec; +} + /// First pass kernel to perform scanning of IVF lists to produce top-k /// candidates template < @@ -41,6 +74,8 @@ __global__ void ivfInterleavedScan( Tensor residualBase, Tensor listIds, void** allListData, + void** allListIndices, + IndicesOptions opt, idx_t* listLengths, Codec codec, Metric metric, @@ -48,7 +83,8 @@ __global__ void ivfInterleavedScan( // [query][probe][k] Tensor distanceOut, Tensor indicesOut, - const bool Residual) { + const bool Residual, + const bool TieBreak) { if constexpr ((NumWarpQ == 1 && NumThreadQ == 1) || NumWarpQ >= kWarpSize) { extern __shared__ float smem[]; @@ -88,7 +124,7 @@ __global__ void ivfInterleavedScan( float, idx_t, Metric::kDirection, - Comparator, + IVFScanComparator, NumWarpQ, NumThreadQ, ThreadsPerBlock> @@ -204,7 +240,22 @@ __global__ void ivfInterleavedScan( } if (valid) { - heap.addThreadQ(dist.reduce(), vec); + const float d = dist.reduce(); + idx_t value = vec; + if (NumWarpQ <= kMaxTieBreakK && TieBreak) { + // A strictly worse key cannot enter, so skip its id. + bool couldEnter = true; + if constexpr (NumWarpQ > 1) { + couldEnter = Metric::kDirection + ? (d >= heap.warpKTop) + : (d <= heap.warpKTop); + } + value = couldEnter + ? ivfSelectionKey( + allListIndices, opt, listId, vec) + : idx_t(-1); + } + heap.addThreadQ(d, value); } heap.checkThreadQ(); @@ -240,6 +291,7 @@ void runIVFInterleavedScan( int k, faiss::MetricType metric, bool useResidual, + bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, // output @@ -254,10 +306,12 @@ void runIVFInterleavedScan2( Tensor& distanceIn, Tensor& indicesIn, Tensor& listIds, + DeviceVector& listLengths, int k, DeviceVector& listIndices, IndicesOptions indicesOptions, bool dir, + bool tieBreak, Tensor& distanceOut, Tensor& indicesOut, cudaStream_t stream); diff --git a/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh b/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh index 75c228c11..d19014c0e 100644 --- a/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh +++ b/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedImpl.cuh @@ -32,6 +32,7 @@ void IVFINT_RUN( const int k, METRIC_TYPE metric, const bool useResidual, + const bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, Tensor& outDistances, @@ -49,6 +50,7 @@ void IVFINT_CODECS( const int k, METRIC_TYPE metric, const bool useResidual, + const bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, Tensor& outDistances, @@ -67,6 +69,7 @@ void IVFINT_CODECS( k, metric, useResidual, + tieBreak, residualBase, scalarQ, outDistances, @@ -214,6 +217,7 @@ void ivfInterleavedScanImpl( const int k, faiss::MetricType metric_name, const bool useResidual, + const bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, Tensor& outDistances, @@ -231,6 +235,7 @@ void ivfInterleavedScanImpl( k, metric, useResidual, + tieBreak, residualBase, scalarQ, outDistances, diff --git a/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu b/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu index 1481f4d12..532828e76 100644 --- a/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu +++ b/thirdparty/faiss/faiss/gpu/impl/scan/IVFInterleavedScanKernelTemplate.cu @@ -27,6 +27,7 @@ void IVFINT_RUN< const int k, SUB_METRIC_TYPE metric, const bool useResidual, + const bool tieBreak, Tensor& residualBase, GpuScalarQuantizer* scalarQ, Tensor& outDistances, @@ -60,22 +61,27 @@ void IVFINT_RUN< residualBase, listIds, listData.data(), + listIndices.data(), + indicesOptions, listLengths.data(), codec, metric, k, distanceTemp, indicesTemp, - useResidual); + useResidual, + tieBreak); runIVFInterleavedScan2( distanceTemp, indicesTemp, listIds, + listLengths, k, listIndices, indicesOptions, SUB_METRIC_TYPE::kDirection, + tieBreak, outDistances, outIndices, stream); diff --git a/thirdparty/faiss/faiss/gpu/test/CMakeLists.txt b/thirdparty/faiss/faiss/gpu/test/CMakeLists.txt index bbd789ddd..534a39ddb 100644 --- a/thirdparty/faiss/faiss/gpu/test/CMakeLists.txt +++ b/thirdparty/faiss/faiss/gpu/test/CMakeLists.txt @@ -50,6 +50,9 @@ faiss_gpu_test(TestGpuResidualQuantizer.cpp) faiss_gpu_test(TestGpuDistance.${GPU_EXT_PREFIX}) faiss_gpu_test(TestGpuSelect.${GPU_EXT_PREFIX}) if(FAISS_ENABLE_CUVS) + faiss_gpu_test(TestGpuDataset.cu) + add_library(TestGpuDatasetHeader OBJECT TestGpuDatasetHeader.cpp) + target_link_libraries(TestGpuDatasetHeader PRIVATE faiss) faiss_gpu_test(TestGpuFilterConvert.cu) faiss_gpu_test(TestGpuIndexBinaryCagra.cu) faiss_gpu_test(TestGpuIndexCagra.cu) diff --git a/thirdparty/faiss/faiss/gpu/test/TestCodePacking.cpp b/thirdparty/faiss/faiss/gpu/test/TestCodePacking.cpp index 4b08b6276..d3ab6b3ea 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestCodePacking.cpp +++ b/thirdparty/faiss/faiss/gpu/test/TestCodePacking.cpp @@ -22,7 +22,9 @@ TEST(TestCodePacking, NonInterleavedCodes_UnpackPack) { // deterministic auto seed = std::random_device()(); std::mt19937 gen(seed); - std::uniform_int_distribution dist; + // uint8_t is not a conforming uniform_int_distribution type (N4950 + // [rand.req.genl]/1.5); MSVC's STL rejects it. Use int over [0,255]. + std::uniform_int_distribution dist{0, 255}; std::cout << "seed " << seed << "\n"; @@ -74,7 +76,9 @@ TEST(TestCodePacking, NonInterleavedCodes_PackUnpack) { // deterministic std::random_device rd; std::mt19937 gen(rd()); - std::uniform_int_distribution dist; + // uint8_t is not a conforming uniform_int_distribution type (N4950 + // [rand.req.genl]/1.5); MSVC's STL rejects it. Use int over [0,255]. + std::uniform_int_distribution dist{0, 255}; for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) { for (auto dims : {1, 7, 8, 31, 32}) { @@ -112,7 +116,9 @@ TEST(TestCodePacking, InterleavedCodes_UnpackPack) { // deterministic std::random_device rd; std::mt19937 gen(rd()); - std::uniform_int_distribution dist; + // uint8_t is not a conforming uniform_int_distribution type (N4950 + // [rand.req.genl]/1.5); MSVC's STL rejects it. Use int over [0,255]. + std::uniform_int_distribution dist{0, 255}; for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) { for (auto dims : {1, 7, 8, 31, 32}) { @@ -249,7 +255,9 @@ TEST(TestCodePacking, InterleavedCodes_PackUnpack) { // deterministic std::random_device rd; std::mt19937 gen(rd()); - std::uniform_int_distribution dist; + // uint8_t is not a conforming uniform_int_distribution type (N4950 + // [rand.req.genl]/1.5); MSVC's STL rejects it. Use int over [0,255]. + std::uniform_int_distribution dist{0, 255}; for (auto bitsPerCode : {4, 5, 6, 8, 16, 32}) { for (auto dims : {1, 7, 8, 31, 32}) { diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuDataset.cu b/thirdparty/faiss/faiss/gpu/test/TestGpuDataset.cu new file mode 100644 index 000000000..d0aacc5e6 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuDataset.cu @@ -0,0 +1,237 @@ +/* + * 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. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using faiss::NumericType; +using faiss::gpu::Dataset; +using faiss::gpu::StandardGpuResources; + +TEST(TestGpuDataset, HostStridesCopyLogicalColumnsWithoutChangingInput) { + std::vector storage{-128, 0, 127, 42, 42, -1, 1, 2, 43, 43}; + const auto original = storage; + auto dataset = + Dataset::viewHost(storage.data(), 2, 3, NumericType::Int8, 5); + EXPECT_FALSE(dataset.ownsData()); + EXPECT_FALSE(dataset.isDevice()); + EXPECT_FALSE(dataset.isCagraCompatible()); + EXPECT_EQ(dataset.getDevice(), -1); + EXPECT_EQ(dataset.getData(), storage.data()); + EXPECT_EQ(dataset.getLayout(), Dataset::Layout::Standard); + std::vector packed(6); + dataset.copyToHost(packed.data()); + EXPECT_EQ(packed, (std::vector{-128, 0, 127, -1, 1, 2})); + EXPECT_EQ(storage, original); +} + +TEST(TestGpuDataset, InvalidMetadataIsRejected) { + std::vector storage(32); + EXPECT_THROW( + Dataset::viewHost(nullptr, 2, 4, NumericType::Float32, 4), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewHost(storage.data(), -1, 4, NumericType::Float32, 4), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewHost(storage.data(), 2, 0, NumericType::Float32, 4), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewHost(storage.data(), 2, 4, NumericType::Float32, 3), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewHost( + storage.data(), 2, 4, static_cast(99), 4), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewDevice( + storage.data(), 2, 4, NumericType::Float32, 4, 0), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewDevice( + storage.data(), 2, 4, NumericType::Float32, 4, -1), + faiss::FaissException); +} + +template +void testPaddedCopy(NumericType type) { + constexpr int dim = 5; + constexpr int sourceStride = 9; + constexpr int numRows = 3; + std::vector storage(numRows * sourceStride, T(42)); + std::vector expected(numRows * dim); + for (int row = 0; row < numRows; ++row) { + for (int col = 0; col < dim; ++col) { + expected[row * dim + col] = T(row * dim + col + 1); + storage[row * sourceStride + col] = expected[row * dim + col]; + } + } + const auto original = storage; + auto resources = std::make_unique(); + resources->noTempMemory(); + auto input = + Dataset::viewHost(storage.data(), numRows, dim, type, sourceStride); + auto output = Dataset::makeDevicePadded(resources.get(), input, 0); + EXPECT_TRUE(output.ownsData()); + EXPECT_TRUE(output.isDevice()); + EXPECT_TRUE(output.isCagraCompatible()); + EXPECT_EQ(output.getLayout(), Dataset::Layout::Padded); + EXPECT_EQ(output.getNumericType(), type); + EXPECT_EQ(output.getNumRows(), numRows); + EXPECT_EQ(output.getDim(), dim); + EXPECT_EQ( + output.getRowStride(), + ((dim * sizeof(T) + 15) / 16) * 16 / sizeof(T)); + std::vector actual(expected.size()); + output.copyToHost(actual.data()); + EXPECT_EQ( + std::memcmp( + actual.data(), expected.data(), actual.size() * sizeof(T)), + 0); + EXPECT_EQ( + std::memcmp( + storage.data(), + original.data(), + storage.size() * sizeof(T)), + 0); + + std::vector physical(numRows * output.getRowStride()); + ASSERT_EQ( + cudaMemcpy( + physical.data(), + output.getData(), + physical.size() * sizeof(T), + cudaMemcpyDeviceToHost), + cudaSuccess); + for (int row = 0; row < numRows; ++row) { + for (int col = dim; col < output.getRowStride(); ++col) { + EXPECT_EQ( + static_cast( + physical[row * output.getRowStride() + col]), + 0); + } + } + + // After the copy completes, resource providers and host inputs can go away. + resources.reset(); + storage.clear(); + output.copyToHost(actual.data()); + EXPECT_EQ( + std::memcmp( + actual.data(), expected.data(), actual.size() * sizeof(T)), + 0); +} + +TEST(TestGpuDataset, PaddedCopiesAllDtypesAndRetainsResources) { + testPaddedCopy(NumericType::Float32); + testPaddedCopy(NumericType::Float16); + testPaddedCopy(NumericType::Int8); + testPaddedCopy(NumericType::UInt8); +} + +TEST(TestGpuDataset, AlignedStandardInputCanBeBorrowedForSearch) { + // 12 floats are 48 bytes, satisfying alignment without dim % 16 == 0. + std::vector storage(24, 1.0f); + StandardGpuResources resources; + resources.noTempMemory(); + auto host = + Dataset::viewHost(storage.data(), 2, 12, NumericType::Float32, 12); + auto owner = Dataset::makeDevicePadded(&resources, host, 0); + auto standard = Dataset::viewDevice( + owner.getData(), 2, 12, NumericType::Float32, 12, 0); + EXPECT_EQ(standard.getLayout(), Dataset::Layout::Standard); + EXPECT_TRUE(standard.isCagraCompatible()); + EXPECT_FALSE(standard.ownsData()); + EXPECT_EQ(standard.getData(), owner.getData()); + + auto padded = Dataset::viewDevicePadded( + owner.getData(), 2, 12, NumericType::Float32, 12, 0); + EXPECT_EQ(padded.getData(), owner.getData()); + EXPECT_TRUE(padded.isCagraCompatible()); + EXPECT_THROW( + Dataset::viewDevicePadded( + owner.getData(), 1, 4, NumericType::Float32, 8, 0), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewDevicePadded( + static_cast(owner.getData()) + 1, + 1, + 4, + NumericType::Float32, + 4, + 0), + faiss::FaissException); + EXPECT_THROW( + Dataset::viewHost(owner.getData(), 2, 12, NumericType::Float32, 12), + faiss::FaissException); +} + +TEST(TestGpuDataset, PreparingCompatibleDeviceInputIsRejected) { + StandardGpuResources resources; + resources.noTempMemory(); + std::vector values(10, 1.0f); + auto host = Dataset::viewHost(values.data(), 2, 5, NumericType::Float32, 5); + auto owner = Dataset::makeDevicePadded(&resources, host, 0); + resources.getResources()->syncDefaultStream(0); + EXPECT_THROW( + Dataset::makeDevicePadded(&resources, owner, 0), raft::logic_error); + auto standard = Dataset::viewDevice( + owner.getData(), + 2, + 5, + NumericType::Float32, + owner.getRowStride(), + 0); + EXPECT_THROW( + Dataset::makeDevicePadded(&resources, standard, 0), + raft::logic_error); +} + +TEST(TestGpuDataset, MovingOwnerPreservesViewAndViewDoesNotOwnStorage) { + StandardGpuResources resources; + resources.noTempMemory(); + std::vector expected(10, 2.0f); + auto host = + Dataset::viewHost(expected.data(), 2, 5, NumericType::Float32, 5); + auto owner = Dataset::makeDevicePadded(&resources, host, 0); + auto borrowed = owner.view(); + const void* allocation = owner.getData(); + auto movedOwner = std::move(owner); + EXPECT_TRUE(movedOwner.ownsData()); + EXPECT_FALSE(borrowed.ownsData()); + EXPECT_EQ(movedOwner.getData(), allocation); + EXPECT_EQ(borrowed.getData(), allocation); + std::vector actual(expected.size()); + borrowed.copyToHost(actual.data()); + EXPECT_EQ(actual, expected); + EXPECT_THROW(owner.getData(), faiss::FaissException); + { + auto anotherBorrow = movedOwner.view(); + EXPECT_FALSE(anotherBorrow.ownsData()); + } + movedOwner.copyToHost(actual.data()); + EXPECT_EQ(actual, expected); +} + +} // namespace + +int main(int argc, char** argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuDatasetHeader.cpp b/thirdparty/faiss/faiss/gpu/test/TestGpuDatasetHeader.cpp new file mode 100644 index 000000000..597474ac9 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuDatasetHeader.cpp @@ -0,0 +1,18 @@ +/* + * 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. + */ + +// Keep this translation unit ordinary C++ without CUDA, RAFT, or cuVS headers. +#include + +#include + +using faiss::gpu::Dataset; + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexBinaryCagra.cu b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexBinaryCagra.cu index 6b3c2488f..f521cd511 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexBinaryCagra.cu +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexBinaryCagra.cu @@ -21,22 +21,47 @@ * limitations under the License. */ +#include #include +#include +#include +#include #include #include #include #include +#include #include +#include +#include #include +#include #include +#include #include #include +#include #include +#include +#include +#include #include #include #include +// Explicit owner kept by each test for the lifetime of its borrowing index. +faiss::gpu::Dataset makeSearchDataset( + faiss::gpu::GpuResourcesProvider* resources, + faiss::idx_t n, + int dim, + const void* data, + faiss::NumericType type, + int device) { + auto source = faiss::gpu::Dataset::viewHost(data, n, dim, type, dim); + return faiss::gpu::Dataset::makeDevicePadded(resources, source, device); +} + struct Options { Options() { numTrain = 2 * faiss::gpu::randVal(1000, 2000); @@ -98,8 +123,17 @@ void queryTest( config.nn_descent_niter = 20; } + std::optional trainingDataset; + faiss::gpu::GpuIndexBinaryCagra gpuIndex(&res, cpuIndex.d, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim / 8, + trainVecs.data(), + faiss::NumericType::UInt8, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randBinaryVecs(opt.numQuery, opt.dim); @@ -209,8 +243,17 @@ void copyToTest( config.nn_descent_niter = 20; } + std::optional trainingDataset; + faiss::gpu::GpuIndexBinaryCagra gpuIndex(&res, opt.dim, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim / 8, + trainVecs.data(), + faiss::NumericType::UInt8, + opt.device)); + gpuIndex.train(*trainingDataset); faiss::IndexBinaryHNSWCagra copiedCpuIndex( opt.dim, opt.graphDegree / 2); @@ -338,8 +381,20 @@ void copyFromTest( res.noTempMemory(); // convert to gpu index + const auto* cpuStorage = + dynamic_cast(cpuIndex.storage); + ASSERT_NE(cpuStorage, nullptr); + auto cpuDataset = faiss::gpu::Dataset::viewHost( + cpuStorage->xb.data(), + cpuIndex.ntotal, + cpuIndex.d / 8, + faiss::NumericType::UInt8, + cpuIndex.d / 8); + auto importedDataset = + faiss::gpu::Dataset::makeDevicePadded(&res, cpuDataset, 0); + res.getResources()->syncDefaultStream(0); faiss::gpu::GpuIndexBinaryCagra copiedGpuIndex(&res, cpuIndex.d); - copiedGpuIndex.copyFrom(&cpuIndex); + copiedGpuIndex.copyFrom(&cpuIndex, &importedDataset); // train gpu index faiss::gpu::GpuIndexCagraConfig config; @@ -351,8 +406,17 @@ void copyFromTest( config.nn_descent_niter = 20; } + std::optional trainingDataset; + faiss::gpu::GpuIndexBinaryCagra gpuIndex(&res, opt.dim, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim / 8, + trainVecs.data(), + faiss::NumericType::UInt8, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randBinaryVecs(opt.numQuery, opt.dim); @@ -447,8 +511,17 @@ void testIDSelectorBinaryCagra(std::string selectorName) { config.build_algo = faiss::gpu::graph_build_algo::NN_DESCENT; config.nn_descent_niter = 20; + std::optional trainingDataset; + faiss::gpu::GpuIndexBinaryCagra gpuIndex(&res, opt.dim, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim / 8, + trainVecs.data(), + faiss::NumericType::UInt8, + opt.device)); + gpuIndex.train(*trainingDataset); auto queryVecs = faiss::gpu::randBinaryVecs(opt.numQuery, opt.dim); faiss::gpu::TestIDSelectorStruct selector_struct(opt.numTrain); @@ -501,6 +574,425 @@ TEST(TestGpuIndexBinaryCagra, IDSelector_XOr) { testIDSelectorBinaryCagra("XOr"); } +namespace { +using faiss::idx_t; +using faiss::NumericType; +using faiss::gpu::Dataset; +using faiss::gpu::GpuIndexBinaryCagra; +using faiss::gpu::StandardGpuResources; + +constexpr idx_t kRows = 512; + +faiss::gpu::GpuIndexCagraConfig config() { + faiss::gpu::GpuIndexCagraConfig out; + out.device = 0; + out.graph_degree = 16; + out.intermediate_graph_degree = 32; + out.build_algo = faiss::gpu::graph_build_algo::NN_DESCENT; + return out; +} + +std::vector binaryData(int bytes) { + std::mt19937 random(4321); + std::vector data(kRows * bytes); + for (auto& x : data) { + x = static_cast(random()); + } + return data; +} + +void checkBinarySearch(faiss::IndexBinary& index, const uint8_t* queries) { + std::vector distances(8); + std::vector labels(8); + index.search(8, queries, 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + int selfHits = 0; + for (int i = 0; i < 8; ++i) { + EXPECT_GE(labels[i], 0); + EXPECT_LT(labels[i], kRows); + selfHits += labels[i] == i; + } + EXPECT_GE(selfHits, 6); +} + +TEST(TestGpuIndexBinaryCagra, + PointerConstructionRejectedThroughBaseInterfaces) { + StandardGpuResources resources; + auto bytes = binaryData(16); + GpuIndexBinaryCagra binary(&resources, 128, config()); + faiss::IndexBinary* binaryBase = &binary; + EXPECT_THROW(binaryBase->train(kRows, bytes.data()), faiss::FaissException); + EXPECT_THROW(binaryBase->add(kRows, bytes.data()), faiss::FaissException); + EXPECT_THROW( + binaryBase->train_ex(kRows, bytes.data(), NumericType::UInt8), + faiss::FaissException); + EXPECT_THROW( + binaryBase->add_ex(kRows, bytes.data(), NumericType::UInt8), + faiss::FaissException); + EXPECT_FALSE(binary.is_trained); + + faiss::IndexBinaryFlat binaryFlat(128); + binaryBase = &binaryFlat; + EXPECT_NO_THROW(binaryBase->add(kRows, bytes.data())); + EXPECT_EQ(binaryFlat.ntotal, kRows); +} + +TEST(TestGpuIndexBinaryCagra, DatasetIDMap) { + constexpr int dim = 20; + StandardGpuResources resources; + auto values = binaryData(dim); + auto source = Dataset::viewHost( + values.data(), kRows, dim, NumericType::UInt8, dim); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexBinaryCagra cagra(&resources, dim * 8, config()); + faiss::IndexBinaryIDMap2 index(&cagra); + index.train_dataset(storage); + EXPECT_TRUE(index.is_trained); + const auto graph = cagra.get_knngraph(); + faiss::IndexBinary* base = &index; + base->train_dataset(source); + EXPECT_TRUE(cagra.isSearchReady()); + EXPECT_EQ(cagra.get_knngraph(), graph); + + std::vector ids(kRows); + for (idx_t i = 0; i < kRows; ++i) { + ids[i] = 1000 + 2 * i; + } + index.add_with_ids(storage, ids.data()); + EXPECT_EQ(index.ntotal, kRows); + EXPECT_EQ(index.id_map, ids); + EXPECT_NO_THROW(index.check_consistency()); + + std::vector distances(8); + std::vector labels(8); + index.search(8, values.data(), 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + for (auto label : labels) { + EXPECT_GE(label, 1000); + EXPECT_LT(label, 1000 + 2 * kRows); + EXPECT_EQ((label - 1000) % 2, 0); + } + index.reset(); + EXPECT_FALSE(index.is_trained); + EXPECT_EQ(index.ntotal, 0); +} + +TEST(TestGpuIndexBinaryCagra, DatasetAsyncRebindResetAndDestruction) { + constexpr int dim = 19; + constexpr int nq = 64; + auto values = binaryData(dim); + faiss::gpu::DeviceScope scope(0); + cudaStream_t alternateStream; + ASSERT_EQ( + cudaStreamCreateWithFlags(&alternateStream, cudaStreamNonBlocking), + cudaSuccess); + const auto destroyStream = [](cudaStream_t stream) { + EXPECT_EQ(cudaStreamDestroy(stream), cudaSuccess); + }; + // cuVS descriptor caches retain their allocation stream in the resource + // handle, so the external stream must also outlive those resources. + std::unique_ptr< + std::remove_pointer_t, + decltype(destroyStream)> + streamOwner(alternateStream, destroyStream); + StandardGpuResources resources; + auto source = Dataset::viewHost( + values.data(), kRows, dim, NumericType::UInt8, dim); + std::optional first( + Dataset::makeDevicePadded(&resources, source, 0)); + std::optional second( + Dataset::makeDevicePadded(&resources, source, 0)); + auto index = std::make_unique( + &resources, dim * 8, config()); + index->train(*first); + + auto gpuResources = resources.getResources(); + auto originalStream = gpuResources->getDefaultStream(0); + auto queries = faiss::gpu::toDeviceTemporary( + gpuResources.get(), values, originalStream); + auto alloc = faiss::gpu::makeTempAlloc( + faiss::gpu::AllocType::Other, originalStream); + faiss::gpu::DeviceTensor distances( + gpuResources.get(), alloc, {nq, 1}); + faiss::gpu::DeviceTensor labels( + gpuResources.get(), alloc, {nq, 1}); + resources.setDefaultStream(0, alternateStream); + auto checkResults = [&](cudaStream_t stream) { + std::vector actualDistances(nq); + std::vector actualLabels(nq); + faiss::gpu::fromDevice(distances, actualDistances.data(), stream); + faiss::gpu::fromDevice(labels, actualLabels.data(), stream); + int selfHits = 0; + for (int i = 0; i < nq; ++i) { + EXPECT_GE(actualLabels[i], 0); + EXPECT_LT(actualLabels[i], kRows); + if (actualLabels[i] == i) { + ++selfHits; + EXPECT_NEAR(actualDistances[i], 0, 1e-5); + } + } + EXPECT_GE(selfHits, nq * 3 / 4); + }; + + // These searches keep both inputs and outputs on device and queue work. + // Rebind/reset must finish use of the old allocation before its release. + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index->updateDataset(*second); + first.reset(); + checkResults(alternateStream); + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index->reset(); + second.reset(); + checkResults(alternateStream); + + // Build on B, then search on A and destroy without an explicit reset. + // Keep the caller-owned data alive to isolate graph-storage destruction. + std::optional third( + Dataset::makeDevicePadded(&resources, source, 0)); + index->train(*third); + resources.revertDefaultStream(0); + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index.reset(); + checkResults(originalStream); + third.reset(); +} + +TEST(TestGpuIndexBinaryCagra, DatasetGraphOnlyAttachmentAndCpuRoundTrip) { + constexpr int bytes = 19; + StandardGpuResources resources; + auto values = binaryData(bytes); + auto source = Dataset::viewHost( + values.data(), kRows, bytes, NumericType::UInt8, bytes); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexBinaryCagra index(&resources, bytes * 8, config()); + index.add(source); + EXPECT_FALSE(index.isSearchReady()); + int distance; + idx_t label; + EXPECT_THROW( + index.search(1, values.data(), 1, &distance, &label), + faiss::FaissException); + faiss::IndexBinaryHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + std::vector exported(values.size()); + for (idx_t i = 0; i < kRows; ++i) { + cpu.reconstruct(i, exported.data() + i * bytes); + } + EXPECT_EQ(exported, values); + index.updateDataset(storage); + const auto trainedGraph = index.get_knngraph(); + index.train(source); + index.add(source); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), trainedGraph); + auto wrongRows = Dataset::viewDevice( + storage.getData(), + kRows - 1, + bytes, + NumericType::UInt8, + storage.getRowStride(), + 0); + EXPECT_THROW(index.updateDataset(wrongRows), faiss::FaissException); + EXPECT_TRUE(index.isSearchReady()); + checkBinarySearch(index, values.data()); + + faiss::VectorIOWriter writer; + faiss::write_index_binary(&cpu, &writer); + faiss::VectorIOReader reader; + reader.data = std::move(writer.data); + std::unique_ptr restored( + faiss::read_index_binary(&reader)); + auto* restoredCagra = + dynamic_cast(restored.get()); + ASSERT_NE(restoredCagra, nullptr); + const auto* restoredStorage = + dynamic_cast(restoredCagra->storage); + ASSERT_NE(restoredStorage, nullptr); + const auto cpuBytes = restoredStorage->xb; + auto importedStorage = Dataset::makeDevicePadded(&resources, source, 0); + const auto stride = importedStorage.getRowStride(); + ASSERT_EQ( + cudaMemsetAsync( + const_cast(importedStorage.getData()), + 0xa5, + kRows * stride, + resources.getResources()->getDefaultStream(0)), + cudaSuccess); + auto destination = importedStorage.view(); + EXPECT_FALSE(destination.ownsData()); + GpuIndexBinaryCagra imported(&resources, bytes * 8, config()); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &source), faiss::FaissException); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongRows), + faiss::FaissException); + auto wrongDim = Dataset::viewDevice( + storage.getData(), + kRows, + bytes - 1, + NumericType::UInt8, + storage.getRowStride(), + 0); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongDim), faiss::FaissException); + auto wrongType = Dataset::viewDevice( + storage.getData(), + kRows, + bytes, + NumericType::Int8, + storage.getRowStride(), + 0); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongType), + faiss::FaissException); + if (faiss::gpu::getNumDevices() > 1) { + auto wrongDevice = Dataset::makeDevicePadded(&resources, source, 1); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongDevice), + faiss::FaissException); + } + const void* allocation = importedStorage.getData(); + imported.copyFrom(restoredCagra, &destination); + EXPECT_EQ(importedStorage.getData(), allocation); + EXPECT_TRUE(importedStorage.ownsData()); + EXPECT_TRUE(imported.isSearchReady()); + EXPECT_EQ(restoredStorage->xb, cpuBytes); + std::vector physical(kRows * stride); + std::vector expectedPhysical(kRows * stride, 0); + for (idx_t row = 0; row < kRows; ++row) { + std::copy_n( + values.data() + row * bytes, + bytes, + expectedPhysical.data() + row * stride); + } + ASSERT_EQ( + cudaMemcpy( + physical.data(), + importedStorage.getData(), + physical.size(), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(physical, expectedPhysical); + const auto graph = imported.get_knngraph(); + ASSERT_TRUE(restoredCagra->own_fields); + delete restoredCagra->storage; + restoredCagra->storage = nullptr; + std::unique_ptr cloned( + faiss::gpu::index_binary_cpu_to_gpu(&resources, 0, restored.get())); + auto* clonedCagra = dynamic_cast(cloned.get()); + ASSERT_NE(clonedCagra, nullptr); + auto& graphOnly = *clonedCagra; + restored.reset(); + index.reset(); + EXPECT_TRUE(graphOnly.is_trained); + EXPECT_EQ(graphOnly.ntotal, kRows); + EXPECT_FALSE(graphOnly.isSearchReady()); + EXPECT_EQ(graphOnly.get_knngraph(), graph); + EXPECT_THROW( + graphOnly.search(1, values.data(), 1, &distance, &label), + faiss::FaissException); + faiss::IndexBinaryHNSWCagra missingVectors; + EXPECT_THROW(graphOnly.copyTo(&missingVectors), faiss::FaissException); + graphOnly.updateDataset(importedStorage); + EXPECT_TRUE(graphOnly.isSearchReady()); + checkBinarySearch(imported, values.data()); + imported.reset(); + checkBinarySearch(graphOnly, values.data()); + graphOnly.copyTo(&missingVectors); + for (idx_t row = 0; row < kRows; ++row) { + missingVectors.reconstruct(row, exported.data() + row * bytes); + } + EXPECT_EQ(exported, values); + EXPECT_FALSE(index.isSearchReady()); + index.train(storage); + checkBinarySearch(index, values.data()); +} + +void checkStridedDeviceGraphOnly(faiss::gpu::graph_build_algo buildAlgo) { + constexpr int bytes = 19; + constexpr int stride = 23; + faiss::gpu::DeviceScope scope(0); + StandardGpuResources resources; + auto values = binaryData(bytes); + // Device row gaps must be zero, even when the physical stride is not + // compatible with CAGRA search storage. + std::vector strided(kRows * stride, 0); + for (idx_t i = 0; i < kRows; ++i) { + std::copy_n( + values.data() + i * bytes, bytes, strided.data() + i * stride); + } + auto gpuResources = resources.getResources(); + auto stream = gpuResources->getDefaultStream(0); + auto deviceStorage = + faiss::gpu::toDeviceTemporary(gpuResources.get(), strided, stream); + auto source = Dataset::viewDevice( + deviceStorage.data(), kRows, bytes, NumericType::UInt8, stride, 0); + EXPECT_EQ(source.getLayout(), Dataset::Layout::Standard); + EXPECT_FALSE(source.ownsData()); + EXPECT_FALSE(source.isCagraCompatible()); + std::optional searchStorage; + auto options = config(); + options.build_algo = buildAlgo; + GpuIndexBinaryCagra index(&resources, bytes * 8, options); + index.train(source); + EXPECT_TRUE(index.is_trained); + EXPECT_EQ(index.ntotal, kRows); + EXPECT_FALSE(index.isSearchReady()); + int distance; + idx_t label; + EXPECT_THROW( + index.search(1, values.data(), 1, &distance, &label), + faiss::FaissException); + + faiss::IndexBinaryHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + std::vector exported(values.size()); + for (idx_t i = 0; i < kRows; ++i) { + cpu.reconstruct(i, exported.data() + i * bytes); + } + EXPECT_EQ(exported, values); + EXPECT_FALSE(index.isSearchReady()); + EXPECT_THROW(index.updateDataset(source), faiss::FaissException); + const auto graph = index.get_knngraph(); + + searchStorage.emplace(Dataset::makeDevicePadded(&resources, source, 0)); + index.updateDataset(*searchStorage); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), graph); + checkBinarySearch(index, values.data()); + std::vector after(strided.size()); + faiss::gpu::fromDevice(deviceStorage, after.data(), stream); + EXPECT_EQ(after, strided); +} + +TEST(TestGpuIndexBinaryCagra, StridedDeviceGraphOnly) { + checkStridedDeviceGraphOnly(faiss::gpu::graph_build_algo::NN_DESCENT); +} + +TEST(TestGpuIndexBinaryCagra, StridedDeviceIvfPqFallbackGraphOnly) { + checkStridedDeviceGraphOnly(faiss::gpu::graph_build_algo::IVF_PQ); +} + +TEST(TestGpuIndexBinaryCagra, DatasetAlignedStandardDeviceSearch) { + constexpr int bytes = 16; + StandardGpuResources resources; + auto values = binaryData(bytes); + auto source = Dataset::viewHost( + values.data(), kRows, bytes, NumericType::UInt8, bytes); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + auto standard = Dataset::viewDevice( + storage.getData(), kRows, bytes, NumericType::UInt8, bytes, 0); + GpuIndexBinaryCagra index(&resources, bytes * 8, config()); + index.train(standard); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_FALSE(standard.ownsData()); + checkBinarySearch(index, values.data()); +} + +} // namespace + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexCagra.cu b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexCagra.cu index 1f94b6dfb..9d3873f10 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexCagra.cu +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexCagra.cu @@ -22,23 +22,52 @@ */ #include +#include +#include #include +#include +#include #include +#include +#include #include +#include #include #include #include +#include +#include #include +#include +#include #include +#include #include +#include #include #include +#include #include +#include +#include +#include #include #include #include +// Explicit owner kept by each test for the lifetime of its borrowing index. +faiss::gpu::Dataset makeSearchDataset( + faiss::gpu::GpuResourcesProvider* resources, + faiss::idx_t n, + int dim, + const void* data, + faiss::NumericType type, + int device) { + auto source = faiss::gpu::Dataset::viewHost(data, n, dim, type, dim); + return faiss::gpu::Dataset::makeDevicePadded(resources, source, device); +} + struct Options { Options() { numTrain = 2 * faiss::gpu::randVal(2000, 5000); @@ -108,8 +137,17 @@ void queryTest(faiss::MetricType metric, double expected_recall) { config.intermediate_graph_degree = opt.intermediateGraphDegree; config.build_algo = opt.buildAlgo; + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, cpuIndex.d, metric, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim, + trainVecs.data(), + faiss::NumericType::Float32, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim); @@ -226,6 +264,8 @@ void queryTestFP16(faiss::MetricType metric, double expected_recall) { config.intermediate_graph_degree = opt.intermediateGraphDegree; config.build_algo = opt.buildAlgo; + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, cpuIndex.d, metric, config); // Create half vector @@ -235,10 +275,14 @@ void queryTestFP16(faiss::MetricType metric, double expected_recall) { trainVecs_half[i] = __float2half(trainVecs[i]); } - gpuIndex.train_ex( + trainingDataset.emplace(makeSearchDataset( + &res, opt.numTrain, - static_cast(trainVecs_half.data()), - faiss::NumericType::Float16); + opt.dim, + trainVecs_half.data(), + faiss::NumericType::Float16, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim); @@ -364,8 +408,17 @@ void copyToTest( config.intermediate_graph_degree = opt.intermediateGraphDegree; config.build_algo = opt.buildAlgo; + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim, + trainVecs.data(), + faiss::NumericType::Float32, + opt.device)); + gpuIndex.train(*trainingDataset); faiss::IndexHNSWCagra copiedCpuIndex( opt.dim, opt.graphDegree / 2, metric); @@ -527,11 +580,17 @@ void copyToTestFP16( trainVecs_half[i] = __float2half(trainVecs[i]); } + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config); - gpuIndex.train_ex( + trainingDataset.emplace(makeSearchDataset( + &res, opt.numTrain, - static_cast(trainVecs_half.data()), - faiss::NumericType::Float16); + opt.dim, + trainVecs_half.data(), + faiss::NumericType::Float16, + opt.device)); + gpuIndex.train(*trainingDataset); faiss::IndexHNSWCagra copiedCpuIndex( opt.dim, @@ -664,8 +723,19 @@ void copyFromTest(faiss::MetricType metric, double expected_recall) { res.noTempMemory(); // convert to gpu index + const auto* cpuStorage = + dynamic_cast(cpuIndex.storage); + ASSERT_NE(cpuStorage, nullptr); + auto cpuDataset = faiss::gpu::Dataset::viewHost( + cpuStorage->get_xb(), + cpuIndex.ntotal, + cpuIndex.d, + faiss::NumericType::Float32, + cpuIndex.d); + auto importedDataset = + faiss::gpu::Dataset::makeDevicePadded(&res, cpuDataset, 0); faiss::gpu::GpuIndexCagra copiedGpuIndex(&res, opt.dim, metric); - copiedGpuIndex.copyFrom(&cpuIndex); + copiedGpuIndex.copyFrom(&cpuIndex, &importedDataset); // train gpu index faiss::gpu::GpuIndexCagraConfig config; @@ -674,8 +744,17 @@ void copyFromTest(faiss::MetricType metric, double expected_recall) { config.intermediate_graph_degree = opt.intermediateGraphDegree; config.build_algo = opt.buildAlgo; + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim, + trainVecs.data(), + faiss::NumericType::Float32, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim); @@ -782,8 +861,21 @@ void copyFromTestFP16(faiss::MetricType metric, double expected_recall) { res.noTempMemory(); // convert to gpu index + const auto* cpuStorage = + dynamic_cast( + cpuIndex.storage); + ASSERT_NE(cpuStorage, nullptr); + ASSERT_EQ(cpuStorage->sq.qtype, faiss::ScalarQuantizer::QT_fp16); + auto cpuDataset = faiss::gpu::Dataset::viewHost( + cpuStorage->codes.data(), + cpuIndex.ntotal, + cpuIndex.d, + faiss::NumericType::Float16, + cpuIndex.d); + auto importedDataset = + faiss::gpu::Dataset::makeDevicePadded(&res, cpuDataset, 0); faiss::gpu::GpuIndexCagra copiedGpuIndex(&res, opt.dim, metric); - copiedGpuIndex.copyFrom_ex(&cpuIndex, faiss::NumericType::Float16); + copiedGpuIndex.copyFrom(&cpuIndex, &importedDataset); // train gpu index faiss::gpu::GpuIndexCagraConfig config; @@ -795,6 +887,8 @@ void copyFromTestFP16(faiss::MetricType metric, double expected_recall) { // faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config); // gpuIndex.train(opt.numTrain, trainVecs.data()); + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metric, config); // Create half vector @@ -804,10 +898,14 @@ void copyFromTestFP16(faiss::MetricType metric, double expected_recall) { trainVecs_half[i] = __float2half(trainVecs[i]); } - gpuIndex.train_ex( + trainingDataset.emplace(makeSearchDataset( + &res, opt.numTrain, - static_cast(trainVecs_half.data()), - faiss::NumericType::Float16); + opt.dim, + trainVecs_half.data(), + faiss::NumericType::Float16, + opt.device)); + gpuIndex.train(*trainingDataset); // query auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim); @@ -913,8 +1011,17 @@ void testIDSelectorCagra(faiss::MetricType metricType) { // Use only IVF_PQ to avoid NN_DESCENT + IP combination config.build_algo = faiss::gpu::graph_build_algo::IVF_PQ; + std::optional trainingDataset; + faiss::gpu::GpuIndexCagra gpuIndex(&res, opt.dim, metricType, config); - gpuIndex.train(opt.numTrain, trainVecs.data()); + trainingDataset.emplace(makeSearchDataset( + &res, + opt.numTrain, + opt.dim, + trainVecs.data(), + faiss::NumericType::Float32, + opt.device)); + gpuIndex.train(*trainingDataset); auto queryVecs = faiss::gpu::randVecs(opt.numQuery, opt.dim); if (metricType == faiss::METRIC_INNER_PRODUCT) { @@ -943,6 +1050,914 @@ TEST(TestGpuIndexCagra, IDSelector_IP) { testIDSelectorCagra(faiss::METRIC_INNER_PRODUCT); } +namespace { +using faiss::idx_t; +using faiss::NumericType; +using faiss::gpu::Dataset; +using faiss::gpu::GpuIndexCagra; +using faiss::gpu::StandardGpuResources; + +constexpr idx_t kRows = 512; + +faiss::gpu::GpuIndexCagraConfig config() { + faiss::gpu::GpuIndexCagraConfig out; + out.device = 0; + out.graph_degree = 16; + out.intermediate_graph_degree = 32; + out.build_algo = faiss::gpu::graph_build_algo::NN_DESCENT; + return out; +} + +std::vector floatData(int dim) { + std::mt19937 random(1234); + std::uniform_real_distribution value(-1.0f, 1.0f); + std::vector data(kRows * dim); + for (auto& x : data) { + x = value(random); + } + return data; +} + +void checkFloatSearch(faiss::Index& index, const float* queries) { + std::vector distances(8); + std::vector labels(8); + index.search(8, queries, 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + int selfHits = 0; + for (int i = 0; i < 8; ++i) { + EXPECT_GE(labels[i], 0); + EXPECT_LT(labels[i], kRows); + selfHits += labels[i] == i; + } + EXPECT_GE(selfHits, 6); +} + +TEST(TestGpuIndexCagra, PointerConstructionRejectedThroughBaseInterfaces) { + StandardGpuResources resources; + auto floats = floatData(16); + GpuIndexCagra cagra(&resources, 16, faiss::METRIC_L2, config()); + faiss::Index* base = &cagra; + EXPECT_THROW(base->train(kRows, floats.data()), faiss::FaissException); + EXPECT_THROW(base->add(kRows, floats.data()), faiss::FaissException); + EXPECT_THROW( + base->train_ex(kRows, floats.data(), NumericType::Float32), + faiss::FaissException); + EXPECT_THROW( + base->add_ex(kRows, floats.data(), NumericType::Float32), + faiss::FaissException); + EXPECT_FALSE(cagra.is_trained); + + faiss::gpu::GpuIndexFlatL2 flat(&resources, 16); + base = ♭ + EXPECT_NO_THROW(base->add(kRows, floats.data())); + EXPECT_EQ(flat.ntotal, kRows); +} + +TEST(TestGpuIndexCagra, DatasetIDMap) { + constexpr int dim = 20; + StandardGpuResources resources; + auto values = floatData(dim); + auto source = Dataset::viewHost( + values.data(), kRows, dim, NumericType::Float32, dim); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexCagra cagra(&resources, dim, faiss::METRIC_L2, config()); + faiss::IndexIDMap2 index(&cagra); + index.train_dataset(storage); + EXPECT_TRUE(index.is_trained); + const auto graph = cagra.get_knngraph(); + faiss::Index* base = &index; + base->train_dataset(source); + EXPECT_TRUE(cagra.isSearchReady()); + EXPECT_EQ(cagra.get_knngraph(), graph); + + std::vector ids(kRows); + for (idx_t i = 0; i < kRows; ++i) { + ids[i] = 1000 + 2 * i; + } + index.add_with_ids(storage, ids.data()); + EXPECT_EQ(index.ntotal, kRows); + EXPECT_EQ(index.id_map, ids); + EXPECT_NO_THROW(index.check_consistency()); + + std::vector distances(8); + std::vector labels(8); + index.search(8, values.data(), 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + for (auto label : labels) { + EXPECT_GE(label, 1000); + EXPECT_LT(label, 1000 + 2 * kRows); + EXPECT_EQ((label - 1000) % 2, 0); + } + index.reset(); + EXPECT_FALSE(index.is_trained); + EXPECT_EQ(index.ntotal, 0); +} + +TEST(TestGpuIndexCagra, BruteForceRequiresMultipleDevices) { + StandardGpuResources resources; + auto values = floatData(20); + auto source = Dataset::viewHost( + values.data(), kRows, 20, NumericType::Float32, 20); + auto options = config(); + options.build_algo = faiss::gpu::graph_build_algo::BRUTE_FORCE; + GpuIndexCagra index(&resources, 20, faiss::METRIC_L2, options); + try { + index.train(source); + FAIL() << "Single-device BRUTE_FORCE must be rejected"; + } catch (const faiss::FaissException& error) { + EXPECT_NE( + std::string(error.what()).find("BRUTE_FORCE"), + std::string::npos); + } + EXPECT_FALSE(index.is_trained); +} + +TEST(TestGpuIndexCagra, CompatibleStandardDeviceBorrowsWithoutOwning) { + // Twenty Float32 columns satisfy 16-byte rows without dim % 16 == 0. + constexpr int dim = 20; + StandardGpuResources resources; + auto values = floatData(dim); + auto source = Dataset::viewHost( + values.data(), kRows, dim, NumericType::Float32, dim); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexCagra index(&resources, dim, faiss::METRIC_L2, config()); + { + auto standard = Dataset::viewDevice( + storage.getData(), kRows, dim, NumericType::Float32, dim, 0); + EXPECT_EQ(standard.getLayout(), Dataset::Layout::Standard); + EXPECT_EQ(standard.getData(), storage.getData()); + EXPECT_FALSE(standard.ownsData()); + EXPECT_TRUE(standard.isCagraCompatible()); + index.train(standard); + } + EXPECT_TRUE(index.isSearchReady()); + auto movedStorage = std::move(storage); + checkFloatSearch(index, values.data()); + const auto graph = index.get_knngraph(); + index.train(source); + index.add(source); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), graph); + checkFloatSearch(index, values.data()); + index.reset(); + EXPECT_FALSE(index.isSearchReady()); + EXPECT_FALSE(index.is_trained); + EXPECT_EQ(index.ntotal, 0); + index.add(movedStorage); + checkFloatSearch(index, values.data()); +} + +TEST(TestGpuIndexCagra, GraphOnlyHostExportAndExplicitAttachment) { + constexpr int dim = 19; + constexpr int stride = 23; + StandardGpuResources resources; + auto values = floatData(dim); + std::vector strided(kRows * stride, 1234.0f); + for (idx_t i = 0; i < kRows; ++i) { + std::copy_n(values.data() + i * dim, dim, strided.data() + i * stride); + } + auto source = Dataset::viewHost( + strided.data(), kRows, dim, NumericType::Float32, stride); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexCagra index(&resources, dim, faiss::METRIC_L2, config()); + index.train(source); + EXPECT_TRUE(index.is_trained); + EXPECT_FALSE(index.isSearchReady()); + float distance; + idx_t label; + EXPECT_THROW( + index.search(1, values.data(), 1, &distance, &label), + faiss::FaissException); + + faiss::IndexHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + std::vector exported(values.size()); + cpu.reconstruct_n(0, kRows, exported.data()); + EXPECT_EQ(exported, values); + EXPECT_EQ(strided[stride - 1], 1234.0f); + faiss::RangeSearchResult range(8); + cpu.range_search(8, values.data(), 1.0e9f, &range); + for (int i = 0; i < 8; ++i) { + EXPECT_GT(range.lims[i + 1], range.lims[i]); + } + + index.updateDataset(storage); + EXPECT_TRUE(index.isSearchReady()); + const auto graph = index.get_knngraph(); + auto wrongRows = Dataset::viewDevice( + storage.getData(), + kRows - 1, + dim, + NumericType::Float32, + storage.getRowStride(), + 0); + EXPECT_THROW(index.updateDataset(wrongRows), faiss::FaissException); + auto wrongType = Dataset::viewDevice( + storage.getData(), + kRows, + dim, + NumericType::UInt8, + storage.getRowStride() * sizeof(float), + 0); + EXPECT_THROW(index.updateDataset(wrongType), faiss::FaissException); + auto wrongDim = Dataset::viewDevice( + storage.getData(), + kRows, + dim - 1, + NumericType::Float32, + storage.getRowStride(), + 0); + EXPECT_THROW(index.updateDataset(wrongDim), faiss::FaissException); + EXPECT_THROW(index.updateDataset(source), faiss::FaissException); + if (faiss::gpu::getNumDevices() > 1) { + auto wrongDevice = Dataset::makeDevicePadded(&resources, source, 1); + EXPECT_THROW(index.updateDataset(wrongDevice), faiss::FaissException); + } + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), graph); + checkFloatSearch(index, values.data()); + + // CPU serialization and re-import retain their existing ownership behavior. + faiss::VectorIOWriter writer; + faiss::write_index(&cpu, &writer); + faiss::VectorIOReader reader; + reader.data = std::move(writer.data); + std::unique_ptr restored(faiss::read_index(&reader)); + auto* restoredCagra = dynamic_cast(restored.get()); + ASSERT_NE(restoredCagra, nullptr); + auto importedStorage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexCagra imported(&resources, dim, faiss::METRIC_L2, config()); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &source), faiss::FaissException); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongRows), + faiss::FaissException); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongType), + faiss::FaissException); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongDim), faiss::FaissException); + if (faiss::gpu::getNumDevices() > 1) { + auto wrongDevice = Dataset::makeDevicePadded(&resources, source, 1); + EXPECT_THROW( + imported.copyFrom(restoredCagra, &wrongDevice), + faiss::FaissException); + } + imported.copyFrom(restoredCagra, &importedStorage); + EXPECT_TRUE(imported.isSearchReady()); + ASSERT_TRUE(restoredCagra->own_fields); + delete restoredCagra->storage; + restoredCagra->storage = nullptr; + std::unique_ptr cloned( + faiss::gpu::index_cpu_to_gpu(&resources, 0, restored.get())); + auto* clonedCagra = dynamic_cast(cloned.get()); + ASSERT_NE(clonedCagra, nullptr); + auto& graphOnly = *clonedCagra; + restored.reset(); + index.reset(); + EXPECT_TRUE(graphOnly.is_trained); + EXPECT_EQ(graphOnly.ntotal, kRows); + EXPECT_FALSE(graphOnly.isSearchReady()); + EXPECT_EQ(graphOnly.get_knngraph(), graph); + EXPECT_THROW( + graphOnly.search(1, values.data(), 1, &distance, &label), + faiss::FaissException); + faiss::IndexHNSWCagra missingVectors; + EXPECT_THROW(graphOnly.copyTo(&missingVectors), faiss::FaissException); + graphOnly.updateDataset(importedStorage); + EXPECT_TRUE(graphOnly.isSearchReady()); + checkFloatSearch(imported, values.data()); + imported.reset(); + checkFloatSearch(graphOnly, values.data()); + graphOnly.copyTo(&missingVectors); + missingVectors.reconstruct_n(0, kRows, exported.data()); + EXPECT_EQ(exported, values); + checkFloatSearch(cpu, values.data()); +} + +TEST(TestGpuIndexCagra, DatasetAsyncRebindResetAndDestruction) { + constexpr int dim = 19; + constexpr int nq = 64; + auto values = floatData(dim); + faiss::gpu::DeviceScope scope(0); + cudaStream_t alternateStream; + ASSERT_EQ( + cudaStreamCreateWithFlags(&alternateStream, cudaStreamNonBlocking), + cudaSuccess); + const auto destroyStream = [](cudaStream_t stream) { + EXPECT_EQ(cudaStreamDestroy(stream), cudaSuccess); + }; + // cuVS descriptor caches retain their allocation stream in the resource + // handle, so the external stream must also outlive those resources. + std::unique_ptr< + std::remove_pointer_t, + decltype(destroyStream)> + streamOwner(alternateStream, destroyStream); + StandardGpuResources resources; + auto source = Dataset::viewHost( + values.data(), kRows, dim, NumericType::Float32, dim); + std::optional first( + Dataset::makeDevicePadded(&resources, source, 0)); + std::optional second( + Dataset::makeDevicePadded(&resources, source, 0)); + auto index = std::make_unique( + &resources, dim, faiss::METRIC_L2, config()); + index->train(*first); + + auto gpuResources = resources.getResources(); + auto originalStream = gpuResources->getDefaultStream(0); + auto queries = faiss::gpu::toDeviceTemporary( + gpuResources.get(), values, originalStream); + auto alloc = faiss::gpu::makeTempAlloc( + faiss::gpu::AllocType::Other, originalStream); + faiss::gpu::DeviceTensor distances( + gpuResources.get(), alloc, {nq, 1}); + faiss::gpu::DeviceTensor labels( + gpuResources.get(), alloc, {nq, 1}); + resources.setDefaultStream(0, alternateStream); + auto checkResults = [&](cudaStream_t stream) { + std::vector actualDistances(nq); + std::vector actualLabels(nq); + faiss::gpu::fromDevice(distances, actualDistances.data(), stream); + faiss::gpu::fromDevice(labels, actualLabels.data(), stream); + int selfHits = 0; + for (int i = 0; i < nq; ++i) { + EXPECT_GE(actualLabels[i], 0); + EXPECT_LT(actualLabels[i], kRows); + if (actualLabels[i] == i) { + ++selfHits; + EXPECT_NEAR(actualDistances[i], 0, 1e-5); + } + } + EXPECT_GE(selfHits, nq * 3 / 4); + }; + + // These searches keep both inputs and outputs on device and queue work. + // Rebind/reset must finish use of the old allocation before its release. + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index->updateDataset(*second); + first.reset(); + checkResults(alternateStream); + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index->reset(); + second.reset(); + checkResults(alternateStream); + + // Build on B, then search on A and destroy without an explicit reset. + // Keep the caller-owned data alive to isolate graph-storage destruction. + std::optional third( + Dataset::makeDevicePadded(&resources, source, 0)); + index->train(*third); + resources.revertDefaultStream(0); + index->search(nq, queries.data(), 1, distances.data(), labels.data()); + index.reset(); + checkResults(originalStream); + third.reset(); +} + +TEST(TestGpuIndexCagra, MultiGpuDatasetBuildAndCpuExport) { + int deviceCount = 0; + ASSERT_EQ(cudaGetDeviceCount(&deviceCount), cudaSuccess); + if (deviceCount < 2) { + GTEST_SKIP() << "Requires at least two GPUs"; + } + constexpr int dim = 32; + constexpr idx_t rows = 4096; + StandardGpuResources resources; + std::mt19937 random(1234); + std::uniform_real_distribution value(-1.0f, 1.0f); + std::vector values(rows * dim); + for (auto& x : values) { + x = value(random); + } + auto source = Dataset::viewHost( + values.data(), rows, dim, NumericType::Float32, dim); + auto options = config(); + options.devices = {0, 1}; + // Exact cluster graphs bound the work while exercising the full + // multi-GPU graph-build and CPU-export path. + options.build_algo = faiss::gpu::graph_build_algo::BRUTE_FORCE; + options.graph_degree = 32; + options.intermediate_graph_degree = 64; + options.all_neighbors_params.n_clusters = 4; + options.all_neighbors_params.overlap_factor = 2; + GpuIndexCagra index(&resources, dim, faiss::METRIC_L2, options); + index.train(source); + ASSERT_TRUE(index.is_trained); + EXPECT_EQ(index.ntotal, rows); + EXPECT_FALSE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph().size(), rows * options.graph_degree); + EXPECT_THROW(index.updateDataset(source), faiss::FaissException); + faiss::IndexHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + EXPECT_EQ(cpu.ntotal, rows); + std::vector exported(values.size()); + cpu.reconstruct_n(0, rows, exported.data()); + EXPECT_EQ(exported, values); + index.reset(); + float distance; + idx_t label; + cpu.search(1, values.data(), 1, &distance, &label); + EXPECT_EQ(label, 0); + EXPECT_FLOAT_EQ(distance, 0.0f); +} + +template +void checkStridedDeviceGraphOnly(NumericType type) { + constexpr int dim = 19; + constexpr int stride = 23; + faiss::gpu::DeviceScope scope(0); + StandardGpuResources resources; + std::vector values(kRows * dim); + if constexpr (std::is_same_v) { + values = floatData(dim); + } else { + std::mt19937 random(9012); + for (auto& x : values) { + x = static_cast(static_cast(random() % 201) - 100); + } + } + // Device row gaps must be zero, even when the physical stride is not + // compatible with CAGRA search storage. + std::vector strided(kRows * stride, static_cast(0)); + for (idx_t i = 0; i < kRows; ++i) { + std::copy_n(values.data() + i * dim, dim, strided.data() + i * stride); + } + auto gpuResources = resources.getResources(); + auto stream = gpuResources->getDefaultStream(0); + auto deviceStorage = + faiss::gpu::toDeviceTemporary(gpuResources.get(), strided, stream); + auto source = Dataset::viewDevice( + deviceStorage.data(), kRows, dim, type, stride, 0); + EXPECT_EQ(source.getLayout(), Dataset::Layout::Standard); + EXPECT_FALSE(source.ownsData()); + EXPECT_FALSE(source.isCagraCompatible()); + std::optional searchStorage; + GpuIndexCagra index(&resources, dim, faiss::METRIC_L2, config()); + index.train(source); + EXPECT_TRUE(index.is_trained); + EXPECT_EQ(index.ntotal, kRows); + EXPECT_FALSE(index.isSearchReady()); + float distance; + idx_t label; + EXPECT_THROW( + index.search_ex(1, values.data(), type, 1, &distance, &label), + faiss::FaissException); + + faiss::IndexHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + EXPECT_EQ(cpu.get_numeric_type(), type); + std::vector exported(values.size()); + cpu.reconstruct_n(0, kRows, exported.data()); + std::vector expected(values.size()); + std::transform(values.begin(), values.end(), expected.begin(), [](T x) { + return static_cast(x); + }); + EXPECT_EQ(exported, expected); + EXPECT_FALSE(index.isSearchReady()); + EXPECT_THROW(index.updateDataset(source), faiss::FaissException); + const auto graph = index.get_knngraph(); + + searchStorage.emplace(Dataset::makeDevicePadded(&resources, source, 0)); + index.updateDataset(*searchStorage); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), graph); + std::vector distances(8); + std::vector labels(8); + index.search_ex(8, values.data(), type, 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + int selfHits = 0; + for (int i = 0; i < 8; ++i) { + EXPECT_GE(labels[i], 0); + EXPECT_LT(labels[i], kRows); + if (labels[i] == i) { + ++selfHits; + EXPECT_NEAR(distances[i], 0.0f, 1.0f); + } + } + EXPECT_GE(selfHits, 6); + std::vector after(strided.size()); + faiss::gpu::fromDevice(deviceStorage, after.data(), stream); + EXPECT_EQ( + std::memcmp( + after.data(), strided.data(), strided.size() * sizeof(T)), + 0); +} + +TEST(TestGpuIndexCagra, StridedDeviceFloat32GraphOnly) { + checkStridedDeviceGraphOnly(NumericType::Float32); +} + +TEST(TestGpuIndexCagra, StridedDeviceFloat16GraphOnly) { + checkStridedDeviceGraphOnly(NumericType::Float16); +} + +TEST(TestGpuIndexCagra, StridedDeviceInt8GraphOnly) { + checkStridedDeviceGraphOnly(NumericType::Int8); +} + +template +void checkTypedExport(NumericType type) { + constexpr int dim = 19; + StandardGpuResources resources; + std::mt19937 random(9012); + std::vector values(kRows * dim); + for (auto& x : values) { + x = static_cast(static_cast(random() % 201) - 100); + } + auto original = values; + auto source = Dataset::viewHost(values.data(), kRows, dim, type, dim); + auto storage = Dataset::makeDevicePadded(&resources, source, 0); + GpuIndexCagra index(&resources, dim, faiss::METRIC_L2, config()); + index.train(storage); + faiss::IndexHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + EXPECT_EQ(cpu.get_numeric_type(), type); + std::vector afterExport(values.size()); + storage.copyToHost(afterExport.data()); + EXPECT_EQ( + std::memcmp( + afterExport.data(), + original.data(), + original.size() * sizeof(T)), + 0); + EXPECT_EQ( + std::memcmp( + values.data(), + original.data(), + original.size() * sizeof(T)), + 0); + + const auto* cpuStorage = + dynamic_cast(cpu.storage); + ASSERT_NE(cpuStorage, nullptr); + const std::vector cpuCodes( + cpuStorage->codes.begin(), cpuStorage->codes.end()); + auto importedStorage = Dataset::makeDevicePadded(&resources, source, 0); + const auto stride = importedStorage.getRowStride(); + // Poison logical values and padding: copyFrom must fill this allocation. + ASSERT_EQ( + cudaMemsetAsync( + const_cast(importedStorage.getData()), + 0xa5, + kRows * stride * sizeof(T), + resources.getResources()->getDefaultStream(0)), + cudaSuccess); + const void* allocation = importedStorage.getData(); + auto destination = importedStorage.view(); + EXPECT_FALSE(destination.ownsData()); + GpuIndexCagra imported(&resources, dim, faiss::METRIC_L2, config()); + imported.copyFrom(&cpu, &destination); + EXPECT_EQ(importedStorage.getData(), allocation); + EXPECT_TRUE(importedStorage.ownsData()); + EXPECT_TRUE(imported.isSearchReady()); + EXPECT_EQ(imported.get_numeric_type(), type); + EXPECT_EQ(imported.get_knngraph(), index.get_knngraph()); + EXPECT_EQ( + std::vector( + cpuStorage->codes.begin(), cpuStorage->codes.end()), + cpuCodes); + std::vector physical(kRows * stride); + std::vector expectedPhysical(kRows * stride, T(0)); + for (idx_t row = 0; row < kRows; ++row) { + std::copy_n( + original.data() + row * dim, + dim, + expectedPhysical.data() + row * stride); + } + ASSERT_EQ( + cudaMemcpy( + physical.data(), + importedStorage.getData(), + physical.size() * sizeof(T), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ( + std::memcmp( + physical.data(), + expectedPhysical.data(), + physical.size() * sizeof(T)), + 0); + // Exercise the unchanged typed query interface for both the original and + // re-imported graph, including Int8 whose Python build path is unavailable. + for (auto* searched : {&index, &imported}) { + std::vector distances(8); + std::vector labels(8); + searched->search_ex( + 8, original.data(), type, 1, distances.data(), labels.data()); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + int selfHits = 0; + for (int i = 0; i < 8; ++i) { + EXPECT_GE(labels[i], 0); + EXPECT_LT(labels[i], kRows); + if (labels[i] == i) { + ++selfHits; + EXPECT_NEAR(distances[i], 0.0f, 1.0f); + } + } + EXPECT_GE(selfHits, 6); + } +} + +// Exact 0/1 vectors need no quantizer training: the endpoints of [0, 1] +// have codes 0 and 2^bits - 1. Keep every allocation outside the Faiss Dataset. +template +auto makeBBQQuantizer( + raft::resources const& handle, + const std::vector& values, + faiss::gpu::BBQCodeLayout layout, + faiss::MetricType metric) { + namespace bbq = cuvs::preprocessing::quantize::bbq; + constexpr int dim = 64; + const auto nativeLayout = static_cast(layout); + bbq::quantizer owner( + handle, + kRows, + dim, + nativeLayout, + metric == faiss::METRIC_L2 + ? cuvs::distance::DistanceType::L2Expanded + : cuvs::distance::DistanceType::InnerProduct); + const int bits = bbq::get_bit_width(nativeLayout); + const int maximum = (1 << bits) - 1; + const int bytes = owner.encoded_row_length(); + std::vector codes(kRows * bytes, 0); + std::vector zeros(kRows, 0), ones(kRows, 1), norms(kRows, 0); + std::vector deltas(kRows, 1.0f / maximum); + std::vector sums(kRows, 0); + std::vector centroid(dim, T(0)); + for (idx_t row = 0; row < kRows; ++row) { + for (int col = 0; col < dim; ++col) { + if (static_cast(values[row * dim + col]) == 0) { + continue; + } + ++norms[row]; + sums[row] += maximum; + auto* encoded = codes.data() + row * bytes; + if (layout == faiss::gpu::BBQCodeLayout::Packed4Bit) { + encoded[col / 2] |= maximum << (4 * (1 - col % 2)); + } else if (bits >= 7) { + encoded[col] = maximum; + } else { + for (int plane = 0; plane < bits; ++plane) { + encoded[plane * (dim / 8) + col / 8] |= 1 << (7 - col % 8); + } + } + } + } + auto upload = [](auto& destination, const auto& source) { + EXPECT_EQ( + cudaMemcpy( + destination.data_handle(), + source.data(), + source.size() * sizeof(source[0]), + cudaMemcpyHostToDevice), + cudaSuccess); + }; + upload(owner.codes, codes); + upload(owner.lower_intervals, zeros); + upload(owner.upper_intervals, ones); + upload(owner.additional_corrections, + metric == faiss::METRIC_L2 ? norms : zeros); + upload(owner.quantized_component_sums, sums); + upload(owner.centroid, centroid); + upload(owner.dequant_delta, deltas); + upload(owner.dequant_sum_delta, norms); + upload(owner.row_norm, norms); + return owner; +} + +template +faiss::gpu::BBQQuantizer describeBBQ( + const cuvs::preprocessing::quantize::bbq::quantizer& owner, + faiss::MetricType metric) { + faiss::gpu::BBQQuantizer result; + result.codes = owner.codes.data_handle(); + result.lowerIntervals = owner.lower_intervals.data_handle(); + result.upperIntervals = owner.upper_intervals.data_handle(); + result.additionalCorrections = owner.additional_corrections.data_handle(); + result.quantizedComponentSums = + owner.quantized_component_sums.data_handle(); + result.centroid = owner.centroid.data_handle(); + result.dequantDelta = owner.dequant_delta.data_handle(); + result.dequantSumDelta = owner.dequant_sum_delta.data_handle(); + result.rowNorm = owner.row_norm.data_handle(); + result.codeLayout = static_cast(owner.layout); + result.metric = metric; + return result; +} + +template +void checkBBQDataset( + NumericType type, + faiss::gpu::BBQCodeLayout layout, + faiss::MetricType metric, + std::optional second = std::nullopt) { + SCOPED_TRACE( + ::testing::Message() << "type=" << int(type) << " layout=" + << int(layout) << " metric=" << int(metric)); + constexpr int dim = 64, queries = 32, k = 10; + const bool checkLifecycle = type == NumericType::Float32 && + layout == faiss::gpu::BBQCodeLayout::Packed1Bit && + metric == faiss::METRIC_L2 && !second; + faiss::gpu::DeviceScope scope(0); + StandardGpuResources resources; + auto& handle = resources.getResources()->getRaftHandle(0); + std::mt19937 random(42); + std::vector values(kRows * dim); + for (auto& value : values) { + value = T(random() % 2); + } + auto owner = makeBBQQuantizer(handle, values, layout, metric); + auto primary = describeBBQ(owner, metric); + std::optional secondOwner; + faiss::gpu::BBQQuantizer secondary; + if (second) { + secondOwner.emplace(makeBBQQuantizer(handle, values, *second, metric)); + secondary = describeBBQ(*secondOwner, metric); + } + if (checkLifecycle) { + auto unaligned = primary; + ++unaligned.codes; + EXPECT_THROW( + Dataset::viewDeviceBBQ(unaligned, kRows, dim, type, 0), + faiss::FaissException); + } + auto source = Dataset::viewDeviceBBQ( + primary, kRows, dim, type, 0, second ? &secondary : nullptr); + auto borrowed = source.view(); + auto moved = std::move(borrowed); + EXPECT_EQ(moved.getLayout(), Dataset::Layout::BBQ); + EXPECT_EQ(moved.getNumRows(), kRows); + EXPECT_EQ(moved.getDim(), dim); + EXPECT_EQ(moved.getNumericType(), type); + EXPECT_EQ(moved.getDevice(), 0); + EXPECT_TRUE(moved.isDevice()); + EXPECT_FALSE(moved.ownsData()); + EXPECT_FALSE(moved.isCagraCompatible()); + if (checkLifecycle) { + EXPECT_THROW(moved.getData(), faiss::FaissException); + EXPECT_THROW(moved.getRowStride(), faiss::FaissException); + EXPECT_THROW(moved.copyToHost(values.data()), faiss::FaissException); + EXPECT_THROW( + Dataset::makeDevicePadded(&resources, moved, 0), + faiss::FaissException); + } + + auto cfg = config(); + cfg.graph_degree = 32; + cfg.intermediate_graph_degree = 64; + // The original dense allocation must outlive both indexes that borrow it. + auto dense = Dataset::viewHost(values.data(), kRows, dim, type, dim); + auto storage = Dataset::makeDevicePadded(&resources, dense, 0); + GpuIndexCagra index(&resources, dim, metric, cfg); + index.train(moved); + EXPECT_TRUE(index.is_trained); + EXPECT_EQ(index.ntotal, kRows); + EXPECT_FALSE(index.isSearchReady()); + const auto graph = index.get_knngraph(); + ASSERT_EQ(graph.size(), kRows * cfg.graph_degree); + for (auto label : graph) { + ASSERT_GE(label, 0); + ASSERT_LT(label, kRows); + } + std::vector distances(queries * k); + std::vector labels(queries * k); + if (checkLifecycle) { + EXPECT_THROW( + index.search_ex( + queries, + values.data(), + type, + k, + distances.data(), + labels.data()), + faiss::FaissException); + faiss::IndexHNSWCagra cpu; + const auto originalDim = cpu.d; + const auto* originalStorage = cpu.storage; + EXPECT_THROW(index.copyTo(&cpu), faiss::FaissException); + EXPECT_EQ(cpu.d, originalDim); + EXPECT_EQ(cpu.ntotal, 0); + EXPECT_EQ(cpu.storage, originalStorage); + EXPECT_THROW(index.updateDataset(moved), faiss::FaissException); + } + + index.updateDataset(storage); + EXPECT_TRUE(index.isSearchReady()); + EXPECT_EQ(index.get_knngraph(), graph); + faiss::gpu::SearchParametersCagra params; + params.itopk_size = 128; + auto checkSearch = [&](GpuIndexCagra& searched) { + searched.search_ex( + queries, + values.data(), + type, + k, + distances.data(), + labels.data(), + ¶ms); + ASSERT_EQ(cudaDeviceSynchronize(), cudaSuccess); + int matches = 0; + for (int q = 0; q < queries; ++q) { + std::vector exact(kRows); + for (idx_t row = 0; row < kRows; ++row) { + float score = 0; + for (int col = 0; col < dim; ++col) { + const float a = static_cast(values[q * dim + col]); + const float b = static_cast(values[row * dim + col]); + score += metric == faiss::METRIC_L2 ? (a - b) * (a - b) + : a * b; + } + exact[row] = score; + } + auto ranked = exact; + std::sort(ranked.begin(), ranked.end()); + const float threshold = metric == faiss::METRIC_L2 + ? ranked[k - 1] + : ranked[kRows - k]; + for (int j = 0; j < k; ++j) { + const auto label = labels[q * k + j]; + ASSERT_GE(label, 0); + ASSERT_LT(label, kRows); + EXPECT_NEAR(distances[q * k + j], exact[label], 1e-4); + matches += metric == faiss::METRIC_L2 + ? exact[label] <= threshold + : exact[label] >= threshold; + EXPECT_EQ( + std::count( + labels.begin() + q * k, + labels.begin() + (q + 1) * k, + label), + 1); + } + } + // Equal distances are common for exact 0/1 data; accept any top-k tie. + EXPECT_GE(double(matches) / (queries * k), 0.98); + }; + checkSearch(index); + if (checkLifecycle) { + faiss::IndexHNSWCagra cpu; + cpu.base_level_only = true; + index.copyTo(&cpu); + GpuIndexCagra imported(&resources, dim, metric, cfg); + imported.copyFrom(&cpu); + EXPECT_FALSE(imported.isSearchReady()); + imported.updateDataset(storage); + checkSearch(imported); + cfg.build_algo = faiss::gpu::graph_build_algo::IVF_PQ; + GpuIndexCagra unsupported(&resources, dim, metric, cfg); + EXPECT_THROW(unsupported.train(moved), faiss::FaissException); + GpuIndexCagra mismatched( + &resources, + dim, + metric == faiss::METRIC_L2 ? faiss::METRIC_INNER_PRODUCT + : faiss::METRIC_L2, + config()); + EXPECT_THROW(mismatched.train(moved), faiss::FaissException); + } +} + +TEST(TestGpuIndexCagra, BBQLayoutsBuildGraphAndAttachDenseDataset) { + using Layout = faiss::gpu::BBQCodeLayout; + for (auto metric : {faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}) { + for (auto layout : + {Layout::Packed1Bit, + Layout::Transposed2Bit, + Layout::Packed4Bit, + Layout::Packed7Bit, + Layout::Packed8Bit}) { + checkBBQDataset(NumericType::Float32, layout, metric); + } + checkBBQDataset( + NumericType::Float32, + Layout::Transposed4Bit, + metric, + Layout::Packed1Bit); + checkBBQDataset( + NumericType::Float16, + Layout::Transposed4Bit, + metric, + Layout::Transposed2Bit); + checkBBQDataset( + NumericType::Int8, + Layout::Packed4Bit, + metric, + Layout::Packed1Bit); + } +} + +TEST(TestGpuIndexCagra, TypedCopyFromFillsDestinationAndPreservesCpuStorage) { + checkTypedExport(NumericType::Float32); + checkTypedExport(NumericType::Float16); + checkTypedExport(NumericType::Int8); +} +} // namespace + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp index 3b2ca1c19..71f28481e 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexFlat.cpp @@ -5,14 +5,19 @@ * LICENSE file in the root directory of this source tree. */ +#include #include #include +#include #include #include #include #include #include +#include #include +#include +#include #include #include #include @@ -807,6 +812,216 @@ TEST(TestCuvsGpuIndexFlat, IDSelector_IP) { } #endif +// Packs float vectors as IEEE binary16, the Float16 input of search_ex +std::vector toFp16(const std::vector& v) { + std::vector out(v.size()); + std::transform(v.begin(), v.end(), out.begin(), [](float f) { + return faiss::encode_fp16(f); + }); + return out; +} + +std::vector fromFp16(const std::vector& v) { + std::vector out(v.size()); + std::transform(v.begin(), v.end(), out.begin(), [](uint16_t h) { + return faiss::decode_fp16(h); + }); + return out; +} + +// A copy of host data on a GPU device +struct DeviceCopy { + DeviceCopy(int device, const void* src, size_t bytes) { + faiss::gpu::DeviceScope scope(device); + CUDA_VERIFY(cudaMalloc(&data, bytes)); + CUDA_VERIFY(cudaMemcpy(data, src, bytes, cudaMemcpyHostToDevice)); + } + + DeviceCopy(const DeviceCopy&) = delete; + DeviceCopy& operator=(const DeviceCopy&) = delete; + + ~DeviceCopy() { + CUDA_VERIFY(cudaFree(data)); + } + + void* data = nullptr; +}; + +// search_ex on Float16 queries must return exactly what search returns on the +// float32 queries rounded to fp16, as the rounded values are what the index +// computes with, whether the queries are on the host (paged or not) or on the +// device +void testSearchExFloat16(faiss::gpu::GpuIndex& index) { + int numQuery = faiss::gpu::randVal(1, 512); + int k = std::min(faiss::gpu::randVal(1, 50), int(index.ntotal)); + + auto queries = faiss::gpu::randVecs(numQuery, index.d); + auto queries16 = toFp16(queries); + auto roundedQueries = fromFp16(queries16); + + std::vector refDistances(numQuery * k); + std::vector refLabels(numQuery * k); + index.search( + numQuery, + roundedQueries.data(), + k, + refDistances.data(), + refLabels.data()); + + auto expectSearchExMatches = [&](const void* x, const std::string& where) { + std::vector distances(numQuery * k, 0); + std::vector labels(numQuery * k, -1); + index.search_ex( + numQuery, + x, + faiss::NumericType::Float16, + k, + distances.data(), + labels.data()); + + EXPECT_EQ(labels, refLabels) << where; + EXPECT_EQ(distances, refDistances) << where; + }; + + expectSearchExMatches(queries16.data(), "host queries"); + + auto minPagingSize = index.getMinPagingSize(); + index.setMinPagingSize(0); + expectSearchExMatches(queries16.data(), "paged host queries"); + index.setMinPagingSize(minPagingSize); + + DeviceCopy queries16Device( + index.getDevice(), + queries16.data(), + queries16.size() * sizeof(uint16_t)); + expectSearchExMatches(queries16Device.data, "device queries"); +} + +// Covers both float32 storage (queries widened on the device) and float16 +// storage (queries searched natively) +template +void testFlatSearchExFloat16() { + faiss::gpu::StandardGpuResources res; + res.noTempMemory(); + + int dim = faiss::gpu::randVal(50, 400); + int numVecs = faiss::gpu::randVal(1000, 5000); + auto vecs = faiss::gpu::randVecs(numVecs, dim); + + for (bool useFloat16 : {false, true}) { + faiss::gpu::GpuIndexFlatConfig config; + config.device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1); + config.useFloat16 = useFloat16; + + GpuIndexFlatT gpuIndex(&res, dim, config); + gpuIndex.add(numVecs, vecs.data()); + + SCOPED_TRACE(useFloat16 ? "useFloat16" : "float32 storage"); + testSearchExFloat16(gpuIndex); + } +} + +TEST(TestGpuIndexFlat, SearchExFloat16_L2) { + testFlatSearchExFloat16(); +} + +TEST(TestGpuIndexFlat, SearchExFloat16_IP) { + testFlatSearchExFloat16(); +} + +// Indexes without a native fp16 search widen the queries on the device +TEST(TestGpuIndexFlat, SearchExFloat16_IVFFlatDefault) { + faiss::gpu::StandardGpuResources res; + res.noTempMemory(); + + int dim = 64; + int numVecs = 5000; + auto vecs = faiss::gpu::randVecs(numVecs, dim); + + faiss::gpu::GpuIndexIVFFlatConfig config; + config.device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1); + + int numLists = 32; + faiss::gpu::GpuIndexIVFFlat gpuIndex( + &res, dim, numLists, faiss::METRIC_L2, config); + gpuIndex.nprobe = 4; + gpuIndex.train(numVecs, vecs.data()); + gpuIndex.add(numVecs, vecs.data()); + + testSearchExFloat16(gpuIndex); +} + +// k-means on fp16 data with a GPU assignment index must match k-means on the +// float32 rounding of that data with the same kind of index +TEST(TestGpuIndexFlat, ClusteringTrainExFloat16) { + faiss::gpu::StandardGpuResources res; + res.noTempMemory(); + + int dim = 32; + int numCentroids = 20; + // Fits in a single decode block, so that both runs search the same batches + int numVecs = 2000; + auto vecs = faiss::gpu::randVecs(numVecs, dim); + auto vecs16 = toFp16(vecs); + auto roundedVecs = fromFp16(vecs16); + + faiss::ClusteringParameters cp; + cp.niter = 10; + + for (bool useFloat16 : {false, true}) { + faiss::gpu::GpuIndexFlatConfig config; + config.device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1); + config.useFloat16 = useFloat16; + + faiss::gpu::GpuIndexFlatL2 refIndex(&res, dim, config); + faiss::Clustering refClustering(dim, numCentroids, cp); + refClustering.train(numVecs, roundedVecs.data(), refIndex); + + faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, dim, config); + faiss::Clustering clustering(dim, numCentroids, cp); + clustering.train_ex( + numVecs, vecs16.data(), faiss::NumericType::Float16, gpuIndex); + + ASSERT_EQ(clustering.centroids.size(), refClustering.centroids.size()); + for (size_t i = 0; i < clustering.centroids.size(); ++i) { + EXPECT_NEAR( + clustering.centroids[i], refClustering.centroids[i], 1e-5f) + << "useFloat16 " << useFloat16 << " element " << i; + } + } +} + +// add and reconstruct_n copy the whole vector set between host and device in +// one copy. On ROCm, a pageable copy of more than 64 KiB goes through 16 MiB +// pinned chunks: 17 vectors take one chunk, and 10,500 vectors take two full +// chunks and a partial one. Each size has its own resources, so the second +// size reuses the pinned chunks after the streams of the first are destroyed. +TEST(TestGpuIndexFlat, LargeHostCopyRoundTrip) { + int dim = 1000; + int device = faiss::gpu::randVal(0, faiss::gpu::getNumDevices() - 1); + + for (int numVecs : {17, 10500}) { + faiss::gpu::StandardGpuResources res; + res.noTempMemory(); + + faiss::gpu::GpuIndexFlatConfig config; + config.device = device; + + faiss::gpu::GpuIndexFlatL2 gpuIndex(&res, dim, config); + std::vector vecs = faiss::gpu::randVecs(numVecs, dim); + gpuIndex.add(numVecs, vecs.data()); + + std::vector out(vecs.size()); + gpuIndex.reconstruct_n(0, numVecs, out.data()); + + // Report the first difference; printing millions of values is useless + size_t firstDiff = + std::mismatch(out.begin(), out.end(), vecs.begin()).first - + out.begin(); + EXPECT_EQ(firstDiff, out.size()) << "numVecs " << numVecs; + } +} + int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); diff --git a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp index 34b0218f7..64eeed88c 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp +++ b/thirdparty/faiss/faiss/gpu/test/TestGpuIndexIVFFlat.cpp @@ -31,8 +31,11 @@ #include #include #include +#include #include +#include #include +#include #include // FIXME: figure out a better way to test fp16 @@ -472,6 +475,101 @@ TEST(TestGpuIndexIVFFlat, Float32_32_CopyFrom) { #endif } +#if defined USE_NVIDIA_CUVS +class TestCuvsGpuIndexIVFFlatCopyFrom + : public testing::TestWithParam {}; + +TEST_P(TestCuvsGpuIndexIVFFlatCopyFrom, SearchLargeK) { + constexpr int numVecs = 16384; + constexpr int dim = 128; + constexpr int numCentroids = 32; + const auto metric = GetParam(); + std::mt19937 rng(42); + std::uniform_int_distribution random(-30, 30); + std::vector vecs(numVecs * dim); + for (auto& value : vecs) { + value = random(rng); + } + + faiss::IndexFlat quantizer(dim, metric); + faiss::IndexIVFFlat cpuIndex(&quantizer, dim, numCentroids, metric); + cpuIndex.cp.niter = 5; + cpuIndex.train(numVecs, vecs.data()); + cpuIndex.add(numVecs, vecs.data()); + cpuIndex.nprobe = numCentroids; + + faiss::gpu::StandardGpuResources res; + faiss::gpu::GpuIndexIVFFlatConfig config; + config.use_cuvs = true; + config.indicesOptions = faiss::gpu::INDICES_64_BIT; + faiss::gpu::GpuIndexIVFFlat gpuIndex( + &res, dim, numCentroids, metric, config); + gpuIndex.copyFrom(&cpuIndex); + + faiss::IndexFlat exact(dim, metric); + exact.add(numVecs, vecs.data()); + // k > 256 takes the cuVS path that sizes its workspace from the + // accumulated list sizes. Cloning must populate those sizes first. + for (int k : {256, 257, 500, 3500}) { + SCOPED_TRACE(testing::Message() << "k=" << k); + for (int numQueries : {1, 4}) { + SCOPED_TRACE(testing::Message() << "numQueries=" << numQueries); + std::vector expected(numQueries * k); + std::vector distances(numQueries * k); + std::vector expectedIds(numQueries * k); + std::vector ids(numQueries * k); + exact.search( + numQueries, + vecs.data(), + k, + expected.data(), + expectedIds.data()); + for (int repeat = 0; repeat < 2; ++repeat) { + gpuIndex.search( + numQueries, + vecs.data(), + k, + distances.data(), + ids.data()); + for (int q = 0; q < numQueries; ++q) { + std::unordered_set uniqueIds; + for (int i = q * k; i < (q + 1) * k; ++i) { + ASSERT_GE(ids[i], 0); + ASSERT_LT(ids[i], numVecs); + EXPECT_TRUE(uniqueIds.insert(ids[i]).second); + float score = 0; + for (int j = 0; j < dim; ++j) { + float a = vecs[q * dim + j]; + float b = vecs[ids[i] * dim + j]; + score += metric == faiss::METRIC_L2 + ? (a - b) * (a - b) + : a * b; + } + EXPECT_FLOAT_EQ(score, distances[i]); + } + // cuVS need not return sorted results, and tied scores + // may select different IDs at the top-k boundary. + std::vector actual( + distances.begin() + q * k, + distances.begin() + (q + 1) * k); + auto begin = expected.begin() + q * k; + std::sort(begin, begin + k); + std::sort(actual.begin(), actual.end()); + for (int i = 0; i < k; ++i) { + EXPECT_FLOAT_EQ(begin[i], actual[i]); + } + } + } + } + } +} + +INSTANTIATE_TEST_SUITE_P( + Cuvs, + TestCuvsGpuIndexIVFFlatCopyFrom, + testing::Values(faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT)); +#endif + TEST(TestGpuIndexIVFFlat, Float32_negative) { Options opt; diff --git a/thirdparty/faiss/faiss/gpu/test/TestUtils.cpp b/thirdparty/faiss/faiss/gpu/test/TestUtils.cpp index 22ddb73a3..bc45d52cb 100644 --- a/thirdparty/faiss/faiss/gpu/test/TestUtils.cpp +++ b/thirdparty/faiss/faiss/gpu/test/TestUtils.cpp @@ -9,7 +9,7 @@ #include #include #include -#include +#include #include #include #include @@ -100,10 +100,11 @@ std::mt19937 rng(1); std::uniform_int_distribution<> distrib; void newTestSeed() { - struct timespec t; - clock_gettime(CLOCK_REALTIME, &t); - - setTestSeed(t.tv_nsec); + auto ns = std::chrono::high_resolution_clock::now().time_since_epoch(); + setTestSeed( + static_cast( + std::chrono::duration_cast(ns) + .count())); } void setTestSeed(long seed) { diff --git a/thirdparty/faiss/faiss/gpu/test/bench_approaches.py b/thirdparty/faiss/faiss/gpu/test/bench_approaches.py index 5070f9f69..bfba3a9e6 100644 --- a/thirdparty/faiss/faiss/gpu/test/bench_approaches.py +++ b/thirdparty/faiss/faiss/gpu/test/bench_approaches.py @@ -168,7 +168,8 @@ def build_cagra_hnsw( index = faiss.GpuIndexCagra(res_list[0], d, faiss.METRIC_L2, config) t0 = time.time() - index.train(xb) + dataset = faiss.Dataset.viewHost(xb) + index.train(dataset) timings["build"] = time.time() - t0 t0 = time.time() diff --git a/thirdparty/faiss/faiss/gpu/test/test_binary_cagra.py b/thirdparty/faiss/faiss/gpu/test/test_binary_cagra.py index 58f5314ce..7a0052dbe 100644 --- a/thirdparty/faiss/faiss/gpu/test/test_binary_cagra.py +++ b/thirdparty/faiss/faiss/gpu/test/test_binary_cagra.py @@ -17,133 +17,227 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -# -import numpy as np +"""Binary CAGRA Dataset construction, ownership, and CPU interchange.""" +import gc import unittest +import weakref +import numpy as np import faiss - from faiss.contrib import evaluation -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestInterop(unittest.TestCase): - - def do_interop(self): - d = 64 * 8 - k = 12 - - res = faiss.StandardGpuResources() - - index = faiss.GpuIndexBinaryCagra(res, d) - xb = np.random.randint( - low=0, high=256, size=(1000000, d // 8), dtype=np.uint8 - ) - index.train(xb) - queries = np.random.randint( - low=0, high=256, size=(1000, d // 8), dtype=np.uint8 - ) - Dnew, Inew = index.search(queries, k) - - cpu_index = faiss.index_binary_gpu_to_cpu(index) - Dref, Iref = cpu_index.search(queries, k) - - evaluation.check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, k) - - deserialized_index = faiss.deserialize_index_binary( - faiss.serialize_index_binary(cpu_index) - ) - - gpu_index = faiss.index_binary_cpu_to_gpu(res, 0, deserialized_index) - Dnew2, Inew2 = gpu_index.search(queries, k) - - evaluation.check_ref_knn_with_draws(Dnew2, Inew2, Dnew, Inew, k) - - def test_interop(self): - self.do_interop() - - -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestComputeGT(unittest.TestCase): +@unittest.skipIf("CUVS" not in faiss.get_compile_options(), "requires cuVS") +class TestBinaryCagraDataset(unittest.TestCase): + def setUp(self): + self.res = faiss.StandardGpuResources() + # Match the C++ Dataset fixture's seed, size, and byte generation. + self.xb = np.random.RandomState(4321).randint( + 0, 2**32, (512, 19), dtype=np.uint32 + ).astype("uint8") + self.host = faiss.Dataset.viewHost(self.xb) - def do_compute_GT(self, build_algo=None): - d = 64 * 8 - k = 12 - flat_index = faiss.IndexBinaryFlat(d) - xb = np.random.randint( - low=0, high=256, size=(1000000, d // 8), dtype=np.uint8 + def make_index(self, build_algo=None): + config = faiss.GpuIndexCagraConfig() + config.graph_degree = 16 + config.intermediate_graph_degree = 32 + config.build_algo = ( + faiss.graph_build_algo_NN_DESCENT + if build_algo is None else build_algo ) - flat_index.add(xb) - queries = np.random.randint( - low=0, high=256, size=(1000, d // 8), dtype=np.uint8 + return faiss.GpuIndexBinaryCagra(self.res, self.xb.shape[1] * 8, config) + + def check_search(self, index): + distances, labels = index.search(self.xb[:8], 1) + self.assertTrue(np.all((labels >= 0) & (labels < len(self.xb)))) + self_hits = labels[:, 0] == np.arange(8) + # Preserve the C++ Dataset regression's accepted self-hit threshold. + self.assertGreaterEqual(np.count_nonzero(self_hits), 6) + np.testing.assert_array_equal(distances[self_hits], 0) + # Check actual Hamming distances, including any non-self result. + expected = np.unpackbits( + self.xb[labels[:, 0]] ^ self.xb[:8], axis=1 + ).sum(axis=1) + np.testing.assert_array_equal(distances[:, 0], expected) + + def test_device_build_and_search(self): + for algorithm in ( + faiss.graph_build_algo_NN_DESCENT, + faiss.graph_build_algo_ITERATIVE_SEARCH, + ): + with self.subTest(algorithm=algorithm): + storage = faiss.Dataset.makeDevicePadded(self.res, self.host, 0) + storage_ref = weakref.ref(storage) + index = self.make_index(algorithm) + index.train(storage) + del storage + self.assertIsNotNone(storage_ref()) + self.assertTrue(index.is_trained) + self.assertEqual(index.ntotal, len(self.xb)) + self.assertTrue(index.isSearchReady()) + self.check_search(index) + index.reset() + self.assertIsNone(storage_ref()) + + def test_host_graph_attachment_and_reset(self): + index = self.make_index() + source = self.host.view() + source_ref = weakref.ref(source) + index.train(source) + del source + self.assertIsNotNone(source_ref()) + self.assertTrue(index.is_trained) + self.assertFalse(index.isSearchReady()) + with self.assertRaisesRegex(RuntimeError, "updateDataset"): + index.search(self.xb[:8], 1) + cpu = faiss.IndexBinaryHNSWCagra() + cpu.base_level_only = True + index.copyTo(cpu) + np.testing.assert_array_equal(cpu.reconstruct_n(), self.xb) + + storage = faiss.Dataset.makeDevicePadded(self.res, self.host, 0) + storage_ref = weakref.ref(storage) + index.updateDataset(storage.view()) + del storage + self.assertIsNone(source_ref()) + self.assertIsNotNone(storage_ref()) + self.assertTrue(index.isSearchReady()) + with self.assertRaises(RuntimeError): + index.updateDataset(self.host) + index.train(self.host) + index.add(self.host) + self.assertIsNotNone(storage_ref()) + self.check_search(index) + index.reset() + self.assertIsNone(storage_ref()) + self.assertFalse(index.is_trained) + self.assertFalse(index.isSearchReady()) + self.assertEqual(index.ntotal, 0) + storage = faiss.Dataset.makeDevicePadded(self.res, self.host, 0) + storage_ref = weakref.ref(storage) + index.add(storage) + del storage + self.assertIsNotNone(storage_ref()) + self.check_search(index) + index.reset() + self.assertIsNone(storage_ref()) + + def test_idmap_dataset(self): + ids = np.arange(len(self.xb), dtype="int64") * 7 + 100 + for map_class in (faiss.IndexBinaryIDMap, faiss.IndexBinaryIDMap2): + with self.subTest(map_class=map_class.__name__): + storage = faiss.Dataset.makeDevicePadded(self.res, self.host, 0) + owner_ref = weakref.ref(storage) + cagra = self.make_index() + index = map_class(cagra) + index.add_with_ids(storage, ids) + index.train(self.host) # Preserve the device Dataset owner. + if isinstance(index, faiss.IndexBinaryIDMap2): + index.check_consistency() + expected_d, positions = cagra.search(self.xb[:8], 4) + actual_d, labels = index.search(self.xb[:8], 4) + np.testing.assert_array_equal(labels, ids[positions]) + np.testing.assert_array_equal(actual_d, expected_d) + del storage + self.assertIsNotNone(owner_ref()) + index.reset() + self.assertIsNone(owner_ref()) + self.assertFalse(index.is_trained) + self.assertFalse(cagra.is_trained) + self.assertEqual(index.ntotal, 0) + + def test_cpu_serialization_and_optional_destination_import(self): + index = self.make_index() + index.train(self.host) + cpu = faiss.IndexBinaryHNSWCagra() + cpu.base_level_only = True + index.copyTo(cpu) + self.addCleanup(faiss.omp_set_num_threads, faiss.omp_get_max_threads()) + faiss.omp_set_num_threads(2) + expected_d, expected_i = cpu.search(self.xb[:8], 4) + self.assertTrue(np.all(expected_i >= 0)) + loaded = faiss.deserialize_index_binary(faiss.serialize_index_binary(cpu)) + actual_d, actual_i = loaded.search(self.xb[:8], 4) + evaluation.check_ref_knn_with_draws( + expected_d, expected_i, actual_d, actual_i ) - Dref, Iref = flat_index.search(queries, k) - - res = faiss.StandardGpuResources() - - # Configure the index with specified build algorithm - config = faiss.GpuIndexCagraConfig() - if build_algo is not None: - config.build_algo = build_algo - if build_algo == faiss.graph_build_algo_NN_DESCENT: - config.nn_descent_niter = 20 - - index = faiss.GpuIndexBinaryCagra(res, d, config) - index.train(xb) - Dnew, Inew = index.search(queries, k) - - evaluation.check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, k) - - def test_compute_GT_nn_descent(self): - self.do_compute_GT(faiss.graph_build_algo_NN_DESCENT) - - def test_compute_GT_iterative_search(self): - self.do_compute_GT(faiss.graph_build_algo_ITERATIVE_SEARCH) - - -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestIndexBinaryIDMap(unittest.TestCase): - """Test IndexBinaryIDMap functionality with GpuIndexBinaryCagra""" - - @unittest.skip( - "GPU binary-CAGRA search via IndexBinaryIDMap deadlocks at " - "d=1024 on CUDA 12.9; root cause TBD." - ) - def test_add_with_ids(self): - d = 128 * 8 - k = 10 - n = 100000 - - res = faiss.StandardGpuResources() - - # Create GpuIndexBinaryCagra with IDMap - index_gpu = faiss.GpuIndexBinaryCagra(res, d) - index_idmap = faiss.IndexBinaryIDMap(index_gpu) - - xb = np.random.randint( - low=0, high=256, size=(n, d // 8), dtype=np.uint8 + graph_only = faiss.index_binary_cpu_to_gpu(self.res, 0, loaded) + self.assertTrue(graph_only.thisown) + self.assertTrue(graph_only.is_trained) + self.assertEqual(graph_only.ntotal, len(self.xb)) + self.assertFalse(graph_only.isSearchReady()) + + # The owning allocation exposes all 32 physical bytes to verify that + # copyFrom fills logical columns and zeroes every padding byte. + sentinel = np.full((512, 32), 0xa5, dtype="uint8") + sentinel_host = faiss.Dataset.viewHost(sentinel) + allocation = faiss.Dataset.makeDevicePadded(self.res, sentinel_host, 0) + destination = faiss.Dataset.viewDevicePadded( + allocation.getData(), 512, 19, faiss.UInt8, 32, 0 ) - ids = np.arange(1000000, 1000000 + n).astype(np.int64) - - index_idmap.add_with_ids(xb, ids) - - nq = 1000 - xq = np.random.randint( - low=0, high=256, size=(nq, d // 8), dtype=np.uint8 + imported = self.make_index() + address = int(allocation.getData()) + imported.copyFrom(loaded, destination) + self.assertEqual(int(allocation.getData()), address) + self.assertTrue(allocation.ownsData()) + self.assertFalse(destination.ownsData()) + self.assertTrue(imported.isSearchReady()) + np.testing.assert_array_equal(loaded.reconstruct_n(), self.xb) + expected_physical = np.zeros_like(sentinel) + expected_physical[:, :19] = self.xb + np.testing.assert_array_equal(allocation.copyToHost(), expected_physical) + + owner = faiss.Dataset.makeDevicePadded(self.res, self.host, 0) + owner_ref = weakref.ref(owner) + graph_only.copyFrom(loaded, owner) + del owner + self.assertIsNotNone(owner_ref()) + with self.assertRaises(RuntimeError): + graph_only.copyFrom(loaded, self.host) + self.assertIsNotNone(owner_ref()) + self.check_search(graph_only) + graph_only.copyFrom(loaded) + self.assertIsNone(owner_ref()) + self.assertFalse(graph_only.isSearchReady()) + + source_ref = weakref.ref(loaded) + descriptor_ref = weakref.ref(destination) + index.reset() + del loaded, cpu, destination + gc.collect() + self.assertIsNone(source_ref()) + self.assertIsNotNone(descriptor_ref()) + self.check_search(imported) # Raw pointer storage remains explicitly retained. + with self.assertRaisesRegex(RuntimeError, "updateDataset"): + graph_only.search(self.xb[:8], 1) + exported = faiss.IndexBinaryHNSWCagra() + with self.assertRaisesRegex(RuntimeError, "Dataset"): + graph_only.copyTo(exported) + attached = faiss.Dataset.viewDevice( + allocation.getData(), 512, 19, faiss.UInt8, 32, 0 ) - D, I = index_idmap.search(xq, k) - - self.assertTrue(np.all(I >= 1000000)) - self.assertTrue(np.all(I < 1000000 + n)) - - D_exact, I_exact = index_idmap.search(xb[:10], 1) - expected_ids = ids[:10].reshape(-1, 1) - np.testing.assert_array_equal(I_exact, expected_ids) - np.testing.assert_array_equal(D_exact, np.zeros((10, 1))) + graph_only.updateDataset(attached) + self.check_search(graph_only) + exported.base_level_only = True + graph_only.copyTo(exported) + np.testing.assert_array_equal(exported.reconstruct_n(), self.xb) + graph_only.reset() + imported.reset() + self.assertIsNone(descriptor_ref()) + + def test_pointer_and_base_build_require_dataset(self): + index = self.make_index() + for method in (index.train, index.add): + with self.assertRaisesRegex(TypeError, "Dataset"): + method(self.xb) + for method in (faiss.IndexBinary.train, faiss.IndexBinary.add): + with self.assertRaisesRegex(RuntimeError, "Dataset"): + method(index, self.xb) + self.assertEqual(index.ntotal, 0) + + def test_idmap_does_not_bypass_dataset_requirement(self): + cagra = self.make_index() + index = faiss.IndexBinaryIDMap(cagra) + with self.assertRaisesRegex(RuntimeError, "Dataset"): + index.add_with_ids(self.xb, np.arange(len(self.xb), dtype="int64")) diff --git a/thirdparty/faiss/faiss/gpu/test/test_cagra.py b/thirdparty/faiss/faiss/gpu/test/test_cagra.py index e18a5b6a6..f01d36068 100644 --- a/thirdparty/faiss/faiss/gpu/test/test_cagra.py +++ b/thirdparty/faiss/faiss/gpu/test/test_cagra.py @@ -3,246 +3,380 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -import unittest +"""CAGRA Dataset workflows and Python ownership lifetimes.""" -import faiss +import gc +import unittest +import weakref -from faiss.contrib import datasets, evaluation import numpy as np +import faiss -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestComputeGT(unittest.TestCase): - - def do_compute_GT(self, metric, numeric_type): - d = 64 - k = 12 - - if numeric_type == faiss.Int8: - data_base_nt = np.random.randint( - -128, 128, size=(10000, d), dtype=np.int8 - ) - data_query_nt = np.random.randint( - -128, 128, size=(100, d), dtype=np.int8 - ) - data_base = data_base_nt.astype(np.float32) - data_query = data_query_nt.astype(np.float32) - else: - ds = datasets.SyntheticDataset(d, 0, 10000, 100) - data_base = ds.get_database() # fp32 - data_query = ds.get_queries() # fp32 - # Normalize for inner product to avoid duplicate neighbors - if metric == faiss.METRIC_INNER_PRODUCT: - # Normalize database vectors - data_base = data_base / np.linalg.norm( - data_base, axis=1, keepdims=True - ) - # Normalize query vectors - data_query = data_query / np.linalg.norm( - data_query, axis=1, keepdims=True - ) - if numeric_type == faiss.Float16: - data_base_nt = data_base.astype(np.float16) - data_query_nt = data_query.astype(np.float16) - elif numeric_type == faiss.Float32: - data_base_nt = data_base - data_query_nt = data_query - - Dref, Iref = faiss.knn(data_query, data_base, k, metric) - +@unittest.skipIf("CUVS" not in faiss.get_compile_options(), "requires cuVS") +class TestDataset(unittest.TestCase): + def test_host_views_preserve_types_strides_and_borrowing(self): + for dtype, numeric_type in ((np.float32, faiss.Float32), + (np.float16, faiss.Float16), + (np.int8, faiss.Int8), + (np.uint8, faiss.UInt8)): + with self.subTest(dtype=dtype): + allocation = np.arange(27, dtype=dtype).reshape(3, 9) + values = allocation[:, :5] + values_ref = weakref.ref(values) + source = faiss.Dataset.viewHost(values) + self.assertEqual(int(source.getData()), values.ctypes.data) + self.assertEqual(source.getNumRows(), 3) + self.assertEqual(source.getDim(), 5) + self.assertEqual(source.getRowStride(), 9) + self.assertEqual(source.getNumericType(), numeric_type) + self.assertFalse(source.ownsData()) + self.assertFalse(source.isDevice()) + packed = source.copyToHost() + self.assertEqual(packed.dtype, values.dtype) + self.assertTrue(packed.flags.c_contiguous) + np.testing.assert_array_equal(packed, values) + + raw = faiss.Dataset.viewHost_c( + faiss.cast_integer_to_void_ptr(values.ctypes.data), + 3, 5, numeric_type, 9) + np.testing.assert_array_equal(raw.copyToHost(), values) + del raw # Raw pointer views require an explicitly retained allocation. + source_ref = weakref.ref(source) + descriptor = source.view() + del source, values + gc.collect() + self.assertIsNotNone(source_ref()) + self.assertIsNotNone(values_ref()) + np.testing.assert_array_equal(descriptor.copyToHost(), packed) + del descriptor + gc.collect() + self.assertIsNone(source_ref()) + self.assertIsNone(values_ref()) + + def test_host_view_rejects_implicit_conversion_or_column_strides(self): + for values in (np.zeros((3, 5), dtype="float64"), + np.zeros(15, dtype="float32"), + np.zeros((3, 10), dtype="float32")[:, ::2], + np.zeros((3, 5), dtype="float32")[::-1]): + with self.subTest(shape=values.shape, strides=values.strides): + with self.assertRaises((TypeError, ValueError)): + faiss.Dataset.viewHost(values) + + def test_padded_owners_and_device_views(self): res = faiss.StandardGpuResources() - - # attempt to set custom IVF-PQ params - cagraIndexConfig = faiss.GpuIndexCagraConfig() - cagraIndexConfig.graph_degree = 32 - cagraIndexConfig.intermediate_graph_degree = 64 - cagraIndexIVFPQConfig = faiss.IVFPQBuildCagraConfig() - cagraIndexIVFPQConfig.kmeans_trainset_fraction = 0.5 - cagraIndexConfig.ivf_pq_params = cagraIndexIVFPQConfig - cagraIndexConfig.build_algo = faiss.graph_build_algo_IVF_PQ - - index = faiss.GpuIndexCagra(res, d, metric, cagraIndexConfig) - index.train(data_base_nt, numeric_type=numeric_type) - Dnew, Inew = index.search(data_query_nt, k, numeric_type=numeric_type) - - evaluation.check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, k) - - def test_compute_GT_L2(self): - self.do_compute_GT(faiss.METRIC_L2, faiss.Float32) - - def test_compute_GT_IP(self): - self.do_compute_GT(faiss.METRIC_INNER_PRODUCT, faiss.Float32) - - def test_compute_GT_L2_FP16(self): - self.do_compute_GT(faiss.METRIC_L2, faiss.Float16) - - @unittest.skip( - "GPU CAGRA inner-product + FP16 search deadlocks on CUDA 12.9; " - "root cause TBD." - ) - def test_compute_GT_IP_FP16(self): - self.do_compute_GT(faiss.METRIC_INNER_PRODUCT, faiss.Float16) - - def test_compute_GT_L2_Int8(self): - self.do_compute_GT(faiss.METRIC_L2, faiss.Int8) - - def test_compute_GT_IP_Int8(self): - self.do_compute_GT(faiss.METRIC_INNER_PRODUCT, faiss.Int8) - - -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestInterop(unittest.TestCase): - - def do_interop(self, metric, numeric_type): - d = 64 - k = 12 - if numeric_type == faiss.Int8: - data_base_nt = np.random.randint( - -128, 128, size=(10000, d), dtype=np.int8 - ) - data_query_nt = np.random.randint( - -128, 128, size=(100, d), dtype=np.int8 - ) - data_base = data_base_nt.astype(np.float32) - data_query = data_query_nt.astype(np.float32) + for dtype, numeric_type in ((np.float32, faiss.Float32), + (np.float16, faiss.Float16), + (np.int8, faiss.Int8), + (np.uint8, faiss.UInt8)): + with self.subTest(dtype=dtype): + allocation = np.arange(27, dtype=dtype).reshape(3, 9) + values = allocation[:, :5] + source = faiss.Dataset.viewHost(values) + owner = faiss.Dataset.makeDevicePadded(res, source, 0) + self.assertTrue(owner.ownsData()) + self.assertTrue(owner.isDevice()) + self.assertTrue(owner.isCagraCompatible()) + self.assertEqual(owner.getDevice(), 0) + packed = owner.copyToHost() + self.assertEqual(packed.dtype, values.dtype) + np.testing.assert_array_equal(packed, values) + del source + stride = owner.getRowStride() + standard = faiss.Dataset.viewDevice( + owner.getData(), 3, 5, numeric_type, stride, 0) + padded = faiss.Dataset.viewDevicePadded( + faiss.cast_integer_to_void_ptr(int(owner.getData())), + 3, 5, numeric_type, stride, 0) + for descriptor in (standard, padded): + self.assertFalse(descriptor.ownsData()) + self.assertEqual(int(descriptor.getData()), int(owner.getData())) + np.testing.assert_array_equal(descriptor.copyToHost(), values) + physical = faiss.Dataset.viewDevice( + owner.getData(), 3, stride, numeric_type, stride, 0) + np.testing.assert_array_equal(physical.copyToHost()[:, 5:], 0) + del standard, padded, descriptor, physical + descriptor = owner.view() + owner_ref = weakref.ref(owner) + del owner + gc.collect() + self.assertIsNotNone(owner_ref()) + self.assertFalse(descriptor.ownsData()) + np.testing.assert_array_equal(descriptor.copyToHost(), values) + del descriptor + gc.collect() + self.assertIsNone(owner_ref()) + + +@unittest.skipIf("CUVS" not in faiss.get_compile_options(), "requires cuVS") +class TestCagraDataset(unittest.TestCase): + @staticmethod + def config(): + config = faiss.GpuIndexCagraConfig() + config.graph_degree = 32 + config.intermediate_graph_degree = 64 + config.build_algo = faiss.graph_build_algo_NN_DESCENT + return config + + def check_search(self, index, database, queries, numeric_type): + k = 8 + params = faiss.SearchParametersCagra() + params.itopk_size = 128 + distances, labels = index.search( + queries, k, params=params, numeric_type=numeric_type) + self.assertTrue(np.all((labels >= 0) & (labels < len(database)))) + float_database = database.astype("float32") + float_queries = queries.astype("float32") + _, reference = faiss.knn(float_queries, float_database, k) + recall = np.mean([len(set(found) & set(expected)) / k + for found, expected in zip(labels, reference)]) + self.assertGreaterEqual(recall, 0.98) + expected_distances = np.sum( + (float_queries[:, None, :] - float_database[labels]) ** 2, axis=2) + np.testing.assert_allclose( + distances, expected_distances, + rtol=2e-3 if numeric_type == faiss.Float16 else 6e-5, atol=1e-5) + + def check_workflow(self, dtype, numeric_type): + random = np.random.RandomState(1732) + rows, dim = 1024, 19 + if dtype == np.int8: + values = random.randint(-50, 51, (rows, dim)).astype(dtype) + queries = random.randint(-50, 51, (32, dim)).astype(dtype) else: - ds = datasets.SyntheticDataset(d, 0, 10000, 100) - data_base = ds.get_database() # fp32 - data_query = ds.get_queries() # fp32 - if numeric_type == faiss.Float16: - data_base_nt = data_base.astype(np.float16) - data_query_nt = data_query.astype(np.float16) - elif numeric_type == faiss.Float32: - data_base_nt = data_base - data_query_nt = data_query - + values = random.normal(size=(rows, dim)).astype(dtype) + queries = random.normal(size=(32, dim)).astype(dtype) + # Host gaps may contain arbitrary values; keep the whole allocation alive. + allocation = np.full((rows, dim + 4), 37, dtype=dtype) + allocation[:, :dim] = values + source = faiss.Dataset.viewHost(allocation[:, :dim]) res = faiss.StandardGpuResources() - - index = faiss.GpuIndexCagra(res, d, metric) - index.train(data_base_nt, numeric_type=numeric_type) - Dnew, Inew = index.search(data_query_nt, k, numeric_type=numeric_type) - - cpu_index = faiss.index_gpu_to_cpu(index) - # cpu index always search in fp32 - Dref, Iref = cpu_index.search(data_query, k) - - evaluation.check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, k) - - deserialized_index = faiss.deserialize_index( - faiss.serialize_index(cpu_index) - ) - - gpu_index = faiss.index_cpu_to_gpu(res, 0, deserialized_index) - Dnew2, Inew2 = gpu_index.search( - data_query_nt, k, numeric_type=numeric_type - ) - - evaluation.check_ref_knn_with_draws(Dnew2, Inew2, Dnew, Inew, k) - - def test_interop_L2(self): - self.do_interop(faiss.METRIC_L2, faiss.Float32) - - def test_interop_IP(self): - self.do_interop(faiss.METRIC_INNER_PRODUCT, faiss.Float32) - - def test_interop_L2_FP16(self): - self.do_interop(faiss.METRIC_L2, faiss.Float16) - - def test_interop_IP_FP16(self): - self.do_interop(faiss.METRIC_INNER_PRODUCT, faiss.Float16) - - def test_interop_L2_Int8(self): - self.do_interop(faiss.METRIC_L2, faiss.Int8) - - def test_interop_IP_Int8(self): - self.do_interop(faiss.METRIC_INNER_PRODUCT, faiss.Int8) - - def test_base_level_only_range_search(self): - d = 32 - nb = 1000 - nq = 10 - ds = datasets.SyntheticDataset(d, 0, nb, nq) - data_base = ds.get_database() - data_query = ds.get_queries() - + storage = faiss.Dataset.makeDevicePadded(res, source, 0) + index = faiss.GpuIndexCagra(res, dim, faiss.METRIC_L2, self.config()) + descriptor_ref = weakref.ref(source) + index.train(source) + del source + gc.collect() + self.assertIsNotNone(descriptor_ref()) + self.assertTrue(index.is_trained) + self.assertEqual(index.ntotal, rows) + self.assertFalse(index.isSearchReady()) + with self.assertRaisesRegex(RuntimeError, "Dataset"): + index.search(queries, 8, numeric_type=numeric_type) + graph = faiss.vector_to_array(index.get_knngraph()) + descriptor = storage.view() + index.updateDataset(descriptor) + self.assertIsNone(descriptor_ref()) + descriptor_ref = weakref.ref(descriptor) + del descriptor + self.assertIsNotNone(descriptor_ref()) + self.assertTrue(index.isSearchReady()) + np.testing.assert_array_equal(faiss.vector_to_array(index.get_knngraph()), graph) + self.check_search(index, values, queries, numeric_type) + np.testing.assert_array_equal(storage.copyToHost(), values) + np.testing.assert_array_equal(allocation[:, dim:], 37) + index.train(storage) + index.add(storage) + self.assertIsNotNone(descriptor_ref()) + index.reset() + self.assertIsNone(descriptor_ref()) + self.assertFalse(index.isSearchReady()) + self.assertFalse(index.is_trained) + self.assertEqual(index.ntotal, 0) + index.add(storage) + self.check_search(index, values, queries, numeric_type) + + cpu = faiss.IndexHNSWCagra() + cpu.base_level_only = True + index.copyTo(cpu) + loaded = faiss.deserialize_index(faiss.serialize_index(cpu)) + np.testing.assert_array_equal(loaded.reconstruct_n(0, rows).astype(dtype), values) + cpu_storage = faiss.downcast_index(loaded.storage) + cpu_codes = faiss.vector_to_array(cpu_storage.codes) + + # Allocate all physical columns with a sentinel, including future padding. + stride = storage.getRowStride() + sentinel = np.full((rows, stride), 37, dtype=dtype) + sentinel_view = faiss.Dataset.viewHost(sentinel) + output_owner = faiss.Dataset.makeDevicePadded(res, sentinel_view, 0) + output = faiss.Dataset.viewDevicePadded( + output_owner.getData(), rows, dim, numeric_type, stride, 0) + self.assertFalse(output.ownsData()) + imported = faiss.GpuIndexCagra(res, dim, faiss.METRIC_L2, self.config()) + imported.copyFrom(loaded, output) + output_ref = weakref.ref(output) + del output + self.assertIsNotNone(output_ref()) + self.assertTrue(imported.isSearchReady()) + filled = output_owner.copyToHost() + self.assertEqual(filled.dtype, values.dtype) + np.testing.assert_array_equal(filled[:, :dim], values) + np.testing.assert_array_equal(filled[:, dim:], 0) + np.testing.assert_array_equal(faiss.vector_to_array(cpu_storage.codes), cpu_codes) + with self.assertRaises(RuntimeError): + imported.copyFrom(loaded, faiss.Dataset.viewHost(values)) + self.assertIsNotNone(output_ref()) + self.check_search(imported, values, queries, numeric_type) + imported.copyFrom(loaded) + self.assertIsNone(output_ref()) + self.assertFalse(imported.isSearchReady()) + imported.updateDataset(storage) + + graph_only = faiss.index_cpu_to_gpu(res, 0, loaded) + del cpu_storage, loaded, cpu + gc.collect() + self.assertFalse(graph_only.isSearchReady()) + self.assertTrue(graph_only.is_trained) + self.assertEqual(graph_only.ntotal, rows) + np.testing.assert_array_equal( + faiss.vector_to_array(graph_only.get_knngraph()), + faiss.vector_to_array(imported.get_knngraph())) + with self.assertRaisesRegex(RuntimeError, "Dataset"): + graph_only.search(queries, 8, numeric_type=numeric_type) + empty_cpu = faiss.IndexHNSWCagra() + with self.assertRaisesRegex(RuntimeError, "Dataset"): + graph_only.copyTo(empty_cpu) + graph_only.updateDataset(storage) + storage_ref = weakref.ref(storage) + del storage + gc.collect() + self.assertIsNotNone(storage_ref()) + self.check_search(index, values, queries, numeric_type) + self.check_search(imported, values, queries, numeric_type) + del index + imported.reset() + self.assertIsNotNone(storage_ref()) + self.check_search(graph_only, values, queries, numeric_type) + del graph_only + gc.collect() + self.assertIsNone(storage_ref()) + + def test_float32_workflow(self): + self.check_workflow(np.float32, faiss.Float32) + + def test_float16_workflow(self): + self.check_workflow(np.float16, faiss.Float16) + + def test_int8_workflow(self): + self.check_workflow(np.int8, faiss.Int8) + + def test_bbq_graph_then_dense_search(self): + rows, dim = 1024, 64 + values = np.random.RandomState(1732).randint( + 0, 2, (rows, dim)).astype("float32") + sums = values.sum(axis=1) + # These 0/1 vectors have exact one-bit codes and zero-centroid corrections. + arrays = [np.packbits(values.astype("uint8"), axis=1, bitorder="big"), + np.zeros(rows, dtype="float32"), + np.ones(rows, dtype="float32"), sums, + sums.astype("int32").view("uint8")] res = faiss.StandardGpuResources() - index = faiss.GpuIndexCagra(res, d, faiss.METRIC_L2) - index.train(data_base, numeric_type=faiss.Float32) - - cpu_index = faiss.index_gpu_to_cpu(index) - cpu_index.base_level_only = True - cpu_index.num_base_level_search_entrypoints = 8 - - radius = np.float32(1e9) - lims, _, _ = cpu_index.range_search(data_query, radius) - counts = lims[1:] - lims[:-1] - self.assertTrue(np.all(counts > 0)) - - -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -class TestIDMapCagra(unittest.TestCase): - - def do_IDMapCagra(self, metric, numeric_type): - d = 64 - k = 12 - if numeric_type == faiss.Int8: - data_base_nt = np.random.randint( - -128, 128, size=(10000, d), dtype=np.int8 - ) - data_query_nt = np.random.randint( - -128, 128, size=(100, d), dtype=np.int8 - ) - data_base = data_base_nt.astype(np.float32) - data_query = data_query_nt.astype(np.float32) - else: - ds = datasets.SyntheticDataset(d, 0, 10000, 100) - data_base = ds.get_database() # fp32 - data_query = ds.get_queries() # fp32 - if numeric_type == faiss.Float16: - data_base_nt = data_base.astype(np.float16) - data_query_nt = data_query.astype(np.float16) - elif numeric_type == faiss.Float32: - data_base_nt = data_base - data_query_nt = data_query - - Dref, Iref = faiss.knn(data_query, data_base, k, metric) - + # Keep every raw allocation owner and async-copy source alive explicitly. + owners = [faiss.Dataset.makeDevicePadded( + res, faiss.Dataset.viewHost(array.reshape(1, -1)), 0) + for array in arrays] + quantizer = faiss.BBQQuantizer() + quantizer.codeLayout = faiss.BBQCodeLayout_Packed1Bit + quantizer.codes = faiss.cast_integer_to_uint8_ptr(int(owners[0].getData())) + quantizer.centroid = owners[1].getData() + for field, owner in (("lowerIntervals", 1), ("upperIntervals", 2), + ("additionalCorrections", 3), ("dequantDelta", 2), + ("dequantSumDelta", 3), ("rowNorm", 3)): + setattr(quantizer, field, + faiss.cast_integer_to_float_ptr(int(owners[owner].getData()))) + quantizer.quantizedComponentSums = faiss.cast_integer_to_int_ptr( + int(owners[4].getData())) + source = faiss.Dataset.viewDeviceBBQ( + quantizer, rows, dim, faiss.Float32, 0) + self.assertEqual(source.getLayout(), faiss.Dataset.Layout_BBQ) + self.assertEqual((source.getNumRows(), source.getDim()), (rows, dim)) + self.assertTrue(source.isDevice()) + self.assertFalse(source.ownsData()) + self.assertFalse(source.isCagraCompatible()) + descriptor = source.view() + source_ref, descriptor_ref = weakref.ref(source), weakref.ref(descriptor) + res.syncDefaultStreamCurrentDevice() + index = faiss.GpuIndexCagra(res, dim, faiss.METRIC_L2, self.config()) + index.train(descriptor) + del source, descriptor, quantizer + gc.collect() + self.assertIsNotNone(source_ref()) + self.assertIsNotNone(descriptor_ref()) + self.assertTrue(index.is_trained) + self.assertEqual(index.ntotal, rows) + self.assertFalse(index.isSearchReady()) + graph = faiss.vector_to_array(index.get_knngraph()) + with self.assertRaisesRegex(RuntimeError, "Dataset"): + index.search(values[:64], 1) + with self.assertRaisesRegex(RuntimeError, "BBQ"): + index.copyTo(faiss.IndexHNSWCagra()) + + dense = faiss.Dataset.makeDevicePadded( + res, faiss.Dataset.viewHost(values), 0) + index.updateDataset(dense) + gc.collect() + self.assertIsNone(source_ref()) + self.assertIsNone(descriptor_ref()) + self.assertTrue(index.isSearchReady()) + np.testing.assert_array_equal( + faiss.vector_to_array(index.get_knngraph()), graph) + params = faiss.SearchParametersCagra() + params.itopk_size = 128 + distances, labels = index.search(values[:64], 1, params=params) + self.assertTrue(np.all((labels >= 0) & (labels < rows))) + self.assertGreaterEqual(np.mean(labels[:, 0] == np.arange(64)), 0.98) + expected = np.sum((values[:64, None, :] - values[labels]) ** 2, axis=2) + np.testing.assert_allclose(distances, expected, rtol=6e-5, atol=1e-5) + + def test_arrays_do_not_bypass_dataset_requirement(self): res = faiss.StandardGpuResources() + cagra = faiss.GpuIndexCagra(res, 20, faiss.METRIC_L2, self.config()) + values = np.zeros((64, 20), dtype="float32") + for method in (cagra.train, cagra.add): + with self.assertRaisesRegex(TypeError, "Dataset"): + method(values) + index = faiss.IndexIDMap(cagra) + with self.assertRaisesRegex(RuntimeError, "Dataset"): + index.train(values) + + + def test_idmap_dataset(self): + random = np.random.RandomState(1732) + for dtype, numeric_type in ((np.float32, faiss.Float32), + (np.float16, faiss.Float16), + (np.int8, faiss.Int8)): + values = random.randint(-50, 51, (1024, 19)).astype(dtype) + for map_class in (faiss.IndexIDMap, faiss.IndexIDMap2): + with self.subTest(dtype=dtype, map_class=map_class.__name__): + res = faiss.StandardGpuResources() + source = faiss.Dataset.viewHost(values) + storage = faiss.Dataset.makeDevicePadded(res, source, 0) + owner_ref = weakref.ref(storage) + cagra = faiss.GpuIndexCagra( + res, 19, faiss.METRIC_L2, self.config()) + index = map_class(cagra) + index.train(storage) + index.train(source) # Does not replace the attached owner. + ids = np.arange(len(values), dtype="int64") * 7 + 100 + with self.assertRaises(ValueError): + index.add_with_ids(storage, ids[:-1]) + index.add_with_ids(storage, ids) + self.assertEqual(index.ntotal, len(values)) + if isinstance(index, faiss.IndexIDMap2): + index.check_consistency() + expected_d, positions = cagra.search( + values[:16], 4, numeric_type=numeric_type) + actual_d, labels = index.search( + values[:16], 4, numeric_type=numeric_type) + np.testing.assert_array_equal(labels, ids[positions]) + np.testing.assert_array_equal(actual_d, expected_d) + del storage, index + gc.collect() + self.assertIsNotNone(owner_ref()) + cagra.search(values[:16], 4, numeric_type=numeric_type) + cagra.reset() + self.assertIsNone(owner_ref()) - index = faiss.GpuIndexCagra(res, d, metric) - idMapIndex = faiss.IndexIDMap(index) - idMapIndex.train(data_base_nt, numeric_type=numeric_type) - ids = np.array([i for i in range(10000)]) - idMapIndex.add_with_ids(data_base_nt, ids, numeric_type=numeric_type) - Dnew, Inew = idMapIndex.search( - data_query_nt, k, numeric_type=numeric_type - ) - - evaluation.check_ref_knn_with_draws(Dref, Iref, Dnew, Inew, k) - - def test_IDMapCagra_L2(self): - self.do_IDMapCagra(faiss.METRIC_L2, faiss.Float32) - - def test_IDMapCagra_IP(self): - self.do_IDMapCagra(faiss.METRIC_INNER_PRODUCT, faiss.Float32) - - def test_IDMapCagra_L2_FP16(self): - self.do_IDMapCagra(faiss.METRIC_L2, faiss.Float16) - - def test_IDMapCagra_IP_FP16(self): - self.do_IDMapCagra(faiss.METRIC_INNER_PRODUCT, faiss.Float16) - - def test_IDMapCagra_L2_Int8(self): - self.do_IDMapCagra(faiss.METRIC_L2, faiss.Int8) - - def test_IDMapCagra_IP_Int8(self): - self.do_IDMapCagra(faiss.METRIC_INNER_PRODUCT, faiss.Int8) @unittest.skipIf( @@ -276,71 +410,3 @@ def test_multi_gpu_knobs_survive_swig(self): ), (16, 3, 8192), ) - - def test_brute_force_rejected_without_multiple_devices(self): - ds = datasets.SyntheticDataset(32, 0, 1000, 1) - config = faiss.GpuIndexCagraConfig() - config.build_algo = faiss.graph_build_algo_BRUTE_FORCE - res = faiss.StandardGpuResources() - index = faiss.GpuIndexCagra(res, ds.d, faiss.METRIC_L2, config) - - with self.assertRaises(RuntimeError): - index.train(ds.get_database()) - - -@unittest.skipIf( - "CUVS" not in faiss.get_compile_options(), "only if cuVS is compiled in" -) -@unittest.skipIf( - faiss.get_num_gpus() < 2, "need at least 2 GPUs for multi-GPU test" -) -class TestMultiGpuCagra(unittest.TestCase): - - def test_all_neighbors_build(self): - """train() on a multi-device config builds a unified CAGRA graph.""" - ds = datasets.SyntheticDataset(32, 0, 50_000, 100) - xb = ds.get_database() - xq = ds.get_queries() - k = 10 - - gt_index = faiss.IndexFlatL2(ds.d) - gt_index.add(xb) - Dref, Iref = gt_index.search(xq, k) - - devices = faiss.Int32Vector() - for i in range(min(faiss.get_num_gpus(), 4)): - devices.push_back(i) - - all_neighbors = faiss.AllNeighborsCagraConfig() - - config = faiss.GpuIndexCagraConfig() - config.graph_degree = 32 - config.intermediate_graph_degree = 48 - config.build_algo = faiss.graph_build_algo_NN_DESCENT - config.devices = devices - config.all_neighbors_params = all_neighbors - - res = faiss.StandardGpuResources() - index = faiss.GpuIndexCagra(res, ds.d, faiss.METRIC_L2, config) - index.train(xb) - - cpu_index = faiss.IndexHNSWCagra() - cpu_index.base_level_only = True - index.copyTo(cpu_index) - self.assertEqual(cpu_index.ntotal, ds.nb) - - cpu_index.hnsw.efSearch = 128 - Dnew, Inew = cpu_index.search(xq, k) - - recall = np.mean( - [len(set(Inew[i]) & set(Iref[i])) / k for i in range(ds.nq)] - ) - self.assertGreater( - recall, 0.70, f"all_neighbors recall@{k} too low: {recall:.4f}" - ) - - # Serialization roundtrip - loaded = faiss.deserialize_index(faiss.serialize_index(cpu_index)) - loaded.hnsw.efSearch = 128 - _, Inew2 = loaded.search(xq, k) - np.testing.assert_array_equal(Inew, Inew2) diff --git a/thirdparty/faiss/faiss/gpu/test/test_tiebreak_repro.py b/thirdparty/faiss/faiss/gpu/test/test_tiebreak_repro.py new file mode 100644 index 000000000..581cdc11f --- /dev/null +++ b/thirdparty/faiss/faiss/gpu/test/test_tiebreak_repro.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +# 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. + +"""Tie-break and padding tests for the classic (non-cuVS) GPU IVF search. + +`TieBreakComparator` orders an equal distance by the value, which pass 1 +sets to the user id. Two properties follow, and this file tests both: + +- Pass 2 must reject a padded entry by the list length. A pad ties with the + init key, so it can now win and make pass 2 decode a sentinel index. That + raised `CUDA error 700 an illegal memory access was encountered`. +- The GPU must break a tie the same way the CPU does. + +The shapes below give short lists on purpose, so a probed list holds fewer than +`k` vectors and pass 1 pads the rest. +""" + +import unittest + +import faiss +import numpy as np + +D = 32 +N = 20000 +NQ = 256 +SEED = 1234 + +# k above the average list length (N / nlist) leaves padded entries in the +# pass-1 output for pass 2 to select over. k stops at 512: at 1024 the scan +# asks for 48 KB of shared memory and fails to launch, a separate limit. +SHAPES = [(10, 1), (100, 1), (100, 8), (100, 64), (512, 8)] +FACTORIES = ["IVF1024,SQ8", "IVF1024,Flat", "IVF1024,PQ8"] + +# Copies of each distinct vector, so a query ties against a whole group. +DUPLICATES = 8 +REPEATS = 20 + + +def build_cpu_index( + factory: str, duplicates: int = 1 +) -> tuple[faiss.Index, np.ndarray]: + """Build an index over N vectors. + + `duplicates` > 1 repeats each distinct vector, so a query ties exactly + against a whole group and the tie straddles the k-th place. + """ + rs = np.random.RandomState(SEED) + xb = rs.rand(N // duplicates, D).astype("float32") + xb = np.ascontiguousarray(np.repeat(xb, duplicates, axis=0)) + index = faiss.index_factory(D, factory, faiss.METRIC_L2) + index.train(xb) + index.add(xb) + return index, xb + + +class TieBreakSelectionTest(unittest.TestCase): + def setUp(self) -> None: + self.res = faiss.StandardGpuResources() + rs = np.random.RandomState(SEED + 1) + self.xq: np.ndarray = rs.rand(NQ, D).astype("float32") + + def _to_gpu(self, cpu_index: faiss.Index) -> faiss.Index: + co = faiss.GpuClonerOptions() + co.useFloat16 = True + co.deterministic_tie_break = True + return faiss.index_cpu_to_gpu(self.res, 0, cpu_index, co) + + def test_short_lists_do_not_fault(self) -> None: + for factory in FACTORIES: + cpu_index, _ = build_cpu_index(factory) + gpu_index = self._to_gpu(cpu_index) + for k, nprobe in SHAPES: + with self.subTest(factory=factory, k=k, nprobe=nprobe): + gpu_index.nprobe = nprobe + _, ids = gpu_index.search(self.xq, k) + out_of_range = int((ids[ids >= 0] >= N).sum()) + self.assertEqual( + out_of_range, + 0, + f"{factory} k={k} nprobe={nprobe} returned " + f"{out_of_range} ids outside [0, {N})", + ) + + def test_empty_lists_do_not_fault(self) -> None: + """A sharded index probes lists that hold no vectors at all, because + the shard owns only some of the lists. Keep one list to reproduce it. + """ + factory = "IVF1024,SQ8" + cpu_index, xb = build_cpu_index(factory) + ivf = faiss.extract_index_ivf(cpu_index) + # Keep list 0 only, so every other probed list is present but empty. + for list_no in range(1, ivf.nlist): + ivf.invlists.resize(list_no, 0) + ivf.ntotal = ivf.invlists.list_size(0) + + gpu_index = self._to_gpu(cpu_index) + for k, nprobe in SHAPES: + with self.subTest(k=k, nprobe=nprobe): + gpu_index.nprobe = nprobe + _, ids = gpu_index.search(self.xq, k) + out_of_range = int((ids[ids >= 0] >= len(xb)).sum()) + self.assertEqual( + out_of_range, + 0, + f"k={k} nprobe={nprobe} returned {out_of_range} ids " + f"outside [0, {len(xb)})", + ) + + def test_tied_distances_select_the_same_neighbours(self) -> None: + """`PQ8` approximates the distance, so the CPU comparison below cannot + assert on it. This covers it by repeating the same search instead. + """ + for factory in FACTORIES: + cpu_index, _ = build_cpu_index(factory, duplicates=DUPLICATES) + gpu_index = self._to_gpu(cpu_index) + for k, nprobe in SHAPES: + with self.subTest(factory=factory, k=k, nprobe=nprobe): + gpu_index.nprobe = nprobe + first_d, first_i = gpu_index.search(self.xq, k) + ties = self._count_boundary_ties(first_d) + for repeat in range(1, REPEATS): + d, i = gpu_index.search(self.xq, k) + np.testing.assert_array_equal( + i, + first_i, + f"{factory} k={k} nprobe={nprobe} repeat {repeat} " + f"returned different neighbours ({ties} queries " + "tie at the k-th place)", + ) + np.testing.assert_array_equal(d, first_d) + + def test_gpu_breaks_a_tie_the_way_the_cpu_does(self) -> None: + """The CPU keeps the smaller id on a tie, in `CMax::cmp2` in + `utils/ordered_key_value.h`. `SQ8` and `Flat` compute the same + distances as the CPU, so the GPU must return the same ids in the same + order. `PQ8` is not tested here: the GPU approximates its distances in + a different way from the CPU. + + Measured on one A100 at k=100, nprobe=8, SQ8: without the tie-break + 135/256 queries match the CPU as a set and 0/256 match in order. With + the tie-break, 256/256 on both. + """ + for factory in ["IVF1024,SQ8", "IVF1024,Flat"]: + cpu_index, _ = build_cpu_index(factory, duplicates=DUPLICATES) + gpu_index = self._to_gpu(cpu_index) + for k, nprobe in [(100, 8), (512, 8)]: + with self.subTest(factory=factory, k=k, nprobe=nprobe): + cpu_index.nprobe = nprobe + gpu_index.nprobe = nprobe + cpu_d, cpu_i = cpu_index.search(self.xq, k) + gpu_d, gpu_i = gpu_index.search(self.xq, k) + + ties = self._count_boundary_ties(gpu_d) + same_set = sum( + set(cpu_i[q].tolist()) == set(gpu_i[q].tolist()) + for q in range(NQ) + ) + same_order = int((cpu_i == gpu_i).all(axis=1).sum()) + print( + f"{factory} k={k} nprobe={nprobe}: " + f"{ties}/{NQ} queries tie at the k-th place, " + f"{same_set}/{NQ} match the CPU as a set, " + f"{same_order}/{NQ} match the CPU in order", + flush=True, + ) + self.assertEqual(same_set, NQ) + self.assertEqual(same_order, NQ) + + @staticmethod + def _count_boundary_ties(distances: np.ndarray) -> int: + """Queries whose k-th and (k-1)-th neighbour are the same distance. + + A count of 0 means the case proves nothing, so the tests report it. + """ + if distances.shape[1] < 2: + return 0 + return int((distances[:, -1] == distances[:, -2]).sum()) diff --git a/thirdparty/faiss/faiss/gpu/utils/Comparators.cuh b/thirdparty/faiss/faiss/gpu/utils/Comparators.cuh index 6144eb29b..9e818fd3e 100644 --- a/thirdparty/faiss/faiss/gpu/utils/Comparators.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/Comparators.cuh @@ -22,6 +22,42 @@ struct Comparator { __device__ static inline bool gt(T a, T b) { return a > b; } + + template + __device__ static inline bool lt(T a, V, T b, V) { + return a < b; + } + + template + __device__ static inline bool gt(T a, V, T b, V) { + return a > b; + } +}; + +/// Orders on the key, then on the value, as `CMin::cmp2` does in +/// `utils/ordered_key_value.h`. +/// +/// Do not select over padded entries. A pad ties with the init key, so the +/// value decides the order and the pad can reach the output. +template +struct TieBreakComparator { + __device__ static inline bool lt(T a, T b) { + return a < b; + } + + __device__ static inline bool gt(T a, T b) { + return a > b; + } + + template + __device__ static inline bool lt(T a, V av, T b, V bv) { + return (a < b) || ((a == b) && (av < bv)); + } + + template + __device__ static inline bool gt(T a, V av, T b, V bv) { + return (a > b) || ((a == b) && (av > bv)); + } }; template <> @@ -41,6 +77,39 @@ struct Comparator { return __half2float(a) > __half2float(b); #endif // FAISS_USE_FULL_FLOAT16 } + + template + __device__ static inline bool lt(half a, V, half b, V) { + return lt(a, b); + } + + template + __device__ static inline bool gt(half a, V, half b, V) { + return gt(a, b); + } +}; + +template <> +struct TieBreakComparator { + __device__ static inline bool lt(half a, half b) { + return Comparator::lt(a, b); + } + + __device__ static inline bool gt(half a, half b) { + return Comparator::gt(a, b); + } + + template + __device__ static inline bool lt(half a, V av, half b, V bv) { + return Comparator::lt(a, b) || + (!Comparator::gt(a, b) && av < bv); + } + + template + __device__ static inline bool gt(half a, V av, half b, V bv) { + return Comparator::gt(a, b) || + (!Comparator::lt(a, b) && av > bv); + } }; } // namespace gpu diff --git a/thirdparty/faiss/faiss/gpu/utils/CopyUtils.cuh b/thirdparty/faiss/faiss/gpu/utils/CopyUtils.cuh index 19a07f901..3e4fd1332 100644 --- a/thirdparty/faiss/faiss/gpu/utils/CopyUtils.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/CopyUtils.cuh @@ -117,8 +117,8 @@ inline void fromDevice(T* src, T* dst, size_t num, cudaStream_t stream) { int dev = getDeviceForAddress(dst); if (dev == -1) { - CUDA_VERIFY(cudaMemcpyAsync( - dst, src, num * sizeof(T), cudaMemcpyDeviceToHost, stream)); + memcpyHostDeviceAsync( + dst, src, num * sizeof(T), cudaMemcpyDeviceToHost, stream); cudaStreamSynchronize(stream); } else { CUDA_VERIFY(cudaMemcpyAsync( diff --git a/thirdparty/faiss/faiss/gpu/utils/CuvsFilterConvert.cu b/thirdparty/faiss/faiss/gpu/utils/CuvsFilterConvert.cu index 5cac75d90..ce4435719 100644 --- a/thirdparty/faiss/faiss/gpu/utils/CuvsFilterConvert.cu +++ b/thirdparty/faiss/faiss/gpu/utils/CuvsFilterConvert.cu @@ -86,7 +86,7 @@ void convert_to_bitset_range( int64_t n_elements_to_set = (imax - 1) / original_nbits - imin / original_nbits + 1; - auto stream = raft::resource::get_cuda_stream(res); + auto stream = raft::resource::get_cuda_stream(res).get(); const int threads_per_block = 256; const int blocks = @@ -182,7 +182,7 @@ void convert_to_bitset_bitmap( return; } - auto stream = raft::resource::get_cuda_stream(res); + auto stream = raft::resource::get_cuda_stream(res).get(); auto d_bitmap = raft::make_device_vector(res, n_elements); auto d_bitmap_ptr = d_bitmap.data_handle(); raft::copy( diff --git a/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.cu b/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.cu index 123c8e05e..f50f89674 100644 --- a/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.cu +++ b/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.cu @@ -8,9 +8,12 @@ #include #include #include +#include +#include #include #include #include +#include namespace faiss { namespace gpu { @@ -150,6 +153,217 @@ int getDeviceForAddress(const void* p) { #endif } +#ifdef USE_AMD_ROCM +namespace { + +// ROCm copies pageable host memory of more than 64 KiB by pinning the user's +// pages for the copy. On MI350X that path takes GPU memory access faults when +// the process unmaps other host memory meanwhile, so copy through our own +// pinned buffers instead, as CUDA does internally. +constexpr size_t kMinStagedCopyBytes = 64 * 1024; +constexpr size_t kStagingChunkBytes = 16 * 1024 * 1024; +// Double buffering: the host copy of one chunk overlaps the device copy of the +// other +constexpr int kStagingBuffers = 2; + +struct PinnedStaging { + PinnedStaging() { + for (int i = 0; i < kStagingBuffers; ++i) { + auto err = hipHostMalloc( + &buf[i], kStagingChunkBytes, hipHostMallocPortable); + if (err == hipSuccess) { + err = hipEventCreateWithFlags(&done[i], hipEventDisableTiming); + } + if (err != hipSuccess) { + // A sticky error would fail a later, unrelated launch check + (void)hipGetLastError(); + releaseAfterFailure(); + FAISS_THROW_FMT( + "failed to allocate a %zu byte pinned staging buffer " + "for a pageable host copy (error %d %s)", + kStagingChunkBytes, + (int)err, + hipGetErrorString(err)); + } + } + } + + void releaseAfterFailure() { + for (int i = 0; i < kStagingBuffers; ++i) { + if (done[i]) { + (void)hipEventDestroy(done[i]); + } + if (buf[i]) { + (void)hipHostFree(buf[i]); + } + } + } + + void wait(int b) { + if (pending[b]) { + CUDA_VERIFY(hipEventSynchronize(done[b])); + pending[b] = false; + } + } + + void waitAll() { + for (int b = 0; b < kStagingBuffers; ++b) { + wait(b); + } + } + + void record(int b, hipStream_t stream) { + CUDA_VERIFY(hipEventRecord(done[b], stream)); + pending[b] = true; + } + + void* buf[kStagingBuffers] = {}; + hipEvent_t done[kStagingBuffers] = {}; + bool pending[kStagingBuffers] = {}; +}; + +// Free staging buffers per device (events belong to a device). The pool is +// never destroyed: freeing pinned memory from a static or thread_local +// destructor crashes once the HIP runtime has shut down at exit. +struct StagingPool { + std::mutex mutex; + std::unordered_map> free; +}; + +StagingPool& stagingPool() { + static auto* pool = new StagingPool(); + return *pool; +} + +// Takes a staging buffer set for the current device for one copy +class StagingLease { + public: + StagingLease() : device_(getCurrentDevice()) { + auto& pool = stagingPool(); + std::lock_guard lock(pool.mutex); + auto& list = pool.free[device_]; + if (list.empty()) { + staging_ = new PinnedStaging(); + } else { + staging_ = list.back(); + list.pop_back(); + } + } + + ~StagingLease() { + // An event must not be waited on after its stream may be destroyed: + // hipEventSynchronize dereferences the stream of the last record + staging_->waitAll(); + auto& pool = stagingPool(); + std::lock_guard lock(pool.mutex); + pool.free[device_].push_back(staging_); + } + + StagingLease(const StagingLease&) = delete; + StagingLease& operator=(const StagingLease&) = delete; + + PinnedStaging& operator*() const { + return *staging_; + } + + private: + int device_; + PinnedStaging* staging_; +}; + +bool isPageableHostMemory(const void* p) { + hipPointerAttribute_t att; + if (hipPointerGetAttributes(&att, p) != hipSuccess) { + (void)hipGetLastError(); + return true; + } + return att.type == hipMemoryTypeUnregistered; +} + +void stagedHostToDevice( + char* dst, + const char* src, + size_t bytes, + hipStream_t stream) { + StagingLease lease; + auto& s = *lease; + for (size_t off = 0, i = 0; off < bytes; off += kStagingChunkBytes, ++i) { + const int b = i % kStagingBuffers; + const size_t n = std::min(kStagingChunkBytes, bytes - off); + s.wait(b); + std::memcpy(s.buf[b], src + off, n); + CUDA_VERIFY(hipMemcpyAsync( + dst + off, s.buf[b], n, hipMemcpyHostToDevice, stream)); + s.record(b, stream); + } +} + +void stagedDeviceToHost( + char* dst, + const char* src, + size_t bytes, + hipStream_t stream) { + StagingLease lease; + auto& s = *lease; + // The host copy of chunk i - 1 overlaps the device copy of chunk i + auto drain = [&](int b, size_t off, size_t n) { + s.wait(b); + std::memcpy(dst + off, s.buf[b], n); + }; + int prevB = -1; + size_t prevOff = 0; + size_t prevN = 0; + for (size_t off = 0, i = 0; off < bytes; off += kStagingChunkBytes, ++i) { + const int b = i % kStagingBuffers; + const size_t n = std::min(kStagingChunkBytes, bytes - off); + s.wait(b); + CUDA_VERIFY(hipMemcpyAsync( + s.buf[b], src + off, n, hipMemcpyDeviceToHost, stream)); + s.record(b, stream); + if (prevB >= 0) { + drain(prevB, prevOff, prevN); + } + prevB = b; + prevOff = off; + prevN = n; + } + if (prevB >= 0) { + drain(prevB, prevOff, prevN); + } +} + +} // namespace +#endif + +void memcpyHostDeviceAsync( + void* dst, + const void* src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) { +#ifdef USE_AMD_ROCM + if (bytes > kMinStagedCopyBytes) { + if (kind == hipMemcpyHostToDevice && isPageableHostMemory(src)) { + stagedHostToDevice( + static_cast(dst), + static_cast(src), + bytes, + stream); + return; + } + if (kind == hipMemcpyDeviceToHost && isPageableHostMemory(dst)) { + stagedDeviceToHost( + static_cast(dst), + static_cast(src), + bytes, + stream); + return; + } + } +#endif + CUDA_VERIFY(cudaMemcpyAsync(dst, src, bytes, kind, stream)); +} + bool getFullUnifiedMemSupport(int device) { const auto& prop = getDeviceProperties(device); return (prop.major >= 6); diff --git a/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.h b/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.h index edb1b7157..5981957a3 100644 --- a/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.h +++ b/thirdparty/faiss/faiss/gpu/utils/DeviceUtils.h @@ -63,6 +63,17 @@ size_t getMaxSharedMemPerBlockCurrentDevice(); /// a device (deviceId >= 0) or the host (-1). int getDeviceForAddress(const void* p); +/// cudaMemcpyAsync, except that on ROCm a copy of more than 64 KiB to or from +/// pageable host memory goes through pinned staging buffers. As with CUDA's +/// pageable copies, a host-to-device copy returns once the source can be +/// reused, and a device-to-host copy returns once the data is on the host. +void memcpyHostDeviceAsync( + void* dst, + const void* src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream); + /// Does the given device support full unified memory sharing host /// memory? bool getFullUnifiedMemSupport(int device); diff --git a/thirdparty/faiss/faiss/gpu/utils/DeviceVector.cuh b/thirdparty/faiss/faiss/gpu/utils/DeviceVector.cuh index 20c58ffc6..96e35285e 100644 --- a/thirdparty/faiss/faiss/gpu/utils/DeviceVector.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/DeviceVector.cuh @@ -77,12 +77,12 @@ class DeviceVector { if (num_ > 0) { FAISS_ASSERT(data()); - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( out.data(), data(), num_ * sizeof(T), cudaMemcpyDeviceToHost, - stream)); + stream); } return out; @@ -108,12 +108,12 @@ class DeviceVector { int dev = getDeviceForAddress(d); if (dev == -1) { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( data() + num_, d, n * sizeof(T), cudaMemcpyHostToDevice, - stream)); + stream); } else { CUDA_VERIFY(cudaMemcpyAsync( data() + num_, diff --git a/thirdparty/faiss/faiss/gpu/utils/Float16.cuh b/thirdparty/faiss/faiss/gpu/utils/Float16.cuh index cfe405c79..6c80df255 100644 --- a/thirdparty/faiss/faiss/gpu/utils/Float16.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/Float16.cuh @@ -21,13 +21,16 @@ #define FAISS_USE_FULL_BFLOAT16 1 #endif // __CUDA_ARCH__ types -#if !defined(USE_AMD_ROCM) -#include -#include -#else +// The HIP branch must come first: hipify-perl (ROCm 10.1 and later) drops an +// #include it has already emitted, so translating the CUDA branch first would +// delete these lines. +#if defined(USE_AMD_ROCM) #include #include -#endif // !defined(USE_AMD_ROCM) +#else +#include +#include +#endif // defined(USE_AMD_ROCM) namespace faiss { namespace gpu { diff --git a/thirdparty/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh b/thirdparty/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh index dbc230863..0896edf54 100644 --- a/thirdparty/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/MergeNetworkBlock.cuh @@ -53,26 +53,14 @@ inline __device__ void blockMergeSmall(K* listK, V* listV) { if (AllThreads || (threadIdx.x < N * L)) { K ka = listK[pos]; K kb = listK[pos + stride]; + V va = listV[pos]; + V vb = listV[pos + stride]; - bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool swap = Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); listK[pos] = swap ? kb : ka; listK[pos + stride] = swap ? ka : kb; - - V va = listV[pos]; - V vb = listV[pos + stride]; listV[pos] = swap ? vb : va; listV[pos + stride] = swap ? va : vb; - - // FIXME: is this a CUDA 9 compiler bug? - // K& ka = listK[pos]; - // K& kb = listK[pos + stride]; - - // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); - // swap(s, ka, kb); - - // V& va = listV[pos]; - // V& vb = listV[pos + stride]; - // swap(s, va, vb); } __syncthreads(); @@ -84,26 +72,15 @@ inline __device__ void blockMergeSmall(K* listK, V* listV) { if (AllThreads || (threadIdx.x < N * L)) { K ka = listK[pos]; K kb = listK[pos + stride]; + V va = listV[pos]; + V vb = listV[pos + stride]; - bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool swap = + Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); listK[pos] = swap ? kb : ka; listK[pos + stride] = swap ? ka : kb; - - V va = listV[pos]; - V vb = listV[pos + stride]; listV[pos] = swap ? vb : va; listV[pos + stride] = swap ? va : vb; - - // FIXME: is this a CUDA 9 compiler bug? - // K& ka = listK[pos]; - // K& kb = listK[pos + stride]; - - // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); - // swap(s, ka, kb); - - // V& va = listV[pos]; - // V& vb = listV[pos + stride]; - // swap(s, va, vb); } __syncthreads(); @@ -140,26 +117,14 @@ inline __device__ void blockMergeLarge(K* listK, V* listV) { K ka = listK[pos]; K kb = listK[pos + stride]; + V va = listV[pos]; + V vb = listV[pos + stride]; - bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool swap = Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); listK[pos] = swap ? kb : ka; listK[pos + stride] = swap ? ka : kb; - - V va = listV[pos]; - V vb = listV[pos + stride]; listV[pos] = swap ? vb : va; listV[pos + stride] = swap ? va : vb; - - // FIXME: is this a CUDA 9 compiler bug? - // K& ka = listK[pos]; - // K& kb = listK[pos + stride]; - - // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); - // swap(s, ka, kb); - - // V& va = listV[pos]; - // V& vb = listV[pos + stride]; - // swap(s, va, vb); } __syncthreads(); @@ -176,26 +141,15 @@ inline __device__ void blockMergeLarge(K* listK, V* listV) { K ka = listK[pos]; K kb = listK[pos + stride]; + V va = listV[pos]; + V vb = listV[pos + stride]; - bool swap = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool swap = + Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); listK[pos] = swap ? kb : ka; listK[pos + stride] = swap ? ka : kb; - - V va = listV[pos]; - V vb = listV[pos + stride]; listV[pos] = swap ? vb : va; listV[pos + stride] = swap ? va : vb; - - // FIXME: is this a CUDA 9 compiler bug? - // K& ka = listK[pos]; - // K& kb = listK[pos + stride]; - - // bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); - // swap(s, ka, kb); - - // V& va = listV[pos]; - // V& vb = listV[pos + stride]; - // swap(s, va, vb); } __syncthreads(); diff --git a/thirdparty/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh b/thirdparty/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh index 39b3008b7..c4a385f73 100644 --- a/thirdparty/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/MergeNetworkWarp.cuh @@ -111,12 +111,14 @@ inline __device__ void warpBitonicMergeLE16(K& k, V& v) { // See the comment above how performing both of these // comparisons in the warp seems to win out over the // alternatives in practice - bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK); + bool s = small ? Comp::gt(k, v, otherK, otherV) + : Comp::lt(k, v, otherK, otherV); assign(s, k, otherK); assign(s, v, otherV); } else { - bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK); + bool s = small ? Comp::lt(k, v, otherK, otherV) + : Comp::gt(k, v, otherK, otherV); assign(s, k, otherK); assign(s, v, otherV); } @@ -131,12 +133,14 @@ inline __device__ void warpBitonicMergeLE16(K& k, V& v) { bool small = !(laneId & stride); if (Dir) { - bool s = small ? Comp::gt(k, otherK) : Comp::lt(k, otherK); + bool s = small ? Comp::gt(k, v, otherK, otherV) + : Comp::lt(k, v, otherK, otherV); assign(s, k, otherK); assign(s, v, otherV); } else { - bool s = small ? Comp::lt(k, otherK) : Comp::gt(k, otherK); + bool s = small ? Comp::lt(k, v, otherK, otherV) + : Comp::gt(k, v, otherK, otherV); assign(s, k, otherK); assign(s, v, otherV); } @@ -186,7 +190,7 @@ struct BitonicMergeStep { K& kb = k[i + N / 2]; V& vb = v[i + N / 2]; - bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool s = Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); swap(s, ka, kb); swap(s, va, vb); } @@ -254,7 +258,7 @@ struct BitonicMergeStep { K& kb = k[i + kNextHighestPowerOf2 / 2]; V& vb = v[i + kNextHighestPowerOf2 / 2]; - bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool s = Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); swap(s, ka, kb); swap(s, va, vb); } @@ -341,7 +345,7 @@ struct BitonicMergeStep { K& kb = k[i + kNextHighestPowerOf2 / 2]; V& vb = v[i + kNextHighestPowerOf2 / 2]; - bool s = Dir ? Comp::gt(ka, kb) : Comp::lt(ka, kb); + bool s = Dir ? Comp::gt(ka, va, kb, vb) : Comp::lt(ka, va, kb, vb); swap(s, ka, kb); swap(s, va, vb); } @@ -452,14 +456,16 @@ inline __device__ void warpMergeAnyRegisters( // ka is always first in the list, so we needn't use our lane // in this comparison - bool swapa = Dir ? Comp::gt(ka, otherKb) : Comp::lt(ka, otherKb); + bool swapa = Dir ? Comp::gt(ka, va, otherKb, otherVb) + : Comp::lt(ka, va, otherKb, otherVb); assign(swapa, ka, otherKb); assign(swapa, va, otherVb); // kb is always second in the list, so we needn't use our lane // in this comparison if (FullMerge) { - bool swapb = Dir ? Comp::lt(kb, otherKa) : Comp::gt(kb, otherKa); + bool swapb = Dir ? Comp::lt(kb, vb, otherKa, otherVa) + : Comp::gt(kb, vb, otherKa, otherVa); assign(swapb, kb, otherKa); assign(swapb, vb, otherVa); diff --git a/thirdparty/faiss/faiss/gpu/utils/Select.cuh b/thirdparty/faiss/faiss/gpu/utils/Select.cuh index 19ae65e06..f6975b4e3 100644 --- a/thirdparty/faiss/faiss/gpu/utils/Select.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/Select.cuh @@ -158,6 +158,7 @@ struct BlockSelect { initV(initVVal), numVals(0), warpKTop(initKVal), + warpVTop(initVVal), sharedK(smemK), sharedV(smemV), kMinus1(k - 1) { @@ -190,7 +191,8 @@ struct BlockSelect { } __device__ inline void addThreadQ(K k, V v) { - if (Dir ? Comp::gt(k, warpKTop) : Comp::lt(k, warpKTop)) { + if (Dir ? Comp::gt(k, v, warpKTop, warpVTop) + : Comp::lt(k, v, warpKTop, warpVTop)) { // Rotate right #pragma unroll for (int i = NumThreadQ - 1; i > 0; --i) { @@ -233,6 +235,7 @@ struct BlockSelect { // We have to beat at least this element warpKTop = warpK[kMinus1]; + warpVTop = warpV[kMinus1]; warpFence(); } @@ -316,6 +319,8 @@ struct BlockSelect { // The k-th highest (Dir) or lowest (!Dir) element K warpKTop; + // The value paired with warpKTop + V warpVTop; // Thread queue values K threadK[NumThreadQ]; @@ -349,7 +354,8 @@ struct BlockSelect { : threadK(initK), threadV(initV), sharedK(smemK), sharedV(smemV) {} __device__ inline void addThreadQ(K k, V v) { - bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK); + bool swap = Dir ? Comp::gt(k, v, threadK, threadV) + : Comp::lt(k, v, threadK, threadV); threadK = swap ? k : threadK; threadV = swap ? v : threadV; } @@ -398,7 +404,8 @@ struct BlockSelect { K k = sharedK[i]; V v = sharedV[i]; - bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK); + bool swap = Dir ? Comp::gt(k, v, threadK, threadV) + : Comp::lt(k, v, threadK, threadV); threadK = swap ? k : threadK; threadV = swap ? v : threadV; } @@ -444,6 +451,7 @@ struct WarpSelect { initV(initVVal), numVals(0), warpKTop(initKVal), + warpVTop(initVVal), kLane((k - 1) % kWarpSize) { static_assert( utils::isPowerOf2(ThreadsPerBlock), @@ -467,7 +475,8 @@ struct WarpSelect { } __device__ inline void addThreadQ(K k, V v) { - if (Dir ? Comp::gt(k, warpKTop) : Comp::lt(k, warpKTop)) { + if (Dir ? Comp::gt(k, v, warpKTop, warpVTop) + : Comp::lt(k, v, warpKTop, warpVTop)) { // Rotate right #pragma unroll for (int i = NumThreadQ - 1; i > 0; --i) { @@ -509,6 +518,7 @@ struct WarpSelect { // We have to beat at least this element warpKTop = shfl(warpK[kNumWarpQRegisters - 1], kLane); + warpVTop = shfl(warpV[kNumWarpQRegisters - 1], kLane); } /// This function handles sorting and merging together the @@ -570,6 +580,8 @@ struct WarpSelect { // The k-th highest (Dir) or lowest (!Dir) element K warpKTop; + // The value paired with warpKTop + V warpVTop; // Thread queue values K threadK[NumThreadQ]; @@ -600,7 +612,8 @@ struct WarpSelect { : threadK(initK), threadV(initV) {} __device__ inline void addThreadQ(K k, V v) { - bool swap = Dir ? Comp::gt(k, threadK) : Comp::lt(k, threadK); + bool swap = Dir ? Comp::gt(k, v, threadK, threadV) + : Comp::lt(k, v, threadK, threadV); threadK = swap ? k : threadK; threadV = swap ? v : threadV; } diff --git a/thirdparty/faiss/faiss/gpu/utils/StackDeviceMemory.cpp b/thirdparty/faiss/faiss/gpu/utils/StackDeviceMemory.cpp index f218a1c24..d8b304f4d 100644 --- a/thirdparty/faiss/faiss/gpu/utils/StackDeviceMemory.cpp +++ b/thirdparty/faiss/faiss/gpu/utils/StackDeviceMemory.cpp @@ -145,7 +145,7 @@ void StackDeviceMemory::Stack::returnAlloc( } head_ = p; - lastUsers_.push_back(Range(p, p + size, stream)); + lastUsers_.emplace_back(p, p + size, stream); } std::string StackDeviceMemory::Stack::toString() const { diff --git a/thirdparty/faiss/faiss/gpu/utils/Tensor-inl.cuh b/thirdparty/faiss/faiss/gpu/utils/Tensor-inl.cuh index 57b6d73b6..1cb7b6385 100644 --- a/thirdparty/faiss/faiss/gpu/utils/Tensor-inl.cuh +++ b/thirdparty/faiss/faiss/gpu/utils/Tensor-inl.cuh @@ -188,21 +188,21 @@ __host__ void Tensor::copyFrom( int tDev = getDeviceForAddress(t.data()); if (tDev == -1) { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( this->data_, t.data(), this->getSizeInBytes(), ourDev == -1 ? cudaMemcpyHostToHost : cudaMemcpyHostToDevice, - stream)); + stream); } else { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( this->data_, t.data(), this->getSizeInBytes(), ourDev == -1 ? cudaMemcpyDeviceToHost : cudaMemcpyDeviceToDevice, - stream)); + stream); } } } @@ -232,21 +232,21 @@ __host__ void Tensor::copyTo( int tDev = getDeviceForAddress(t.data()); if (tDev == -1) { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( t.data(), this->data_, this->getSizeInBytes(), ourDev == -1 ? cudaMemcpyHostToHost : cudaMemcpyDeviceToHost, - stream)); + stream); } else { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( t.data(), this->data_, this->getSizeInBytes(), ourDev == -1 ? cudaMemcpyHostToDevice : cudaMemcpyDeviceToDevice, - stream)); + stream); } } } @@ -270,12 +270,12 @@ __host__ void Tensor::copyFrom( GPU_FAISS_ASSERT(this->data_); int ourDev = getDeviceForAddress(this->data_); - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( this->data_, v.data(), this->getSizeInBytes(), ourDev == -1 ? cudaMemcpyHostToHost : cudaMemcpyHostToDevice, - stream)); + stream); } } @@ -299,12 +299,12 @@ __host__ std::vector Tensor:: std::memcpy( out.data(), this->data_, this->numElements() * sizeof(T)); } else { - CUDA_VERIFY(cudaMemcpyAsync( + memcpyHostDeviceAsync( out.data(), this->data_, this->numElements() * sizeof(T), cudaMemcpyDeviceToHost, - stream)); + stream); } } diff --git a/thirdparty/faiss/faiss/gpu_metal/CMakeLists.txt b/thirdparty/faiss/faiss/gpu_metal/CMakeLists.txt index beac5c9fc..abe8c890c 100644 --- a/thirdparty/faiss/faiss/gpu_metal/CMakeLists.txt +++ b/thirdparty/faiss/faiss/gpu_metal/CMakeLists.txt @@ -15,6 +15,7 @@ set(FAISS_METAL_SRC MetalDistance.mm MetalFlatKernels.mm MetalIndexFlat.mm + MetalIndexBinaryFlat.mm MetalIndexIVFFlat.mm MetalIndexIVFPQ.mm impl/MetalIVFFlat.mm @@ -24,6 +25,11 @@ set(FAISS_METAL_SRC MetalPythonBridge.mm ) +# BinaryFlat owns its persistent and temporary Metal buffers through ARC. +set_source_files_properties(MetalIndexBinaryFlat.mm PROPERTIES + COMPILE_OPTIONS "-fobjc-arc" +) + add_library(faiss_metal STATIC ${FAISS_METAL_SRC}) target_link_libraries(faiss_metal @@ -94,6 +100,7 @@ set(FAISS_METAL_HEADERS MetalFlatKernels.h MetalIndex.h MetalIndexFlat.h + MetalIndexBinaryFlat.h MetalIndexIVFFlat.h MetalKernels.h MetalPythonBridge.h diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalCloner.h b/thirdparty/faiss/faiss/gpu_metal/MetalCloner.h index 423b4d2ab..07bbd2ddd 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalCloner.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalCloner.h @@ -11,6 +11,7 @@ #pragma once #include +#include namespace faiss { namespace gpu_metal { @@ -31,5 +32,15 @@ faiss::Index* index_cpu_to_metal_gpu( /// Caller owns the returned index. faiss::Index* index_metal_gpu_to_cpu(const faiss::Index* index); +/// Clone IndexBinaryFlat to Metal. device must be 0; caller owns the result. +faiss::IndexBinary* index_binary_cpu_to_metal_gpu( + StandardMetalResources* res, + int device, + const faiss::IndexBinary* index); + +/// Clone MetalIndexBinaryFlat to CPU. Caller owns the returned index. +faiss::IndexBinary* index_binary_metal_gpu_to_cpu( + const faiss::IndexBinary* index); + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalCloner.mm b/thirdparty/faiss/faiss/gpu_metal/MetalCloner.mm index 46c897fee..621d51254 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalCloner.mm +++ b/thirdparty/faiss/faiss/gpu_metal/MetalCloner.mm @@ -12,6 +12,7 @@ #include #include #include +#import "MetalIndexBinaryFlat.h" #import "MetalIndexFlat.h" #import "MetalIndexIVFFlat.h" #import "MetalIndexIVFPQ.h" @@ -120,5 +121,28 @@ int get_num_gpus() { "(supported: MetalIndexFlat, MetalIndexIVFFlat, MetalIndexIVFPQ)"); } +faiss::IndexBinary* index_binary_cpu_to_metal_gpu( + StandardMetalResources* res, + int device, + const faiss::IndexBinary* index) { + FAISS_THROW_IF_NOT(res && res->getResources()); + FAISS_THROW_IF_NOT(res->getResources()->isAvailable()); + FAISS_THROW_IF_NOT_MSG(device == 0, "Metal backend supports only device 0"); + const auto* flat = dynamic_cast(index); + FAISS_THROW_IF_NOT_MSG( + flat, "Metal binary cloner supports only IndexBinaryFlat"); + return new MetalIndexBinaryFlat(res->getResources(), flat); +} + +faiss::IndexBinary* index_binary_metal_gpu_to_cpu( + const faiss::IndexBinary* index) { + const auto* metal = dynamic_cast(index); + FAISS_THROW_IF_NOT_MSG( + metal, "Metal binary cloner supports only MetalIndexBinaryFlat"); + auto cpu = std::make_unique(metal->d); + metal->copyTo(cpu.get()); + return cpu.release(); +} + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.h b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.h index 2785f5d47..ffa9a1ff4 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.h @@ -83,5 +83,97 @@ bool runMetalIVFFlatFullSearch( bool centroidsAreFP16 = false, bool waitForCompletion = true); +/// Full IVF-PQ search on the GPU: builds per-(query, probe) PQ lookup tables, +/// scans the assigned inverted lists with 8-bit ADC, and merges the per-list +/// top-k into the final top-k. Coarse quantization is performed on the CPU and +/// the assignments are passed in via @p coarseAssign. @p coarseDist carries +/// the per-(query, probe) coarse scores, added for inner product (the IP +/// tables hold only); unused for L2. +bool runMetalIVFPQFullSearch( + id device, + id queue, + id queries, + id coarseAssign, + id coarseDist, + id coarseCentroids, + id pqCentroids, + id lookupTable, + id codes, + id ids, + id listOffset, + id listLength, + int nq, + int d, + int M, + int k, + int nprobe, + int nlist, + int avgListLen, + bool lookupFp16, + bool isL2, + id outDistances, + id outIndices, + id perListDistBuf, + id perListIdxBuf, + bool waitForCompletion = true); + +/// Build the query-independent precomputed term of the IVFPQ L2 distance +/// decomposition on the GPU: term2[l][m][c] = ||pq[m][c]||^2 + +/// 2 , laid out as nlist * M * 256 floats. Run once +/// per trained index; consumed by runMetalIVFPQPrecompSearch. +bool runMetalIVFPQPrecomputeTerm2( + id device, + id queue, + id coarseCentroids, + id pqCentroids, + id outTerm2, + int nlist, + int d, + int M); + +/// IVF-PQ search using the precomputed-table decomposition: a per-query +/// M*256 term is built once per batch (instead of a full residual LUT per +/// (query, probe)), combined with @p term2 in threadgroup memory by the scan +/// kernel, and the coarse distance is added as the constant ||x - c||^2 term. +/// The scan keeps an exact running top-k over arbitrarily long lists and the +/// merge runs in rounds, so there is no list-length or nprobe*k cap; the +/// remaining requirements are k <= 512, M <= 64 and d/M <= 256. +/// onTheFly evaluates encountered codes directly (d <= 256), using the +/// supplied coarse centroids; shortLists requires every list to have <= 128 +/// entries and selects a smaller threadgroup and scratch allocation. +/// @p term2 may be nil for inner product (qterm is the whole table); +/// @p useDis0 adds the coarse distance (required for L2, by_residual for IP). +bool runMetalIVFPQPrecompSearch( + id device, + id queue, + id queries, + id coarseAssign, + id coarseDist, + id term2, + id qtermScratch, + id pqCentroids, + id codes, + id ids, + id listOffset, + id listLength, + int nq, + int d, + int M, + int k, + int nprobe, + bool isL2, + bool useDis0, + id outDistances, + id outIndices, + id perListDistBuf, + id perListIdxBuf, + id mergeScratchDistBuf, + id mergeScratchIdxBuf, + bool waitForCompletion = true, + id coarseCentroids = nil, + bool onTheFly = false, + bool shortLists = false, + bool compactMerge = true); + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.metal b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.metal index d2f96de47..94ecefbbd 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.metal +++ b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.metal @@ -434,16 +434,13 @@ kernel void l2_with_norms( // Shared params layout (device const uint*): // [0] nq [1] d [2] k [3] nprobe [4] want_min -inline bool ivf_better_int(float aDist, int aIdx, float bDist, int bIdx, uint want_min) { - constexpr float tie_eps = 1e-6f; - float delta = aDist - bDist; - bool strictly = want_min ? (delta < -tie_eps) : (delta > tie_eps); - if (strictly) return true; - if (fabs(delta) <= tie_eps) return aIdx < bIdx; - return false; -} - -inline bool ivf_better_long(float aDist, long aIdx, float bDist, long bIdx, uint want_min) { +template +inline bool ivf_better( + float aDist, + IndexT aIdx, + float bDist, + IndexT bIdx, + uint want_min) { constexpr float tie_eps = 1e-6f; float delta = aDist - bDist; bool strictly = want_min ? (delta < -tie_eps) : (delta > tie_eps); @@ -557,7 +554,7 @@ kernel void ivf_scan_list( localDist[pos] = dist; localIdx [pos] = vi; while (pos > 0) { - bool sw = ivf_better_int( + bool sw = ivf_better( localDist[pos], localIdx[pos], localDist[pos - 1], localIdx[pos - 1], want_min); @@ -586,11 +583,11 @@ kernel void ivf_scan_list( uint partner = idx ^ j; if (partner < CAND && partner > idx) { bool ascending = ((idx & k2) == 0); - bool pB = ivf_better_int( + bool pB = ivf_better( tgDist[partner], tgIdx[partner], tgDist[idx], tgIdx[idx], want_min); - bool iB = ivf_better_int( + bool iB = ivf_better( tgDist[idx], tgIdx[idx], tgDist[partner], tgIdx[partner], want_min); @@ -709,7 +706,7 @@ kernel void ivf_scan_list_small( int vi = (int)vecIdx; - bool better = ivf_better_int(dist, vi, bestDist, bestIdx, want_min); + bool better = ivf_better(dist, vi, bestDist, bestIdx, want_min); if (better) { bestDist = dist; bestIdx = vi; @@ -728,11 +725,11 @@ kernel void ivf_scan_list_small( uint partner = tid ^ j; if (partner < CAND && partner > tid) { bool ascending = ((tid & k2) == 0); - bool pB = ivf_better_int( + bool pB = ivf_better( tgDist[partner], tgIdx[partner], tgDist[tid], tgIdx[tid], want_min); - bool iB = ivf_better_int( + bool iB = ivf_better( tgDist[tid], tgIdx[tid], tgDist[partner], tgIdx[partner], want_min); @@ -875,7 +872,7 @@ kernel void ivf_scan_list_interleaved( localDist[pos] = dist; localIdx [pos] = vi; while (pos > 0) { - bool sw = ivf_better_int( + bool sw = ivf_better( localDist[pos], localIdx[pos], localDist[pos - 1], localIdx[pos - 1], want_min); @@ -904,11 +901,11 @@ kernel void ivf_scan_list_interleaved( uint partner = idx ^ j; if (partner < CAND && partner > idx) { bool ascending = ((idx & k2) == 0); - bool pB = ivf_better_int( + bool pB = ivf_better( tgDist[partner], tgIdx[partner], tgDist[idx], tgIdx[idx], want_min); - bool iB = ivf_better_int( + bool iB = ivf_better( tgDist[idx], tgIdx[idx], tgDist[partner], tgIdx[partner], want_min); @@ -982,7 +979,7 @@ kernel void ivf_merge_lists( localDist[pos] = d; localIdx [pos] = v; while (pos > 0) { - bool sw = ivf_better_long( + bool sw = ivf_better( localDist[pos], localIdx[pos], localDist[pos - 1], localIdx[pos - 1], want_min); @@ -1010,11 +1007,11 @@ kernel void ivf_merge_lists( uint partner = idx ^ j; if (partner < CAND && partner > idx) { bool ascending = ((idx & k2) == 0); - bool pB = ivf_better_long( + bool pB = ivf_better( tgDist[partner], tgIdx[partner], tgDist[idx], tgIdx[idx], want_min); - bool iB = ivf_better_long( + bool iB = ivf_better( tgDist[idx], tgIdx[idx], tgDist[partner], tgIdx[partner], want_min); @@ -1077,3 +1074,1523 @@ inline float sq6_decode_component(device const uchar* code, uint i) { return (float(bits) + 0.5f) / 63.0f; } + +// IVF-PQ scan kernel (8-bit codes) +// ============================================================ +// +// One threadgroup per (query, probe). Layout matches ivf_scan_list: +// output is per-list top-k in perListDist/perListIdx. +// +// lookupTable layout: (nq * nprobe) * M * 256 floats +// For entry (qi, probe), offset = (qi * nprobe + probe) * M * 256 +// table[m * 256 + code] gives the partial distance contribution. +// +// params: [nq, M, k, nprobe, want_min] + +// ============================================================ +// IVFPQ LUT build kernels +// ============================================================ +// +// Build lookup table layout: (nq * nprobe * M * 256), contiguous. +// For each (qi, pi, m, c): +// L2: tab = || (q_m - coarse_m) - pq[m][c] ||^2 +// IP: tab = +// +// params: [nq, d, M, nprobe] + +kernel void ivfpq_build_lut_l2( + device const float* queries [[buffer(0)]], + device const int* coarseAssign [[buffer(1)]], + device const float* coarseCentroids [[buffer(2)]], + device const float* pqCentroids [[buffer(3)]], + device float* outLookup [[buffer(4)]], + constant uint* params [[buffer(5)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nq = params[0]; + uint d = params[1]; + uint M = params[2]; + uint nprobe = params[3]; + if (M == 0 || nprobe == 0) return; + uint dsub = d / M; + if (dsub == 0) return; + + uint totalTG = nq * nprobe * M; + if (tgid >= totalTG || tid >= 256) return; + uint m = tgid % M; + uint qp = tgid / M; + uint pi = qp % nprobe; + uint qi = qp / nprobe; + if (qi >= nq) return; + uint c = tid; + + int listNo = coarseAssign[qi * nprobe + pi]; + if (listNo < 0) { + outLookup[(tgid * 256) + c] = 1e38f; + return; + } + + threadgroup float tgResidual[256]; + uint qbase = qi * d + m * dsub; + uint cbase = uint(listNo) * d + m * dsub; + uint pqbase = ((m * 256 + c) * dsub); + for (uint j = tid; j < dsub; j += 256) { + tgResidual[j] = queries[qbase + j] - coarseCentroids[cbase + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + float diff = tgResidual[j] - pqCentroids[pqbase + j]; + acc += diff * diff; + } + outLookup[(tgid * 256) + c] = acc; +} + +kernel void ivfpq_build_lut_ip( + device const float* queries [[buffer(0)]], + device const int* coarseAssign [[buffer(1)]], + device const float* coarseCentroids [[buffer(2)]], + device const float* pqCentroids [[buffer(3)]], + device float* outLookup [[buffer(4)]], + constant uint* params [[buffer(5)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + (void)coarseAssign; + (void)coarseCentroids; + + uint nq = params[0]; + uint d = params[1]; + uint M = params[2]; + uint nprobe = params[3]; + if (M == 0 || nprobe == 0) return; + uint dsub = d / M; + if (dsub == 0) return; + + uint totalTG = nq * nprobe * M; + if (tgid >= totalTG || tid >= 256) return; + uint m = tgid % M; + uint qp = tgid / M; + uint qi = qp / nprobe; + if (qi >= nq) return; + uint c = tid; + + threadgroup float tgQuery[256]; + uint qbase = qi * d + m * dsub; + uint pqbase = ((m * 256 + c) * dsub); + for (uint j = tid; j < dsub; j += 256) { + tgQuery[j] = queries[qbase + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + acc += tgQuery[j] * pqCentroids[pqbase + j]; + } + outLookup[(tgid * 256) + c] = acc; +} + +kernel void ivfpq_build_lut_l2_f16( + device const float* queries [[buffer(0)]], + device const int* coarseAssign [[buffer(1)]], + device const float* coarseCentroids [[buffer(2)]], + device const float* pqCentroids [[buffer(3)]], + device half* outLookup [[buffer(4)]], + constant uint* params [[buffer(5)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nq = params[0]; + uint d = params[1]; + uint M = params[2]; + uint nprobe = params[3]; + if (M == 0 || nprobe == 0) return; + uint dsub = d / M; + if (dsub == 0) return; + + uint totalTG = nq * nprobe * M; + if (tgid >= totalTG || tid >= 256) return; + uint m = tgid % M; + uint qp = tgid / M; + uint pi = qp % nprobe; + uint qi = qp / nprobe; + if (qi >= nq) return; + uint c = tid; + + int listNo = coarseAssign[qi * nprobe + pi]; + if (listNo < 0) { + outLookup[(tgid * 256) + c] = half(65504.0f); + return; + } + + threadgroup float tgResidual[256]; + uint qbase = qi * d + m * dsub; + uint cbase = uint(listNo) * d + m * dsub; + uint pqbase = ((m * 256 + c) * dsub); + for (uint j = tid; j < dsub; j += 256) { + tgResidual[j] = queries[qbase + j] - coarseCentroids[cbase + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + float diff = tgResidual[j] - pqCentroids[pqbase + j]; + acc += diff * diff; + } + outLookup[(tgid * 256) + c] = half(acc); +} + +kernel void ivfpq_build_lut_ip_f16( + device const float* queries [[buffer(0)]], + device const int* coarseAssign [[buffer(1)]], + device const float* coarseCentroids [[buffer(2)]], + device const float* pqCentroids [[buffer(3)]], + device half* outLookup [[buffer(4)]], + constant uint* params [[buffer(5)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + (void)coarseAssign; + (void)coarseCentroids; + + uint nq = params[0]; + uint d = params[1]; + uint M = params[2]; + uint nprobe = params[3]; + if (M == 0 || nprobe == 0) return; + uint dsub = d / M; + if (dsub == 0) return; + + uint totalTG = nq * nprobe * M; + if (tgid >= totalTG || tid >= 256) return; + uint m = tgid % M; + uint qp = tgid / M; + uint qi = qp / nprobe; + if (qi >= nq) return; + uint c = tid; + + threadgroup float tgQuery[256]; + uint qbase = qi * d + m * dsub; + uint pqbase = ((m * 256 + c) * dsub); + for (uint j = tid; j < dsub; j += 256) { + tgQuery[j] = queries[qbase + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + acc += tgQuery[j] * pqCentroids[pqbase + j]; + } + outLookup[(tgid * 256) + c] = half(acc); +} + +kernel void ivf_scan_list_pq8( + device const float* lookupTable [[buffer(0)]], + device const uchar* codes [[buffer(1)]], + device const long* ids [[buffer(2)]], + device const uint* listOffset [[buffer(3)]], + device const uint* listLength [[buffer(4)]], + device const int* coarseAssign [[buffer(5)]], + device float* perListDist [[buffer(6)]], + device long* perListIdx [[buffer(7)]], + device const uint* params [[buffer(8)]], + device const float* coarseDist [[buffer(9)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + constexpr uint TG_SIZE = 256; + constexpr uint LOCAL_K = 4; + + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint useDis0 = params[5]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + + int list_no = coarseAssign[qi * nprobe + pi]; + if (list_no < 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + return; + } + + uint lOff = listOffset[(uint)list_no]; + uint lLen = listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + return; + } + + uint tableOff = (qi * nprobe + pi) * M * 256; + + // Inner product needs the coarse score: the table holds only. + // L2 tables hold the complete residual distance, so dis0 stays 0. + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + + float localDist[LOCAL_K]; + int localIdx [LOCAL_K]; + uint localCount = 0; + for (uint i = 0; i < LOCAL_K; i++) { + localDist[i] = sentinel; + localIdx [i] = -1; + } + + for (uint li = tid; li < lLen; li += TG_SIZE) { + uint vecIdx = lOff + li; + device const uchar* cvec = codes + vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; m++) { + dist += lookupTable[tableOff + m * 256 + uint(cvec[m])]; + } + + int vi = (int)vecIdx; + + bool better = want_min ? (dist < localDist[LOCAL_K-1]) + : (dist > localDist[LOCAL_K-1]); + if (localCount < LOCAL_K || better) { + uint pos = (localCount < LOCAL_K) ? localCount : LOCAL_K - 1; + localDist[pos] = dist; + localIdx [pos] = vi; + while (pos > 0) { + bool sw = want_min + ? (localDist[pos] < localDist[pos-1] || (localDist[pos] == localDist[pos-1] && localIdx[pos] < localIdx[pos-1])) + : (localDist[pos] > localDist[pos-1] || (localDist[pos] == localDist[pos-1] && localIdx[pos] < localIdx[pos-1])); + if (!sw) break; + float td = localDist[pos]; localDist[pos] = localDist[pos-1]; localDist[pos-1] = td; + int ti = localIdx [pos]; localIdx [pos] = localIdx [pos-1]; localIdx [pos-1] = ti; + pos--; + } + if (localCount < LOCAL_K) localCount++; + } + } + + constexpr uint CAND = TG_SIZE * LOCAL_K; + threadgroup float tgDist[CAND]; + threadgroup int tgIdx [CAND]; + + for (uint i = 0; i < LOCAL_K; i++) { + tgDist[tid * LOCAL_K + i] = (i < localCount) ? localDist[i] : sentinel; + tgIdx [tid * LOCAL_K + i] = (i < localCount) ? localIdx [i] : -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (uint k2 = 2; k2 <= CAND; k2 *= 2) { + for (uint j = k2 >> 1; j > 0; j >>= 1) { + for (uint idx = tid; idx < CAND; idx += TG_SIZE) { + uint partner = idx ^ j; + if (partner < CAND && partner > idx) { + bool ascending = ((idx & k2) == 0); + bool pB = want_min + ? (tgDist[partner] < tgDist[idx] || (tgDist[partner] == tgDist[idx] && tgIdx[partner] < tgIdx[idx])) + : (tgDist[partner] > tgDist[idx] || (tgDist[partner] == tgDist[idx] && tgIdx[partner] < tgIdx[idx])); + bool iB = want_min + ? (tgDist[idx] < tgDist[partner] || (tgDist[idx] == tgDist[partner] && tgIdx[idx] < tgIdx[partner])) + : (tgDist[idx] > tgDist[partner] || (tgDist[idx] == tgDist[partner] && tgIdx[idx] < tgIdx[partner])); + if (ascending ? pB : iB) { + float td = tgDist[idx]; tgDist[idx] = tgDist[partner]; tgDist[partner] = td; + int ti = tgIdx [idx]; tgIdx [idx] = tgIdx [partner]; tgIdx [partner] = ti; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + uint kk = min(k, CAND); + for (uint i = tid; i < kk; i += TG_SIZE) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx [outBase + i] = (vi < 0) ? -1L : ids[vi]; + } + for (uint i = tid; i < k - kk; i += TG_SIZE) { + perListDist[outBase + kk + i] = sentinel; + perListIdx [outBase + kk + i] = -1L; + } +} + +kernel void ivf_scan_list_pq8_f16( + device const half* lookupTable [[buffer(0)]], + device const uchar* codes [[buffer(1)]], + device const long* ids [[buffer(2)]], + device const uint* listOffset [[buffer(3)]], + device const uint* listLength [[buffer(4)]], + device const int* coarseAssign [[buffer(5)]], + device float* perListDist [[buffer(6)]], + device long* perListIdx [[buffer(7)]], + device const uint* params [[buffer(8)]], + device const float* coarseDist [[buffer(9)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + constexpr uint TG_SIZE = 256; + constexpr uint LOCAL_K = 4; + + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint useDis0 = params[5]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + + int list_no = coarseAssign[qi * nprobe + pi]; + if (list_no < 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + uint lOff = listOffset[(uint)list_no]; + uint lLen = listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + uint tableOff = (qi * nprobe + pi) * M * 256; + + // Inner product needs the coarse score: the table holds only. + // L2 tables hold the complete residual distance, so dis0 stays 0. + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + + float localDist[LOCAL_K]; + int localIdx[LOCAL_K]; + uint localCount = 0; + for (uint i = 0; i < LOCAL_K; i++) { + localDist[i] = sentinel; + localIdx[i] = -1; + } + + for (uint li = tid; li < lLen; li += TG_SIZE) { + uint vecIdx = lOff + li; + device const uchar* cvec = codes + vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; m++) { + dist += float(lookupTable[tableOff + m * 256 + uint(cvec[m])]); + } + + int vi = (int)vecIdx; + bool better = want_min ? (dist < localDist[LOCAL_K - 1]) + : (dist > localDist[LOCAL_K - 1]); + if (localCount < LOCAL_K || better) { + uint pos = (localCount < LOCAL_K) ? localCount : LOCAL_K - 1; + localDist[pos] = dist; + localIdx[pos] = vi; + while (pos > 0) { + bool sw = want_min + ? (localDist[pos] < localDist[pos - 1] || + (localDist[pos] == localDist[pos - 1] && + localIdx[pos] < localIdx[pos - 1])) + : (localDist[pos] > localDist[pos - 1] || + (localDist[pos] == localDist[pos - 1] && + localIdx[pos] < localIdx[pos - 1])); + if (!sw) break; + float td = localDist[pos]; + localDist[pos] = localDist[pos - 1]; + localDist[pos - 1] = td; + int ti = localIdx[pos]; + localIdx[pos] = localIdx[pos - 1]; + localIdx[pos - 1] = ti; + pos--; + } + if (localCount < LOCAL_K) localCount++; + } + } + + constexpr uint CAND = TG_SIZE * LOCAL_K; + threadgroup float tgDist[CAND]; + threadgroup int tgIdx[CAND]; + + for (uint i = 0; i < LOCAL_K; i++) { + tgDist[tid * LOCAL_K + i] = (i < localCount) ? localDist[i] : sentinel; + tgIdx[tid * LOCAL_K + i] = (i < localCount) ? localIdx[i] : -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (uint k2 = 2; k2 <= CAND; k2 *= 2) { + for (uint j = k2 >> 1; j > 0; j >>= 1) { + for (uint idx = tid; idx < CAND; idx += TG_SIZE) { + uint partner = idx ^ j; + if (partner < CAND && partner > idx) { + bool ascending = ((idx & k2) == 0); + bool pB = want_min + ? (tgDist[partner] < tgDist[idx] || + (tgDist[partner] == tgDist[idx] && + tgIdx[partner] < tgIdx[idx])) + : (tgDist[partner] > tgDist[idx] || + (tgDist[partner] == tgDist[idx] && + tgIdx[partner] < tgIdx[idx])); + bool iB = want_min + ? (tgDist[idx] < tgDist[partner] || + (tgDist[idx] == tgDist[partner] && + tgIdx[idx] < tgIdx[partner])) + : (tgDist[idx] > tgDist[partner] || + (tgDist[idx] == tgDist[partner] && + tgIdx[idx] < tgIdx[partner])); + if (ascending ? pB : iB) { + float td = tgDist[idx]; + tgDist[idx] = tgDist[partner]; + tgDist[partner] = td; + int ti = tgIdx[idx]; + tgIdx[idx] = tgIdx[partner]; + tgIdx[partner] = ti; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + uint kk = min(k, CAND); + for (uint i = tid; i < kk; i += TG_SIZE) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx[outBase + i] = (vi < 0) ? -1L : ids[vi]; + } + for (uint i = tid; i < k - kk; i += TG_SIZE) { + perListDist[outBase + kk + i] = sentinel; + perListIdx[outBase + kk + i] = -1L; + } +} + +// Small-list IVFPQ variant: lower threadgroup/barrier cost when average list +// length is short. +kernel void ivf_scan_list_pq8_small( + device const float* lookupTable [[buffer(0)]], + device const uchar* codes [[buffer(1)]], + device const long* ids [[buffer(2)]], + device const uint* listOffset [[buffer(3)]], + device const uint* listLength [[buffer(4)]], + device const int* coarseAssign [[buffer(5)]], + device float* perListDist [[buffer(6)]], + device long* perListIdx [[buffer(7)]], + device const uint* params [[buffer(8)]], + device const float* coarseDist [[buffer(9)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + constexpr uint TG_SIZE = 32; + constexpr uint LOCAL_K = 1; + + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint useDis0 = params[5]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + + int list_no = coarseAssign[qi * nprobe + pi]; + if (list_no < 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + return; + } + + uint lOff = listOffset[(uint)list_no]; + uint lLen = listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += TG_SIZE) { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + return; + } + + uint tableOff = (qi * nprobe + pi) * M * 256; + + // Inner product needs the coarse score: the table holds only. + // L2 tables hold the complete residual distance, so dis0 stays 0. + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + + float bestDist = sentinel; + int bestIdx = -1; + for (uint li = tid; li < lLen; li += TG_SIZE) { + uint vecIdx = lOff + li; + device const uchar* cvec = codes + vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; m++) { + dist += lookupTable[tableOff + m * 256 + uint(cvec[m])]; + } + + int vi = (int)vecIdx; + bool better = want_min + ? (dist < bestDist || (dist == bestDist && vi < bestIdx)) + : (dist > bestDist || (dist == bestDist && vi < bestIdx)); + if (better) { + bestDist = dist; + bestIdx = vi; + } + } + + constexpr uint CAND = TG_SIZE * LOCAL_K; + threadgroup float tgDist[CAND]; + threadgroup int tgIdx[CAND]; + tgDist[tid] = bestDist; + tgIdx[tid] = bestIdx; + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (uint k2 = 2; k2 <= CAND; k2 *= 2) { + for (uint j = k2 >> 1; j > 0; j >>= 1) { + uint partner = tid ^ j; + if (partner < CAND && partner > tid) { + bool ascending = ((tid & k2) == 0); + bool pB = want_min + ? (tgDist[partner] < tgDist[tid] || + (tgDist[partner] == tgDist[tid] && + tgIdx[partner] < tgIdx[tid])) + : (tgDist[partner] > tgDist[tid] || + (tgDist[partner] == tgDist[tid] && + tgIdx[partner] < tgIdx[tid])); + bool iB = want_min + ? (tgDist[tid] < tgDist[partner] || + (tgDist[tid] == tgDist[partner] && + tgIdx[tid] < tgIdx[partner])) + : (tgDist[tid] > tgDist[partner] || + (tgDist[tid] == tgDist[partner] && + tgIdx[tid] < tgIdx[partner])); + if (ascending ? pB : iB) { + float td = tgDist[tid]; + tgDist[tid] = tgDist[partner]; + tgDist[partner] = td; + int ti = tgIdx[tid]; + tgIdx[tid] = tgIdx[partner]; + tgIdx[partner] = ti; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + uint kk = min(k, CAND); + for (uint i = tid; i < kk; i += TG_SIZE) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx[outBase + i] = (vi < 0) ? -1L : ids[vi]; + } + for (uint i = tid; i < k - kk; i += TG_SIZE) { + perListDist[outBase + kk + i] = sentinel; + perListIdx[outBase + kk + i] = -1L; + } +} + +// ============================================================ +// IVF-PQ precomputed-table search path +// ============================================================ +// +// Mirrors faiss::IndexIVFPQ use_precomputed_table for L2/by_residual: +// +// ||x - (c + pq)||^2 = ||x - c||^2 (coarse distance, dis0) +// + (||pq||^2 + 2) (term2: per index, once) +// - 2 (qterm: per query, once) +// +// term2 is built once per index (nlist * M * 256), qterm once per query +// batch (nq * M * 256). The scan kernel adds the two tables into threadgroup +// memory per (query, probe) and streams the list codes against it, so no +// per-(query, probe) lookup table is ever written to device memory. +// +// For inner product the score is + : qterm holds and +// dis0 is the coarse score (term2 unused). +// +// The scan keeps an exact running top-k over segments of PQPRE_SEG codes: +// per segment, candidates that beat the current k-th best are gathered via a +// threadgroup atomic and re-merged with a bitonic sort sized to the actual +// candidate count. Exact for any list length; requires k <= PQPRE_MAX_K. + +constant constexpr uint PQPRE_TG = 256; +constant constexpr uint PQPRE_SEG = 512; +constant constexpr uint PQPRE_MAX_K = 512; +constant constexpr uint PQPRE_CAND = PQPRE_MAX_K + PQPRE_SEG; // 1024 +constant constexpr uint PQPRE_LUT_MAX = 16 * 256; // M <= 16 + +// Bitonic sort over tgDist/tgIdx[0..n), n a power of two. Sorted best-first. +template +inline void ivf_tg_bitonic( + threadgroup float* tgDist, + threadgroup IndexT* tgIdx, + uint n, + uint tid, + uint want_min +) { + for (uint k2 = 2; k2 <= n; k2 *= 2) { + for (uint j = k2 >> 1; j > 0; j >>= 1) { + for (uint idx = tid; idx < n; idx += ThreadgroupSize) { + uint partner = idx ^ j; + if (partner < n && partner > idx) { + bool ascending = ((idx & k2) == 0); + bool pB = ivf_better( + tgDist[partner], tgIdx[partner], + tgDist[idx], tgIdx[idx], want_min); + bool iB = ivf_better( + tgDist[idx], tgIdx[idx], + tgDist[partner], tgIdx[partner], want_min); + if (ascending ? pB : iB) { + float td = tgDist[idx]; + tgDist[idx] = tgDist[partner]; + tgDist[partner] = td; + IndexT ti = tgIdx[idx]; + tgIdx[idx] = tgIdx[partner]; + tgIdx[partner] = ti; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } +} + +inline uint ivf_next_pow2(uint v) { + uint p = 1; + while (p < v) p <<= 1; + return p; +} + +// term2[(l * M + m) * 256 + c] = ||pq[m][c]||^2 + 2 +// One threadgroup per (l, m), one thread per code c. Run once per index. +// params: [nlist, d, M] +kernel void ivfpq_precompute_term2( + device const float* coarseCentroids [[buffer(0)]], + device const float* pqCentroids [[buffer(1)]], + device float* outTerm2 [[buffer(2)]], + constant uint* params [[buffer(3)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nlist = params[0]; + uint d = params[1]; + uint M = params[2]; + if (M == 0) return; + uint dsub = d / M; + if (dsub == 0 || dsub > 256) return; + + uint m = tgid % M; + uint l = tgid / M; + if (l >= nlist || tid >= 256) return; + uint c = tid; + + threadgroup float tgC[256]; + for (uint j = tid; j < dsub; j += 256) { + tgC[j] = coarseCentroids[l * d + m * dsub + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint pqbase = (m * 256 + c) * dsub; + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + float p = pqCentroids[pqbase + j]; + acc += p * p + 2.0f * tgC[j] * p; + } + outTerm2[(l * M + m) * 256 + c] = acc; +} + +// qterm[(qi * M + m) * 256 + c] = -2 (L2) +// = (IP) +// One threadgroup per (qi, m), one thread per code c. Run once per batch. +// params: [nq, d, M, isL2] +kernel void ivfpq_build_query_term( + device const float* queries [[buffer(0)]], + device const float* pqCentroids [[buffer(1)]], + device float* outQTerm [[buffer(2)]], + constant uint* params [[buffer(3)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nq = params[0]; + uint d = params[1]; + uint M = params[2]; + uint isL2 = params[3]; + if (M == 0) return; + uint dsub = d / M; + if (dsub == 0 || dsub > 256) return; + + uint m = tgid % M; + uint qi = tgid / M; + if (qi >= nq || tid >= 256) return; + uint c = tid; + + threadgroup float tgQ[256]; + for (uint j = tid; j < dsub; j += 256) { + tgQ[j] = queries[qi * d + m * dsub + j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint pqbase = (m * 256 + c) * dsub; + float acc = 0.0f; + for (uint j = 0; j < dsub; ++j) { + acc += tgQ[j] * pqCentroids[pqbase + j]; + } + outQTerm[(qi * M + m) * 256 + c] = isL2 ? (-2.0f * acc) : acc; +} + +// Scan with precomputed tables. One threadgroup per (query, probe). +// The M*256 lookup table is assembled in threadgroup memory as +// qterm[qi] (+ term2[list_no] when useTerm2), then the list is streamed in +// segments of PQPRE_SEG codes. A running, sorted top-k is kept in tgDist[0..k); +// per segment only candidates beating the current k-th best are gathered +// (threadgroup atomic) and re-merged with a bitonic sort sized to the actual +// candidate count. Exact for any list length when k <= PQPRE_MAX_K. +// params: [nq, M, k, nprobe, want_min, useTerm2, useDis0] +kernel void ivf_scan_list_pq8_precomp( + device const float* term2 [[buffer(0)]], + device const float* qterm [[buffer(1)]], + device const float* coarseDist [[buffer(2)]], + device const uchar* codes [[buffer(3)]], + device const long* ids [[buffer(4)]], + device const uint* listOffset [[buffer(5)]], + device const uint* listLength [[buffer(6)]], + device const int* coarseAssign [[buffer(7)]], + device float* perListDist [[buffer(8)]], + device long* perListIdx [[buffer(9)]], + constant uint* params [[buffer(10)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint useTerm2 = params[5]; + uint useDis0 = params[6]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) + return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + if (k > PQPRE_MAX_K || M > PQPRE_LUT_MAX / 256) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + int list_no = coarseAssign[qi * nprobe + pi]; + uint lLen = (list_no < 0) ? 0u : listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + return; + } + + threadgroup float tgLUT[PQPRE_LUT_MAX]; + threadgroup float tgDist[PQPRE_CAND]; + threadgroup int tgIdx [PQPRE_CAND]; + threadgroup float tgThresh; + threadgroup atomic_uint tgCount; + + // Assemble the per-(query, probe) lookup table in threadgroup memory. + uint lutN = M * 256; + uint qBase = qi * lutN; + uint t2Base = (uint)list_no * lutN; + for (uint i = tid; i < lutN; i += PQPRE_TG) { + tgLUT[i] = qterm[qBase + i] + (useTerm2 ? term2[t2Base + i] : 0.0f); + } + if (tid == 0) { + tgThresh = sentinel; + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + uint lOff = listOffset[(uint)list_no]; + uint kk = 0; // current size of the sorted running top-k (uniform) + + for (uint segStart = 0; segStart < lLen; segStart += PQPRE_SEG) { + uint segN = min(PQPRE_SEG, lLen - segStart); + float thresh = tgThresh; + bool haveK = (kk >= k); + + for (uint li = tid; li < segN; li += PQPRE_TG) { + uint vecIdx = lOff + segStart + li; + device const uchar* cv = codes + (ulong)vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; ++m) { + dist += tgLUT[m * 256 + (uint)cv[m]]; + } + bool accept = !haveK || + (want_min ? (dist < thresh) : (dist > thresh)); + if (accept) { + uint slot = atomic_fetch_add_explicit( + &tgCount, 1u, memory_order_relaxed); + tgDist[kk + slot] = dist; + tgIdx [kk + slot] = (int)vecIdx; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint count = atomic_load_explicit(&tgCount, memory_order_relaxed); + if (count > 0) { + uint total = kk + count; + uint paddedN = ivf_next_pow2(total); + for (uint i = total + tid; i < paddedN; i += PQPRE_TG) { + tgDist[i] = sentinel; + tgIdx [i] = -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + ivf_tg_bitonic(tgDist, tgIdx, paddedN, tid, want_min); + kk = min(k, total); + } + if (tid == 0) { + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + if (kk >= k) + tgThresh = tgDist[k - 1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + for (uint i = tid; i < k; i += PQPRE_TG) { + if (i < kk) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx [outBase + i] = (vi < 0) ? -1L : ids[vi]; + } else { + perListDist[outBase + i] = sentinel; + perListIdx [outBase + i] = -1L; + } + } +} + +// Large-dimensional fallback: stream the precomputed terms directly rather +// than allocating an M*256 threadgroup LUT. Selection remains segmented/exact. +kernel void ivf_scan_list_pq8_precomp_large( + device const float* term2 [[buffer(0)]], + device const float* qterm [[buffer(1)]], + device const float* coarseDist [[buffer(2)]], + device const uchar* codes [[buffer(3)]], + device const long* ids [[buffer(4)]], + device const uint* listOffset [[buffer(5)]], + device const uint* listLength [[buffer(6)]], + device const int* coarseAssign [[buffer(7)]], + device float* perListDist [[buffer(8)]], + device long* perListIdx [[buffer(9)]], + constant uint* params [[buffer(10)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]]) { + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint useTerm2 = params[5]; + uint useDis0 = params[6]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) + return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + if (k > PQPRE_MAX_K || M > 64) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + int list_no = coarseAssign[qi * nprobe + pi]; + uint lLen = (list_no < 0) ? 0u : listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + threadgroup float tgDist[PQPRE_CAND]; + threadgroup int tgIdx[PQPRE_CAND]; + threadgroup float tgThresh; + threadgroup atomic_uint tgCount; + + // Address the query and centroid terms without a threadgroup LUT. + uint lutN = M * 256; + uint qBase = qi * lutN; + uint t2Base = (uint)list_no * lutN; + if (tid == 0) { + tgThresh = sentinel; + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + uint lOff = listOffset[(uint)list_no]; + uint kk = 0; // current size of the sorted running top-k (uniform) + + for (uint segStart = 0; segStart < lLen; segStart += PQPRE_SEG) { + uint segN = min(PQPRE_SEG, lLen - segStart); + float thresh = tgThresh; + bool haveK = (kk >= k); + + for (uint li = tid; li < segN; li += PQPRE_TG) { + uint vecIdx = lOff + segStart + li; + device const uchar* cv = codes + (ulong)vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; ++m) { + uint idx = m * 256 + (uint)cv[m]; + dist += qterm[qBase + idx] + + (useTerm2 ? term2[t2Base + idx] : 0.0f); + } + bool accept = + !haveK || (want_min ? (dist < thresh) : (dist > thresh)); + if (accept) { + uint slot = atomic_fetch_add_explicit( + &tgCount, 1u, memory_order_relaxed); + tgDist[kk + slot] = dist; + tgIdx[kk + slot] = (int)vecIdx; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint count = atomic_load_explicit(&tgCount, memory_order_relaxed); + if (count > 0) { + uint total = kk + count; + uint paddedN = ivf_next_pow2(total); + for (uint i = total + tid; i < paddedN; i += PQPRE_TG) { + tgDist[i] = sentinel; + tgIdx[i] = -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + ivf_tg_bitonic(tgDist, tgIdx, paddedN, tid, want_min); + kk = min(k, total); + } + if (tid == 0) { + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + if (kk >= k) + tgThresh = tgDist[k - 1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + for (uint i = tid; i < k; i += PQPRE_TG) { + if (i < kk) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx[outBase + i] = (vi < 0) ? -1L : ids[vi]; + } else { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + } +} + +// For d <= 256, the codebook is small enough to reuse through the device cache. +// Evaluate only encountered codes: dis0 + sum(p*p - 2*(q-c)*p) for L2, +// or dis0 + sum(q*p) for IP. No M*256 table is needed, regardless of M. +// Buffers 0/1 contain coarse centroids/queries, not precomputed terms. +// This variant handles arbitrarily long lists in 512-code segments. +kernel void ivf_scan_list_pq8_onthefly( + device const float* coarseCentroids [[buffer(0)]], + device const float* queries [[buffer(1)]], + device const float* coarseDist [[buffer(2)]], + device const uchar* codes [[buffer(3)]], + device const long* ids [[buffer(4)]], + device const uint* listOffset [[buffer(5)]], + device const uint* listLength [[buffer(6)]], + device const int* coarseAssign [[buffer(7)]], + device float* perListDist [[buffer(8)]], + device long* perListIdx [[buffer(9)]], + constant uint* params [[buffer(10)]], + device const float* pqCentroids [[buffer(11)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]]) { + uint nq = params[0]; + uint M = params[1]; + uint k = params[2]; + uint nprobe = params[3]; + uint want_min = params[4]; + uint isL2 = params[5]; + uint useDis0 = params[6]; + + uint qi = tgid / nprobe; + uint pi = tgid % nprobe; + if (qi >= nq || k == 0) + return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint outBase = (qi * nprobe + pi) * k; + if (k > PQPRE_MAX_K || M == 0 || M > 64 || params[7] == 0 || + params[7] > 256 || params[7] % M != 0) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + int list_no = coarseAssign[qi * nprobe + pi]; + uint lLen = (list_no < 0) ? 0u : listLength[(uint)list_no]; + if (lLen == 0) { + for (uint i = tid; i < k; i += PQPRE_TG) { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + return; + } + + threadgroup float tgDist[PQPRE_CAND]; + threadgroup int tgIdx[PQPRE_CAND]; + threadgroup float tgThresh; + threadgroup atomic_uint tgCount; + + uint d = params[7]; + uint dsub = d / M; + threadgroup float residual[256]; + for (uint j = tid; j < d; j += PQPRE_TG) + residual[j] = queries[qi * d + j] - + (isL2 ? coarseCentroids[(uint)list_no * d + j] : 0.0f); + if (tid == 0) { + tgThresh = sentinel; + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + float dis0 = useDis0 ? coarseDist[qi * nprobe + pi] : 0.0f; + uint lOff = listOffset[(uint)list_no]; + uint kk = 0; // current size of the sorted running top-k (uniform) + + for (uint segStart = 0; segStart < lLen; segStart += PQPRE_SEG) { + uint segN = min(PQPRE_SEG, lLen - segStart); + float thresh = tgThresh; + bool haveK = (kk >= k); + + for (uint li = tid; li < segN; li += PQPRE_TG) { + uint vecIdx = lOff + segStart + li; + device const uchar* cv = codes + (ulong)vecIdx * M; + float dist = dis0; + for (uint m = 0; m < M; ++m) { + uint base = (m * 256 + (uint)cv[m]) * dsub; + for (uint j = 0; j < dsub; ++j) { + float p = pqCentroids[base + j]; + dist += isL2 ? p * p - 2.0f * residual[m * dsub + j] * p + : residual[m * dsub + j] * p; + } + } + bool accept = + !haveK || (want_min ? (dist < thresh) : (dist > thresh)); + if (accept) { + uint slot = atomic_fetch_add_explicit( + &tgCount, 1u, memory_order_relaxed); + tgDist[kk + slot] = dist; + tgIdx[kk + slot] = (int)vecIdx; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + uint count = atomic_load_explicit(&tgCount, memory_order_relaxed); + if (count > 0) { + uint total = kk + count; + uint paddedN = ivf_next_pow2(total); + for (uint i = total + tid; i < paddedN; i += PQPRE_TG) { + tgDist[i] = sentinel; + tgIdx[i] = -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + ivf_tg_bitonic(tgDist, tgIdx, paddedN, tid, want_min); + kk = min(k, total); + } + if (tid == 0) { + atomic_store_explicit(&tgCount, 0u, memory_order_relaxed); + if (kk >= k) + tgThresh = tgDist[k - 1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + for (uint i = tid; i < k; i += PQPRE_TG) { + if (i < kk) { + int vi = tgIdx[i]; + perListDist[outBase + i] = tgDist[i]; + perListIdx[outBase + i] = (vi < 0) ? -1L : ids[vi]; + } else { + perListDist[outBase + i] = sentinel; + perListIdx[outBase + i] = -1L; + } + } +} + +// All lists must have <= 128 codes (checked by the host). Four vectors share +// a 32-thread group, eight lanes per vector, to parallelize over subquantizers. +// The residual and sorting scratch occupy only 2 KiB of threadgroup memory. +// Buffers 0/1 contain coarse centroids/queries; params[7] is d (<= 256). +kernel void ivf_scan_list_pq8_onthefly_small( + device const float* coarseCentroids [[buffer(0)]], + device const float* queries [[buffer(1)]], + device const float* coarseDist [[buffer(2)]], + device const uchar* codes [[buffer(3)]], + device const long* ids [[buffer(4)]], + device const uint* listOffset [[buffer(5)]], + device const uint* listLength [[buffer(6)]], + device const int* coarseAssign [[buffer(7)]], + device float* perListDist [[buffer(8)]], + device long* perListIdx [[buffer(9)]], + constant uint* params [[buffer(10)]], + device const float* pqCentroids [[buffer(11)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]]) { + uint M = params[1], k = params[2], nprobe = params[3], want_min = params[4]; + uint isL2 = params[5], useDis0 = params[6], qi = tgid / nprobe; + if (qi >= params[0] || k == 0) + return; + int list = coarseAssign[tgid]; + uint len = list < 0 ? 0u : listLength[list]; + float sentinel = want_min ? 1e38f : -1e38f; + threadgroup float ds[128]; + threadgroup int ix[128]; + if (len > 128 || M > 64) + len = 0; + uint off = list < 0 ? 0u : listOffset[list]; + float dis0 = useDis0 ? coarseDist[tgid] : 0.0f; + uint d = params[7]; + if (M == 0 || M > 64 || k > PQPRE_MAX_K || d == 0 || d > 256 || + d % M != 0) { + for (uint i = tid; i < k; i += 32) { + perListDist[tgid * k + i] = sentinel; + perListIdx[tgid * k + i] = -1L; + } + return; + } + uint dsub = d / M; + threadgroup float residual[256]; + for (uint j = tid; j < d; j += 32) + residual[j] = queries[qi * d + j] - + (isL2 && list >= 0 ? coarseCentroids[uint(list) * d + j] + : 0.0f); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint li = tid / 8; li < ((len + 3) / 4) * 4; li += 4) { + uint vec = off + li; + device const uchar* cv = codes + (ulong)vec * M; + float dist = 0; + for (uint m = tid % 8; li < len && m < M; m += 8) { + uint base = (m * 256 + uint(cv[m])) * dsub; + for (uint j = 0; j < dsub; ++j) { + float p = pqCentroids[base + j]; + dist += isL2 ? p * p - 2.0f * residual[m * dsub + j] * p + : residual[m * dsub + j] * p; + } + } + dist += simd_shuffle_down(dist, 4); + dist += simd_shuffle_down(dist, 2); + dist += simd_shuffle_down(dist, 1); + if (li < len && tid % 8 == 0) { + ds[li] = dist + dis0; + ix[li] = int(vec); + } + } + uint padded = ivf_next_pow2(len); + for (uint i = len + tid; i < padded; i += 32) { + ds[i] = sentinel; + ix[i] = -1; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + ivf_tg_bitonic(ds, ix, padded, tid, want_min); + for (uint i = tid; i < k; i += 32) { + perListDist[tgid * k + i] = i < len ? ds[i] : sentinel; + perListIdx[tgid * k + i] = i < len ? ids[ix[i]] : -1L; + } +} + +// Merge numLists per-query candidate lists (k entries each, best-first or +// sentinel-padded) in groups of groupSize lists per threadgroup. Output is +// nGroups = ceil(numLists / groupSize) lists of k per query. Run repeatedly +// (ping-pong) until one list remains; exact for any nprobe * k as long as +// groupSize * k <= MERGE_GROUP_CAND. +// params: [nq, numLists, groupSize, k, want_min, compact] +constant constexpr uint MERGE_GROUP_CAND = 2048; + +kernel void ivf_merge_lists_grouped( + device const float* inDist [[buffer(0)]], + device const long* inIdx [[buffer(1)]], + device float* outDist [[buffer(2)]], + device long* outIdx [[buffer(3)]], + constant uint* params [[buffer(4)]], + uint tgid [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]] +) { + uint nq = params[0]; + uint numLists = params[1]; + uint groupSize = params[2]; + uint k = params[3]; + uint want_min = params[4]; + if (numLists == 0 || groupSize == 0 || k == 0) + return; + if (groupSize * k > MERGE_GROUP_CAND) + return; + + uint nGroups = (numLists + groupSize - 1) / groupSize; + uint qi = tgid / nGroups; + uint g = tgid % nGroups; + if (qi >= nq) return; + + float sentinel = want_min ? 1e38f : -1e38f; + uint listStart = g * groupSize; + uint nLists = min(groupSize, numLists - listStart); + uint count = nLists * k; + + threadgroup float tgDist[MERGE_GROUP_CAND]; + threadgroup long tgIdx [MERGE_GROUP_CAND]; + threadgroup atomic_uint validCount; + + uint inBase = (qi * numLists + listStart) * k; + if (params[5]) { + // Short IVF lists often contribute far fewer than k results. Compact + // away their padding before sorting, especially for large k. + if (tid == 0) + atomic_store_explicit(&validCount, 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = tid; i < count; i += PQPRE_TG) { + long id = inIdx[inBase + i]; + if (id >= 0) { + uint slot = atomic_fetch_add_explicit( + &validCount, 1u, memory_order_relaxed); + tgDist[slot] = inDist[inBase + i]; + tgIdx[slot] = id; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + count = atomic_load_explicit(&validCount, memory_order_relaxed); + } else { + for (uint i = tid; i < count; i += PQPRE_TG) { + tgDist[i] = inDist[inBase + i]; + tgIdx[i] = inIdx[inBase + i]; + } + } + uint paddedN = ivf_next_pow2(count); + for (uint i = count + tid; i < paddedN; i += PQPRE_TG) { + tgDist[i] = sentinel; + tgIdx [i] = -1L; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + ivf_tg_bitonic(tgDist, tgIdx, paddedN, tid, want_min); + + uint outBase = (qi * nGroups + g) * k; + for (uint i = tid; i < k; i += PQPRE_TG) { + outDist[outBase + i] = i < count ? tgDist[i] : sentinel; + outIdx [outBase + i] = i < count ? tgIdx[i] : -1L; + } +} + +// CUDA's BinaryDistance.cu uses packed words when code strides permit them. +// Keep byte loads for odd strides: casting those rows to uint* is unaligned. +inline int hamming_code_distance( + device const uchar* query, + device const uchar* vector, + uint codeSize) { + int distance = 0; + if ((codeSize & 3u) == 0) { + auto q = reinterpret_cast(query); + auto v = reinterpret_cast(vector); + for (uint word = 0; word < codeSize / 4; ++word) { + distance += popcount(q[word] ^ v[word]); + } + } else { + for (uint byte = 0; byte < codeSize; ++byte) { + distance += popcount(uint(query[byte] ^ vector[byte])); + } + } + return distance; +} + +inline bool hamming_candidate_before(int a, uint ai, int b, uint bi) { + return a < b || (a == b && ai < bi); +} + +// Exact fused Hamming search. Like CUDA WarpSelect, retain only the requested +// k and reject candidates below the running cutoff before merging. Sort only +// new candidates; merge their sorted run into the existing top-k by parallel +// binary searches, rather than sorting 1024 entries after every segment. +// Like the other kernels in this file, scalar arguments travel in one params +// buffer with nq first. The host dispatches one threadgroup per query, and +// nq guards threadgroups beyond the grid, as the top-k kernels do. +// params: [nq, nb, code_size, k], 1 <= k <= 512. +kernel void hamming_distance_topk( + device const uchar* queries [[buffer(0)]], + device const uchar* database [[buffer(1)]], + device int* outDist [[buffer(2)]], + device long* outIdx [[buffer(3)]], + constant uint* params [[buffer(4)]], + uint qi [[threadgroup_position_in_grid]], + uint tid [[thread_position_in_threadgroup]]) { + constexpr uint SEG = 512; + constexpr uint TG = 256; + constexpr int INF = 0x7fffffff; + uint nq = params[0], nb = params[1], codeSize = params[2], k = params[3]; + if (qi >= nq) { + return; + } + threadgroup int bestDist[SEG], newDist[SEG], mergedDist[SEG]; + // The GPU envelope has at most UINT32_MAX vectors, so real labels fit + // uint and UINT32_MAX is free for padding. Widen only at the public int64 + // output; signed int would corrupt labels above INT32_MAX. + threadgroup uint bestIds[SEG], newIds[SEG], mergedIds[SEG]; + threadgroup atomic_uint count; + threadgroup int threshold; + for (uint i = tid; i < k; i += TG) { + bestDist[i] = INF; + bestIds[i] = 0xffffffffu; + } + if (tid == 0) { + atomic_store_explicit(&count, 0u, memory_order_relaxed); + threshold = INF; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device const uchar* query = queries + ulong(qi) * codeSize; + // 64-bit offsets/counters avoid overflow in the last uint32-sized segment. + for (ulong base = 0; base < nb; base += SEG) { + int cutoff = threshold; + for (uint i = tid; i < SEG; i += TG) { + ulong vi = base + i; + if (vi < nb) { + int distance = hamming_code_distance( + query, database + vi * codeSize, codeSize); + // All previous labels are smaller than this segment's labels, + // so equality cannot improve the deterministic (distance, ID) + // top-k. No truncation of candidates inside a thread occurs. + if (distance < cutoff) { + uint slot = atomic_fetch_add_explicit( + &count, 1u, memory_order_relaxed); + newDist[slot] = distance; + newIds[slot] = uint(vi); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint added = atomic_load_explicit(&count, memory_order_relaxed); + if (added > 0) { + uint padded = 1; + while (padded < added) + padded *= 2; + for (uint i = added + tid; i < padded; i += TG) { + newDist[i] = INF; + newIds[i] = 0xffffffffu; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint width = 2; width <= padded; width *= 2) { + for (uint stride = width / 2; stride > 0; stride /= 2) { + for (uint i = tid; i < padded; i += TG) { + uint j = i ^ stride; + if (j > i) { + bool swap = (i & width) == 0 + ? hamming_candidate_before( + newDist[j], + newIds[j], + newDist[i], + newIds[i]) + : hamming_candidate_before( + newDist[i], + newIds[i], + newDist[j], + newIds[j]); + if (swap) { + int dv = newDist[i]; + newDist[i] = newDist[j]; + newDist[j] = dv; + uint iv = newIds[i]; + newIds[i] = newIds[j]; + newIds[j] = iv; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + // Each candidate gets its unique rank in the merged order. Real + // labels are disjoint, and padding exists only in the old run. + for (uint i = tid; i < k; i += TG) { + int value = bestDist[i]; + uint id = bestIds[i]; + uint lo = 0, hi = added; + while (lo < hi) { + uint mid = (lo + hi) / 2; + if (hamming_candidate_before( + newDist[mid], newIds[mid], value, id)) + lo = mid + 1; + else + hi = mid; + } + uint rank = i + lo; + if (rank < k) { + mergedDist[rank] = value; + mergedIds[rank] = id; + } + } + for (uint i = tid; i < added; i += TG) { + int value = newDist[i]; + uint id = newIds[i]; + uint lo = 0, hi = k; + while (lo < hi) { + uint mid = (lo + hi) / 2; + if (hamming_candidate_before( + bestDist[mid], bestIds[mid], value, id)) + lo = mid + 1; + else + hi = mid; + } + uint rank = i + lo; + if (rank < k) { + mergedDist[rank] = value; + mergedIds[rank] = id; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = tid; i < k; i += TG) { + bestDist[i] = mergedDist[i]; + bestIds[i] = mergedIds[i]; + } + if (tid == 0) { + threshold = mergedDist[k - 1]; + atomic_store_explicit(&count, 0u, memory_order_relaxed); + } + } + // Even an empty merge must finish reading count in every thread before + // any thread starts appending candidates from the next segment. + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint i = tid; i < k; i += TG) { + outDist[ulong(qi) * k + i] = bestDist[i]; + outIdx[ulong(qi) * k + i] = + bestIds[i] == 0xffffffffu ? -1L : long(bestIds[i]); + } +} diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.mm b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.mm index a17e9d9ae..4540523aa 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalDistance.mm +++ b/thirdparty/faiss/faiss/gpu_metal/MetalDistance.mm @@ -355,5 +355,328 @@ bool runMetalIVFFlatFullSearch( return cmdBuf.status == MTLCommandBufferStatusCompleted; } +// ============================================================ +// runMetalIVFPQFullSearch +// ============================================================ + +bool runMetalIVFPQFullSearch( + id device, + id queue, + id queries, + id coarseAssign, + id coarseDist, + id coarseCentroids, + id pqCentroids, + id lookupTable, + id codes, + id ids, + id listOffset, + id listLength, + int nq, + int d, + int M, + int k, + int nprobe, + int nlist, + int avgListLen, + bool lookupFp16, + bool isL2, + id outDistances, + id outIndices, + id perListDistBuf, + id perListIdxBuf, + bool waitForCompletion) { + if (!device || !queue || !queries || !coarseAssign || !coarseDist || + !pqCentroids || !lookupTable || !codes || !ids || !listOffset || + !listLength || !outDistances || !outIndices || !perListDistBuf || + !perListIdxBuf) { + return false; + } + if (nq <= 0 || d <= 0 || M <= 0 || k <= 0 || nprobe <= 0 || nlist <= 0) + return false; + // LUT build stages subvectors in 256-wide threadgroup scratch: + // d / M > 256 (degenerate super-quantized shape) is unsupported. + if (isL2 && !coarseCentroids) + return false; + if (!fitsU32(nq) || !fitsU32(M) || !fitsU32(k) || !fitsU32(nprobe)) + return false; + + // The scan and merge kernels retain only kIvfReduceExactCandidates + // candidates (TG_SIZE * LOCAL_K). The result is exact only when both the + // merge input (nprobe * k) and every scanned list fit within that bound; + // otherwise fall back to the caller's CPU path. + if (!ivfMergeExactnessHolds(nprobe, k)) + return false; + if (!ivfScanExactnessHoldsForAllLists( + listLength, nlist, kIvfReduceExactCandidates)) { + return false; + } + + MetalKernels& K = getMetalKernels(device); + if (!K.isValid()) + return false; + + // params[5] selects the coarse-score term: inner-product tables hold + // only, so the per-(query, probe) coarse score is added + // during the scan. L2 tables hold the complete residual distance. + uint32_t sp[6] = { + (uint32_t)nq, + (uint32_t)M, + (uint32_t)k, + (uint32_t)nprobe, + isL2 ? 1u : 0u, + isL2 ? 0u : 1u}; + id paramsBuf = + [device newBufferWithBytes:sp + length:sizeof(sp) + options:MTLResourceStorageModeShared]; + if (!paramsBuf) + return false; + + id cmdBuf = [queue commandBuffer]; + id enc = [cmdBuf computeCommandEncoder]; + + // Step 1: build per-(query, probe) PQ lookup tables. + K.encodeIVFPQBuildLookupTables( + enc, + isL2, + lookupFp16, + queries, + coarseAssign, + coarseCentroids, + pqCentroids, + lookupTable, + nq, + d, + M, + nprobe); + + // Step 2: scan the assigned inverted lists with 8-bit ADC. The small-list + // kernel is exact only when every list is provably bounded. + (void)avgListLen; + const bool useSmall = !lookupFp16 && k <= (int)kIvfSmallExactCandidates && + ivfScanExactnessHoldsForAllLists( + listLength, nlist, kIvfSmallExactCandidates); + K.encodeIVFPQScanList( + enc, + useSmall, + lookupFp16, + lookupTable, + codes, + ids, + listOffset, + listLength, + coarseAssign, + perListDistBuf, + perListIdxBuf, + paramsBuf, + coarseDist, + nq, + nprobe); + + // Step 3: merge per-list top-k into the final top-k. + K.encodeIVFMergeLists( + enc, + perListDistBuf, + perListIdxBuf, + outDistances, + outIndices, + paramsBuf, + nq); + + [enc endEncoding]; + [cmdBuf commit]; + if (!waitForCompletion) + return true; + [cmdBuf waitUntilCompleted]; + return cmdBuf.status == MTLCommandBufferStatusCompleted; +} + +// ============================================================ +// IVF-PQ precomputed-table path +// ============================================================ + +// Must match the limits in MetalDistance.metal (PQPRE_* / MERGE_GROUP_CAND). +constexpr int kIvfPQPrecompMaxK = 512; +constexpr int kIvfPQPrecompMaxM = 64; +constexpr int kIvfPQPrecompMaxDsub = 256; +constexpr uint32_t kIvfMergeGroupCand = 2048; + +bool runMetalIVFPQPrecomputeTerm2( + id device, + id queue, + id coarseCentroids, + id pqCentroids, + id outTerm2, + int nlist, + int d, + int M) { + if (!device || !queue || !coarseCentroids || !pqCentroids || !outTerm2) + return false; + if (nlist <= 0 || d <= 0 || M <= 0 || (d % M) != 0) + return false; + if (M > kIvfPQPrecompMaxM || (d / M) > kIvfPQPrecompMaxDsub) + return false; + if (!fitsU32(nlist) || !fitsU32(d) || !fitsU32(M)) + return false; + + MetalKernels& K = getMetalKernels(device); + if (!K.isValid()) + return false; + + id cmdBuf = [queue commandBuffer]; + id enc = [cmdBuf computeCommandEncoder]; + K.encodeIVFPQPrecomputeTerm2( + enc, coarseCentroids, pqCentroids, outTerm2, nlist, d, M); + [enc endEncoding]; + [cmdBuf commit]; + [cmdBuf waitUntilCompleted]; + return cmdBuf.status == MTLCommandBufferStatusCompleted; +} + +bool runMetalIVFPQPrecompSearch( + id device, + id queue, + id queries, + id coarseAssign, + id coarseDist, + id term2, + id qtermScratch, + id pqCentroids, + id codes, + id ids, + id listOffset, + id listLength, + int nq, + int d, + int M, + int k, + int nprobe, + bool isL2, + bool useDis0, + id outDistances, + id outIndices, + id perListDistBuf, + id perListIdxBuf, + id mergeScratchDistBuf, + id mergeScratchIdxBuf, + bool waitForCompletion, + id coarseCentroids, + bool onTheFly, + bool shortLists, + bool compactMerge) { + if (!device || !queue || !queries || !coarseAssign || !coarseDist || + (!onTheFly && !qtermScratch) || !pqCentroids || !codes || !ids || + !listOffset || !listLength || !outDistances || !outIndices) { + return false; + } + if (nq <= 0 || d <= 0 || M <= 0 || k <= 0 || nprobe <= 0) + return false; + if ((d % M) != 0) + return false; + if (M > kIvfPQPrecompMaxM || (d / M) > kIvfPQPrecompMaxDsub) + return false; + if (k > kIvfPQPrecompMaxK) + return false; + if (onTheFly && (d > 256 || !coarseCentroids)) + return false; + if (isL2 && !onTheFly && !term2) + return false; + if (nprobe > 1 && + (!perListDistBuf || !perListIdxBuf || !mergeScratchDistBuf || + !mergeScratchIdxBuf)) { + return false; + } + if (!fitsU32(nq) || !fitsU32(d) || !fitsU32(M) || !fitsU32(k) || + !fitsU32(nprobe)) { + return false; + } + + MetalKernels& K = getMetalKernels(device); + if (!K.isValid()) + return false; + + const bool wantMin = isL2; + const bool useTerm2 = isL2; + + id cmdBuf = [queue commandBuffer]; + id enc = [cmdBuf computeCommandEncoder]; + + // Step 1: per-query M*256 term (once per batch, not per probe). + if (!onTheFly) + K.encodeIVFPQBuildQueryTerm( + enc, queries, pqCentroids, qtermScratch, nq, d, M, isL2); + + // Step 2: fused LUT-combine + list scan with exact running top-k. + // With a single probe the per-list result is the final result. + id scanDist = (nprobe == 1) ? outDistances : perListDistBuf; + id scanIdx = (nprobe == 1) ? outIndices : perListIdxBuf; + K.encodeIVFPQScanListPrecomp( + enc, + useTerm2 ? term2 : nil, + qtermScratch, + coarseDist, + codes, + ids, + listOffset, + listLength, + coarseAssign, + scanDist, + scanIdx, + nq, + M, + k, + nprobe, + wantMin, + useTerm2, + useDis0, + queries, + coarseCentroids, + pqCentroids, + d, + onTheFly, + shortLists); + + // Step 3: merge the nprobe per-list top-k in rounds of groupSize lists + // per threadgroup, ping-ponging between the per-list and scratch buffers. + if (nprobe > 1) { + const int groupSize = + std::max(2, (int)(kIvfMergeGroupCand / (uint32_t)k)); + int numLists = nprobe; + id curD = perListDistBuf; + id curI = perListIdxBuf; + id altD = mergeScratchDistBuf; + id altI = mergeScratchIdxBuf; + while (numLists > 1) { + const int nGroups = (numLists + groupSize - 1) / groupSize; + const bool last = (nGroups == 1); + K.encodeIVFMergeListsGrouped( + enc, + curD, + curI, + last ? outDistances : altD, + last ? outIndices : altI, + nq, + numLists, + groupSize, + k, + wantMin, + compactMerge); + if (!last) { + std::swap(curD, altD); + std::swap(curI, altI); + } + numLists = nGroups; + } + } + + [enc endEncoding]; + [cmdBuf commit]; + if (!waitForCompletion) + return true; + [cmdBuf waitUntilCompleted]; + return cmdBuf.status == MTLCommandBufferStatusCompleted; +} + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalIndex.h b/thirdparty/faiss/faiss/gpu_metal/MetalIndex.h index f40a4ca49..0b5d6ab6f 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalIndex.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalIndex.h @@ -24,6 +24,10 @@ struct MetalIndexConfig { bool useFloat16CoarseQuantizer = false; + /// Build the IVF-PQ distance lookup tables in half precision. Halves LUT + /// bandwidth during the GPU scan at a small accuracy cost. + bool useFloat16 = false; + faiss::gpu::IndicesOptions indicesOptions = faiss::gpu::INDICES_64_BIT; bool interleavedLayout = true; diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h b/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h new file mode 100644 index 000000000..8489cd8a2 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.h @@ -0,0 +1,69 @@ +// @lint-ignore-every LICENSELINT +/** + * Copyright (c) Meta Platforms, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include + +namespace faiss { +namespace gpu_metal { + +/// Exhaustive Hamming search over GPU-resident binary vectors. +/// Every positive dimension divisible by 8 is supported. GPU search is exact +/// for k <= 512, with ties ordered by increasing label. Larger k, selectors, +/// and counts exceeding uint32_t use the CPU copy. GPU failures throw rather +/// than silently falling back. Range search and remove_ids are not supported. +/// As with other Metal indexes, callers must serialize mutation and search. +class MetalIndexBinaryFlat : public faiss::IndexBinary { + public: + static constexpr int kMaxGpuK = 512; + + MetalIndexBinaryFlat(std::shared_ptr resources, int d); + MetalIndexBinaryFlat( + std::shared_ptr resources, + const faiss::IndexBinaryFlat* index); + ~MetalIndexBinaryFlat() override; + + MetalIndexBinaryFlat(const MetalIndexBinaryFlat&) = delete; + MetalIndexBinaryFlat& operator=(const MetalIndexBinaryFlat&) = delete; + + void add(idx_t n, const uint8_t* x) override; + void reset() override; + void search( + idx_t n, + const uint8_t* x, + idx_t k, + int32_t* distances, + idx_t* labels, + const SearchParameters* params = nullptr) const override; + void reconstruct(idx_t key, uint8_t* recons) const override; + + void copyFrom(const faiss::IndexBinaryFlat* index); + void copyTo(faiss::IndexBinaryFlat* index) const; + + std::shared_ptr getResources() const { + return resources_; + } + + private: + std::shared_ptr resources_; + faiss::IndexBinaryFlat cpuIndex_; + id vectorsBuf_ = nil; + // Search is synchronous and callers serialize access, so scratch buffers + // can be reused after waitUntilCompleted. ARC releases them on destruction. + mutable id queryBuf_ = nil; + mutable id distanceBuf_ = nil; + mutable id labelBuf_ = nil; + + id upload(const uint8_t* data, size_t bytes) const; +}; + +} // namespace gpu_metal +} // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.mm b/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.mm new file mode 100644 index 000000000..e872a6970 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu_metal/MetalIndexBinaryFlat.mm @@ -0,0 +1,260 @@ +// @lint-ignore-every LICENSELINT +/** + * Copyright (c) Meta Platforms, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "MetalIndexBinaryFlat.h" +#import "MetalKernels.h" + +#include +#include +#include +#include +#include + +namespace faiss { +namespace gpu_metal { +namespace { + +// Metal requires endEncoding even when pipeline lookup throws. +struct ComputeEncoderScope { + id encoder; + ~ComputeEncoderScope() { + [encoder endEncoding]; + } +}; + +size_t checkedBytes(idx_t count, size_t stride) { + FAISS_THROW_IF_NOT(count >= 0); + FAISS_THROW_IF_NOT( + uint64_t(count) <= std::numeric_limits::max() / stride); + return size_t(count) * stride; +} + +int checkedDimension(const faiss::IndexBinaryFlat* index) { + FAISS_THROW_IF_NOT(index); + FAISS_THROW_IF_NOT(index->d > 0 && index->d % 8 == 0); + return index->d; +} + +id reserveSearchBuffer( + id device, + id current, + size_t bytes) { + const size_t limit = device.maxBufferLength; + FAISS_THROW_IF_NOT(bytes > 0 && bytes <= limit); + const size_t capacity = current.length; + if (capacity >= bytes) { + return current; + } + const size_t doubled = capacity > limit / 2 ? limit : capacity * 2; + auto buffer = [device newBufferWithLength:std::max(bytes, doubled) + options:MTLResourceStorageModeShared]; + FAISS_THROW_IF_NOT_MSG( + buffer, "MetalIndexBinaryFlat: search allocation failed"); + return buffer; +} + +} // namespace + +MetalIndexBinaryFlat::MetalIndexBinaryFlat( + std::shared_ptr resources, + int dim) + : IndexBinary(dim), resources_(std::move(resources)), cpuIndex_(dim) { + FAISS_THROW_IF_NOT(dim > 0 && dim % 8 == 0); + FAISS_THROW_IF_NOT(resources_ && resources_->isAvailable()); + is_trained = true; +} + +MetalIndexBinaryFlat::MetalIndexBinaryFlat( + std::shared_ptr resources, + const faiss::IndexBinaryFlat* index) + : MetalIndexBinaryFlat(std::move(resources), checkedDimension(index)) { + copyFrom(index); +} + +MetalIndexBinaryFlat::~MetalIndexBinaryFlat() = default; + +id MetalIndexBinaryFlat::upload(const uint8_t* data, size_t bytes) + const { + if (bytes == 0) { + return nil; + } + auto device = resources_->getDevice(); + FAISS_THROW_IF_NOT(bytes <= device.maxBufferLength); + id buffer = + [device newBufferWithBytes:data + length:bytes + options:MTLResourceStorageModeShared]; + FAISS_THROW_IF_NOT_MSG(buffer, "MetalIndexBinaryFlat: allocation failed"); + return buffer; +} + +void MetalIndexBinaryFlat::add(idx_t n, const uint8_t* x) { + FAISS_THROW_IF_NOT(n >= 0); + if (n == 0) { + return; + } + FAISS_THROW_IF_NOT(x); + FAISS_THROW_IF_NOT(n <= std::numeric_limits::max() - ntotal); + size_t bytes = checkedBytes(ntotal + n, code_size); + auto device = resources_->getDevice(); + size_t limit = device.maxBufferLength; + FAISS_THROW_IF_NOT(bytes <= limit); + // Grow geometrically, capped before doubling to avoid overflow. Keep the + // replacement local until the CPU append succeeds, so allocation failure + // leaves both published copies and ntotal unchanged. + id buffer = vectorsBuf_; + size_t capacity = buffer.length; + size_t oldBytes = checkedBytes(ntotal, code_size); + if (bytes > capacity) { + size_t doubled = capacity > limit / 2 ? limit : capacity * 2; + size_t newCapacity = std::max(bytes, doubled); + buffer = [device newBufferWithLength:newCapacity + options:MTLResourceStorageModeShared]; + FAISS_THROW_IF_NOT_MSG( + buffer, "MetalIndexBinaryFlat: allocation failed"); + if (oldBytes) { + std::memcpy(buffer.contents, vectorsBuf_.contents, oldBytes); + } + } + cpuIndex_.add(n, x); + // The CPU append is the last throwing operation. Copy only the new codes + // from the owned CPU copy, which holds the canonical appended bytes. + std::memcpy( + static_cast(buffer.contents) + oldBytes, + cpuIndex_.xb.data() + oldBytes, + bytes - oldBytes); + vectorsBuf_ = buffer; + ntotal = cpuIndex_.ntotal; +} + +void MetalIndexBinaryFlat::reset() { + cpuIndex_.reset(); + vectorsBuf_ = nil; + queryBuf_ = nil; + distanceBuf_ = nil; + labelBuf_ = nil; + ntotal = 0; +} + +void MetalIndexBinaryFlat::search( + idx_t n, + const uint8_t* x, + idx_t k, + int32_t* distances, + idx_t* labels, + const SearchParameters* params) const { + FAISS_THROW_IF_NOT(n >= 0 && k > 0); + size_t count = checkedBytes(n, size_t(k)); + checkedBytes(n, checkedBytes(k, sizeof(idx_t))); + if (n == 0) { + return; + } + FAISS_THROW_IF_NOT(distances && labels); + if (ntotal == 0) { + std::fill_n(distances, count, std::numeric_limits::max()); + std::fill_n(labels, count, idx_t(-1)); + return; + } + FAISS_THROW_IF_NOT(x); + checkedBytes(n, code_size); + if (k > kMaxGpuK || (params && params->sel) || + uint64_t(n) > std::numeric_limits::max() || + uint64_t(ntotal) > std::numeric_limits::max()) { + cpuIndex_.search(n, x, k, distances, labels, params); + return; + } + + @autoreleasepool { + auto device = resources_->getDevice(); + size_t queryBytes = checkedBytes(n, code_size); + size_t distBytes = checkedBytes(n, checkedBytes(k, sizeof(int32_t))); + size_t labelBytes = checkedBytes(n, checkedBytes(k, sizeof(idx_t))); + // Prepare all replacements before publishing any of them. Partial + // allocation failure releases local replacements and retains the old + // scratch capacities; neither outputs nor database state are changed. + id queries = + reserveSearchBuffer(device, queryBuf_, queryBytes); + id outDist = + reserveSearchBuffer(device, distanceBuf_, distBytes); + id outIdx = + reserveSearchBuffer(device, labelBuf_, labelBytes); + FAISS_THROW_IF_NOT(queries && outDist && outIdx && vectorsBuf_); + queryBuf_ = queries; + distanceBuf_ = outDist; + labelBuf_ = outIdx; + std::memcpy(queries.contents, x, queryBytes); + auto& kernels = getMetalKernels(device); + FAISS_THROW_IF_NOT_MSG( + kernels.isValid(), "Metal Hamming library unavailable"); + id command = + [resources_->getCommandQueue() commandBuffer]; + FAISS_THROW_IF_NOT(command); + id encoder = [command computeCommandEncoder]; + FAISS_THROW_IF_NOT(encoder); + { + ComputeEncoderScope scope{encoder}; + kernels.encodeHammingDistanceTopK( + encoder, + queries, + vectorsBuf_, + outDist, + outIdx, + uint32_t(n), + uint32_t(ntotal), + uint32_t(code_size), + uint32_t(k)); + } + [command commit]; + [command waitUntilCompleted]; + FAISS_THROW_IF_NOT_MSG( + command.status == MTLCommandBufferStatusCompleted, + "MetalIndexBinaryFlat: GPU Hamming search failed"); + static_assert(sizeof(idx_t) == sizeof(int64_t)); + std::memcpy(distances, outDist.contents, distBytes); + std::memcpy(labels, outIdx.contents, labelBytes); + } +} + +void MetalIndexBinaryFlat::reconstruct(idx_t key, uint8_t* recons) const { + FAISS_THROW_IF_NOT(key >= 0 && key < ntotal && recons); + cpuIndex_.reconstruct(key, recons); +} + +void MetalIndexBinaryFlat::copyFrom(const faiss::IndexBinaryFlat* index) { + checkedDimension(index); + FAISS_THROW_IF_NOT(index->code_size == index->d / 8); + size_t bytes = checkedBytes(index->ntotal, index->code_size); + FAISS_THROW_IF_NOT(index->xb.size() == bytes); + faiss::IndexBinaryFlat replacement(*index); + // MaybeOwnedVector copies can retain a borrowed view. Always own the CPU + // backing bytes so reconstruction/fallback survive the source's lifetime. + replacement.xb = faiss::MaybeOwnedVector(bytes); + if (bytes) { + std::memcpy(replacement.xb.data(), index->xb.data(), bytes); + } + id buffer = upload(replacement.xb.data(), bytes); + cpuIndex_ = std::move(replacement); + vectorsBuf_ = buffer; + d = cpuIndex_.d; + code_size = cpuIndex_.code_size; + ntotal = cpuIndex_.ntotal; + is_trained = cpuIndex_.is_trained; + metric_type = cpuIndex_.metric_type; + verbose = cpuIndex_.verbose; +} + +void MetalIndexBinaryFlat::copyTo(faiss::IndexBinaryFlat* index) const { + FAISS_THROW_IF_NOT(index); + *index = cpuIndex_; + // The whole CPU copy transfers use_heap, query_batch_size, and the data. + // verbose lives on this object too, so forward it explicitly. + index->verbose = verbose; +} + +} // namespace gpu_metal +} // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h b/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h index 7b59be6ec..193fe520b 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.h @@ -75,13 +75,51 @@ class MetalIndexIVFPQ : public MetalIndex { std::unique_ptr cpuIndex_; std::unique_ptr gpuIvf_; + // Reusable GPU scratch buffers for the search path, grown on demand. + mutable id searchQueriesBuf_ = nil; + mutable id searchCoarseBuf_ = nil; + mutable id searchOutDistBuf_ = nil; + mutable id searchOutIdxBuf_ = nil; + mutable id searchPerListDistBuf_ = nil; + mutable id searchPerListIdxBuf_ = nil; + mutable id lookupTableBuf_ = nil; + mutable id lookupTableHalfBuf_ = nil; + mutable id searchCoarseDistBuf_ = nil; + mutable id searchQTermBuf_ = nil; + mutable id searchMergeDistBuf_ = nil; + mutable id searchMergeIdxBuf_ = nil; + mutable size_t searchQueriesCap_ = 0; + mutable size_t searchCoarseCap_ = 0; + mutable size_t searchOutDistCap_ = 0; + mutable size_t searchOutIdxCap_ = 0; + mutable size_t searchPerListDistCap_ = 0; + mutable size_t searchPerListIdxCap_ = 0; + mutable size_t lookupTableCap_ = 0; + mutable size_t lookupTableHalfCap_ = 0; + mutable size_t searchCoarseDistCap_ = 0; + mutable size_t searchQTermCap_ = 0; + mutable size_t searchMergeDistCap_ = 0; + mutable size_t searchMergeIdxCap_ = 0; + + // Coarse centroids mirrored on the GPU for the L2 lookup-table build. + mutable id centroidBuf_ = nil; + + // Query-independent term of the L2 precomputed-table decomposition + // (nlist * M * 256 floats), built once per trained index on the GPU. + mutable id term2Buf_ = nil; + void verifyPQSettings_() const; + void precomputeTerm2_() const; void encodeResidualAndAppend_( idx_t n, const float* x, const idx_t* list_nos, const idx_t* xids); + + void ensureSearchBuf_(id& buf, size_t& cap, size_t needed) const; + void uploadCentroids_() const; + void uploadPQCentroids_() const; }; } // namespace gpu_metal diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.mm b/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.mm index a4b2606ec..3ff5b76db 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.mm +++ b/thirdparty/faiss/faiss/gpu_metal/MetalIndexIVFPQ.mm @@ -9,6 +9,7 @@ #import "MetalIndexIVFPQ.h" #include +#include #include #include @@ -21,6 +22,22 @@ namespace faiss { namespace gpu_metal { +namespace { +inline int checkedIdxToInt(faiss::idx_t v, const char* what) { + if (!(v >= 0 && v <= (faiss::idx_t)std::numeric_limits::max())) { + FAISS_THROW_FMT("%s", what); + } + return (int)v; +} + +inline int checkedSizeToInt(size_t v, const char* what) { + if (!(v <= (size_t)std::numeric_limits::max())) { + FAISS_THROW_FMT("%s", what); + } + return (int)v; +} +} // namespace + // ============================================================ // Constructors // ============================================================ @@ -113,6 +130,104 @@ MetalIndexIVFPQ::~MetalIndexIVFPQ() = default; +// ============================================================ +// GPU buffer helpers +// ============================================================ + +void MetalIndexIVFPQ::ensureSearchBuf_( + id& buf, + size_t& cap, + size_t needed) const { + if (buf != nil && cap >= needed) + return; + size_t newCap = std::max(needed, cap * 2); + id device = resources_->getDevice(); + // Commit only on success so a failed over-large allocation keeps the + // existing valid buffer instead of forcing later reallocations. + id grown = + [device newBufferWithLength:newCap + options:MTLResourceStorageModeShared]; + if (grown) { + buf = grown; + cap = newCap; + } +} + +void MetalIndexIVFPQ::uploadCentroids_() const { + if (!cpuIndex_ || !cpuIndex_->quantizer || !resources_) + return; + auto* flatQ = dynamic_cast(cpuIndex_->quantizer); + if (!flatQ || flatQ->ntotal == 0) { + centroidBuf_ = nil; + return; + } + size_t bytes = (size_t)flatQ->ntotal * (size_t)d * sizeof(float); + id device = resources_->getDevice(); + if (!device) + return; + centroidBuf_ = [device newBufferWithLength:bytes + options:MTLResourceStorageModeShared]; + if (centroidBuf_) { + std::memcpy([centroidBuf_ contents], flatQ -> get_xb(), bytes); + } +} + +void MetalIndexIVFPQ::uploadPQCentroids_() const { + if (!cpuIndex_ || !gpuIvf_) + return; + const auto& pq = cpuIndex_->pq; + if (pq.centroids.empty()) + return; + gpuIvf_->setPQCentroids(pq.centroids.data()); +} + +void MetalIndexIVFPQ::precomputeTerm2_() const { + // GPU analogue of faiss::IndexIVFPQ::precompute_table(): the + // query-independent term ||pq||^2 + 2 of the L2 by_residual + // decomposition, built once per trained index. + term2Buf_ = nil; + if (!cpuIndex_ || !resources_ || !gpuIvf_) + return; + if (cpuIndex_->metric_type != METRIC_L2 || !cpuIndex_->by_residual) + return; + if (!centroidBuf_ || !gpuIvf_->pqCentroidsBuffer()) + return; + + const int M = (int)cpuIndex_->pq.M; + const idx_t nl = cpuIndex_->nlist; + if (M <= 0 || M > 64 || (d % M) != 0 || (d / M) > 256 || nl <= 0) + return; + // These indexes evaluate only the encountered codes from the codebook. + if (M > 16 && d <= 256) + return; + + // Mirror the CPU's precomputed_table_max_bytes default (2 GiB). + const size_t bytes = (size_t)nl * (size_t)M * 256 * sizeof(float); + if (bytes > ((size_t)1 << 31)) + return; + + id device = resources_->getDevice(); + id queue = resources_->getCommandQueue(); + if (!device || !queue) + return; + + term2Buf_ = [device newBufferWithLength:bytes + options:MTLResourceStorageModeShared]; + if (!term2Buf_) + return; + if (!runMetalIVFPQPrecomputeTerm2( + device, + queue, + centroidBuf_, + gpuIvf_->pqCentroidsBuffer(), + term2Buf_, + (int)nl, + d, + M)) { + term2Buf_ = nil; + } +} + // ============================================================ // Train / add / reset // ============================================================ @@ -125,6 +240,11 @@ cpuIndex_->precompute_table(); } is_trained = cpuIndex_->is_trained; + + // Mirror coarse and PQ centroids onto the GPU for the lookup-table build. + uploadCentroids_(); + uploadPQCentroids_(); + precomputeTerm2_(); } void MetalIndexIVFPQ::encodeResidualAndAppend_( @@ -217,12 +337,270 @@ FAISS_THROW_IF_NOT(cpuIndex_); FAISS_THROW_IF_NOT(k > 0); - if (auto* ivfParams = dynamic_cast(params)) { - if (ivfParams->nprobe > 0) - cpuIndex_->nprobe = ivfParams->nprobe; + const float inf = std::numeric_limits::infinity(); + const float negInf = -std::numeric_limits::infinity(); + const bool isL2 = (metric_type == METRIC_L2); + + if (cpuIndex_->ntotal == 0 || n == 0) { + for (idx_t i = 0; i < n * k; ++i) { + labels[i] = -1; + distances[i] = isL2 ? inf : negInf; + } + return; + } + + id device = resources_ ? resources_->getDevice() : nil; + id queue = + resources_ ? resources_->getCommandQueue() : nil; + + // Fall back to CPU when the GPU-resident storage or device is unavailable, + // when k exceeds what the Metal top-k kernels support, or when the PQ + // centroids have not been mirrored onto the GPU. + const int maxK = getMetalDistanceMaxK(); + if (!device || !queue || !gpuIvf_ || !gpuIvf_->codesBuffer() || + !gpuIvf_->idsBuffer() || !gpuIvf_->listOffsetGpuBuffer() || + !gpuIvf_->listLengthGpuBuffer() || !gpuIvf_->pqCentroidsBuffer() || + k > maxK) { + cpuIndex_->search(n, x, k, distances, labels, params); + return; + } + + size_t nprobe = cpuIndex_->nprobe; + if (params) { + const auto* ivfParams = + dynamic_cast(params); + const auto* pqParams = + dynamic_cast(params); + // The GPU scans every code in each probe and cannot apply selectors, + // scan budgets, or polysemous filters. Preserve CPU semantics when + // extending GPU dispatch to configurations that previously fell back. + if (!ivfParams || ivfParams->nprobe == 0 || ivfParams->sel || + ivfParams->max_codes || ivfParams->max_lists_num || + ivfParams->ensure_topk_full || + ivfParams->max_empty_result_buckets || + ivfParams->quantizer_params || ivfParams->inverted_list_context || + (pqParams && + (pqParams->polysemous_ht || pqParams->scan_table_threshold))) { + cpuIndex_->search(n, x, k, distances, labels, params); + return; + } + nprobe = ivfParams->nprobe; + } + nprobe = std::min(nprobe, (size_t)cpuIndex_->nlist); + if (nprobe == 0) { + for (idx_t i = 0; i < n * k; ++i) { + labels[i] = -1; + distances[i] = isL2 ? inf : negInf; + } + return; + } + + // Coarse quantization on the CPU. + std::vector coarseDistVec((size_t)n * nprobe); + std::vector coarseAssignVec((size_t)n * nprobe); + cpuIndex_->quantizer->search( + n, x, (idx_t)nprobe, coarseDistVec.data(), coarseAssignVec.data()); + + const int M = (int)cpuIndex_->pq.M; + const int ksub = (int)cpuIndex_->pq.ksub; + const bool useFp16Lut = config_.useFloat16; + + const size_t outDistBytes = (size_t)n * (size_t)k * sizeof(float); + const size_t outIdxBytes = (size_t)n * (size_t)k * sizeof(int64_t); + const size_t queryBytes = (size_t)n * (size_t)d * sizeof(float); + const size_t perListBytes = (size_t)n * nprobe * (size_t)k * sizeof(float); + const size_t perListIdxB = (size_t)n * nprobe * (size_t)k * sizeof(int64_t); + const size_t coarseBytes = (size_t)n * nprobe * sizeof(int32_t); + + ensureSearchBuf_(searchQueriesBuf_, searchQueriesCap_, queryBytes); + ensureSearchBuf_(searchOutDistBuf_, searchOutDistCap_, outDistBytes); + ensureSearchBuf_(searchOutIdxBuf_, searchOutIdxCap_, outIdxBytes); + ensureSearchBuf_( + searchPerListDistBuf_, searchPerListDistCap_, perListBytes); + ensureSearchBuf_(searchPerListIdxBuf_, searchPerListIdxCap_, perListIdxB); + ensureSearchBuf_(searchCoarseBuf_, searchCoarseCap_, coarseBytes); + + // A failed growth keeps the old (too-small) buffer, so check capacities + // as well as nil before writing into the buffers. + if (!searchQueriesBuf_ || searchQueriesCap_ < queryBytes || + !searchOutDistBuf_ || searchOutDistCap_ < outDistBytes || + !searchOutIdxBuf_ || searchOutIdxCap_ < outIdxBytes || + !searchPerListDistBuf_ || searchPerListDistCap_ < perListBytes || + !searchPerListIdxBuf_ || searchPerListIdxCap_ < perListIdxB || + !searchCoarseBuf_ || searchCoarseCap_ < coarseBytes) { + cpuIndex_->search(n, x, k, distances, labels, params); + return; + } + std::memcpy([searchQueriesBuf_ contents], x, queryBytes); + + // Upload coarse assignments as int32. + auto* coarseDst = reinterpret_cast([searchCoarseBuf_ contents]); + for (size_t i = 0; i < (size_t)n * nprobe; ++i) { + FAISS_THROW_IF_NOT_MSG( + coarseAssignVec[i] >= + (idx_t)std::numeric_limits::min() && + coarseAssignVec[i] <= + (idx_t)std::numeric_limits::max(), + "MetalIndexIVFPQ: coarse assignment exceeds int32 range"); + coarseDst[i] = (int32_t)coarseAssignVec[i]; } - cpuIndex_->search(n, x, k, distances, labels); + const int nI = checkedIdxToInt(n, "MetalIndexIVFPQ: n exceeds int range"); + const int kI = checkedIdxToInt(k, "MetalIndexIVFPQ: k exceeds int range"); + const int nprobeI = checkedSizeToInt( + nprobe, "MetalIndexIVFPQ: nprobe exceeds int range"); + const int avgListLen = cpuIndex_->nlist > 0 + ? (int)(cpuIndex_->ntotal / cpuIndex_->nlist) + : 0; + + bool ok = false; + + // Preferred path: evaluate encountered codes directly for small dimensions, + // or use the precomputed decomposition. Both scans retain an exact top-k; + // merging runs in rounds for any nprobe * k. Keep the cached LUT kernel for + // M <= 16 when the small-list specialization cannot be used. + const int dsub = d / M; + const bool byResidual = cpuIndex_->by_residual; + const auto& listLengths = gpuIvf_->listLength(); + const bool shortLists = + std::all_of(listLengths.begin(), listLengths.end(), [](size_t len) { + return len <= 128; + }); + const bool onTheFly = + d <= 256 && M >= 8 && (M > 16 || shortLists) && centroidBuf_ != nil; + const bool compactMerge = std::any_of( + listLengths.begin(), listLengths.end(), [k](size_t len) { + return len < (size_t)k; + }); + const bool canPrecomp = M <= 64 && dsub <= 256 && kI <= 512 && + (!isL2 || (byResidual && (onTheFly || term2Buf_ != nil))) && + gpuIvf_->totalVecs() <= (size_t)std::numeric_limits::max(); + if (canPrecomp) { + const size_t coarseDistBytes = (size_t)n * nprobe * sizeof(float); + const size_t qtermBytes = + (size_t)n * (size_t)M * (size_t)ksub * sizeof(float); + ensureSearchBuf_( + searchCoarseDistBuf_, searchCoarseDistCap_, coarseDistBytes); + if (!onTheFly) + ensureSearchBuf_(searchQTermBuf_, searchQTermCap_, qtermBytes); + if (nprobeI > 1) { + ensureSearchBuf_( + searchMergeDistBuf_, searchMergeDistCap_, perListBytes); + ensureSearchBuf_( + searchMergeIdxBuf_, searchMergeIdxCap_, perListIdxB); + } + if (searchCoarseDistBuf_ && searchCoarseDistCap_ >= coarseDistBytes && + (onTheFly || (searchQTermBuf_ && searchQTermCap_ >= qtermBytes)) && + (nprobeI == 1 || + (searchMergeDistBuf_ && searchMergeDistCap_ >= perListBytes && + searchMergeIdxBuf_ && searchMergeIdxCap_ >= perListIdxB))) { + std::memcpy( + [searchCoarseDistBuf_ contents], + coarseDistVec.data(), + coarseDistBytes); + ok = runMetalIVFPQPrecompSearch( + device, + queue, + searchQueriesBuf_, + searchCoarseBuf_, + searchCoarseDistBuf_, + isL2 ? term2Buf_ : nil, + searchQTermBuf_, + gpuIvf_->pqCentroidsBuffer(), + gpuIvf_->codesBuffer(), + gpuIvf_->idsBuffer(), + gpuIvf_->listOffsetGpuBuffer(), + gpuIvf_->listLengthGpuBuffer(), + nI, + d, + M, + kI, + nprobeI, + isL2, + byResidual, + searchOutDistBuf_, + searchOutIdxBuf_, + searchPerListDistBuf_, + searchPerListIdxBuf_, + searchMergeDistBuf_, + searchMergeIdxBuf_, + true, + centroidBuf_, + onTheFly, + shortLists, + compactMerge); + } + } + + // Legacy path: per-(query, probe) lookup tables. Only allocate the large + // LUT buffer when this path is actually taken. The coarse scores are + // needed as well: inner-product tables hold only. + if (!ok) { + const size_t tableSize = (size_t)n * nprobe * M * ksub; + const size_t tableBytes = tableSize * sizeof(float); + const size_t tableHalfBytes = tableSize * sizeof(uint16_t); + const size_t coarseDistBytes = (size_t)n * nprobe * sizeof(float); + ensureSearchBuf_(lookupTableBuf_, lookupTableCap_, tableBytes); + ensureSearchBuf_( + searchCoarseDistBuf_, searchCoarseDistCap_, coarseDistBytes); + if (useFp16Lut) { + ensureSearchBuf_( + lookupTableHalfBuf_, lookupTableHalfCap_, tableHalfBytes); + } + if (lookupTableBuf_ && lookupTableCap_ >= tableBytes && + searchCoarseDistBuf_ && searchCoarseDistCap_ >= coarseDistBytes && + (!useFp16Lut || + (lookupTableHalfBuf_ && lookupTableHalfCap_ >= tableHalfBytes))) { + std::memcpy( + [searchCoarseDistBuf_ contents], + coarseDistVec.data(), + coarseDistBytes); + ok = runMetalIVFPQFullSearch( + device, + queue, + searchQueriesBuf_, + searchCoarseBuf_, + searchCoarseDistBuf_, + centroidBuf_, + gpuIvf_->pqCentroidsBuffer(), + useFp16Lut ? lookupTableHalfBuf_ : lookupTableBuf_, + gpuIvf_->codesBuffer(), + gpuIvf_->idsBuffer(), + gpuIvf_->listOffsetGpuBuffer(), + gpuIvf_->listLengthGpuBuffer(), + nI, + d, + M, + kI, + nprobeI, + (int)cpuIndex_->nlist, + avgListLen, + useFp16Lut, + isL2, + searchOutDistBuf_, + searchOutIdxBuf_, + searchPerListDistBuf_, + searchPerListIdxBuf_); + } + } + + if (!ok) { + cpuIndex_->search(n, x, k, distances, labels, params); + return; + } + + const float* outDistPtr = + reinterpret_cast([searchOutDistBuf_ contents]); + const int64_t* outIdxPtr = + reinterpret_cast([searchOutIdxBuf_ contents]); + for (idx_t qi = 0; qi < n; ++qi) { + for (idx_t j = 0; j < k; ++j) { + const size_t pos = (size_t)qi * (size_t)k + (size_t)j; + const int64_t globalId = outIdxPtr[pos]; + labels[pos] = (globalId < 0) ? -1 : (idx_t)globalId; + distances[pos] = outDistPtr[pos]; + } + } } // ============================================================ @@ -241,6 +619,16 @@ FAISS_THROW_IF_NOT_MSG( src->polysemous_ht == 0, "copyFrom: polysemous codes are not supported"); + FAISS_THROW_IF_NOT_FMT( + src->d == d, + "copyFrom: dimension mismatch (%zd vs %zd)", + (size_t)src->d, + (size_t)d); + FAISS_THROW_IF_NOT_FMT( + src->pq.M == cpuIndex_->pq.M, + "copyFrom: PQ sub-quantizer mismatch (%zd vs %zd)", + (size_t)src->pq.M, + (size_t)cpuIndex_->pq.M); FAISS_THROW_IF_NOT_FMT( src->nlist == cpuIndex_->nlist, "copyFrom: nlist mismatch (%zd vs %zd)", @@ -280,6 +668,11 @@ } is_trained = true; + // Mirror coarse and PQ centroids onto the GPU for the lookup-table build. + uploadCentroids_(); + uploadPQCentroids_(); + precomputeTerm2_(); + // Gather IVF list data. size_t totalN = 0; for (size_t l = 0; l < (size_t)src->nlist; ++l) diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalKernels.h b/thirdparty/faiss/faiss/gpu_metal/MetalKernels.h index 92fb79df5..fb4890939 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalKernels.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalKernels.h @@ -91,6 +91,112 @@ class MetalKernels { id paramsBuf, int nq); + // ---- IVF-PQ ---- + + void encodeIVFPQBuildLookupTables( + id enc, + bool isL2, + bool outFp16, + id queries, + id coarseAssign, + id coarseCentroids, + id pqCentroids, + id outLookup, + int nq, + int d, + int M, + int nprobe); + + void encodeIVFPQScanList( + id enc, + bool useSmall, + bool useFp16Lookup, + id lookupTable, + id codes, + id ids, + id listOffset, + id listLength, + id coarseAssign, + id perListDist, + id perListIdx, + id paramsBuf, + id coarseDist, + int nq, + int nprobe); + + // ---- IVF-PQ precomputed-table path ---- + + void encodeIVFPQPrecomputeTerm2( + id enc, + id coarseCentroids, + id pqCentroids, + id outTerm2, + int nlist, + int d, + int M); + + void encodeIVFPQBuildQueryTerm( + id enc, + id queries, + id pqCentroids, + id outQTerm, + int nq, + int d, + int M, + bool isL2); + + void encodeIVFPQScanListPrecomp( + id enc, + id term2, // nil when useTerm2 is false (IP path) + id qterm, + id coarseDist, + id codes, + id ids, + id listOffset, + id listLength, + id coarseAssign, + id perListDist, + id perListIdx, + int nq, + int M, + int k, + int nprobe, + bool wantMin, + bool useTerm2, + bool useDis0, + id queries, + id coarseCentroids, + id pqCentroids, + int d, + bool onTheFly, + bool shortLists); + + void encodeIVFMergeListsGrouped( + id enc, + id inDist, + id inIdx, + id outDist, + id outIdx, + int nq, + int numLists, + int groupSize, + int k, + bool wantMin, + bool compact); + + // Exact Hamming top-k from the precompiled MetalDistance.metallib. + // Requires positive uint32-sized counts and 1 <= k <= 512. + void encodeHammingDistanceTopK( + id enc, + id queries, + id database, + id outDist, + id outIdx, + uint32_t nq, + uint32_t nb, + uint32_t codeSize, + uint32_t k); + static int selectTopKVariantIndex(int k); private: diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalKernels.mm b/thirdparty/faiss/faiss/gpu_metal/MetalKernels.mm index 84ec24496..71a11682e 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalKernels.mm +++ b/thirdparty/faiss/faiss/gpu_metal/MetalKernels.mm @@ -115,6 +115,30 @@ return ps; } +void MetalKernels::encodeHammingDistanceTopK( + id enc, + id queries, + id database, + id outDist, + id outIdx, + uint32_t nq, + uint32_t nb, + uint32_t codeSize, + uint32_t k) { + FAISS_THROW_IF_NOT(nq > 0 && nb > 0 && codeSize > 0 && k > 0 && k <= 512); + auto ps = pipeline("hamming_distance_topk"); + FAISS_THROW_IF_NOT_MSG(ps, "Metal Hamming pipeline unavailable"); + [enc setComputePipelineState:ps]; + [enc setBuffer:queries offset:0 atIndex:0]; + [enc setBuffer:database offset:0 atIndex:1]; + [enc setBuffer:outDist offset:0 atIndex:2]; + [enc setBuffer:outIdx offset:0 atIndex:3]; + uint32_t args[] = {nq, nb, codeSize, k}; + [enc setBytes:args length:sizeof(args) atIndex:4]; + [enc dispatchThreadgroups:MTLSizeMake(nq, 1, 1) + threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; +} + void MetalKernels::encodeDistanceMatrix( id enc, id queries, @@ -274,6 +298,218 @@ threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; } +void MetalKernels::encodeIVFPQBuildLookupTables( + id enc, + bool isL2, + bool outFp16, + id queries, + id coarseAssign, + id coarseCentroids, + id pqCentroids, + id outLookup, + int nq, + int d, + int M, + int nprobe) { + const char* name = nullptr; + if (isL2) { + name = outFp16 ? "ivfpq_build_lut_l2_f16" : "ivfpq_build_lut_l2"; + } else { + name = outFp16 ? "ivfpq_build_lut_ip_f16" : "ivfpq_build_lut_ip"; + } + [enc setComputePipelineState:pipeline(name)]; + [enc setBuffer:queries offset:0 atIndex:0]; + [enc setBuffer:coarseAssign offset:0 atIndex:1]; + [enc setBuffer:coarseCentroids offset:0 atIndex:2]; + [enc setBuffer:pqCentroids offset:0 atIndex:3]; + [enc setBuffer:outLookup offset:0 atIndex:4]; + uint32_t args[4] = { + (uint32_t)nq, (uint32_t)d, (uint32_t)M, (uint32_t)nprobe}; + [enc setBytes:args length:sizeof(args) atIndex:5]; + const NSUInteger totalTG = + (NSUInteger)nq * (NSUInteger)nprobe * (NSUInteger)M; + [enc dispatchThreadgroups:MTLSizeMake(totalTG, 1, 1) + threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; +} + +void MetalKernels::encodeIVFPQScanList( + id enc, + bool useSmall, + bool useFp16Lookup, + id lookupTable, + id codes, + id ids, + id listOffset, + id listLength, + id coarseAssign, + id perListDist, + id perListIdx, + id paramsBuf, + id coarseDist, + int nq, + int nprobe) { + const char* name = "ivf_scan_list_pq8"; + if (useFp16Lookup) { + name = "ivf_scan_list_pq8_f16"; + } else if (useSmall) { + name = "ivf_scan_list_pq8_small"; + } + [enc setComputePipelineState:pipeline(name)]; + [enc setBuffer:lookupTable offset:0 atIndex:0]; + [enc setBuffer:codes offset:0 atIndex:1]; + [enc setBuffer:ids offset:0 atIndex:2]; + [enc setBuffer:listOffset offset:0 atIndex:3]; + [enc setBuffer:listLength offset:0 atIndex:4]; + [enc setBuffer:coarseAssign offset:0 atIndex:5]; + [enc setBuffer:perListDist offset:0 atIndex:6]; + [enc setBuffer:perListIdx offset:0 atIndex:7]; + [enc setBuffer:paramsBuf offset:0 atIndex:8]; + [enc setBuffer:coarseDist offset:0 atIndex:9]; + [enc dispatchThreadgroups:MTLSizeMake( + (NSUInteger)nq * (NSUInteger)nprobe, 1, 1) + threadsPerThreadgroup:MTLSizeMake( + (useSmall && !useFp16Lookup) ? 32 + : 256, + 1, + 1)]; +} + +void MetalKernels::encodeIVFPQPrecomputeTerm2( + id enc, + id coarseCentroids, + id pqCentroids, + id outTerm2, + int nlist, + int d, + int M) { + [enc setComputePipelineState:pipeline("ivfpq_precompute_term2")]; + [enc setBuffer:coarseCentroids offset:0 atIndex:0]; + [enc setBuffer:pqCentroids offset:0 atIndex:1]; + [enc setBuffer:outTerm2 offset:0 atIndex:2]; + uint32_t args[3] = {(uint32_t)nlist, (uint32_t)d, (uint32_t)M}; + [enc setBytes:args length:sizeof(args) atIndex:3]; + const NSUInteger totalTG = (NSUInteger)nlist * (NSUInteger)M; + [enc dispatchThreadgroups:MTLSizeMake(totalTG, 1, 1) + threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; +} + +void MetalKernels::encodeIVFPQBuildQueryTerm( + id enc, + id queries, + id pqCentroids, + id outQTerm, + int nq, + int d, + int M, + bool isL2) { + [enc setComputePipelineState:pipeline("ivfpq_build_query_term")]; + [enc setBuffer:queries offset:0 atIndex:0]; + [enc setBuffer:pqCentroids offset:0 atIndex:1]; + [enc setBuffer:outQTerm offset:0 atIndex:2]; + uint32_t args[4] = {(uint32_t)nq, (uint32_t)d, (uint32_t)M, isL2 ? 1u : 0u}; + [enc setBytes:args length:sizeof(args) atIndex:3]; + const NSUInteger totalTG = (NSUInteger)nq * (NSUInteger)M; + [enc dispatchThreadgroups:MTLSizeMake(totalTG, 1, 1) + threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; +} + +void MetalKernels::encodeIVFPQScanListPrecomp( + id enc, + id term2, + id qterm, + id coarseDist, + id codes, + id ids, + id listOffset, + id listLength, + id coarseAssign, + id perListDist, + id perListIdx, + int nq, + int M, + int k, + int nprobe, + bool wantMin, + bool useTerm2, + bool useDis0, + id queries, + id coarseCentroids, + id pqCentroids, + int d, + bool onTheFly, + bool shortLists) { + const char* name = onTheFly + ? (shortLists ? "ivf_scan_list_pq8_onthefly_small" + : "ivf_scan_list_pq8_onthefly") + : (M > 16 ? "ivf_scan_list_pq8_precomp_large" + : "ivf_scan_list_pq8_precomp"); + [enc setComputePipelineState:pipeline(name)]; + // The kernel never reads term2 when useTerm2 is 0, but Metal requires a + // valid binding; rebind qterm in that case. + [enc setBuffer:(onTheFly ? coarseCentroids : (term2 ? term2 : qterm)) + offset:0 + atIndex:0]; + [enc setBuffer:(onTheFly ? queries : qterm) offset:0 atIndex:1]; + [enc setBuffer:coarseDist offset:0 atIndex:2]; + [enc setBuffer:codes offset:0 atIndex:3]; + [enc setBuffer:ids offset:0 atIndex:4]; + [enc setBuffer:listOffset offset:0 atIndex:5]; + [enc setBuffer:listLength offset:0 atIndex:6]; + [enc setBuffer:coarseAssign offset:0 atIndex:7]; + [enc setBuffer:perListDist offset:0 atIndex:8]; + [enc setBuffer:perListIdx offset:0 atIndex:9]; + uint32_t args[8] = { + (uint32_t)nq, + (uint32_t)M, + (uint32_t)k, + (uint32_t)nprobe, + wantMin ? 1u : 0u, + useTerm2 ? 1u : 0u, + useDis0 ? 1u : 0u, + (uint32_t)d}; + [enc setBytes:args length:sizeof(args) atIndex:10]; + if (onTheFly) + [enc setBuffer:pqCentroids offset:0 atIndex:11]; + [enc dispatchThreadgroups:MTLSizeMake( + (NSUInteger)nq * (NSUInteger)nprobe, 1, 1) + threadsPerThreadgroup:MTLSizeMake( + onTheFly && shortLists ? 32 : 256, + 1, + 1)]; +} + +void MetalKernels::encodeIVFMergeListsGrouped( + id enc, + id inDist, + id inIdx, + id outDist, + id outIdx, + int nq, + int numLists, + int groupSize, + int k, + bool wantMin, + bool compact) { + [enc setComputePipelineState:pipeline("ivf_merge_lists_grouped")]; + [enc setBuffer:inDist offset:0 atIndex:0]; + [enc setBuffer:inIdx offset:0 atIndex:1]; + [enc setBuffer:outDist offset:0 atIndex:2]; + [enc setBuffer:outIdx offset:0 atIndex:3]; + uint32_t args[6] = { + (uint32_t)nq, + (uint32_t)numLists, + (uint32_t)groupSize, + (uint32_t)k, + wantMin ? 1u : 0u, + compact ? 1u : 0u}; + [enc setBytes:args length:sizeof(args) atIndex:4]; + const NSUInteger nGroups = + ((NSUInteger)numLists + (NSUInteger)groupSize - 1) / + (NSUInteger)groupSize; + [enc dispatchThreadgroups:MTLSizeMake((NSUInteger)nq * nGroups, 1, 1) + threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; +} + MetalKernels& getMetalKernels(id device) { static std::mutex mu; static std::unordered_map> map; diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.h b/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.h index 592ac11ad..491fb9e9f 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.h +++ b/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.h @@ -12,6 +12,7 @@ #pragma once #include +#include namespace faiss { namespace gpu_metal { @@ -41,5 +42,14 @@ faiss::Index* index_cpu_to_gpu( /// Copy Metal index back to CPU. Caller owns returned index. faiss::Index* index_gpu_to_cpu(const faiss::Index* index); +/// Clone CPU IndexBinaryFlat to Metal. Caller owns the returned index. +faiss::IndexBinary* index_binary_cpu_to_gpu( + StandardMetalResourcesHolder* res, + int device, + const faiss::IndexBinary* index); + +/// Clone MetalIndexBinaryFlat back to CPU. Caller owns the returned index. +faiss::IndexBinary* index_binary_gpu_to_cpu(const faiss::IndexBinary* index); + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.mm b/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.mm index d019c248e..98abb3a11 100644 --- a/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.mm +++ b/thirdparty/faiss/faiss/gpu_metal/MetalPythonBridge.mm @@ -75,5 +75,18 @@ void gpu_sync_all_devices() { return index_metal_gpu_to_cpu(index); } +faiss::IndexBinary* index_binary_cpu_to_gpu( + StandardMetalResourcesHolder* res, + int device, + const faiss::IndexBinary* index) { + FAISS_THROW_IF_NOT(res && res->impl); + return index_binary_cpu_to_metal_gpu( + static_cast(res->impl), device, index); +} + +faiss::IndexBinary* index_binary_gpu_to_cpu(const faiss::IndexBinary* index) { + return index_binary_metal_gpu_to_cpu(index); +} + } // namespace gpu_metal } // namespace faiss diff --git a/thirdparty/faiss/faiss/gpu_metal/test/CMakeLists.txt b/thirdparty/faiss/faiss/gpu_metal/test/CMakeLists.txt index 446d234ef..2515e0b48 100644 --- a/thirdparty/faiss/faiss/gpu_metal/test/CMakeLists.txt +++ b/thirdparty/faiss/faiss/gpu_metal/test/CMakeLists.txt @@ -57,3 +57,37 @@ set_target_properties(TestMetalIndexIVFPQ PROPERTIES OBJCXX_STANDARD_REQUIRED ON ) gtest_discover_tests(TestMetalIndexIVFPQ) + +add_executable(TestMetalIndexBinaryFlat TestMetalIndexBinaryFlat.mm) +target_link_libraries(TestMetalIndexBinaryFlat PRIVATE + faiss_metal + faiss + GTest::gtest_main +) +target_include_directories(TestMetalIndexBinaryFlat PRIVATE ${PROJECT_SOURCE_DIR}) +set_target_properties(TestMetalIndexBinaryFlat PROPERTIES + OBJCXX_STANDARD 17 + OBJCXX_STANDARD_REQUIRED ON +) +target_compile_options(TestMetalIndexBinaryFlat PRIVATE -fobjc-arc) +gtest_discover_tests(TestMetalIndexBinaryFlat) + +add_executable(TestMetalBinaryFlatFailures TestMetalBinaryFlatFailures.mm) +target_link_libraries(TestMetalBinaryFlatFailures PRIVATE faiss_metal faiss) +target_include_directories(TestMetalBinaryFlatFailures PRIVATE ${PROJECT_SOURCE_DIR}) +set_target_properties(TestMetalBinaryFlatFailures PROPERTIES + OBJCXX_STANDARD 17 + OBJCXX_STANDARD_REQUIRED ON +) +target_compile_options(TestMetalBinaryFlatFailures PRIVATE -fobjc-arc) +target_compile_definitions(TestMetalBinaryFlatFailures PRIVATE + FAISS_TEST_METALLIB_PATH="${PROJECT_BINARY_DIR}/faiss/gpu_metal/MetalDistance.metallib" +) +foreach(fault function pipeline growth scratch) + add_test(NAME TestMetalIndexBinaryFlat.Reject_${fault} + COMMAND TestMetalBinaryFlatFailures ${fault}) + set_tests_properties(TestMetalIndexBinaryFlat.Reject_${fault} PROPERTIES + ENVIRONMENT "MTL_DEBUG_LAYER=1;MTL_SHADER_VALIDATION=1" + SKIP_RETURN_CODE 77 + ) +endforeach() diff --git a/thirdparty/faiss/faiss/gpu_metal/test/TestMetalBinaryFlatFailures.mm b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalBinaryFlatFailures.mm new file mode 100644 index 000000000..7612c1567 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalBinaryFlatFailures.mm @@ -0,0 +1,245 @@ +// @lint-ignore-every LICENSELINT +/** + * Copyright (c) Meta Platforms, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#import +#include +#include +#include +#include + +using namespace faiss::gpu_metal; + +namespace { +IMP original; + +typedef id Lookup(id, SEL, NSString*) __attribute__((ns_returns_retained)); +id rejectFunction(id self, SEL selector, NSString* name) + __attribute__((ns_returns_retained)); +id rejectFunction(id self, SEL selector, NSString* name) { + if ([name isEqualToString:@"hamming_distance_topk"]) { + return nil; + } + return reinterpret_cast(original)(self, selector, name); +} + +typedef id CreatePipeline( + id, + SEL, + id, + NSError**) __attribute__((ns_returns_retained)); +id rejectPipeline( + id self, + SEL selector, + id function, + NSError** error) __attribute__((ns_returns_retained)); +id rejectPipeline( + id self, + SEL selector, + id function, + NSError** error) { + if ([function.name isEqualToString:@"hamming_distance_topk"]) { + return nil; + } + return reinterpret_cast(original)( + self, selector, function, error); +} +size_t allocationCount = 0; +size_t allocatedBytes = 0; +bool rejectAllocation = false; +size_t rejectAt = 0; +typedef id Allocate(id, SEL, NSUInteger, MTLResourceOptions) + __attribute__((ns_returns_retained)); +id trackAllocation( + id self, + SEL selector, + NSUInteger size, + MTLResourceOptions options) __attribute__((ns_returns_retained)); +id trackAllocation( + id self, + SEL selector, + NSUInteger size, + MTLResourceOptions options) { + ++allocationCount; + allocatedBytes += size; + if (rejectAllocation || (rejectAt && allocationCount == rejectAt)) { + return nil; + } + return reinterpret_cast(original)(self, selector, size, options); +} + +bool checkGrowth(std::shared_ptr resources) { + auto device = resources->getDevice(); + Method method = class_getInstanceMethod( + [device class], @selector(newBufferWithLength:options:)); + original = method_setImplementation( + method, reinterpret_cast(trackAllocation)); + MetalIndexBinaryFlat index(resources, 24); + constexpr int n = 1025; + for (int i = 0; i < n; ++i) { + uint8_t code[] = {uint8_t(i), uint8_t(i >> 8), 0}; + index.add(1, code); + } + // Bound work rather than a particular initial capacity or growth factor. + bool valid = allocationCount <= 16 && allocatedBytes <= 4 * n * 3; + rejectAllocation = true; + std::vector extra(1024 * 3); + bool caught = false; + try { + index.add(1024, extra.data()); // exceeds the geometrically grown buffer + } catch (const std::exception&) { + caught = true; + } + valid = valid && caught && index.ntotal == n; + for (int i = 0; i < n; ++i) { + uint8_t actual[3]; + index.reconstruct(i, actual); + valid = valid && actual[0] == uint8_t(i) && + actual[1] == uint8_t(i >> 8) && actual[2] == 0; + } + // An append within spare capacity must succeed even if GPU allocations + // are rejected. It must not recopy the existing prefix. + size_t before = allocationCount; + uint8_t code[] = {1, 4, 0}; + index.add(1, code); + valid = valid && allocationCount == before && index.ntotal == n + 1; + rejectAllocation = false; + method_setImplementation(method, original); + int32_t distance = -1; + faiss::idx_t label = -1; + index.search(1, code, 1, &distance, &label); + return valid && distance == 0 && label == n; +} + +bool checkScratch(std::shared_ptr resources) { + MetalIndexBinaryFlat index(resources, 24); + std::vector codes(257 * 3, 0); + index.add(257, codes.data()); + constexpr int nq = 7, k = 64; + std::vector queries(513 * 3, 0); + std::vector distances(513 * k, -123); + std::vector labels(513 * k, -123); + index.search(nq, queries.data(), k, distances.data(), labels.data()); + auto device = resources->getDevice(); + Method method = class_getInstanceMethod( + [device class], @selector(newBufferWithLength:options:)); + original = method_setImplementation( + method, reinterpret_cast(trackAllocation)); + bool valid = true; + // Every individual allocation in a larger search may fail. None may + // publish a partial replacement or write any caller output. + for (size_t failure : {1u, 2u, 3u}) { + std::fill(distances.begin(), distances.end(), -123); + std::fill(labels.begin(), labels.end(), -123); + allocationCount = 0; + rejectAt = failure; + bool caught = false; + try { + index.search( + 513, queries.data(), k, distances.data(), labels.data()); + } catch (const std::exception&) { + caught = true; + } + valid = valid && caught && allocationCount == failure && + std::all_of( + distances.begin(), + distances.end(), + [](int32_t value) { return value == -123; }) && + std::all_of( + labels.begin(), labels.end(), [](faiss::idx_t value) { + return value == -123; + }); + rejectAt = 0; + rejectAllocation = true; + allocationCount = 0; + index.search(nq, queries.data(), k, distances.data(), labels.data()); + valid = valid && allocationCount == 0; + for (int q = 0; q < nq; ++q) { + for (int j = 0; j < k; ++j) { + valid = valid && distances[q * k + j] == 0 && + labels[q * k + j] == j; + } + } + rejectAllocation = false; + } + method_setImplementation(method, original); + index.reset(); + index.add(257, codes.data()); + index.search(nq, queries.data(), k, distances.data(), labels.data()); + return valid && index.ntotal == 257; +} + +} // namespace + +// Run each fault in a fresh process: pipeline caches must start empty and Metal +// validation must be enabled before device creation. Returning successfully +// after draining the autorelease pool proves exception cleanup does not abort. +int main(int argc, char** argv) { + bool caught = false; + @autoreleasepool { + auto resources = std::make_shared(); + if (!resources->isAvailable()) { + return 77; + } + if (argc == 2 && std::strcmp(argv[1], "growth") == 0) { + return checkGrowth(resources) ? 0 : 1; + } + if (argc == 2 && std::strcmp(argv[1], "scratch") == 0) { + return checkScratch(resources) ? 0 : 1; + } + auto device = resources->getDevice(); + Method method; + IMP replacement; + if (argc == 2 && std::strcmp(argv[1], "function") == 0) { + NSError* error = nil; + auto library = [device + newLibraryWithURL: + [NSURL fileURLWithPath:@(FAISS_TEST_METALLIB_PATH)] + error:&error]; + if (!library) { + return 1; + } + method = class_getInstanceMethod( + [library class], @selector(newFunctionWithName:)); + replacement = reinterpret_cast(rejectFunction); + } else if (argc == 2 && std::strcmp(argv[1], "pipeline") == 0) { + method = class_getInstanceMethod( + [device class], + @selector(newComputePipelineStateWithFunction:error:)); + replacement = reinterpret_cast(rejectPipeline); + } else { + return 1; + } + if (!method) { + return 1; + } + original = method_setImplementation(method, replacement); + { + MetalIndexBinaryFlat index(resources, 8); + uint8_t code = 42; + int32_t distance = -123; + faiss::idx_t label = -123; + index.add(1, &code); + try { + index.search(1, &code, 1, &distance, &label); + } catch (const std::exception& e) { + caught = std::strstr( + e.what(), + "Metal Hamming pipeline unavailable") && + distance == -123 && label == -123; + } + } + method_setImplementation(method, original); + } + if (!caught) { + std::cerr + << "Expected a catchable pipeline failure and unchanged outputs\n"; + return 1; + } + return 0; +} diff --git a/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexBinaryFlat.mm b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexBinaryFlat.mm new file mode 100644 index 000000000..220fdf994 --- /dev/null +++ b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexBinaryFlat.mm @@ -0,0 +1,399 @@ +// @lint-ignore-every LICENSELINT +/** + * Copyright (c) Meta Platforms, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using faiss::idx_t; +using namespace faiss::gpu_metal; + +namespace { +std::vector randomBytes(size_t n, uint32_t seed) { + std::mt19937 rng(seed); + std::vector bytes(n); + for (auto& b : bytes) { + b = uint8_t(rng()); + } + return bytes; +} + +// Independent full-sort oracle, including deterministic ties and sentinels. +void checkExact( + const std::vector& database, + const std::vector& queries, + int codeSize, + int k, + const int32_t* distances, + const idx_t* labels) { + size_t nb = database.size() / codeSize; + size_t nq = queries.size() / codeSize; + for (size_t q = 0; q < nq; ++q) { + std::vector> expected; + for (size_t v = 0; v < nb; ++v) { + int32_t distance = 0; + for (int b = 0; b < codeSize; ++b) { + distance += __builtin_popcount( + unsigned( + queries[q * codeSize + b] ^ + database[v * codeSize + b])); + } + expected.emplace_back(distance, v); + } + std::sort(expected.begin(), expected.end()); + for (int j = 0; j < k; ++j) { + auto value = size_t(j) < nb + ? expected[j] + : std::make_pair( + std::numeric_limits::max(), idx_t(-1)); + ASSERT_EQ(distances[q * k + j], value.first) + << "q=" << q << " j=" << j; + ASSERT_EQ(labels[q * k + j], value.second) + << "q=" << q << " j=" << j; + } + } +} +} // namespace + +class TestMetalIndexBinaryFlat : public ::testing::Test { + protected: + void SetUp() override { + resources = std::make_shared(); + if (!resources->isAvailable()) { + GTEST_SKIP() << "Metal not available"; + } + } + std::shared_ptr resources; +}; + +TEST_F(TestMetalIndexBinaryFlat, DimensionsAndKBoundaries) { + // Odd code strides exercise unaligned vectors. 513/1024-byte codes exceed + // the prototype's fixed 512-byte threadgroup query cache. + for (int cs : {1, 3, 5, 32, 513, 1024}) { + SCOPED_TRACE(cs); + constexpr int nb = 1537, nq = 7; + auto database = randomBytes(nb * cs, 1234); + auto queries = randomBytes(nq * cs, 5678); + MetalIndexBinaryFlat metal(resources, cs * 8); + metal.add(511, database.data()); + metal.add(nb - 511, database.data() + 511 * cs); + faiss::IndexBinaryFlat cpu(cs * 8); + cpu.add(nb, database.data()); + for (int k : {1, 7, 255, 256, 511, 512}) { + SCOPED_TRACE(k); + std::vector distances(nq * k), cpuDist(nq * k); + std::vector labels(nq * k), cpuLabels(nq * k); + metal.search( + nq, queries.data(), k, distances.data(), labels.data()); + checkExact( + database, queries, cs, k, distances.data(), labels.data()); + cpu.search(nq, queries.data(), k, cpuDist.data(), cpuLabels.data()); + EXPECT_EQ(distances, cpuDist); + } + } +} + +TEST_F(TestMetalIndexBinaryFlat, DirectCompiledKernelAdversarialCandidates) { + // All nearest neighbors belong to the same strided prototype thread. + // Keeping only four candidates per thread would lose most of these hits. + constexpr int nb = 8193, cs = 3, nq = 1, k = 32; + std::vector database(nb * cs, 255), queries(cs, 0); + for (int v = 0; v < nb; v += 256) { + std::fill_n(database.data() + v * cs, cs, uint8_t(0)); + } + auto device = resources->getDevice(); + id db = [device newBufferWithBytes:database.data() + length:database.size() + options:MTLResourceStorageModeShared]; + id q = [device newBufferWithBytes:queries.data() + length:queries.size() + options:MTLResourceStorageModeShared]; + id dist = + [device newBufferWithLength:k * sizeof(int32_t) + options:MTLResourceStorageModeShared]; + id ids = + [device newBufferWithLength:k * sizeof(idx_t) + options:MTLResourceStorageModeShared]; + ASSERT_TRUE(db && q && dist && ids); + auto& kernels = getMetalKernels(device); + ASSERT_TRUE(kernels.isValid()); + auto command = [resources->getCommandQueue() commandBuffer]; + auto encoder = [command computeCommandEncoder]; + kernels.encodeHammingDistanceTopK(encoder, q, db, dist, ids, nq, nb, cs, k); + [encoder endEncoding]; + [command commit]; + [command waitUntilCompleted]; + ASSERT_EQ(command.status, MTLCommandBufferStatusCompleted); + checkExact( + database, + queries, + cs, + k, + static_cast(dist.contents), + static_cast(ids.contents)); +} + +TEST_F(TestMetalIndexBinaryFlat, PackedAndOddStridesSelectionBoundaries) { + // Exercise the CUDA-style word path and its byte-stride fallback. Values + // around powers of two cover selection capacities and partial segments. + for (int cs : {3, 4, 8, 12, 16, 32, 64, 128, 129, 132}) { + SCOPED_TRACE(cs); + constexpr int nb = 2053, nq = 3; + auto database = randomBytes(nb * cs, 177); + auto queries = randomBytes(nq * cs, 991); + MetalIndexBinaryFlat metal(resources, cs * 8); + metal.add(nb, database.data()); + for (int k : + {1, + 2, + 31, + 32, + 33, + 63, + 64, + 65, + 127, + 128, + 129, + 255, + 256, + 257, + 511, + 512}) { + SCOPED_TRACE(k); + std::vector distances(nq * k); + std::vector labels(nq * k); + metal.search( + nq, queries.data(), k, distances.data(), labels.data()); + checkExact( + database, queries, cs, k, distances.data(), labels.data()); + } + } +} + +TEST_F(TestMetalIndexBinaryFlat, LateImprovementsAndCutoffTies) { + constexpr int cs = 8, nb = 8193; + std::vector database(nb * cs, 0), query(cs, 0); + for (int v = 0; v < nb; ++v) { + // Repeatedly improve the current cutoff, including the last partial + // segment, with enough equal distances to require deterministic IDs. + int distance = (nb - v) % (cs * 8 + 1); + for (int bit = 0; bit < distance; ++bit) { + database[v * cs + bit / 8] |= uint8_t(1u << (bit % 8)); + } + } + MetalIndexBinaryFlat metal(resources, cs * 8); + metal.add(nb, database.data()); + for (int k : {1, 20, 128, 512}) { + std::vector distances(k); + std::vector labels(k); + metal.search(1, query.data(), k, distances.data(), labels.data()); + checkExact(database, query, cs, k, distances.data(), labels.data()); + } +} + +TEST_F(TestMetalIndexBinaryFlat, IntegerDistancesBeyondFloatPrecision) { + constexpr int cs = (1 << 21) + 1, d = cs * 8; + std::vector database(size_t(3) * cs, 255), query(cs, 0); + database[cs] = 254; + std::fill(database.begin() + 2 * cs, database.end(), 0); + MetalIndexBinaryFlat metal(resources, d); + metal.add(3, database.data()); + int32_t distances[4]; + idx_t labels[4]; + metal.search(1, query.data(), 4, distances, labels); + EXPECT_EQ(distances[0], 0); + EXPECT_EQ(distances[1], d - 1); + EXPECT_EQ(distances[2], d); + EXPECT_EQ(distances[3], std::numeric_limits::max()); + EXPECT_EQ(labels[0], 2); + EXPECT_EQ(labels[1], 1); + EXPECT_EQ(labels[2], 0); + EXPECT_EQ(labels[3], -1); +} + +TEST_F(TestMetalIndexBinaryFlat, EmptyShortAndReset) { + constexpr int cs = 5, nq = 3, k = 512; + auto queries = randomBytes(nq * cs, 42); + for (int nb : {0, 1, 17, 511, 512, 513}) { + SCOPED_TRACE(nb); + auto database = randomBytes(nb * cs, 13); + MetalIndexBinaryFlat metal(resources, cs * 8); + metal.add(nb, database.data()); + std::vector distances(nq * k, -2); + std::vector labels(nq * k, -2); + metal.search(nq, queries.data(), k, distances.data(), labels.data()); + checkExact(database, queries, cs, k, distances.data(), labels.data()); + metal.reset(); + EXPECT_EQ(metal.ntotal, 0); + metal.search(nq, queries.data(), k, distances.data(), labels.data()); + checkExact({}, queries, cs, k, distances.data(), labels.data()); + metal.add(nq, queries.data()); + metal.search(nq, queries.data(), k, distances.data(), labels.data()); + checkExact(queries, queries, cs, k, distances.data(), labels.data()); + } +} + +TEST_F(TestMetalIndexBinaryFlat, RepeatedTiesAcrossSegmentsAndLargeBatch) { + constexpr int nb = 100003, cs = 1, nq = 65, k = 512; + std::vector database(nb * cs, 0), queries(nq * cs, 0); + MetalIndexBinaryFlat metal(resources, cs * 8); + metal.add(nb, database.data()); + std::vector distances(nq * k); + std::vector labels(nq * k); + metal.search(nq, queries.data(), k, distances.data(), labels.data()); + for (int q = 0; q < nq; ++q) { + for (int j = 0; j < k; ++j) { + EXPECT_EQ(distances[q * k + j], 0); + EXPECT_EQ(labels[q * k + j], j); + } + } +} + +TEST_F(TestMetalIndexBinaryFlat, CpuFallbackLargeKAndSelectors) { + constexpr int nb = 701, cs = 8, nq = 3; + auto database = randomBytes(nb * cs, 91); + auto queries = randomBytes(nq * cs, 12); + faiss::IndexBinaryFlat cpu(cs * 8); + cpu.add(nb, database.data()); + MetalIndexBinaryFlat metal(resources, &cpu); + faiss::IDSelectorRange selector(7, 25); + faiss::SearchParameters params; + params.sel = &selector; + for (int k : {7, 513, 709}) { + for (const auto* p : + {static_cast(nullptr), + static_cast(¶ms)}) { + if (k == 7 && !p) + continue; + std::vector distances(nq * k), expected(nq * k); + std::vector labels(nq * k), expectedLabels(nq * k); + cpu.search( + nq, + queries.data(), + k, + expected.data(), + expectedLabels.data(), + p); + metal.search( + nq, queries.data(), k, distances.data(), labels.data(), p); + EXPECT_EQ(distances, expected); + EXPECT_EQ(labels, expectedLabels); + } + } +} + +TEST_F(TestMetalIndexBinaryFlat, CloneOwnsSourceAndPreservesCpuOptions) { + constexpr int cs = 3, nb = 19; + auto bytes = randomBytes(nb * cs, 71); + faiss::IndexBinaryFlat cpu(cs * 8); + // A borrowed source must be deep-copied rather than retaining its view. + cpu.xb = faiss::MaybeOwnedVector::create_view( + bytes.data(), bytes.size(), nullptr); + cpu.ntotal = nb; + cpu.use_heap = false; + cpu.query_batch_size = 7; + cpu.verbose = true; + StandardMetalResources res; + std::unique_ptr metal( + index_binary_cpu_to_metal_gpu(&res, 0, &cpu)); + auto expected = bytes; + std::fill(bytes.begin(), bytes.end(), 0); + cpu.xb = faiss::MaybeOwnedVector(); + cpu.reset(); + auto* flat = dynamic_cast(metal.get()); + ASSERT_NE(flat, nullptr); + std::vector recons(cs); + for (int v = 0; v < nb; ++v) { + flat->reconstruct(v, recons.data()); + EXPECT_TRUE( + std::equal( + recons.begin(), + recons.end(), + expected.data() + v * cs)); + } + std::unique_ptr back( + index_binary_metal_gpu_to_cpu(flat)); + auto* cpuBack = dynamic_cast(back.get()); + ASSERT_NE(cpuBack, nullptr); + EXPECT_EQ(cpuBack->ntotal, nb); + EXPECT_FALSE(cpuBack->use_heap); + EXPECT_EQ(cpuBack->query_batch_size, 7); + EXPECT_TRUE(cpuBack->verbose); + EXPECT_EQ( + std::memcmp(cpuBack->xb.data(), expected.data(), expected.size()), + 0); + flat->reset(); + EXPECT_EQ( + std::memcmp(cpuBack->xb.data(), expected.data(), expected.size()), + 0); + // copyFrom changes dimensions and replaces existing GPU data. + flat->copyFrom(cpuBack); + faiss::IndexBinaryFlat other(8); + const uint8_t one = 42; + other.add(1, &one); + flat->copyFrom(&other); + EXPECT_EQ(flat->d, 8); + EXPECT_EQ(flat->ntotal, 1); + flat->reconstruct(0, recons.data()); + EXPECT_EQ(recons[0], one); +} + +TEST_F(TestMetalIndexBinaryFlat, InvalidInputsDoNotChangeState) { + EXPECT_ANY_THROW(MetalIndexBinaryFlat(resources, 0)); + EXPECT_ANY_THROW(MetalIndexBinaryFlat(resources, 7)); + EXPECT_ANY_THROW(MetalIndexBinaryFlat(nullptr, 8)); + EXPECT_ANY_THROW(MetalIndexBinaryFlat( + resources, static_cast(nullptr))); + MetalIndexBinaryFlat metal(resources, 8); + uint8_t value = 42; + int32_t distance; + idx_t label; + metal.add(1, &value); + EXPECT_ANY_THROW(metal.add(-1, &value)); + EXPECT_ANY_THROW(metal.add(1, nullptr)); + EXPECT_ANY_THROW(metal.add(std::numeric_limits::max(), &value)); + EXPECT_ANY_THROW(metal.search(-1, &value, 1, &distance, &label)); + EXPECT_ANY_THROW(metal.search(1, &value, 0, &distance, &label)); + EXPECT_ANY_THROW(metal.search(1, nullptr, 1, &distance, &label)); + EXPECT_ANY_THROW(metal.search(1, &value, 1, nullptr, &label)); + EXPECT_ANY_THROW(metal.search( + 1, &value, std::numeric_limits::max(), &distance, &label)); + EXPECT_ANY_THROW(metal.reconstruct(-1, &value)); + EXPECT_ANY_THROW(metal.reconstruct(1, &value)); + EXPECT_ANY_THROW(metal.copyFrom(nullptr)); + EXPECT_ANY_THROW(metal.copyTo(nullptr)); + metal.search(0, nullptr, 1, nullptr, nullptr); + metal.add(0, nullptr); + faiss::IndexBinaryFlat invalid(16); + invalid.ntotal = 1; + EXPECT_ANY_THROW(metal.copyFrom(&invalid)); + EXPECT_EQ(metal.d, 8); + EXPECT_EQ(metal.ntotal, 1); + metal.search(1, &value, 1, &distance, &label); + EXPECT_EQ(distance, 0); + EXPECT_EQ(label, 0); + StandardMetalResources res; + EXPECT_ANY_THROW(index_binary_cpu_to_metal_gpu(&res, 1, &invalid)); + EXPECT_ANY_THROW(index_binary_cpu_to_metal_gpu(nullptr, 0, &invalid)); + EXPECT_ANY_THROW(index_binary_cpu_to_metal_gpu(&res, 0, nullptr)); + EXPECT_ANY_THROW(index_binary_metal_gpu_to_cpu(&invalid)); + faiss::IndexBinaryFlat quantizer(8); + faiss::IndexBinaryIVF unsupported(&quantizer, 8, 2); + EXPECT_ANY_THROW(index_binary_cpu_to_metal_gpu(&res, 0, &unsupported)); +} diff --git a/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexIVFPQ.mm b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexIVFPQ.mm index 52f725a25..48d2b8d09 100644 --- a/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexIVFPQ.mm +++ b/thirdparty/faiss/faiss/gpu_metal/test/TestMetalIndexIVFPQ.mm @@ -11,12 +11,16 @@ #include #include #include +#include #include #include #include +#include #include #include +#include #import +#include #import #import #import @@ -170,3 +174,259 @@ void SetUp() override { std::unique_ptr cpuBackPtr(cpuBack); ASSERT_EQ(cpuBack->ntotal, nb); } + +TEST_F(TestMetalIndexIVFPQ, LargeMSearchParametersKeepCpuSemantics) { + constexpr int d = 128, nb = 2000, nq = 4, k = 20; + std::vector xb(nb * d), xq(nq * d); + faiss::float_rand(xb.data(), xb.size(), 123); + faiss::float_rand(xq.data(), xq.size(), 456); + faiss::IndexFlatL2 quantizer(d); + faiss::IndexIVFPQ cpu(&quantizer, d, 8, 32, 8); + cpu.nprobe = 2; + cpu.train(nb, xb.data()); + cpu.add(nb, xb.data()); + faiss::gpu_metal::MetalIndexIVFPQ metal(resources_, &cpu); + faiss::IDSelectorRange selector(0, 10); + for (bool useSelector : {true, false}) { + faiss::IVFPQSearchParameters params; + params.nprobe = 8; + params.sel = useSelector ? &selector : nullptr; + params.max_codes = useSelector ? 0 : 12; + std::vector cpuD(nq * k), gpuD(nq * k); + std::vector cpuI(nq * k), gpuI(nq * k); + cpu.search(nq, xq.data(), k, cpuD.data(), cpuI.data(), ¶ms); + metal.search(nq, xq.data(), k, gpuD.data(), gpuI.data(), ¶ms); + EXPECT_EQ(cpuI, gpuI); + EXPECT_EQ(cpuD, gpuD); + EXPECT_EQ(metal.nprobe(), 2); + } +} + +// Exercise the Metal entry point directly: a CPU fallback cannot satisfy this +// test. The oracle reconstructs PQ vectors and computes their distances, +// without using the GPU's lookup-table decomposition or selection +// implementation. +TEST_F(TestMetalIndexIVFPQ, ScanVariantsAgainstReconstruction) { + struct Config { + int M; + int d; + bool onTheFly; + }; + const Config configs[] = { + {8, 128, false}, + {16, 128, false}, + {8, 128, true}, + {16, 128, true}, + {17, 136, true}, + {32, 128, true}, + {48, 192, true}, + {64, 128, true}, + {32, 512, false}, + {64, 512, false}}; + for (const auto& config : configs) { + for (int shape : {0, 1, 2, 3, 4}) { + const bool shortLists = shape != 1 && shape != 3; + for (bool isL2 : {true, false}) { + @autoreleasepool { + const int M = config.M, d = config.d, dsub = d / M; + const int nq = 3; + std::vector lengths = shortLists + ? std::vector{0, 1, 6, 24, 127, 128} + : std::vector{ + 0, + 1, + 6, + 24, + 127, + 128, + 129, + 511, + 512, + 513, + 1025, + 2051, + 3}; + if (shape == 2) + lengths = {0, 0, 0}; + else if (shape == 3) + lengths = {2051}; + else if (shape == 4) + lengths = {128}; + const int nl = lengths.size(), np = nl; + std::vector offsets(nl); + size_t nb = 0; + for (int l = 0; l < nl; ++l) { + offsets[l] = nb; + nb += lengths[l]; + } + std::vector queries(nq * d), coarse(nl * d), + pq(d * 256); + faiss::float_rand(queries.data(), queries.size(), 43); + faiss::float_rand(coarse.data(), coarse.size(), 44); + faiss::float_rand(pq.data(), pq.size(), 45); + std::vector codes(nb * M); + for (size_t i = 0; i < codes.size(); ++i) + codes[i] = (i * 131 + i / 7 + i / 257) % 256; + std::vector ids(nb); + for (size_t i = 0; i < nb; ++i) + ids[i] = (int64_t(1) << 40) + i * 17; + std::vector assign(nq * np); + std::vector coarseDist(nq * np); + std::vector>> ref(nq); + std::vector> score(nq); + for (int q = 0; q < nq; ++q) { + for (int p = 0; p < np; ++p) { + int l = (p + q) % nl; + assign[q * np + p] = np > 1 && p == np - 1 ? -1 : l; + if (assign[q * np + p] < 0) + continue; + for (int j = 0; j < d; ++j) { + float x = queries[q * d + j], + c = coarse[l * d + j]; + coarseDist[q * np + p] += + isL2 ? (x - c) * (x - c) : x * c; + } + for (uint32_t v = offsets[l]; + v < offsets[l] + lengths[l]; + ++v) { + double distance = 0; + for (int j = 0; j < d; ++j) { + float reconstructed = coarse[l * d + j] + + pq[((j / dsub) * 256 + + codes[size_t(v) * M + + j / dsub]) * + dsub + + j % dsub]; + double x = queries[q * d + j]; + distance += isL2 ? (x - reconstructed) * + (x - reconstructed) + : x * reconstructed; + } + score[q][ids[v]] = distance; + ref[q].emplace_back(distance, ids[v]); + } + } + std::sort( + ref[q].begin(), + ref[q].end(), + [isL2](const auto& a, const auto& b) { + return a.first == b.first + ? a.second < b.second + : (isL2 ? a.first < b.first + : a.first > b.first); + }); + } + auto device = resources_->getDevice(); + auto buffer = [&](const void* src, size_t bytes) { + if (bytes == 0) + return [device + newBufferWithLength:1 + options:MTLResourceStorageModeShared]; + return src + ? [device newBufferWithBytes:src + length:bytes + options:MTLResourceStorageModeShared] + : [device newBufferWithLength:bytes + options:MTLResourceStorageModeShared]; + }; + auto qb = buffer(queries.data(), queries.size() * 4); + auto cb = buffer(coarse.data(), coarse.size() * 4); + auto pb = buffer(pq.data(), pq.size() * 4); + auto codesb = buffer(codes.data(), codes.size()); + auto ib = buffer(ids.data(), ids.size() * 8); + auto ob = buffer(offsets.data(), offsets.size() * 4); + auto lb = buffer(lengths.data(), lengths.size() * 4); + auto ab = buffer(assign.data(), assign.size() * 4); + auto db = buffer(coarseDist.data(), coarseDist.size() * 4); + auto qt = buffer(nullptr, size_t(nq) * M * 256 * 4); + auto t2 = buffer(nullptr, size_t(nl) * M * 256 * 4); + if (isL2 && !config.onTheFly) { + ASSERT_TRUE( + faiss::gpu_metal::runMetalIVFPQPrecomputeTerm2( + device, + resources_->getCommandQueue(), + cb, + pb, + t2, + nl, + d, + M)); + } + for (int k : {1, 20, 128, 512}) { + for (bool compact : {false, true}) { + SCOPED_TRACE( + ::testing::Message() + << "M=" << M << " d=" << d + << " short=" << shortLists << " L2=" << isL2 + << " onTheFly=" << config.onTheFly + << " k=" << k); + auto outD = buffer(nullptr, nq * k * 4), + outI = buffer(nullptr, nq * k * 8); + auto perD = buffer(nullptr, nq * np * k * 4), + perI = buffer(nullptr, nq * np * k * 8); + auto tmpD = buffer(nullptr, nq * np * k * 4), + tmpI = buffer(nullptr, nq * np * k * 8); + ASSERT_TRUE( + faiss::gpu_metal:: + runMetalIVFPQPrecompSearch( + device, + resources_ + ->getCommandQueue(), + qb, + ab, + db, + t2, + qt, + pb, + codesb, + ib, + ob, + lb, + nq, + d, + M, + k, + np, + isL2, + true, + outD, + outI, + perD, + perI, + tmpD, + tmpI, + true, + cb, + config.onTheFly, + shortLists, + compact)); + const auto* gd = + static_cast(outD.contents); + const auto* gi = + static_cast(outI.contents); + for (int q = 0; q < nq; ++q) { + std::set seen; + for (int j = 0; j < k; ++j) { + int pos = q * k + j; + if (j >= ref[q].size()) { + EXPECT_EQ(gi[pos], -1); + EXPECT_GE( + isL2 ? gd[pos] : -gd[pos], + 1e38f); + continue; + } + ASSERT_TRUE(score[q].count(gi[pos])); + EXPECT_TRUE(seen.insert(gi[pos]).second); + EXPECT_NEAR( + gd[pos], score[q][gi[pos]], 0.002); + EXPECT_NEAR( + gd[pos], ref[q][j].first, 0.002); + } + } + } + } + } + } + } + } +} diff --git a/thirdparty/faiss/faiss/gpu_metal/test/test_metal_python.py b/thirdparty/faiss/faiss/gpu_metal/test/test_metal_python.py index 9c885f2ea..e6093580d 100644 --- a/thirdparty/faiss/faiss/gpu_metal/test/test_metal_python.py +++ b/thirdparty/faiss/faiss/gpu_metal/test/test_metal_python.py @@ -87,6 +87,60 @@ def test_flat_gpu_to_cpu(self): np.testing.assert_array_equal(I_back, I_orig) +class TestMetalBinaryFlat(unittest.TestCase): + + def setUp(self): + if faiss.get_num_gpus() == 0: + self.skipTest("No Metal device") + + def test_clone_search_and_lifetime(self): + import gc + + rng = np.random.default_rng(1234) + xb = rng.integers(0, 256, (1537, 5), dtype=np.uint8) + xq = rng.integers(0, 256, (9, 5), dtype=np.uint8) + cpu = faiss.IndexBinaryFlat(40) + cpu.add(xb) + resources = faiss.StandardGpuResources() + gpu = faiss.index_binary_cpu_to_gpu(resources, 0, cpu) + del resources, cpu + gc.collect() + + xor = xq[:, None, :] ^ xb[None, :, :] + distances = np.unpackbits(xor, axis=2).sum(axis=2) + order = np.argsort(distances, axis=1, kind="stable")[:, :512] + expected = np.take_along_axis(distances, order, axis=1) + for _ in range(2): + d, labels = gpu.search(xq, 512) + self.assertEqual(d.dtype, np.int32) + self.assertEqual(labels.dtype, np.int64) + np.testing.assert_array_equal(d, expected) + np.testing.assert_array_equal(labels, order) + np.testing.assert_array_equal(gpu.reconstruct(17), xb[17]) + + back = faiss.index_binary_gpu_to_cpu(gpu) + gpu.reset() + self.assertEqual(back.ntotal, len(xb)) + np.testing.assert_array_equal(back.reconstruct(17), xb[17]) + gpu.add(xb[:7]) + d, labels = gpu.search(xq, 20) + self.assertTrue(np.all(labels[:, 7:] == -1)) + self.assertTrue(np.all(d[:, 7:] == np.iinfo(np.int32).max)) + + def test_cpu_fallback_and_invalid_device(self): + xb = np.arange(200, dtype=np.uint8).reshape(100, 2) + cpu = faiss.IndexBinaryFlat(16) + cpu.add(xb) + resources = faiss.StandardGpuResources() + with self.assertRaises(RuntimeError): + faiss.index_binary_cpu_to_gpu(resources, 1, cpu) + gpu = faiss.index_binary_cpu_to_gpu(resources, 0, cpu) + expected_d, expected_i = cpu.search(xb[:3], 513) + d, labels = gpu.search(xb[:3], 513) + np.testing.assert_array_equal(d, expected_d) + np.testing.assert_array_equal(labels, expected_i) + + class TestMetalIVFFlat(unittest.TestCase): def test_ivfflat_l2(self): @@ -284,5 +338,40 @@ def test_ivfpq_gpu_to_cpu_roundtrip(self): np.testing.assert_array_equal(I_back, I_orig) +class TestMetalAllGpusHelpers(unittest.TestCase): + + def test_index_cpu_to_all_gpus(self): + if faiss.get_num_gpus() == 0: + self.skipTest("No Metal device") + d, nb, nq, k = 32, 500, 5, 3 + np.random.seed(77) + xb = np.random.randn(nb, d).astype(np.float32) + xq = np.random.randn(nq, d).astype(np.float32) + + cpu_index = faiss.IndexFlatL2(d) + cpu_index.add(xb) + gpu_index = faiss.index_cpu_to_all_gpus(cpu_index) + + D_gpu, I_gpu = gpu_index.search(xq, k) + D_cpu, I_cpu = cpu_index.search(xq, k) + np.testing.assert_allclose(D_gpu, D_cpu, rtol=1e-5, atol=1e-5) + np.testing.assert_array_equal(I_gpu, I_cpu) + + def test_kmeans_gpu(self): + if faiss.get_num_gpus() == 0: + self.skipTest("No Metal device") + d, n, k = 16, 2000, 10 + np.random.seed(88) + x = np.random.randn(n, d).astype(np.float32) + + km_cpu = faiss.Kmeans(d, k, niter=5, seed=1) + km_cpu.train(x) + km_gpu = faiss.Kmeans(d, k, niter=5, seed=1, gpu=True) + km_gpu.train(x) + np.testing.assert_allclose( + km_gpu.centroids, km_cpu.centroids, rtol=1e-4, atol=1e-4 + ) + + if __name__ == "__main__": unittest.main() diff --git a/thirdparty/faiss/faiss/gpu_metal/test/test_metal_wheel.py b/thirdparty/faiss/faiss/gpu_metal/test/test_metal_wheel.py new file mode 100644 index 000000000..45dad607c --- /dev/null +++ b/thirdparty/faiss/faiss/gpu_metal/test/test_metal_wheel.py @@ -0,0 +1,130 @@ +# 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. + +"""Opt-in installed-wheel test using a relocated, dedicated Metal build. + +Build swigfaiss in a temporary build directory, then move that directory away +from its original path. Set FAISS_METAL_WHEEL_BUILD_DIR to the relocated build +and FAISS_METAL_WHEEL_ORIGINAL_BUILD_DIR to its now nonexistent original path. +The test never moves or edits the supplied build. Requires setuptools, wheel, +pip, numpy, packaging, and a Metal device. Run this file with unittest. +""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +import zipfile + + +class TestMetalWheel(unittest.TestCase): + @unittest.skipUnless( + os.environ.get("FAISS_METAL_WHEEL_BUILD_DIR"), + "Requires a relocated dedicated Metal build", + ) + def test_installed_wheel_without_build_tree(self): + build = Path(os.environ["FAISS_METAL_WHEEL_BUILD_DIR"]).resolve() + original = Path( + os.environ["FAISS_METAL_WHEEL_ORIGINAL_BUILD_DIR"] + ).absolute() + self.assertFalse( + original.exists(), "Original build tree must be unavailable" + ) + python_build = build / "faiss/python" + shader = build / "faiss/gpu_metal/MetalDistance.metallib" + source = Path(__file__).resolve().parents[2] / "python" + # Verify that the extension really refers to the absent path, rather + # than accidentally testing another build with an available metallib. + embedded_path = os.fsencode( + str(original / "faiss/gpu_metal/MetalDistance.metallib") + ) + self.assertTrue( + embedded_path in (python_build / "_swigfaiss.so").read_bytes(), + "Extension must refer to the unavailable original build tree", + ) + with tempfile.TemporaryDirectory( + prefix="faiss-metal-wheel-" + ) as directory: + stage = Path(directory) / "inputs" + stage.mkdir() + # Use the current source setup.py, not an older configured copy. + shutil.copy2(source / "setup.py", stage / "setup.py") + for path in python_build.glob("*.py"): + if path.name != "setup.py": + shutil.copy2(path, stage / path.name) + shutil.copy2( + python_build / "_swigfaiss.so", stage / "_swigfaiss.so" + ) + shutil.copytree(python_build / "contrib", stage / "contrib") + shutil.copy2(shader, stage / shader.name) + subprocess.run( + [sys.executable, "setup.py", "bdist_wheel"], + cwd=stage, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + wheel, = (stage / "dist").glob("*.whl") + with zipfile.ZipFile(wheel) as archive: + self.assertIn( + "faiss/MetalDistance.metallib", archive.namelist() + ) + wheel_shader = archive.read("faiss/MetalDistance.metallib") + self.assertTrue( + wheel_shader == shader.read_bytes(), + "The wheel must contain the newly built shader library", + ) + target = Path(directory) / "installed" + subprocess.run( + [ + sys.executable, "-m", "pip", "install", + "--no-deps", "--no-index", + "--target", str(target), str(wheel), + ], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + env = os.environ.copy() + env.pop("FAISS_METALLIB_PATH", None) + env["PYTHONPATH"] = str(target) + # A fresh process avoids the global pipeline/library cache. Its + # extension has an unavailable compiled-in build path, so successful + # searches must load the packaged metallib through dladdr lookup. + subprocess.run( + [sys.executable, "-c", """ +from pathlib import Path +import faiss +import numpy as np +import sys +assert Path(faiss.__file__).resolve().is_relative_to( + Path(sys.argv[1]).resolve()) +assert not Path(sys.argv[2]).exists() +assert faiss.get_num_gpus() > 0, 'A real Metal device is required' +r = faiss.StandardGpuResources() +x = np.array([[0, 1, 2], [255, 254, 253]], dtype=np.uint8) +cpu = faiss.IndexBinaryFlat(24) +cpu.add(x) +gpu = faiss.index_binary_cpu_to_gpu(r, 0, cpu) +d, labels = gpu.search(x, 2) +np.testing.assert_array_equal(d, [[0, 24], [0, 24]]) +np.testing.assert_array_equal(labels, [[0, 1], [1, 0]]) +flat = faiss.IndexFlatL2(2) +flat.add(np.array([[0, 0], [1, 1]], dtype=np.float32)) +metal = faiss.index_cpu_to_gpu(r, 0, flat) +d, labels = metal.search(np.array([[0, 0]], dtype=np.float32), 2) +np.testing.assert_array_equal(d, [[0, 2]]) +np.testing.assert_array_equal(labels, [[0, 1]]) +""", str(target), str(original)], cwd=directory, env=env, check=True, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/faiss/impl/AuxIndexStructures.cpp b/thirdparty/faiss/faiss/impl/AuxIndexStructures.cpp index 66aa2b94d..fbaba7496 100644 --- a/thirdparty/faiss/faiss/impl/AuxIndexStructures.cpp +++ b/thirdparty/faiss/faiss/impl/AuxIndexStructures.cpp @@ -123,7 +123,7 @@ RangeSearchPartialResult::RangeSearchPartialResult(RangeSearchResult* res_in) /// begin a new result RangeQueryResult& RangeSearchPartialResult::new_result(idx_t qno) { - RangeQueryResult qres = {qno, 0, this}; + RangeQueryResult qres = {qno, 0, this, {}}; queries.push_back(qres); return queries.back(); } @@ -246,6 +246,8 @@ void TimeoutCallback::set_timeout(double timeout_in_seconds) { } bool TimeoutCallback::want_interrupt() { + static std::mutex mutex; + std::lock_guard guard(mutex); if (timeout == 0) { return false; } diff --git a/thirdparty/faiss/faiss/impl/AuxIndexStructures.h b/thirdparty/faiss/faiss/impl/AuxIndexStructures.h index 58a80997a..3147202c6 100644 --- a/thirdparty/faiss/faiss/impl/AuxIndexStructures.h +++ b/thirdparty/faiss/faiss/impl/AuxIndexStructures.h @@ -146,12 +146,7 @@ struct FAISS_API InterruptCallback { static void clear_instance(); - /** check if: - * - an interrupt callback is set - * - the callback returns true - * if this is the case, then throw an exception. Should not be called - * from multiple threads. - */ + /// Concurrent calls require a thread-safe want_interrupt(). static void check(); /// same as check() but return true if is interrupted instead of diff --git a/thirdparty/faiss/faiss/impl/ClusteringHelpers.cpp b/thirdparty/faiss/faiss/impl/ClusteringHelpers.cpp index 669cdacf4..582271cee 100644 --- a/thirdparty/faiss/faiss/impl/ClusteringHelpers.cpp +++ b/thirdparty/faiss/faiss/impl/ClusteringHelpers.cpp @@ -7,6 +7,8 @@ #include +#include +#include #include #include #include @@ -20,11 +22,88 @@ #include #include +#include #include +#include namespace faiss { namespace detail { +namespace { + +#if defined(_OPENMP) && !defined(FAISS_USE_OMP_MOCK) +/// Below this many values, the fp16 finiteness check stays on one thread. +constexpr size_t fp16_parallel_threshold = size_t(1) << 16; +#endif + +/** Shared body of compute_centroids and compute_centroids_fp16. + * + * `add_row(i, w, c, scratch)` adds training vector i to the fp32 vector c, + * scaled by *w when w is not null. `scratch` is a per-thread buffer of d + * floats. + */ +template +void compute_centroids_impl( + size_t d, + size_t k, + size_t n, + size_t k_frozen, + const int64_t* assign, + const float* weights, + float* hassign, + float* centroids, + const AddRow& add_row) { + k -= k_frozen; + centroids += k_frozen * d; + + memset(centroids, 0, sizeof(*centroids) * d * k); + + std::atomic invalid_assignment{false}; + const int64_t num_centroids = static_cast(k + k_frozen); +#pragma omp parallel + { + int nt = omp_get_num_threads(); + int rank = omp_get_thread_num(); + + // this thread is taking care of centroids c0:c1 + size_t c0 = (k * rank) / nt; + size_t c1 = (k * (rank + 1)) / nt; + std::vector scratch(d); + + for (size_t i = 0; i < n; i++) { + int64_t ci = assign[i]; + if (ci < 0 || ci >= num_centroids) { + invalid_assignment.store(true, std::memory_order_relaxed); + continue; + } + ci -= k_frozen; + if (ci >= static_cast(c0) && + ci < static_cast(c1)) { + const float* w = weights ? weights + i : nullptr; + hassign[ci] += w ? *w : 1.0f; + add_row(i, w, centroids + ci * d, scratch.data()); + } + } + } + FAISS_THROW_IF_MSG( + invalid_assignment.load(std::memory_order_relaxed), + "invalid cluster assignment"); + +#pragma omp parallel for + for (idx_t ci = 0; ci < static_cast(k); ci++) { + if (hassign[ci] == 0) { + continue; + } + float norm = 1 / hassign[ci]; + float* c = centroids + ci * d; + for (size_t j = 0; j < d; j++) { + c[j] *= norm; + } + } +} + +} // namespace + uint64_t get_actual_rng_seed(const int seed) { return (seed >= 0) ? seed @@ -109,66 +188,76 @@ void compute_centroids( const float* weights, float* hassign, float* centroids) { - k -= k_frozen; - centroids += k_frozen * d; - - memset(centroids, 0, sizeof(*centroids) * d * k); - - size_t line_size = codec ? codec->sa_code_size() : d * sizeof(float); - -#pragma omp parallel - { - int nt = omp_get_num_threads(); - int rank = omp_get_thread_num(); - - // this thread is taking care of centroids c0:c1 - size_t c0 = (k * rank) / nt; - size_t c1 = (k * (rank + 1)) / nt; - std::vector decode_buffer(d); - - for (size_t i = 0; i < n; i++) { - int64_t ci = assign[i]; - FAISS_THROW_IF_NOT_MSG( - ci >= 0 && ci < k + k_frozen, "invalid cluster assignment"); - ci -= k_frozen; - if (ci >= static_cast(c0) && - ci < static_cast(c1)) { - float* c = centroids + ci * d; + const size_t line_size = codec ? codec->sa_code_size() : d * sizeof(float); + compute_centroids_impl( + d, + k, + n, + k_frozen, + assign, + weights, + hassign, + centroids, + [&](size_t i, const float* w, float* c, float* scratch) { const float* xi; if (!codec) { xi = reinterpret_cast(x + i * line_size); } else { - float* xif = decode_buffer.data(); - codec->sa_decode(1, x + i * line_size, xif); - xi = xif; + codec->sa_decode(1, x + i * line_size, scratch); + xi = scratch; } - if (weights) { - float w = weights[i]; - hassign[ci] += w; + if (w) { + const float wi = *w; for (size_t j = 0; j < d; j++) { - c[j] += xi[j] * w; + c[j] += xi[j] * wi; } } else { - hassign[ci] += 1.0; for (size_t j = 0; j < d; j++) { c[j] += xi[j]; } } - } - } - } + }); +} -#pragma omp parallel for - for (idx_t ci = 0; ci < static_cast(k); ci++) { - if (hassign[ci] == 0) { - continue; - } - float norm = 1 / hassign[ci]; - float* c = centroids + ci * d; - for (size_t j = 0; j < d; j++) { - c[j] *= norm; +void compute_centroids_fp16( + size_t d, + size_t k, + size_t n, + size_t k_frozen, + const uint16_t* x, + const int64_t* assign, + const float* weights, + float* hassign, + float* centroids) { + with_selected_simd_levels([&]() { + compute_centroids_impl( + d, + k, + n, + k_frozen, + assign, + weights, + hassign, + centroids, + [&](size_t i, const float* w, float* c, float* /*scratch*/) { + // x * 1.0f is exact, so unweighted sums match the + // fp32 path. + fp16_madd(d, x + i * d, w ? *w : 1.0f, c); + }); + }); +} + +bool fp16_all_finite(size_t n, const uint16_t* x) { + // binary16 NaNs and infinities are the values with all exponent bits set + constexpr uint16_t exponent_mask = 0x7c00; + std::atomic all_finite{true}; +#pragma omp parallel for if (n > fp16_parallel_threshold) + for (int64_t i = 0; i < static_cast(n); i++) { + if ((x[i] & exponent_mask) == exponent_mask) { + all_finite.store(false, std::memory_order_relaxed); } } + return all_finite.load(std::memory_order_relaxed); } // a bit above machine epsilon for float16 diff --git a/thirdparty/faiss/faiss/impl/ClusteringHelpers.h b/thirdparty/faiss/faiss/impl/ClusteringHelpers.h index a9e67cb56..fe55ba157 100644 --- a/thirdparty/faiss/faiss/impl/ClusteringHelpers.h +++ b/thirdparty/faiss/faiss/impl/ClusteringHelpers.h @@ -51,6 +51,15 @@ idx_t subsample_training_set( uint8_t** x_out, float** weights_out); +/** Initialize non-random centroids directly from packed IEEE binary16 rows. */ +void init_centroids_fp16( + const ClusteringInitialization& initializer, + size_t n, + const uint16_t* x, + float* centroids, + size_t n_existing_centroids = 0, + const float* existing_centroids = nullptr); + /** compute centroids as (weighted) sum of training points * * @param x training vectors, size n * code_size (from codec) @@ -75,6 +84,33 @@ void compute_centroids( float* hassign, float* centroids); +/** Same as compute_centroids for training vectors stored as packed IEEE + * binary16 values. + * + * Rows are widened in registers and accumulated directly into the fp32 + * centroids: there is no per-row decode call and no decode buffer. + * + * @param x training vectors, size n * d + */ +void compute_centroids_fp16( + size_t d, + size_t k, + size_t n, + size_t k_frozen, + const uint16_t* x, + const int64_t* assign, + const float* weights, + float* hassign, + float* centroids); + +/** Check packed IEEE binary16 values for NaNs and infinities. + * + * The check runs on the bit patterns, without widening to fp32. + * + * @return true iff none of the `n` values is a NaN or an infinity + */ +bool fp16_all_finite(size_t n, const uint16_t* x); + /** Handle empty clusters by splitting larger ones. * * It works by slightly changing the centroids to make 2 clusters from diff --git a/thirdparty/faiss/faiss/impl/ClusteringInitialization.cpp b/thirdparty/faiss/faiss/impl/ClusteringInitialization.cpp index 0ad60fd61..ce9c0a96c 100644 --- a/thirdparty/faiss/faiss/impl/ClusteringInitialization.cpp +++ b/thirdparty/faiss/faiss/impl/ClusteringInitialization.cpp @@ -13,11 +13,15 @@ #include #include #include +#include #include +#include #include +#include #include #include +#include namespace faiss { @@ -32,37 +36,90 @@ uint64_t get_seed(int64_t seed) { .count()); } +struct FloatRows { + static constexpr bool needs_scratch = false; + static constexpr bool has_fixed_simd_level = false; + + size_t d; + const float* x; + + const float* row(size_t idx, float*) const { + return x + idx * d; + } + + void copy_row(size_t idx, float* out) const { + std::memcpy(out, x + idx * d, d * sizeof(float)); + } +}; + +template +struct Fp16Rows { + static constexpr bool needs_scratch = true; + static constexpr bool has_fixed_simd_level = true; + static constexpr SIMDLevel simd_level = SL; + + size_t d; + const uint16_t* x; + + const float* row(size_t idx, float* scratch) const { + detail::fp16_to_fp32_kernel(d, x + idx * d, scratch); + return scratch; + } + + void copy_row(size_t idx, float* out) const { + detail::fp16_to_fp32_kernel(d, x + idx * d, out); + } + + void copy_rows(size_t idx, size_t count, float* out) const { + detail::fp16_to_fp32_kernel(count * d, x + idx * d, out); + } +}; + +template +auto with_rows_simd_level(Action&& action) { + if constexpr (Rows::has_fixed_simd_level) { + return action.template operator()(); + } else { + return with_simd_level(std::forward(action)); + } +} + +template +std::vector row_scratch(size_t d) { + return std::vector(Rows::needs_scratch ? d : 0); +} + /// Compute distance from point idx to its nearest centroid. /// Optionally checks both primary and secondary centroid sets. +template float distance_to_nearest_centroid( - size_t d, + const Rows& rows, size_t n_centroids, - const float* x, size_t idx, const float* centroids, - size_t n_existing_centroids = 0, - const float* existing_centroids = nullptr) { + size_t n_existing_centroids, + const float* existing_centroids, + float* scratch) { if (n_centroids == 0 && n_existing_centroids == 0) { return std::numeric_limits::infinity(); } - const float* point = x + idx * d; + const float* point = rows.row(idx, scratch); float min_dist = std::numeric_limits::max(); auto check_centroids = [&]() { - // Check primary centroids for (size_t c = 0; c < n_centroids; c++) { - float dist = fvec_L2sqr(point, centroids + c * d, d); + float dist = fvec_L2sqr(point, centroids + c * rows.d, rows.d); min_dist = std::min(min_dist, dist); } - // Check existing centroids if provided for (size_t c = 0; c < n_existing_centroids; c++) { - float dist = fvec_L2sqr(point, existing_centroids + c * d, d); + float dist = fvec_L2sqr( + point, existing_centroids + c * rows.d, rows.d); min_dist = std::min(min_dist, dist); } }; - with_simd_level(check_centroids); + with_rows_simd_level(check_centroids); return min_dist; } @@ -78,10 +135,10 @@ struct InitDistancesResult { /// Otherwise, selects first centroid randomly and computes distances to it. /// Returns first_new_centroid_idx (0 if existing, 1 if random first), /// sum of squared distances, and the first selected index (if applicable). +template InitDistancesResult init_distances_for_d2_sampling( - size_t d, size_t n, - const float* x, + const Rows& rows, float* centroids, size_t n_existing_centroids, const float* existing_centroids, @@ -89,25 +146,30 @@ InitDistancesResult init_distances_for_d2_sampling( std::mt19937_64& rng) { double sum_d2 = 0.0; size_t first_selected_idx = 0; + auto scratch = row_scratch(rows.d); if (n_existing_centroids > 0 && existing_centroids != nullptr) { - // Compute distances to nearest existing centroid for (size_t i = 0; i < n; i++) { distances[i] = distance_to_nearest_centroid( - d, n_existing_centroids, x, i, existing_centroids); + rows, + n_existing_centroids, + i, + existing_centroids, + 0, + nullptr, + scratch.data()); sum_d2 += distances[i]; } return {0, sum_d2, 0}; } else { - // Select first centroid randomly std::uniform_int_distribution uniform_dist(0, n - 1); first_selected_idx = uniform_dist(rng); - std::memcpy(centroids, x + first_selected_idx * d, d * sizeof(float)); + rows.copy_row(first_selected_idx, centroids); - // Compute distances to first centroid - with_simd_level([&]() { + with_rows_simd_level([&]() { for (size_t i = 0; i < n; i++) { - distances[i] = fvec_L2sqr(x + i * d, centroids, d); + const float* point = rows.row(i, scratch.data()); + distances[i] = fvec_L2sqr(point, centroids, rows.d); sum_d2 += distances[i]; } }); @@ -140,138 +202,97 @@ size_t sample_from_cumsum( return std::min(idx, n - 1); } -} // namespace - -ClusteringInitialization::ClusteringInitialization(size_t d_in, size_t k_in) - : d(d_in), k(k_in) {} - -void ClusteringInitialization::init_centroids( +template +void init_kmeans_plus_plus_impl( + const ClusteringInitialization& initializer, size_t n, - const float* x, + const Rows& rows, float* centroids, size_t n_existing_centroids, - const float* existing_centroids) const { - FAISS_THROW_IF_NOT_FMT( - n >= k, - "Number of points (%zu) must be >= number of centroids (%zu)", - n, - k); - FAISS_THROW_IF_NOT(d > 0); - FAISS_THROW_IF_NOT(x); - FAISS_THROW_IF_NOT(centroids); - FAISS_THROW_IF_NOT( - n_existing_centroids == 0 || existing_centroids != nullptr); - - switch (method) { - case ClusteringInitMethod::RANDOM: - init_random(n, x, centroids); - break; - case ClusteringInitMethod::KMEANS_PLUS_PLUS: - init_kmeans_plus_plus( - n, x, centroids, n_existing_centroids, existing_centroids); - break; - case ClusteringInitMethod::AFK_MC2: - init_afkmc2( - n, x, centroids, n_existing_centroids, existing_centroids); - break; - default: - FAISS_THROW_MSG("Unknown initialization method"); - } -} - -void ClusteringInitialization::init_random( - size_t n, - const float* x, - float* centroids) const { - // Use rand_perm for backward compatibility with Clustering.cpp - // This ensures the same random sequence as the original implementation - std::vector perm(n); - rand_perm(perm.data(), n, seed); - - // Copy selected points to centroids - for (size_t i = 0; i < k; i++) { - std::memcpy(centroids + i * d, x + perm[i] * d, d * sizeof(float)); - } -} - -void ClusteringInitialization::init_kmeans_plus_plus( - size_t n, - const float* x, - float* centroids, - size_t n_existing_centroids, - const float* existing_centroids) const { - std::mt19937_64 rng(get_seed(seed)); + const float* existing_centroids) { + std::mt19937_64 rng(get_seed(initializer.seed)); std::vector min_distances(n); auto result = init_distances_for_d2_sampling( - d, n, - x, + rows, centroids, n_existing_centroids, existing_centroids, min_distances, rng); - if (result.first_new_centroid_idx == 1 && k == 1) { + if (result.first_new_centroid_idx == 1 && initializer.k == 1) { return; } - // Reusable buffer for cumulative sum std::vector cumsum(n); - // Select remaining centroids using D² sampling - with_simd_level([&]() { - for (size_t c = result.first_new_centroid_idx; c < k; c++) { - // Compute cumulative sum + with_rows_simd_level([&]() { + for (size_t c = result.first_new_centroid_idx; c < initializer.k; c++) { cumsum[0] = min_distances[0]; for (size_t i = 1; i < n; i++) { cumsum[i] = cumsum[i - 1] + min_distances[i]; } - // Sample using precomputed cumsum size_t next_idx = sample_from_cumsum(cumsum, rng); - float* new_centroid = centroids + c * d; - std::memcpy(new_centroid, x + next_idx * d, d * sizeof(float)); - - // Update min distances incrementally. The writes are independent, - // so the loop parallelizes without changing the output. - const int64_t ni = static_cast(n); + float* new_centroid = centroids + c * rows.d; + rows.copy_row(next_idx, new_centroid); + + if constexpr (Rows::needs_scratch) { + constexpr size_t kRowsPerBlock = 64; + const int64_t nblocks = static_cast( + (n + kRowsPerBlock - 1) / kRowsPerBlock); +#pragma omp parallel + { + std::vector block(kRowsPerBlock * rows.d); +#pragma omp for + for (int64_t b = 0; b < nblocks; b++) { + const size_t first = + static_cast(b) * kRowsPerBlock; + const size_t count = std::min(kRowsPerBlock, n - first); + rows.copy_rows(first, count, block.data()); + for (size_t j = 0; j < count; j++) { + double dist = fvec_L2sqr( + block.data() + j * rows.d, + new_centroid, + rows.d); + min_distances[first + j] = + std::min(min_distances[first + j], dist); + } + } + } + } else { + const int64_t ni = static_cast(n); #pragma omp parallel for - for (int64_t i = 0; i < ni; i++) { - double dist = fvec_L2sqr(x + i * d, new_centroid, d); - min_distances[i] = std::min(min_distances[i], dist); + for (int64_t i = 0; i < ni; i++) { + double dist = fvec_L2sqr( + rows.row(i, nullptr), new_centroid, rows.d); + min_distances[i] = std::min(min_distances[i], dist); + } } } }); } -void ClusteringInitialization::init_afkmc2( +template +void init_afkmc2_impl( + const ClusteringInitialization& initializer, size_t n, - const float* x, + const Rows& rows, float* centroids, size_t n_existing_centroids, - const float* existing_centroids) const { - // AFK-MC² (Assumption-Free K-MC²) algorithm: - // Reference: Bachem et al., "Fast and Provably Good Seedings for - // k-Means" - - std::mt19937_64 rng(get_seed(seed)); + const float* existing_centroids) { + std::mt19937_64 rng(get_seed(initializer.seed)); std::uniform_real_distribution uniform_01(0.0, 1.0); - // Track selected centroids to prevent duplicates std::unordered_set selected_centroids; - // Compute proposal distribution q(x) - // If existing centroids: base q on distance to nearest existing - // centroid Otherwise: select first centroid randomly and base q on - // it std::vector dist_to_nearest(n); auto result = init_distances_for_d2_sampling( - d, n, - x, + rows, centroids, n_existing_centroids, existing_centroids, @@ -280,12 +301,11 @@ void ClusteringInitialization::init_afkmc2( if (result.first_new_centroid_idx == 1) { selected_centroids.insert(result.first_selected_idx); - if (k == 1) { + if (initializer.k == 1) { return; } } - // Compute q(x) and cumulative sum in a single pass std::vector q(n); std::vector q_cumsum(n); double uniform_term = 0.5 / static_cast(n); @@ -298,55 +318,42 @@ void ClusteringInitialization::init_afkmc2( q_cumsum[i] = (i > 0 ? q_cumsum[i - 1] : 0.0) + q[i]; } - // Main loop: Select remaining centroids using MCMC - for (size_t c = result.first_new_centroid_idx; c < k; c++) { - // Sample initial candidate from proposal distribution q, skip - // duplicates + auto scratch = row_scratch(rows.d); + for (size_t c = result.first_new_centroid_idx; c < initializer.k; c++) { size_t current_idx; do { current_idx = sample_from_cumsum(q_cumsum, rng); } while (selected_centroids.count(current_idx) > 0); - // Compute distance to nearest centroid (existing + newly - // selected) double current_dist = distance_to_nearest_centroid( - d, + rows, c, - x, current_idx, centroids, n_existing_centroids, - existing_centroids); + existing_centroids, + scratch.data()); double current_q = q[current_idx]; - // Run Markov chain - for (size_t m = 0; m < afkmc2_chain_length; m++) { - // Sample proposal from q + for (size_t m = 0; m < initializer.afkmc2_chain_length; m++) { size_t proposed_idx = sample_from_cumsum(q_cumsum, rng); - // Skip duplicates before expensive distance computation if (selected_centroids.count(proposed_idx) > 0) { continue; } - // Compute distance to nearest centroid (existing + newly - // selected) double proposed_dist = distance_to_nearest_centroid( - d, + rows, c, - x, proposed_idx, centroids, n_existing_centroids, - existing_centroids); + existing_centroids, + scratch.data()); double proposed_q = q[proposed_idx]; - // Metropolis-Hastings acceptance ratio: - // accept = min(1, d(y,C)² · q(x) / (d(x,C)² · q(y))) double acceptance_prob = 0.0; if (current_dist <= 0) { - // Current point is a centroid (distance = 0), never - // leave acceptance_prob = 0.0; } else if (proposed_q > 0) { double numerator = proposed_dist * current_q; @@ -361,10 +368,134 @@ void ClusteringInitialization::init_afkmc2( } } - // Use final chain state as new centroid selected_centroids.insert(current_idx); - std::memcpy(centroids + c * d, x + current_idx * d, d * sizeof(float)); + rows.copy_row(current_idx, centroids + c * rows.d); + } +} + +void validate_initialization( + const ClusteringInitialization& initializer, + size_t n, + const void* x, + float* centroids, + size_t n_existing_centroids, + const float* existing_centroids) { + FAISS_THROW_IF_NOT_FMT( + n >= initializer.k, + "Number of points (%zu) must be >= number of centroids (%zu)", + n, + initializer.k); + FAISS_THROW_IF_NOT(initializer.d > 0); + FAISS_THROW_IF_NOT(x); + FAISS_THROW_IF_NOT(centroids); + FAISS_THROW_IF_NOT( + n_existing_centroids == 0 || existing_centroids != nullptr); +} + +void init_random( + const ClusteringInitialization& initializer, + size_t n, + const float* x, + float* centroids) { + const size_t d = initializer.d; + // Use rand_perm for backward compatibility with Clustering.cpp + // This ensures the same random sequence as the original implementation + std::vector perm(n); + rand_perm(perm.data(), n, initializer.seed); + + for (size_t i = 0; i < initializer.k; i++) { + std::memcpy(centroids + i * d, x + perm[i] * d, d * sizeof(float)); } } +} // namespace + +ClusteringInitialization::ClusteringInitialization(size_t d_in, size_t k_in) + : d(d_in), k(k_in) {} + +void ClusteringInitialization::init_centroids( + size_t n, + const float* x, + float* centroids, + size_t n_existing_centroids, + const float* existing_centroids) const { + validate_initialization( + *this, n, x, centroids, n_existing_centroids, existing_centroids); + + switch (method) { + case ClusteringInitMethod::RANDOM: + init_random(*this, n, x, centroids); + break; + case ClusteringInitMethod::KMEANS_PLUS_PLUS: + init_kmeans_plus_plus_impl( + *this, + n, + FloatRows{d, x}, + centroids, + n_existing_centroids, + existing_centroids); + break; + case ClusteringInitMethod::AFK_MC2: + init_afkmc2_impl( + *this, + n, + FloatRows{d, x}, + centroids, + n_existing_centroids, + existing_centroids); + break; + default: + FAISS_THROW_MSG("Unknown initialization method"); + } +} + +namespace detail { + +void init_centroids_fp16( + const ClusteringInitialization& initializer, + size_t n, + const uint16_t* x, + float* centroids, + size_t n_existing_centroids, + const float* existing_centroids) { + validate_initialization( + initializer, + n, + x, + centroids, + n_existing_centroids, + existing_centroids); + + with_selected_simd_levels([&]() { + switch (initializer.method) { + case ClusteringInitMethod::KMEANS_PLUS_PLUS: + init_kmeans_plus_plus_impl( + initializer, + n, + Fp16Rows{initializer.d, x}, + centroids, + n_existing_centroids, + existing_centroids); + break; + case ClusteringInitMethod::AFK_MC2: + init_afkmc2_impl( + initializer, + n, + Fp16Rows{initializer.d, x}, + centroids, + n_existing_centroids, + existing_centroids); + break; + case ClusteringInitMethod::RANDOM: + FAISS_THROW_MSG( + "fp16 centroid helper requires non-random " + "initialization"); + default: + FAISS_THROW_MSG("Unknown initialization method"); + } + }); +} + +} // namespace detail + } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/ClusteringInitialization.h b/thirdparty/faiss/faiss/impl/ClusteringInitialization.h index 3f9af6688..3e93b41cd 100644 --- a/thirdparty/faiss/faiss/impl/ClusteringInitialization.h +++ b/thirdparty/faiss/faiss/impl/ClusteringInitialization.h @@ -87,21 +87,6 @@ struct ClusteringInitialization { float* centroids, size_t n_existing_centroids = 0, const float* existing_centroids = nullptr) const; - - private: - void init_random(size_t n, const float* x, float* centroids) const; - void init_kmeans_plus_plus( - size_t n, - const float* x, - float* centroids, - size_t n_existing_centroids, - const float* existing_centroids) const; - void init_afkmc2( - size_t n, - const float* x, - float* centroids, - size_t n_existing_centroids, - const float* existing_centroids) const; }; } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/CodePacker.cpp b/thirdparty/faiss/faiss/impl/CodePacker.cpp index 618940887..6e984d831 100644 --- a/thirdparty/faiss/faiss/impl/CodePacker.cpp +++ b/thirdparty/faiss/faiss/impl/CodePacker.cpp @@ -50,7 +50,7 @@ void CodePackerFlat::unpack_all(const uint8_t* block, uint8_t* flat_codes) void CodePackerFlat::pack_1( const uint8_t* flat_code, - size_t offset, + [[maybe_unused]] size_t offset, uint8_t* block) const { assert(offset == 0); pack_all(flat_code, block); @@ -58,7 +58,7 @@ void CodePackerFlat::pack_1( void CodePackerFlat::unpack_1( const uint8_t* block, - size_t offset, + [[maybe_unused]] size_t offset, uint8_t* flat_code) const { assert(offset == 0); unpack_all(block, flat_code); diff --git a/thirdparty/faiss/faiss/impl/CodePackerRaBitQ.cpp b/thirdparty/faiss/faiss/impl/CodePackerRaBitQ.cpp index 0a3f73f35..c33e90c7e 100644 --- a/thirdparty/faiss/faiss/impl/CodePackerRaBitQ.cpp +++ b/thirdparty/faiss/faiss/impl/CodePackerRaBitQ.cpp @@ -13,10 +13,10 @@ namespace faiss { CodePackerRaBitQ::CodePackerRaBitQ( - size_t nsq, + size_t nsq_in, size_t bbs, size_t aux_per_vector) { - this->nsq = nsq; + nsq = nsq_in; this->aux_size_per_vec = aux_per_vector; nvec = bbs; const size_t pq4_bytes = (nsq * 4 + 7) / 8; diff --git a/thirdparty/faiss/faiss/impl/DeterministicNNDescent.cpp b/thirdparty/faiss/faiss/impl/DeterministicNNDescent.cpp new file mode 100644 index 000000000..079e34d21 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/DeterministicNNDescent.cpp @@ -0,0 +1,2167 @@ +/* + * 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. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" { + +#ifndef FINTEGER +#define FINTEGER long +#endif + +int sgemm_( + const char* transa, + const char* transb, + FINTEGER* m, + FINTEGER* n, + FINTEGER* k, + const float* alpha, + const float* a, + FINTEGER* lda, + const float* b, + FINTEGER* ldb, + float* beta, + float* c, + FINTEGER* ldc); + +int ssyrk_( + const char* uplo, + const char* trans, + FINTEGER* n, + FINTEGER* k, + float* alpha, + float* a, + FINTEGER* lda, + float* beta, + float* c, + FINTEGER* ldc); +} + +namespace faiss { + +namespace { + +constexpr float kInf = std::numeric_limits::infinity(); + +/// (distance, id); operator< orders by (distance, id) +using DisId = std::pair; +using DisId64 = std::pair; + +/// a hash of x: the first output of SplitMix64 seeded with x +uint64_t mix64(uint64_t x) { + return SplitMix64RandomGenerator(int64_t(x)).next(); +} + +/// open-addressing map from ids to 0, 1, 2, ... in insertion order; +/// cleared in O(size) +struct IdMap { + std::vector keys; // -1: empty + std::vector vals; + std::vector used; + uint32_t mask = 0; + + IdMap() { + rehash(1024); + } + + void rehash(size_t size) { + std::vector ok = std::move(keys), ov = std::move(vals); + std::vector ou = std::move(used); + keys.assign(size, -1); + vals.assign(size, 0); + used.clear(); + mask = uint32_t(size - 1); + for (uint32_t h : ou) { + insert_new(ok[h], ov[h]); + } + } + + void clear() { + for (uint32_t h : used) { + keys[h] = -1; + } + used.clear(); + } + + uint32_t slot(int32_t id) const { + // high bits of a multiplicative hash: ids that share low bits spread + uint32_t h = uint32_t( + (uint64_t(uint32_t(id)) * 0x9e3779b97f4a7c15ULL) >> + 32) & + mask; + while (keys[h] >= 0 && keys[h] != id) { + h = (h + 1) & mask; + } + return h; + } + + void insert_new(int32_t id, int32_t val) { + const uint32_t h = slot(id); + keys[h] = id; + vals[h] = val; + used.push_back(h); + } + + /// value of id, inserting size() if absent; sets is_new + int32_t find_or_insert(int32_t id, bool& is_new) { + uint32_t h = slot(id); + if (keys[h] >= 0) { + is_new = false; + return vals[h]; + } + is_new = true; + const int32_t v = int32_t(used.size()); + keys[h] = id; + vals[h] = v; + used.push_back(h); + if (2 * used.size() > keys.size()) { + rehash(2 * keys.size()); + } + return v; + } +}; + +/** Per-thread read access to the float vectors of the storage. IndexFlat is + * read in place and IndexScalarQuantizer is decoded directly: + * Index::reconstruct of IndexScalarQuantizer opens a nested OpenMP region and + * allocates for each call. The pointer that get() returns is valid until the + * next get(). */ +struct VectorReader { + const Index& storage; + const size_t d; + const float* flat = nullptr; + const IndexScalarQuantizer* sq = nullptr; + std::unique_ptr squant; + std::vector buf; + + explicit VectorReader(const Index& s) : storage(s), d(s.d), buf(s.d) { + // exact types: subclasses such as IndexFlatPanorama change the layout + const std::type_info& t = typeid(s); + if (t == typeid(IndexFlat) || t == typeid(IndexFlatL2) || + t == typeid(IndexFlatIP)) { + flat = static_cast(s).get_xb(); + } else if (auto* q = dynamic_cast(&s)) { + // throws for a quantizer without a decoder, such as QT_0bit + sq = q; + squant.reset(q->sq.select_quantizer()); + } + } + + const float* get(idx_t i) { + if (flat) { + return flat + i * d; + } + decode(i, buf.data()); + return buf.data(); + } + + void decode(idx_t i, float* out) { + if (flat) { + std::copy_n(flat + i * d, d, out); + } else if (squant) { + squant->decode_vector(sq->codes.data() + i * sq->code_size, out); + } else { + storage.reconstruct(i, out); + } + } + + void prefetch(idx_t i) const { + const uint8_t* p; + size_t nbytes; + if (flat) { + p = reinterpret_cast(flat + i * d); + nbytes = d * sizeof(float); + } else if (squant) { + p = sq->codes.data() + i * sq->code_size; + nbytes = sq->code_size; + } else { + return; + } + for (size_t o = 0; o < std::min(nbytes, size_t(4096)); o += 64) { + prefetch_L1(p + o); + } + } +}; + +/// one smaller-is-better distance: L2, or the negated inner product. NaN +/// (overflow) becomes +inf and -0 becomes +0, as in products_to_distances() +float pair_distance( + MetricType metric_type, + const float* x, + const float* y, + size_t d) { + const float v = metric_type == METRIC_INNER_PRODUCT + ? -fvec_inner_product(x, y, d) + : fvec_L2sqr(x, y, d); + return std::isnan(v) ? kInf : v + 0.0f; +} + +/** Rows [0, r) of the upper triangle of the Gram matrix of the m rows of x + * into out (row-major, m columns): the entries i < r, j > i, by ssyrk + * (new x new) and sgemm (new x old); the other entries are not set. */ +void gram_upper_rows_blas( + const float* x, + size_t r, + size_t m, + size_t d, + float* out) { + FINTEGER ri = FINTEGER(r), di = FINTEGER(d), mi = FINTEGER(m); + float alpha = 1, beta = 0; + // column-major lower triangle = row-major upper triangle (j >= i) + ssyrk_("L", + "T", + &ri, + &di, + &alpha, + const_cast(x), + &di, + &beta, + out, + &mi); + if (m > r) { + FINTEGER oi = FINTEGER(m - r); + sgemm_("T", + "N", + &oi, + &ri, + &di, + &alpha, + x + r * d, + &di, + x, + &di, + &beta, + out + r, + &mi); + } +} + +/// levels with the nndescent::gram_upper_rows kernel: the higher AVX-512 +/// levels fall back to AVX512, and ARM_SVE to ARM_NEON. The others use BLAS. +constexpr int kGramLevels = + AVAILABLE_SIMD_LEVELS_AVX2_NEON | (1 << int(SIMDLevel::AVX512)); + +using GramKernel = void (*)( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out); + +/// the kernel of the SIMD level, or null for BLAS. The kernel reads the rows +/// through pointers, in place for flat storage, without the gather copy and +/// BLAS. BLAS called from an OpenMP region can open a nested region, so the +/// kernel is also the safer path. +GramKernel gram_kernel() { + GramKernel kernel = nullptr; + with_selected_simd_levels([&]() { + if constexpr (SL != SIMDLevel::NONE) { + kernel = &nndescent::gram_upper_rows; + } + }); + return kernel; +} + +/** Turns the inner products of gram_upper_rows_*() into distances, in place: + * negated for IP; for L2 from the squared norms, clamped at 0. Scaling by -1 + * or -2 is exact. A NaN (overflow) becomes +inf as in + * pipnn::gram_to_distance, and -0 becomes +0 so that a value has one bit + * pattern. A pair can get a different value in another join; the rounds do + * not depend on it (see drop_old_ids()). */ +void products_to_distances( + MetricType metric_type, + const float* norms, + size_t r, + size_t m, + float* out) { + const bool ip = metric_type == METRIC_INNER_PRODUCT; + for (size_t i = 0; i < r; i++) { + float* oi = out + i * m; + for (size_t j = i + 1; j < m; j++) { + float v = ip ? -oi[j] : norms[i] + norms[j] - 2 * oi[j]; + if (std::isnan(v)) { + v = kInf; + } else if (!ip) { + v = std::max(0.0f, v); + } + oi[j] = v + 0.0f; // -0 + 0 = +0 + } + } +} + +/// keeps the k smallest of cand by (dis, id), in any order +void keep_best(std::vector& cand, size_t k) { + if (cand.size() > k) { + std::nth_element(cand.begin(), cand.begin() + k, cand.end()); + cand.resize(k); + } +} + +struct Segment { + size_t begin, end; + uint64_t hash; +}; + +bool any_nonempty(const std::vector>& work) { + for (const std::vector& w : work) { + if (!w.empty()) { + return true; + } + } + return false; +} + +/// whether vector v is on the side of pivot a +struct OnPivotASide { + const uint8_t* side; + + bool operator()(int32_t v) const { + return side[v] == 0; + } +}; + +/// maximum points in a cluster tree leaf +constexpr size_t kLeafSize = 512; + +/** Splits the points of perms[t] by random cluster tree t, for all trees at + * once, and returns the leaves of each tree. Each level reads each vector + * once for all trees. The pivots of a segment come from its hash, so the + * trees do not depend on the thread count. */ +std::vector> cluster_trees( + const Index& storage, + std::vector>& perms, + uint64_t seed) { + const int T = int(perms.size()); + const size_t n = storage.ntotal; + const size_t d = storage.d; + const bool ip = storage.metric_type == METRIC_INNER_PRODUCT; + std::vector> work(T), leaves(T); + for (int t = 0; t < T; t++) { + const Segment root = {0, n, mix64(seed + t)}; + (n <= kLeafSize ? leaves[t] : work[t]).push_back(root); + } + // segment of each vector in the current level (-1: in a leaf), and side + std::vector segv(size_t(T) * n); + std::vector sidev(size_t(T) * n); + std::vector> w(T), c(T); + while (any_nonempty(work)) { + for (int t = 0; t < T; t++) { + // side test: nearer to pivot a than to pivot b, as one dot + // product: <= (|b|^2 - |a|^2) / 2 for L2, <= 0 for IP + const std::vector& perm = perms[t]; + const size_t ns = work[t].size(); + w[t].resize(ns * d); + c[t].resize(ns); + VectorReader vr(storage); + std::vector pa(d), pb(d); + for (size_t s = 0; s < ns; s++) { + const Segment& sg = work[t][s]; + const size_t size = sg.end - sg.begin; + const uint64_t r = mix64(sg.hash); + const size_t a = r % size; + const size_t b = (a + 1 + mix64(r) % (size - 1)) % size; + vr.decode(perm[sg.begin + a], pa.data()); + vr.decode(perm[sg.begin + b], pb.data()); + for (size_t k = 0; k < d; k++) { + w[t][s * d + k] = pb[k] - pa[k]; + } + c[t][s] = ip ? 0 + : (fvec_norm_L2sqr(pb.data(), d) - + fvec_norm_L2sqr(pa.data(), d)) / + 2; + } + int32_t* sv = segv.data() + size_t(t) * n; + std::fill(sv, sv + n, -1); +#pragma omp parallel for schedule(dynamic) + for (int64_t s = 0; s < int64_t(ns); s++) { + for (size_t i = work[t][s].begin; i < work[t][s].end; i++) { + sv[perm[i]] = int32_t(s); + } + } + } +#pragma omp parallel + { + VectorReader vr(storage); +#pragma omp for schedule(static) + for (int64_t v = 0; v < int64_t(n); v++) { + const float* x = nullptr; + for (int t = 0; t < T; t++) { + const int32_t q = segv[size_t(t) * n + v]; + if (q < 0) { + continue; + } + if (!x) { + x = vr.get(v); + } + sidev[size_t(t) * n + v] = + fvec_inner_product(x, w[t].data() + q * d, d) <= + c[t][q] + ? 0 + : 1; + } + } + } + for (int t = 0; t < T; t++) { + std::vector& perm = perms[t]; + const uint8_t* side = sidev.data() + size_t(t) * n; + const size_t ns = work[t].size(); + std::vector children(2 * ns); +#pragma omp parallel for schedule(dynamic) + for (int64_t s = 0; s < int64_t(ns); s++) { + const Segment sg = work[t][s]; + const auto first = perm.begin() + sg.begin; + size_t mid = sg.begin + + (std::stable_partition( + first, + perm.begin() + sg.end, + OnPivotASide{side}) - + first); + if (mid == sg.begin || mid == sg.end) { + // copies of one vector: split by position + mid = sg.begin + (sg.end - sg.begin) / 2; + } + children[2 * s] = {sg.begin, mid, mix64(sg.hash ^ 1)}; + children[2 * s + 1] = {mid, sg.end, mix64(sg.hash ^ 2)}; + } + std::vector next; + for (const Segment& cs : children) { + (cs.end - cs.begin <= kLeafSize ? leaves[t] : next) + .push_back(cs); + } + work[t].swap(next); + } + } + return leaves; +} + +} // namespace + +namespace { + +/// whether id is in the K slots of row; no early exit, so that the loop +/// vectorizes +template +inline bool row_contains(const Id* row, int K, Id id) { + int hit = 0; + for (int i = 0; i < K; i++) { + hit |= row[i] == id; + } + return hit != 0; +} + +/** Merges the candidates c[0..m) into the sorted row of K slots. The + * candidates are sorted by (distance, id) and have distinct ids. The row + * keeps the K best entries by (distance, id), with the smallest distance of + * each id. An entry from a candidate is new. The result does not depend on + * the order of the candidates. buf holds K entries and K flags. */ +template +void merge_into_row( + int K, + Id* ids, + float* dis, + uint8_t* is_new, + std::pair* c, + size_t m, + std::vector>& buf, + std::vector& buf_new) { + // a candidate with an id of the row replaces the entry if it is better, + // else it is dropped + size_t mk = 0; + for (size_t j = 0; j < m; j++) { + if (row_contains(ids, K, c[j].second)) { + int pos = 0; + while (ids[pos] != c[j].second) { + pos++; + } + if (!(c[j] < std::make_pair(dis[pos], ids[pos]))) { + continue; + } + ids[pos] = -2; // removed + } + c[mk++] = c[j]; + } + if (mk == 0) { + return; + } + buf.resize(K); + buf_new.resize(K); + int i = 0, k = 0; + size_t j = 0; + while (k < K) { + while (i < K && ids[i] == -2) { + i++; + } + const bool has_row = i < K && ids[i] >= 0; + const bool has_cand = j < mk; + if (!has_row && !has_cand) { + break; + } + if (has_cand && (!has_row || c[j] < std::make_pair(dis[i], ids[i]))) { + buf[k] = c[j++]; + buf_new[k++] = 1; + } else { + buf[k] = {dis[i], ids[i]}; + buf_new[k++] = is_new[i++]; + } + } + for (int t = 0; t < k; t++) { + ids[t] = buf[t].second; + dis[t] = buf[t].first; + is_new[t] = buf_new[t]; + } + for (int t = k; t < K; t++) { + ids[t] = -1; + dis[t] = kInf; + is_new[t] = 0; + } +} + +/** Keeps at the front of cand the candidates that can enter the row: by + * (distance, id), better than the K-th entry of a full row (its distance is + * kth), and with an id that is not in the old row orow. Returns the number + * kept. An id of the old row keeps + * its old entry. If the id could leave the row and come back, the row would + * depend on the order of the candidates when one pair gets two distances. */ +template +size_t drop_old_ids( + const Id* orow, + float kth, + int K, + std::vector>& cand) { + const bool full = orow[K - 1] >= 0; + const std::pair worst = {kth, orow[K - 1]}; + size_t m = 0; + for (const std::pair& c : cand) { + if ((full && !(c < worst)) || row_contains(orow, K, c.second)) { + continue; + } + cand[m++] = c; + } + return m; +} + +struct LeafScratch { + AlignedTable xl, dis; + std::vector norms; + std::vector rows; +}; + +/// all distances between the m points lp of a leaf, into ls.dis (m x m) +void leaf_distances( + MetricType metric_type, + GramKernel kernel, + const int32_t* lp, + size_t m, + VectorReader& vr, + LeafScratch& ls) { + const size_t d = vr.d; + // the kernel reads flat storage in place; BLAS reads one matrix + const bool in_place = kernel && vr.flat; + if (!in_place) { + pipnn::ensure_size(ls.xl, m * d); + } + ls.rows.resize(m); + ls.norms.resize(m); + for (size_t p = 0; p < m; p++) { + if (in_place) { + ls.rows[p] = vr.flat + size_t(lp[p]) * d; + } else { + vr.decode(lp[p], ls.xl.data() + p * d); + ls.rows[p] = ls.xl.data() + p * d; + } + ls.norms[p] = fvec_norm_L2sqr(ls.rows[p], d); + } + pipnn::ensure_size(ls.dis, m * m); + float* leaf_dis = ls.dis.data(); + if (kernel) { + kernel(ls.rows.data(), m, m, d, leaf_dis); + products_to_distances(metric_type, ls.norms.data(), m, m, leaf_dis); + for (size_t p = 0; p < m; p++) { + for (size_t q = p + 1; q < m; q++) { + leaf_dis[q * m + p] = leaf_dis[p * m + q]; + } + } + return; + } + pipnn::pairwise_distances( + ls.xl.data(), ls.norms.data(), m, d, metric_type, leaf_dis); + for (size_t e = 0; e < m * m; e++) { + leaf_dis[e] += 0.0f; // -0 + 0 = +0, as in products_to_distances + } +} + +/// merges the candidates into the row v of init(), as round() does +void add_to_row( + int K, + int32_t* ids, + float* dis, + uint8_t* is_new, + idx_t v, + std::vector& cand, + std::vector& buf, + std::vector& buf_new) { + const size_t o = size_t(v) * K; + const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, cand); + if (m == 0) { + return; + } + std::sort(cand.begin(), cand.begin() + m); + merge_into_row( + K, ids + o, dis + o, is_new + o, cand.data(), m, buf, buf_new); +} + +/// appends 2K random ids of [0, n) for node v, then the next ids, so that a +/// row of n - 1 >= K fills +void random_ids( + idx_t v, + idx_t n, + int K, + int64_t seed, + std::vector& c) { + const int want = int(std::min(K, n - 1)); + uint64_t r = mix64(uint64_t(seed) ^ mix64(v) ^ 0x5bd1e995); + for (int j = 0; j < 2 * want; j++) { + r = mix64(r); + c.push_back(int32_t(r % n)); + } + for (int j = 1; j <= want; j++) { + c.push_back(int32_t((v + j) % n)); + } +} + +} // namespace + +void DeterministicNNDescent::init(const Index& storage) { + check_params(); + FAISS_THROW_IF_NOT_MSG( + storage.metric_type == METRIC_L2 || + storage.metric_type == METRIC_INNER_PRODUCT, + "DeterministicNNDescent: only METRIC_L2 and METRIC_INNER_PRODUCT"); + FAISS_THROW_IF_NOT_MSG( + storage.d > 0, "DeterministicNNDescent: d must be > 0"); + FAISS_THROW_IF_NOT_MSG( + storage.ntotal < (idx_t(1) << 31), + "DeterministicNNDescent: at most 2^31 - 1 vectors"); + n = storage.ntotal; + d = storage.d; + metric_type = storage.metric_type; + const size_t nK = size_t(n) * K; + if (n > 0) { + // a storage that cannot reconstruct throws here, not inside OpenMP + VectorReader(storage).get(0); + } + ids.assign(nK, -1); + dis.assign(nK, kInf); + is_new.assign(nK, 1); + order.resize(n); + std::iota(order.begin(), order.end(), 0); + ndis = 0; + if (n <= 1) { + return; + } + const double t0 = getmillisecs(); + + size_t nd_total = 0; + if (ntrees > 0) { + std::vector> perms( + ntrees, std::vector(n)); + for (auto& perm : perms) { + std::iota(perm.begin(), perm.end(), 0); + } + const std::vector> all_leaves = + cluster_trees(storage, perms, uint64_t(seed)); + order = perms[0]; + const GramKernel kernel = gram_kernel(); + for (int t = 0; t < ntrees; t++) { + const std::vector& perm = perms[t]; + const std::vector& leaves = all_leaves[t]; +#pragma omp parallel reduction(+ : nd_total) + { + VectorReader vr(storage); + LeafScratch ls; + std::vector cand, buf; + std::vector buf_new; +#pragma omp for schedule(dynamic) + for (int64_t l = 0; l < int64_t(leaves.size()); l++) { + const int32_t* lp = perm.data() + leaves[l].begin; + const size_t m = leaves[l].end - leaves[l].begin; + leaf_distances(metric_type, kernel, lp, m, vr, ls); + const auto& leaf_dis = ls.dis; + nd_total += m * (m - 1) / 2; + for (size_t p = 0; p < m; p++) { + const float* ld = leaf_dis.data() + p * m; + // what cannot beat the K-th of the row cannot enter + const size_t ro = size_t(lp[p]) * K + K - 1; + const float rw = ids[ro] >= 0 ? dis[ro] : kInf; + cand.clear(); + for (size_t q = 0; q < m; q++) { + if (q != p && ld[q] <= rw) { + cand.push_back({ld[q], lp[q]}); + } + } + keep_best(cand, K); + add_to_row( + K, + ids.data(), + dis.data(), + is_new.data(), + lp[p], + cand, + buf, + buf_new); + } + } + } + } + } + // rows that the leaves left short, and all rows with ntrees = 0, get + // random neighbors +#pragma omp parallel reduction(+ : nd_total) + { + VectorReader rv(storage), rc(storage); + IdMap seen; + std::vector c; + std::vector cand, buf; + std::vector buf_new; +#pragma omp for schedule(dynamic, 256) + for (idx_t v = 0; v < n; v++) { + const int want = int(std::min(K, n - 1)); + if (ids[size_t(v) * K + want - 1] >= 0) { + continue; + } + c.clear(); + random_ids(v, n, K, seed, c); + // the ids of c that are not v and not in the row + seen.clear(); + bool is_new_id; + seen.find_or_insert(int32_t(v), is_new_id); + for (int j = 0; j < K && ids[size_t(v) * K + j] >= 0; j++) { + seen.find_or_insert(ids[size_t(v) * K + j], is_new_id); + } + const float* xv = rv.get(v); + cand.clear(); + for (int32_t id : c) { + seen.find_or_insert(id, is_new_id); + if (is_new_id) { + cand.push_back( + {pair_distance(metric_type, xv, rc.get(id), d), + id}); + } + } + nd_total += cand.size(); + keep_best(cand, K); + add_to_row( + K, + ids.data(), + dis.data(), + is_new.data(), + v, + cand, + buf, + buf_new); + } + } + // every entry is new for the first round, as in NNDescentShard::set_rows() +#pragma omp parallel for schedule(static) + for (int64_t e = 0; e < int64_t(nK); e++) { + is_new[e] = ids[e] >= 0; + } + ndis = nd_total; + if (verbose) { + printf("DeterministicNNDescent: init n=%" PRId64 + " K=%d in %.1f s, %.0f distances per node\n", + n, + K, + (getmillisecs() - t0) / 1000, + double(ndis) / n); + } +} + +namespace { + +struct SpinLock { + std::atomic_flag& flag; + explicit SpinLock(std::atomic_flag& f) : flag(f) { + while (flag.test_and_set(std::memory_order_acquire)) { + } + } + SpinLock(const SpinLock&) = delete; + SpinLock& operator=(const SpinLock&) = delete; + ~SpinLock() { + flag.clear(std::memory_order_release); + } +}; + +/// merge_into_row() of the sorted c[0..m) under the lock of the row; lowers +/// the K-th distance worst of the row +template +void merge_into_row_locked( + int K, + std::atomic_flag& lock, + std::atomic& worst, + Id* ids, + float* dis, + uint8_t* is_new, + std::pair* c, + size_t m, + std::vector>& buf, + std::vector& buf_new) { + SpinLock guard(lock); + merge_into_row(K, ids, dis, is_new, c, m, buf, buf_new); + if (ids[K - 1] >= 0) { + worst.store(dis[K - 1], std::memory_order_relaxed); + } +} + +/** The flags of the next rows at the start of a round: the local joins use + * the first S new entries of each row, and the other new entries stay new + * for the next round. */ +void unsampled_new( + const std::vector& is_new, + idx_t n, + int K, + int S, + std::vector& next_new) { + next_new.assign(is_new.size(), 0); +#pragma omp parallel for schedule(static) + for (idx_t v = 0; v < n; v++) { + int taken = 0; + for (int j = 0; j < K; j++) { + const size_t e = size_t(v) * K + j; + if (is_new[e] && taken++ >= S) { + next_new[e] = 1; + } + } + } +} + +/// number of rows with a new entry +idx_t count_rows_with_new(const std::vector& is_new, idx_t n, int K) { + idx_t changed = 0; +#pragma omp parallel for reduction(+ : changed) + for (idx_t v = 0; v < n; v++) { + const auto row = is_new.begin() + size_t(v) * K; + changed += std::find(row, row + K, 1) != row + K; + } + return changed; +} + +/// per-thread scratch of local_join() +template +struct JoinScratch { + IdMap seen; + std::vector nbr; ///< the new members, then the old ones + std::vector> lst; ///< (member, is new) + AlignedTable xs, out; + std::vector rows; + std::vector nrm, thr; + std::vector>> bk; + std::vector> mbuf; + std::vector mbuf_new; + + /// adds the members of the list l (len slots, -1 padded, with the flags + /// f) to lst. An id is new if one of its edges is new, and up to S + /// members of the list are new. + void collect(const int32_t* l, const uint8_t* f, int len, int S) { + int taken = 0; + for (int i = 0; i < len && l[i] >= 0; i++) { + bool fresh; + const bool want_new = f[i] && taken < S; + const int32_t k = seen.find_or_insert(l[i], fresh); + if (fresh) { + lst.push_back({l[i], uint8_t(want_new)}); + taken += want_new; + } else if (want_new && !lst[k].second) { + lst[k].second = 1; + taken++; + } + } + } +}; + +/** The local join of one neighborhood, for DeterministicNNDescent::round() + * and NNDescentShard::join_impl(). The members are storage indices: the + * out-list out_l (K slots) and the in-list in_l (Rr slots), -1 padded, with + * their new flags. Up to S new members of each list are new. For the pairs + * (new, new) and (new, old), each distance that can beat the K-th distance + * nworst[] of a member goes to acc.flush(member, cand, buf, buf_new) as + * (distance, acc.gid(other member)). + * + * acc.row(s, buf) returns the vector of member s, or decodes it into buf (d + * floats) and returns buf. acc.prefetch(s) is called two members ahead. The + * products come from kernel, or from BLAS if it is null. Adds the distance + * computations to ndis. Access is RoundAccess or ShardAccess. */ +template +void local_join( + const int32_t* out_l, + const uint8_t* out_f, + int K, + const int32_t* in_l, + const uint8_t* in_f, + int Rr, + int S, + GramKernel kernel, + MetricType metric_type, + size_t d, + const float* norms, + const std::vector>& nworst, + JoinScratch& js, + size_t& ndis, + const Access& acc) { + js.seen.clear(); + js.nbr.clear(); + js.lst.clear(); + js.collect(out_l, out_f, K, S); + js.collect(in_l, in_f, Rr, S); + int r = 0; + for (auto& p : js.lst) { + r += p.second; + } + if (r == 0) { + return; + } + for (auto& p : js.lst) { + if (p.second) { + js.nbr.push_back(p.first); + } + } + for (auto& p : js.lst) { + if (!p.second) { + js.nbr.push_back(p.first); + } + } + const size_t m = js.nbr.size(); + pipnn::ensure_size(js.out, r * m); + pipnn::ensure_size(js.xs, m * d); + js.nrm.resize(m); + js.thr.resize(m); + js.rows.resize(m); + if (js.bk.size() < m) { + js.bk.resize(m); + } + for (size_t i = 0; i < m; i++) { + if (i + 2 < m) { + acc.prefetch(js.nbr[i + 2]); + } + float* buf = js.xs.data() + i * d; + const float* x = acc.row(js.nbr[i], buf); + if (!kernel && x != buf) { + std::copy_n(x, d, buf); // BLAS reads one matrix + } + js.rows[i] = kernel ? x : buf; + js.nrm[i] = norms[js.nbr[i]]; + // nworst starts at the K-th distance of the old row and only goes + // down + js.thr[i] = nworst[js.nbr[i]].load(std::memory_order_relaxed); + js.bk[i].clear(); + } + if (kernel) { + kernel(js.rows.data(), r, m, d, js.out.data()); + } else { + gram_upper_rows_blas(js.xs.data(), r, m, d, js.out.data()); + } + products_to_distances(metric_type, js.nrm.data(), r, m, js.out.data()); + for (int i = 0; i < r; i++) { + const float* oi = js.out.data() + size_t(i) * m; + ndis += m - i - 1; + for (size_t j = i + 1; j < m; j++) { + const float v = oi[j]; + if (v <= js.thr[i]) { + js.bk[i].push_back({v, acc.gid(js.nbr[j])}); + } + if (v <= js.thr[j]) { + js.bk[j].push_back({v, acc.gid(js.nbr[i])}); + } + } + } + for (size_t i = 0; i < m; i++) { + if (!js.bk[i].empty()) { + acc.flush(js.nbr[i], js.bk[i], js.mbuf, js.mbuf_new); + } + } +} + +/** local_join() access of DeterministicNNDescent::round(), one per thread. + * The storage indices are the graph ids. flush() merges the candidates into + * the next rows under the lock of the row. */ +struct RoundAccess { + VectorReader& vr; + int K; + /// the rows at the start of the round + const int32_t* ids; + const float* dis; + int32_t* next_ids; + float* next_dis; + uint8_t* next_new; + std::atomic_flag* locks; + std::atomic* nworst; + + const float* row(int32_t s, float* buf) const { + if (vr.flat) { + return vr.flat + size_t(s) * vr.d; + } + vr.decode(s, buf); + return buf; + } + + void prefetch(int32_t s) const { + vr.prefetch(s); + } + + int32_t gid(int32_t s) const { + return s; + } + + void flush( + int32_t a, + std::vector& cand, + std::vector& buf, + std::vector& buf_new) const { + const size_t o = size_t(a) * K; + const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, cand); + if (m == 0) { + return; + } + std::sort(cand.begin(), cand.begin() + m); + merge_into_row_locked( + K, + locks[a], + nworst[a], + next_ids + o, + next_dis + o, + next_new + o, + cand.data(), + m, + buf, + buf_new); + } +}; + +} // namespace + +idx_t DeterministicNNDescent::round(const Index& storage) { + FAISS_THROW_IF_NOT_MSG( + storage.ntotal == n && ids.size() == size_t(n) * K && + order.size() == size_t(n), + "DeterministicNNDescent: init() before round()"); + check_params(); + FAISS_THROW_IF_NOT_MSG( + size_t(storage.d) == d && storage.metric_type == metric_type, + "DeterministicNNDescent: round() needs the storage of init()"); + if (n > 0) { + // a storage that cannot reconstruct throws here, not inside OpenMP + VectorReader(storage).get(0); + } + const int Rr = nreverse(); + const int S = nsample(); + const double t0 = getmillisecs(); + + // reverse neighbors: the Rr nearest of each node, by (distance, source). + // The edges are counted and placed in parallel; each list is sorted after. + // rpos[t + 1] counts the edges to t, then rpos[t] is the next free slot of + // list t; after the placement, list t is [rpos[t - 1], rpos[t]). + std::vector> rpos(n + 1); + for (idx_t i = 0; i <= n; i++) { + rpos[i].store(0, std::memory_order_relaxed); + } +#pragma omp parallel for schedule(static) + for (idx_t s = 0; s < n; s++) { + for (int j = 0; j < K; j++) { + const int32_t t = ids[size_t(s) * K + j]; + if (t >= 0) { + rpos[t + 1].fetch_add(1, std::memory_order_relaxed); + } + } + } + for (idx_t i = 0; i < n; i++) { + rpos[i + 1].store( + rpos[i + 1].load(std::memory_order_relaxed) + + rpos[i].load(std::memory_order_relaxed), + std::memory_order_relaxed); + } + const int64_t nedges = rpos[n].load(std::memory_order_relaxed); + std::vector redges(nedges); + std::vector rnew(nedges); +#pragma omp parallel for schedule(static) + for (idx_t s = 0; s < n; s++) { + for (int j = 0; j < K; j++) { + const size_t e = size_t(s) * K + j; + const int32_t t = ids[e]; + if (t >= 0) { + const int64_t p = + rpos[t].fetch_add(1, std::memory_order_relaxed); + redges[p] = {dis[e], int32_t(s)}; + rnew[p] = is_new[e]; + } + } + } + std::vector rev(size_t(n) * Rr, -1); + std::vector rev_new(size_t(n) * Rr, 0); +#pragma omp parallel + { + // a source is in a list at most once, so the pairs compare as their + // (distance, source) + std::vector> sel; +#pragma omp for schedule(dynamic, 1024) + for (idx_t t = 0; t < n; t++) { + const int64_t b = + t == 0 ? 0 : rpos[t - 1].load(std::memory_order_relaxed); + const int64_t e = rpos[t].load(std::memory_order_relaxed); + sel.resize(e - b); + for (int64_t p = b; p < e; p++) { + sel[p - b] = {redges[p], rnew[p]}; + } + const size_t m = std::min(sel.size(), Rr); + std::partial_sort(sel.begin(), sel.begin() + m, sel.end()); + for (size_t j = 0; j < m; j++) { + rev[size_t(t) * Rr + j] = sel[j].first.second; + rev_new[size_t(t) * Rr + j] = sel[j].second; + } + } + } + redges = std::vector(); + rnew = std::vector(); + + // the next rows start as the current rows; the local joins insert the + // candidates under a lock per row + std::vector nids = ids; + std::vector ndis_ = dis; + std::vector nnew; + unsampled_new(is_new, n, K, S, nnew); + std::vector locks(n); + // K-th distance of each next row, read without the lock: it can only go + // down, so a candidate above it cannot enter the final row + std::vector> nworst(n); + for (idx_t v = 0; v < n; v++) { + const size_t e = size_t(v) * K + K - 1; + nworst[v].store(ids[e] >= 0 ? dis[e] : kInf, std::memory_order_relaxed); + } + + // squared norms, once per round + std::vector gnorms(n); +#pragma omp parallel + { + VectorReader vr(storage); +#pragma omp for schedule(static) + for (idx_t v = 0; v < n; v++) { + gnorms[v] = fvec_norm_L2sqr(vr.get(v), d); + } + } + + const GramKernel kernel = gram_kernel(); + size_t nd_total = 0; +#pragma omp parallel reduction(+ : nd_total) + { + VectorReader vr(storage); + JoinScratch js; + const RoundAccess acc{ + vr, + K, + ids.data(), + dis.data(), + nids.data(), + ndis_.data(), + nnew.data(), + locks.data(), + nworst.data()}; +#pragma omp for schedule(dynamic, 64) + for (idx_t pos = 0; pos < n; pos++) { + const idx_t u = order[pos]; + local_join( + ids.data() + size_t(u) * K, + is_new.data() + size_t(u) * K, + K, + rev.data() + size_t(u) * Rr, + rev_new.data() + size_t(u) * Rr, + Rr, + S, + kernel, + metric_type, + d, + gnorms.data(), + nworst, + js, + nd_total, + acc); + } + } + const idx_t changed = count_rows_with_new(nnew, n, K); + ids.swap(nids); + dis.swap(ndis_); + is_new.swap(nnew); + ndis = nd_total; + if (verbose) { + printf("DeterministicNNDescent: round in %.1f s, %" PRId64 + " nodes changed, %.0f distances per node\n", + (getmillisecs() - t0) / 1000, + changed, + double(ndis) / n); + } + return changed; +} + +void DeterministicNNDescent::check_params() const { + FAISS_THROW_IF_NOT_FMT( + K >= 1 && K <= 4096, + "DeterministicNNDescent: K must be in [1, 4096], got %d", + K); + FAISS_THROW_IF_NOT_FMT( + R >= 0 && R <= 4096, + "DeterministicNNDescent: R must be in [0, 4096], got %d", + R); + FAISS_THROW_IF_NOT_FMT( + sample >= 0, + "DeterministicNNDescent: sample must be >= 0, got %d", + sample); + FAISS_THROW_IF_NOT_FMT( + ntrees >= 0, + "DeterministicNNDescent: ntrees must be >= 0, got %d", + ntrees); +} + +void DeterministicNNDescent::build(const Index& storage) { + init(storage); + for (int r = 0; r < max_rounds; r++) { + if (round(storage) < delta * n) { + break; + } + } +} + +/************************************************************* + * NNDescentShard + *************************************************************/ + +namespace { + +/// owner process of graph id v +inline int owner_of(const std::vector& owner_begin, int64_t v) { + return int(std::upper_bound(owner_begin.begin(), owner_begin.end(), v) - + owner_begin.begin()) - + 1; +} + +/// throws msg if one of the n ids is not in [lo, hi), or -1 with allow_none. +/// An id out of range would index past the end of per-owner arrays. +void check_graph_ids( + const int64_t* v, + size_t n, + int64_t lo, + int64_t hi, + bool allow_none, + const char* msg) { + int bad = 0; +#pragma omp parallel for schedule(static) reduction(| : bad) + for (int64_t e = 0; e < int64_t(n); e++) { + const bool ok = (allow_none && v[e] == -1) || (v[e] >= lo && v[e] < hi); + bad |= ok ? 0 : 1; + } + if (bad) { + FAISS_THROW_MSG(msg); + } +} + +/// counts of a list grouped by owner, from the owner of each item +void group_counts( + const std::vector& owner_begin, + const std::vector& sorted_ids, + std::vector& counts) { + const int world = int(owner_begin.size()) - 1; + counts.assign(world, 0); + for (int p = 0; p < world; p++) { + counts[p] = + std::lower_bound( + sorted_ids.begin(), + sorted_ids.end(), + owner_begin[p + 1]) - + std::lower_bound( + sorted_ids.begin(), sorted_ids.end(), owner_begin[p]); + } +} + +/// appends the remote ids of the list v (len slots, -1 padded) to the +/// buckets of their owners; the home ids are [hb, hb + nh) +void bucket_remote_ids( + const int64_t* v, + int len, + int64_t hb, + idx_t nh, + const std::vector& owner_begin, + std::vector>& buckets) { + for (int j = 0; j < len; j++) { + if (v[j] >= 0 && (v[j] < hb || v[j] >= hb + nh)) { + buckets[owner_of(owner_begin, v[j])].push_back(v[j]); + } + } +} + +} // namespace + +void NNDescentShard::set_rows( + int K_in, + MetricType metric_type_in, + size_t d_in, + int rank_in, + int world, + const int64_t* owner_begin_in, + const float* x_in, + const int64_t* ids_in, + const float* dis_in) { + FAISS_THROW_IF_NOT_FMT( + K_in >= 1 && K_in <= 4096, + "NNDescentShard: K must be in [1, 4096], got %d", + K_in); + FAISS_THROW_IF_NOT_MSG( + metric_type_in == METRIC_L2 || + metric_type_in == METRIC_INNER_PRODUCT, + "NNDescentShard: only METRIC_L2 and METRIC_INNER_PRODUCT"); + FAISS_THROW_IF_NOT_MSG(d_in > 0, "NNDescentShard: d must be > 0"); + FAISS_THROW_IF_NOT(world >= 1 && rank_in >= 0 && rank_in < world); + for (int p = 0; p < world; p++) { + FAISS_THROW_IF_NOT_MSG( + owner_begin_in[p] <= owner_begin_in[p + 1], + "NNDescentShard: owner_begin must be non-decreasing"); + } + const size_t nK = + size_t(owner_begin_in[rank_in + 1] - owner_begin_in[rank_in]) * + K_in; + check_graph_ids( + ids_in, + nK, + owner_begin_in[0], + owner_begin_in[world], + true, + "NNDescentShard: row id out of range"); + K = K_in; + metric_type = metric_type_in; + d = d_in; + rank = rank_in; + owner_begin.assign(owner_begin_in, owner_begin_in + world + 1); + x = x_in; + ids.assign(ids_in, ids_in + nK); + dis.assign(dis_in, dis_in + nK); + is_new.resize(nK); + for (size_t e = 0; e < nK; e++) { + is_new[e] = ids[e] >= 0; + } + remote_ids.clear(); + reverse_ids.clear(); + reverse_new.clear(); +} + +idx_t NNDescentShard::nhome() const { + return owner_begin.empty() ? 0 : owner_begin[rank + 1] - owner_begin[rank]; +} + +void NNDescentShard::reverse_edges( + std::vector& counts, + std::vector& target, + std::vector& source, + std::vector& edge_dis, + std::vector& edge_new) const { + const int world = int(owner_begin.size()) - 1; + const idx_t nh = nhome(); + const size_t nK = size_t(nh) * K; + std::vector owner(nK, -1); +#pragma omp parallel for schedule(static) + for (int64_t e = 0; e < int64_t(nK); e++) { + if (ids[e] >= 0) { + owner[e] = owner_of(owner_begin, ids[e]); + } + } + const int nt = omp_get_max_threads(); + // pos[c * world + p]: the edges of row chunk c to owner p, then the + // position of the next one + std::vector pos(size_t(nt) * world, 0); +#pragma omp parallel for schedule(static) + for (int c = 0; c < nt; c++) { + int64_t* mine = pos.data() + size_t(c) * world; + for (size_t e = nK * c / nt; e < nK * (c + 1) / nt; e++) { + if (owner[e] >= 0) { + mine[owner[e]]++; + } + } + } + counts.assign(world, 0); + int64_t total = 0; + for (int p = 0; p < world; p++) { + for (int c = 0; c < nt; c++) { + const int64_t m = pos[size_t(c) * world + p]; + pos[size_t(c) * world + p] = total; + total += m; + counts[p] += m; + } + } + target.resize(total); + source.resize(total); + edge_dis.resize(total); + edge_new.resize(total); +#pragma omp parallel for schedule(static) + for (int c = 0; c < nt; c++) { + int64_t* cur = pos.data() + size_t(c) * world; + for (size_t e = nK * c / nt; e < nK * (c + 1) / nt; e++) { + if (owner[e] < 0) { + continue; + } + const int64_t q = cur[owner[e]]++; + target[q] = ids[e]; + source[q] = owner_begin[rank] + int64_t(e / K); + edge_dis[q] = dis[e]; + edge_new[q] = is_new[e]; + } + } +} + +namespace { + +/// Groups the n items by their home row target[e] - hb, and calls +/// rows.row(t, begin, end) on the items [begin, end) of each home row t. The +/// items of a row keep their input order. rows.make(e) builds item e of type +/// Rows::Item; the function sets its field row. Threads process disjoint +/// ranges of rows. Rows is ReverseEdgeRows or CandidateRows. +template +void group_by_home_row( + size_t n, + const int64_t* target, + int64_t hb, + idx_t nh, + const char* msg, + const Rows& rows) { + using Item = typename Rows::Item; + const int nt = omp_get_max_threads(); + // bucket b holds the rows [b * rows_per, (b + 1) * rows_per) + const idx_t nchunks = 16 * idx_t(nt); + const idx_t rows_per = std::max(1, (nh + nchunks - 1) / nchunks); + const idx_t nb = (nh + rows_per - 1) / rows_per; + // pos[c * nb + b]: the items of input chunk c in bucket b, then the + // position of the next one + std::vector pos(size_t(nt) * nb, 0); + std::vector bad(nt, 0); +#pragma omp parallel for schedule(static) + for (int c = 0; c < nt; c++) { + size_t* mine = pos.data() + size_t(c) * nb; + for (size_t e = n * c / nt; e < n * (c + 1) / nt; e++) { + const int64_t r = target[e] - hb; + if (r < 0 || r >= nh) { + bad[c] = 1; + break; + } + mine[r / rows_per]++; + } + } + FAISS_THROW_IF_NOT_FMT( + std::find(bad.begin(), bad.end(), 1) == bad.end(), "%s", msg); + std::vector bucket_begin(nb + 1); + size_t acc = 0; + for (idx_t b = 0; b < nb; b++) { + bucket_begin[b] = acc; + for (int c = 0; c < nt; c++) { + const size_t m = pos[size_t(c) * nb + b]; + pos[size_t(c) * nb + b] = acc; + acc += m; + } + } + bucket_begin[nb] = acc; + std::vector items(n); +#pragma omp parallel for schedule(static) + for (int c = 0; c < nt; c++) { + size_t* cur = pos.data() + size_t(c) * nb; + for (size_t e = n * c / nt; e < n * (c + 1) / nt; e++) { + const idx_t r = target[e] - hb; + Item& it = items[cur[r / rows_per]++]; + it = rows.make(e); + it.row = uint32_t(r); + } + } +#pragma omp parallel + { + std::vector tmp; + std::vector off; +#pragma omp for schedule(dynamic) + for (idx_t b = 0; b < nb; b++) { + const idx_t r0 = b * rows_per; + const idx_t r1 = std::min(nh, r0 + rows_per); + const Item* in = items.data() + bucket_begin[b]; + const size_t m = bucket_begin[b + 1] - bucket_begin[b]; + off.assign(r1 - r0 + 1, 0); + for (size_t i = 0; i < m; i++) { + off[in[i].row - r0 + 1]++; + } + for (idx_t t = r0; t < r1; t++) { + off[t - r0 + 1] += off[t - r0]; + } + tmp.resize(m); + for (size_t i = 0; i < m; i++) { + tmp[off[in[i].row - r0]++] = in[i]; + } + for (idx_t t = r1; t > r0; t--) { + off[t - r0] = off[t - r0 - 1]; + } + off[0] = 0; + for (idx_t t = r0; t < r1; t++) { + rows.row( + t, + tmp.data() + off[t - r0], + tmp.data() + off[t - r0 + 1]); + } + } + } +} + +/// group_by_home_row() items of NNDescentShard::set_reverse_edges(): each +/// home row keeps its Rr nearest reverse edges by (distance, source) +struct ReverseEdgeRows { + struct Item { + float dis; + uint32_t row; + int64_t id; + uint8_t is_new; + + bool operator<(const Item& other) const { + return dis < other.dis || (dis == other.dis && id < other.id); + } + }; + + const int64_t* source; + const float* edge_dis; + const uint8_t* edge_new; + int Rr; + int64_t* reverse_ids; + uint8_t* reverse_new; + + Item make(size_t e) const { + return Item{edge_dis[e], 0, source[e], edge_new[e]}; + } + + void row(idx_t t, Item* b, Item* e) const { + const size_t m = std::min(e - b, Rr); + std::partial_sort(b, b + m, e); + for (size_t j = 0; j < m; j++) { + reverse_ids[size_t(t) * Rr + j] = b[j].id; + reverse_new[size_t(t) * Rr + j] = b[j].is_new; + } + } +}; + +/// group_by_home_row() items of NNDescentShard::insert_candidates(): each +/// home row merges its candidates into its next row, one entry per +/// candidate with its smallest distance +struct CandidateRows { + struct Item { + float dis; + uint32_t row; + int64_t id; + }; + + /// order by (id, distance), so that the best entry of an id comes first + struct IdThenDis { + bool operator()(const Item& p, const Item& q) const { + return p.id < q.id || (p.id == q.id && p.dis < q.dis); + } + }; + + const int64_t* candidate; + const float* candidate_dis; + int K; + /// the rows at the start of the round + const int64_t* ids; + const float* dis; + int64_t* next_ids; + float* next_dis; + uint8_t* next_new; + /// per-thread buffers + std::vector* cand; + std::vector* mbuf; + std::vector* mbuf_new; + + Item make(size_t e) const { + return Item{candidate_dis[e], 0, candidate[e]}; + } + + void row(idx_t t, Item* b, Item* e) const { + const int th = omp_get_thread_num(); + const size_t o = size_t(t) * K; + std::sort(b, e, IdThenDis()); + std::vector& c = cand[th]; + c.clear(); + for (Item* it = b; it != e; ++it) { + if (it == b || it->id != it[-1].id) { + c.push_back({it->dis, it->id}); + } + } + const size_t m = drop_old_ids(ids + o, dis[o + K - 1], K, c); + if (m == 0) { + return; + } + std::sort(c.begin(), c.begin() + m); + merge_into_row( + K, + next_ids + o, + next_dis + o, + next_new + o, + c.data(), + m, + mbuf[th], + mbuf_new[th]); + } +}; + +} // namespace + +void NNDescentShard::set_reverse_edges( + size_t n, + const int64_t* target, + const int64_t* source, + const float* edge_dis, + const uint8_t* edge_new) { + const idx_t nh = nhome(); + const int64_t hb = owner_begin[rank]; + const int Rr = nreverse(); + check_graph_ids( + source, + n, + owner_begin.front(), + owner_begin.back(), + false, + "NNDescentShard: reverse edge source out of range"); + reverse_ids.assign(size_t(nh) * Rr, -1); + reverse_new.assign(size_t(nh) * Rr, 0); + group_by_home_row( + n, + target, + hb, + nh, + "NNDescentShard: reverse edge to an id of another process", + ReverseEdgeRows{ + source, + edge_dis, + edge_new, + Rr, + reverse_ids.data(), + reverse_new.data()}); + + select_rows(0, nh); +} + +void NNDescentShard::select_rows(idx_t begin, idx_t end) { + FAISS_THROW_IF_NOT_MSG( + begin >= 0 && begin <= end && end <= nhome(), + "NNDescentShard: invalid row range"); + FAISS_THROW_IF_NOT_MSG( + reverse_ids.size() == size_t(nhome()) * nreverse(), + "NNDescentShard: set_reverse_edges() before select_rows()"); + selected_begin = begin; + selected_end = end; + collect_remote_ids(true, begin, end); +} + +bool NNDescentShard::has_new_member(idx_t t) const { + const int Rr = nreverse(); + for (int j = 0; j < K && ids[size_t(t) * K + j] >= 0; j++) { + if (is_new[size_t(t) * K + j]) { + return true; + } + } + for (int j = 0; j < Rr && reverse_ids[size_t(t) * Rr + j] >= 0; j++) { + if (reverse_new[size_t(t) * Rr + j]) { + return true; + } + } + return false; +} + +// the ids are bucketed by owner, then sorted and unique in each bucket +void NNDescentShard::collect_remote_ids( + bool with_reverse, + idx_t begin, + idx_t end) { + const int Rr = with_reverse ? nreverse() : 0; + const idx_t nh = nhome(); + const int64_t hb = owner_begin[rank]; + const int world = int(owner_begin.size()) - 1; + const int nt = omp_get_max_threads(); + std::vector>> buckets( + nt, std::vector>(world)); +#pragma omp parallel + { + auto& mine = buckets[omp_get_thread_num()]; +#pragma omp for schedule(static) + for (idx_t t = begin; t < end; t++) { + if (with_reverse && !has_new_member(t)) { + continue; + } + bucket_remote_ids( + ids.data() + size_t(t) * K, K, hb, nh, owner_begin, mine); + if (Rr > 0) { + bucket_remote_ids( + reverse_ids.data() + size_t(t) * Rr, + Rr, + hb, + nh, + owner_begin, + mine); + } + } + } + std::vector> per_owner(world); +#pragma omp parallel for schedule(dynamic) + for (int p = 0; p < world; p++) { + auto& v = per_owner[p]; + for (int t = 0; t < nt; t++) { + v.insert(v.end(), buckets[t][p].begin(), buckets[t][p].end()); + buckets[t][p] = std::vector(); + } + std::sort(v.begin(), v.end()); + v.erase(std::unique(v.begin(), v.end()), v.end()); + } + remote_ids.clear(); + for (auto& v : per_owner) { + remote_ids.insert(remote_ids.end(), v.begin(), v.end()); + } +} + +void NNDescentShard::set_remote_ids_of_rows() { + collect_remote_ids(false, 0, nhome()); +} + +void NNDescentShard::original_ids( + const int64_t* home_original, + const int64_t* remote_original, + int64_t* out) const { + const idx_t nh = nhome(); + const int64_t hb = owner_begin[rank]; + int missing = 0; +#pragma omp parallel for schedule(static) reduction(| : missing) + for (int64_t e = 0; e < int64_t(size_t(nh) * K); e++) { + const int64_t v = ids[e]; + if (v < 0) { + out[e] = -1; + } else if (v >= hb && v < hb + nh) { + out[e] = home_original[v - hb]; + } else { + const auto it = + std::lower_bound(remote_ids.begin(), remote_ids.end(), v); + if (it != remote_ids.end() && *it == v) { + out[e] = remote_original[it - remote_ids.begin()]; + } else { + out[e] = -1; + missing = 1; + } + } + } + // throw outside the OpenMP region, where the caller can catch it + FAISS_THROW_IF_MSG( + missing, + "NNDescentShard: row id not in remote_ids; call set_remote_ids_of_rows()"); +} + +void NNDescentShard::remote_counts(std::vector& counts) const { + group_counts(owner_begin, remote_ids, counts); +} + +void NNDescentShard::join( + const float* remote_x, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis) { + RemoteVectors rv; + rv.x = remote_x; + join_impl(rv, remote_kth, counts, target, candidate, candidate_dis); +} + +void NNDescentShard::join_fp16( + const uint16_t* remote_x, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis) { + RemoteVectors rv; + rv.x16 = remote_x; + join_impl(rv, remote_kth, counts, target, candidate, candidate_dis); +} + +void NNDescentShard::join_sq8( + const uint8_t* remote_codes, + const float* vmin, + const float* vdiff, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis) { + RemoteVectors rv; + rv.codes = remote_codes; + rv.vmin = vmin; + rv.vdiff = vdiff; + join_impl(rv, remote_kth, counts, target, candidate, candidate_dis); +} + +namespace { + +/** local_join() access of NNDescentShard::join_impl(). Storage index s < nh + * is home row s, and s >= nh is remote id s - nh. flush() merges the + * candidates for a home row into its next row under the lock of the row, + * and keeps the candidates for a remote row in hbuf. */ +struct ShardAccess { + NNDescentShard& shard; + idx_t nh; + int64_t hb; + const NNDescentShard::RemoteVectors& rv; + const float* remote_kth; + std::atomic_flag* locks; + std::atomic* nworst; + /// candidates for each remote row: the K best by (distance, candidate), + /// one per id + std::vector* hbuf; + + /// storage index of graph id v: home ids first, then the remote ids; -1 + /// if v is not a home id or in remote_ids + int32_t sidx(int64_t v) const { + if (v >= hb && v < hb + nh) { + return int32_t(v - hb); + } + const std::vector& rid = shard.remote_ids; + const auto it = std::lower_bound(rid.begin(), rid.end(), v); + return it != rid.end() && *it == v ? int32_t(nh + (it - rid.begin())) + : -1; + } + + int64_t gid(int32_t s) const { + return s < nh ? hb + s : shard.remote_ids[s - nh]; + } + + /// the vector of storage index s; a coded remote vector is decoded into + /// buf + const float* row(int32_t s, float* buf) const { + const size_t d = shard.d; + if (s < nh) { + return shard.x + size_t(s) * d; + } + const size_t o = size_t(s - nh) * d; + if (rv.x) { + return rv.x + o; + } + if (rv.x16) { + for (size_t j = 0; j < d; j++) { + buf[j] = decode_fp16(rv.x16[o + j]); + } + return buf; + } + // two loops: a fused multiply-add would round differently from the + // encoder's float32 decode + for (size_t j = 0; j < d; j++) { + buf[j] = (rv.codes[o + j] + 0.5f) / 255.f * rv.vdiff[j]; + } + for (size_t j = 0; j < d; j++) { + buf[j] += rv.vmin[j]; + } + return buf; + } + + void prefetch(int32_t) const {} + + void flush( + int32_t a, + std::vector& cand, + std::vector& buf, + std::vector& buf_new) const { + const int K = shard.K; + size_t m = 0; + if (a < nh) { + const size_t o = size_t(a) * K; + m = drop_old_ids( + shard.ids.data() + o, shard.dis[o + K - 1], K, cand); + } else { + // the owner drops the ids of its row in insert_candidates() + const float kth = remote_kth[a - nh]; + for (const DisId64& c : cand) { + if (c.first <= kth) { + cand[m++] = c; + } + } + } + if (m == 0) { + return; + } + std::sort(cand.begin(), cand.begin() + m); + if (a < nh) { + const size_t o = size_t(a) * K; + merge_into_row_locked( + K, + locks[a], + nworst[a], + shard.next_ids.data() + o, + shard.next_dis.data() + o, + shard.next_new.data() + o, + cand.data(), + m, + buf, + buf_new); + return; + } + insert_remote(a, cand.data(), m); + } + + /// keeps in hbuf the K best distinct candidates of remote row a by their + /// smallest distance, in any order of the candidates + void insert_remote(int32_t a, const DisId64* cand, size_t m) const { + const size_t K = shard.K; + SpinLock lock(locks[a]); + std::vector& h = hbuf[a - nh]; + for (size_t j = 0; j < m; j++) { + const DisId64 c = cand[j]; + size_t k = 0; + while (k < h.size() && h[k].second != c.second) { + k++; + } + if (k < h.size()) { + if (c < h[k]) { + h[k] = c; + } + } else if (h.size() < K) { + h.push_back(c); + } else { + auto w = std::max_element(h.begin(), h.end()); + if (c < *w) { + *w = c; + } + } + } + if (h.size() == K) { + const auto w = std::max_element(h.begin(), h.end()); + if (w->first < nworst[a].load(std::memory_order_relaxed)) { + nworst[a].store(w->first, std::memory_order_relaxed); + } + } + } +}; + +} // namespace + +void NNDescentShard::join_impl( + const RemoteVectors& rv, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis) { + const idx_t nh = nhome(); + const size_t nr = remote_ids.size(); + const int64_t hb = owner_begin[rank]; + const int Rr = nreverse(); + const int S = nsample(); + FAISS_THROW_IF_NOT_MSG( + reverse_ids.size() == size_t(nh) * Rr, + "NNDescentShard: set_reverse_edges() before join()"); + FAISS_THROW_IF_NOT_MSG( + size_t(nh) + nr < (size_t(1) << 31), + "NNDescentShard: at most 2^31 - 1 home and remote ids"); + + std::vector locks(nh + nr); + std::vector> nworst(nh + nr); + std::vector> hbuf(nr); + const ShardAccess acc{ + *this, + nh, + hb, + rv, + remote_kth, + locks.data(), + nworst.data(), + hbuf.data()}; + // remote_ids has only the members of the neighborhoods with a new member; + // the other rows stay -1 and their local joins are empty + std::vector out_s(size_t(nh) * K, -1), in_s(size_t(nh) * Rr, -1); + std::vector norms(nh + nr); + int missing = 0; +#pragma omp parallel for schedule(static) reduction(| : missing) + for (idx_t t = selected_begin; t < selected_end; t++) { + if (!has_new_member(t)) { + continue; + } + for (int j = 0; j < K; j++) { + const int64_t v = ids[size_t(t) * K + j]; + if (v >= 0) { + out_s[size_t(t) * K + j] = acc.sidx(v); + missing |= out_s[size_t(t) * K + j] < 0; + } + } + for (int j = 0; j < Rr; j++) { + const int64_t v = reverse_ids[size_t(t) * Rr + j]; + if (v >= 0) { + in_s[size_t(t) * Rr + j] = acc.sidx(v); + missing |= in_s[size_t(t) * Rr + j] < 0; + } + } + } + FAISS_THROW_IF_MSG( + missing, + "NNDescentShard: a neighborhood id is not in remote_ids; " + "call select_rows() before join()"); +#pragma omp parallel + { + std::vector buf(d); +#pragma omp for schedule(static) + for (int64_t s = 0; s < int64_t(nh + nr); s++) { + norms[s] = fvec_norm_L2sqr(acc.row(int32_t(s), buf.data()), d); + } + } + + // next rows, as in round(), at the first join() of the round + if (next_ids.size() != ids.size()) { + next_ids = ids; + next_dis = dis; + unsampled_new(is_new, nh, K, S, next_new); + ndis = 0; + } + for (idx_t v = 0; v < nh; v++) { + const size_t e = size_t(v) * K + K - 1; + nworst[v].store( + next_ids[e] >= 0 ? next_dis[e] : kInf, + std::memory_order_relaxed); + } + for (size_t i = 0; i < nr; i++) { + nworst[nh + i].store(remote_kth[i], std::memory_order_relaxed); + } + const GramKernel kernel = gram_kernel(); + size_t nd_total = 0; +#pragma omp parallel reduction(+ : nd_total) + { + JoinScratch js; +#pragma omp for schedule(dynamic, 64) + for (idx_t u = selected_begin; u < selected_end; u++) { + local_join( + out_s.data() + size_t(u) * K, + is_new.data() + size_t(u) * K, + K, + in_s.data() + size_t(u) * Rr, + reverse_new.data() + size_t(u) * Rr, + Rr, + S, + kernel, + metric_type, + d, + norms.data(), + nworst, + js, + nd_total, + acc); + } + } + ndis += nd_total; + + // candidates for remote rows, grouped by owner because remote_ids is + // sorted + size_t total = 0; + std::vector start(nr + 1, 0); + for (size_t i = 0; i < nr; i++) { + start[i + 1] = start[i] + hbuf[i].size(); + } + total = start[nr]; + target.resize(total); + candidate.resize(total); + candidate_dis.resize(total); +#pragma omp parallel for schedule(dynamic, 1024) + for (int64_t i = 0; i < int64_t(nr); i++) { + auto& b = hbuf[i]; + std::sort(b.begin(), b.end()); + for (size_t j = 0; j < b.size(); j++) { + target[start[i] + j] = remote_ids[i]; + candidate[start[i] + j] = b[j].second; + candidate_dis[start[i] + j] = b[j].first; + } + } + group_counts(owner_begin, target, counts); +} + +void NNDescentShard::insert_candidates( + size_t n, + const int64_t* target, + const int64_t* candidate, + const float* candidate_dis) { + const idx_t nh = nhome(); + const int64_t hb = owner_begin[rank]; + FAISS_THROW_IF_NOT_MSG( + next_ids.size() == ids.size(), + "NNDescentShard: join() before insert_candidates()"); + check_graph_ids( + candidate, + n, + owner_begin.front(), + owner_begin.back(), + false, + "NNDescentShard: candidate out of range"); + std::vector> cand(omp_get_max_threads()); + std::vector> mbuf(cand.size()); + std::vector> mbuf_new(cand.size()); + group_by_home_row( + n, + target, + hb, + nh, + "NNDescentShard: candidate for an id of another process", + CandidateRows{ + candidate, + candidate_dis, + K, + ids.data(), + dis.data(), + next_ids.data(), + next_dis.data(), + next_new.data(), + cand.data(), + mbuf.data(), + mbuf_new.data()}); +} + +idx_t NNDescentShard::end_round() { + const idx_t nh = nhome(); + FAISS_THROW_IF_NOT_MSG( + next_ids.size() == ids.size(), + "NNDescentShard: join() before end_round()"); + const idx_t changed = count_rows_with_new(next_new, nh, K); + ids.swap(next_ids); + dis.swap(next_dis); + is_new.swap(next_new); + next_ids.clear(); + next_dis.clear(); + next_new.clear(); + reverse_ids.clear(); + reverse_new.clear(); + remote_ids.clear(); + return changed; +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/DeterministicNNDescent.h b/thirdparty/faiss/faiss/impl/DeterministicNNDescent.h new file mode 100644 index 000000000..6e35ecf2b --- /dev/null +++ b/thirdparty/faiss/faiss/impl/DeterministicNNDescent.h @@ -0,0 +1,301 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include + +namespace faiss { + +/// parameters of the local joins, shared by DeterministicNNDescent and +/// NNDescentShard +struct NNDescentParams { + int K = 64; ///< neighbors per node + int R = 0; ///< reverse neighbors used per node; 0: 2 * K + /// new neighbors of each kind (neighbors, reverse neighbors) that a local + /// join uses; 0: all + int sample = 0; + + int nreverse() const { + return R != 0 ? R : 2 * K; + } + + int nsample() const { + return sample != 0 ? sample : K + nreverse(); + } +}; + +/** A K-nearest-neighbor graph built by NN-descent, with a result that does + * not depend on the thread count. + * + * Dong, Charikar and Li, "Efficient K-Nearest Neighbor Graph Construction for + * Generic Similarity Measures", WWW 2011. The batch structure follows + * pyNNDescent in ParlayANN (Manohar et al., PPoPP 2024). + * + * - Initialization: random cluster trees. Each tree splits the points by + * their nearer of two random pivots, down to leaves of at most 512 points, + * and links each point to its K nearest in its leaf. With ntrees = 0, each + * node gets K random neighbors. Rows that stay short get random neighbors. + * - Rounds: a round reads a fixed copy of the graph. For each node u, a + * local join computes the distances between the members of the + * neighborhood of u (its K neighbors and R nearest reverse neighbors), for + * the pairs where at least one member is new (added by the previous + * round), and inserts each pair as a candidate in the rows of both + * members. The new row of a node holds the K best of its old row and of + * its candidates by (distance, id), with the smallest distance of each id. + * This set does not depend on the order of the candidates, so the rows do + * not depend on the thread count. + * + * The vectors are read in place for IndexFlat, decoded for + * IndexScalarQuantizer, and reconstructed for other storage types. The + * distances of a leaf and of a local join come from the inner products of + * the float vectors: from the nndescent::gram_upper_rows kernel on AVX2, + * AVX-512 and ARM NEON or SVE, else from BLAS. The values of a level do not + * depend on the thread count, but differ between levels. Distances are + * smaller-is-better: for METRIC_INNER_PRODUCT they are negated inner products. + * A distance that overflows to NaN becomes +inf. */ +struct DeterministicNNDescent : NNDescentParams { + int ntrees = 8; ///< random cluster trees for init(); 0: random init + int max_rounds = 20; ///< maximum rounds of build() + float delta = 0.05f; ///< build() stops when fewer nodes change + int64_t seed = 1234; + bool verbose = false; + + // the storage of init() + idx_t n = 0; + size_t d = 0; + MetricType metric_type = METRIC_L2; + /// n * K neighbors per node, sorted by (distance, id), -1 padded + std::vector ids; + std::vector dis; + + /// distance computations of the last init() or round() + size_t ndis = 0; + + /// Initializes the graph over the ntotal vectors of storage. + void init(const Index& storage); + + /// One round; returns the number of nodes whose row changed. + idx_t round(const Index& storage); + + /// init(storage), then rounds until fewer than delta * n nodes change + void build(const Index& storage); + + // internal state + /// n * K, nonzero for an entry added by the last init() or round() + std::vector is_new; + /// order in which round() visits the nodes: the leaf order of the first + /// cluster tree, so that consecutive nodes share neighbors in the cache + std::vector order; + + void check_params() const; +}; + +/** The rows of one process in an NN-descent round over a graph that is split + * between processes (for example a distributed build, after the + * per-partition builds). + * + * Graph ids are int64. Process p owns the ids owner_begin[p] .. + * owner_begin[p + 1] - 1 and holds their rows and vectors in that order. A + * round has four steps. Between the steps, the caller sends the lists to the + * other processes; each list is grouped by destination process, with one + * count per process. + * 1. reverse_edges(): the edges u -> v of the home rows, for the owner of v. + * 2. set_reverse_edges(): the received edges. Each home row keeps its R + * nearest reverse edges by (distance, source). The remote ids are the + * sorted ids that other processes own, of the neighborhoods that have a + * new member: a local join of a neighborhood without one computes no + * distances. + * 3. join(): with the vectors and the K-th distances of the remote ids, the + * local joins of the home rows, as in DeterministicNNDescent::round(). + * join() inserts the candidates for home rows and returns the candidates + * for remote rows, the K best for each row. With select_rows(), several + * join() calls can each cover a range of the home rows, with the remote + * ids of that range only. + * 4. insert_candidates(): the candidates that the other processes sent, in + * any order, then end_round(), which returns the number of home rows + * that changed. + * With the same rows, a round gives the same rows as + * DeterministicNNDescent::round() on the whole graph, except for the order of + * equal distances. The result does not depend on the thread count or on the + * order in which the lists arrive. + * + * The candidates for a remote row can include ids that are already in the + * row: the owner drops them in insert_candidates(). A pair can get two + * distances that differ in the last bits: init() computes some distances + * directly and the local joins from the squared norms, and coded remote + * vectors differ from the home vectors. The cases below that give "the same + * rows" assume one value per pair; otherwise the rows can differ slightly, + * but are still the same in every run with the same input. */ +struct NNDescentShard : NNDescentParams { + /// nhome() x K rows: graph ids sorted by (distance, id), -1 padded + std::vector ids; + std::vector dis; + /// ids that other processes own, of the neighborhoods of this round that + /// have a new member + std::vector remote_ids; + + /// distance computations of the join() calls of the round + size_t ndis = 0; + + /// rows of the home ids; every entry is new. Every row id is -1 or in + /// [owner_begin[0], owner_begin[world]). + void set_rows( + int K, + MetricType metric_type, + size_t d, + int rank, + int world, + const int64_t* owner_begin, + const float* x, + const int64_t* ids, + const float* dis); + + idx_t nhome() const; + + /// edges u -> v grouped by the owner of v + void reverse_edges( + std::vector& counts, + std::vector& target, + std::vector& source, + std::vector& edge_dis, + std::vector& edge_new) const; + + /// the received edges, whose targets are home ids and whose sources are + /// graph ids; computes remote_ids + void set_reverse_edges( + size_t n, + const int64_t* target, + const int64_t* source, + const float* edge_dis, + const uint8_t* edge_new); + + /** Selects the home rows [begin, end) for the next join() and sets + * remote_ids to the remote ids of their neighborhoods that have a new + * member. set_reverse_edges() selects all home rows. join() calls on + * disjoint ranges that cover the home rows need only the remote ids of + * their range. With one distance per pair, they give the same rows as one + * join() on all rows. When a pair can get two distances (see above), a + * range can send a candidate to a remote row that one join() would cut, + * so the rows can differ slightly. */ + void select_rows(idx_t begin, idx_t end); + + /// number of remote ids that each process owns + void remote_counts(std::vector& counts) const; + + /** Local joins of the selected home rows. For remote id i: its vector + * remote_x[i * d] and the K-th distance of its row remote_kth[i] (+inf if + * the row is short). Throws if a neighborhood id of the selected rows is + * not in remote_ids. Returns the candidates for remote rows grouped by + * owner: (target, candidate, distance), sorted by target, then by + * (distance, candidate). */ + void join( + const float* remote_x, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis); + + /// join() with float16 remote vectors, which take half the memory + void join_fp16( + const uint16_t* remote_x, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis); + + /** join() with 8-bit remote codes, a quarter of the float memory. + * Component j of a remote vector is vmin[j] + (code + 0.5) / 255 * + * vdiff[j], as in the 8-bit ScalarQuantizer. */ + void join_sq8( + const uint8_t* remote_codes, + const float* vmin, + const float* vdiff, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis); + + /// sets remote_ids to the sorted ids of the home rows that other + /// processes own + void set_remote_ids_of_rows(); + + /** The rows with the original ids: home_original[i] for home id + * owner_begin[rank] + i, remote_original[j] for remote_ids[j]. out: + * nhome() x K, -1 padded. */ + void original_ids( + const int64_t* home_original, + const int64_t* remote_original, + int64_t* out) const; + + /** Inserts the candidates for home rows that other processes sent: + * (target, candidate, distance), with home targets and candidates that + * are graph ids. The caller can insert the candidates of each join() as + * they arrive, in any order, then call end_round(). */ + void insert_candidates( + size_t n, + const int64_t* target, + const int64_t* candidate, + const float* candidate_dis); + + /// ends the round; returns the number of home rows that changed + idx_t end_round(); + + // internal state, set by set_rows() + MetricType metric_type = METRIC_L2; + size_t d = 0; + int rank = 0; + /// world + 1 boundaries of the graph ids that each process owns + std::vector owner_begin; + /// nhome() x d home vectors; the caller keeps them alive + const float* x = nullptr; + /// nhome() x K flags of the rows + std::vector is_new; + + // state between the steps of a round + std::vector reverse_ids; ///< nhome() x nreverse(), -1 padded + std::vector reverse_new; ///< flag of each reverse edge + std::vector next_ids; ///< rows after the merges + std::vector next_dis; + std::vector next_new; + idx_t selected_begin = 0; ///< home rows of the next join() + idx_t selected_end = 0; + + /// remote vectors of join_impl(): exactly one of x, x16 and codes + struct RemoteVectors { + const float* x = nullptr; + const uint16_t* x16 = nullptr; + const uint8_t* codes = nullptr; + const float* vmin = nullptr; + const float* vdiff = nullptr; + }; + + void join_impl( + const RemoteVectors& rv, + const float* remote_kth, + std::vector& counts, + std::vector& target, + std::vector& candidate, + std::vector& candidate_dis); + + /// whether the neighborhood of home row t has a new member, so that its + /// local join computes distances + bool has_new_member(idx_t t) const; + + /** The remote ids of the home rows [begin, end), sorted. With the + * reverse lists: the remote ids of the neighborhoods that have a new + * member, which are the only ones that a local join reads. */ + void collect_remote_ids(bool with_reverse, idx_t begin, idx_t end); +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/DistanceComputer.cpp b/thirdparty/faiss/faiss/impl/DistanceComputer.cpp new file mode 100644 index 000000000..d5afea779 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/DistanceComputer.cpp @@ -0,0 +1,63 @@ +/* + * 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. + */ + +#include + +#include + +namespace faiss { + +void DistanceComputer::distances_batch_4( + const idx_t idx0, + const idx_t idx1, + const idx_t idx2, + const idx_t idx3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) { + // compute first, assign next + const float d0 = this->operator()(idx0); + const float d1 = this->operator()(idx1); + const float d2 = this->operator()(idx2); + const float d3 = this->operator()(idx3); + dis0 = d0; + dis1 = d1; + dis2 = d2; + dis3 = d3; +} + +float FlatCodesDistanceComputer::partial_dot_product( + const idx_t /* i */, + const uint32_t /* offset */, + const uint32_t /* num_components */) { + FAISS_THROW_MSG("partial_dot_product not implemented"); +} + +void FlatCodesDistanceComputer::partial_dot_product_batch_4( + const idx_t idx0, + const idx_t idx1, + const idx_t idx2, + const idx_t idx3, + float& dp0, + float& dp1, + float& dp2, + float& dp3, + const uint32_t offset, + const uint32_t num_components) { + // default implementation for correctness + const float d0 = this->partial_dot_product(idx0, offset, num_components); + const float d1 = this->partial_dot_product(idx1, offset, num_components); + const float d2 = this->partial_dot_product(idx2, offset, num_components); + const float d3 = this->partial_dot_product(idx3, offset, num_components); + dp0 = d0; + dp1 = d1; + dp2 = d2; + dp3 = d3; +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/DistanceComputer.h b/thirdparty/faiss/faiss/impl/DistanceComputer.h index 60f227640..3c4b87c25 100644 --- a/thirdparty/faiss/faiss/impl/DistanceComputer.h +++ b/thirdparty/faiss/faiss/impl/DistanceComputer.h @@ -41,17 +41,7 @@ struct DistanceComputer { float& dis0, float& dis1, float& dis2, - float& dis3) { - // compute first, assign next - const float d0 = this->operator()(idx0); - const float d1 = this->operator()(idx1); - const float d2 = this->operator()(idx2); - const float d3 = this->operator()(idx3); - dis0 = d0; - dis1 = d1; - dis2 = d2; - dis3 = d3; - } + float& dis3); /// compute distance between two stored vectors virtual float symmetric_dis(idx_t i, idx_t j) = 0; @@ -181,9 +171,7 @@ struct FlatCodesDistanceComputer : DistanceComputer { virtual float partial_dot_product( const idx_t /* i */, const uint32_t /* offset */, - const uint32_t /* num_components */) { - FAISS_THROW_MSG("partial_dot_product not implemented"); - } + const uint32_t /* num_components */); /// compute distance of current query to an encoded vector virtual float distance_to_code(const uint8_t* code) = 0; @@ -214,21 +202,7 @@ struct FlatCodesDistanceComputer : DistanceComputer { float& dp2, float& dp3, const uint32_t offset, - const uint32_t num_components) { - // default implementation for correctness - const float d0 = - this->partial_dot_product(idx0, offset, num_components); - const float d1 = - this->partial_dot_product(idx1, offset, num_components); - const float d2 = - this->partial_dot_product(idx2, offset, num_components); - const float d3 = - this->partial_dot_product(idx3, offset, num_components); - dp0 = d0; - dp1 = d1; - dp2 = d2; - dp3 = d3; - } + const uint32_t num_components); virtual ~FlatCodesDistanceComputer() override {} }; diff --git a/thirdparty/faiss/faiss/impl/HNSW.h b/thirdparty/faiss/faiss/impl/HNSW.h index 39acb6525..bffd027f1 100644 --- a/thirdparty/faiss/faiss/impl/HNSW.h +++ b/thirdparty/faiss/faiss/impl/HNSW.h @@ -296,6 +296,76 @@ void hnsw_add_vertices_deterministic( const std::function& set_query); +/// Parameters of add_level_0_links_from_sample() of IndexHNSW and +/// IndexBinaryHNSW. +struct HNSWLevel0LinkParameters { + /// The search that the new links are for. nullptr: the search settings + /// of the index, which the IVF assignment with a coarse quantizer uses. + const SearchParametersHNSW* search_params = nullptr; + /// A sink receives at least this factor times the mean number of + /// vectors per node. + float min_mean_factor = 3.0f; + /// For at least this fraction of the vectors that the search sends to a + /// sink, an exact search finds a nearer node. + float min_closer_fraction = 0.5f; + /// Maximum number of level-0 links added to one sink in one round. + int max_links_per_sink = 32; + /// Maximum number of rounds that find sinks and add links. + int max_rounds = 3; +}; + +struct HNSWLevel0LinkStats { + /// Sinks found in the first round. + size_t n_sinks_found = 0; + /// Sinks found after the last round. + size_t n_sinks_remaining = 0; + /// Level-0 links written into free slots. + size_t n_links_added = 0; + /// Level-0 links that replaced a link. + size_t n_links_replaced = 0; + /// Rounds that changed links. + int n_rounds = 0; + /// Exact searches with the storage, in all rounds. + size_t n_exact_searches = 0; +}; + +/** The two searches of the sample vectors that + * hnsw_add_level_0_links_from_sample() compares. IndexHNSW and IndexBinaryHNSW + * implement them for their vector types. */ +struct HNSWLinkSampleSearch { + /// number of sample vectors + idx_t n = 0; + + virtual ~HNSWLinkSampleSearch() = default; + + /// HNSW search (k = 1) of the m sample vectors `ids` (null: the first m). + virtual void search( + const SearchParametersHNSW* params, + size_t m, + const idx_t* ids, + idx_t* labels) const = 0; + + /** Exact search (k = 1) of the m sample vectors `ids`. nearer[j] is 1 when + * exact[j] is nearer than found[j] by more than rounding differences. */ + virtual void search_exact( + size_t m, + const idx_t* ids, + const idx_t* found, + idx_t* exact, + uint8_t* nearer) const = 0; +}; + +/** add_level_0_links_from_sample() of IndexHNSW and IndexBinaryHNSW. + * `dis` computes distances between nodes. `similarity` is true when a larger + * distance is nearer. */ +HNSWLevel0LinkStats hnsw_add_level_0_links_from_sample( + HNSW& hnsw, + size_t ntotal, + DistanceComputer& dis, + bool similarity, + const HNSWLinkSampleSearch& sample, + const HNSWLevel0LinkParameters& params); + struct HNSWStats { size_t n1 = 0; /// number of vectors searched size_t n2 = @@ -315,6 +385,8 @@ struct HNSWStats { ndis += other.ndis; nhops += other.nhops; } + + void combine_atomic(const HNSWStats& other); }; // global var that collects them all diff --git a/thirdparty/faiss/faiss/impl/IDSelector.h b/thirdparty/faiss/faiss/impl/IDSelector.h index e4e40ac1f..2d430c499 100644 --- a/thirdparty/faiss/faiss/impl/IDSelector.h +++ b/thirdparty/faiss/faiss/impl/IDSelector.h @@ -55,10 +55,11 @@ struct IDSelectorContextDispatch { const IDSelector* sel; const IDSelectorWithContext* ctx_sel; - IDSelectorContextDispatch(const IDSelector* sel, bool store_pairs) - : sel(sel), - ctx_sel((sel != nullptr && !store_pairs) - ? dynamic_cast(sel) + IDSelectorContextDispatch(const IDSelector* sel_in, bool store_pairs) + : sel(sel_in), + ctx_sel((sel_in != nullptr && !store_pairs) + ? dynamic_cast( + sel_in) : nullptr) {} bool is_member(idx_t id, const IDScanContext& ctx) const { diff --git a/thirdparty/faiss/faiss/impl/LocalSearchQuantizer.cpp b/thirdparty/faiss/faiss/impl/LocalSearchQuantizer.cpp index 9f4c314f5..28b0911e6 100644 --- a/thirdparty/faiss/faiss/impl/LocalSearchQuantizer.cpp +++ b/thirdparty/faiss/faiss/impl/LocalSearchQuantizer.cpp @@ -23,12 +23,9 @@ #include #include +#include -// this is needed for prefetching - -#ifdef COMPILE_SIMD_AVX2 -#include -#endif +#include extern "C" { // LU decomposition of a general matrix @@ -602,7 +599,7 @@ void LocalSearchQuantizer::icm_encode_step( // Resolve SIMD level once, not per iteration of the n × n_iters × M loop. with_simd_level_256bit([&]() { -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) for (int64_t i = 0; i < static_cast(n); i++) { std::vector objs(K); @@ -622,23 +619,13 @@ void LocalSearchQuantizer::icm_encode_step( continue; } -#ifdef COMPILE_SIMD_AVX2 - // TODO: add platform-independent compiler-independent - // prefetch utilities. if (other_m + 1 < M) { // do a single prefetch int32_t code2 = codes[i * M + other_m + 1]; - // for (int32_t code = 0; code < K; code += 64) { - int32_t code = 0; - { - size_t binary_idx = (other_m + 1) * M * K * K + - m * K * K + code2 * K + code; - _mm_prefetch( - (const char*)(binaries + binary_idx), - _MM_HINT_T0); - } + size_t binary_idx = (other_m + 1) * M * K * K + + m * K * K + code2 * K; + prefetch_L1(binaries + binary_idx); } -#endif for (size_t code = 0; code < K; code++) { int32_t code2 = codes[i * M + other_m]; diff --git a/thirdparty/faiss/faiss/impl/NNDescent.cpp b/thirdparty/faiss/faiss/impl/NNDescent.cpp index a6cf969bc..ca6047bcc 100644 --- a/thirdparty/faiss/faiss/impl/NNDescent.cpp +++ b/thirdparty/faiss/faiss/impl/NNDescent.cpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace faiss { @@ -200,7 +201,7 @@ void NNDescent::join(DistanceComputer& qdis) { idx_t check_period = InterruptCallback::get_period_hint(d * search_L); for (idx_t i0 = 0; i0 < (idx_t)ntotal; i0 += check_period) { idx_t i1 = std::min(i0 + check_period, (idx_t)ntotal); -#pragma omp parallel for default(shared) schedule(dynamic, 100) +#pragma omp parallel for default(shared) schedule(FAISS_OMP_DYNAMIC, 100) for (idx_t n = i0; n < i1; n++) { graph[n].join([&](int i, int j) { if (i != j) { diff --git a/thirdparty/faiss/faiss/impl/NNDescent.h b/thirdparty/faiss/faiss/impl/NNDescent.h index d6fafd048..07038e8a6 100644 --- a/thirdparty/faiss/faiss/impl/NNDescent.h +++ b/thirdparty/faiss/faiss/impl/NNDescent.h @@ -144,6 +144,10 @@ struct NNDescent { int iter = 10; // number of iterations to iterate over int search_L = 0; // size of candidate pool in searching int random_seed = 2021; // random seed for generators + /// IndexNNDescent::add builds the graph with DeterministicNNDescent + /// (K, iter rounds, random_seed), so that it does not depend on the + /// thread count. S, R and L do not apply. Not serialized. + bool deterministic = false; int K; // K in KNN graph int d; // dimensions diff --git a/thirdparty/faiss/faiss/impl/NSG.cpp b/thirdparty/faiss/faiss/impl/NSG.cpp index a2d4118b4..418479b4d 100644 --- a/thirdparty/faiss/faiss/impl/NSG.cpp +++ b/thirdparty/faiss/faiss/impl/NSG.cpp @@ -15,6 +15,7 @@ #include #include +#include namespace faiss { @@ -352,7 +353,7 @@ void NSG::link( std::unique_ptr dis( storage_distance_computer(storage)); -#pragma omp for schedule(dynamic, 100) +#pragma omp for schedule(FAISS_OMP_DYNAMIC, 100) for (int i = 0; i < ntotal; i++) { storage->reconstruct(i, vec.get()); dis->set_query(vec.get()); @@ -375,7 +376,7 @@ void NSG::link( std::unique_ptr dis( storage_distance_computer(storage)); -#pragma omp for schedule(dynamic, 100) +#pragma omp for schedule(FAISS_OMP_DYNAMIC, 100) for (int i = 0; i < ntotal; ++i) { add_reverse_links(i, locks, *dis, graph); } diff --git a/thirdparty/faiss/faiss/impl/Panorama.h b/thirdparty/faiss/faiss/impl/Panorama.h index 6dc1e33a2..2956cf4aa 100644 --- a/thirdparty/faiss/faiss/impl/Panorama.h +++ b/thirdparty/faiss/faiss/impl/Panorama.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -21,7 +22,7 @@ #include #include -#if defined(COMPILE_SIMD_AVX2) && defined(__AVX2__) && defined(__BMI2__) +#if FAISS_SIMD_TU(AVX2) && defined(__BMI2__) #include #endif @@ -154,7 +155,7 @@ inline size_t compact_active_kernel( size_t next_active = 0; size_t i = 0; -#if defined(COMPILE_SIMD_AVX2) && defined(__AVX2__) && defined(__BMI2__) +#if FAISS_SIMD_TU(AVX2) && defined(__BMI2__) for (; i + 8 <= num_active; i += 8) { uint64_t bytes; memcpy(&bytes, &active_byteset[i], 8); diff --git a/thirdparty/faiss/faiss/impl/PiPNN.cpp b/thirdparty/faiss/faiss/impl/PiPNN.cpp new file mode 100644 index 000000000..c59e5027b --- /dev/null +++ b/thirdparty/faiss/faiss/impl/PiPNN.cpp @@ -0,0 +1,824 @@ +/* + * 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. + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace faiss { + +namespace pipnn { + +namespace { + +constexpr size_t kMedoidBatch = 1024; +// distances stay finite: at most 4x this in GEMM form +constexpr float kMaxSquaredNorm = FLT_MAX / 8; +constexpr size_t kNumLocks = size_t(1) << 16; + +/// Reservoirs are allocated, and released after their final prune, in chunks +/// of this many points. +constexpr size_t kReservoirChunk = size_t(1) << 20; + +/// Reservoirs of points [begin, begin + np) in one buffer: np * capacity +/// slots, then np counts, then np cached-farthest indices. +struct ReservoirChunk { + std::unique_ptr buf; + size_t begin = 0; + size_t np = 0; +}; + +/// Reservoirs of one build and the graph its final prune writes. +struct BuildState { + size_t capacity; + size_t chunk_size; + std::vector chunks; + // uninitialized; rows written by the final prune and link_copies + std::unique_ptr graph; + + BuildState(size_t n_slots, size_t n, const PiPNN& p, size_t chunk) + : capacity(size_t(p.reservoir_size)), chunk_size(chunk) { + const size_t per_point = capacity * sizeof(Slot) + 2; + for (size_t begin = 0; begin < n_slots; begin += chunk_size) { + ReservoirChunk ch; + ch.begin = begin; + ch.np = std::min(chunk_size, n_slots - begin); + ch.buf.reset(new uint8_t[ch.np * per_point]); + chunks.push_back(std::move(ch)); + } + graph.reset(new int32_t[n * size_t(p.R)]); + // Touch every reservoir page now so an oversized build fails early; + // small static blocks interleave the pages over NUMA nodes. +#pragma omp parallel for schedule(static, 8) + for (int64_t i = 0; i < int64_t(n_slots); i++) { + const ReservoirRef r = reservoir(size_t(i)); + std::memset(r.slots, 0, capacity * sizeof(Slot)); + *r.count = 0; + *r.farthest = kNoFarthest; + } + } + + ReservoirRef reservoir(size_t i) { + ReservoirChunk& ch = chunks[i / chunk_size]; + const size_t off = i - ch.begin; + Slot* slots = reinterpret_cast(ch.buf.get()); + uint8_t* counts = reinterpret_cast(slots + ch.np * capacity); + return ReservoirRef{ + slots + off * capacity, + counts + off, + counts + ch.np + off, + int(capacity)}; + } +}; + +/// Keeps the graph alive as long as a MaybeOwnedVector views it. +struct GraphOwner : MaybeOwnedVectorOwner { + std::unique_ptr data; + explicit GraphOwner(std::unique_ptr d) : data(std::move(d)) {} +}; + +/// Rows with equal stored codes: the graph is built over the lowest, the +/// others (copies) are linked behind it. Empty if all differ. +struct Duplicates { + /// ascending ids of the rows the graph is built over + std::vector ids; + /// slot_of[i]: slot of the lowest id with the code of row i + std::vector slot_of; + + explicit Duplicates(const Index& storage) { + const auto* flat = dynamic_cast(&storage); + if (!flat) { + return; + } + const size_t n = size_t(storage.ntotal); + std::vector rep(n); + if (find_duplicate_codes( + n, flat->code_size, flat->codes.data(), rep.data()) == n) { + return; + } + slot_of.resize(n); + for (size_t i = 0; i < n; i++) { + if (rep[i] == int64_t(i)) { + slot_of[i] = int32_t(ids.size()); + ids.push_back(int32_t(i)); + } else { + slot_of[i] = slot_of[rep[i]]; + } + } + } + + size_t n_slots(size_t n) const { + return ids.empty() ? n : ids.size(); + } + size_t slot(int32_t id) const { + return slot_of.empty() ? size_t(id) : size_t(slot_of[id]); + } + int32_t id(size_t slot) const { + return ids.empty() ? int32_t(slot) : ids[slot]; + } + + /// Returns next_copy and clears the graph rows of the copies; consumes ids. + std::vector link_copies(int32_t* graph, size_t R) { + std::vector next(slot_of.size(), -1); + for (size_t i = 0; i < next.size(); i++) { + int32_t& tail = ids[slot_of[i]]; + if (tail != int32_t(i)) { + std::fill(graph + i * R, graph + (i + 1) * R, -1); + next[tail] = int32_t(i); + tail = int32_t(i); + } + } + return next; + } +}; + +} // namespace + +int32_t medoid_and_validate(const Index& storage, float* norm_cv) { + const size_t d = size_t(storage.d); + const size_t n = size_t(storage.ntotal); + FAISS_THROW_IF_MSG(n == 0, "PiPNN: the medoid of 0 vectors is undefined"); + FAISS_THROW_IF_MSG( + n > size_t(std::numeric_limits::max()), + "PiPNN: more than 2^31 - 1 vectors"); + const size_t nblocks = (n + kMedoidBlock - 1) / kMedoidBlock; + std::vector sums(nblocks * d); + std::vector mean(d); + // (distance to the mean, id): pairs order ties by the lower id + std::vector> block_best(nblocks); + std::vector> norm_sums(norm_cv ? nblocks : 0); + + // pass 0: validate and sum per block; pass 1: per-block argmin + for (int pass = 0; pass < 2; pass++) { + std::exception_ptr ex; + std::atomic interrupt{false}; +#pragma omp parallel + { + AlignedTable buf; + int32_t ids[kMedoidBatch]; +#pragma omp for schedule(dynamic) + for (int64_t b = 0; b < int64_t(nblocks); b++) { + if (interrupt.load(std::memory_order_relaxed)) { + continue; + } + try { + ensure_size(buf, kMedoidBatch * d); + const size_t i0 = size_t(b) * kMedoidBlock; + const size_t i1 = std::min(n, i0 + kMedoidBlock); + double* acc = sums.data() + size_t(b) * d; + std::pair best{ + std::numeric_limits::infinity(), -1}; + for (size_t j0 = i0; j0 < i1; j0 += kMedoidBatch) { + const size_t k = std::min(kMedoidBatch, i1 - j0); + std::iota(ids, ids + k, int32_t(j0)); + gather_rows(storage, ids, k, buf.get()); + for (size_t r = 0; r < k; r++) { + const float* x = buf.get() + r * d; + if (pass == 0) { + // NaN and inf fail this comparison too + const float nrm = fvec_norm_L2sqr(x, d); + FAISS_THROW_IF_NOT_FMT( + nrm <= kMaxSquaredNorm, + "PiPNN: vector %zu has squared norm " + "%g; need finite and <= FLT_MAX / 8", + j0 + r, + double(nrm)); + if (norm_cv && nrm > 0) { + norm_sums[b][0] += 1; + norm_sums[b][1] += std::sqrt(double(nrm)); + norm_sums[b][2] += nrm; + } + for (size_t j = 0; j < d; j++) { + acc[j] += double(x[j]); + } + } else { + best = std::min( + best, + {fvec_L2sqr(x, mean.data(), d), + int32_t(j0 + r)}); + } + } + } + if (pass == 1) { + block_best[b] = best; + } + // blocks are large: poll after every one + if (omp_get_thread_num() == 0 && + InterruptCallback::is_interrupted()) { + FAISS_THROW_MSG("computation interrupted"); + } + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + } + omp_rethrow_if_exception(ex); + if (pass == 0) { + for (size_t j = 0; j < d; j++) { + double s = 0; + for (size_t b = 0; b < nblocks; b++) { + s += sums[b * d + j]; + } + mean[j] = float(s / double(n)); + } + } + } + if (norm_cv) { + double c = 0, s1 = 0, s2 = 0; + for (const auto& [bc, b1, b2] : norm_sums) { + c += bc; + s1 += b1; + s2 += b2; + } + if (c == 0) { + *norm_cv = 0; + } else { + const double norm_mean = s1 / c; + *norm_cv = + std::sqrt(std::max(s2 / c - norm_mean * norm_mean, 0.0)) / + norm_mean; + } + } + return std::min_element(block_best.begin(), block_best.end())->second; +} + +namespace { + +PartitionParams partition_params(const PiPNN& p, MetricType metric) { + return {.c_max = p.c_max, + .c_min = p.c_min, + .leader_cap = p.leader_cap, + .leader_fraction = p.leader_fraction, + .fanout = p.fanout, + .metric = metric, + .ip_partition_by_angle = p.ip_partition_by_angle, + .wave_budget = p.partition_wave_budget}; +} + +/// Offers the nearest neighbours of every leaf point to the HashPrune +/// reservoirs. +void fill_reservoirs( + BuildState& st, + const Index& storage, + const Duplicates& dup, + const PiPNN& p, + bool verbose) { + const size_t n = dup.n_slots(size_t(storage.ntotal)); + const size_t d = size_t(storage.d); + const MetricType metric = storage.metric_type; + const bool is_ip = metric == METRIC_INNER_PRODUCT; + // n <= c_max is a single leaf; there each point offers its + // reservoir_size nearest instead of its leaf_k nearest. + const size_t k = + n <= size_t(p.c_max) ? size_t(p.reservoir_size) : size_t(p.leaf_k); + + const Hyperplanes hp(storage.d, p.hash_bits, p.seed); + std::vector locks(kNumLocks); + + struct LeafScratch { + AlignedTable vecs, gram; + std::vector norms, nn_dist, sketches; + std::vector nn_idx; + }; + std::vector scratch(omp_get_max_threads()); + const LeafVisitor on_leaf = [&](const int32_t* ids, size_t s) { + LeafScratch& sc = scratch[omp_get_thread_num()]; + ensure_size(sc.vecs, s * d); + gather_rows(storage, ids, s, sc.vecs.get()); + sc.norms.resize(s); + sc.sketches.resize(s * 16); + for (size_t i = 0; i < s; i++) { + const float* x = sc.vecs.get() + i * d; + sc.norms[i] = fvec_norm_L2sqr(x, d); + hp.sketch(x, sc.sketches.data() + i * 16); + } + ensure_size(sc.gram, s * s); + sc.nn_idx.resize(s * k); + sc.nn_dist.resize(s * k); + leaf_knn( + sc.vecs.get(), + sc.norms.data(), + s, + d, + metric, + int(k), + sc.gram.get(), + sc.nn_idx.data(), + sc.nn_dist.data()); + // Offers leaf point b to the reservoir of leaf point a. Keys are + // dist - d(a, a), so near candidates sit near 0 where bf16 is finest. + auto offer = [&](size_t a, size_t b, float dist) { + const uint16_t hash = residual_hash( + sc.sketches.data() + a * 16, + sc.sketches.data() + b * 16, + p.hash_bits); + const uint16_t key = + distance_key(is_ip ? dist + sc.norms[a] : dist); + std::lock_guard guard( + locks[uint32_t(ids[a]) & (kNumLocks - 1)]); + st.reservoir(dup.slot(ids[a])).offer(ids[b], hash, key); + }; + for (size_t i = 0; i < s; i++) { + for (size_t t = 0; t < k; t++) { + const int32_t j = sc.nn_idx[i * k + t]; + if (j < 0) { + break; + } + offer(i, size_t(j), sc.nn_dist[i * k + t]); + offer(size_t(j), i, sc.nn_dist[i * k + t]); + } + } + }; + + const double t0 = getmillisecs(); + PartitionStats stats; + partition_and_visit( + storage, + partition_params(p, metric), + mix_seed(uint64_t(p.seed), 0), + on_leaf, + &stats, + dup.ids); + if (verbose) { + printf("PiPNN: partition: %.3f s, %zu leaves, replication %.2f\n", + (getmillisecs() - t0) / 1000, + stats.n_leaves, + double(stats.n_point_instances) / double(n)); + } +} + +/// Prunes each reservoir into its graph row, freeing each chunk once pruned. +void final_prune( + BuildState& st, + const Index& storage, + const Duplicates& dup, + float alpha, + int R, + bool cosine) { + const size_t d = size_t(storage.d); + const MetricType metric = storage.metric_type; + int32_t* graph = st.graph.get(); + for (ReservoirChunk& ch : st.chunks) { + std::exception_ptr ex; + std::atomic interrupt{false}; +#pragma omp parallel + { + AlignedTable X; + AlignedTable D; + std::vector norms; + std::vector ids; + std::vector order; + size_t n_done = 0; +#pragma omp for schedule(dynamic, 64) + for (int64_t i = int64_t(ch.begin); i < int64_t(ch.begin + ch.np); + i++) { + if (interrupt.load(std::memory_order_relaxed)) { + continue; + } + try { + const ReservoirRef r = st.reservoir(size_t(i)); + const size_t l = *r.count; + const size_t m = l + 1; + ensure_size(X, m * d); + ensure_size(D, m * m); + norms.resize(m); + ids.resize(m); + order.resize(l); + ids[0] = dup.id(size_t(i)); + for (size_t t = 0; t < l; t++) { + ids[1 + t] = r.slots[t].id; + } + gather_rows(storage, ids.data(), m, X.get()); + if (cosine) { + fvec_renorm_L2(d, m, X.get()); + } + for (size_t t = 0; t < m; t++) { + norms[t] = fvec_norm_L2sqr(X.get() + t * d, d); + } + pairwise_distances( + X.get(), norms.data(), m, d, metric, D.get()); + robust_prune( + D.get(), + m, + ids.data() + 1, + metric, + alpha, + R, + order.data(), + graph + size_t(ids[0]) * size_t(R)); + if (omp_get_thread_num() == 0 && n_done++ % 64 == 0 && + InterruptCallback::is_interrupted()) { + FAISS_THROW_MSG("computation interrupted"); + } + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + } + omp_rethrow_if_exception(ex); + ch.buf.reset(); + } +} + +} // namespace + +void robust_prune( + const float* D, + size_t m, + const int32_t* cand, + MetricType metric, + float alpha, + int R, + int* order, + int32_t* out) { + const size_t l = m - 1; + std::iota(order, order + l, 0); + std::sort(order, order + l, [&](int a, int b) { + return CMin::cmp2(D[1 + a], D[1 + b], cand[a], cand[b]); + }); + const bool is_ip = metric == METRIC_INNER_PRODUCT; + int na = 0; + for (size_t t = 0; t < l && na < R; t++) { + const int c = order[t]; + const float dxc = D[1 + c]; + const bool kept = std::none_of(order, order + na, [&](int y) { + const float dyc = D[size_t(1 + y) * m + 1 + c]; + return is_ip ? dyc < alpha * dxc : alpha * dyc < dxc; + }); + if (kept) { + order[na++] = c; // na <= t: never overwrites an unread entry + } + } + for (int u = 0; u < na; u++) { + out[u] = cand[order[u]]; + } + std::fill(out + na, out + R, -1); +} + +namespace detail { + +void build_with_chunk( + PiPNN& p, + const Index& storage, + size_t reservoir_chunk, + bool verbose) { + p.check_params(); + const size_t n = size_t(storage.ntotal); + if (n == 0) { + p.effective_alpha(storage.metric_type); + p.reset(); + return; + } + + const double t0 = getmillisecs(); + InterruptCallback::check(); + float norm_cv = 0; + const int32_t ep = medoid_and_validate( + storage, + storage.metric_type == METRIC_INNER_PRODUCT ? &norm_cv : nullptr); + const bool cosine = norm_cv > 0.05f; + const float alpha = p.effective_alpha(storage.metric_type); + if (verbose) { + printf("PiPNN: medoid and validation of %zu vectors (d=%d): %.3f s\n", + n, + storage.d, + (getmillisecs() - t0) / 1000); + } + + Duplicates dup(storage); + BuildState st(dup.n_slots(n), n, p, reservoir_chunk); + fill_reservoirs(st, storage, dup, p, verbose); + + const double t1 = getmillisecs(); + final_prune(st, storage, dup, alpha, p.R, cosine); + std::vector next_copy = + dup.link_copies(st.graph.get(), size_t(p.R)); + InterruptCallback::check(); + if (verbose) { + printf("PiPNN: final prune: %.3f s\n", (getmillisecs() - t1) / 1000); + } + + // Publish: nothing below can throw after the members start changing. + auto owner = std::make_shared(std::move(st.graph)); + p.graph = MaybeOwnedVector::create_view( + owner->data.get(), n * size_t(p.R), owner); + p.next_copy = std::move(next_copy); + p.entry_point = ep; + p.ntotal = idx_t(n); +} + +} // namespace detail + +namespace { + +/// Up to cap entries in (dis, id) order; all before cursor are expanded. +struct SearchBeam { + struct Entry { + float dis; + int32_t id; + bool expanded; + + bool operator<(const Entry& o) const { + return CMin::cmp2(dis, o.dis, id, o.id); + } + }; + + std::vector entries; + size_t cap; + size_t cursor = 0; + + explicit SearchBeam(size_t cap_in) : cap(cap_in) { + entries.reserve(cap_in + 1); + } + + void insert(float dis, int32_t id) { + const Entry e{dis, id, false}; + if (entries.size() == cap && !(e < entries.back())) { + return; + } + const auto it = std::lower_bound(entries.begin(), entries.end(), e); + cursor = std::min(cursor, size_t(it - entries.begin())); + entries.insert(it, e); + if (entries.size() > cap) { + entries.pop_back(); + } + } + + /// The closest unexpanded entry after the cursor, or -1. + int32_t peek_next() const { + for (size_t c = cursor + 1; c < entries.size(); c++) { + if (!entries[c].expanded) { + return entries[c].id; + } + } + return -1; + } + + /// Marks the closest unexpanded entry expanded; returns its id, or -1. + int32_t expand_next() { + while (cursor < entries.size() && entries[cursor].expanded) { + cursor++; + } + if (cursor == entries.size()) { + return -1; + } + entries[cursor].expanded = true; + return entries[cursor].id; + } +}; + +template +void beam_search( + const PiPNN& pipnn, + DistanceComputer& qdis, + const uint8_t* codes, + size_t code_size, + size_t cap, + size_t k, + idx_t* I, + float* D, + VT& vt, + const IDSelector* sel) { + const uint32_t n = uint32_t(pipnn.ntotal); + const size_t R = size_t(pipnn.R); + const int32_t* graph = pipnn.graph.data(); + const int32_t* next_copy = + pipnn.next_copy.size() == 0 ? nullptr : pipnn.next_copy.data(); + SearchBeam beam(cap); + + // id breaks ties, so the result does not depend on visit order + auto offer = [&](int32_t id, float dis) { + const bool better = + CMax::cmp2(D[0], dis, I[0], idx_t(id)); + if (better && (sel == nullptr || sel->is_member(id))) { + maxheap_replace_top(k, D, I, dis, idx_t(id)); + } + return better; + }; + // Copies skip the beam. Their ids increase, so the first one the heap + // rejects ends the chain; checking that also stops a corrupt chain. + auto visit = [&](int32_t id, float dis) { + int32_t c = id; + while (offer(c, dis) && next_copy && next_copy[c] > c && + uint32_t(next_copy[c]) < n) { + c = next_copy[c]; + } + beam.insert(dis, id); + }; + + vt.set(size_t(pipnn.entry_point)); + visit(pipnn.entry_point, qdis(pipnn.entry_point)); + + // Prefetching more than 1 KiB per vector costs more than it saves. + const size_t prefetch_bytes = std::min(code_size, size_t(1024)); + auto prefetch = [](const void* p, size_t nbytes) { + const uintptr_t a = reinterpret_cast(p); + for (uintptr_t b = a & ~uintptr_t(63); b < a + nbytes; b += 64) { + prefetch_L1(reinterpret_cast(b)); + } + }; + auto prefetch_code = [&](int32_t id) { + prefetch(codes + size_t(id) * code_size, prefetch_bytes); + }; + // Vectors are prefetched about 4 KiB ahead of the distance computation, + // at least one batch: prefetching all neighbors of a large-vector graph at + // once evicts the ones about to be read when two threads share a core. + const size_t ahead = std::max( + size_t(4), size_t(4096) / std::max(prefetch_bytes, size_t(64))); + std::vector todo(R); + for (int32_t v0 = beam.expand_next(); v0 >= 0; v0 = beam.expand_next()) { + // The closest unexpanded entry usually comes next. + const int32_t next = beam.peek_next(); + if (next >= 0) { + prefetch(graph + size_t(next) * R, R * sizeof(int32_t)); + } + const int32_t* row = graph + size_t(v0) * R; + // One unsigned compare stops at the -1 padding and at any id that is + // out of range in a corrupt (e.g. mmapped) graph. + size_t jmax = 0; + while (jmax < R && uint32_t(row[jmax]) < n) { + vt.prefetch(size_t(row[jmax])); + jmax++; + } + size_t nt = 0; + for (size_t j = 0; j < jmax; j++) { + if (vt.set(size_t(row[j]))) { + if (nt < ahead) { + prefetch_code(row[j]); + } + todo[nt++] = row[j]; + } + } + size_t i = 0; + for (; i + 4 <= nt; i += 4) { + for (size_t t = i + ahead; t < std::min(i + ahead + 4, nt); t++) { + prefetch_code(todo[t]); + } + float d4[4]; + qdis.distances_batch_4( + todo[i], + todo[i + 1], + todo[i + 2], + todo[i + 3], + d4[0], + d4[1], + d4[2], + d4[3]); + for (size_t t = 0; t < 4; t++) { + visit(todo[i + t], d4[t]); + } + } + for (; i < nt; i++) { + visit(todo[i], qdis(todo[i])); + } + } +} + +} // namespace + +} // namespace pipnn + +float PiPNN::effective_alpha(MetricType metric) const { + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT, + "PiPNN supports only METRIC_L2 and METRIC_INNER_PRODUCT"); + return alpha != 0 ? alpha : 1.2f; +} + +void PiPNN::check_params() const { + FAISS_THROW_IF_NOT_FMT(R >= 1, "PiPNN: R must be >= 1, got %d", R); + FAISS_THROW_IF_NOT_FMT( + leaf_k >= 1 && leaf_k <= c_max, + "PiPNN: need 1 <= leaf_k <= c_max, got leaf_k=%d c_max=%d", + leaf_k, + c_max); + FAISS_THROW_IF_NOT_FMT( + hash_bits >= 1 && hash_bits <= 16, + "PiPNN: hash_bits must be in [1, 16], got %d", + hash_bits); + FAISS_THROW_IF_NOT_FMT( + reservoir_size >= 1 && reservoir_size <= 255, + "PiPNN: reservoir_size must be in [1, 255], got %d", + reservoir_size); + FAISS_THROW_IF_NOT_FMT( + R <= reservoir_size, + "PiPNN: need R <= reservoir_size, got R=%d reservoir_size=%d", + R, + reservoir_size); + for (int f : fanout) { + FAISS_THROW_IF_NOT_FMT( + f >= 1, "PiPNN: every fanout must be >= 1, got %d", f); + } + FAISS_THROW_IF_NOT_FMT( + c_min >= 1 && c_min <= c_max, + "PiPNN: need 1 <= c_min <= c_max, got c_min=%d c_max=%d", + c_min, + c_max); + FAISS_THROW_IF_NOT_FMT( + c_max <= pipnn::kMaxCMax, + "PiPNN: c_max must be <= %d, got %d", + pipnn::kMaxCMax, + c_max); + FAISS_THROW_IF_NOT_FMT( + leader_cap >= 1 && leader_cap <= pipnn::kMaxLeaderCap, + "PiPNN: leader_cap must be in [1, %d], got %d", + pipnn::kMaxLeaderCap, + leader_cap); + FAISS_THROW_IF_NOT_FMT( + leader_fraction >= 0 && leader_fraction <= 1, + "PiPNN: leader_fraction must be in [0, 1], got %g", + double(leader_fraction)); + FAISS_THROW_IF_NOT_FMT( + alpha == 0 || (std::isfinite(alpha) && alpha >= 1), + "PiPNN: alpha must be 0 (default) or finite and >= 1, got %g", + double(alpha)); +} + +void PiPNN::build(const Index& storage, bool verbose) { + pipnn::detail::build_with_chunk( + *this, storage, pipnn::kReservoirChunk, verbose); +} + +void PiPNN::search( + DistanceComputer& qdis, + int L, + idx_t k, + idx_t* I, + float* D, + VisitedTable& vt, + const IDSelector* sel) const { + FAISS_THROW_IF_NOT_MSG(k > 0, "PiPNN::search: k must be positive"); + maxheap_heapify(size_t(k), D, I); + if (ntotal == 0) { + return; + } + // At most ntotal distinct nodes enter the beam. + const size_t cap = size_t(std::min(std::max(idx_t(L), k), ntotal)); + // The codes of Flat and SQ storage, to prefetch. + DistanceComputer* base = &qdis; + if (auto* neg = dynamic_cast(base)) { + base = neg->basedis; + } + const auto* fc = dynamic_cast(base); + const uint8_t* codes = fc ? fc->codes : nullptr; + const size_t code_size = fc ? fc->code_size : 0; + auto run = [&](auto& vtc) { + pipnn::beam_search( + *this, qdis, codes, code_size, cap, size_t(k), I, D, vtc, sel); + }; + if (auto* vtv = dynamic_cast(&vt)) { + run(*vtv); + } else { + run(dynamic_cast(vt)); + } + maxheap_reorder(size_t(k), D, I); + vt.advance(); +} + +void PiPNN::reset() { + // not graph.clear(): it asserts on the view build() publishes + graph = MaybeOwnedVector(); + next_copy = MaybeOwnedVector(); + entry_point = -1; + ntotal = 0; +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/PiPNN.h b/thirdparty/faiss/faiss/impl/PiPNN.h new file mode 100644 index 000000000..e8263aa98 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/PiPNN.h @@ -0,0 +1,122 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +#include +#include + +namespace faiss { + +struct DistanceComputer; +struct IDSelector; +struct Index; +struct PiPNN; +struct VisitedTable; + +namespace pipnn { + +// Internal build pieces, exposed for tests; hidden from SWIG. +#ifndef SWIG + +/// Points per medoid block. It fixes the summation order of the mean, so +/// changing it changes the entry point. +constexpr size_t kMedoidBlock = size_t(1) << 16; + +/// Throws unless every vector is finite with squared norm <= FLT_MAX / 8, and +/// returns the L2 medoid: the point closest to the mean, lowest id on ties. +int32_t medoid_and_validate(const Index& storage, float* norm_cv = nullptr); + +/// RobustPrune of x (row 0 of the m x m D) over cand[t] (row 1 + t) in +/// (D, id) order; writes <= R ids to out, -1 padded. order: m - 1 ints. +void robust_prune( + const float* D, + size_t m, + const int32_t* cand, + MetricType metric, + float alpha, + int R, + int* order, + int32_t* out); + +namespace detail { + +/// PiPNN::build with a given reservoir chunk size, for tests. +void build_with_chunk( + PiPNN& p, + const Index& storage, + size_t reservoir_chunk, + bool verbose); + +} // namespace detail + +#endif // SWIG + +} // namespace pipnn + +/// PiPNN graph (Rubel et al., KDD '26, arXiv:2602.21247). +struct PiPNN { + // build parameters + int R = 64; ///< max out-degree + int leaf_k = 2; ///< neighbours each point offers per leaf + int hash_bits = 12; ///< HashPrune keeps one candidate per hash bucket + int reservoir_size = 64; ///< candidates kept per point + int c_max = 1024; ///< largest leaf + int c_min = 128; ///< smaller partition children are merged + int leader_cap = 1000; ///< most leaders per split + float leader_fraction = 0.005f; ///< leaders per split, fraction of its size + float alpha = 0; ///< 0 = 1.2 + std::vector fanout = {10, 3}; ///< leaders joined per depth, then 1 + int64_t seed = 1234; + /// IP: rank partition leaders by angle, not inner product + bool ip_partition_by_angle = false; + /// point instances per partition wave, which bounds memory + size_t partition_wave_budget = size_t(1) << 30; + + int search_L = 64; ///< default beam width of search + + // result + MaybeOwnedVector graph; ///< ntotal x R, -1 padded + /// next higher row with the same code, or -1; empty if all codes differ. + /// Such copies have empty graph rows; search returns them with the first. + MaybeOwnedVector next_copy; + int32_t entry_point = -1; ///< L2 medoid + idx_t ntotal = 0; + + PiPNN() = default; + explicit PiPNN(int R_in) : R(R_in) {} + + float effective_alpha(MetricType metric) const; + + void check_params() const; + +#ifndef SWIG + /// Builds over the vectors and metric of storage. Strong guarantee: the + /// results are unchanged if it throws. + void build(const Index& storage, bool verbose = false); + + /// Beam max(L, k); qdis smaller-is-better; vt: ntotal slots, clean in/out. + /// Writes the k nearest in sel by (dis, id), padded; sel does not prune. + void search( + DistanceComputer& qdis, + int L, + idx_t k, + idx_t* I, + float* D, + VisitedTable& vt, + const IDSelector* sel) const; +#endif + + /// Empties the graph; entry_point = -1, ntotal = 0. + void reset(); +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/PolysemousTraining.cpp b/thirdparty/faiss/faiss/impl/PolysemousTraining.cpp index dce008b8b..e82bcdf6c 100644 --- a/thirdparty/faiss/faiss/impl/PolysemousTraining.cpp +++ b/thirdparty/faiss/faiss/impl/PolysemousTraining.cpp @@ -299,7 +299,7 @@ struct ReproduceWithHammingObjective : PermutationObjective { double dis_weight_factor_in) : nbits(nbits_in), dis_weight_factor(dis_weight_factor_in) { n = 1 << nbits; - FAISS_THROW_IF_NOT(dis_table.size() == n * n); + FAISS_THROW_IF_NOT(dis_table.size() == static_cast(n * n)); set_affine_target_dis(dis_table); } diff --git a/thirdparty/faiss/faiss/impl/ProductQuantizer.cpp b/thirdparty/faiss/faiss/impl/ProductQuantizer.cpp index cebfbf351..fba3b5498 100644 --- a/thirdparty/faiss/faiss/impl/ProductQuantizer.cpp +++ b/thirdparty/faiss/faiss/impl/ProductQuantizer.cpp @@ -9,6 +9,8 @@ #include +#include +#include #include #include #include @@ -16,10 +18,12 @@ #include #include +#include #include #include #include +#include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include #include @@ -141,8 +145,8 @@ void ProductQuantizer::train(size_t n, const float* x) { } } - std::unique_ptr xslice(new float[n * dsub]); - for (size_t m = 0; m < M; m++) { + const auto train_slice = [&](size_t m) { + std::unique_ptr xslice(new float[n * dsub]); for (size_t j = 0; j < n; j++) memcpy(xslice.get() + j * dsub, x + j * d + m * dsub, @@ -150,7 +154,6 @@ void ProductQuantizer::train(size_t n, const float* x) { Clustering clus(dsub, ksub, cp); - // we have some initialization for the centroids if (final_train_type != Train_default) { clus.centroids.resize(dsub * ksub); } @@ -187,6 +190,28 @@ void ProductQuantizer::train(size_t n, const float* x) { IndexFlatL2 index(dsub); clus.train(n, xslice.get(), assign_index ? *assign_index : index); set_params(clus.centroids.data(), m); + }; + + if (!assign_index && x != centroids.data() && M > 1 && + M * 8 >= static_cast(omp_get_max_threads())) { + std::exception_ptr ex; + std::atomic failed{false}; +#pragma omp parallel for + for (int64_t m = 0; m < static_cast(M); m++) { + if (failed) { + continue; + } + try { + train_slice(m); + } catch (...) { + omp_capture_exception(ex, [&] { failed = true; }); + } + } + omp_rethrow_if_exception(ex); + } else { + for (size_t m = 0; m < M; m++) { + train_slice(m); + } } } else { @@ -422,10 +447,21 @@ void ProductQuantizer::compute_codes(const float* x, uint8_t* codes, size_t n) int64_t n_signed = n; if (dsub < 16) { // simple direct computation + std::exception_ptr ex; + std::atomic interrupt{false}; #pragma omp parallel for - for (int64_t i = 0; i < n_signed; i++) - compute_code(x + i * d, codes + i * code_size); + for (int64_t i = 0; i < n_signed; i++) { + if (interrupt.load(std::memory_order_relaxed)) { + continue; + } + try { + compute_code(x + i * d, codes + i * code_size); + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + omp_rethrow_if_exception(ex); } else { // worthwhile to use BLAS std::unique_ptr dis_tables(new float[n * ksub * M]); @@ -489,8 +525,12 @@ void ProductQuantizer::compute_distance_tables( const float* x, float* dis_tables) const { int64_t nx_signed = nx; -#if defined(COMPILE_SIMD_AVX2) || defined(COMPILE_SIMD_ARM_NEON) - if (dsub == 2 && nbits < 8) { // interesting for a narrow range of settings +#if defined(COMPILE_SIMD_AVX2) || defined(COMPILE_SIMD_ARM_NEON) || \ + defined(COMPILE_SIMD_RISCV_RVV) + // The dsub2 kernels help for a narrow range of settings. They require + // ksub = 1 << nbits to be a multiple of 8. Therefore nbits must be 3 or + // more. + if (dsub == 2 && nbits >= 3 && nbits < 8) { compute_PQ_dis_tables_dsub2( d, ksub, centroids.data(), nx, x, false, dis_tables); } else @@ -524,8 +564,9 @@ void ProductQuantizer::compute_inner_prod_tables( const float* x, float* dis_tables) const { int64_t nx_signed = nx; -#if defined(COMPILE_SIMD_AVX2) || defined(COMPILE_SIMD_ARM_NEON) - if (dsub == 2 && nbits < 8) { +#if defined(COMPILE_SIMD_AVX2) || defined(COMPILE_SIMD_ARM_NEON) || \ + defined(COMPILE_SIMD_RISCV_RVV) + if (dsub == 2 && nbits >= 3 && nbits < 8) { compute_PQ_dis_tables_dsub2( d, ksub, centroids.data(), nx, x, true, dis_tables); } else @@ -872,8 +913,9 @@ void ProductQuantizer::search_sdc( float* heap_dis = res->val + i * k; const uint8_t* qcode = qcodes + i * code_size; - if (init_finalize_heap) + if (init_finalize_heap) { maxheap_heapify(k, heap_dis, heap_ids); + } // Precompute per-subquantizer row pointers: q_row[m] points to // sdc_table[m*ksub^2 + qcode[m]*ksub], eliminating M @@ -897,8 +939,9 @@ void ProductQuantizer::search_sdc( bcode += code_size; } - if (init_finalize_heap) + if (init_finalize_heap) { maxheap_reorder(k, heap_dis, heap_ids); + } } } } diff --git a/thirdparty/faiss/faiss/impl/RaBitQUtils.cpp b/thirdparty/faiss/faiss/impl/RaBitQUtils.cpp index dae57cd09..a8e5845c2 100644 --- a/thirdparty/faiss/faiss/impl/RaBitQUtils.cpp +++ b/thirdparty/faiss/faiss/impl/RaBitQUtils.cpp @@ -77,8 +77,6 @@ SignBitFactorsWithError compute_factors_from_intermediates( MetricType metric_type, bool compute_error) { constexpr float epsilon = std::numeric_limits::epsilon(); - constexpr float kConstEpsilon = - 1.9f; // Error bound constant from RaBitQ paper const float inv_d_sqrt = (d == 0) ? 1.0f : (1.0f / std::sqrt(static_cast(d))); diff --git a/thirdparty/faiss/faiss/impl/RaBitQUtils.h b/thirdparty/faiss/faiss/impl/RaBitQUtils.h index 4d46aff6c..afb32dbfa 100644 --- a/thirdparty/faiss/faiss/impl/RaBitQUtils.h +++ b/thirdparty/faiss/faiss/impl/RaBitQUtils.h @@ -22,6 +22,9 @@ namespace faiss { namespace rabitq_utils { +/// constant of the RaBitQ error bound (RaBitQ paper, Theorem 3.2) +constexpr float kConstEpsilon = 1.9f; + /** Base factors computed per database vector for RaBitQ distance computation. * Used by both 1-bit and multi-bit RaBitQ variants. * These can be stored either embedded in codes (IndexRaBitQ) or separately @@ -87,6 +90,32 @@ struct QueryFactorsData { */ FAISS_API extern const float Z_MAX_BY_QB[8]; +// out[code] = base + sum of v_i for each set bit in code. +inline void write_subset_sum_lut( + float* out, + float base, + float v0, + float v1, + float v2, + float v3) { + out[0] = base; + out[1] = base + v0; + out[2] = base + v1; + out[3] = base + v0 + v1; + out[4] = base + v2; + out[5] = base + v0 + v2; + out[6] = base + v1 + v2; + out[7] = base + v0 + v1 + v2; + out[8] = base + v3; + out[9] = base + v0 + v3; + out[10] = base + v1 + v3; + out[11] = base + v0 + v1 + v3; + out[12] = base + v2 + v3; + out[13] = base + v0 + v2 + v3; + out[14] = base + v1 + v2 + v3; + out[15] = base + v0 + v1 + v2 + v3; +} + /** Fast half-away rounding for non-negative RaBitQ quantization values. * * Contract: x must be finite, non-NaN, and in [0, 255.5). This is not a @@ -353,7 +382,7 @@ inline int extract_code_inline( * The multi-bit distance combines the sign bit (1-bit) with additional * magnitude bits (ex_bits) to compute a more accurate distance estimate. * Uses SIMD-optimized bit-plane decomposition (AVX2+BMI2) for ex_bits 1-7, - * with scalar fallback for non-x86 or non-BMI2 platforms. + * with scalar fallback for non-x86 platforms. * * @param sign_bits unpacked sign bits (1-bit codes in standard format) * @param ex_code packed ex-bit codes diff --git a/thirdparty/faiss/faiss/impl/RaBitQuantizer.cpp b/thirdparty/faiss/faiss/impl/RaBitQuantizer.cpp index bd9ba704e..6b82c9f25 100644 --- a/thirdparty/faiss/faiss/impl/RaBitQuantizer.cpp +++ b/thirdparty/faiss/faiss/impl/RaBitQuantizer.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,11 @@ namespace faiss { RaBitQStats rabitq_stats; +void RaBitQStats::add_atomic(const RaBitQStats& other) { + detail::atomic_fetch_add_relaxed(n_1bit, other.n_1bit); + detail::atomic_fetch_add_relaxed(n_refine, other.n_refine); +} + // Import shared utilities from RaBitQUtils using rabitq_utils::ExtraBitsFactors; using rabitq_utils::QueryFactorsData; @@ -297,27 +303,10 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer { float distance_to_code_1bit_impl( const uint8_t* binary_data, const SignBitFactors* base_fac) const { - // this is the baseline code - // - // compute using floats - float dot_qo = 0; - // It was a willful decision (after the discussion) to not to pre-cache - // the sum of all bits, just in order to reduce the overhead per - // vector. - uint64_t sum_q = 0; + const float dot_qo = fvec_masked_sum::value>( + rotated_q.data(), binary_data, d); - for (size_t i = 0; i < d; i++) { - // Extract i-th bit - bool bit = rabitq_utils::extract_bit_standard(binary_data, i); - // accumulate dp - dot_qo += bit ? rotated_q[i] : 0; - // accumulate sum-of-bits - sum_q += bit ? 1 : 0; - } - - // Apply query factors - float final_dot = - query_fac.c1 * dot_qo + query_fac.c2 * sum_q - query_fac.c34; + float final_dot = query_fac.c1 * dot_qo - query_fac.c34; // pre_dist = ||or - c||^2 + ||qr - c||^2 - // 2 * ||or - c|| * ||qr - c|| * - (IP ? ||or||^2 : 0) @@ -419,7 +408,6 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer { } query_fac.c1 = 2 * inv_d; - query_fac.c2 = 0; query_fac.c34 = sum_q * inv_d; if (metric_type == MetricType::METRIC_INNER_PRODUCT) { @@ -431,9 +419,9 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer { size_t scan_codes_multibit( size_t list_size, - const uint8_t* codes, + const uint8_t* list_codes, const idx_t* ids, - size_t code_size, + size_t list_code_size, idx_t list_no, bool store_pairs, const IDSelector* sel, @@ -454,16 +442,16 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer { idx_t id = store_pairs ? lo_build(list_no, j) : ids[j]; if (!sel_dispatch.is_member( id, IDScanContext{ids, list_size, j})) { - codes += code_size; + list_codes += list_code_size; continue; } } const auto* base_fac = reinterpret_cast( - codes + code_size_base); + list_codes + code_size_base); const float est_distance = - distance_to_code_1bit_impl(codes, base_fac); + distance_to_code_1bit_impl(list_codes, base_fac); const bool should_refine = rabitq_utils::should_refine_candidate( est_distance, @@ -473,15 +461,17 @@ struct RaBitQDistanceComputerNotQ final : RaBitQDistanceComputer { keep_max); if (should_refine) { handler.stats.scan_cnt++; - const float dis = distance_to_code_full(codes); + const float dis = distance_to_code_full(list_codes); idx_t id = store_pairs ? lo_build(list_no, j) : ids[j]; - if (handler.add_result(dis, id)) { + if ((keep_max ? dis > handler.threshold + : dis < handler.threshold) && + handler.add_result(dis, id)) { handler.stats.nheap_updates++; nup++; } } - codes += code_size; + list_codes += list_code_size; } return nup; @@ -521,8 +511,6 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer { float final_dot = 0; if (centered) { int64_t int_dot = ((1 << qb) - 1) * d; - // See RaBitDistanceComputerNotQ::distance_to_code() for - // baseline code. int_dot -= 2 * rabitq::bitwise_xor_dot_product( rearranged_rotated_qq.data(), @@ -688,60 +676,60 @@ struct RaBitQDistanceComputerQ final : RaBitQDistanceComputer { size_t scan_codes_multibit( size_t list_size, - const uint8_t* codes, + const uint8_t* list_codes, const idx_t* ids, - size_t code_size, + size_t list_code_size, idx_t list_no, bool store_pairs, const IDSelector* sel, bool keep_max, ResultHandler& handler) final { const size_t code_size_base = (d + 7) / 8; - const size_t ex_bits = nb_bits - 1; - FAISS_ASSERT(ex_bits > 0); - // Honor IDSelectorWithContext on the multibit path too, so a RaBitQ - // index does not silently lose the context hook once nb_bits >= 2 (the - // 1-bit path already routes through run_scan_codes1). const IDSelectorContextDispatch sel_dispatch(sel, store_pairs); - size_t nup = 0; - for (size_t j = 0; j < list_size; j++) { - if (sel != nullptr) { - idx_t id = store_pairs ? lo_build(list_no, j) : ids[j]; - if (!sel_dispatch.is_member( - id, IDScanContext{ids, list_size, j})) { - codes += code_size; - continue; + auto scan = [&](auto multibit) { + size_t nup = 0; + for (size_t j = 0; j < list_size; + j++, list_codes += list_code_size) { + if (sel != nullptr) { + idx_t id = store_pairs ? lo_build(list_no, j) : ids[j]; + if (!sel_dispatch.is_member( + id, IDScanContext{ids, list_size, j})) { + continue; + } } - } - const auto* base_fac = - reinterpret_cast( - codes + code_size_base); - const float est_distance = - distance_to_code_1bit_impl(codes, base_fac, code_size_base); - - const bool should_refine = rabitq_utils::should_refine_candidate( - est_distance, - base_fac->f_error, - g_error, - handler.threshold, - keep_max); - if (should_refine) { + const auto* base_fac = + reinterpret_cast( + list_codes + code_size_base); + float dis = distance_to_code_1bit_impl( + list_codes, base_fac, code_size_base); + + if constexpr (decltype(multibit)::value) { + if (!rabitq_utils::should_refine_candidate( + dis, + base_fac->f_error, + g_error, + handler.threshold, + keep_max)) { + continue; + } + dis = distance_to_code_full(list_codes); + } handler.stats.scan_cnt++; - const float dis = distance_to_code_full(codes); idx_t id = store_pairs ? lo_build(list_no, j) : ids[j]; - if (handler.add_result(dis, id)) { + if ((keep_max ? dis > handler.threshold + : dis < handler.threshold) && + handler.add_result(dis, id)) { handler.stats.nheap_updates++; nup++; } } - codes += code_size; - } - - return nup; + return nup; + }; + return nb_bits == 1 ? scan(std::false_type{}) : scan(std::true_type{}); } }; diff --git a/thirdparty/faiss/faiss/impl/RaBitQuantizer.h b/thirdparty/faiss/faiss/impl/RaBitQuantizer.h index 5adea2f7d..7ec23a428 100644 --- a/thirdparty/faiss/faiss/impl/RaBitQuantizer.h +++ b/thirdparty/faiss/faiss/impl/RaBitQuantizer.h @@ -40,6 +40,8 @@ struct RaBitQStats { n_refine += other.n_refine; } + void add_atomic(const RaBitQStats& other); + double refine_ratio() const { return n_1bit ? double(n_refine) / double(n_1bit) : 0.0; } @@ -157,11 +159,11 @@ struct RaBitQDistanceComputer : FlatCodesDistanceComputer { // Compute 1-bit distance estimate (fast) virtual float distance_to_code_1bit(const uint8_t* code) = 0; - /// Compute four independent one-bit estimates, in input order, after - /// set_query(). Each pointer addresses one complete encoded row; rows need - /// not be contiguous or distinct. Output has room for four floats. - /// Does not refine candidates, update thresholds, or increment stats. - /// The default implementation delegates to four single-code evaluations. + /// Compute four one-bit estimates in input order. Caller must call + /// set_query() first. Each pointer addresses one complete encoded row; rows + /// need not be contiguous or distinct. The output holds four floats. + /// Does not refine candidates, update thresholds, or increment stats. The + /// default calls the single estimate four times. virtual void distance_to_code_1bit_batch_4( const uint8_t* const* codes_in, float* distances) { @@ -170,54 +172,6 @@ struct RaBitQDistanceComputer : FlatCodesDistanceComputer { } } - // Avoid another virtual dispatch through FlatCodesDistanceComputer's - // code-batch entry on this ID-based hot path. - void distances_batch_4( - const idx_t i1, - const idx_t i2, - const idx_t i3, - const idx_t i4, - float& d1, - float& d2, - float& d3, - float& d4) override { - RaBitQDistanceComputer::distance_to_code_batch_4( - codes + i1 * code_size, - codes + i2 * code_size, - codes + i3 * code_size, - codes + i4 * code_size, - d1, - d2, - d3, - d4); - } - - /// Standard full-distance batch entry. A one-bit code is already a full - /// code; use its existing batch kernel. Multi-bit codes retain full - /// scoring. - void distance_to_code_batch_4( - const uint8_t* c1, - const uint8_t* c2, - const uint8_t* c3, - const uint8_t* c4, - float& d1, - float& d2, - float& d3, - float& d4) override { - if (nb_bits == 1) { - const uint8_t* codes_in[4] = {c1, c2, c3, c4}; - float distances[4]; - distance_to_code_1bit_batch_4(codes_in, distances); - d1 = distances[0]; - d2 = distances[1]; - d3 = distances[2]; - d4 = distances[3]; - } else { - FlatCodesDistanceComputer::distance_to_code_batch_4( - c1, c2, c3, c4, d1, d2, d3, d4); - } - } - // Compute full multi-bit distance (accurate) virtual float distance_to_code_full(const uint8_t* code) = 0; diff --git a/thirdparty/faiss/faiss/impl/ResultHandler.h b/thirdparty/faiss/faiss/impl/ResultHandler.h index a30f18786..04d609f7f 100644 --- a/thirdparty/faiss/faiss/impl/ResultHandler.h +++ b/thirdparty/faiss/faiss/impl/ResultHandler.h @@ -256,6 +256,112 @@ struct Top1BlockResultHandler : TopkBlockResultHandler { } }; +/***************************************************************** + * Two best results handler. + * Keeps the two best results of each query, best first, without a heap. + *****************************************************************/ + +/** Insert a result into a pair sorted best first. + * + * Results are ordered by C::cmp2, as in the heaps: equal distances are + * ordered by id (the lower id first for CMax, the higher id first for CMin). + * + * @param dis distance of the result + * @param idx id of the result + * @param dis2 in/out: the two best distances, best first, size 2 + * @param ids2 in/out: their ids (-1 for none), size 2 + */ +template +inline void top2_insert( + typename C::T dis, + typename C::TI idx, + typename C::T* dis2, + typename C::TI* ids2) { + if (C::cmp2(dis2[1], dis, ids2[1], idx)) { + const bool first = C::cmp2(dis2[0], dis, ids2[0], idx); + dis2[1] = first ? dis2[0] : dis; + ids2[1] = first ? ids2[0] : idx; + if (first) { + dis2[0] = dis; + ids2[0] = idx; + } + } +} + +/** Top-2 search results: query i's two best results, best first, are stored + * at dis_tab[2 * i] and ids_tab[2 * i]. Queries with fewer than two results + * get C::neutral() and id -1. Results are admitted as in the heaps (strict + * comparison against the current second best, so NaN is never admitted) and + * equal distances are ordered as in top2_insert, so the results match the + * heap handler's. + */ +template +struct Top2BlockResultHandler : TopkBlockResultHandler { + using T = typename C::T; + using TI = typename C::TI; + using BlockResultHandler::i0; + using BlockResultHandler::i1; + + Top2BlockResultHandler( + size_t nq_, + T* dis_tab_, + TI* ids_tab_, + const IDSelector* sel_ = nullptr) + : TopkBlockResultHandler( + nq_, + dis_tab_, + ids_tab_, + 2, + sel_) {} + + struct SingleResultHandler : ResultHandlerT { + Top2BlockResultHandler& hr; + using ResultHandlerT::threshold; + + T dis2[2]; + TI ids2[2]; + size_t current_idx = 0; + + explicit SingleResultHandler(Top2BlockResultHandler& hr_) : hr(hr_) {} + + /// begin results for query # i + void begin(const size_t current_idx_2) { + current_idx = current_idx_2; + threshold = dis2[0] = dis2[1] = C::neutral(); + ids2[0] = ids2[1] = -1; + } + + /// add one result for query i; threshold is the second best + bool add_result(T dis, TI idx) final { + if (C::cmp(threshold, dis)) { + top2_insert(dis, idx, dis2, ids2); + threshold = dis2[1]; + return true; + } + return false; + } + + /// series of results for query i is done + void end() { + std::copy(dis2, dis2 + 2, hr.dis_tab + 2 * current_idx); + std::copy(ids2, ids2 + 2, hr.ids_tab + 2 * current_idx); + } + }; + + /// begin + void begin_multiple(size_t i0_in, size_t i1_in) final { + this->i0 = i0_in; + this->i1 = i1_in; + std::fill(this->dis_tab + 2 * i0, this->dis_tab + 2 * i1, C::neutral()); + std::fill(this->ids_tab + 2 * i0, this->ids_tab + 2 * i1, TI(-1)); + } + + /// add results for query i0..i1 and j0..j1 + /// Implemented in result_handler.cpp; dispatches via + /// with_selected_simd_levels to top2_add_results_tpl. + void add_results(size_t j0, size_t j1, const T* dis_tab_2) final; +}; + /***************************************************************** * Heap based result handler *****************************************************************/ @@ -725,6 +831,9 @@ typename Consumer::T dispatch_knn_ResultHandler( if (k == 1) { \ Top1BlockResultHandler res(nx, vals, ids, sel); \ return consumer.template f<>(res, args...); \ + } else if (k == 2) { \ + Top2BlockResultHandler res(nx, vals, ids, sel); \ + return consumer.template f<>(res, args...); \ } else if (k < static_cast(distance_compute_min_k_reservoir)) { \ HeapBlockResultHandler res(nx, vals, ids, k, sel); \ return consumer.template f<>(res, args...); \ @@ -792,6 +901,13 @@ void top1_add_results_tpl( size_t j1, const typename C::T* dis_tab); +template +void top2_add_results_tpl( + Top2BlockResultHandler* self, + size_t j0, + size_t j1, + const typename C::T* dis_tab); + template void reservoir_add_results_tpl( ReservoirBlockResultHandler* self, diff --git a/thirdparty/faiss/faiss/impl/ScalarQuantizer.cpp b/thirdparty/faiss/faiss/impl/ScalarQuantizer.cpp index 23ef44f55..49cd3fb58 100644 --- a/thirdparty/faiss/faiss/impl/ScalarQuantizer.cpp +++ b/thirdparty/faiss/faiss/impl/ScalarQuantizer.cpp @@ -453,6 +453,35 @@ float unit_norm_component_scale(size_t d) { } // namespace +void ScalarQuantizer::SQDistanceComputer::query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const { + dis0 = query_to_code(code_0); + dis1 = query_to_code(code_1); + dis2 = query_to_code(code_2); + dis3 = query_to_code(code_3); +} + +namespace scalar_quantizer { + +void IVFCoarseDistanceScanner::set_list(idx_t list_no_in, float coarse_dis_in) { + this->list_no = list_no_in; + this->coarse_dis = coarse_dis_in; +} + +float IVFCoarseDistanceScanner::distance_to_code( + const uint8_t* /*code*/) const { + return coarse_dis; +} + +} // namespace scalar_quantizer + /******************************************************************* * ScalarQuantizer implementation ********************************************************************/ diff --git a/thirdparty/faiss/faiss/impl/ScalarQuantizer.h b/thirdparty/faiss/faiss/impl/ScalarQuantizer.h index 9ae8dbb4d..65e0a65a3 100644 --- a/thirdparty/faiss/faiss/impl/ScalarQuantizer.h +++ b/thirdparty/faiss/faiss/impl/ScalarQuantizer.h @@ -133,12 +133,7 @@ struct ScalarQuantizer : Quantizer { float& dis0, float& dis1, float& dis2, - float& dis3) const { - dis0 = query_to_code(code_0); - dis1 = query_to_code(code_1); - dis2 = query_to_code(code_2); - dis3 = query_to_code(code_3); - } + float& dis3) const; float distance_to_code(const uint8_t* code) final { return query_to_code(code); diff --git a/thirdparty/faiss/faiss/impl/approx_topk/avx2.cpp b/thirdparty/faiss/faiss/impl/approx_topk/avx2.cpp index 85022e8d4..61d528532 100644 --- a/thirdparty/faiss/faiss/impl/approx_topk/avx2.cpp +++ b/thirdparty/faiss/faiss/impl/approx_topk/avx2.cpp @@ -8,8 +8,6 @@ // Explicit template instantiations of HeapWithBucketsCMaxFloat and // accum_and_*_tab for SIMDLevel::AVX2. -#ifdef COMPILE_SIMD_AVX2 - #include #include #include @@ -64,5 +62,3 @@ INSTANTIATE_ACCUM_TAB(8) #undef INSTANTIATE_ACCUM_TAB } // namespace faiss - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/approx_topk/neon.cpp b/thirdparty/faiss/faiss/impl/approx_topk/neon.cpp index 81ebdd2cf..ef431092f 100644 --- a/thirdparty/faiss/faiss/impl/approx_topk/neon.cpp +++ b/thirdparty/faiss/faiss/impl/approx_topk/neon.cpp @@ -8,8 +8,6 @@ // Explicit template instantiations of HeapWithBucketsCMaxFloat and // accum_and_*_tab for SIMDLevel::ARM_NEON. -#ifdef COMPILE_SIMD_ARM_NEON - #include #include #include @@ -64,5 +62,3 @@ INSTANTIATE_ACCUM_TAB(8) #undef INSTANTIATE_ACCUM_TAB } // namespace faiss - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h b/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h index 779258b47..7234826d2 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h +++ b/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryHash_impl.h @@ -139,11 +139,14 @@ void search_single_query_template( } while (fe.next()); } +// A hash type with internal linkage makes the functions of the set local. +struct ShortlistHash : std::hash {}; + template static void verify_shortlist( const IndexBinaryFlat* index, const uint8_t* q, - const std::unordered_set& shortlist, + const std::unordered_set& shortlist, SearchResults& res) { size_t code_size = index->code_size; @@ -164,7 +167,7 @@ void search_1_query_multihash( size_t& n0, size_t& nlist, size_t& ndis) { - std::unordered_set shortlist; + std::unordered_set shortlist; int b = index.b; BitstringReader br(xi, index.code_size); diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h b/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h index 3f26200fa..32a14a126 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h +++ b/thirdparty/faiss/faiss/impl/binary_hamming/IndexBinaryIVF_impl.h @@ -271,9 +271,7 @@ void search_knn_hamming_count( } } - indexIVF_stats.nq += nx; - indexIVF_stats.nlist += nlistv; - indexIVF_stats.ndis += ndis; + add_search_stats(nx, nlistv, ndis); } /* Manages NQ queries at a time, stores results */ diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/avx2.cpp b/thirdparty/faiss/faiss/impl/binary_hamming/avx2.cpp index 6bd7d8c8c..e2e58473b 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/avx2.cpp +++ b/thirdparty/faiss/faiss/impl/binary_hamming/avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #define THE_SIMD_LEVEL SIMDLevel::AVX2 // NOLINTNEXTLINE(facebook-hte-InlineHeader,facebook-unused-include-check) @@ -22,5 +20,3 @@ #include // IWYU pragma: keep // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/avx512.cpp b/thirdparty/faiss/faiss/impl/binary_hamming/avx512.cpp index cb2bcedba..61b02677b 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/avx512.cpp +++ b/thirdparty/faiss/faiss/impl/binary_hamming/avx512.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #define THE_SIMD_LEVEL SIMDLevel::AVX512 // NOLINTNEXTLINE(facebook-hte-InlineHeader) @@ -22,5 +20,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/neon.cpp b/thirdparty/faiss/faiss/impl/binary_hamming/neon.cpp index 324117ee8..320edd0e0 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/neon.cpp +++ b/thirdparty/faiss/faiss/impl/binary_hamming/neon.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #define THE_SIMD_LEVEL SIMDLevel::ARM_NEON // NOLINTNEXTLINE(facebook-hte-InlineHeader) @@ -22,5 +20,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/impl/binary_hamming/rvv.cpp b/thirdparty/faiss/faiss/impl/binary_hamming/rvv.cpp index 4a1590f5b..ad21a7db8 100644 --- a/thirdparty/faiss/faiss/impl/binary_hamming/rvv.cpp +++ b/thirdparty/faiss/faiss/impl/binary_hamming/rvv.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_RISCV_RVV - #define THE_SIMD_LEVEL SIMDLevel::RISCV_RVV // NOLINTNEXTLINE(facebook-hte-InlineHeader) @@ -22,5 +20,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/impl/expanded_scanners.h b/thirdparty/faiss/faiss/impl/expanded_scanners.h index 5b5658031..82e6e7c06 100644 --- a/thirdparty/faiss/faiss/impl/expanded_scanners.h +++ b/thirdparty/faiss/faiss/impl/expanded_scanners.h @@ -69,8 +69,9 @@ size_t run_scan_codes1( // Batched variant of run_scan_codes1 for the SQ scanners: distances four codes // per step via distance_to_codes_batch_4, then applies the threshold and heap -// updates in id order so results match run_scan_codes1. No-selector path only. -template +// updates in id order so results match run_scan_codes1. With use_sel, the +// selector is tested only on codes that beat the threshold. +template size_t run_scan_codes4( const ScannerType& scanner, size_t list_size, @@ -81,6 +82,21 @@ size_t run_scan_codes4( size_t list_no = scanner.list_no; size_t code_size = scanner.code_size; float threshold = handler.threshold; + auto add = [&](size_t j, float dis) { + if (!C::cmp(threshold, dis)) { + return; + } + int64_t id = store_pairs ? lo_build(list_no, j) : ids[j]; + // No scan context: few codes get here, so a lookahead would be wasted. + if (use_sel && !scanner.sel->is_member(id)) { + return; + } + if (handler.add_result(dis, id)) { + handler.stats.nheap_updates++; + nup++; + threshold = handler.threshold; + } + }; size_t j = 0; for (; j + 4 <= list_size; j += 4) { @@ -96,15 +112,7 @@ size_t run_scan_codes4( dis[3]); handler.stats.scan_cnt += 4; for (size_t b = 0; b < 4; b++) { - if (C::cmp(threshold, dis[b])) { - int64_t id = - store_pairs ? lo_build(list_no, j + b) : ids[j + b]; - if (handler.add_result(dis[b], id)) { - handler.stats.nheap_updates++; - nup++; - threshold = handler.threshold; - } - } + add(j + b, dis[b]); } codes += 4 * code_size; } @@ -112,15 +120,7 @@ size_t run_scan_codes4( // tail: the final < 4 codes, one at a time for (; j < list_size; j++) { handler.stats.scan_cnt++; - float dis = scanner.distance_to_code(codes); - if (C::cmp(threshold, dis)) { - int64_t id = store_pairs ? lo_build(list_no, j) : ids[j]; - if (handler.add_result(dis, id)) { - handler.stats.nheap_updates++; - nup++; - threshold = handler.threshold; - } - } + add(j, scanner.distance_to_code(codes)); codes += code_size; } @@ -196,8 +196,9 @@ size_t run_scan_codes_fix_C( } } -// Routing wrapper for the SQ scanners: the no-selector path takes the batched -// run_scan_codes4, the selector path stays on run_scan_codes1. +// Routing wrapper for the SQ scanners: the no-selector path and a selector +// tested after the distance take the batched run_scan_codes4, a selector tested +// first stays on run_scan_codes1. template size_t run_scan_codes4_fix_C( const ScannerType& scanner, @@ -205,6 +206,10 @@ size_t run_scan_codes4_fix_C( const uint8_t* codes, const idx_t* ids, ResultHandler& handler) { + if (scanner.sel && scanner.sel_after_distance && !scanner.store_pairs) { + return run_scan_codes4( + scanner, list_size, codes, ids, handler); + } if (scanner.sel) { if (scanner.store_pairs) { return run_scan_codes1( @@ -215,10 +220,10 @@ size_t run_scan_codes4_fix_C( } } else { if (scanner.store_pairs) { - return run_scan_codes4( + return run_scan_codes4( scanner, list_size, codes, ids, handler); } else { - return run_scan_codes4( + return run_scan_codes4( scanner, list_size, codes, ids, handler); } } diff --git a/thirdparty/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h b/thirdparty/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h index 72b5b27f6..8d9a30192 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/FastScanDistancePostProcessing.h @@ -29,6 +29,10 @@ struct FastScanDistancePostProcessing { /// QueryFactorsData subset for this context. rabitq_utils::QueryFactorsData* query_factors = nullptr; + /// Multi-bit IVF RaBitQ: rotated query per (query, probe), d floats each, + /// indexed like query_factors (nullptr if unused). + float* rotated_q = nullptr; + /// The nprobe value used when allocating query_factors storage. /// This is needed because the allocation size (n * nprobe) may use a /// different nprobe than index->nprobe if search params override it. diff --git a/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops.h b/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops.h index 34d5e174a..1f3ad8dbf 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops.h @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -14,22 +22,14 @@ * Contains: * - accumulate_fixed_blocks / pq4_accumulate_loop_fixed_scaler * (search_1 multi-BB path, bbs > 32) - * - accumulate_q_4step_256 / pq4_accumulate_loop_qbs_fixed_scaler_256 - * (QBS path, bbs == 32, 256-bit kernel only) + * - SIMD-level-selected QBS traversal (bbs == 32) * - * The QBS helpers here use pq4_kernel_qbs_256 exclusively (not - * decompose_qbs.h) because decompose_qbs.h includes kernels_simd512.h - * whose 512-bit types need explicit SIMD levels. The 512-bit QBS path - * lives in accumulate_loops_512.h, used by the AVX512 per-ISA TU. + * The default PQ4QBSKernel uses the 256-bit kernel. Architecture-specific + * headers may specialize it while reusing the traversal and QBS dispatch. * * All functions live in `namespace faiss` (not anonymous) so they can be * shared by both the per-SIMD TU dispatcher (dispatching.h) and the old * free-function search paths (pq4_fast_scan_search_1.cpp). - * - * The QBS helpers here always use pq4_kernel_qbs_256 (never 512-bit). - * This is required for the per-SIMD DD TUs where SINGLE_SIMD_LEVEL=NONE - * leaves 512-bit types empty. The old pq4_fast_scan_search_qbs.cpp - * continues to use decompose_qbs.h which includes both 256 and 512 paths. */ #include @@ -37,7 +37,11 @@ #include #include #include +#if FAISS_SIMD_TU(ARM_NEON) +#include +#endif #include +#include namespace faiss { @@ -112,15 +116,11 @@ void pq4_accumulate_loop_fixed_scaler( } /*************************************************************** - * QBS path helpers (bbs == 32, 256-bit kernel only) + * QBS path helpers (bbs == 32) ***************************************************************/ -template < - int QBS, - SIMDLevel KernelSL = SINGLE_SIMD_LEVEL, - class ResultHandler, - class Scaler> -void accumulate_q_4step_256( +template +void accumulate_q_4step_for_simd( size_t ntotal2, int nsq, const uint8_t* codes, @@ -135,33 +135,31 @@ void accumulate_q_4step_256( constexpr int SQ = Q1 + Q2 + Q3 + Q4; for_each_block<32>(ntotal2, codes, block_stride, res, [&](size_t) { - FixedStorageHandler res2; + // Scaler as LinkageTag: see FixedStorageHandler. + FixedStorageHandler res2; const uint8_t* LUT = LUT0; - pq4_kernel_qbs_256(nsq, codes, LUT, res2, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res2, scaler); LUT += Q1 * nsq * 16; if (Q2 > 0) { res2.set_block_origin(Q1, 0); - pq4_kernel_qbs_256(nsq, codes, LUT, res2, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res2, scaler); LUT += Q2 * nsq * 16; } if (Q3 > 0) { res2.set_block_origin(Q1 + Q2, 0); - pq4_kernel_qbs_256(nsq, codes, LUT, res2, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res2, scaler); LUT += Q3 * nsq * 16; } if (Q4 > 0) { res2.set_block_origin(Q1 + Q2 + Q3, 0); - pq4_kernel_qbs_256(nsq, codes, LUT, res2, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res2, scaler); } res2.to_other_handler(res); }); } -template < - SIMDLevel KernelSL = SINGLE_SIMD_LEVEL, - class ResultHandler, - class Scaler> -void pq4_accumulate_loop_qbs_fixed_scaler_256( +template +void pq4_accumulate_loop_qbs_fixed_scaler_simd( int qbs, size_t ntotal2, int nsq, @@ -175,38 +173,37 @@ void pq4_accumulate_loop_qbs_fixed_scaler_256( assert(is_aligned_pointer(LUT0)); switch (qbs) { -#define FAISS_QBS256_DISPATCH(QBS) \ +#define FAISS_QBS_DISPATCH(QBS) \ case QBS: \ - accumulate_q_4step_256( \ + accumulate_q_4step_for_simd( \ ntotal2, nsq, codes, LUT0, res, scaler, block_stride); \ return; - FAISS_QBS256_DISPATCH(0x3333); // 12 - FAISS_QBS256_DISPATCH(0x2333); // 11 - FAISS_QBS256_DISPATCH(0x2233); // 10 - FAISS_QBS256_DISPATCH(0x333); // 9 - FAISS_QBS256_DISPATCH(0x2223); // 9 - FAISS_QBS256_DISPATCH(0x233); // 8 - FAISS_QBS256_DISPATCH(0x1223); // 8 - FAISS_QBS256_DISPATCH(0x223); // 7 - FAISS_QBS256_DISPATCH(0x34); // 7 - FAISS_QBS256_DISPATCH(0x133); // 7 - FAISS_QBS256_DISPATCH(0x6); // 6 - FAISS_QBS256_DISPATCH(0x33); // 6 - FAISS_QBS256_DISPATCH(0x123); // 6 - FAISS_QBS256_DISPATCH(0x222); // 6 - FAISS_QBS256_DISPATCH(0x23); // 5 - FAISS_QBS256_DISPATCH(0x5); // 5 - FAISS_QBS256_DISPATCH(0x13); // 4 - FAISS_QBS256_DISPATCH(0x22); // 4 - FAISS_QBS256_DISPATCH(0x4); // 4 - FAISS_QBS256_DISPATCH(0x3); // 3 - FAISS_QBS256_DISPATCH(0x21); // 3 - FAISS_QBS256_DISPATCH(0x2); // 2 - FAISS_QBS256_DISPATCH(0x1); // 1 -#undef FAISS_QBS256_DISPATCH + FAISS_QBS_DISPATCH(0x3333); // 12 + FAISS_QBS_DISPATCH(0x2333); // 11 + FAISS_QBS_DISPATCH(0x2233); // 10 + FAISS_QBS_DISPATCH(0x333); // 9 + FAISS_QBS_DISPATCH(0x2223); // 9 + FAISS_QBS_DISPATCH(0x233); // 8 + FAISS_QBS_DISPATCH(0x1223); // 8 + FAISS_QBS_DISPATCH(0x223); // 7 + FAISS_QBS_DISPATCH(0x34); // 7 + FAISS_QBS_DISPATCH(0x133); // 7 + FAISS_QBS_DISPATCH(0x6); // 6 + FAISS_QBS_DISPATCH(0x33); // 6 + FAISS_QBS_DISPATCH(0x123); // 6 + FAISS_QBS_DISPATCH(0x222); // 6 + FAISS_QBS_DISPATCH(0x23); // 5 + FAISS_QBS_DISPATCH(0x5); // 5 + FAISS_QBS_DISPATCH(0x13); // 4 + FAISS_QBS_DISPATCH(0x22); // 4 + FAISS_QBS_DISPATCH(0x4); // 4 + FAISS_QBS_DISPATCH(0x3); // 3 + FAISS_QBS_DISPATCH(0x21); // 3 + FAISS_QBS_DISPATCH(0x2); // 2 + FAISS_QBS_DISPATCH(0x1); // 1 +#undef FAISS_QBS_DISPATCH } - // Default: qbs not known at compile time for_each_block<32>(ntotal2, codes, block_stride, res, [&](size_t j0) { const uint8_t* LUT = LUT0; int qi = qbs; @@ -215,16 +212,16 @@ void pq4_accumulate_loop_qbs_fixed_scaler_256( int nq = qi & 15; qi >>= 4; res.set_block_origin(i0, j0); -#define FAISS_NQ256_DISPATCH(NQ) \ - case NQ: \ - pq4_kernel_qbs_256(nsq, codes, LUT, res, scaler); \ +#define FAISS_NQ_DISPATCH(NQ) \ + case NQ: \ + PQ4QBSKernel::template run(nsq, codes, LUT, res, scaler); \ break switch (nq) { - FAISS_NQ256_DISPATCH(1); - FAISS_NQ256_DISPATCH(2); - FAISS_NQ256_DISPATCH(3); - FAISS_NQ256_DISPATCH(4); -#undef FAISS_NQ256_DISPATCH + FAISS_NQ_DISPATCH(1); + FAISS_NQ_DISPATCH(2); + FAISS_NQ_DISPATCH(3); + FAISS_NQ_DISPATCH(4); +#undef FAISS_NQ_DISPATCH default: FAISS_THROW_FMT("accumulate nq=%d not instantiated", nq); } diff --git a/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops_512.h b/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops_512.h index 1b9d73b60..178f7eabe 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops_512.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/accumulate_loops_512.h @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -23,8 +31,6 @@ * dispatching.h's conditional include. */ -#if defined(COMPILE_SIMD_AVX512) && defined(__AVX512F__) - #include #include @@ -169,17 +175,10 @@ void pq4_accumulate_loop_qbs_fixed_scaler_512( // Fallback for unknown QBS values: use 256-bit path. // This is rare — pq4_preferred_qbs() covers all values above. - if constexpr (Scaler::nscale == 0) { - DummyScaler scaler_avx2; - pq4_accumulate_loop_qbs_fixed_scaler_256( - qbs, ntotal2, nsq, codes, LUT0, res, scaler_avx2, block_stride); - } else { - NormTableScaler scaler_avx2(scaler.scale_int); - pq4_accumulate_loop_qbs_fixed_scaler_256( - qbs, ntotal2, nsq, codes, LUT0, res, scaler_avx2, block_stride); - } + // The caller's AVX512-level scaler gives these instantiations symbol names + // that the AVX2 TU does not emit. + pq4_accumulate_loop_qbs_fixed_scaler_simd( + qbs, ntotal2, nsq, codes, LUT0, res, scaler, block_stride); } } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 && __AVX512F__ diff --git a/thirdparty/faiss/faiss/impl/fast_scan/decompose_qbs.h b/thirdparty/faiss/faiss/impl/fast_scan/decompose_qbs.h index dc44c3d60..d41bfc8d4 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/decompose_qbs.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/decompose_qbs.h @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -12,7 +20,11 @@ #include #include #include +#if FAISS_SIMD_TU(ARM_NEON) +#include +#endif #include +#include namespace faiss { @@ -20,7 +32,7 @@ using namespace simd_result_handlers; /* * Unified kernel: selects 256-bit vs 512-bit path based on - * compile-time __AVX512F__ guard. + * compile-time COMPILE_SIMD_AVX512 && __AVX512F__ guard. * * KernelSL selects the SIMD type width used for the inner accumulation * loop. In DD mode the caller passes the dispatch level so the kernel @@ -37,66 +49,20 @@ void kernel_accumulate_block( const uint8_t* LUT, ResultHandler& res, const Scaler& scaler) { -#ifdef __AVX512F__ +#if FAISS_SIMD_TU(AVX512) if constexpr ( KernelSL == SIMDLevel::AVX512 || KernelSL == SIMDLevel::AVX512_VPOPCNT || KernelSL == SIMDLevel::AVX512_SPR) { pq4_kernel_qbs_512(nsq, codes, LUT, res, scaler); } else { - pq4_kernel_qbs_256(nsq, codes, LUT, res, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res, scaler); } #else - pq4_kernel_qbs_256(nsq, codes, LUT, res, scaler); + PQ4QBSKernel::template run(nsq, codes, LUT, res, scaler); #endif } -// handle at most 4 blocks of queries -template < - int QBS, - SIMDLevel KernelSL = SINGLE_SIMD_LEVEL, - class ResultHandler, - class Scaler> -void accumulate_q_4step( - size_t ntotal2, - int nsq, - const uint8_t* codes, - const uint8_t* LUT0, - ResultHandler& res, - const Scaler& scaler, - size_t block_stride) { - constexpr int Q1 = QBS & 15; - constexpr int Q2 = (QBS >> 4) & 15; - constexpr int Q3 = (QBS >> 8) & 15; - constexpr int Q4 = (QBS >> 12) & 15; - constexpr int SQ = Q1 + Q2 + Q3 + Q4; - - for_each_block<32>(ntotal2, codes, block_stride, res, [&](size_t) { - FixedStorageHandler res2; - const uint8_t* LUT = LUT0; - kernel_accumulate_block(nsq, codes, LUT, res2, scaler); - LUT += Q1 * nsq * 16; - if (Q2 > 0) { - res2.set_block_origin(Q1, 0); - kernel_accumulate_block( - nsq, codes, LUT, res2, scaler); - LUT += Q2 * nsq * 16; - } - if (Q3 > 0) { - res2.set_block_origin(Q1 + Q2, 0); - kernel_accumulate_block( - nsq, codes, LUT, res2, scaler); - LUT += Q3 * nsq * 16; - } - if (Q4 > 0) { - res2.set_block_origin(Q1 + Q2 + Q3, 0); - kernel_accumulate_block( - nsq, codes, LUT, res2, scaler); - } - res2.to_other_handler(res); - }); -} - template < int NQ, SIMDLevel KernelSL = SINGLE_SIMD_LEVEL, @@ -149,82 +115,4 @@ void accumulate( #undef DISPATCH } -template < - SIMDLevel KernelSL = SINGLE_SIMD_LEVEL, - class ResultHandler, - class Scaler> -void pq4_accumulate_loop_qbs_fixed_scaler( - int qbs, - size_t ntotal2, - int nsq, - const uint8_t* codes, - const uint8_t* LUT0, - ResultHandler& res, - const Scaler& scaler, - size_t block_stride = 0) { - assert(nsq % 2 == 0); - assert(is_aligned_pointer(codes)); - assert(is_aligned_pointer(LUT0)); - - // try out optimized versions - switch (qbs) { -#define DISPATCH(QBS) \ - case QBS: \ - accumulate_q_4step( \ - ntotal2, nsq, codes, LUT0, res, scaler, block_stride); \ - return; - DISPATCH(0x3333); // 12 - DISPATCH(0x2333); // 11 - DISPATCH(0x2233); // 10 - DISPATCH(0x333); // 9 - DISPATCH(0x2223); // 9 - DISPATCH(0x233); // 8 - DISPATCH(0x1223); // 8 - DISPATCH(0x223); // 7 - DISPATCH(0x34); // 7 - DISPATCH(0x133); // 7 - DISPATCH(0x6); // 6 - DISPATCH(0x33); // 6 - DISPATCH(0x123); // 6 - DISPATCH(0x222); // 6 - DISPATCH(0x23); // 5 - DISPATCH(0x5); // 5 - DISPATCH(0x13); // 4 - DISPATCH(0x22); // 4 - DISPATCH(0x4); // 4 - DISPATCH(0x3); // 3 - DISPATCH(0x21); // 3 - DISPATCH(0x2); // 2 - DISPATCH(0x1); // 1 -#undef DISPATCH - } - - // default implementation where qbs is not known at compile time - for_each_block<32>(ntotal2, codes, block_stride, res, [&](size_t j0) { - const uint8_t* LUT = LUT0; - int qi = qbs; - int i0 = 0; - while (qi) { - int nq = qi & 15; - qi >>= 4; - res.set_block_origin(i0, j0); -#define DISPATCH(NQ) \ - case NQ: \ - kernel_accumulate_block(nsq, codes, LUT, res, scaler); \ - break - switch (nq) { - DISPATCH(1); - DISPATCH(2); - DISPATCH(3); - DISPATCH(4); -#undef DISPATCH - default: - FAISS_THROW_FMT("accumulate nq=%d not instantiated", nq); - } - i0 += nq; - LUT += nq * nsq * 16; - } - }); -} - } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/fast_scan/dispatching.h b/thirdparty/faiss/faiss/impl/fast_scan/dispatching.h index 2dfe5da07..d15ab3938 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/dispatching.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/dispatching.h @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -20,8 +28,8 @@ * #define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX2 * #include * - * Kernel helpers come from accumulate_loops.h (search_1 multi-BB path - * and QBS 256-bit path) and accumulate_loops_512.h (QBS 512-bit path, + * Kernel helpers come from accumulate_loops.h (search_1 multi-BB path and + * SIMD-level-selected QBS path) and accumulate_loops_512.h (QBS 512-bit path, * AVX512 TU only). */ @@ -35,7 +43,7 @@ #include #include -#if defined(COMPILE_SIMD_AVX512) && defined(__AVX512F__) +#if FAISS_SIMD_TU(AVX512) #include #endif @@ -107,7 +115,7 @@ struct ScannerMixIn : FastScanCodeScanner { const uint8_t* LUT, int pq2x4_scale, size_t block_stride) override { -#if defined(COMPILE_SIMD_AVX512) && defined(__AVX512F__) +#if FAISS_SIMD_TU(AVX512) constexpr bool use_avx512_qbs = (THE_LEVEL_TO_DISPATCH == SIMDLevel::AVX512 || THE_LEVEL_TO_DISPATCH == SIMDLevel::AVX512_SPR); @@ -115,18 +123,14 @@ struct ScannerMixIn : FastScanCodeScanner { constexpr bool use_avx512_qbs = false; #endif if constexpr (use_avx512_qbs) { - // AMD Zen 4 / Zen 4c ("Bergamo", family 0x19) split 512-bit - // ops over a 256-bit datapath, so the 512-bit QBS kernel yields no - // throughput gain but pays extra per-block LUT-assembly and - // cross-lane reduction overhead (measured ~14% search regression - // for PQ8x4fs / PQ16x4fs). Route those CPUs to the 256-bit (AVX2) - // QBS kernel instead -- same output, no downside on Zen 4. This is - // a process-constant runtime branch, hoisted out of the inner - // accumulate loop. Intel AVX-512 keeps the 512-bit kernel. + // Zen 4 runs 512-bit ops on a 256-bit datapath, so the 512-bit QBS + // kernel is slower there; use the AVX2 kernel. if (SIMDConfig::avx512_split) { + // THE_LEVEL_TO_DISPATCH scalers give these AVX2-loop + // instantiations symbol names that the AVX2 TU does not emit. if (pq2x4_scale) { - NormTableScaler scaler(pq2x4_scale); - pq4_accumulate_loop_qbs_fixed_scaler_256( + NormTableScaler scaler(pq2x4_scale); + pq4_accumulate_loop_qbs_fixed_scaler_simd( qbs, nb, nsq, @@ -136,8 +140,8 @@ struct ScannerMixIn : FastScanCodeScanner { scaler, block_stride); } else { - DummyScaler dummy; - pq4_accumulate_loop_qbs_fixed_scaler_256( + DummyScaler dummy; + pq4_accumulate_loop_qbs_fixed_scaler_simd( qbs, nb, nsq, @@ -174,7 +178,8 @@ struct ScannerMixIn : FastScanCodeScanner { } else { if (pq2x4_scale) { NormTableScaler scaler(pq2x4_scale); - pq4_accumulate_loop_qbs_fixed_scaler_256( + pq4_accumulate_loop_qbs_fixed_scaler_simd< + THE_LEVEL_TO_DISPATCH>( qbs, nb, nsq, @@ -185,7 +190,8 @@ struct ScannerMixIn : FastScanCodeScanner { block_stride); } else { DummyScaler dummy; - pq4_accumulate_loop_qbs_fixed_scaler_256( + pq4_accumulate_loop_qbs_fixed_scaler_simd< + THE_LEVEL_TO_DISPATCH>( qbs, nb, nsq, diff --git a/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.cpp b/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.cpp index 64960a9f1..7953b8648 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.cpp +++ b/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.cpp @@ -12,10 +12,16 @@ #include #include +#include #include namespace faiss { +void SIMDResultHandlerToFloat::end() { + normalizers = nullptr; + scan_cnt = 0; +} + using namespace simd_result_handlers; /*************************************************************** @@ -34,8 +40,8 @@ void get_matrix_column( int64_t i, int64_t j, TA& dest) { - for (int64_t k = 0; k < dest.size(); k++) { - if (k + i >= 0 && k + i < m) { + for (int64_t k = 0; k < static_cast(dest.size()); k++) { + if (k + i >= 0 && k + i < static_cast(m)) { dest[k] = src[(k + i) * n + j]; } else { dest[k] = 0; @@ -83,7 +89,7 @@ void pq4_pack_codes( uint8_t* codes2 = blocks; for (size_t i0 = 0; i0 < nb; i0 += bbs) { - for (int sq = 0; sq < nsq; sq += 2) { + for (size_t sq = 0; sq < nsq; sq += 2) { for (size_t i = 0; i < bbs; i += 32) { std::array c, c0, c1; get_matrix_column( @@ -142,7 +148,7 @@ void pq4_pack_codes_range( for (size_t b = block0; b < block1; b++) { uint8_t* codes2 = blocks + b * block_stride; int64_t i_base = b * bbs - i0; - for (int sq = 0; sq < nsq; sq += 2) { + for (size_t sq = 0; sq < nsq; sq += 2) { for (size_t i = 0; i < bbs; i += 32) { std::array c, c0, c1; get_matrix_column( @@ -236,8 +242,8 @@ void pq4_set_packed_element( * CodePackerPQ4 implementation ***************************************************************/ -CodePackerPQ4::CodePackerPQ4(size_t nsq, size_t bbs) { - this->nsq = nsq; +CodePackerPQ4::CodePackerPQ4(size_t nsq_in, size_t bbs) { + nsq = nsq_in; nvec = bbs; code_size = (nsq * 4 + 7) / 8; block_size = ((nsq + 1) / 2) * bbs; @@ -432,6 +438,67 @@ void accumulate_to_mem( }); } +/*************************************************************** + * accumulate_hacc: NONE specialization + runtime dispatch. + ***************************************************************/ + +template <> +void accumulate_hacc_impl( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + // byte j of a 16-byte half holds the codes of elements perm0[j] (low + // nibble) and perm0[j] + 16 (high nibble), as packed by pq4_pack_codes +#ifdef FAISS_BIG_ENDIAN + const uint8_t perm0[16] = { + 8, 0, 9, 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7}; +#else + const uint8_t perm0[16] = { + 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15}; +#endif + const size_t block_stride = 32 * size_t(nsq) / 2; + for (int q = 0; q < nq; q++) { + const uint8_t* lut_lo = LUT + size_t(q) * 2 * 16 * nsq; + const uint8_t* lut_hi = lut_lo + 16 * size_t(nsq); + for (size_t b = 0; b < ntotal2 / 32; b++) { + const uint8_t* block = codes + b * block_stride; + int32_t* out = accu + q * ntotal2 + b * 32; + std::fill(out, out + 32, 0); + for (int sq = 0; sq < nsq; sq++) { + const uint8_t* c = block + (sq / 2) * 32 + (sq % 2) * 16; + const uint8_t* lo = lut_lo + 16 * sq; + const uint8_t* hi = lut_hi + 16 * sq; + for (int j = 0; j < 16; j++) { + const int c0 = c[j] & 15, c1 = c[j] >> 4; + out[perm0[j]] += lo[c0] + (int32_t(hi[c0]) << 8); + out[perm0[j] + 16] += lo[c1] + (int32_t(hi[c1]) << 8); + } + } + } + } +} + +void accumulate_hacc( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + FAISS_THROW_IF_NOT(ntotal2 % 32 == 0); + FAISS_THROW_IF_NOT(nsq % 2 == 0); + FAISS_THROW_IF_NOT_FMT( + nsq <= 32768, + "accumulate_hacc: nsq=%d > 32768 would overflow the int32 sums", + nsq); + with_selected_simd_levels([&]() { + accumulate_hacc_impl(nq, ntotal2, nsq, codes, LUT, accu); + }); +} + } // namespace faiss namespace faiss { diff --git a/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.h b/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.h index 0d260295f..c3ee9b85a 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/fast_scan.h @@ -178,6 +178,49 @@ void accumulate_to_mem_impl( const uint8_t* LUT, uint16_t* accu); +/// SIMD levels with high-accuracy FastScan accumulation implementations. +/// The AVX512 kernel returns wrong sums when compiled with MSVC, where the +/// AVX2 one is used instead. +#ifdef _MSC_VER +constexpr int FAST_SCAN_HACC_SIMD_LEVELS = + (1 << int(SIMDLevel::NONE)) | (1 << int(SIMDLevel::AVX2)); +#else +constexpr int FAST_SCAN_HACC_SIMD_LEVELS = (1 << int(SIMDLevel::NONE)) | + (1 << int(SIMDLevel::AVX2)) | (1 << int(SIMDLevel::AVX512)) | + (1 << int(SIMDLevel::ARM_NEON)); +#endif + +/** Same as accumulate_to_mem, but with 16-bit look-up table entries summed + * exactly into 32-bit accumulators for nsq <= 32768. Each 16-bit table is given + * as two 8-bit tables: the low bytes of its entries, then the high bytes. + * + * @param nq number of queries + * @param ntotal2 number of database elements (multiple of 32) + * @param nsq number of sub-quantizers (multiple of 2) + * @param codes packed codes array, in blocks of 32 elements + * @param LUT for each query, 16 * nsq bytes of low bytes, then 16 * nsq + * bytes of high bytes, each laid out as by + * pq4_pack_LUT(1, nsq, ...) + * @param accu array to store the results, size nq * ntotal2 + */ +void accumulate_hacc( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu); + +/// Per-SIMD specialization of accumulate_hacc (defined in per-SIMD TUs) +template +void accumulate_hacc_impl( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu); + /*************************************************************** * FastScanCodeScanner: virtual base that bundles handler + kernel * behind the SIMD dispatch boundary. Per-SIMD TUs instantiate this diff --git a/thirdparty/faiss/faiss/impl/fast_scan/impl-avx2.cpp b/thirdparty/faiss/faiss/impl/fast_scan/impl-avx2.cpp index 5dba4f9ad..20e358638 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/impl-avx2.cpp +++ b/thirdparty/faiss/faiss/impl/fast_scan/impl-avx2.cpp @@ -5,13 +5,14 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX2 #include // IWYU pragma: keep #include // IWYU pragma: keep #include +#include + +#include namespace faiss { @@ -31,6 +32,16 @@ void accumulate_to_mem_impl( nq, ntotal2, nsq, codes, LUT, handler, scaler, 32 * nsq / 2); } -} // namespace faiss +template <> +void accumulate_hacc_impl( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + accumulate_hacc_simdlib( + nq, ntotal2, nsq, codes, LUT, accu); +} -#endif // COMPILE_SIMD_AVX2 +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/fast_scan/impl-avx512.cpp b/thirdparty/faiss/faiss/impl/fast_scan/impl-avx512.cpp index 9f03766e8..b46a7a3c4 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/impl-avx512.cpp +++ b/thirdparty/faiss/faiss/impl/fast_scan/impl-avx512.cpp @@ -5,13 +5,16 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX512 #include // IWYU pragma: keep #include // IWYU pragma: keep #include +#include + +#include +#include +#include namespace faiss { @@ -35,6 +38,114 @@ void accumulate_to_mem_impl( nq, ntotal2, nsq, codes, LUT, handler, scaler, 32 * nsq / 2); } -} // namespace faiss +/* accumulate_hacc over one block of 32 codes. One 512-bit register holds 4 + * sub-quantizers, one per 128-bit lane. The sums of two lanes are added in + * 16 bits before widening, so segments of 512 sub-quantizers keep them below + * 255 * 512 / 2 < 2^16. */ +static inline void accumulate_hacc_block_avx512( + int nsq, + const uint8_t* codes, + const uint8_t* lut_lo, + const uint8_t* lut_hi, + int32_t* accu) { + constexpr int kSegmentSq = 512; + const __m512i low_mask = _mm512_set1_epi8(0xf); + __m512i res[2] = {_mm512_setzero_si512(), _mm512_setzero_si512()}; + + for (int seg = 0; seg < nsq; seg += kSegmentSq) { + const int seg_end = std::min(nsq, seg + kSegmentSq); + // 4 sub-quantizers from sq on; when only 2 are left, the upper + // lanes are zero: zero codes look up zero table entries + auto load4 = [seg_end](const uint8_t* p, int sq) { + if (sq + 4 <= seg_end) { + return _mm512_loadu_si512(p); + } + return _mm512_inserti64x4( + _mm512_setzero_si512(), + _mm256_loadu_si256((const __m256i*)p), + 0); + }; + // [low or high byte table][elements 0-15 even / odd bytes, + // elements 16-31 even / odd bytes] + __m512i acc[2][4]; + for (auto& a : acc) { + for (auto& reg : a) { + reg = _mm512_setzero_si512(); + } + } + for (int sq = seg; sq < seg_end; sq += 4) { + const __m512i c = load4(codes + 16 * sq, sq); + const __m512i clo = _mm512_and_si512(c, low_mask); + const __m512i chi = + _mm512_and_si512(_mm512_srli_epi16(c, 4), low_mask); + const uint8_t* luts[2] = {lut_lo + 16 * sq, lut_hi + 16 * sq}; + for (int t = 0; t < 2; t++) { + const __m512i lut = load4(luts[t], sq); + const __m512i res_lo = _mm512_shuffle_epi8(lut, clo); + const __m512i res_hi = _mm512_shuffle_epi8(lut, chi); + acc[t][0] = _mm512_add_epi16(acc[t][0], res_lo); + acc[t][1] = _mm512_add_epi16( + acc[t][1], _mm512_srli_epi16(res_lo, 8)); + acc[t][2] = _mm512_add_epi16(acc[t][2], res_hi); + acc[t][3] = _mm512_add_epi16( + acc[t][3], _mm512_srli_epi16(res_hi, 8)); + } + } + + // add the two 256-bit halves, then the lanes holding the same + // elements, widening to 32 bits + auto combine = [](__m512i even, __m512i odd) { + __m256i e = _mm256_add_epi16( + _mm512_castsi512_si256(even), + _mm512_extracti64x4_epi64(even, 1)); + __m256i o = _mm256_add_epi16( + _mm512_castsi512_si256(odd), + _mm512_extracti64x4_epi64(odd, 1)); + e = _mm256_sub_epi16(e, _mm256_slli_epi16(o, 8)); + return _mm512_add_epi32( + _mm512_cvtepu16_epi32( + _mm256_permute2f128_si256(e, o, 0x21)), + _mm512_cvtepu16_epi32(_mm256_blend_epi32(e, o, 0xF0))); + }; + __m512i dis0[2], dis1[2]; + for (int t = 0; t < 2; t++) { + dis0[t] = combine(acc[t][0], acc[t][1]); + dis1[t] = combine(acc[t][2], acc[t][3]); + } + // low + (high << 8) + res[0] = _mm512_add_epi32( + res[0], + _mm512_add_epi32(dis0[0], _mm512_slli_epi32(dis0[1], 8))); + res[1] = _mm512_add_epi32( + res[1], + _mm512_add_epi32(dis1[0], _mm512_slli_epi32(dis1[1], 8))); + } + + _mm512_storeu_si512(accu, res[0]); // elements 0 to 15 + _mm512_storeu_si512(accu + 16, res[1]); // elements 16 to 31 +} -#endif // COMPILE_SIMD_AVX512 +template <> +void accumulate_hacc_impl( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + const size_t block_stride = 32 * size_t(nsq) / 2; + for (int q = 0; q < nq; q++) { + const uint8_t* lut_lo = LUT + size_t(q) * 2 * 16 * nsq; + const uint8_t* lut_hi = lut_lo + 16 * size_t(nsq); + for (size_t b = 0; b < ntotal2 / 32; b++) { + accumulate_hacc_block_avx512( + nsq, + codes + b * block_stride, + lut_lo, + lut_hi, + accu + q * ntotal2 + b * 32); + } + } +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp b/thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp index 7c40e832d..643445a81 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp +++ b/thirdparty/faiss/faiss/impl/fast_scan/impl-neon.cpp @@ -5,13 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #define THE_LEVEL_TO_DISPATCH SIMDLevel::ARM_NEON #include // IWYU pragma: keep #include // IWYU pragma: keep #include +#include namespace faiss { @@ -31,90 +30,16 @@ void accumulate_to_mem_impl( nq, ntotal2, nsq, codes, LUT, handler, scaler, 32 * nsq / 2); } -} // namespace faiss - -// ARM_SVE: forward to ARM_NEON implementation until a dedicated SVE -// specialization is written (same pattern as scalar_quantizer/sq-neon.cpp). -#ifdef COMPILE_SIMD_ARM_SVE - -namespace faiss { - template <> -std::unique_ptr make_fast_scan_scanner_impl< - SIMDLevel::ARM_SVE>( - bool is_max, - int impl, - size_t nq, - size_t ntotal, - int64_t k, - float* distances, - int64_t* ids, - const IDSelector* sel, - bool with_id_map) { - return make_fast_scan_scanner_impl( - is_max, impl, nq, ntotal, k, distances, ids, sel, with_id_map); -} - -template <> -std::unique_ptr make_range_scanner_impl< - SIMDLevel::ARM_SVE>( - bool is_max, - RangeSearchResult& rres, - float radius, - size_t ntotal, - const IDSelector* sel) { - return make_range_scanner_impl( - is_max, rres, radius, ntotal, sel); -} - -template <> -std::unique_ptr make_partial_range_scanner_impl< - SIMDLevel::ARM_SVE>( - bool is_max, - RangeSearchPartialResult& pres, - float radius, - size_t ntotal, - size_t q0, - size_t q1, - const IDSelector* sel) { - return make_partial_range_scanner_impl( - is_max, pres, radius, ntotal, q0, q1, sel); -} - -template <> -std::unique_ptr rabitq_make_knn_scanner_impl< - SIMDLevel::ARM_SVE>( - const IndexRaBitQFastScan* index, - bool is_max, - size_t nq, - int64_t k, - float* distances, - int64_t* ids, - const IDSelector* sel, - const FastScanDistancePostProcessing& context, - bool is_multi_bit) { - return rabitq_make_knn_scanner_impl( - index, is_max, nq, k, distances, ids, sel, context, is_multi_bit); -} - -template <> -std::unique_ptr rabitq_ivf_make_knn_scanner_impl< - SIMDLevel::ARM_SVE>( - bool is_max, - const IndexIVFRaBitQFastScan* index, - size_t nq, - size_t k, - float* distances, - int64_t* ids, - const IDSelector* sel, - const FastScanDistancePostProcessing* context, - bool multi_bit) { - return rabitq_ivf_make_knn_scanner_impl( - is_max, index, nq, k, distances, ids, sel, context, multi_bit); +void accumulate_hacc_impl( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + accumulate_hacc_simdlib( + nq, ntotal2, nsq, codes, LUT, accu); } } // namespace faiss - -#endif // COMPILE_SIMD_ARM_SVE - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/impl/fast_scan/impl-riscv.cpp b/thirdparty/faiss/faiss/impl/fast_scan/impl-riscv.cpp index b765a016f..ca9d289ae 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/impl-riscv.cpp +++ b/thirdparty/faiss/faiss/impl/fast_scan/impl-riscv.cpp @@ -8,8 +8,6 @@ // RISC-V RVV: forward all fast_scan specializations to NONE until // dedicated RVV implementations are written. -#ifdef COMPILE_SIMD_RISCV_RVV - #include namespace faiss { @@ -100,5 +98,3 @@ std::unique_ptr rabitq_ivf_make_knn_scanner_impl< } } // namespace faiss - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/impl/fast_scan/kernels_neon.h b/thirdparty/faiss/faiss/impl/fast_scan/kernels_neon.h new file mode 100644 index 000000000..e3e8ecd7a --- /dev/null +++ b/thirdparty/faiss/faiss/impl/fast_scan/kernels_neon.h @@ -0,0 +1,155 @@ +/* + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include +#include + +namespace faiss { + +/* + * Single-BB QBS variant: accumulates NQ queries x 32 db elements (BB=1). + * Uses native 128-bit AdvSIMD registers instead of logical 256-bit values. + */ +template +FAISS_ALWAYS_INLINE void pq4_kernel_qbs_neon( + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + ResultHandler& res, + const Scaler& scaler) { + // Avoid a zero-length array for NQ=0 instantiations. + constexpr int NQA = NQ > 0 ? NQ : 1; + const uint16x8_t zero = vdupq_n_u16(0); + // accu[q][b] holds distances for vectors 8*b..8*b+7. + uint16x8_t accu[NQA][4]; + + for (int q = 0; q < NQ; q++) { + for (int b = 0; b < 4; b++) { + accu[q][b] = zero; + } + } + + // Process two subquantizers per iteration. + for (int sq = 0; sq < nsq - scaler.nscale; sq += 2) { + const uint8x16_t code0 = vld1q_u8(codes); + const uint8x16_t code1 = vld1q_u8(codes + 16); + codes += 32; + + const uint8x16_t mask = vdupq_n_u8(0x0f); + const uint8x16_t code0_lo = vandq_u8(code0, mask); + const uint8x16_t code1_lo = vandq_u8(code1, mask); + const uint8x16_t code0_hi = vshrq_n_u8(code0, 4); + const uint8x16_t code1_hi = vshrq_n_u8(code1, 4); + + for (int q = 0; q < NQ; q++) { + // Load LUTs for two subquantizers. + const uint8x16_t lut0 = vld1q_u8(LUT); + const uint8x16_t lut1 = vld1q_u8(LUT + 16); + LUT += 32; + + const uint8x16_t d0_lo = vqtbl1q_u8(lut0, code0_lo); + const uint8x16_t d0_hi = vqtbl1q_u8(lut0, code0_hi); + const uint8x16_t d1_lo = vqtbl1q_u8(lut1, code1_lo); + const uint8x16_t d1_hi = vqtbl1q_u8(lut1, code1_hi); + + accu[q][0] = vaddq_u16( + accu[q][0], + vaddl_u8(vget_low_u8(d0_lo), vget_low_u8(d1_lo))); + accu[q][1] = vaddq_u16(accu[q][1], vaddl_high_u8(d0_lo, d1_lo)); + accu[q][2] = vaddq_u16( + accu[q][2], + vaddl_u8(vget_low_u8(d0_hi), vget_low_u8(d1_hi))); + accu[q][3] = vaddq_u16(accu[q][3], vaddl_high_u8(d0_hi, d1_hi)); + } + } + + // Scaled tail used by additive-quantizer FastScan indexes. + // (this is compiled out for DummyScaler) + for (int sq = 0; sq < scaler.nscale; sq += 2) { + const uint16_t scale = scaler.scale_one(uint16_t{1}); + const uint8x16_t code0 = vld1q_u8(codes); + const uint8x16_t code1 = vld1q_u8(codes + 16); + codes += 32; + + const uint8x16_t mask = vdupq_n_u8(0x0f); + const uint8x16_t code0_lo = vandq_u8(code0, mask); + const uint8x16_t code1_lo = vandq_u8(code1, mask); + const uint8x16_t code0_hi = vshrq_n_u8(code0, 4); + const uint8x16_t code1_hi = vshrq_n_u8(code1, 4); + + for (int q = 0; q < NQ; q++) { + // Load LUTs for two subquantizers. + const uint8x16_t lut0 = vld1q_u8(LUT); + const uint8x16_t lut1 = vld1q_u8(LUT + 16); + LUT += 32; + + const uint8x16_t d0_lo = vqtbl1q_u8(lut0, code0_lo); + const uint8x16_t d0_hi = vqtbl1q_u8(lut0, code0_hi); + const uint8x16_t d1_lo = vqtbl1q_u8(lut1, code1_lo); + const uint8x16_t d1_hi = vqtbl1q_u8(lut1, code1_hi); + + accu[q][0] = vaddq_u16( + accu[q][0], + vmulq_n_u16( + vaddl_u8(vget_low_u8(d0_lo), vget_low_u8(d1_lo)), + scale)); + accu[q][1] = vaddq_u16( + accu[q][1], + vmulq_n_u16(vaddl_high_u8(d0_lo, d1_lo), scale)); + accu[q][2] = vaddq_u16( + accu[q][2], + vmulq_n_u16( + vaddl_u8(vget_low_u8(d0_hi), vget_low_u8(d1_hi)), + scale)); + accu[q][3] = vaddq_u16( + accu[q][3], + vmulq_n_u16(vaddl_high_u8(d0_hi, d1_hi), scale)); + } + } + + // Reorder the four 8-lane accumulators for the result handler. + using simd16uint16 = simd16uint16_tpl; + for (int q = 0; q < NQ; q++) { + const uint16x8_t d0 = vuzp1q_u16(accu[q][0], accu[q][1]); + const uint16x8_t d1 = vuzp2q_u16(accu[q][0], accu[q][1]); + const uint16x8_t d2 = vuzp1q_u16(accu[q][2], accu[q][3]); + const uint16x8_t d3 = vuzp2q_u16(accu[q][2], accu[q][3]); + res.handle( + q, + 0, + simd16uint16(uint16x8x2_t{d0, d1}), + simd16uint16(uint16x8x2_t{d2, d3})); + } +} + +template <> +struct PQ4QBSKernel { + template + FAISS_ALWAYS_INLINE static void run( + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + ResultHandler& res, + const Scaler& scaler) { + pq4_kernel_qbs_neon(nsq, codes, LUT, res, scaler); + } +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd256.h b/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd256.h index 71142832e..66dbd4e46 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd256.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd256.h @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -9,8 +17,92 @@ #include +#include +#include + namespace faiss { +/* + * accumulate_hacc (see fast_scan.h) over one block of 32 codes. The low and + * high byte tables are looked up separately, and their sums are kept in + * 16-bit lanes over segments of 256 sub-quantizers, short enough for + * 255 * 256 < 2^16. Each segment is then added to the 32-bit accumulators as + * low + (high << 8). + */ +template +void kernel_accumulate_hacc_block( + int nsq, + const uint8_t* codes, + const uint8_t* lut_lo, + const uint8_t* lut_hi, + int32_t* accu) { + constexpr SIMDLevel SL256 = simd256_level_selector::value; + using simd16uint16 = simd16uint16_tpl; + using simd32uint8 = simd32uint8_tpl; + constexpr int kSegmentSq = 256; + const simd32uint8 mask(15); + std::fill(accu, accu + 32, 0); + for (int seg = 0; seg < nsq; seg += kSegmentSq) { + const int seg_end = std::min(nsq, seg + kSegmentSq); + // [low or high byte table][as in kernel_accumulate_block] + simd16uint16 acc[2][4]; + for (auto& a : acc) { + for (auto& r : a) { + r.clear(); + } + } + for (int sq = seg; sq < seg_end; sq += 2) { + const simd32uint8 c(codes + 16 * sq); + const simd32uint8 clo = c & mask; + const simd32uint8 chi = simd32uint8(simd16uint16(c) >> 4) & mask; + const uint8_t* luts[2] = {lut_lo + 16 * sq, lut_hi + 16 * sq}; + for (int t = 0; t < 2; t++) { + const simd32uint8 lut(luts[t]); + const simd32uint8 res0 = lut.lookup_2_lanes(clo); + const simd32uint8 res1 = lut.lookup_2_lanes(chi); + acc[t][0] += simd16uint16(res0); + acc[t][1] += simd16uint16(res0) >> 8; + acc[t][2] += simd16uint16(res1); + acc[t][3] += simd16uint16(res1) >> 8; + } + } + uint16_t sums[2][32]; // [table][element] + for (int t = 0; t < 2; t++) { + acc[t][0] -= acc[t][1] << 8; + combine2x2(acc[t][0], acc[t][1]).storeu(sums[t]); + acc[t][2] -= acc[t][3] << 8; + combine2x2(acc[t][2], acc[t][3]).storeu(sums[t] + 16); + } + for (int i = 0; i < 32; i++) { + accu[i] += sums[0][i] + (int32_t(sums[1][i]) << 8); + } + } +} + +/// accumulate_hacc with kernel_accumulate_hacc_block +template +void accumulate_hacc_simdlib( + int nq, + size_t ntotal2, + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + int32_t* accu) { + const size_t block_stride = 32 * size_t(nsq) / 2; + for (int q = 0; q < nq; q++) { + const uint8_t* lut_lo = LUT + size_t(q) * 2 * 16 * nsq; + const uint8_t* lut_hi = lut_lo + 16 * size_t(nsq); + for (size_t b = 0; b < ntotal2 / 32; b++) { + kernel_accumulate_hacc_block( + nsq, + codes + b * block_stride, + lut_lo, + lut_hi, + accu + q * ntotal2 + b * 32); + } + } +} + /* * Multi-BB variant: accumulates NQ queries x BB*32 database elements. * Used by the search_1 path (bbs > 32). @@ -210,4 +302,17 @@ void pq4_kernel_qbs_256( } } +template +struct PQ4QBSKernel { + template + FAISS_ALWAYS_INLINE static void run( + int nsq, + const uint8_t* codes, + const uint8_t* LUT, + ResultHandler& res, + const Scaler& scaler) { + pq4_kernel_qbs_256(nsq, codes, LUT, res, scaler); + } +}; + } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd512.h b/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd512.h index 22dde7080..70bfa8776 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd512.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/kernels_simd512.h @@ -9,15 +9,12 @@ #include #include +#include -#ifdef __AVX512F__ +#if FAISS_SIMD_TU(AVX512) namespace faiss { -// Explicit SIMD-level aliases for this file (no global bare aliases). -using simd32uint16 = simd32uint16_tpl; -using simd64uint8 = simd64uint8_tpl; - // NQ=1 specialization: processes 512-bit chunks aggressively. // a special version for NQ=1. // Despite the function being large in the text form, it compiles to a very @@ -476,4 +473,4 @@ void pq4_kernel_qbs_512( } // namespace faiss -#endif // __AVX512F__ +#endif // FAISS_SIMD_TU(AVX512) diff --git a/thirdparty/faiss/faiss/impl/fast_scan/rabitq_result_handler.h b/thirdparty/faiss/faiss/impl/fast_scan/rabitq_result_handler.h index 152590dc9..5709d531c 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/rabitq_result_handler.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/rabitq_result_handler.h @@ -95,7 +95,6 @@ struct IVFRaBitQHeapHandler : ResultHandlerCompare { return nup; } - private: float compute_full_multibit_distance( size_t local_q, size_t global_q, diff --git a/thirdparty/faiss/faiss/impl/fast_scan/simd_result_handlers.h b/thirdparty/faiss/faiss/impl/fast_scan/simd_result_handlers.h index 341004d69..c4aee8891 100644 --- a/thirdparty/faiss/faiss/impl/fast_scan/simd_result_handlers.h +++ b/thirdparty/faiss/faiss/impl/fast_scan/simd_result_handlers.h @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include #include @@ -112,8 +113,8 @@ struct SIMDResultHandlerToFloat { size_t scan_cnt = 0; // scanned vector number (except filtered) SIMDResultHandlerToFloat() = default; - SIMDResultHandlerToFloat(size_t nq, size_t ntotal) - : nq(nq), ntotal(ntotal) {} + SIMDResultHandlerToFloat(size_t nq_in, size_t ntotal_in) + : nq(nq_in), ntotal(ntotal_in) {} virtual void begin(const float* norms) { normalizers = norms; @@ -122,10 +123,7 @@ struct SIMDResultHandlerToFloat { // called at end of search to convert int16 distances to float, before // normalizers are deallocated - virtual void end() { - normalizers = nullptr; - scan_cnt = 0; - } + virtual void end(); // Get the number of scanned vectors size_t count_scanned_rows() { @@ -203,7 +201,8 @@ struct StoreResultHandler : SIMDResultHandler { size_t i0 = 0; size_t j0 = 0; - StoreResultHandler(uint16_t* data, size_t ld) : data(data), ld(ld) {} + StoreResultHandler(uint16_t* data_in, size_t ld_in) + : data(data_in), ld(ld_in) {} void handle(size_t q, size_t b, simd16uint16 d0, simd16uint16 d1) final { size_t ofs = (q + i0) * ld + j0 + b * 32; @@ -217,8 +216,17 @@ struct StoreResultHandler : SIMDResultHandler { } }; -/** stores results in fixed-size matrix. */ -template +/** stores results in fixed-size matrix. + * + * LinkageTag is unused by the handler. A tag type that only one TU uses gives + * the instantiation (and its out-of-line virtual handle()) a symbol name of + * its own, so a copy compiled with other SIMD flags cannot replace the copy + * of another TU. */ +template < + int NQ, + int BB, + SIMDLevel SL = SINGLE_SIMD_LEVEL_256, + class LinkageTag = void> struct FixedStorageHandler : SIMDResultHandler { using typename SIMDResultHandler::simd16uint16; @@ -230,7 +238,7 @@ struct FixedStorageHandler : SIMDResultHandler { dis[q + i0][2 * b + 1] = d1; } - void set_block_origin(size_t i0_in, size_t j0_in) final { + void set_block_origin(size_t i0_in, [[maybe_unused]] size_t j0_in) final { this->i0 = i0_in; assert(j0_in == 0); } @@ -258,8 +266,11 @@ struct ResultHandlerCompare : SIMDResultHandler { const IDSelector* sel; - ResultHandlerCompare(size_t nq, size_t ntotal, const IDSelector* sel_in) - : SIMDResultHandler(nq, ntotal), sel{sel_in} { + ResultHandlerCompare( + size_t nq_in, + size_t ntotal_in, + const IDSelector* sel_in) + : SIMDResultHandler(nq_in, ntotal_in), sel{sel_in} { this->is_CMax = C::is_max; this->sizeof_ids = sizeof(typename C::TI); this->with_fields = with_id_map; @@ -343,13 +354,16 @@ struct SingleResultHandler : ResultHandlerCompare { int64_t* ids; SingleResultHandler( - size_t nq, - size_t ntotal, - float* dis, - int64_t* ids, + size_t nq_in, + size_t ntotal_in, + float* dis_in, + int64_t* ids_in, const IDSelector* sel_in) - : RHC(nq, ntotal, sel_in), idis(nq), dis(dis), ids(ids) { - for (size_t i = 0; i < nq; i++) { + : RHC(nq_in, ntotal_in, sel_in), + idis(nq_in), + dis(dis_in), + ids(ids_in) { + for (size_t i = 0; i < nq_in; i++) { ids[i] = -1; idis[i] = C::neutral(); } @@ -374,7 +388,7 @@ struct SingleResultHandler : ResultHandlerCompare { if (this->sel != nullptr) { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); auto real_idx = this->adjust_id(b, j); lt_mask -= 1 << j; if (this->sel->is_member(real_idx)) { @@ -391,7 +405,7 @@ struct SingleResultHandler : ResultHandlerCompare { } else { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; this->scan_cnt++; T d = d32tab[j]; @@ -440,19 +454,19 @@ struct HeapHandler : ResultHandlerCompare { size_t nup = 0; // number of heap updates HeapHandler( - size_t nq, - size_t ntotal, - int64_t k, - float* dis, - int64_t* ids, + size_t nq_in, + size_t ntotal_in, + int64_t k_in, + float* dis_in, + int64_t* ids_in, const IDSelector* sel_in, - const float* normalizers = nullptr) - : RHC(nq, ntotal, sel_in), - idis(nq * k, threshold_idis(dis, normalizers)), - iids(nq * k, -1), - dis(dis), - ids(ids), - k(k) {} + const float* normalizers_in = nullptr) + : RHC(nq_in, ntotal_in, sel_in), + idis(nq_in * k_in, threshold_idis(dis_in, normalizers_in)), + iids(nq_in * k_in, -1), + dis(dis_in), + ids(ids_in), + k(k_in) {} static uint16_t threshold_idis(float* dis_in, const float* normalizers) { if (dis_in[0] == std::numeric_limits::max()) { @@ -498,7 +512,7 @@ struct HeapHandler : ResultHandlerCompare { if (this->sel != nullptr) { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); auto real_idx = this->adjust_id(b, j); lt_mask -= 1 << j; if (this->sel->is_member(real_idx)) { @@ -520,7 +534,7 @@ struct HeapHandler : ResultHandlerCompare { } else { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; this->scan_cnt++; T dis_for_j = d32tab[j]; @@ -554,7 +568,7 @@ struct HeapHandler : ResultHandlerCompare { one_a = a != 0 ? 1 / a : 0; b = normalizers[2 * q + 1]; } - for (int j = 0; j < k; j++) { + for (size_t j = 0; j < k; j++) { heap_dis[j] = heap_dis_in[j] * one_a + b; heap_ids[j] = heap_ids_in[j]; } @@ -592,24 +606,29 @@ struct ReservoirHandler : ResultHandlerCompare { std::vector all_ids; AlignedTable all_vals; - std::vector> reservoirs; + // Declared in this class, which takes the SIMD level, so that + // std::vector is a different type at each level. + struct Reservoir : ReservoirTopN { + using ReservoirTopN::ReservoirTopN; + }; + std::vector reservoirs; ReservoirHandler( - size_t nq, - size_t ntotal, + size_t nq_in, + size_t ntotal_in, size_t k, size_t cap, - float* dis, - int64_t* ids, + float* dis_in, + int64_t* ids_in, const IDSelector* sel_in) - : RHC(nq, ntotal, sel_in), + : RHC(nq_in, ntotal_in, sel_in), capacity((cap + 15) & ~15), - dis(dis), - ids(ids) { + dis(dis_in), + ids(ids_in) { assert(capacity % 16 == 0); - all_ids.resize(nq * capacity); - all_vals.resize(nq * capacity); - for (size_t q = 0; q < nq; q++) { + all_ids.resize(nq_in * capacity); + all_vals.resize(nq_in * capacity); + for (size_t q = 0; q < nq_in; q++) { reservoirs.emplace_back( k, capacity, @@ -637,7 +656,7 @@ struct ReservoirHandler : ResultHandlerCompare { if (this->sel != nullptr) { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); auto real_idx = this->adjust_id(b, j); lt_mask -= 1 << j; if (this->sel->is_member(real_idx)) { @@ -651,7 +670,7 @@ struct ReservoirHandler : ResultHandlerCompare { } else { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; T dis_for_j = d32tab[j]; this->scan_cnt++; @@ -736,18 +755,20 @@ struct RangeHandler : ResultHandlerCompare { std::vector triplets; RangeHandler( - RangeSearchResult& rres, - float radius, - size_t ntotal, + RangeSearchResult& rres_in, + float radius_in, + size_t ntotal_in, const IDSelector* sel_in) - : RHC(rres.nq, ntotal, sel_in), rres(rres), radius(radius) { + : RHC(rres_in.nq, ntotal_in, sel_in), + rres(rres_in), + radius(radius_in) { thresholds.resize(nq); n_per_query.resize(nq + 1); } void begin(const float* norms) override { normalizers = norms; - for (int q = 0; q < nq; ++q) { + for (size_t q = 0; q < nq; ++q) { thresholds[q] = int(normalizers[2 * q] * (radius - normalizers[2 * q + 1])); } @@ -771,7 +792,7 @@ struct RangeHandler : ResultHandlerCompare { if (this->sel != nullptr) { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; auto real_idx = this->adjust_id(b, j); @@ -786,7 +807,7 @@ struct RangeHandler : ResultHandlerCompare { } else { while (lt_mask) { // find first non-zero - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; T dis = d32tab[j]; n_per_query[q]++; @@ -809,7 +830,7 @@ struct RangeHandler : ResultHandlerCompare { memmove(rres.lims + 1, rres.lims, sizeof(*rres.lims) * rres.nq); rres.lims[0] = 0; - for (int q = 0; q < nq; q++) { + for (size_t q = 0; q < nq; q++) { float a = normalizers[2 * q]; float one_a = a != 0 ? 1 / a : 0; float b = normalizers[2 * q + 1]; @@ -837,20 +858,20 @@ struct PartialRangeHandler : RangeHandler { RangeSearchPartialResult& pres; PartialRangeHandler( - RangeSearchPartialResult& pres, - float radius, - size_t ntotal, - size_t q0, + RangeSearchPartialResult& pres_in, + float radius_in, + size_t ntotal_in, + size_t q0_in, size_t q1, const IDSelector* sel_in) : RangeHandler( - *pres.res, - radius, - ntotal, + *pres_in.res, + radius_in, + ntotal_in, sel_in), - pres(pres) { - nq = q1 - q0; - this->q0 = q0; + pres(pres_in) { + nq = q1 - q0_in; + this->q0 = q0_in; } // shift left n_per_query @@ -864,7 +885,7 @@ struct PartialRangeHandler : RangeHandler { // commit to partial result instead of full RangeResult void end() override { std::vector sorted_triplets(triplets.size()); - for (int q = 0; q < nq; q++) { + for (size_t q = 0; q < nq; q++) { n_per_query[q + 1] += n_per_query[q]; } shift_n_per_query(); @@ -876,7 +897,7 @@ struct PartialRangeHandler : RangeHandler { size_t* lims = n_per_query.data(); - for (int q = 0; q < nq; q++) { + for (size_t q = 0; q < nq; q++) { float a = normalizers[2 * q]; float one_a = a != 0 ? 1 / a : 0; float b = normalizers[2 * q + 1]; @@ -915,9 +936,9 @@ struct SingleQueryResultCollectHandler SingleQueryResultCollectHandler( std::vector>& res, - size_t ntotal, + size_t ntotal_in, const IDSelector* sel_in) - : RHC(1, ntotal, sel_in), collect(res) { + : RHC(1, ntotal_in, sel_in), collect(res) { this->q_map = &q_id; } @@ -944,7 +965,7 @@ struct SingleQueryResultCollectHandler if (this->sel != nullptr) { while (lt_mask) { - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); auto real_idx = this->adjust_id(b, j); lt_mask -= 1 << j; if (this->sel->is_member(real_idx)) { @@ -955,7 +976,7 @@ struct SingleQueryResultCollectHandler } } else { while (lt_mask) { - int j = __builtin_ctz(lt_mask); + int j = std::countr_zero(lt_mask); lt_mask -= 1 << j; T dis = d32tab[j]; int64_t idx = this->adjust_id(b, j); diff --git a/thirdparty/faiss/faiss/impl/hnsw/LockVector.h b/thirdparty/faiss/faiss/impl/hnsw/LockVector.h index d8fac1137..55bf37dfa 100644 --- a/thirdparty/faiss/faiss/impl/hnsw/LockVector.h +++ b/thirdparty/faiss/faiss/impl/hnsw/LockVector.h @@ -50,12 +50,11 @@ class LockVector { omp_unset_lock(&data_[i]); } - bool try_lock(size_t i) { + bool try_lock([[maybe_unused]] size_t i) { FAISS_CHECK_RANGE_DEBUG(i, 0, size_); return omp_test_lock(&data_[i]); } - private: omp_lock_t* data_ = nullptr; size_t size_ = 0; size_t capacity_ = 0; diff --git a/thirdparty/faiss/faiss/impl/hnsw/avx2.cpp b/thirdparty/faiss/faiss/impl/hnsw/avx2.cpp index d2619fe66..05647bb07 100644 --- a/thirdparty/faiss/faiss/impl/hnsw/avx2.cpp +++ b/thirdparty/faiss/faiss/impl/hnsw/avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #include #include @@ -146,5 +144,3 @@ int pop_min_tpl, SIMDLevel::AVX2>( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/hnsw/avx512.cpp b/thirdparty/faiss/faiss/impl/hnsw/avx512.cpp index b7e1d79e3..4ee8eec26 100644 --- a/thirdparty/faiss/faiss/impl/hnsw/avx512.cpp +++ b/thirdparty/faiss/faiss/impl/hnsw/avx512.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #include #include @@ -138,5 +136,3 @@ int pop_min_tpl, SIMDLevel::AVX512>( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/index_read.cpp b/thirdparty/faiss/faiss/impl/index_read.cpp index fd3a23e2c..dbbcaf257 100644 --- a/thirdparty/faiss/faiss/impl/index_read.cpp +++ b/thirdparty/faiss/faiss/impl/index_read.cpp @@ -10,6 +10,7 @@ #include +#include #include #include #include @@ -36,6 +37,9 @@ #include #include #include +#ifdef FAISS_ENABLE_DISK_IVF +#include +#endif #include #include #include @@ -53,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -379,8 +384,9 @@ std::unique_ptr read_VectorTransform_up(IOReader* f) { itqt->pca_then_itq = *pi; } vt = std::move(itqt); - } else if (h == fourcc("HRot")) { + } else if (h == fourcc("HRot") || h == fourcc("HR64")) { auto hr = std::make_unique(); + hr->pad_to_power_of_2 = h == fourcc("HRot"); READ1(hr->seed); vt = std::move(hr); } else { @@ -448,6 +454,27 @@ std::unique_ptr read_VectorTransform_up(IOReader* f) { "HadamardRotation d_out exceeds deserialization byte limit"); hr->init(hr->seed); } + if (h == fourcc("HR64")) { + auto* hr = dynamic_cast(vt.get()); + FAISS_THROW_IF_NOT_MSG(hr, "dynamic_cast to HadamardRotation failed"); + FAISS_THROW_IF_NOT_FMT( + vt->d_in > 0, + "invalid HadamardRotation d_in=%d (must be > 0)", + vt->d_in); + size_t p = (static_cast(vt->d_in) + 63) / 64 * 64; + FAISS_THROW_IF_NOT_FMT( + static_cast(vt->d_out) == p, + "invalid HadamardRotation d_out %d for d_in %d" + " (d_out must be the smallest multiple of 64 >= d_in)", + vt->d_out, + vt->d_in); + // Up to four sign-flip vectors of d_out floats. + FAISS_THROW_IF_NOT_MSG( + p <= get_deserialization_vector_byte_limit() / + (4 * sizeof(float)), + "HadamardRotation d_out exceeds deserialization byte limit"); + hr->init(hr->seed); + } if (h == fourcc("RmDT")) { auto* rdt = dynamic_cast(vt.get()); FAISS_THROW_IF_NOT_MSG( @@ -767,6 +794,10 @@ void read_ProductQuantizer(ProductQuantizer* pq, IOReader* f) { pq->d * pq->ksub); } +static void validate_codebooks_size( + const AdditiveQuantizer& aq, + size_t effective_d); + static void read_ResidualQuantizer_old(ResidualQuantizer& rq, IOReader* f) { READ1(rq.d); FAISS_THROW_IF_NOT_FMT( @@ -788,6 +819,7 @@ static void read_ResidualQuantizer_old(ResidualQuantizer& rq, IOReader* f) { READ1(rq.norm_min); READ1(rq.norm_max); rq.set_derived_values(); + validate_codebooks_size(rq, rq.d); } static void read_AdditiveQuantizer(AdditiveQuantizer& aq, IOReader* f) { @@ -849,6 +881,9 @@ static void read_AdditiveQuantizer(AdditiveQuantizer& aq, IOReader* f) { static void validate_codebooks_size( const AdditiveQuantizer& aq, size_t effective_d) { + if (!aq.is_trained && aq.codebooks.empty()) { + return; + } size_t required = mul_no_overflow( effective_d, aq.total_codebook_size, "codebooks validation"); FAISS_THROW_IF_NOT_FMT( @@ -1361,6 +1396,59 @@ static void read_NSG(NSG& nsg, IOReader* f) { FAISS_CHECK_RANGE(nsg.enterpoint, 0, N); } +static void read_PiPNN(PiPNN& pipnn, idx_t index_ntotal, IOReader* f) { + READ1(pipnn.R); + READ1(pipnn.leaf_k); + READ1(pipnn.hash_bits); + READ1(pipnn.reservoir_size); + READ1(pipnn.c_max); + READ1(pipnn.c_min); + READ1(pipnn.leader_cap); + // Former replicas field: build metadata that search does not need. + int replicas; + READ1(replicas); + READ1(pipnn.leader_fraction); + READ1(pipnn.alpha); + READVECTOR(pipnn.fanout); + READ1(pipnn.seed); + READ1_BOOL(pipnn.ip_partition_by_angle); + READ1(pipnn.search_L); + pipnn.check_params(); + READ1(pipnn.ntotal); + READ1(pipnn.entry_point); + // Checked before the graph is allocated; ntotal == 0 means unbuilt. + if (pipnn.ntotal != 0) { + FAISS_THROW_IF_NOT_FMT( + pipnn.ntotal == index_ntotal, + "PiPNN ntotal %" PRId64 " != index ntotal %" PRId64, + pipnn.ntotal, + index_ntotal); + FAISS_THROW_IF_NOT_FMT( + pipnn.ntotal <= INT32_MAX, + "built PiPNN ntotal %" PRId64 " exceeds INT32_MAX", + pipnn.ntotal); + FAISS_CHECK_RANGE(pipnn.entry_point, 0, pipnn.ntotal); + } + const size_t graph_size = mul_no_overflow( + (size_t)pipnn.ntotal, (size_t)pipnn.R, "PiPNN graph"); + // Views (IO_FLAG_MMAP_IFC, zero-copy) skip the scan: it would fault in + // the whole graph. Search bounds-checks every neighbour id instead. + if (!read_vector_base(pipnn.graph, f, graph_size, std::nullopt)) { + FAISS_THROW_IF_NOT( + graph_size < + get_deserialization_vector_byte_limit() / sizeof(int32_t)); + pipnn.graph.resize(graph_size); + READANDCHECK(pipnn.graph.data(), graph_size); + for (int32_t id : pipnn.graph) { + FAISS_CHECK_RANGE(id, -1, pipnn.ntotal); + } + } + read_vector(pipnn.next_copy, f); + FAISS_THROW_IF_NOT( + pipnn.next_copy.size() == 0 || + pipnn.next_copy.size() == size_t(pipnn.ntotal)); +} + static void read_NNDescent(NNDescent& nnd, IOReader* f) { READ1(nnd.ntotal); READ1(nnd.d); @@ -1442,6 +1530,11 @@ static void read_RaBitQuantizer( "RaBitQuantizer dimension mismatch: rabitq.d=%zu vs index d=%d", rabitq.d, expected_d); + + FAISS_THROW_IF_NOT_FMT( + rabitq.nb_bits >= 1 && rabitq.nb_bits <= 9, + "RaBitQuantizer nb_bits=%zu out of range [1, 9]", + rabitq.nb_bits); } static void read_EDENScalarQuantizer( @@ -1843,6 +1936,14 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { } else { read_ResidualQuantizer(idxr->rq, f, io_flags); } + FAISS_THROW_IF_NOT_MSG( + idxr->rq.is_trained == idxr->is_trained, + "IndexResidualQuantizer is_trained does not match " + "ResidualQuantizer is_trained"); + FAISS_THROW_IF_NOT_MSG( + idxr->ntotal == 0 || idxr->rq.is_trained, + "IndexResidualQuantizer with ntotal > 0 must have trained " + "ResidualQuantizer"); validate_aq_dimension_match( idxr->rq, idxr->d, "IndexResidualQuantizer"); READ1(idxr->code_size); @@ -2484,7 +2585,7 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { idxmap->own_fields = true; READVECTOR(idxmap->id_map); FAISS_THROW_IF_NOT_FMT( - idxmap->id_map.size() == idxmap->ntotal, + idxmap->id_map.size() == static_cast(idxmap->ntotal), "IndexIDMap id_map size (%" PRId64 ") does not match ntotal (%" PRId64 ")", int64_t(idxmap->id_map.size()), @@ -2762,6 +2863,37 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { idxnnd->d); } idx = std::move(idxnnd); + } else if (h == fourcc("IPNf") || h == fourcc("IPNs")) { + std::unique_ptr idxpipnn; + if (h == fourcc("IPNf")) { + idxpipnn = std::make_unique(); + } else { + idxpipnn = std::make_unique(); + } + read_index_header(*idxpipnn, f); + READ1_BOOL(idxpipnn->defer_build); + read_PiPNN(idxpipnn->pipnn, idxpipnn->ntotal, f); + idxpipnn->storage = read_index(f, io_flags); + idxpipnn->own_fields = true; + FAISS_THROW_IF_NOT_MSG( + idxpipnn->storage, "IndexPiPNN requires non-null storage"); + IndexPiPNN::check_storage_supported(*idxpipnn->storage); + FAISS_THROW_IF_NOT_FMT( + idxpipnn->storage->ntotal == idxpipnn->ntotal, + "PiPNN storage ntotal %" PRId64 " != index ntotal %" PRId64, + idxpipnn->storage->ntotal, + idxpipnn->ntotal); + FAISS_THROW_IF_NOT_FMT( + idxpipnn->storage->d == idxpipnn->d, + "PiPNN storage d %d != index d %d", + idxpipnn->storage->d, + idxpipnn->d); + FAISS_THROW_IF_NOT_FMT( + idxpipnn->storage->metric_type == idxpipnn->metric_type, + "PiPNN storage metric %d != index metric %d", + (int)idxpipnn->storage->metric_type, + (int)idxpipnn->metric_type); + idx = std::move(idxpipnn); } else if (h == fourcc("ISfs")) { auto idxsqfs = std::make_unique(); read_index_header(*idxsqfs, f); @@ -2773,6 +2905,8 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { READ1(idxsqfs->ntotal2); READ1(idxsqfs->M2); READVECTOR(idxsqfs->codes); + READ1(idxsqfs->rerank_factor); + READVECTOR(idxsqfs->lo_codes); // Restore FastScan base-class fields from the SQ idxsqfs->M = idxsqfs->sq.d; @@ -2836,18 +2970,18 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { bool has_orig; READ1(has_orig); if (has_orig) { - ivfsqfs->orig_codes_invlists = read_InvertedLists(f, io_flags); - // Rebuild direct_map from orig_codes_invlists for reranking + ivfsqfs->lo_codes_invlists = read_InvertedLists(f, io_flags); + // Rebuild direct_map from lo_codes_invlists for reranking ivfsqfs->direct_map.set_type( DirectMap::Hashtable, ivfsqfs->invlists, 0); for (size_t list_no = 0; list_no < ivfsqfs->nlist; list_no++) { size_t list_size = - ivfsqfs->orig_codes_invlists->list_size(list_no); + ivfsqfs->lo_codes_invlists->list_size(list_no); if (list_size == 0) { continue; } InvertedLists::ScopedIds ids( - ivfsqfs->orig_codes_invlists, list_no); + ivfsqfs->lo_codes_invlists, list_no); for (size_t j = 0; j < list_size; j++) { ivfsqfs->direct_map.add_single_id(ids[j], list_no, j); } @@ -3006,8 +3140,25 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { auto idxq = std::make_unique(); read_index_header(*idxq, f); read_RaBitQuantizer(idxq->rabitq, f, idxq->d, false); + // Update rabitq to match nb_bits + idxq->rabitq.code_size = + idxq->rabitq.compute_code_size(idxq->d, idxq->rabitq.nb_bits); read_vector(idxq->codes, f); READVECTOR(idxq->center); + const size_t expected_codes_size = mul_no_overflow( + static_cast(idxq->ntotal), + idxq->rabitq.code_size, + "IndexRaBitQ codes"); + FAISS_THROW_IF_NOT_FMT( + idxq->codes.size() == expected_codes_size, + "IndexRaBitQ codes size mismatch: got %zu, expected %zu", + idxq->codes.size(), + expected_codes_size); + FAISS_THROW_IF_NOT_FMT( + idxq->center.size() == static_cast(idxq->d), + "IndexRaBitQ center size mismatch: got %zu, expected %d", + idxq->center.size(), + idxq->d); READ1(idxq->qb); // qb=0: Not quantized - direct distance computation on given float32s. // qb>0 && qb<=8: Scalar-quantized with qb bits of precision. @@ -3025,8 +3176,25 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { read_index_header(*idxq, f); read_RaBitQuantizer( idxq->rabitq, f, idxq->d, true); // Reads nb_bits from file + // Update rabitq to match nb_bits + idxq->rabitq.code_size = + idxq->rabitq.compute_code_size(idxq->d, idxq->rabitq.nb_bits); read_vector(idxq->codes, f); READVECTOR(idxq->center); + const size_t expected_codes_size = mul_no_overflow( + static_cast(idxq->ntotal), + idxq->rabitq.code_size, + "IndexRaBitQ codes"); + FAISS_THROW_IF_NOT_FMT( + idxq->codes.size() == expected_codes_size, + "IndexRaBitQ codes size mismatch: got %zu, expected %zu", + idxq->codes.size(), + expected_codes_size); + FAISS_THROW_IF_NOT_FMT( + idxq->center.size() == static_cast(idxq->d), + "IndexRaBitQ center size mismatch: got %zu, expected %d", + idxq->center.size(), + idxq->d); READ1(idxq->qb); // qb=0: Not quantized - direct distance computation on given float32s. // qb>0 && qb<=8: Scalar-quantized with qb bits of precision. @@ -3081,6 +3249,72 @@ std::unique_ptr read_index_up(IOReader* f, int io_flags) { read_InvertedLists(*ivrq, f, io_flags); idx = std::move(ivrq); } +#ifdef FAISS_ENABLE_DISK_IVF + else if (h == fourcc("IwDr")) { + auto ivdr = std::make_unique(); + read_ivf_header(ivdr.get(), f); + read_RaBitQuantizer(ivdr->rabitq, f, ivdr->d, true); + FAISS_THROW_IF_NOT_MSG( + ivdr->rabitq.metric_type == ivdr->metric_type, + "IndexIVFRaBitQSSD: metric mismatch"); + FAISS_THROW_IF_NOT_MSG( + ivdr->metric_type == METRIC_L2 || + ivdr->metric_type == METRIC_INNER_PRODUCT, + "IndexIVFRaBitQSSD: unsupported metric"); + FAISS_THROW_IF_NOT_FMT( + ivdr->rabitq.nb_bits >= 2 && ivdr->rabitq.nb_bits <= 9, + "invalid IndexIVFRaBitQSSD nb_bits=%zu", + ivdr->rabitq.nb_bits); + ivdr->rabitq.code_size = + ivdr->rabitq.compute_code_size(ivdr->d, ivdr->rabitq.nb_bits); + ivdr->code_size = ivdr->rabitq.code_size; + READ1(ivdr->mem_dim); + FAISS_THROW_IF_NOT_MSG( + ivdr->d > 0 && ivdr->d % 64 == 0, + "IndexIVFRaBitQSSD: d must be a positive multiple of 64"); + FAISS_THROW_IF_NOT_MSG( + ivdr->mem_dim >= 64 && ivdr->mem_dim <= size_t(ivdr->d) && + ivdr->mem_dim % 64 == 0, + "IndexIVFRaBitQSSD: mem_dim must be a multiple of 64 in [64, d]"); + READ1_BOOL(ivdr->use_hacc); + READ1(ivdr->drain_alpha); + READ1(ivdr->qd_per_thread); + FAISS_THROW_IF_NOT_FMT( + ivdr->drain_alpha >= 0 && ivdr->drain_alpha <= 1, + "invalid IndexIVFRaBitQSSD drain_alpha=%g", + ivdr->drain_alpha); + FAISS_THROW_IF_NOT_FMT( + ivdr->qd_per_thread >= 1 && + ivdr->qd_per_thread <= + IndexIVFRaBitQSSD::kMaxReadsInFlight, + "invalid IndexIVFRaBitQSSD qd_per_thread=%zu", + ivdr->qd_per_thread); + READVECTOR(ivdr->centroid_norms); + FAISS_THROW_IF_NOT( + ivdr->centroid_norms.empty() || + ivdr->centroid_norms.size() == ivdr->nlist); + READVECTOR(ivdr->centroid_scales); + FAISS_THROW_IF_NOT( + ivdr->centroid_scales.empty() || + ivdr->centroid_scales.size() == ivdr->nlist); + read_InvertedLists(*ivdr, f, io_flags); + if (ivdr->invlists) { + // checks the type and the layout of the inverted lists + ivdr->get_ssd_invlists(); + // the search accepts empty centroid_norms when ntotal is 0. ntotal + // can exceed the list sizes: add() counts the vectors it skips + // (coarse list -1). + FAISS_THROW_IF_NOT_MSG( + size_t(ivdr->ntotal) >= ivdr->invlists->compute_ntotal(), + "IndexIVFRaBitQSSD: the inverted lists hold more than ntotal vectors"); + } else { + FAISS_THROW_IF_NOT_MSG( + ivdr->ntotal == 0, + "IndexIVFRaBitQSSD: non-empty index needs inverted lists"); + } + idx = std::move(ivdr); + } +#endif // FAISS_ENABLE_DISK_IVF #ifdef FAISS_ENABLE_SVS else if ( h == fourcc("ILVQ") || h == fourcc("ISVL") || h == fourcc("ISVD") || @@ -3379,7 +3613,8 @@ static void read_InvertedLists(IndexBinaryIVF& ivf, IOReader* f, int io_flags) { auto ils = read_InvertedLists_up(f, io_flags); FAISS_THROW_IF_NOT( !ils || - (ils->nlist == ivf.nlist && ils->code_size == ivf.code_size)); + (ils->nlist == ivf.nlist && + ils->code_size == static_cast(ivf.code_size))); ivf.invlists = ils.release(); ivf.own_invlists = true; } @@ -3490,6 +3725,10 @@ static void read_binary_multi_hash_map( int id_bits; size_t sz; READ1(id_bits); + FAISS_THROW_IF_NOT_FMT( + id_bits >= 0 && id_bits <= 64, + "multi hash map: invalid id_bits=%d (must be in [0, 64])", + id_bits); READ1(sz); FAISS_CHECK_DESERIALIZATION_LOOP_LIMIT(sz, "multi hash map sz"); std::vector buf; @@ -3611,7 +3850,7 @@ std::unique_ptr read_index_binary_up(IOReader* f, int io_flags) { idxmap->own_fields = true; READVECTOR(idxmap->id_map); FAISS_THROW_IF_NOT_FMT( - idxmap->id_map.size() == idxmap->ntotal, + idxmap->id_map.size() == static_cast(idxmap->ntotal), "IndexBinaryIDMap id_map size (%" PRId64 ") does not match ntotal (%" PRId64 ")", int64_t(idxmap->id_map.size()), @@ -3635,7 +3874,8 @@ std::unique_ptr read_index_binary_up(IOReader* f, int io_flags) { "invalid IndexBinaryHash b=%d (must be > 0)", idxh->b); FAISS_THROW_IF_NOT_FMT( - static_cast(idxh->b) <= idxh->code_size * 8, + static_cast(idxh->b) <= + static_cast(idxh->code_size) * 8, "IndexBinaryHash b=%d exceeds code_size=%d bits", idxh->b, idxh->code_size); diff --git a/thirdparty/faiss/faiss/impl/index_write.cpp b/thirdparty/faiss/faiss/impl/index_write.cpp index 0ffe46185..c468a48b5 100644 --- a/thirdparty/faiss/faiss/impl/index_write.cpp +++ b/thirdparty/faiss/faiss/impl/index_write.cpp @@ -31,6 +31,9 @@ #include #include #include +#ifdef FAISS_ENABLE_DISK_IVF +#include +#endif #include #include #include @@ -48,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -115,7 +119,8 @@ static void write_index_header(const Index* idx, IOWriter* f) { void write_VectorTransform(const VectorTransform* vt, IOWriter* f) { if (const HadamardRotation* hr = dynamic_cast(vt)) { - uint32_t h = fourcc("HRot"); + // HR64: d_out padded to a multiple of 64 rather than a power of 2. + uint32_t h = fourcc(hr->pad_to_power_of_2 ? "HRot" : "HR64"); WRITE1(h); WRITE1(hr->seed); } else if ( @@ -423,6 +428,29 @@ static void write_NNDescent(const NNDescent* nnd, IOWriter* f) { WRITEVECTOR(nnd->final_graph); } +static void write_PiPNN(const PiPNN& pipnn, IOWriter* f) { + WRITE1(pipnn.R); + WRITE1(pipnn.leaf_k); + WRITE1(pipnn.hash_bits); + WRITE1(pipnn.reservoir_size); + WRITE1(pipnn.c_max); + WRITE1(pipnn.c_min); + WRITE1(pipnn.leader_cap); + // Former replicas field, kept so that the format does not change. + const int replicas = 1; + WRITE1(replicas); + WRITE1(pipnn.leader_fraction); + WRITE1(pipnn.alpha); + WRITEVECTOR(pipnn.fanout); + WRITE1(pipnn.seed); + WRITE1(pipnn.ip_partition_by_angle); + WRITE1(pipnn.search_L); + WRITE1(pipnn.ntotal); + WRITE1(pipnn.entry_point); + WRITEANDCHECK(pipnn.graph.data(), pipnn.graph.size()); + WRITEVECTOR(pipnn.next_copy); +} + // Write RaBitQuantizer for 1-bit format (backward compatible) static void write_RaBitQuantizer( const RaBitQuantizer* rabitq, @@ -940,6 +968,40 @@ void write_index(const Index* idx, IOWriter* f, int io_flags) { WRITE1(idxnsg->nndescent_iter); write_NSG(&idxnsg->nsg, f); write_index(idxnsg->storage, f); + } else if ( + const IndexPiPNN* idxpipnn = dynamic_cast(idx)) { + FAISS_THROW_IF_NOT_FMT( + typeid(*idx) == typeid(IndexPiPNN) || + typeid(*idx) == typeid(IndexPiPNNFlat) || + typeid(*idx) == typeid(IndexPiPNNSQ), + "don't know how to serialize this IndexPiPNN subtype: %s", + typeid(*idx).name()); + const Index* storage = idxpipnn->storage; + const PiPNN& state = idxpipnn->pipnn; + // The reader rejects these states, so they are not written either. + FAISS_THROW_IF_NOT_MSG( + storage, "cannot serialize an IndexPiPNN without storage"); + IndexPiPNN::check_storage_supported(*storage); + state.check_params(); + FAISS_THROW_IF_NOT_MSG( + storage->ntotal == idxpipnn->ntotal && + storage->d == idxpipnn->d && + storage->metric_type == idxpipnn->metric_type, + "cannot serialize IndexPiPNN: the storage is inconsistent " + "with the index (was the storage modified directly?)"); + FAISS_THROW_IF_NOT_MSG( + state.graph.size() == size_t(state.ntotal) * size_t(state.R), + "cannot serialize IndexPiPNN: graph size != ntotal * R"); + // The subclasses differ only by their constructors: the fourcc names + // the storage. + const uint32_t h = dynamic_cast(storage) + ? fourcc("IPNs") + : fourcc("IPNf"); + WRITE1(h); + write_index_header(idxpipnn, f); + WRITE1(idxpipnn->defer_build); + write_PiPNN(state, f); + write_index(storage, f); } else if ( const IndexNNDescent* idxnnd = dynamic_cast(idx)) { @@ -966,6 +1028,8 @@ void write_index(const Index* idx, IOWriter* f, int io_flags) { WRITE1(idxsqfs->ntotal2); WRITE1(idxsqfs->M2); WRITEVECTOR(idxsqfs->codes); + WRITE1(idxsqfs->rerank_factor); + WRITEVECTOR(idxsqfs->lo_codes); } else if ( const IndexPQFastScan* idxpqfs = dynamic_cast(idx)) { @@ -993,11 +1057,11 @@ void write_index(const Index* idx, IOWriter* f, int io_flags) { WRITE1(ivfsqfs->rerank_factor); write_ScalarQuantizer(&ivfsqfs->sq, f); write_InvertedLists(ivfsqfs->invlists, f); - // Write orig_codes_invlists if present - bool has_orig = (ivfsqfs->orig_codes_invlists != nullptr); + // Write lo_codes_invlists if present + bool has_orig = (ivfsqfs->lo_codes_invlists != nullptr); WRITE1(has_orig); if (has_orig) { - write_InvertedLists(ivfsqfs->orig_codes_invlists, f); + write_InvertedLists(ivfsqfs->lo_codes_invlists, f); } } else if ( const IndexIVFPQFastScan* ivpq_2 = @@ -1107,6 +1171,23 @@ void write_index(const Index* idx, IOWriter* f, int io_flags) { WRITE1(ivrq->qb); write_InvertedLists(ivrq->invlists, f); } +#ifdef FAISS_ENABLE_DISK_IVF + else if ( + const IndexIVFRaBitQSSD* ivdr = + dynamic_cast(idx)) { + uint32_t h = fourcc("IwDr"); + WRITE1(h); + write_ivf_header(ivdr, f); + write_RaBitQuantizer(&ivdr->rabitq, f, true); + WRITE1(ivdr->mem_dim); + WRITE1(ivdr->use_hacc); + WRITE1(ivdr->drain_alpha); + WRITE1(ivdr->qd_per_thread); + WRITEVECTOR(ivdr->centroid_norms); + WRITEVECTOR(ivdr->centroid_scales); + write_InvertedLists(ivdr->invlists, f); + } +#endif // FAISS_ENABLE_DISK_IVF #ifdef FAISS_ENABLE_SVS else if ( const IndexSVSVamana* svs = @@ -1168,19 +1249,20 @@ void write_index(const Index* idx, IOWriter* f, int io_flags) { WRITEVECTOR(svs->stored_vectors); } } else if ( - const IndexSVSFlat* svs = dynamic_cast(idx)) { + const IndexSVSFlat* svs_flat = + dynamic_cast(idx)) { uint32_t h = fourcc("ISVF"); WRITE1(h); write_index_header(idx, f); - bool initialized = (svs->impl != nullptr); + bool initialized = (svs_flat->impl != nullptr); WRITE1(initialized); if (initialized) { // Wrap SVS I/O and stream to IOWriter faiss::BufferedIOWriter bwr(f); faiss::svs_io::WriterStreambuf wbuf(&bwr); std::ostream os(&wbuf); - svs->serialize_impl(os); + svs_flat->serialize_impl(os); os.flush(); } } else if ( @@ -1338,8 +1420,10 @@ static void write_binary_multi_hash_map( int b, size_t ntotal, IOWriter* f) { + // id_bits is also used to store the bucket sizes, which can be equal + // to ntotal, so it must be able to represent ntotal itself. int id_bits = 0; - while ((ntotal > (size_t(1) << id_bits))) { + while (ntotal >= (size_t(1) << id_bits)) { id_bits++; } WRITE1(id_bits); diff --git a/thirdparty/faiss/faiss/impl/io.cpp b/thirdparty/faiss/faiss/impl/io.cpp index cf0018351..3b632dee7 100644 --- a/thirdparty/faiss/faiss/impl/io.cpp +++ b/thirdparty/faiss/faiss/impl/io.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include diff --git a/thirdparty/faiss/faiss/impl/io_macros.h b/thirdparty/faiss/faiss/impl/io_macros.h index c8ed20471..3910fb193 100644 --- a/thirdparty/faiss/faiss/impl/io_macros.h +++ b/thirdparty/faiss/faiss/impl/io_macros.h @@ -7,6 +7,8 @@ #pragma once +#include + #include /************************************************************* @@ -73,7 +75,6 @@ size_t get_deserialization_vector_byte_limit(); size_t size; \ READANDCHECK(&size, 1); \ FAISS_THROW_IF_NOT( \ - size >= 0 && \ size < (faiss::get_deserialization_vector_byte_limit() / \ sizeof(*(vec).data()))); \ FAISS_THROW_IF_NOT_FMT( \ @@ -122,7 +123,6 @@ size_t get_deserialization_vector_byte_limit(); size_t size; \ READANDCHECK(&size, 1); \ FAISS_THROW_IF_NOT( \ - size >= 0 && \ size < (faiss::get_deserialization_vector_byte_limit() / \ (4 * sizeof(*(vec).data())))); \ size *= 4; \ diff --git a/thirdparty/faiss/faiss/impl/mapped_io.cpp b/thirdparty/faiss/faiss/impl/mapped_io.cpp index 2582e6f57..e0ecafb2f 100644 --- a/thirdparty/faiss/faiss/impl/mapped_io.cpp +++ b/thirdparty/faiss/faiss/impl/mapped_io.cpp @@ -20,6 +20,7 @@ #endif +#include #include #include diff --git a/thirdparty/faiss/faiss/impl/nndescent/gram-avx2.cpp b/thirdparty/faiss/faiss/impl/nndescent/gram-avx2.cpp new file mode 100644 index 000000000..dcfeadffe --- /dev/null +++ b/thirdparty/faiss/faiss/impl/nndescent/gram-avx2.cpp @@ -0,0 +1,121 @@ +/* + * 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. + */ + +#include + +#include +#include + +#include + +namespace faiss { +namespace nndescent { + +using VF = simd8float32_tpl; +constexpr size_t W = sizeof(VF) / sizeof(float); +// tiles of RI x RJ entries: 12 accumulators and 4 operands fill the 16 +// registers +constexpr int RI = 3, RJ = 4; + +/** One tile, a block of I x J Gram matrix entries that the kernel computes + * together: out[i * ldo + j] = for i < I, j < J. Each vector + * that the kernel loads serves J or I products. Each product has its own + * accumulator, and the tail uses std::fma whatever the compiler contracts, so + * a product depends only on its two rows. */ +template +static void tile( + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + VF acc[I][J]; + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + acc[i][j] = VF(0.0f); + } + } + size_t k = 0; + for (; k + W <= d; k += W) { + VF x[I]; + for (int i = 0; i < I; i++) { + x[i] = VF(a[i] + k); + } + for (int j = 0; j < J; j++) { + const VF y(b[j] + k); + for (int i = 0; i < I; i++) { + acc[i][j] = fmadd(x[i], y, acc[i][j]); + } + } + } + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + float v = horizontal_add(acc[i][j]); + for (size_t t = k; t < d; t++) { + v = std::fma(a[i][t], b[j][t], v); + } + out[i * ldo + j] = v; + } + } +} + +/// a tile of I x nj entries, nj <= J +template +static void run_tile_cols( + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (J > 1) { + if (nj < J) { + run_tile_cols(nj, a, b, d, out, ldo); + return; + } + } + tile(a, b, d, out, ldo); +} + +/// a tile of ni x nj entries, ni <= I, nj <= RJ +template +static void run_tile( + int ni, + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (I > 1) { + if (ni < I) { + run_tile(ni, nj, a, b, d, out, ldo); + return; + } + } + run_tile_cols(nj, a, b, d, out, ldo); +} + +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out) { + // rows i0 .. i0 + RI - 1 against the rows j > i0, tile by tile + for (size_t i0 = 0; i0 < r; i0 += RI) { + const int ni = int(std::min(RI, r - i0)); + for (size_t j = i0 + 1; j < m; j += RJ) { + const int nj = int(std::min(RJ, m - j)); + run_tile(ni, nj, rows + i0, rows + j, d, out + i0 * m + j, m); + } + } +} + +} // namespace nndescent +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/nndescent/gram-avx512.cpp b/thirdparty/faiss/faiss/impl/nndescent/gram-avx512.cpp new file mode 100644 index 000000000..9039acdbe --- /dev/null +++ b/thirdparty/faiss/faiss/impl/nndescent/gram-avx512.cpp @@ -0,0 +1,124 @@ +/* + * 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. + */ + +#include + +#include + +#include + +namespace faiss { +namespace nndescent { + +namespace { + +// tiles of 4 x 6 entries: 24 accumulators and 5 operands of the 32 registers +constexpr int RI = 4, RJ = 6; + +/// out[i * ldo + j] = for i < I, j < J; the tail is a masked +/// load, so there is no scalar loop +template +void tile( + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + __m512 acc[I][J]; + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + acc[i][j] = _mm512_setzero_ps(); + } + } + size_t k = 0; + for (; k + 16 <= d; k += 16) { + __m512 x[I]; + for (int i = 0; i < I; i++) { + x[i] = _mm512_loadu_ps(a[i] + k); + } + for (int j = 0; j < J; j++) { + const __m512 y = _mm512_loadu_ps(b[j] + k); + for (int i = 0; i < I; i++) { + acc[i][j] = _mm512_fmadd_ps(x[i], y, acc[i][j]); + } + } + } + if (k < d) { + const __mmask16 mask = __mmask16((1u << (d - k)) - 1); + __m512 x[I]; + for (int i = 0; i < I; i++) { + x[i] = _mm512_maskz_loadu_ps(mask, a[i] + k); + } + for (int j = 0; j < J; j++) { + const __m512 y = _mm512_maskz_loadu_ps(mask, b[j] + k); + for (int i = 0; i < I; i++) { + acc[i][j] = _mm512_fmadd_ps(x[i], y, acc[i][j]); + } + } + } + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + out[i * ldo + j] = _mm512_reduce_add_ps(acc[i][j]); + } + } +} + +template +void run_tile_cols( + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (J > 1) { + if (nj < J) { + run_tile_cols(nj, a, b, d, out, ldo); + return; + } + } + tile(a, b, d, out, ldo); +} + +template +void run_tile( + int ni, + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (I > 1) { + if (ni < I) { + run_tile(ni, nj, a, b, d, out, ldo); + return; + } + } + run_tile_cols(nj, a, b, d, out, ldo); +} + +} // namespace + +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out) { + for (size_t i0 = 0; i0 < r; i0 += RI) { + const int ni = int(std::min(RI, r - i0)); + for (size_t j = i0 + 1; j < m; j += RJ) { + const int nj = int(std::min(RJ, m - j)); + run_tile(ni, nj, rows + i0, rows + j, d, out + i0 * m + j, m); + } + } +} + +} // namespace nndescent +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/nndescent/gram-neon.cpp b/thirdparty/faiss/faiss/impl/nndescent/gram-neon.cpp new file mode 100644 index 000000000..640ab1329 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/nndescent/gram-neon.cpp @@ -0,0 +1,114 @@ +/* + * 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. + */ + +#include + +#include + +#include +#include + +namespace faiss { +namespace nndescent { + +namespace { + +// tiles of 4 x 6 entries: 24 accumulators and 5 operands of the 32 registers +constexpr int RI = 4, RJ = 6; + +template +void tile( + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + float32x4_t acc[I][J]; + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + acc[i][j] = vdupq_n_f32(0.0f); + } + } + size_t k = 0; + for (; k + 4 <= d; k += 4) { + float32x4_t x[I]; + for (int i = 0; i < I; i++) { + x[i] = vld1q_f32(a[i] + k); + } + for (int j = 0; j < J; j++) { + const float32x4_t y = vld1q_f32(b[j] + k); + for (int i = 0; i < I; i++) { + acc[i][j] = vfmaq_f32(acc[i][j], x[i], y); + } + } + } + for (int i = 0; i < I; i++) { + for (int j = 0; j < J; j++) { + float v = vaddvq_f32(acc[i][j]); + for (size_t t = k; t < d; t++) { + v = std::fma(a[i][t], b[j][t], v); + } + out[i * ldo + j] = v; + } + } +} + +template +void run_tile_cols( + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (J > 1) { + if (nj < J) { + run_tile_cols(nj, a, b, d, out, ldo); + return; + } + } + tile(a, b, d, out, ldo); +} + +template +void run_tile( + int ni, + int nj, + const float* const* a, + const float* const* b, + size_t d, + float* out, + size_t ldo) { + if constexpr (I > 1) { + if (ni < I) { + run_tile(ni, nj, a, b, d, out, ldo); + return; + } + } + run_tile_cols(nj, a, b, d, out, ldo); +} + +} // namespace + +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out) { + for (size_t i0 = 0; i0 < r; i0 += RI) { + const int ni = int(std::min(RI, r - i0)); + for (size_t j = i0 + 1; j < m; j += RJ) { + const int nj = int(std::min(RJ, m - j)); + run_tile(ni, nj, rows + i0, rows + j, d, out + i0 * m + j, m); + } + } +} + +} // namespace nndescent +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/nndescent/gram.h b/thirdparty/faiss/faiss/impl/nndescent/gram.h new file mode 100644 index 000000000..1836b4bd8 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/nndescent/gram.h @@ -0,0 +1,66 @@ +/* + * 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. + */ + +#pragma once + +#include + +#include + +namespace faiss { +namespace nndescent { + +/** Rows [0, r) of the upper triangle of the Gram matrix of the m vectors + * rows[0 .. m): out[i * m + j] = for i < r and + * i < j < m. The Gram matrix of m vectors is the m x m matrix of their inner + * products. In a local join of DeterministicNNDescent, the first r vectors + * are the new members, so these are the pairs with at least one new member. + * The vectors are read in place. The kernel also sets some entries with + * j <= i. The sums have a fixed order, so the values do not depend on the + * thread. Defined for AVX2, AVX512 and ARM_NEON. The dispatch uses AVX512 on + * the higher AVX-512 levels and ARM_NEON on ARM_SVE, and the caller uses BLAS + * for the other levels. */ +template +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out); + +#ifdef COMPILE_SIMD_AVX2 +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out); +#endif + +#ifdef COMPILE_SIMD_AVX512 +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out); +#endif + +#ifdef COMPILE_SIMD_ARM_NEON +template <> +void gram_upper_rows( + const float* const* rows, + size_t r, + size_t m, + size_t d, + float* out); +#endif + +} // namespace nndescent +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/HashPrune.cpp b/thirdparty/faiss/faiss/impl/pipnn/HashPrune.cpp new file mode 100644 index 000000000..123918a49 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/HashPrune.cpp @@ -0,0 +1,159 @@ +/* + * 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. + */ + +#include + +#include + +#include +#include +#include +#include + +namespace faiss { +namespace pipnn { + +uint16_t distance_key(float v) { + // Normalized on the bit pattern, so -ffast-math cannot remove the checks. + uint32_t u; + std::memcpy(&u, &v, sizeof(u)); + if ((u & 0x7fffffffu) == 0) { + u = 0; // -0 -> +0 + } else if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu) != 0) { + u = 0x7f800000u; // NaN -> +inf + } + std::memcpy(&v, &u, sizeof(v)); + // Scalar `encode_bf16` only: the SIMD path rounds differently, so keys + // would depend on the CPU. + const uint16_t b = encode_bf16(v); + return (b & 0x8000) ? static_cast(~b) + : static_cast(b | 0x8000); +} + +bool ReservoirRef::offer(int32_t id, uint16_t hash, uint16_t key) { + const int n = *count; + // A full reservoir rejects anything not below its maximum (rules 1 and 3). + if (n == capacity && *farthest != kNoFarthest) { + const Slot& f = slots[*farthest]; + if (!slot_less(key, id, f.key, f.id)) { + return false; + } + } + + int lo = 0; + int hi = n; + while (lo < hi) { + const int mid = (lo + hi) / 2; + if (slots[mid].hash < hash) { + lo = mid + 1; + } else { + hi = mid; + } + } + + // Rule 1: bucket hit. The cached farthest stays valid only when a + // non-farthest slot is lowered. + if (lo < n && slots[lo].hash == hash) { + Slot& s = slots[lo]; + if (!slot_less(key, id, s.key, s.id)) { + return false; + } + s.id = id; + s.key = key; + if (*farthest == lo) { + *farthest = kNoFarthest; + } + return true; + } + + // Rule 2: miss with room. + if (n < capacity) { + std::memmove( + slots + lo + 1, + slots + lo, + sizeof(Slot) * static_cast(n - lo)); + slots[lo] = Slot{id, hash, key}; + *count = static_cast(n + 1); + *farthest = kNoFarthest; + return true; + } + + // Rule 3: miss, full. Compare against the slot_less-maximum. + int z = *farthest; + if (z == kNoFarthest) { + z = 0; + for (int i = 1; i < n; i++) { + if (slot_less( + slots[z].key, slots[z].id, slots[i].key, slots[i].id)) { + z = i; + } + } + *farthest = static_cast(z); + } + const Slot& zs = slots[z]; + if (!slot_less(key, id, zs.key, zs.id)) { + return false; + } + if (z < lo) { + std::memmove( + slots + z, + slots + z + 1, + sizeof(Slot) * static_cast(lo - 1 - z)); + slots[lo - 1] = Slot{id, hash, key}; + } else { + std::memmove( + slots + lo + 1, + slots + lo, + sizeof(Slot) * static_cast(z - lo)); + slots[lo] = Slot{id, hash, key}; + } + *farthest = kNoFarthest; + return true; +} + +Hyperplanes::Hyperplanes(int d_in, int m_in, int64_t seed) : d(d_in), m(m_in) { + FAISS_THROW_IF_NOT_FMT(d >= 1, "Hyperplanes: d must be >= 1, got %d", d); + FAISS_THROW_IF_NOT_FMT( + m >= 1 && m <= 16, "Hyperplanes: m must be in [1, 16], got %d", m); + std::vector h(static_cast(m) * d); + float_randn(h.data(), h.size(), seed); + ht.assign(static_cast(d) * 16, 0.0f); + for (int i = 0; i < m; i++) { + for (int j = 0; j < d; j++) { + ht[static_cast(j) * 16 + i] = + h[static_cast(i) * d + j]; + } + } +} + +FAISS_NOINLINE void Hyperplanes::sketch(const float* x, float* out16) const { + // Local accumulators, j ascending: the result depends only on the values + // of x, never on its buffer, alignment or caller. + float acc[16] = {}; + const float* h = ht.data(); + for (int j = 0; j < d; j++) { + const float xj = x[j]; + const float* hj = h + static_cast(j) * 16; + for (int i = 0; i < 16; i++) { + acc[i] += xj * hj[i]; + } + } + std::memcpy(out16, acc, sizeof(acc)); +} + +uint16_t residual_hash(const float* sketch_p, const float* sketch_c, int m) { + uint16_t h = 0; + for (int i = 0; i < m; i++) { + if (sketch_c[i] - sketch_p[i] >= 0) { + h = static_cast(h | (1u << i)); + } + } + return h; +} + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/HashPrune.h b/thirdparty/faiss/faiss/impl/pipnn/HashPrune.h new file mode 100644 index 000000000..8d78421f6 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/HashPrune.h @@ -0,0 +1,69 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +namespace faiss { +namespace pipnn { + +/// One reservoir slot: candidate id, residual-LSH bucket, order-preserving key. +struct Slot { + int32_t id; + uint16_t hash; + uint16_t key; +}; +static_assert(sizeof(Slot) == 8, "PiPNN reservoir slots must be 8 bytes"); + +/// "No cached farthest slot"; never a slot index since capacity <= 255. +constexpr uint8_t kNoFarthest = 0xFF; + +/// Monotone 16-bit key of a distance, which may be negative, from its scalar +/// bf16 encoding. NaN maps to +inf and -0 to +0. +uint16_t distance_key(float v); + +/// Strict (key, id) order. Deciding key ties by id makes the reservoir +/// independent of the offer order. +inline bool slot_less(uint16_t ka, int32_t ia, uint16_t kb, int32_t ib) { + return ka < kb || (ka == kb && ia < ib); +} + +/// One point's reservoir in caller-owned storage; not thread-safe. Slots are +/// sorted by distinct hash, and *farthest caches the slot_less-maximum. +struct ReservoirRef { + Slot* slots; + uint8_t* count; // 0 when fresh + uint8_t* farthest; // kNoFarthest when fresh or unknown + int capacity; // 1..255 + + /// Keeps the smaller offer on a bucket hit, else inserts or evicts the + /// maximum. An id must always come with the same hash. True iff changed. + bool offer(int32_t id, uint16_t hash, uint16_t key); +}; + +/// m <= 16 Gaussian hyperplanes from float_randn(seed), stored transposed +/// and zero-padded: ht[j * 16 + i]. +struct Hyperplanes { + int d = 0; + int m = 0; + std::vector ht; // d * 16 + + Hyperplanes() = default; + Hyperplanes(int d, int m, int64_t seed); + + /// out16[i] = sum over ascending j of x[j] * ht[j * 16 + i]. Not inlined, + /// so all call sites produce bitwise-identical sketches. + void sketch(const float* x, float* out16) const; +}; + +/// Bit i (i < m <= 16) is set iff sketch_c[i] - sketch_p[i] >= 0. +uint16_t residual_hash(const float* sketch_p, const float* sketch_c, int m); + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/Partition.cpp b/thirdparty/faiss/faiss/impl/pipnn/Partition.cpp new file mode 100644 index 000000000..dab8f18e3 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/Partition.cpp @@ -0,0 +1,587 @@ +/* + * 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. + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace faiss { +namespace pipnn { + +int PartitionParams::fanout_at(int depth) const { + FAISS_ASSERT(depth >= 0); + return static_cast(depth) < fanout.size() ? fanout[depth] : 1; +} + +uint64_t mix_seed(uint64_t a, uint64_t b) { + return SplitMix64RandomGenerator(int64_t(a ^ (b + (a << 6) + (a >> 2)))) + .next(); +} + +namespace detail { + +size_t leader_count(size_t size, const PartitionParams& p, int depth) { + size_t by_fraction = static_cast(std::ceil( + static_cast(p.leader_fraction) * + static_cast(size))); + size_t floor4 = 4 * static_cast(p.fanout_at(depth)); + size_t count = std::max(by_fraction, floor4); + count = std::min(count, static_cast(p.leader_cap)); + return std::min(count, size); +} + +void sample_positions( + size_t N, + size_t k, + uint64_t seed, + std::vector& out) { + FAISS_ASSERT(k <= N); + out.clear(); + out.reserve(k); + SplitMix64RandomGenerator rng(static_cast(seed)); + for (size_t j = N - k; j < N; j++) { + size_t t = static_cast( + rng.next() % (static_cast(j) + 1)); + auto it = std::lower_bound(out.begin(), out.end(), t); + if (it != out.end() && *it == t) { + out.push_back(j); // every sampled position is < j + } else { + out.insert(it, t); + } + } +} + +Ranking ranking_for(const PartitionParams& p, bool force_l2) { + if (p.metric == METRIC_L2 || force_l2) { + return Ranking::L2; + } + return p.ip_partition_by_angle ? Ranking::Angle : Ranking::IP; +} + +} // namespace detail + +namespace { + +/// Positions per counting-sort block; unlike kStripe, it does not affect +/// leaves. +constexpr size_t kScatterBlock = 65536; +/// Above any leader index, so the merge-order seed never equals a child's. +constexpr uint64_t kMergeShuffleIndex = uint64_t(1) << 33; + +constexpr size_t kNoSplit = std::numeric_limits::max(); + +/// `ids` is sorted and owned by a LevelStorage (or the root list). +struct Node { + const int32_t* ids; + size_t size; + uint64_t seed; + int depth; + bool force_l2; // L2 ranking: this or an ancestor was a > 90% IP child +}; + +/// Owns the id lists of every node of one level. +struct LevelStorage { + std::unique_ptr child_ids; + std::vector> merge_pools; +}; + +/// Inputs and stats shared by every level of one partition. +struct LevelContext { + const Index& storage; + const PartitionParams& p; + const LeafVisitor& on_leaf; + PartitionStats& stats; +}; + +/// A leaf (split == kNoSplit) or kStripe points of a split node from `begin`. +struct WorkItem { + size_t node; + size_t split; + size_t begin; +}; + +struct SplitInfo { + size_t node = 0; + std::vector leaders; // ascending ids + int fanout = 0; + Ranking ranking = Ranking::L2; + size_t offset = 0; // start in the level assignment / child-id buffers + size_t n_blocks = 0; + size_t count_offset = 0; // start in the level count buffer + std::vector child_off; // |L| + 1 offsets into the child-id buffer +}; + +struct LevelPlan { + std::vector items; + std::vector splits; + size_t n_instances = 0; // (point, chosen leader) pairs of all splits + size_t n_counts = 0; // entries of the count buffer +}; + +/// Next-level nodes of one split. Merged groups have ids == nullptr until +/// collect_children points them into their pool. +struct SplitOutput { + std::vector nodes; + std::vector pool_offsets; + std::vector pool; + size_t n_slices = 0; + size_t n_l2 = 0; +}; + +void check_params(const Index& storage, const PartitionParams& p) { + FAISS_THROW_IF_NOT_MSG( + p.c_min >= 1 && p.c_min <= p.c_max, + "PiPNN partition: need 1 <= c_min <= c_max"); + FAISS_THROW_IF_NOT_FMT( + p.c_max <= kMaxCMax, + "PiPNN partition: need c_max <= %d (got %d): each thread holds a " + "c_max x c_max float matrix", + kMaxCMax, + p.c_max); + FAISS_THROW_IF_NOT_FMT( + p.leader_cap >= 1 && p.leader_cap <= kMaxLeaderCap, + "PiPNN partition: need 1 <= leader_cap <= %d", + kMaxLeaderCap); + FAISS_THROW_IF_NOT_MSG( + p.leader_fraction >= 0 && p.leader_fraction <= 1, + "PiPNN partition: need 0 <= leader_fraction <= 1"); + for (int f : p.fanout) { + FAISS_THROW_IF_NOT_MSG( + f >= 1, "PiPNN partition: every fanout must be >= 1"); + } + FAISS_THROW_IF_NOT_MSG( + p.metric == METRIC_L2 || p.metric == METRIC_INNER_PRODUCT, + "PiPNN partition: metric must be L2 or inner product"); + FAISS_THROW_IF_NOT_MSG( + storage.ntotal >= 0 && + storage.ntotal <= std::numeric_limits::max(), + "PiPNN partition: need 0 <= n <= INT32_MAX"); +} + +void record_leaf(PartitionStats& stats, size_t size, int depth) { + stats.n_leaves++; + stats.n_point_instances += size; + stats.max_leaf = std::max(stats.max_leaf, size); + stats.max_depth_seen = std::max(stats.max_depth_seen, depth); + const size_t bucket = (size - 1) / 64; + if (stats.leaf_size_histogram.size() <= bucket) { + stats.leaf_size_histogram.resize(bucket + 1, 0); + } + stats.leaf_size_histogram[bucket]++; +} + +void push_slices(const Node& child, size_t c_max, SplitOutput& out) { + for (size_t o = 0; o < child.size; o += c_max) { + out.nodes.push_back( + Node{child.ids + o, + std::min(c_max, child.size - o), + child.seed, + child.depth, + child.force_l2}); + } +} + +LevelPlan plan_level(const LevelContext& ctx, const std::vector& nodes) { + const PartitionParams& p = ctx.p; + const size_t c_max = static_cast(p.c_max); + size_t n_items = 0; + size_t n_splits = 0; + for (const Node& nd : nodes) { + if (nd.size <= c_max) { + n_items++; + } else { + n_items += (nd.size + kStripe - 1) / kStripe; + n_splits++; + } + } + LevelPlan plan; + plan.splits.reserve(n_splits); + plan.items.reserve(n_items); + for (size_t i = 0; i < nodes.size(); i++) { + const Node& nd = nodes[i]; + if (nd.size <= c_max) { + record_leaf(ctx.stats, nd.size, nd.depth); + plan.items.push_back(WorkItem{i, kNoSplit, 0}); + continue; + } + SplitInfo sp; + sp.node = i; + const size_t n_leaders = detail::leader_count(nd.size, p, nd.depth); + std::vector positions; + detail::sample_positions(nd.size, n_leaders, nd.seed, positions); + sp.leaders.resize(n_leaders); + for (size_t l = 0; l < n_leaders; l++) { + sp.leaders[l] = nd.ids[positions[l]]; + } + sp.fanout = + std::min(p.fanout_at(nd.depth), static_cast(n_leaders)); + sp.ranking = detail::ranking_for(p, nd.force_l2); + sp.offset = plan.n_instances; + plan.n_instances += nd.size * sp.fanout; + sp.n_blocks = (nd.size + kScatterBlock - 1) / kScatterBlock; + sp.count_offset = plan.n_counts; + plan.n_counts += sp.n_blocks * n_leaders; + for (size_t b = 0; b < nd.size; b += kStripe) { + plan.items.push_back(WorkItem{i, plan.splits.size(), b}); + } + plan.splits.push_back(std::move(sp)); + } + return plan; +} + +/// Runs the leaf and stripe items; returns each point's `fanout` nearest +/// leaders. +std::unique_ptr assign_leaders( + const LevelContext& ctx, + const std::vector& nodes, + const LevelPlan& plan) { + const Index& storage = ctx.storage; + const size_t d = static_cast(storage.d); + // new T[n], not std::vector: every entry is written first; zeroing is + // serial. + std::unique_ptr assign(new uint16_t[plan.n_instances]); + std::exception_ptr ex; + std::atomic interrupt{false}; +#pragma omp parallel + { + AlignedTable stripe_vecs, leader_vecs, dist; + std::vector leader_norms; + size_t n_done = 0; +#pragma omp for schedule(FAISS_OMP_DYNAMIC) + for (int64_t i = 0; i < static_cast(plan.items.size()); i++) { + if (interrupt.load(std::memory_order_relaxed)) { + continue; + } + try { + const WorkItem& item = plan.items[i]; + const Node& nd = nodes[item.node]; + if (item.split == kNoSplit) { + ctx.on_leaf(nd.ids, nd.size); + } else { + const SplitInfo& sp = plan.splits[item.split]; + const size_t S = std::min(kStripe, nd.size - item.begin); + const size_t L = sp.leaders.size(); + ensure_size(stripe_vecs, S * d); + ensure_size(leader_vecs, L * d); + ensure_size(dist, S * L); + leader_norms.resize(L); + gather_rows( + storage, + nd.ids + item.begin, + S, + stripe_vecs.data()); + gather_rows( + storage, sp.leaders.data(), L, leader_vecs.data()); + for (size_t l = 0; l < L; l++) { + leader_norms[l] = + fvec_norm_L2sqr(leader_vecs.data() + l * d, d); + } + stripe_assign( + stripe_vecs.data(), + S, + leader_vecs.data(), + leader_norms.data(), + L, + d, + sp.ranking, + sp.fanout, + dist.data(), + assign.get() + sp.offset + item.begin * sp.fanout); + } + if (omp_get_thread_num() == 0 && n_done++ % 64 == 0 && + InterruptCallback::is_interrupted()) { + FAISS_THROW_MSG("computation interrupted"); + } + } catch (...) { + omp_capture_exception(ex, [&] { interrupt = true; }); + } + } + } + omp_rethrow_if_exception(ex); + return assign; +} + +/// Counting sort per (split, block): count, prefix sums in (leader, block) +/// order, scatter. Every child comes out in parent order. Fills child_off and +/// returns the child ids, owned by next_storage. +const int32_t* scatter_children( + const std::vector& nodes, + LevelPlan& plan, + const uint16_t* assign, + LevelStorage& next_storage) { + std::vector& splits = plan.splits; + std::vector> blocks; + for (size_t s = 0; s < splits.size(); s++) { + for (size_t b = 0; b < splits[s].n_blocks; b++) { + blocks.emplace_back(s, b); + } + } + std::unique_ptr counts(new size_t[plan.n_counts]); +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (int64_t i = 0; i < static_cast(blocks.size()); i++) { + const SplitInfo& sp = splits[blocks[i].first]; + const size_t b = blocks[i].second; + const Node& nd = nodes[sp.node]; + const size_t L = sp.leaders.size(); + size_t* cnt = counts.get() + sp.count_offset + b * L; + std::fill(cnt, cnt + L, 0); + const uint16_t* a = assign + sp.offset; + const size_t end = std::min(nd.size, (b + 1) * kScatterBlock); + for (size_t pos = b * kScatterBlock; pos < end; pos++) { + for (int j = 0; j < sp.fanout; j++) { + cnt[a[pos * sp.fanout + j]]++; + } + } + } + for (SplitInfo& sp : splits) { + const size_t L = sp.leaders.size(); + sp.child_off.resize(L + 1); + size_t running = sp.offset; + for (size_t l = 0; l < L; l++) { + sp.child_off[l] = running; + for (size_t b = 0; b < sp.n_blocks; b++) { + size_t& c = counts[sp.count_offset + b * L + l]; + const size_t block_count = c; + c = running; + running += block_count; + } + } + sp.child_off[L] = running; + } + next_storage.child_ids.reset(new int32_t[plan.n_instances]); + int32_t* child_ids = next_storage.child_ids.get(); +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (int64_t i = 0; i < static_cast(blocks.size()); i++) { + const SplitInfo& sp = splits[blocks[i].first]; + const size_t b = blocks[i].second; + const Node& nd = nodes[sp.node]; + size_t* cursor = counts.get() + sp.count_offset + b * sp.leaders.size(); + const uint16_t* a = assign + sp.offset; + const size_t end = std::min(nd.size, (b + 1) * kScatterBlock); + for (size_t pos = b * kScatterBlock; pos < end; pos++) { + for (int j = 0; j < sp.fanout; j++) { + child_ids[cursor[a[pos * sp.fanout + j]]++] = nd.ids[pos]; + } + } + } + return child_ids; +} + +/// Child rules, in order: below c_min it is merged; up to c_max it is a leaf; +/// at max_depth it is sliced; an IP-ranked child above 90% of its parent is +/// re-split by L2; a child equal to its parent is sliced; else it is split. +void classify_children( + const PartitionParams& p, + const Node& nd, + const SplitInfo& sp, + const int32_t* child_ids, + SplitOutput& out) { + const size_t c_min = static_cast(p.c_min); + const size_t c_max = static_cast(p.c_max); + const int child_depth = nd.depth + 1; + std::vector small_children; + for (size_t l = 0; l < sp.leaders.size(); l++) { + Node child{ + child_ids + sp.child_off[l], + sp.child_off[l + 1] - sp.child_off[l], + mix_seed(nd.seed, l), + child_depth, + nd.force_l2}; + if (child.size < c_min) { + small_children.push_back(static_cast(l)); + } else if (child.size <= c_max) { + out.nodes.push_back(child); + } else if (child_depth >= p.max_depth) { + push_slices(child, c_max, out); + out.n_slices++; + } else if (sp.ranking != Ranking::L2 && 10 * child.size > 9 * nd.size) { + child.force_l2 = true; + out.nodes.push_back(child); + out.n_l2++; + } else if (child.size == nd.size) { + push_slices(child, c_max, out); + out.n_slices++; + } else { + out.nodes.push_back(child); + } + } + + std::vector merge_order(small_children.size()); + rand_perm_splitmix64( + merge_order.data(), + merge_order.size(), + static_cast(mix_seed(nd.seed, kMergeShuffleIndex))); + std::vector group; + auto close_group = [&]() { + std::sort(group.begin(), group.end()); + group.erase(std::unique(group.begin(), group.end()), group.end()); + out.pool_offsets.push_back(out.pool.size()); + out.pool.insert(out.pool.end(), group.begin(), group.end()); + // At most c_max points, so it is a leaf and its seed is never used. + out.nodes.push_back( + Node{nullptr, group.size(), 0, child_depth, nd.force_l2}); + group.clear(); + }; + for (int i : merge_order) { + const uint32_t l = small_children[i]; + const int32_t* c = child_ids + sp.child_off[l]; + const size_t size = sp.child_off[l + 1] - sp.child_off[l]; + if (!group.empty() && group.size() + size > c_max) { + close_group(); + } + group.insert(group.end(), c, c + size); + } + if (!group.empty()) { + close_group(); + } +} + +void collect_children( + const LevelContext& ctx, + const std::vector& nodes, + const std::vector& splits, + const int32_t* child_ids, + std::vector& next, + LevelStorage& next_storage) { + std::vector outputs(splits.size()); + std::exception_ptr ex; +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) + for (int64_t s = 0; s < static_cast(splits.size()); s++) { + try { + classify_children( + ctx.p, + nodes[splits[s].node], + splits[s], + child_ids, + outputs[s]); + } catch (...) { + omp_capture_exception(ex); + } + } + omp_rethrow_if_exception(ex); + size_t n_next = next.size(); + for (const SplitOutput& out : outputs) { + n_next += out.nodes.size(); + } + next.reserve(n_next); + next_storage.merge_pools.reserve(outputs.size()); + for (SplitOutput& out : outputs) { + ctx.stats.n_slice_fallbacks += out.n_slices; + ctx.stats.n_l2_repartitions += out.n_l2; + next_storage.merge_pools.push_back(std::move(out.pool)); + const int32_t* pool = next_storage.merge_pools.back().data(); + size_t k = 0; + for (Node& child : out.nodes) { + if (child.ids == nullptr) { + child.ids = pool + out.pool_offsets[k++]; + } + } + next.insert( + next.end(), + std::make_move_iterator(out.nodes.begin()), + std::make_move_iterator(out.nodes.end())); + std::vector().swap(out.nodes); + std::vector().swap(out.pool_offsets); + } +} + +void run_level( + const LevelContext& ctx, + const std::vector& nodes, + std::vector& next, + LevelStorage& next_storage) { + LevelPlan plan = plan_level(ctx, nodes); + const std::unique_ptr assign = assign_leaders(ctx, nodes, plan); + if (plan.splits.empty()) { + return; + } + const int32_t* child_ids = + scatter_children(nodes, plan, assign.get(), next_storage); + collect_children(ctx, nodes, plan.splits, child_ids, next, next_storage); +} + +} // namespace + +void partition_and_visit( + const Index& storage, + const PartitionParams& p, + uint64_t root_seed, + const LeafVisitor& on_leaf, + PartitionStats* stats, + const std::vector& ids) { + check_params(storage, p); + PartitionStats st; + const LevelContext ctx{storage, p, on_leaf, st}; + const size_t n = + ids.empty() ? static_cast(storage.ntotal) : ids.size(); + if (n > 0) { + InterruptCallback::check(); + std::unique_ptr root_ids(new int32_t[n]); + for (size_t i = 0; i < n; i++) { + root_ids[i] = ids.empty() ? static_cast(i) : ids[i]; + } + std::vector root_children; + LevelStorage root_storage; + run_level( + ctx, + {Node{root_ids.get(), n, root_seed, 0, false}}, + root_children, + root_storage); + root_ids.reset(); + + size_t w0 = 0; + while (w0 < root_children.size()) { + size_t w1 = w0; + size_t load = 0; + while (w1 < root_children.size() && + (w1 == w0 || + load + root_children[w1].size <= p.wave_budget)) { + load += root_children[w1].size; + w1++; + } + st.n_waves++; + std::vector nodes( + root_children.begin() + w0, root_children.begin() + w1); + std::unique_ptr level_storage; + while (!nodes.empty()) { + InterruptCallback::check(); + std::vector next; + auto next_storage = std::make_unique(); + run_level(ctx, nodes, next, *next_storage); + nodes = std::move(next); + level_storage = + std::move(next_storage); // frees the parent lists + } + w0 = w1; + } + } + if (stats) { + *stats = std::move(st); + } +} + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/Partition.h b/thirdparty/faiss/faiss/impl/pipnn/Partition.h new file mode 100644 index 000000000..4062bcd3f --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/Partition.h @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +namespace faiss { + +struct Index; + +namespace pipnn { + +enum class Ranking : uint8_t; + +/// Randomized Ball Carving settings (paper Alg. 5). +struct PartitionParams { + int c_max = 1024; // largest leaf + int c_min = 128; // smaller children are merged + int leader_cap = 1000; // most leaders per split + float leader_fraction = 0.005f; // leaders per split, as a fraction of it + std::vector fanout = {10, 3}; // leaders joined per depth, then 1 + MetricType metric = METRIC_L2; + bool ip_partition_by_angle = false; + size_t wave_budget = size_t(1) << 30; // point instances per wave + int max_depth = 32; // children at this depth are cut into id slices + int fanout_at(int depth) const; +}; + +/// Each partition thread holds a c_max x c_max float matrix. +inline constexpr int kMaxCMax = 4096; +/// Leader indices are stored as uint16_t. +inline constexpr int kMaxLeaderCap = 65535; + +struct PartitionStats { + size_t n_leaves = 0; + size_t n_point_instances = 0; // sum of leaf sizes + size_t max_leaf = 0; + size_t n_slice_fallbacks = 0, n_l2_repartitions = 0; + int max_depth_seen = 0; + /// leaf_size_histogram[i] counts leaves of size in [64 i + 1, 64 (i + 1)]. + std::vector leaf_size_histogram; + size_t n_waves = 0; +}; + +/// Called once per leaf with its sorted, unique ids (s <= c_max), concurrently +/// from partition_and_visit's OpenMP region: omp_get_thread_num() identifies +/// the calling thread. `ids` is valid only during the call. +using LeafVisitor = std::function; + +/// Randomized Ball Carving with multi-level fanout over the sorted `ids` (all +/// of storage if empty). Calls `on_leaf` exactly once per leaf and fills +/// `*stats` (if not null). On an exception or an interrupt it rethrows with +/// some leaves unvisited and `*stats` unchanged. +void partition_and_visit( + const Index& storage, + const PartitionParams& p, + uint64_t root_seed, + const LeafVisitor& on_leaf, + PartitionStats* stats, + const std::vector& ids = {}); + +/// Deterministic hash of (a, b) for derived seeds. For a fixed a, distinct b +/// give distinct results. +uint64_t mix_seed(uint64_t a, uint64_t b); + +/// Building blocks of partition_and_visit, exposed for unit tests. +namespace detail { + +/// min(max(ceil(leader_fraction * size), 4 * fanout(depth)), leader_cap, size) +size_t leader_count(size_t size, const PartitionParams& p, int depth); + +/// k distinct positions of [0, N), ascending (Floyd's algorithm). +void sample_positions( + size_t N, + size_t k, + uint64_t seed, + std::vector& out); + +Ranking ranking_for(const PartitionParams& p, bool force_l2); + +} // namespace detail + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/kernels.cpp b/thirdparty/faiss/faiss/impl/pipnn/kernels.cpp new file mode 100644 index 000000000..2b95141d5 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/kernels.cpp @@ -0,0 +1,326 @@ +/* + * 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. + */ + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +extern "C" { + +// this is to keep the clang syntax checker happy +#ifndef FINTEGER +#define FINTEGER int +#endif + +/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */ + +int sgemm_( + const char* transa, + const char* transb, + FINTEGER* m, + FINTEGER* n, + FINTEGER* k, + const float* alpha, + const float* a, + FINTEGER* lda, + const float* b, + FINTEGER* ldb, + float* beta, + float* c, + FINTEGER* ldc); + +int ssyrk_( + const char* uplo, + const char* trans, + FINTEGER* n, + FINTEGER* k, + float* alpha, + float* a, + FINTEGER* lda, + float* beta, + float* c, + FINTEGER* ldc); +} + +namespace faiss { +namespace pipnn { + +namespace { + +FINTEGER to_finteger(size_t v, const char* what) { + FAISS_THROW_IF_NOT_FMT( + v <= size_t(std::numeric_limits::max()), + "PiPNN kernel: %s=%zu exceeds the BLAS integer range", + what, + v); + return static_cast(v); +} + +float nan_to_inf(float v) { + return std::isnan(v) ? std::numeric_limits::infinity() : v; +} + +/// Top-k in (dist, index) order on a Faiss max-heap. Empty slots are +/// (+inf, INT32_MAX), so +inf offers still fill them, in index order. +using TopK = CMax; +constexpr int32_t kEmpty = std::numeric_limits::max(); + +void topk_init(float* D, int32_t* I, size_t k) { + std::fill(D, D + k, std::numeric_limits::infinity()); + std::fill(I, I + k, kEmpty); +} + +void topk_offer(float* D, int32_t* I, size_t k, float v, int32_t id) { + if (TopK::cmp2(D[0], v, I[0], id)) { + heap_replace_top(k, D, I, v, id); + } +} + +/// Sorts the slots by (dist, index); slots never filled become (+inf, -1). +void topk_finish(float* D, int32_t* I, size_t k) { + heap_reorder(k, D, I); + std::replace(I, I + k, kEmpty, int32_t(-1)); +} + +} // namespace + +void stripe_assign( + const float* points, + size_t S, + const float* leaders, + const float* leader_norms, + size_t L, + size_t d, + Ranking ranking, + int fanout, + float* scratch, + uint16_t* out) { + FAISS_THROW_IF_NOT_FMT( + L >= 1 && L <= 65535, + "stripe_assign: L=%zu must be in [1, 65535]", + L); + FAISS_THROW_IF_NOT_FMT( + fanout >= 1 && size_t(fanout) <= L, + "stripe_assign: fanout=%d must be in [1, L=%zu]", + fanout, + L); + FAISS_THROW_IF_NOT_MSG(d >= 1, "stripe_assign: d must be >= 1"); + FAISS_THROW_IF_NOT_MSG( + ranking == Ranking::IP || leader_norms, + "stripe_assign: leader_norms is required for the L2 and Angle rankings"); + if (S == 0) { + return; + } + FINTEGER li = to_finteger(L, "L"); + FINTEGER si = to_finteger(S, "S"); + FINTEGER di = to_finteger(d, "d"); + + // Column-major BLAS sees row-major scratch (S x L) as L x S, so "T", "N" + // gives scratch[i * L + j] = alpha * p_i.l_j + beta * scratch[i * L + j]. + float alpha = -1; + float beta = 0; // BLAS does not read C when beta == 0 + if (ranking == Ranking::L2) { + for (size_t i = 0; i < S; i++) { + std::copy(leader_norms, leader_norms + L, scratch + i * L); + } + alpha = -2; + beta = 1; + } + sgemm_("T", + "N", + &li, + &si, + &di, + &alpha, + leaders, + &di, + points, + &di, + &beta, + scratch, + &li); + + if (ranking == Ranking::Angle) { + // A zero-norm leader has no direction: rank it +inf, not the -inf of + // a positive dot product divided by 0. + for (size_t i = 0; i < S; i++) { + float* row = scratch + i * L; + for (size_t j = 0; j < L; j++) { + const float len = std::sqrt(leader_norms[j]); + row[j] = len > 0 ? row[j] / len + : std::numeric_limits::infinity(); + } + } + } + + const size_t f = size_t(fanout); + std::vector D(f); + std::vector I(f); + for (size_t i = 0; i < S; i++) { + topk_init(D.data(), I.data(), f); + const float* row = scratch + i * L; + for (size_t j = 0; j < L; j++) { + topk_offer(D.data(), I.data(), f, nan_to_inf(row[j]), int32_t(j)); + } + topk_finish(D.data(), I.data(), f); + // L >= fanout and every offer precedes an empty slot, so all fanout + // slots are filled, even when the whole row is +inf. + for (size_t r = 0; r < f; r++) { + out[i * f + r] = uint16_t(I[r]); + } + } +} + +namespace { + +/// Distance from a Gram entry: L2 max(0, ni + nj - 2g), IP -g. NaN is mapped +/// to +inf before the L2 clamp, which would otherwise turn it into 0. +float gram_to_distance(bool is_l2, float ni, float nj, float g) { + if (is_l2) { + const float v = ni + nj - 2 * g; + if (std::isnan(v)) { + return std::numeric_limits::infinity(); + } + return v < 0 ? 0 : v; + } + return nan_to_inf(-g); +} + +/// Lower triangle of X X^T, diagonal included, into row-major gram (s x s); +/// the strict upper triangle is not written. +void gram_lower(const float* X, size_t s, size_t d, float* gram) { + // Column-major BLAS reads X as A = X^T (d x s); the upper triangle of + // C = A^T A ("U", "T") is the row-major lower triangle of gram. + FINTEGER si = to_finteger(s, "s"); + FINTEGER di = to_finteger(d, "d"); + float one = 1; + float zero = 0; // BLAS does not read C when beta == 0 + ssyrk_("U", + "T", + &si, + &di, + &one, + const_cast(X), + &di, + &zero, + gram, + &si); +} + +} // namespace + +void leaf_knn( + const float* X, + const float* norms, + size_t s, + size_t d, + MetricType metric, + int k, + float* gram, + int32_t* nn_idx, + float* nn_dist) { + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT, + "leaf_knn: metric must be METRIC_L2 or METRIC_INNER_PRODUCT"); + FAISS_THROW_IF_NOT_MSG(k >= 1, "leaf_knn: k must be >= 1"); + FAISS_THROW_IF_NOT_MSG(d >= 1, "leaf_knn: d must be >= 1"); + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_INNER_PRODUCT || norms, + "leaf_knn: norms is required for METRIC_L2"); + const size_t kk = size_t(k); + for (size_t i = 0; i < s; i++) { + topk_init(nn_dist + i * kk, nn_idx + i * kk, kk); + } + if (s >= 2) { + gram_lower(X, s, d, gram); + } + const bool is_l2 = metric == METRIC_L2; + for (size_t i = 1; i < s; i++) { + const float* gi = gram + i * s; + const float ni = is_l2 ? norms[i] : 0; + for (size_t j = 0; j < i; j++) { + const float nj = is_l2 ? norms[j] : 0; + const float v = gram_to_distance(is_l2, ni, nj, gi[j]); + topk_offer(nn_dist + i * kk, nn_idx + i * kk, kk, v, int32_t(j)); + topk_offer(nn_dist + j * kk, nn_idx + j * kk, kk, v, int32_t(i)); + } + } + for (size_t i = 0; i < s; i++) { + topk_finish(nn_dist + i * kk, nn_idx + i * kk, kk); + } +} + +void pairwise_distances( + const float* X, + const float* norms, + size_t n, + size_t d, + MetricType metric, + float* out) { + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_L2 || metric == METRIC_INNER_PRODUCT, + "pairwise_distances: metric must be METRIC_L2 or METRIC_INNER_PRODUCT"); + FAISS_THROW_IF_NOT_MSG(d >= 1, "pairwise_distances: d must be >= 1"); + FAISS_THROW_IF_NOT_MSG( + metric == METRIC_INNER_PRODUCT || norms, + "pairwise_distances: norms is required for METRIC_L2"); + if (n == 0) { + return; + } + // Row i reads only its lower part of the Gram scratch; mirrored writes of + // earlier rows go to their strict upper triangle. + gram_lower(X, n, d, out); + const bool is_l2 = metric == METRIC_L2; + for (size_t i = 0; i < n; i++) { + float* oi = out + i * n; + const float ni = is_l2 ? norms[i] : 0; + for (size_t j = 0; j < i; j++) { + const float nj = is_l2 ? norms[j] : 0; + const float v = gram_to_distance(is_l2, ni, nj, oi[j]); + oi[j] = v; + out[j * n + i] = v; + } + oi[i] = gram_to_distance(is_l2, ni, ni, oi[i]); + } +} + +void gather_rows( + const Index& storage, + const int32_t* ids, + size_t k, + float* out) { + const size_t d = static_cast(storage.d); + if (typeid(storage) == typeid(IndexScalarQuantizer)) { + // Not reconstruct: ScalarQuantizer::decode opens an OpenMP region, and + // a nested region inside the build's dynamic loops crashes libomp. + const auto& sq = static_cast(storage); + std::unique_ptr quant( + sq.sq.select_quantizer()); + for (size_t i = 0; i < k; i++) { + quant->decode_vector( + sq.codes.data() + + static_cast(ids[i]) * sq.code_size, + out + i * d); + } + return; + } + for (size_t i = 0; i < k; i++) { + storage.reconstruct(ids[i], out + i * d); + } +} + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pipnn/kernels.h b/thirdparty/faiss/faiss/impl/pipnn/kernels.h new file mode 100644 index 000000000..43caca99e --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pipnn/kernels.h @@ -0,0 +1,92 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include + +/* + * Each kernel makes one BLAS call (sgemm_ or ssyrk_), and results are bitwise + * reproducible across thread counts only if that call runs single-threaded. + * So call the kernels inside an OpenMP parallel region, or from serial code + * only when omp_get_max_threads() == 1, and keep BLAS from threading on its + * own: MKL_NUM_THREADS unset or 1, OPENBLAS_NUM_THREADS=1 for pthreads + * OpenBLAS, VECLIB_MAXIMUM_THREADS=1 on macOS, OMP_NUM_THREADS=1 for an + * OpenMP BLAS in a Faiss build without OpenMP. Inputs should be 64-byte + * aligned: some BLAS round differently on differently aligned buffers. + */ + +namespace faiss { + +struct Index; + +namespace pipnn { + +/// Points per stripe item of the partition kernel. Changing it changes graphs. +constexpr size_t kStripe = 1024; + +enum class Ranking : uint8_t { L2 = 0, IP = 1, Angle = 2 }; + +/// out (S x fanout): each point's nearest leaders in (rank, index) order, with +/// rank L2 ||l||^2 - 2 p.l, IP -p.l, Angle -p.l / ||l|| (+inf if ||l|| = 0). +/// NaN ranks +inf. scratch: S * L floats; leader_norms may be null for IP. +void stripe_assign( + const float* points, + size_t S, + const float* leaders, + const float* leader_norms, + size_t L, + size_t d, + Ranking ranking, + int fanout, + float* scratch, + uint16_t* out); + +/// k nearest neighbours (s x k) of each leaf point in (dist, index) order; +/// unfilled slots are -1 / +inf. gram: s * s floats; norms null for IP only. +void leaf_knn( + const float* X, + const float* norms, + size_t s, + size_t d, + MetricType metric, + int k, + float* gram, + int32_t* nn_idx, + float* nn_dist); + +/// n x n distances (L2 clamped at 0, IP -dot); out is also the Gram scratch. +/// The L2 diagonal is small and non-negative, but not necessarily 0. +void pairwise_distances( + const float* X, + const float* norms, + size_t n, + size_t d, + MetricType metric, + float* out); + +/// Rows ids[0..k) of `storage` as floats into out (k x d). SQ rows are decoded +/// directly; other types use reconstruct(), which must not open OpenMP regions. +void gather_rows( + const Index& storage, + const int32_t* ids, + size_t k, + float* out); + +/// Grows a per-thread scratch table and never shrinks it: AlignedTable::resize +/// reallocates whenever the rounded capacity changes, shrinking included. +inline void ensure_size(AlignedTable& table, size_t n) { + if (table.size() < n) { + table.resize(n); + } +} + +} // namespace pipnn +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/platform_macros.h b/thirdparty/faiss/faiss/impl/platform_macros.h index 011ae80c9..7a609441d 100644 --- a/thirdparty/faiss/faiss/impl/platform_macros.h +++ b/thirdparty/faiss/faiss/impl/platform_macros.h @@ -8,8 +8,11 @@ #pragma once // basic int types and size_t +#include +#include #include #include +#include #ifdef _WIN32 @@ -35,9 +38,6 @@ (((*(p)) = _aligned_malloc((s), (a))), *(p) ? 0 : errno) #define posix_memalign_free _aligned_free -// aligned should be in front of the declaration -#define ALIGNED(x) __declspec(align(x)) - // redefine the GCC intrinsics with Windows equivalents #ifdef _MSC_VER @@ -104,14 +104,6 @@ inline int __builtin_clzll(uint64_t x) { #endif // _MSC_VER #define FAISS_ALWAYS_INLINE __forceinline - -// MSVC uses pragma pack instead of __attribute__((packed)) -// Use FAISS_PACK_STRUCTS_BEGIN/END to wrap packed structure definitions -#define FAISS_PACKED -#define FAISS_RESTRICT __restrict -#define FAISS_PACK_STRUCTS_BEGIN __pragma(pack(push, 1)) -#define FAISS_PACK_STRUCTS_END __pragma(pack(pop)) - #else /******************************************************* * Linux and OSX @@ -120,22 +112,6 @@ inline int __builtin_clzll(uint64_t x) { #define FAISS_API #define posix_memalign_free free -// aligned should be *in front* of the declaration, for compatibility with -// windows -#ifdef SWIG -#define ALIGNED(x) -#define FAISS_PACKED -#define FAISS_RESTRICT -#else -#define ALIGNED(x) __attribute__((aligned(x))) -#define FAISS_PACKED __attribute__((packed)) -#define FAISS_RESTRICT __restrict -#endif - -// On non-Windows, FAISS_PACKED handles packing, so these are no-ops -#define FAISS_PACK_STRUCTS_BEGIN -#define FAISS_PACK_STRUCTS_END - #define FAISS_ALWAYS_INLINE __attribute__((always_inline)) inline #endif @@ -146,6 +122,50 @@ inline int __builtin_clzll(uint64_t x) { #define FAISS_DEPRECATED(msg) #endif // GCC or Clang +// Never inlined, so floating-point results do not depend on the compile +// flags of the call site (e.g. under LTO). +#if defined(_MSC_VER) +#define FAISS_NOINLINE __declspec(noinline) +#elif defined(__clang__) +#define FAISS_NOINLINE __attribute__((noinline)) +#elif defined(__GNUC__) +#define FAISS_NOINLINE __attribute__((noinline, noclone)) +#else +#define FAISS_NOINLINE +#endif + +namespace faiss { +namespace detail { + +template +inline void atomic_fetch_add_relaxed(T& target, T value) { +#if defined(__cpp_lib_atomic_ref) && __cpp_lib_atomic_ref >= 201806L + std::atomic_ref(target).fetch_add(value, std::memory_order_relaxed); +#else + if constexpr (std::is_floating_point_v) { + // The _n builtins reject a floating-point type, so accumulate with the + // generic compare-exchange builtin instead. + T expected; + __atomic_load(&target, &expected, __ATOMIC_RELAXED); + T desired; + do { + desired = expected + value; + } while (!__atomic_compare_exchange( + &target, + &expected, + &desired, + true, + __ATOMIC_RELAXED, + __ATOMIC_RELAXED)); + } else { + __atomic_fetch_add(&target, value, __ATOMIC_RELAXED); + } +#endif +} + +} // namespace detail +} // namespace faiss + // Localized enablement of imprecise floating point operations // You need to use all 3 macros to cover all compilers. #if defined(_MSC_VER) @@ -201,6 +221,33 @@ inline int __builtin_clzll(uint64_t x) { // clang-format on +/******************************************************* + * Packing and alignment + *******************************************************/ + +// ALIGNED goes *in front* of the declaration, for compatibility with MSVC. +// swigfaiss.swig defines _MSC_VER under SWIGWIN, so check SWIG first. +#if defined(SWIG) +#define ALIGNED(x) +#define FAISS_PACKED +#define FAISS_RESTRICT +#define FAISS_PACK_STRUCTS_BEGIN +#define FAISS_PACK_STRUCTS_END +#elif defined(_MSC_VER) // MSVC and clang-cl +#define ALIGNED(x) __declspec(align(x)) +// Wrap packed structs in FAISS_PACK_STRUCTS_BEGIN/END for MSVC. +#define FAISS_PACKED +#define FAISS_RESTRICT __restrict +#define FAISS_PACK_STRUCTS_BEGIN __pragma(pack(push, 1)) +#define FAISS_PACK_STRUCTS_END __pragma(pack(pop)) +#else // GCC and Clang, including MinGW +#define ALIGNED(x) __attribute__((aligned(x))) +#define FAISS_PACKED __attribute__((packed)) +#define FAISS_RESTRICT __restrict +#define FAISS_PACK_STRUCTS_BEGIN +#define FAISS_PACK_STRUCTS_END +#endif + /******************************************************* * BIGENDIAN specific macros *******************************************************/ @@ -226,3 +273,20 @@ inline int __builtin_clzll(uint64_t x) { #define FAISS_MAYBE_UNUSED [[maybe_unused]] #define FAISS_FINAL final #endif + +/******************************************************* + * OpenMP dynamic scheduling + *******************************************************/ + +// Use as schedule(FAISS_OMP_DYNAMIC) or schedule(FAISS_OMP_DYNAMIC, chunk). +// OpenMP 5.0 makes schedule(dynamic) nonmonotonic, and libomp 12 runs +// nonmonotonic dynamic loops with its static-steal scheduler, which crashes +// intermittently under load (libomp itself keeps it off by default). MSVC's +// OpenMP 2.0 has no schedule modifiers. +// clang-format off +#ifdef _MSC_VER +#define FAISS_OMP_DYNAMIC dynamic +#else +#define FAISS_OMP_DYNAMIC monotonic : dynamic +#endif +// clang-format on diff --git a/thirdparty/faiss/faiss/impl/polysemous_training/avx512.cpp b/thirdparty/faiss/faiss/impl/polysemous_training/avx512.cpp index 57c196132..dc09e93ea 100644 --- a/thirdparty/faiss/faiss/impl/polysemous_training/avx512.cpp +++ b/thirdparty/faiss/faiss/impl/polysemous_training/avx512.cpp @@ -7,8 +7,6 @@ // -*- c++ -*- -#ifdef COMPILE_SIMD_AVX512 - #include #include #include @@ -280,5 +278,3 @@ double distances_cost_update( } // namespace polysemous_training } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h b/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h index f3aa70b6f..fae53903a 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQScanner_impl.h @@ -11,9 +11,14 @@ #error "THE_SIMD_LEVEL must be defined before including IVFPQScanner_impl.h" #endif +#include +#include +#include + #include #include #include +#include #include #include #include @@ -70,6 +75,48 @@ struct WrappedSearchResult { } }; +/** For each sub-quantizer, a block of codes reads one 1 KB table slice, which + * stays in L1; code by code, a table larger than L1 makes every lookup an L1 + * miss. SL as in PQCodeDistanceScalar. */ +template +void pq_distances_8bit_by_block( + size_t M, + const float* sim_table, + float dis0, + size_t n, + const uint8_t* codes, + float* distances) { + constexpr size_t kBlock = 64; + constexpr size_t ksub = PQCodeDistanceScalar8::ksub; + for (size_t j0 = 0; j0 < n; j0 += kBlock) { + const size_t nb = std::min(kBlock, n - j0); + const uint8_t* block = codes + j0 * M; + float* acc = distances + j0; + std::fill(acc, acc + nb, 0.0f); + const float* tab = sim_table; + size_t m = 0; + for (; m + 4 <= M; m += 4, tab += 4 * ksub) { + const uint8_t* c = block + m; + for (size_t b = 0; b < nb; b++) { + uint32_t w; + memcpy(&w, c + b * M, sizeof(w)); + acc[b] += (tab[w & 255] + tab[ksub + ((w >> 8) & 255)]) + + (tab[2 * ksub + ((w >> 16) & 255)] + + tab[3 * ksub + (w >> 24)]); + } + } + for (; m < M; m++, tab += ksub) { + const uint8_t* c = block + m; + for (size_t b = 0; b < nb; b++) { + acc[b] += tab[c[b * M]]; + } + } + for (size_t b = 0; b < nb; b++) { + acc[b] += dis0; + } + } +} + /***************************************************** * Scaning the codes. * The scanning functions call their favorite precompute_* @@ -411,10 +458,8 @@ struct IVFPQScannerT : QueryTables { } } -#pragma omp critical - { - indexIVFPQ_stats.n_hamming_pass += n_hamming_pass; - } + detail::atomic_fetch_add_relaxed( + indexIVFPQ_stats.n_hamming_pass, n_hamming_pass); } template @@ -487,6 +532,29 @@ struct IVFPQScanner : IVFPQScannerT, this->pq.M, this->pq.nbits, this->sim_table, code); } + void distances_to_codes(size_t n, const uint8_t* codes, float* distances) + const override { + // Where gathers are fast (Intel), the block kernel is faster at + // M <= 64, and the per-code gather kernels are faster at M = 128 + // unless all cores are busy. + if constexpr ( + has_scalar_8bit_kernel() && + std::is_same_v) { + if (precompute_mode == 2 && + (SIMDConfig::scalar_gather || this->pq.M <= 64)) { + pq_distances_8bit_by_block( + this->pq.M, + this->sim_table, + this->dis0, + n, + codes, + distances); + return; + } + } + InvertedListScanner::distances_to_codes(n, codes, distances); + } + size_t scan_codes( size_t ncode, const uint8_t* codes, @@ -560,6 +628,13 @@ InvertedListScanner* make_IVFPQInvertedListScanner( auto with_decoder = [&]() -> InvertedListScanner* { if (ivfpq.pq.nbits == 8) { + if constexpr (has_scalar_8bit_kernel()) { + if (use_scalar_8bit_kernel(ivfpq.pq.M)) { + return make.template operator()< + PQCodeDistanceScalar8Dist, + use_sel>(); + } + } return make.template operator(), use_sel>(); } else if (ivfpq.pq.nbits == 16) { diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp index aca52cc79..167719e44 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/IVFPQ_QueryTables.cpp @@ -67,33 +67,33 @@ void QueryTables::init_query_L2() { } float QueryTables::precompute_list_tables() { - float dis0 = 0; + float local_dis0 = 0; uint64_t t0; TIC; if (by_residual) { if (metric_type == METRIC_INNER_PRODUCT) { - dis0 = precompute_list_tables_IP(); + local_dis0 = precompute_list_tables_IP(); } else { - dis0 = precompute_list_tables_L2(); + local_dis0 = precompute_list_tables_L2(); } } init_list_cycles += TOC; - return dis0; + return local_dis0; } float QueryTables::precompute_list_table_pointers() { - float dis0 = 0; + float local_dis0 = 0; uint64_t t0; TIC; if (by_residual) { if (metric_type == METRIC_INNER_PRODUCT) { FAISS_THROW_MSG("not implemented"); } else { - dis0 = precompute_list_table_pointers_L2(); + local_dis0 = precompute_list_table_pointers_L2(); } } init_list_cycles += TOC; - return dis0; + return local_dis0; } void QueryTables::init_list(idx_t list_no, float coarse_dis_in, int mode) { @@ -112,7 +112,7 @@ float QueryTables::precompute_list_tables_IP() { // and dis0, the initial value ivfpq.quantizer->reconstruct(key, decoded_vec); // decoded_vec = centroid - float dis0 = fvec_inner_product_dispatch(qi, decoded_vec, d); + float local_dis0 = fvec_inner_product_dispatch(qi, decoded_vec, d); if (polysemous_ht) { for (int i = 0; i < d; i++) { @@ -120,11 +120,11 @@ float QueryTables::precompute_list_tables_IP() { } pq.compute_code(residual_vec, q_code.data()); } - return dis0; + return local_dis0; } float QueryTables::precompute_list_tables_L2() { - float dis0 = 0; + float local_dis0 = 0; if (use_precomputed_table == 0 || use_precomputed_table == -1) { ivfpq.quantizer->compute_residual(qi, residual_vec, key); @@ -135,7 +135,7 @@ float QueryTables::precompute_list_tables_L2() { } } else if (use_precomputed_table == 1) { - dis0 = coarse_dis; + local_dis0 = coarse_dis; fvec_madd_dispatch( pq.M * pq.ksub, @@ -150,7 +150,7 @@ float QueryTables::precompute_list_tables_L2() { } } else if (use_precomputed_table == 2) { - dis0 = coarse_dis; + local_dis0 = coarse_dis; const MultiIndexQuantizer* miq = dynamic_cast(ivfpq.quantizer); @@ -188,14 +188,14 @@ float QueryTables::precompute_list_tables_L2() { } } - return dis0; + return local_dis0; } float QueryTables::precompute_list_table_pointers_L2() { - float dis0 = 0; + float local_dis0 = 0; if (use_precomputed_table == 1) { - dis0 = coarse_dis; + local_dis0 = coarse_dis; const float* s = ivfpq.precomputed_table.data() + key * pq.ksub * pq.M; for (size_t m = 0; m < pq.M; m++) { @@ -203,7 +203,7 @@ float QueryTables::precompute_list_table_pointers_L2() { s += pq.ksub; } } else if (use_precomputed_table == 2) { - dis0 = coarse_dis; + local_dis0 = coarse_dis; const MultiIndexQuantizer* miq = dynamic_cast(ivfpq.quantizer); @@ -237,7 +237,7 @@ float QueryTables::precompute_list_table_pointers_L2() { // avoid with the tables pointers. } - return dis0; + return local_dis0; } } // namespace pq_code_distance diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h b/thirdparty/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h index 787fc2363..13b72bfbc 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/PQDistanceComputer_impl.h @@ -102,6 +102,12 @@ template <> FlatCodesDistanceComputer* get_PQFlatCodesDistanceComputer( const IndexPQ& index) { if (index.pq.nbits == 8) { + if constexpr (has_scalar_8bit_kernel()) { + if (use_scalar_8bit_kernel(index.pq.M)) { + return new PQDistanceComputer< + PQCodeDistanceScalar8Dist>(index); + } + } return new PQDistanceComputer< PQCodeDistance>(index); } else if (index.pq.nbits == 16) { diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/avx2.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/avx2.cpp index b019dcaa2..eb3ca1a44 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/avx2.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #define THE_SIMD_LEVEL SIMDLevel::AVX2 // NOLINTNEXTLINE(facebook-hte-InlineHeader,facebook-unused-include-check) @@ -19,5 +17,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader,facebook-unused-include-check) #include - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/avx512.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/avx512.cpp index 74808c7a5..ba3624179 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/avx512.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/avx512.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #define THE_SIMD_LEVEL SIMDLevel::AVX512 // NOLINTNEXTLINE(facebook-hte-InlineHeader) @@ -19,5 +17,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/neon.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/neon.cpp index 84b318276..a692d0136 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/neon.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/neon.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #define THE_SIMD_LEVEL SIMDLevel::ARM_NEON // NOLINTNEXTLINE(facebook-hte-InlineHeader) @@ -19,5 +17,3 @@ #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h index 377504bb8..1252dca1b 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx2.h @@ -160,6 +160,10 @@ inline void distance_four_codes_avx2_pqdecoder8_m8( namespace faiss { namespace pq_code_distance { +// On AMD Zen 3/4/5 (SIMDConfig::scalar_gather) the scalar kernel is 0-48% +// faster than these gathers at M = 8-384; on Intel the gathers are faster. +// The callers select it with use_scalar_8bit_kernel(). + // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) template <> float pq_code_distance_8bit_single_impl( diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h index 1adb998f6..57f817ce4 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-avx512.h @@ -18,7 +18,10 @@ namespace pq_code_distance { // the AVX2 version, which is somewhat unexpected. // This version is kept for completeness. // -// TODO: test for AMD CPUs. +// On AMD Zen 4/5 (SIMDConfig::scalar_gather) the scalar kernel is up to 48% +// faster at M >= 16. Below M = 16 this kernel has no gather and its loop is +// as fast or faster, so it is kept there. The callers select the scalar +// kernel with use_scalar_8bit_kernel(). // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) template <> diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp index 6927bcee2..da4afda8f 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.cpp @@ -40,11 +40,16 @@ void pq_scan_8bit( }); } +// NONE: only the files of level SL may instantiate PQCodeDistanceScalar8. float pq_code_distance_8bit_single( size_t M, const float* sim_table, const uint8_t* code) { return with_simd_level_with_sve([&]() { + if (use_scalar_8bit_kernel(M)) { + return PQCodeDistanceScalar8::distance_single_code( + M, sim_table, code); + } return pq_code_distance_8bit_single_impl(M, sim_table, code); }); } @@ -61,6 +66,20 @@ void pq_code_distance_8bit_four( float& result2, float& result3) { with_simd_level_with_sve([&]() { + if (use_scalar_8bit_kernel(M)) { + PQCodeDistanceScalar8::distance_four_codes( + M, + sim_table, + code0, + code1, + code2, + code3, + result0, + result1, + result2, + result3); + return; + } pq_code_distance_8bit_four_impl( M, sim_table, diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h index cc8171811..09dbc0b84 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-generic.h @@ -20,8 +20,8 @@ inline float pq_code_distance_8bit_single_impl( size_t M, const float* sim_table, const uint8_t* code) { - return PQCodeDistanceScalar::distance_single_code( - M, 8, sim_table, code); + return PQCodeDistanceScalar:: + distance_single_code(M, 8, sim_table, code); } // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) @@ -37,7 +37,7 @@ inline void pq_code_distance_8bit_four_impl( float& result1, float& result2, float& result3) { - PQCodeDistanceScalar::distance_four_codes( + PQCodeDistanceScalar::distance_four_codes( M, 8, sim_table, @@ -60,8 +60,8 @@ inline float pq_code_distance_8bit_single_impl( size_t M, const float* sim_table, const uint8_t* code) { - return PQCodeDistanceScalar::distance_single_code( - M, 8, sim_table, code); + return PQCodeDistanceScalar:: + distance_single_code(M, 8, sim_table, code); } // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) @@ -77,7 +77,7 @@ inline void pq_code_distance_8bit_four_impl( float& result1, float& result2, float& result3) { - PQCodeDistanceScalar::distance_four_codes( + PQCodeDistanceScalar::distance_four_codes( M, 8, sim_table, diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h index 6cb80339d..654724174 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-inl.h @@ -23,6 +23,7 @@ #include #include #include +#include namespace faiss { namespace pq_code_distance { @@ -62,10 +63,14 @@ namespace pq_code_distance { *********************************************************************/ /// Scalar PQ code distance implementation. -/// Templated only on decoder type, independent of SIMD level. /// Used directly by non-PQDecoder8 decoders (PQDecoder16, /// PQDecoderGeneric) and as fallback for PQDecoder8 at NONE/NEON. -template +// SL keeps each SIMD-level TU's instantiation a distinct symbol. Without it +// the linker merges them and may keep one compiled with -mavx512*, which +// then runs on the AVX2 path and raises SIGILL on CPUs without AVX512. +// The default keeps callers outside faiss that name only the decoder (e.g. +// unicorn/features/encoders/PQFSTable.h) compiling; faiss passes SL itself. +template struct PQCodeDistanceScalar { using PQDecoder = PQDecoderT; @@ -124,6 +129,125 @@ struct PQCodeDistanceScalar { } }; +/// 8-bit scalar kernel with four partial sums (one running sum serializes on +/// add latency). Used instead of the gather kernels where +/// SIMDConfig::scalar_gather is set. Both functions use the same per-code +/// summation order (partial sum m % 4, tail into the first), so single-code +/// and four-code results are bit-identical. SL as in PQCodeDistanceScalar. +template +struct PQCodeDistanceScalar8 { + static constexpr size_t ksub = 256; + + static float distance_single_code( + size_t M, + const float* tab, + const uint8_t* code) { + float a[4] = {}; + size_t m = 0; + for (; m + 4 <= M; m += 4, tab += 4 * ksub) { + for (size_t j = 0; j < 4; j++) { + a[j] += tab[j * ksub + code[m + j]]; + } + } + for (; m < M; m++, tab += ksub) { + a[0] += tab[code[m]]; + } + return (a[0] + a[1]) + (a[2] + a[3]); + } + + static void distance_four_codes( + size_t M, + const float* tab, + const uint8_t* __restrict code0, + const uint8_t* __restrict code1, + const uint8_t* __restrict code2, + const uint8_t* __restrict code3, + float& result0, + float& result1, + float& result2, + float& result3) { + const uint8_t* codes[4] = {code0, code1, code2, code3}; + float a[4][4] = {}; + size_t m = 0; + for (; m + 4 <= M; m += 4, tab += 4 * ksub) { + for (size_t j = 0; j < 4; j++) { + for (size_t c = 0; c < 4; c++) { + a[c][j] += tab[j * ksub + codes[c][m + j]]; + } + } + } + for (; m < M; m++, tab += ksub) { + for (size_t c = 0; c < 4; c++) { + a[c][0] += tab[codes[c][m]]; + } + } + float* out[4] = {&result0, &result1, &result2, &result3}; + for (size_t c = 0; c < 4; c++) { + *out[c] = (a[c][0] + a[c][1]) + (a[c][2] + a[c][3]); + } + } +}; + +/// SIMDConfig::scalar_gather is set and the gather kernel of level SL is +/// slower than PQCodeDistanceScalar8: the AVX2 kernel at any M, the AVX-512 +/// kernel at M >= 16. The callers check this once per scan, not per code. +template +inline bool use_scalar_8bit_kernel(size_t M) { + if constexpr (SL == SIMDLevel::AVX2) { + return SIMDConfig::scalar_gather; + } else if constexpr (SL == SIMDLevel::AVX512) { + return SIMDConfig::scalar_gather && M >= 16; + } else { + return false; + } +} + +template +constexpr bool has_scalar_8bit_kernel() { + return SL == SIMDLevel::AVX2 || SL == SIMDLevel::AVX512; +} + +/// PQCodeDistance interface of PQCodeDistanceScalar8. +template +struct PQCodeDistanceScalar8Dist { + using PQDecoder = PQDecoder8; + static constexpr SIMDLevel simd_level = SL; + + static float distance_single_code( + size_t M, + size_t /* nbits */, + const float* sim_table, + const uint8_t* code) { + return PQCodeDistanceScalar8::distance_single_code( + M, sim_table, code); + } + + static void distance_four_codes( + size_t M, + size_t /* nbits */, + const float* sim_table, + const uint8_t* __restrict code0, + const uint8_t* __restrict code1, + const uint8_t* __restrict code2, + const uint8_t* __restrict code3, + float& result0, + float& result1, + float& result2, + float& result3) { + PQCodeDistanceScalar8::distance_four_codes( + M, + sim_table, + code0, + code1, + code2, + code3, + result0, + result1, + result2, + result3); + } +}; + /********************************************************************* * Dispatch bridge — function templates for PQDecoder8 SIMD dispatch. * @@ -168,7 +292,7 @@ struct PQCodeDistance { if constexpr (std::is_same_v) { return pq_code_distance_8bit_single_impl(M, sim_table, code); } else { - return PQCodeDistanceScalar::distance_single_code( + return PQCodeDistanceScalar::distance_single_code( M, nbits, sim_table, code); } } @@ -198,7 +322,7 @@ struct PQCodeDistance { result2, result3); } else { - PQCodeDistanceScalar::distance_four_codes( + PQCodeDistanceScalar::distance_four_codes( M, nbits, sim_table, @@ -250,8 +374,9 @@ FAISS_API void pq_code_distance_8bit_four( * * Scans all ncodes PQ codes against a precomputed distance table, * maintaining a k-nearest-neighbor heap. Uses the SIMD PQ distance - * kernels (AVX2 gathers, etc.) for the inner loop, with the SIMD - * gathers inlined into the scan loop in each per-SIMD TU. + * kernels (AVX2 gathers, etc.), or PQCodeDistanceScalar8 where + * use_scalar_8bit_kernel() selects it, inlined into the scan loop in + * each per-SIMD TU. * * Definitions are in pq_scan_impl.h (per-SIMD TUs) and * pq_code_distance-generic.cpp (dispatch wrapper). diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp index 00cf1f125..a4f9e37e4 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_code_distance-sve.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_SVE - #include #include @@ -351,5 +349,3 @@ void pq_code_distance_8bit_four_impl( // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include #undef THE_SIMD_LEVEL - -#endif // COMPILE_SIMD_ARM_SVE diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_rvv_kernel.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_rvv_kernel.h new file mode 100644 index 000000000..133e576fa --- /dev/null +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_rvv_kernel.h @@ -0,0 +1,89 @@ +/* + * 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. + */ + +#pragma once + +/* 8-bit product-quantizer code distance for RISC-V Vector. + * + * Free-standing (no exceptions, heap or threads), so a freestanding RISC-V + * target can compile it. pq_code_distance/rvv.cpp calls it; no Buck target + * here builds that RISC-V CPU path. + * + * PQDecoder8 fixes nbits = 8, so ksub = 256 and the scalar loop is + * + * for (m = 0; m < M; m++) result += sim_table[m * 256 + code[m]]; + * + * That is a gather, not a contiguous read. RVV issues one vluxei32 per strip: + * build the element offset m * 256 + code[m] across the lanes, scale it to + * bytes, then index sim_table. + * + * The offset stays inside uint32 while M * 256 * 4 bytes does. At M = 1024 + * that is 1 MiB, so no PQ shape in Faiss overflows it. + * + * The accumulator is LMUL 4, as in utils/simd_impl/distances_rvv_kernel.h. + * The lanes add the M terms in a different order than the scalar loop, so + * the last bits can differ. + */ + +#include +#include + +#include + +namespace faiss { +namespace pq_rvv_kernel { + +/// Element offsets into sim_table for subquantizers [m, m + vl). +inline vuint32m4_t row_offsets(size_t m, size_t vl) { + // (m + lane) * 256 + vuint32m4_t row = __riscv_vadd_vx_u32m4(__riscv_vid_v_u32m4(vl), m, vl); + return __riscv_vsll_vx_u32m4(row, 8, vl); +} + +/// Byte offsets for one code, given the precomputed row offsets. +inline vuint32m4_t byte_offsets( + vuint32m4_t row_off, + const uint8_t* code, + size_t m, + size_t vl) { + vuint8m1_t cb = __riscv_vle8_v_u8m1(code + m, vl); + vuint32m4_t idx = __riscv_vzext_vf4_u32m4(cb, vl); + // (row + code) * sizeof(float) + return __riscv_vsll_vx_u32m4( + __riscv_vadd_vv_u32m4(row_off, idx, vl), 2, vl); +} + +inline float reduce(vfloat32m4_t acc, size_t vlmax) { + vfloat32m1_t zero = __riscv_vfmv_v_f_f32m1(0.0f, 1); + vfloat32m1_t sum = __riscv_vfredusum_vs_f32m4_f32m1(acc, zero, vlmax); + return __riscv_vfmv_f_s_f32m1_f32(sum); +} + +/// Distance between a query and one 8-bit PQ code. +/// @param sim_table M * 256 floats, laid out (M, ksub) +inline float distance_8bit( + size_t M, + const float* sim_table, + const uint8_t* code) { + const size_t vlmax = __riscv_vsetvlmax_e32m4(); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + + size_t m = 0; + while (m < M) { + const size_t vl = __riscv_vsetvl_e32m4(M - m); + vuint32m4_t off = byte_offsets(row_offsets(m, vl), code, m, vl); + vfloat32m4_t v = __riscv_vluxei32_v_f32m4(sim_table, off, vl); + // Tail-undisturbed: lanes past vl keep earlier partial sums, and the + // final reduction covers vlmax. + acc = __riscv_vfadd_vv_f32m4_tu(acc, acc, v, vl); + m += vl; + } + return reduce(acc, vlmax); +} + +} // namespace pq_rvv_kernel +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h index b14ac13a9..ee1cb9e44 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/pq_scan_impl.h @@ -19,7 +19,7 @@ namespace pq_code_distance { namespace { -template +template void pq_scan_8bit_at_level( size_t M, const float* dis_table, @@ -33,8 +33,9 @@ void pq_scan_8bit_at_level( size_t j = 0; for (; j + 3 < ncodes; j += 4) { float d0, d1, d2, d3; - pq_code_distance_8bit_four_impl( // NOLINT(facebook-modularize-issue-check) + PQCodeDist::distance_four_codes( M, + 8, dis_table, codes + j * code_size, codes + (j + 1) * code_size, @@ -60,8 +61,8 @@ void pq_scan_8bit_at_level( } for (; j < ncodes; j++) { - float dis = pq_code_distance_8bit_single_impl( // NOLINT(facebook-modularize-issue-check) - M, dis_table, codes + j * code_size); + float dis = PQCodeDist::distance_single_code( + M, 8, dis_table, codes + j * code_size); if (C::cmp(heap_dis[0], dis)) { heap_replace_top(k, heap_dis, heap_ids, dis, j); } @@ -92,13 +93,23 @@ void pq_scan_8bit_impl( float* heap_dis, int64_t* heap_ids, bool max_heap) { - if (max_heap) { - pq_scan_8bit_at_level>( - M, dis_table, codes, ncodes, k, heap_dis, heap_ids); - } else { - pq_scan_8bit_at_level>( - M, dis_table, codes, ncodes, k, heap_dis, heap_ids); + auto scan = [&]() { + if (max_heap) { + pq_scan_8bit_at_level, PQCodeDist>( + M, dis_table, codes, ncodes, k, heap_dis, heap_ids); + } else { + pq_scan_8bit_at_level, PQCodeDist>( + M, dis_table, codes, ncodes, k, heap_dis, heap_ids); + } + }; + if constexpr (has_scalar_8bit_kernel()) { + if (use_scalar_8bit_kernel(M)) { + scan.template + operator()>(); + return; + } } + scan.template operator()>(); } } // namespace pq_code_distance diff --git a/thirdparty/faiss/faiss/impl/pq_code_distance/rvv.cpp b/thirdparty/faiss/faiss/impl/pq_code_distance/rvv.cpp index 8bad873f7..5f484ba7b 100644 --- a/thirdparty/faiss/faiss/impl/pq_code_distance/rvv.cpp +++ b/thirdparty/faiss/faiss/impl/pq_code_distance/rvv.cpp @@ -5,14 +5,15 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_RISCV_RVV +#include #include +#include namespace faiss { namespace pq_code_distance { -// RISCV_RVV: no RVV-optimized PQ code distance exists yet. Use scalar. +// The kernel lives in pq_rvv_kernel.h. See that header for the gather layout. // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) template <> @@ -20,8 +21,7 @@ float pq_code_distance_8bit_single_impl( size_t M, const float* sim_table, const uint8_t* code) { - return PQCodeDistanceScalar::distance_single_code( - M, 8, sim_table, code); + return pq_rvv_kernel::distance_8bit(M, sim_table, code); } // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) @@ -37,18 +37,47 @@ void pq_code_distance_8bit_four_impl( float& result1, float& result2, float& result3) { - PQCodeDistanceScalar::distance_four_codes( - M, - 8, - sim_table, - code0, - code1, - code2, - code3, - result0, - result1, - result2, - result3); + const size_t vlmax = __riscv_vsetvlmax_e32m4(); + vfloat32m4_t acc0 = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + vfloat32m4_t acc1 = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + vfloat32m4_t acc2 = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + vfloat32m4_t acc3 = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + + size_t m = 0; + while (m < M) { + const size_t vl = __riscv_vsetvl_e32m4(M - m); + // The row term is the same for all four codes, so compute it once. + vuint32m4_t row_off = pq_rvv_kernel::row_offsets(m, vl); + + vfloat32m4_t v0 = __riscv_vluxei32_v_f32m4( + sim_table, + pq_rvv_kernel::byte_offsets(row_off, code0, m, vl), + vl); + vfloat32m4_t v1 = __riscv_vluxei32_v_f32m4( + sim_table, + pq_rvv_kernel::byte_offsets(row_off, code1, m, vl), + vl); + vfloat32m4_t v2 = __riscv_vluxei32_v_f32m4( + sim_table, + pq_rvv_kernel::byte_offsets(row_off, code2, m, vl), + vl); + vfloat32m4_t v3 = __riscv_vluxei32_v_f32m4( + sim_table, + pq_rvv_kernel::byte_offsets(row_off, code3, m, vl), + vl); + + acc0 = __riscv_vfadd_vv_f32m4_tu(acc0, acc0, v0, vl); + acc1 = __riscv_vfadd_vv_f32m4_tu(acc1, acc1, v1, vl); + acc2 = __riscv_vfadd_vv_f32m4_tu(acc2, acc2, v2, vl); + acc3 = __riscv_vfadd_vv_f32m4_tu(acc3, acc3, v3, vl); + + m += vl; + } + + result0 = pq_rvv_kernel::reduce(acc0, vlmax); + result1 = pq_rvv_kernel::reduce(acc1, vlmax); + result2 = pq_rvv_kernel::reduce(acc2, vlmax); + result3 = pq_rvv_kernel::reduce(acc3, vlmax); } } // namespace pq_code_distance @@ -66,5 +95,3 @@ void pq_code_distance_8bit_four_impl( #include #undef THE_SIMD_LEVEL - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/impl/residual_quantizer_encode_steps.cpp b/thirdparty/faiss/faiss/impl/residual_quantizer_encode_steps.cpp index 85310a61a..cb153a63a 100644 --- a/thirdparty/faiss/faiss/impl/residual_quantizer_encode_steps.cpp +++ b/thirdparty/faiss/faiss/impl/residual_quantizer_encode_steps.cpp @@ -17,6 +17,7 @@ #include #include +#include extern "C" { @@ -367,7 +368,7 @@ void beam_search_encode_step_tab( // Resolve SIMD level once, not per iteration of the n-parallel loop. with_simd_level_256bit([&]() { -#pragma omp parallel for if (n > 100) schedule(dynamic) +#pragma omp parallel for if (n > 100) schedule(FAISS_OMP_DYNAMIC) for (int64_t i = 0; i < static_cast(n); i++) { std::vector cent_distances(beam_size * K); std::vector cd_common(K); diff --git a/thirdparty/faiss/faiss/impl/result_handler/ResultHandler.cpp b/thirdparty/faiss/faiss/impl/result_handler/ResultHandler.cpp index c7f491470..b64b3e738 100644 --- a/thirdparty/faiss/faiss/impl/result_handler/ResultHandler.cpp +++ b/thirdparty/faiss/faiss/impl/result_handler/ResultHandler.cpp @@ -22,6 +22,12 @@ namespace faiss { constexpr int TOP1_SIMD_LEVELS = (1 << int(SIMDLevel::NONE)) | (1 << int(SIMDLevel::AVX2)) | (1 << int(SIMDLevel::AVX512)); +// Top-2: scalar fallback + AVX2 (8 lanes of best and second best), for CMax +// only: the AVX2 lanes keep the first of equal distances, which matches the +// CMax order of ids but not the CMin one. +constexpr int TOP2_SIMD_LEVELS = + (1 << int(SIMDLevel::NONE)) | (1 << int(SIMDLevel::AVX2)); + // Reservoir: scalar fallback + AVX512 compress path. // VPCOMPRESSPS/VPCOMPRESSD require AVX512F so there is no AVX2 path. // On non-AVX512 hosts the dispatch falls back to NONE automatically. @@ -63,6 +69,26 @@ void top1_add_results_none( } } +template +void top2_add_results_none( + Top2BlockResultHandler* self, + size_t j0, + size_t j1, + const float* dis_tab_in) { + using TI = typename C::TI; +#pragma omp parallel for if (self->i1 - self->i0 >= 16) + for (int64_t qi = self->i0; qi < static_cast(self->i1); qi++) { + const float* dis_tab_i = dis_tab_in + (j1 - j0) * (qi - self->i0) - j0; + float* dis2 = self->dis_tab + 2 * qi; + TI* ids2 = self->ids_tab + 2 * qi; + for (size_t j = j0; j < j1; j++) { + if (C::cmp(dis2[1], dis_tab_i[j]) && self->is_in_selection(j)) { + top2_insert(dis_tab_i[j], TI(j), dis2, ids2); + } + } + } +} + template void reservoir_add_results_none( ReservoirBlockResultHandler* self, @@ -119,6 +145,14 @@ void reservoir_add_results_none( top1_add_results_none(self, j0, j1, dis_tab); \ } \ template <> \ + void top2_add_results_tpl( \ + Top2BlockResultHandler * self, \ + size_t j0, \ + size_t j1, \ + const float* dis_tab) { \ + top2_add_results_none(self, j0, j1, dis_tab); \ + } \ + template <> \ void reservoir_add_results_tpl( \ ReservoirBlockResultHandler * self, \ size_t j0, \ @@ -152,6 +186,21 @@ void Top1BlockResultHandler::add_results( }); } +template +void Top2BlockResultHandler::add_results( + size_t j0, + size_t j1, + const T* dis_tab_2) { + if constexpr (use_sel || !C::is_max) { + top2_add_results_tpl( + this, j0, j1, dis_tab_2); + } else { + with_selected_simd_levels([&]() { + top2_add_results_tpl(this, j0, j1, dis_tab_2); + }); + } +} + template void ReservoirBlockResultHandler::add_results( size_t j0, @@ -183,6 +232,23 @@ template void Top1BlockResultHandler, true>::add_results( size_t, const float*); +template void Top2BlockResultHandler, false>::add_results( + size_t, + size_t, + const float*); +template void Top2BlockResultHandler, true>::add_results( + size_t, + size_t, + const float*); +template void Top2BlockResultHandler, false>::add_results( + size_t, + size_t, + const float*); +template void Top2BlockResultHandler, true>::add_results( + size_t, + size_t, + const float*); + template void ReservoirBlockResultHandler, false>:: add_results(size_t, size_t, const float*); template void ReservoirBlockResultHandler, true>:: diff --git a/thirdparty/faiss/faiss/impl/result_handler/avx2.cpp b/thirdparty/faiss/faiss/impl/result_handler/avx2.cpp index 27c9bf946..f52d23586 100644 --- a/thirdparty/faiss/faiss/impl/result_handler/avx2.cpp +++ b/thirdparty/faiss/faiss/impl/result_handler/avx2.cpp @@ -5,11 +5,10 @@ * LICENSE file in the root directory of this source tree. */ -// AVX2 specialisation of Top1 add_results (8-wide branchless argmin/argmax). +// AVX2 specialisations of Top1 add_results (8-wide branchless argmin/argmax) +// and Top2 add_results for CMax (8 lanes of best and second best). // Reservoir stays on the NONE path — VPCOMPRESSPS requires AVX512F. -#ifdef COMPILE_SIMD_AVX2 - #include #include @@ -88,10 +87,76 @@ void top1_add_results_avx2( } } +/// AVX2 Top2 add_results for L2: each lane keeps its best and second best +/// with strict comparisons (the first of equal distances, NaN never), then +/// the lanes and the tail are merged into the query's pair, lower id first. +template +void top2_add_results_avx2( + Top2BlockResultHandler* self, + size_t j0, + size_t j1, + const float* dis_tab_in) { + using TI = typename C::TI; + const size_t n = j1 - j0; +#pragma omp parallel for if (self->i1 - self->i0 >= 16) + for (int64_t qi = self->i0; qi < static_cast(self->i1); qi++) { + const float* dis_tab_i = dis_tab_in + n * (qi - self->i0); + float* dis2 = self->dis_tab + 2 * qi; + TI* ids2 = self->ids_tab + 2 * qi; + __m256 m1 = _mm256_set1_ps(C::neutral()), m2 = m1; + __m256i a1 = _mm256_set1_epi32(-1), a2 = a1; + __m256i current = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7); + size_t j = 0; + for (; j + 8 <= n; j += 8) { + const __m256 s = _mm256_loadu_ps(dis_tab_i + j); + const __m256 first = _mm256_cmp_ps(s, m1, _CMP_LT_OQ); + const __m256 second = _mm256_cmp_ps(s, m2, _CMP_LT_OQ); + m2 = _mm256_min_ps(_mm256_max_ps(m1, s), m2); + m1 = _mm256_min_ps(s, m1); + const __m256 offered = _mm256_blendv_ps( + _mm256_castsi256_ps(current), + _mm256_castsi256_ps(a1), + first); + a2 = _mm256_castps_si256( + _mm256_blendv_ps(_mm256_castsi256_ps(a2), offered, second)); + a1 = _mm256_castps_si256(_mm256_blendv_ps( + _mm256_castsi256_ps(a1), + _mm256_castsi256_ps(current), + first)); + current = _mm256_add_epi32(current, _mm256_set1_epi32(8)); + } + alignas(32) float lane_dis[16]; + alignas(32) int32_t lane_ids[16]; + _mm256_store_ps(lane_dis, m1); + _mm256_store_ps(lane_dis + 8, m2); + _mm256_store_si256((__m256i*)lane_ids, a1); + _mm256_store_si256((__m256i*)(lane_ids + 8), a2); + for (int l = 0; l < 16; l++) { + if (lane_ids[l] >= 0) { + top2_insert(lane_dis[l], TI(j0 + lane_ids[l]), dis2, ids2); + } + } + for (; j < n; j++) { + if (C::cmp(dis2[1], dis_tab_i[j])) { + top2_insert(dis_tab_i[j], TI(j0 + j), dis2, ids2); + } + } + } +} + } // namespace // Explicit specialisations for AVX2 +template <> +void top2_add_results_tpl, false, SIMDLevel::AVX2>( + Top2BlockResultHandler, false>* self, + size_t j0, + size_t j1, + const float* dis_tab) { + top2_add_results_avx2>(self, j0, j1, dis_tab); +} + template <> void top1_add_results_tpl, false, SIMDLevel::AVX2>( Top1BlockResultHandler, false>* self, @@ -129,5 +194,3 @@ void top1_add_results_tpl, true, SIMDLevel::AVX2>( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/result_handler/avx512.cpp b/thirdparty/faiss/faiss/impl/result_handler/avx512.cpp index 4bcdc74a6..679bd40ac 100644 --- a/thirdparty/faiss/faiss/impl/result_handler/avx512.cpp +++ b/thirdparty/faiss/faiss/impl/result_handler/avx512.cpp @@ -11,8 +11,6 @@ // Reservoir: VPCOMPRESSPS / VPCOMPRESSD bulk-insert of passing elements, // eliminating the per-element threshold branch entirely. -#ifdef COMPILE_SIMD_AVX512 - #include #include @@ -277,5 +275,3 @@ void reservoir_add_results_tpl, true, SIMDLevel::AVX512>( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp index cbcf21114..edeedf50c 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #include #include @@ -68,5 +66,3 @@ void compute_code_dot_lut_batch_8_avx2( } // namespace eden_distance } // namespace faiss - -#endif diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp index e15003b08..77659d9e0 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer-avx512.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #include #include #include @@ -224,5 +222,3 @@ void compute_code_dot_lut_batch_16_avx512( } // namespace eden_distance } // namespace faiss - -#endif diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp index 99a817a4a..654ab1797 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/EDENQuantizer.cpp @@ -508,7 +508,7 @@ EDENFlatCodesDistanceComputer* make_reference_distance_computer( return dc.release(); } -EDENFlatCodesDistanceComputer* make_optimized_distance_computer( +[[maybe_unused]] EDENFlatCodesDistanceComputer* make_optimized_distance_computer( MetricType metric_type, size_t d, size_t nb_bits, diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/distance_computers.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/distance_computers.h index fb625861f..2e299aaf9 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/distance_computers.h +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/distance_computers.h @@ -22,7 +22,11 @@ using SQDistanceComputer = ScalarQuantizer::SQDistanceComputer; * code-to-vector or code-to-code comparisons *******************************************************************/ -template +template < + class Quantizer, + class Similarity, + SIMDLevel SL, + bool four_acc = false> struct DCTemplate : SQDistanceComputer {}; template diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/quantizers.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/quantizers.h index 393983de9..59442f4eb 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/quantizers.h +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/quantizers.h @@ -149,11 +149,11 @@ struct QuantizerTemplate< /******************************************************************* * Lloyd-Max scalar quantizer *******************************************************************/ +// Each QuantizerXBase holds the scalar code of a quantizer. It takes the +// SIMD level of the file that uses it, so each per-level file compiles its own +// copy under its own name. template -struct QuantizerLloydMax; - -template -struct QuantizerLloydMax : ScalarQuantizer::SQuantizer { +struct QuantizerLloydMaxBase : ScalarQuantizer::SQuantizer { static_assert(NBits >= 1 && NBits <= 8); static constexpr size_t kCentroidsCount = size_t(1) << NBits; @@ -164,7 +164,7 @@ struct QuantizerLloydMax : ScalarQuantizer::SQuantizer { const float* centroids; const float* boundaries; - QuantizerLloydMax(size_t d_in, const std::vector& trained) + QuantizerLloydMaxBase(size_t d_in, const std::vector& trained) : d(d_in), centroids(nullptr), boundaries(nullptr) { FAISS_THROW_IF_NOT(trained.size() == 2 * kCentroidsCount - 1); centroids = trained.data(); @@ -220,8 +220,8 @@ struct QuantizerLloydMax : ScalarQuantizer::SQuantizer { }; template -struct QuantizerLloydMax : QuantizerLloydMax { - using QuantizerLloydMax::QuantizerLloydMax; +struct QuantizerLloydMax : QuantizerLloydMaxBase { + using QuantizerLloydMaxBase::QuantizerLloydMaxBase; }; template @@ -232,13 +232,10 @@ using QuantizerTurboQuantMSE = QuantizerLloydMax; *******************************************************************/ template -struct QuantizerFP16; - -template <> -struct QuantizerFP16 : ScalarQuantizer::SQuantizer { +struct QuantizerFP16Base : ScalarQuantizer::SQuantizer { const size_t d; - QuantizerFP16(size_t d_in, const std::vector& /* unused */) + QuantizerFP16Base(size_t d_in, const std::vector& /* unused */) : d(d_in) {} void encode_vector(const float* x, uint8_t* code) const final { @@ -247,7 +244,7 @@ struct QuantizerFP16 : ScalarQuantizer::SQuantizer { } } - void decode_vector(const uint8_t* code, float* x) const final { + void decode_vector(const uint8_t* code, float* x) const override { for (size_t i = 0; i < d; i++) { x[i] = decode_fp16(((uint16_t*)code)[i]); } @@ -261,8 +258,8 @@ struct QuantizerFP16 : ScalarQuantizer::SQuantizer { }; template -struct QuantizerFP16 : QuantizerFP16 { - using QuantizerFP16::QuantizerFP16; +struct QuantizerFP16 : QuantizerFP16Base { + using QuantizerFP16Base::QuantizerFP16Base; }; /******************************************************************* @@ -270,13 +267,10 @@ struct QuantizerFP16 : QuantizerFP16 { *******************************************************************/ template -struct QuantizerBF16; - -template <> -struct QuantizerBF16 : ScalarQuantizer::SQuantizer { +struct QuantizerBF16Base : ScalarQuantizer::SQuantizer { const size_t d; - QuantizerBF16(size_t d_in, const std::vector& /* unused */) + QuantizerBF16Base(size_t d_in, const std::vector& /* unused */) : d(d_in) {} void encode_vector(const float* x, uint8_t* code) const override { @@ -295,8 +289,8 @@ struct QuantizerBF16 : ScalarQuantizer::SQuantizer { }; template -struct QuantizerBF16 : QuantizerBF16 { - using QuantizerBF16::QuantizerBF16; +struct QuantizerBF16 : QuantizerBF16Base { + using QuantizerBF16Base::QuantizerBF16Base; }; template <> @@ -309,22 +303,19 @@ struct QuantizerBF16; *******************************************************************/ template -struct Quantizer8bitDirect; - -template <> -struct Quantizer8bitDirect : ScalarQuantizer::SQuantizer { +struct Quantizer8bitDirectBase : ScalarQuantizer::SQuantizer { const size_t d; - Quantizer8bitDirect(size_t d_in, const std::vector& /* unused */) + Quantizer8bitDirectBase(size_t d_in, const std::vector& /* unused */) : d(d_in) {} - void encode_vector(const float* x, uint8_t* code) const final { + void encode_vector(const float* x, uint8_t* code) const override { for (size_t i = 0; i < d; i++) { code[i] = (uint8_t)x[i]; } } - void decode_vector(const uint8_t* code, float* x) const final { + void decode_vector(const uint8_t* code, float* x) const override { for (size_t i = 0; i < d; i++) { x[i] = code[i]; } @@ -338,8 +329,8 @@ struct Quantizer8bitDirect : ScalarQuantizer::SQuantizer { }; template -struct Quantizer8bitDirect : Quantizer8bitDirect { - using Quantizer8bitDirect::Quantizer8bitDirect; +struct Quantizer8bitDirect : Quantizer8bitDirectBase { + using Quantizer8bitDirectBase::Quantizer8bitDirectBase; }; /******************************************************************* @@ -347,14 +338,10 @@ struct Quantizer8bitDirect : Quantizer8bitDirect { *******************************************************************/ template -struct Quantizer8bitDirectSigned; - -template <> -struct Quantizer8bitDirectSigned - : ScalarQuantizer::SQuantizer { +struct Quantizer8bitDirectSignedBase : ScalarQuantizer::SQuantizer { const size_t d; - Quantizer8bitDirectSigned( + Quantizer8bitDirectSignedBase( size_t d_in, const std::vector& /* unused */) : d(d_in) {} @@ -365,7 +352,7 @@ struct Quantizer8bitDirectSigned } } - void decode_vector(const uint8_t* code, float* x) const final { + void decode_vector(const uint8_t* code, float* x) const override { for (size_t i = 0; i < d; i++) { x[i] = code[i] - 128; } @@ -379,8 +366,8 @@ struct Quantizer8bitDirectSigned }; template -struct Quantizer8bitDirectSigned : Quantizer8bitDirectSigned { - using Quantizer8bitDirectSigned::Quantizer8bitDirectSigned; +struct Quantizer8bitDirectSigned : Quantizer8bitDirectSignedBase { + using Quantizer8bitDirectSignedBase::Quantizer8bitDirectSignedBase; }; /******************************************************************* @@ -403,11 +390,7 @@ struct SQTurboQFactors { FAISS_PACK_STRUCTS_END template -struct QuantizerTurboQuantFull; - -template -struct QuantizerTurboQuantFull - : ScalarQuantizer::SQuantizer { +struct QuantizerTurboQuantFull : ScalarQuantizer::SQuantizer { static_assert(NBits >= 2 && NBits <= 5); static constexpr int kMSEBits = NBits - 1; @@ -658,13 +641,6 @@ struct QuantizerTurboQuantFull } }; -template -struct QuantizerTurboQuantFull - : QuantizerTurboQuantFull { - using QuantizerTurboQuantFull:: - QuantizerTurboQuantFull; -}; - /******************************************************************* * Selection function *******************************************************************/ diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/scanners.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/scanners.h index cb4ec60bb..b91f5d6e9 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/scanners.h +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/scanners.h @@ -63,14 +63,14 @@ struct IVFSQScannerIP : InvertedListScanner { IVFSQScannerIP( int d, const std::vector& trained, - size_t code_size, - bool store_pairs, - const IDSelector* sel, - bool by_residual) - : dc(d, trained), by_residual(by_residual), accu0(0) { - this->store_pairs = store_pairs; - this->sel = sel; - this->code_size = code_size; + size_t code_size_in, + bool store_pairs_in, + const IDSelector* sel_in, + bool by_residual_in) + : dc(d, trained), by_residual(by_residual_in), accu0(0) { + this->store_pairs = store_pairs_in; + this->sel = sel_in; + this->code_size = code_size_in; this->keep_max = true; } @@ -78,8 +78,8 @@ struct IVFSQScannerIP : InvertedListScanner { dc.set_query(query); } - void set_list(idx_t list_no, float coarse_dis) override { - this->list_no = list_no; + void set_list(idx_t list_no_in, float coarse_dis) override { + this->list_no = list_no_in; accu0 = by_residual ? coarse_dis : 0; } @@ -132,19 +132,19 @@ struct IVFSQScannerL2 : InvertedListScanner { IVFSQScannerL2( int d, const std::vector& trained, - size_t code_size, - const Index* quantizer, - bool store_pairs, - const IDSelector* sel, - bool by_residual) + size_t code_size_in, + const Index* quantizer_in, + bool store_pairs_in, + const IDSelector* sel_in, + bool by_residual_in) : dc(d, trained), - by_residual(by_residual), - quantizer(quantizer), + by_residual(by_residual_in), + quantizer(quantizer_in), x(nullptr), tmp(d) { - this->store_pairs = store_pairs; - this->sel = sel; - this->code_size = code_size; + this->store_pairs = store_pairs_in; + this->sel = sel_in; + this->code_size = code_size_in; } void set_query(const float* query) override { @@ -154,10 +154,10 @@ struct IVFSQScannerL2 : InvertedListScanner { } } - void set_list(idx_t list_no, float /*coarse_dis*/) override { - this->list_no = list_no; + void set_list(idx_t list_no_in, float /*coarse_dis*/) override { + this->list_no = list_no_in; if (by_residual) { - quantizer->compute_residual(x, tmp.data(), list_no); + quantizer->compute_residual(x, tmp.data(), list_no_in); dc.set_query(tmp.data()); } else { dc.set_query(x); @@ -219,23 +219,18 @@ struct IVFCoarseDistanceScanner : InvertedListScanner { IVFCoarseDistanceScanner( bool is_similarity, - bool store_pairs, - const IDSelector* sel) - : InvertedListScanner(store_pairs, sel) { + bool store_pairs_in, + const IDSelector* sel_in) + : InvertedListScanner(store_pairs_in, sel_in) { code_size = 0; keep_max = is_similarity; } void set_query(const float* /*query_vector*/) override {} - void set_list(idx_t list_no_in, float coarse_dis_in) override { - this->list_no = list_no_in; - this->coarse_dis = coarse_dis_in; - } + void set_list(idx_t list_no_in, float coarse_dis_in) override; - float distance_to_code(const uint8_t* /*code*/) const override { - return coarse_dis; - } + float distance_to_code(const uint8_t* /*code*/) const override; }; } // namespace scalar_quantizer diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp index ea9c37b3a..d610ef550 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #include #include @@ -16,6 +14,8 @@ #include #include #include +#include +#include namespace faiss { @@ -182,12 +182,12 @@ struct QuantizerTemplate< Codec, QuantizerTemplateScaling::UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, QuantizerTemplateScaling::UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 8 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -213,12 +213,12 @@ struct QuantizerTemplate< Codec, QuantizerTemplateScaling::NON_UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 8 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -236,17 +236,18 @@ struct QuantizerTemplate< **********************************************************/ // 1-bit MSE: boundary is always at centroids midpoint. -// Encode: 8 comparisons → 1 byte via movemask. +// Encode: 8 comparisons → 1 byte via movemask. NLT_UQ is !(x < b), matching +// the scalar upper_bound tie-break: x == b (and NaN) encodes to the upper bin. // Decode: gather 8 centroids via index unpack. // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization,facebook-hte-ShadowingClass) template <> struct QuantizerLloydMax<1, SIMDLevel::AVX2> - : QuantizerLloydMax<1, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<1, SIMDLevel::NONE>; + : QuantizerLloydMaxBase<1, SIMDLevel::AVX2> { + using Base = QuantizerLloydMaxBase<1, SIMDLevel::AVX2>; - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 8 == 0); + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -260,7 +261,7 @@ struct QuantizerLloydMax<1, SIMDLevel::AVX2> for (size_t i = 0; i < this->d; i += 8) { __m256 vals = _mm256_loadu_ps(x + i); int mask = _mm256_movemask_ps( - _mm256_cmp_ps(vals, boundary, _CMP_GT_OQ)); + _mm256_cmp_ps(vals, boundary, _CMP_NLT_UQ)); code[i / 8] = static_cast(mask); } } @@ -280,12 +281,12 @@ struct QuantizerLloydMax<1, SIMDLevel::AVX2> // NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization,facebook-hte-ShadowingClass) template <> struct QuantizerLloydMax<2, SIMDLevel::AVX2> - : QuantizerLloydMax<2, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<2, SIMDLevel::NONE>; + : QuantizerLloydMaxBase<2, SIMDLevel::AVX2> { + using Base = QuantizerLloydMaxBase<2, SIMDLevel::AVX2>; - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 8 == 0); + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -295,7 +296,8 @@ struct QuantizerLloydMax<2, SIMDLevel::AVX2> } void encode_vector(const float* x, uint8_t* code) const final { - // 3 boundaries → branchless: idx = (x>b0) + (x>b1) + (x>b2) + // 3 boundaries → branchless: idx = !(xboundaries[0]); @@ -303,16 +305,16 @@ struct QuantizerLloydMax<2, SIMDLevel::AVX2> __m256 b2 = _mm256_set1_ps(this->boundaries[2]); for (size_t i = 0; i < this->d; i += 8) { __m256 vals = _mm256_loadu_ps(x + i); - __m256i gt0 = - _mm256_castps_si256(_mm256_cmp_ps(vals, b0, _CMP_GT_OQ)); - __m256i gt1 = - _mm256_castps_si256(_mm256_cmp_ps(vals, b1, _CMP_GT_OQ)); - __m256i gt2 = - _mm256_castps_si256(_mm256_cmp_ps(vals, b2, _CMP_GT_OQ)); - // Each gt is 0 or -1 (0xFFFFFFFF). Sum = -(index). + __m256i ge0 = + _mm256_castps_si256(_mm256_cmp_ps(vals, b0, _CMP_NLT_UQ)); + __m256i ge1 = + _mm256_castps_si256(_mm256_cmp_ps(vals, b1, _CMP_NLT_UQ)); + __m256i ge2 = + _mm256_castps_si256(_mm256_cmp_ps(vals, b2, _CMP_NLT_UQ)); + // Each ge is 0 or -1 (0xFFFFFFFF). Sum = -(index). __m256i idx = _mm256_sub_epi32( _mm256_setzero_si256(), - _mm256_add_epi32(_mm256_add_epi32(gt0, gt1), gt2)); + _mm256_add_epi32(_mm256_add_epi32(ge0, ge1), ge2)); // Pack 8 x 2-bit indices into 2 bytes. // Store to temp array and pack scalarly - faster than // extract+permute. @@ -339,12 +341,12 @@ struct QuantizerLloydMax<2, SIMDLevel::AVX2> #define DEFINE_LLOYD_MAX_AVX2_MULTIBIT(NBITS, UNPACK_EXPR) \ template <> \ struct QuantizerLloydMax \ - : QuantizerLloydMax { \ - using Base = QuantizerLloydMax; \ + : QuantizerLloydMaxBase { \ + using Base = QuantizerLloydMaxBase; \ \ - QuantizerLloydMax(size_t d, const std::vector& trained) \ - : Base(d, trained) { \ - assert(d % 8 == 0); \ + QuantizerLloydMax(size_t d_in, const std::vector& trained) \ + : Base(d_in, trained) { \ + assert(d_in % 8 == 0); \ } \ \ FAISS_ALWAYS_INLINE simd8float32 \ @@ -370,12 +372,12 @@ DEFINE_LLOYD_MAX_AVX2_MULTIBIT(4, unpack_8x4bit_to_u32(code, i)); // 8-bit Lloyd-Max: indices are raw bytes, no bit packing. template <> struct QuantizerLloydMax<8, SIMDLevel::AVX2> - : QuantizerLloydMax<8, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<8, SIMDLevel::NONE>; + : QuantizerLloydMaxBase<8, SIMDLevel::AVX2> { + using Base = QuantizerLloydMaxBase<8, SIMDLevel::AVX2>; - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 8 == 0); + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -401,10 +403,10 @@ struct QuantizerLloydMax<8, SIMDLevel::AVX2> **********************************************************/ template <> -struct QuantizerFP16 : QuantizerFP16 { - QuantizerFP16(size_t d, const std::vector& trained) - : QuantizerFP16(d, trained) { - assert(d % 8 == 0); +struct QuantizerFP16 : QuantizerFP16Base { + QuantizerFP16(size_t d_in, const std::vector& trained) + : QuantizerFP16Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -419,10 +421,10 @@ struct QuantizerFP16 : QuantizerFP16 { **********************************************************/ template <> -struct QuantizerBF16 : QuantizerBF16 { - QuantizerBF16(size_t d, const std::vector& trained) - : QuantizerBF16(d, trained) { - assert(d % 8 == 0); +struct QuantizerBF16 : QuantizerBF16Base { + QuantizerBF16(size_t d_in, const std::vector& trained) + : QuantizerBF16Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -440,10 +442,10 @@ struct QuantizerBF16 : QuantizerBF16 { template <> struct Quantizer8bitDirect - : Quantizer8bitDirect { - Quantizer8bitDirect(size_t d, const std::vector& trained) - : Quantizer8bitDirect(d, trained) { - assert(d % 8 == 0); + : Quantizer8bitDirectBase { + Quantizer8bitDirect(size_t d_in, const std::vector& trained) + : Quantizer8bitDirectBase(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -460,10 +462,10 @@ struct Quantizer8bitDirect template <> struct Quantizer8bitDirectSigned - : Quantizer8bitDirectSigned { - Quantizer8bitDirectSigned(size_t d, const std::vector& trained) - : Quantizer8bitDirectSigned(d, trained) { - assert(d % 8 == 0); + : Quantizer8bitDirectSignedBase { + Quantizer8bitDirectSigned(size_t d_in, const std::vector& trained) + : Quantizer8bitDirectSignedBase(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -488,7 +490,7 @@ struct SimilarityL2 { const float *y, *yi; - explicit SimilarityL2(const float* y) : y(y), yi(nullptr) {} + explicit SimilarityL2(const float* y_in) : y(y_in), yi(nullptr) {} simd8float32 accu8 = {}; FAISS_ALWAYS_INLINE void begin_8() { @@ -548,7 +550,7 @@ struct SimilarityIP { float accu; - explicit SimilarityIP(const float* y) : y(y), yi(nullptr), accu(0) {} + explicit SimilarityIP(const float* y_in) : y(y_in), yi(nullptr), accu(0) {} simd8float32 accu8 = {}; @@ -602,8 +604,18 @@ struct SimilarityIP { * Distance computers **********************************************************/ -template -struct DCTemplate : SQDistanceComputer { +namespace { + +/// 8 lanes to 4: lanes j and j + 4 summed into lane j. +FAISS_ALWAYS_INLINE __m128 reduce_8_to_4(__m256 a) { + return _mm_add_ps(_mm256_castps256_ps128(a), _mm256_extractf128_ps(a, 1)); +} + +} // namespace + +template +struct DCTemplate + : SQDistanceComputer { using Sim = Similarity; Quantizer quant; @@ -626,7 +638,40 @@ struct DCTemplate : SQDistanceComputer { } } + /// Similarity terms of one code with four accumulators. + FAISS_ALWAYS_INLINE __m256 + accumulate_4(const float* x, const uint8_t* code) const { + struct Acc : Similarity { + Acc() : Similarity(nullptr) {} + }; + Acc s[4]; + for (int j = 0; j < 4; j++) { + s[j].begin_8(); + } + const size_t d = quant.d; + size_t i = 0; + for (; i + 32 <= d; i += 32) { + for (int j = 0; j < 4; j++) { + s[j].add_8_components_2( + quant.reconstruct_8_components( + code, static_cast(i + 8 * j)), + simd8float32(x + i + 8 * j)); + } + } + for (; i < d; i += 8) { + s[0].add_8_components_2( + quant.reconstruct_8_components(code, static_cast(i)), + simd8float32(x + i)); + } + return _mm256_add_ps( + _mm256_add_ps(s[0].accu8.f, s[1].accu8.f), + _mm256_add_ps(s[2].accu8.f, s[3].accu8.f)); + } + float compute_distance(const float* x, const uint8_t* code) const { + if constexpr (four_acc) { + return reduce_4(reduce_8_to_4(accumulate_4(x, code))); + } Similarity sim(x); sim.begin_8(); for (size_t i = 0; i < quant.d; i += 8) { @@ -697,6 +742,21 @@ struct DCTemplate : SQDistanceComputer { float& dis1, float& dis2, float& dis3) const final { + if constexpr (four_acc) { + alignas(16) float dis[4]; + _mm_store_ps( + dis, + reduce_4x4( + reduce_8_to_4(accumulate_4(q, code_0)), + reduce_8_to_4(accumulate_4(q, code_1)), + reduce_8_to_4(accumulate_4(q, code_2)), + reduce_8_to_4(accumulate_4(q, code_3)))); + dis0 = dis[0]; + dis1 = dis[1]; + dis2 = dis[2]; + dis3 = dis[3]; + return; + } Similarity sim0(q); Similarity sim1(q); Similarity sim2(q); @@ -726,6 +786,143 @@ struct DCTemplate : SQDistanceComputer { } }; +// QT_8bit + IP. With a, rmin from sq8_coefficients.h, +// = sum_i q_i * rmin_i + sum_i (q_i * a_i) * c_i. +// set_query folds the first sum into bias and the products into qa, so each +// 8 dims cost one convert and one FMA instead of the decode, vmin/vdiff and +// query FMAs. +template +struct DCTemplate< + QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + SIMDLevel::AVX2>, + SimilarityIP, + SIMDLevel::AVX2, + four_acc> : SQDistanceComputer { + using Quantizer = QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + SIMDLevel::AVX2>; + using Sim = SimilarityIP; + + Quantizer quant; + std::vector a, rmin, qa; + float bias = 0; + + DCTemplate(size_t d, const std::vector& trained) + : quant(d, trained), a(d), rmin(d), qa(d) { + sq8::make_coefficients(trained.data(), d, a.data(), rmin.data()); + } + + void set_query(const float* x) final { + q = x; + bias = 0; + for (size_t i = 0; i < quant.d; i++) { + qa[i] = x[i] * a[i]; + bias += x[i] * rmin[i]; + } + } + + static FAISS_ALWAYS_INLINE __m256 codes_8(const uint8_t* code) { + return _mm256_cvtepi32_ps( + _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)code))); + } + + /// sum_i qa[i] * code[i] of N codes, in 4 lanes each. The N codes share + /// each qa load. With four_acc, dims i + 8 * j of each 32 go to + /// accumulator j of the code, so a code sums the same way for any N. + template + FAISS_ALWAYS_INLINE void accumulate( + const uint8_t* const* code_ptrs, + __m128* sums) const { + constexpr size_t n_acc = four_acc ? 4 : 1; + __m256 acc[N][n_acc]; + for (size_t n = 0; n < N; n++) { + for (size_t j = 0; j < n_acc; j++) { + acc[n][j] = _mm256_setzero_ps(); + } + } + const size_t d = quant.d; + size_t i = 0; + if constexpr (four_acc) { + for (; i + 32 <= d; i += 32) { + for (size_t j = 0; j < 4; j++) { + const __m256 qa8 = _mm256_loadu_ps(qa.data() + i + 8 * j); + for (size_t n = 0; n < N; n++) { + acc[n][j] = _mm256_fmadd_ps( + qa8, + codes_8(code_ptrs[n] + i + 8 * j), + acc[n][j]); + } + } + } + } + for (; i < d; i += 8) { + const __m256 qa8 = _mm256_loadu_ps(qa.data() + i); + for (size_t n = 0; n < N; n++) { + acc[n][0] = _mm256_fmadd_ps( + qa8, codes_8(code_ptrs[n] + i), acc[n][0]); + } + } + for (size_t n = 0; n < N; n++) { + __m256 sum = acc[n][0]; + if constexpr (four_acc) { + sum = _mm256_add_ps( + _mm256_add_ps(acc[n][0], acc[n][1]), + _mm256_add_ps(acc[n][2], acc[n][3])); + } + sums[n] = reduce_8_to_4(sum); + } + } + + float query_to_code(const uint8_t* code) const final { + __m128 sum; + accumulate<1>(&code, &sum); + return bias + reduce_4(sum); + } + + void query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const final { + const uint8_t* code_ptrs[4] = {code_0, code_1, code_2, code_3}; + __m128 sums[4]; + if constexpr (four_acc) { + // 16 accumulators would take all 16 AVX2 registers. + accumulate<2>(code_ptrs, sums); + accumulate<2>(code_ptrs + 2, sums + 2); + } else { + accumulate<4>(code_ptrs, sums); + } + alignas(16) float dis[4]; + _mm_store_ps(dis, reduce_4x4(sums[0], sums[1], sums[2], sums[3])); + dis0 = bias + dis[0]; + dis1 = bias + dis[1]; + dis2 = bias + dis[2]; + dis3 = bias + dis[3]; + } + + float symmetric_dis(idx_t i, idx_t j) override { + const uint8_t* c1 = codes + i * code_size; + const uint8_t* c2 = codes + j * code_size; + Sim sim(nullptr); + sim.begin_8(); + for (size_t k = 0; k < quant.d; k += 8) { + const int kk = static_cast(k); + sim.add_8_components_2( + quant.reconstruct_8_components(c1, kk), + quant.reconstruct_8_components(c2, kk)); + } + return sim.result_8(); + } +}; + template struct DistanceComputerByte : SQDistanceComputer { using Sim = Similarity; @@ -733,8 +930,9 @@ struct DistanceComputerByte : SQDistanceComputer { int d; std::vector tmp; - DistanceComputerByte(int d, const std::vector&) : d(d), tmp(d) { - FAISS_THROW_IF_NOT(d % 16 == 0); + DistanceComputerByte(int d_in, const std::vector&) + : d(d_in), tmp(d_in) { + FAISS_THROW_IF_NOT(d_in % 16 == 0); } int compute_code_distance(const uint8_t* code1, const uint8_t* code2) @@ -797,9 +995,9 @@ struct DistanceComputerByteSigned int d; std::vector tmp; - DistanceComputerByteSigned(int d, const std::vector&) - : d(d), tmp(d) { - FAISS_THROW_IF_NOT(d % 16 == 0); + DistanceComputerByteSigned(int d_in, const std::vector&) + : d(d_in), tmp(d_in) { + FAISS_THROW_IF_NOT(d_in % 16 == 0); } int compute_code_distance(const uint8_t* code1, const uint8_t* code2) @@ -853,54 +1051,8 @@ struct DistanceComputerByteSigned } }; -/********************************************************** - * TurboQuant masked_sum AVX2 specialization - **********************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - const __m256i bit_masks = _mm256_set_epi32(128, 64, 32, 16, 8, 4, 2, 1); - __m256 acc = _mm256_setzero_ps(); - size_t full_bytes = d / 8; - for (size_t byte_idx = 0; byte_idx < full_bytes; byte_idx++) { - __m256i byte_broadcast = - _mm256_set1_epi32(static_cast(bits[byte_idx])); - __m256i masked = _mm256_and_si256(byte_broadcast, bit_masks); - __m256i cmp = _mm256_cmpeq_epi32(masked, bit_masks); - __m256 mask = _mm256_castsi256_ps(cmp); - __m256 vals = _mm256_loadu_ps(arr + byte_idx * 8); - acc = _mm256_add_ps(acc, _mm256_and_ps(mask, vals)); - } - __m128 hi = _mm256_extractf128_ps(acc, 1); - __m128 lo = _mm256_castps256_ps128(acc); - __m128 sum128 = _mm_add_ps(lo, hi); - __m128 shuf = _mm_movehdup_ps(sum128); - __m128 sums = _mm_add_ps(sum128, shuf); - shuf = _mm_movehl_ps(shuf, sums); - sums = _mm_add_ss(sums, shuf); - float result = _mm_cvtss_f32(sums); - size_t tail_start = full_bytes * 8; - if (tail_start < d) { - uint8_t last_byte = bits[full_bytes]; - for (size_t j = tail_start; j < d; j++) { - if (last_byte & (1 << (j - tail_start))) { - result += arr[j]; - } - } - } - return result; -} - } // namespace scalar_quantizer } // namespace faiss #define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX2 #include - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h index 39f1061e8..1e9402248 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-impl.h @@ -7,6 +7,12 @@ #pragma once +#include +#include +#include +#include +#include +#include #include namespace faiss { @@ -14,11 +20,6 @@ namespace faiss { namespace scalar_quantizer { using simd16float32 = faiss::simd16float32_tpl; -using simd512bit = faiss::simd512bit_tpl; - -/********************************************************** - * TurboQuant bit-unpacking helpers - **********************************************************/ namespace { @@ -100,7 +101,7 @@ FAISS_ALWAYS_INLINE __m512i unpack_16x4bit_to_u32(const uint8_t* code, int i) { **********************************************************/ template <> -struct Codec8bit : Codec8bit { +struct Codec8bit : Codec8bit { static FAISS_ALWAYS_INLINE simd16float32 decode_16_components(const uint8_t* code, size_t i) { const __m128i c16 = _mm_loadu_si128((__m128i*)(code + i)); @@ -113,7 +114,7 @@ struct Codec8bit : Codec8bit { }; template <> -struct Codec4bit : Codec4bit { +struct Codec4bit : Codec4bit { static FAISS_ALWAYS_INLINE simd16float32 decode_16_components(const uint8_t* code, size_t i) { uint64_t c8 = *(uint64_t*)(code + (i >> 1)); @@ -135,7 +136,7 @@ struct Codec4bit : Codec4bit { }; template <> -struct Codec6bit : Codec6bit { +struct Codec6bit : Codec6bit { static FAISS_ALWAYS_INLINE simd16float32 decode_16_components(const uint8_t* code, size_t i) { // pure AVX512 implementation (not necessarily the fastest). @@ -152,10 +153,10 @@ struct Codec6bit : Codec6bit { // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F // 00 01 02 03 const __m256i shuffle_mask = _mm256_setr_epi16( - 0xFF00, 0x0100, 0x0201, 0xFF02, - 0xFF03, 0x0403, 0x0504, 0xFF05, - 0xFF06, 0x0706, 0x0807, 0xFF08, - 0xFF09, 0x0A09, 0x0B0A, 0xFF0B); + short(0xFF00), 0x0100, 0x0201, short(0xFF02), + short(0xFF03), 0x0403, 0x0504, short(0xFF05), + short(0xFF06), 0x0706, 0x0807, short(0xFF08), + short(0xFF09), 0x0A09, 0x0B0A, short(0xFF0B)); const __m256i shuffled = _mm256_shuffle_epi8(bit_6v_256, shuffle_mask); // 0: xxxxxxxx xx543210 @@ -192,17 +193,17 @@ template struct QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::AVX512> + THE_LEVEL_TO_DISPATCH> : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 16 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 16 == 0); } FAISS_ALWAYS_INLINE simd16float32 @@ -211,23 +212,29 @@ struct QuantizerTemplate< return simd16float32(_mm512_fmadd_ps( xi, _mm512_set1_ps(this->vdiff), _mm512_set1_ps(this->vmin))); } + + /// Raw codec decode without denormalization + FAISS_ALWAYS_INLINE simd16float32 + decode_16_raw(const uint8_t* code, int i) const { + return Codec::decode_16_components(code, i); + } }; template struct QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::AVX512> + THE_LEVEL_TO_DISPATCH> : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 16 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 16 == 0); } FAISS_ALWAYS_INLINE simd16float32 @@ -244,40 +251,87 @@ struct QuantizerTemplate< * Lloyd-Max scalar quantizer **********************************************************/ -#define DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION(NBITS, INDEX_EXPR) \ - template <> \ - struct QuantizerLloydMax \ - : QuantizerLloydMax { \ - using Base = QuantizerLloydMax; \ - \ - QuantizerLloydMax(size_t d, const std::vector& trained) \ - : Base(d, trained) { \ - assert(d % 16 == 0); \ - } \ - \ - FAISS_ALWAYS_INLINE simd16float32 \ - reconstruct_16_components(const uint8_t* code, int i) const { \ - const __m512i indices = (INDEX_EXPR); \ - return simd16float32(_mm512_i32gather_ps( \ - indices, this->centroids, sizeof(float))); \ - } \ - } - -DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION(1, unpack_16x1bit_to_u32(code, i)); -DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION(2, unpack_16x2bit_to_u32(code, i)); -DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION(3, unpack_16x3bit_to_u32(code, i)); -DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION(4, unpack_16x4bit_to_u32(code, i)); - -#undef DEFINE_LLOYD_MAX_AVX512_SPECIALIZATION +// 1-bit Lloyd-Max AVX512: 16 comparisons → 2 bytes via mask compare. +// NLT_UQ is !(x < b), matching the scalar upper_bound tie-break. +template <> +struct QuantizerLloydMax<1, THE_LEVEL_TO_DISPATCH> + : QuantizerLloydMaxBase<1, THE_LEVEL_TO_DISPATCH> { + using Base = QuantizerLloydMaxBase<1, THE_LEVEL_TO_DISPATCH>; + + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 16 == 0); + } + + FAISS_ALWAYS_INLINE simd16float32 + reconstruct_16_components(const uint8_t* code, int i) const { + return simd16float32(_mm512_i32gather_ps( + unpack_16x1bit_to_u32(code, i), + this->centroids, + sizeof(float))); + } + + void encode_vector(const float* x, uint8_t* code) const final { + __m512 boundary = _mm512_set1_ps(this->boundaries[0]); + for (size_t i = 0; i < this->d; i += 16) { + __m512 vals = _mm512_loadu_ps(x + i); + __mmask16 mask = _mm512_cmp_ps_mask(vals, boundary, _CMP_NLT_UQ); + uint16_t bits = _cvtmask16_u32(mask); + memcpy(code + i / 8, &bits, sizeof(uint16_t)); + } + } + + void decode_vector(const uint8_t* code, float* x) const final { + for (size_t i = 0; i < this->d; i += 16) { + simd16float32 xi = + reconstruct_16_components(code, static_cast(i)); + _mm512_storeu_ps(x + i, xi.f); + } + } +}; +// 2-4 bit Lloyd-Max AVX512: decode via gather, encode stays scalar. +#define DEFINE_LLOYD_MAX_AVX512_MULTIBIT(NBITS, UNPACK_EXPR) \ + template <> \ + struct QuantizerLloydMax \ + : QuantizerLloydMaxBase { \ + using Base = QuantizerLloydMaxBase; \ + \ + QuantizerLloydMax(size_t d_in, const std::vector& trained) \ + : Base(d_in, trained) { \ + assert(d_in % 16 == 0); \ + } \ + \ + FAISS_ALWAYS_INLINE simd16float32 \ + reconstruct_16_components(const uint8_t* code, int i) const { \ + return simd16float32(_mm512_i32gather_ps( \ + (UNPACK_EXPR), this->centroids, sizeof(float))); \ + } \ + \ + void decode_vector(const uint8_t* code, float* x) const final { \ + for (size_t i = 0; i < this->d; i += 16) { \ + simd16float32 xi = \ + reconstruct_16_components(code, static_cast(i)); \ + _mm512_storeu_ps(x + i, xi.f); \ + } \ + } \ + } + +DEFINE_LLOYD_MAX_AVX512_MULTIBIT(2, unpack_16x2bit_to_u32(code, i)); +DEFINE_LLOYD_MAX_AVX512_MULTIBIT(3, unpack_16x3bit_to_u32(code, i)); +DEFINE_LLOYD_MAX_AVX512_MULTIBIT(4, unpack_16x4bit_to_u32(code, i)); + +#undef DEFINE_LLOYD_MAX_AVX512_MULTIBIT + +// 8-bit Lloyd-Max AVX512 template <> -struct QuantizerLloydMax<8, SIMDLevel::AVX512> - : QuantizerLloydMax<8, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<8, SIMDLevel::NONE>; +struct QuantizerLloydMax<8, THE_LEVEL_TO_DISPATCH> + : QuantizerLloydMaxBase<8, THE_LEVEL_TO_DISPATCH> { + using Base = QuantizerLloydMaxBase<8, THE_LEVEL_TO_DISPATCH>; - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 16 == 0); + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 16 == 0); } FAISS_ALWAYS_INLINE simd16float32 @@ -288,6 +342,14 @@ struct QuantizerLloydMax<8, SIMDLevel::AVX512> return simd16float32( _mm512_i32gather_ps(indices, this->centroids, sizeof(float))); } + + void decode_vector(const uint8_t* code, float* x) const final { + for (size_t i = 0; i < this->d; i += 16) { + simd16float32 xi = + reconstruct_16_components(code, static_cast(i)); + _mm512_storeu_ps(x + i, xi.f); + } + } }; /********************************************************** @@ -295,17 +357,25 @@ struct QuantizerLloydMax<8, SIMDLevel::AVX512> **********************************************************/ template <> -struct QuantizerFP16 : QuantizerFP16 { - QuantizerFP16(size_t d, const std::vector& trained) - : QuantizerFP16(d, trained) { - assert(d % 16 == 0); - } +struct QuantizerFP16 + : QuantizerFP16Base { + using QuantizerFP16Base::QuantizerFP16Base; FAISS_ALWAYS_INLINE simd16float32 reconstruct_16_components(const uint8_t* code, int i) const { __m256i codei = _mm256_loadu_si256((const __m256i*)(code + 2 * i)); return simd16float32(_mm512_cvtph_ps(codei)); } + + /// Components i .. i + 15 selected by mask, the others 0. Reads no byte + /// past the selected components. + FAISS_ALWAYS_INLINE simd16float32 reconstruct_16_components_masked( + const uint8_t* code, + int i, + __mmask16 mask) const { + __m256i codei = _mm256_maskz_loadu_epi16(mask, code + 2 * i); + return simd16float32(_mm512_cvtph_ps(codei)); + } }; /********************************************************** @@ -313,15 +383,26 @@ struct QuantizerFP16 : QuantizerFP16 { **********************************************************/ template <> -struct QuantizerBF16 : QuantizerBF16 { - QuantizerBF16(size_t d, const std::vector& trained) - : QuantizerBF16(d, trained) { - assert(d % 16 == 0); - } +struct QuantizerBF16 + : QuantizerBF16Base { + using QuantizerBF16Base::QuantizerBF16Base; FAISS_ALWAYS_INLINE simd16float32 reconstruct_16_components(const uint8_t* code, int i) const { __m256i code_256i = _mm256_loadu_si256((const __m256i*)(code + 2 * i)); + return widen(code_256i); + } + + /// Components i .. i + 15 selected by mask, the others 0. Reads no byte + /// past the selected components. + FAISS_ALWAYS_INLINE simd16float32 reconstruct_16_components_masked( + const uint8_t* code, + int i, + __mmask16 mask) const { + return widen(_mm256_maskz_loadu_epi16(mask, code + 2 * i)); + } + + static FAISS_ALWAYS_INLINE simd16float32 widen(__m256i code_256i) { __m512i code_512i = _mm512_cvtepu16_epi32(code_256i); code_512i = _mm512_slli_epi32(code_512i, 16); return simd16float32(_mm512_castsi512_ps(code_512i)); @@ -333,11 +414,11 @@ struct QuantizerBF16 : QuantizerBF16 { **********************************************************/ template <> -struct Quantizer8bitDirect - : Quantizer8bitDirect { - Quantizer8bitDirect(size_t d, const std::vector& trained) - : Quantizer8bitDirect(d, trained) { - assert(d % 16 == 0); +struct Quantizer8bitDirect + : Quantizer8bitDirectBase { + Quantizer8bitDirect(size_t d_in, const std::vector& trained) + : Quantizer8bitDirectBase(d_in, trained) { + assert(d_in % 16 == 0); } FAISS_ALWAYS_INLINE simd16float32 @@ -353,11 +434,13 @@ struct Quantizer8bitDirect **********************************************************/ template <> -struct Quantizer8bitDirectSigned - : Quantizer8bitDirectSigned { - Quantizer8bitDirectSigned(size_t d, const std::vector& trained) - : Quantizer8bitDirectSigned(d, trained) { - assert(d % 16 == 0); +struct Quantizer8bitDirectSigned + : Quantizer8bitDirectSignedBase { + Quantizer8bitDirectSigned(size_t d_in, const std::vector& trained) + : Quantizer8bitDirectSignedBase( + d_in, + trained) { + assert(d_in % 16 == 0); } FAISS_ALWAYS_INLINE simd16float32 @@ -375,14 +458,14 @@ struct Quantizer8bitDirectSigned **********************************************************/ template <> -struct SimilarityL2 { +struct SimilarityL2 { static constexpr int simdwidth = 16; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512; + static constexpr SIMDLevel simd_level = THE_LEVEL_TO_DISPATCH; static constexpr MetricType metric_type = METRIC_L2; const float *y, *yi; - explicit SimilarityL2(const float* y) : y(y), yi(nullptr) {} + explicit SimilarityL2(const float* y_in) : y(y_in), yi(nullptr) {} simd16float32 accu16; @@ -405,20 +488,43 @@ struct SimilarityL2 { accu16 = accu16 + tmp * tmp; } + FAISS_ALWAYS_INLINE void fmadd_16_components_2( + simd16float32 x, + simd16float32 y_2) { + simd16float32 tmp = y_2 - x; + accu16 = fmadd(tmp, tmp, accu16); + } + FAISS_ALWAYS_INLINE float result_16() { return horizontal_add(accu16); } + + static void adjust_query_for_raw_decode( + const float* x, + float* q_adj, + size_t d, + float vmin, + float vdiff, + float& scale_factor, + float& bias) { + float inv_vdiff = (vdiff != 0) ? 1.0f / vdiff : 0.0f; + for (size_t i = 0; i < d; i++) { + q_adj[i] = (x[i] - vmin) * inv_vdiff; + } + scale_factor = vdiff * vdiff; + bias = 0; + } }; template <> -struct SimilarityIP { +struct SimilarityIP { static constexpr int simdwidth = 16; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512; + static constexpr SIMDLevel simd_level = THE_LEVEL_TO_DISPATCH; static constexpr MetricType metric_type = METRIC_INNER_PRODUCT; const float *y, *yi; - explicit SimilarityIP(const float* y) : y(y), yi(nullptr) {} + explicit SimilarityIP(const float* y_in) : y(y_in), yi(nullptr) {} simd16float32 accu16; @@ -439,32 +545,144 @@ struct SimilarityIP { accu16 = accu16 + x1 * x2; } + FAISS_ALWAYS_INLINE void fmadd_16_components_2( + simd16float32 x1, + simd16float32 x2) { + accu16 = fmadd(x1, x2, accu16); + } + FAISS_ALWAYS_INLINE float result_16() { return horizontal_add(accu16); } + + static void adjust_query_for_raw_decode( + const float* x, + float* q_adj, + size_t d, + float vmin, + float vdiff, + float& scale_factor, + float& bias) { + float sum_q = 0; + for (size_t i = 0; i < d; i++) { + q_adj[i] = x[i]; + sum_q += x[i]; + } + scale_factor = vdiff; + bias = vmin * sum_q; + } }; /********************************************************** * Distance Computers **********************************************************/ -template -struct DCTemplate +namespace { + +/// 16 lanes to 4: lanes j, j + 4, j + 8 and j + 12 summed into lane j. +FAISS_ALWAYS_INLINE __m128 reduce_16_to_4(__m512 a) { + const __m256 hi = + _mm256_castpd_ps(_mm512_extractf64x4_pd(_mm512_castps_pd(a), 1)); + const __m256 s8 = _mm256_add_ps(_mm512_castps512_ps256(a), hi); + return _mm_add_ps(_mm256_castps256_ps128(s8), _mm256_extractf128_ps(s8, 1)); +} + +} // namespace + +template +struct DCTemplate : SQDistanceComputer { using Sim = Similarity; Quantizer quant; + // Pre-adjusted query buffer for uniform quantizers + std::vector q_adj; + float scale_factor = 0; + float bias = 0; + + static constexpr bool has_decode_raw() { + return requires(const Quantizer& q, const uint8_t* c, int i) { + { q.decode_16_raw(c, i) }; + }; + } + DCTemplate(size_t d, const std::vector& trained) - : quant(d, trained) {} + : quant(d, trained) { + if constexpr (has_decode_raw()) { + q_adj.resize(d); + } + } + + /// The quantizer can decode a partial block, so d need not be a + /// multiple of 16. + static constexpr bool has_masked_tail() { + return requires(const Quantizer& q, const uint8_t* c) { + { q.reconstruct_16_components_masked(c, 0, __mmask16(0)) }; + }; + } + + /// Adds the partial last block, from component i, of a d that is not a + /// multiple of 16. + FAISS_ALWAYS_INLINE void add_tail( + Similarity& sim, + const float* x, + const uint8_t* code, + size_t i) const { + if constexpr (has_masked_tail()) { + if (i < quant.d) { + const __mmask16 mask = __mmask16((1u << (quant.d - i)) - 1); + sim.fmadd_16_components_2( + quant.reconstruct_16_components_masked( + code, static_cast(i), mask), + simd16float32(_mm512_maskz_loadu_ps(mask, x + i))); + } + } + } + + /// Similarity terms of one code with four accumulators. + FAISS_ALWAYS_INLINE __m512 + accumulate_4(const float* x, const uint8_t* code) const { + struct Acc : Similarity { + Acc() : Similarity(nullptr) {} + }; + Acc s[4]; + for (int j = 0; j < 4; j++) { + s[j].begin_16(); + } + const size_t d = quant.d; + size_t i = 0; + for (; i + 64 <= d; i += 64) { + for (int j = 0; j < 4; j++) { + s[j].fmadd_16_components_2( + quant.reconstruct_16_components( + code, static_cast(i + 16 * j)), + simd16float32(x + i + 16 * j)); + } + } + for (; i + 16 <= d; i += 16) { + s[0].fmadd_16_components_2( + quant.reconstruct_16_components(code, static_cast(i)), + simd16float32(x + i)); + } + add_tail(s[0], x, code, i); + return _mm512_add_ps( + _mm512_add_ps(s[0].accu16.f, s[1].accu16.f), + _mm512_add_ps(s[2].accu16.f, s[3].accu16.f)); + } float compute_distance(const float* x, const uint8_t* code) const { + if constexpr (four_acc) { + return reduce_4(reduce_16_to_4(accumulate_4(x, code))); + } Similarity sim(x); sim.begin_16(); - for (size_t i = 0; i < quant.d; i += 16) { + const size_t d16 = quant.d & ~size_t(15); + for (size_t i = 0; i < d16; i += 16) { simd16float32 xi = quant.reconstruct_16_components(code, i); sim.add_16_components(xi); } + add_tail(sim, x, code, d16); return sim.result_16(); } @@ -472,16 +690,46 @@ struct DCTemplate const { Similarity sim(nullptr); sim.begin_16(); - for (size_t i = 0; i < quant.d; i += 16) { + const size_t d16 = quant.d & ~size_t(15); + for (size_t i = 0; i < d16; i += 16) { simd16float32 x1 = quant.reconstruct_16_components(code1, i); simd16float32 x2 = quant.reconstruct_16_components(code2, i); sim.add_16_components_2(x1, x2); } + if constexpr (has_masked_tail()) { + if (d16 < quant.d) { + const __mmask16 mask = __mmask16((1u << (quant.d - d16)) - 1); + const int i = static_cast(d16); + sim.add_16_components_2( + quant.reconstruct_16_components_masked(code1, i, mask), + quant.reconstruct_16_components_masked(code2, i, mask)); + } + } return sim.result_16(); } void set_query(const float* x) final { q = x; + if constexpr (has_decode_raw()) { + Sim::adjust_query_for_raw_decode( + x, + q_adj.data(), + quant.d, + quant.vmin, + quant.vdiff, + scale_factor, + bias); + } + } + + float query_to_code_predecoded(const uint8_t* code) const { + Similarity sim(q_adj.data()); + sim.begin_16(); + for (size_t i = 0; i < quant.d; i += 16) { + simd16float32 xi = quant.decode_16_raw(code, i); + sim.add_16_components(xi); + } + return bias + scale_factor * sim.result_16(); } float symmetric_dis(idx_t i, idx_t j) override { @@ -490,64 +738,197 @@ struct DCTemplate } float query_to_code(const uint8_t* code) const final { - return compute_distance(q, code); + if constexpr (has_decode_raw()) { + return query_to_code_predecoded(code); + } else { + return compute_distance(q, code); + } } -}; -template -struct DistanceComputerByte - : SQDistanceComputer { - using Sim = Similarity; + void query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const final { + if constexpr (four_acc) { + alignas(16) float dis[4]; + _mm_store_ps( + dis, + reduce_4x4( + reduce_16_to_4(accumulate_4(q, code_0)), + reduce_16_to_4(accumulate_4(q, code_1)), + reduce_16_to_4(accumulate_4(q, code_2)), + reduce_16_to_4(accumulate_4(q, code_3)))); + dis0 = dis[0]; + dis1 = dis[1]; + dis2 = dis[2]; + dis3 = dis[3]; + return; + } + Similarity sim0(q); + Similarity sim1(q); + Similarity sim2(q); + Similarity sim3(q); + + sim0.begin_16(); + sim1.begin_16(); + sim2.begin_16(); + sim3.begin_16(); + + const size_t d16 = quant.d & ~size_t(15); + for (size_t i = 0; i < d16; i += 16) { + simd16float32 xi0 = quant.reconstruct_16_components(code_0, i); + simd16float32 xi1 = quant.reconstruct_16_components(code_1, i); + simd16float32 xi2 = quant.reconstruct_16_components(code_2, i); + simd16float32 xi3 = quant.reconstruct_16_components(code_3, i); + sim0.add_16_components(xi0); + sim1.add_16_components(xi1); + sim2.add_16_components(xi2); + sim3.add_16_components(xi3); + } + add_tail(sim0, q, code_0, d16); + add_tail(sim1, q, code_1, d16); + add_tail(sim2, q, code_2, d16); + add_tail(sim3, q, code_3, d16); - int d; - std::vector tmp; + dis0 = sim0.result_16(); + dis1 = sim1.result_16(); + dis2 = sim2.result_16(); + dis3 = sim3.result_16(); + } +}; - DistanceComputerByte(int d, const std::vector&) : d(d), tmp(d) {} +// QT_8bit + IP: the precomputed form of the AVX2 specialization, 16 dims per +// convert and FMA. +template +struct DCTemplate< + QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + THE_LEVEL_TO_DISPATCH>, + SimilarityIP, + THE_LEVEL_TO_DISPATCH, + four_acc> : SQDistanceComputer { + using Quantizer = QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + THE_LEVEL_TO_DISPATCH>; + using Sim = SimilarityIP; - int compute_code_distance(const uint8_t* code1, const uint8_t* code2) - const { - // compute 16 lanes of 32-bit products (16-bytes) at once for - // the supported metrics - __m512i accu = _mm512_setzero_si512(); - constexpr int kLanes = 16; - for (int i = 0; i < d; i += kLanes) { - __m128i c1 = _mm_loadu_si128((__m128i*)(code1 + i)); - __m128i c2 = _mm_loadu_si128((__m128i*)(code2 + i)); - __m512i c1i = _mm512_cvtepu8_epi32(c1); - __m512i c2i = _mm512_cvtepu8_epi32(c2); - - __m512i v; - if (Sim::metric_type == METRIC_INNER_PRODUCT) { - v = _mm512_mullo_epi32(c1i, c2i); - } else { - __m512i diff = _mm512_sub_epi32(c1i, c2i); - v = _mm512_mullo_epi32(diff, diff); - } - accu = _mm512_add_epi32(accu, v); - } - return _mm512_reduce_add_epi32(accu); + Quantizer quant; + std::vector a, rmin, qa; + float bias = 0; + + DCTemplate(size_t d, const std::vector& trained) + : quant(d, trained), a(d), rmin(d), qa(d) { + sq8::make_coefficients(trained.data(), d, a.data(), rmin.data()); } void set_query(const float* x) final { - for (int i = 0; i < d; i++) { - tmp[i] = int(x[i]); + q = x; + bias = 0; + for (size_t i = 0; i < quant.d; i++) { + qa[i] = x[i] * a[i]; + bias += x[i] * rmin[i]; } } - int compute_distance(const float* x, const uint8_t* code) { - set_query(x); - return compute_code_distance(tmp.data(), code); + static FAISS_ALWAYS_INLINE __m512 codes_16(const uint8_t* code) { + return _mm512_cvtepi32_ps( + _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)code))); } - float symmetric_dis(idx_t i, idx_t j) override { - return compute_code_distance( - codes + i * code_size, codes + j * code_size); + /// sum_i qa[i] * code[i] of N codes, in 4 lanes each. The N codes share + /// each qa load. With four_acc, dims i + 16 * j of each 64 go to + /// accumulator j of the code, so a code sums the same way for any N. + template + FAISS_ALWAYS_INLINE void accumulate( + const uint8_t* const* code_ptrs, + __m128* sums) const { + constexpr size_t n_acc = four_acc ? 4 : 1; + __m512 acc[N][n_acc]; + for (size_t n = 0; n < N; n++) { + for (size_t j = 0; j < n_acc; j++) { + acc[n][j] = _mm512_setzero_ps(); + } + } + const size_t d = quant.d; + size_t i = 0; + if constexpr (four_acc) { + for (; i + 64 <= d; i += 64) { + for (size_t j = 0; j < 4; j++) { + const __m512 qa16 = _mm512_loadu_ps(qa.data() + i + 16 * j); + for (size_t n = 0; n < N; n++) { + acc[n][j] = _mm512_fmadd_ps( + qa16, + codes_16(code_ptrs[n] + i + 16 * j), + acc[n][j]); + } + } + } + } + for (; i < d; i += 16) { + const __m512 qa16 = _mm512_loadu_ps(qa.data() + i); + for (size_t n = 0; n < N; n++) { + acc[n][0] = _mm512_fmadd_ps( + qa16, codes_16(code_ptrs[n] + i), acc[n][0]); + } + } + for (size_t n = 0; n < N; n++) { + __m512 sum = acc[n][0]; + if constexpr (four_acc) { + sum = _mm512_add_ps( + _mm512_add_ps(acc[n][0], acc[n][1]), + _mm512_add_ps(acc[n][2], acc[n][3])); + } + sums[n] = reduce_16_to_4(sum); + } } float query_to_code(const uint8_t* code) const final { - return compute_code_distance(tmp.data(), code); + __m128 sum; + accumulate<1>(&code, &sum); + return bias + reduce_4(sum); + } + + void query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const final { + const uint8_t* code_ptrs[4] = {code_0, code_1, code_2, code_3}; + __m128 sums[4]; + accumulate<4>(code_ptrs, sums); + alignas(16) float dis[4]; + _mm_store_ps(dis, reduce_4x4(sums[0], sums[1], sums[2], sums[3])); + dis0 = bias + dis[0]; + dis1 = bias + dis[1]; + dis2 = bias + dis[2]; + dis3 = bias + dis[3]; + } + + float symmetric_dis(idx_t i, idx_t j) override { + const uint8_t* c1 = codes + i * code_size; + const uint8_t* c2 = codes + j * code_size; + Sim sim(nullptr); + sim.begin_16(); + for (size_t k = 0; k < quant.d; k += 16) { + simd16float32 x1 = quant.reconstruct_16_components(c1, k); + simd16float32 x2 = quant.reconstruct_16_components(c2, k); + sim.add_16_components_2(x1, x2); + } + return sim.result_16(); } }; } // namespace scalar_quantizer + } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp index 087e8e89e..8d07693a6 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512-spr.cpp @@ -5,136 +5,13 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512_SPR - -#include - -#include -#include -#include -#include -#include -#include - +#define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX512_SPR #include +#include namespace faiss { namespace scalar_quantizer { -/********************************************************** - * Codecs — inherit AVX512 implementations - **********************************************************/ - -template <> -struct Codec8bit : Codec8bit {}; - -template <> -struct Codec4bit : Codec4bit {}; - -template <> -struct Codec6bit : Codec6bit {}; - -/********************************************************** - * Quantizers — inherit AVX512 implementations - **********************************************************/ - -template -struct QuantizerTemplate< - Codec, - QuantizerTemplateScaling::UNIFORM, - SIMDLevel::AVX512_SPR> - : QuantizerTemplate< - Codec, - QuantizerTemplateScaling::UNIFORM, - SIMDLevel::AVX512> { - using QuantizerTemplate< - Codec, - QuantizerTemplateScaling::UNIFORM, - SIMDLevel::AVX512>::QuantizerTemplate; -}; - -template -struct QuantizerTemplate< - Codec, - QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::AVX512_SPR> - : QuantizerTemplate< - Codec, - QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::AVX512> { - using QuantizerTemplate< - Codec, - QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::AVX512>::QuantizerTemplate; -}; - -template <> -struct QuantizerFP16 : QuantizerFP16 { - using QuantizerFP16::QuantizerFP16; -}; - -template <> -struct QuantizerBF16 : QuantizerBF16 { - using QuantizerBF16::QuantizerBF16; - - void encode_vector(const float* x, uint8_t* code) const override { - encode_bf16_simd(x, (uint16_t*)code, this->d); - } - - void decode_vector(const uint8_t* code, float* x) const override { - decode_bf16_simd((const uint16_t*)code, x, this->d); - } -}; - -template <> -struct Quantizer8bitDirect - : Quantizer8bitDirect { - using Quantizer8bitDirect::Quantizer8bitDirect; -}; - -template <> -struct Quantizer8bitDirectSigned - : Quantizer8bitDirectSigned { - using Quantizer8bitDirectSigned< - SIMDLevel::AVX512>::Quantizer8bitDirectSigned; -}; - -/********************************************************** - * Lloyd-Max scalar quantizer - inherit AVX512 implementations - **********************************************************/ - -template -struct QuantizerLloydMax - : QuantizerLloydMax { - using QuantizerLloydMax::QuantizerLloydMax; -}; - -/********************************************************** - * Similarities — inherit AVX512 implementations - **********************************************************/ - -template <> -struct SimilarityL2 : SimilarityL2 { - using SimilarityL2::SimilarityL2; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512_SPR; -}; - -template <> -struct SimilarityIP : SimilarityIP { - using SimilarityIP::SimilarityIP; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512_SPR; -}; - -/********************************************************** - * Generic DCTemplate — delegate to AVX512 implementations - **********************************************************/ - -template -struct DCTemplate - : DCTemplate { - using DCTemplate::DCTemplate; -}; - /********************************************************** * DistanceComputerByte: AVX512-VNNI * @@ -150,7 +27,8 @@ struct DistanceComputerByte int d; std::vector tmp; - DistanceComputerByte(int d, const std::vector&) : d(d), tmp(d) {} + DistanceComputerByte(int d_in, const std::vector&) + : d(d_in), tmp(d_in) {} int compute_code_distance(const uint8_t* code1, const uint8_t* code2) const { @@ -264,8 +142,8 @@ struct DistanceComputerByteSigned int d; std::vector tmp; - DistanceComputerByteSigned(int d, const std::vector&) - : d(d), tmp(d) {} + DistanceComputerByteSigned(int d_in, const std::vector&) + : d(d_in), tmp(d_in) {} int compute_code_distance(const uint8_t* code1, const uint8_t* code2) const { @@ -458,7 +336,8 @@ struct DCBF16_IP : SQDistanceComputer { size_t d; std::vector query_bf16; - DCBF16_IP(size_t d, const std::vector&) : d(d), query_bf16(d) {} + DCBF16_IP(size_t d_in, const std::vector&) + : d(d_in), query_bf16(d_in) {} void set_query(const float* x) final { q = x; @@ -488,8 +367,8 @@ struct DCBF16_L2 : SQDistanceComputer { std::vector query_bf16; float query_norm_sq; - DCBF16_L2(size_t d, const std::vector&) - : d(d), query_bf16(d), query_norm_sq(0) {} + DCBF16_L2(size_t d_in, const std::vector&) + : d(d_in), query_bf16(d_in), query_norm_sq(0) {} void set_query(const float* x) final { q = x; @@ -528,31 +407,7 @@ struct DCTemplate< using DCBF16_L2::DCBF16_L2; }; -/********************************************************** - * turboq_masked_sum — delegate to AVX512 implementation - **********************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - return turboq_masked_sum(arr, bits, d); -} - } // namespace scalar_quantizer } // namespace faiss -#define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX512_SPR #include - -#endif // COMPILE_SIMD_AVX512_SPR diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp index ae06627f8..804c00850 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-avx512.cpp @@ -5,666 +5,14 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - -#include - -#include - -#include -#include -#include -#include -#include +#define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX512 +#include +#include namespace faiss { namespace scalar_quantizer { -using simd16float32 = faiss::simd16float32_tpl; - -namespace { - -FAISS_ALWAYS_INLINE uint16_t load_u16(const uint8_t* ptr) { - uint16_t value; - std::memcpy(&value, ptr, sizeof(value)); - return value; -} - -FAISS_ALWAYS_INLINE uint32_t load_u32(const uint8_t* ptr) { - uint32_t value; - std::memcpy(&value, ptr, sizeof(value)); - return value; -} - -FAISS_ALWAYS_INLINE uint64_t load_u64(const uint8_t* ptr) { - uint64_t value; - std::memcpy(&value, ptr, sizeof(value)); - return value; -} - -FAISS_ALWAYS_INLINE uint32_t load_u24(const uint8_t* ptr) { - return static_cast(ptr[0]) | - (static_cast(ptr[1]) << 8) | - (static_cast(ptr[2]) << 16); -} - -FAISS_ALWAYS_INLINE __m256i unpack_8x3bit_to_u32(uint32_t packed) { - const __m256i shifts = _mm256_setr_epi32(0, 3, 6, 9, 12, 15, 18, 21); - const __m256i indices = - _mm256_srlv_epi32(_mm256_set1_epi32(packed), shifts); - return _mm256_and_si256(indices, _mm256_set1_epi32(0x7)); -} - -FAISS_ALWAYS_INLINE __m512i unpack_16x1bit_to_u32(const uint8_t* code, int i) { - const uint32_t packed = load_u16(code + (static_cast(i) >> 3)); - const __m512i shifts = _mm512_setr_epi32( - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - const __m512i indices = - _mm512_srlv_epi32(_mm512_set1_epi32(packed), shifts); - return _mm512_and_si512(indices, _mm512_set1_epi32(0x1)); -} - -FAISS_ALWAYS_INLINE __m512i unpack_16x2bit_to_u32(const uint8_t* code, int i) { - const uint32_t packed = load_u32(code + (static_cast(i) >> 2)); - const __m512i shifts = _mm512_setr_epi32( - 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30); - const __m512i indices = - _mm512_srlv_epi32(_mm512_set1_epi32(packed), shifts); - return _mm512_and_si512(indices, _mm512_set1_epi32(0x3)); -} - -FAISS_ALWAYS_INLINE __m512i unpack_16x3bit_to_u32(const uint8_t* code, int i) { - const size_t byte_offset = (static_cast(i) >> 4) * 6; - const __m256i low = unpack_8x3bit_to_u32(load_u24(code + byte_offset)); - const __m256i high = unpack_8x3bit_to_u32(load_u24(code + byte_offset + 3)); - __m512i indices = _mm512_castsi256_si512(low); - return _mm512_inserti32x8(indices, high, 1); -} - -FAISS_ALWAYS_INLINE __m512i unpack_16x4bit_to_u32(const uint8_t* code, int i) { - const uint64_t packed = load_u64(code + (static_cast(i) >> 1)); - const __m256i shifts = _mm256_setr_epi32(0, 4, 8, 12, 16, 20, 24, 28); - const __m256i low = _mm256_and_si256( - _mm256_srlv_epi32(_mm256_set1_epi32((uint32_t)packed), shifts), - _mm256_set1_epi32(0xf)); - const __m256i high = _mm256_and_si256( - _mm256_srlv_epi32( - _mm256_set1_epi32((uint32_t)(packed >> 32)), shifts), - _mm256_set1_epi32(0xf)); - __m512i indices = _mm512_castsi256_si512(low); - return _mm512_inserti32x8(indices, high, 1); -} - -} // namespace - -/********************************************************** - * Codecs - **********************************************************/ - -template <> -struct Codec8bit : Codec8bit { - static FAISS_ALWAYS_INLINE simd16float32 - decode_16_components(const uint8_t* code, size_t i) { - const __m128i c16 = _mm_loadu_si128((__m128i*)(code + i)); - const __m512i i32 = _mm512_cvtepu8_epi32(c16); - const __m512 f16 = _mm512_cvtepi32_ps(i32); - const __m512 half_one_255 = _mm512_set1_ps(0.5f / 255.f); - const __m512 one_255 = _mm512_set1_ps(1.f / 255.f); - return simd16float32(_mm512_fmadd_ps(f16, one_255, half_one_255)); - } -}; - -template <> -struct Codec4bit : Codec4bit { - static FAISS_ALWAYS_INLINE simd16float32 - decode_16_components(const uint8_t* code, size_t i) { - uint64_t c8 = *(uint64_t*)(code + (i >> 1)); - uint64_t mask = 0x0f0f0f0f0f0f0f0f; - uint64_t c8ev = c8 & mask; - uint64_t c8od = (c8 >> 4) & mask; - - __m128i c16 = - _mm_unpacklo_epi8(_mm_set1_epi64x(c8ev), _mm_set1_epi64x(c8od)); - __m256i c8lo = _mm256_cvtepu8_epi32(c16); - __m256i c8hi = _mm256_cvtepu8_epi32(_mm_srli_si128(c16, 8)); - __m512i i16 = _mm512_castsi256_si512(c8lo); - i16 = _mm512_inserti32x8(i16, c8hi, 1); - __m512 f16 = _mm512_cvtepi32_ps(i16); - const __m512 half_one_255 = _mm512_set1_ps(0.5f / 15.f); - const __m512 one_255 = _mm512_set1_ps(1.f / 15.f); - return simd16float32(_mm512_fmadd_ps(f16, one_255, half_one_255)); - } -}; - -template <> -struct Codec6bit : Codec6bit { - static FAISS_ALWAYS_INLINE simd16float32 - decode_16_components(const uint8_t* code, size_t i) { - // pure AVX512 implementation (not necessarily the fastest). - // see: - // https://github.com/zilliztech/knowhere/blob/main/thirdparty/faiss/faiss/impl/ScalarQuantizerCodec_avx512.h - - // clang-format off - - // 16 components, 16x6 bit=12 bytes - const __m128i bit_6v = - _mm_maskz_loadu_epi8(0b0000111111111111, code + (i >> 2) * 3); - const __m256i bit_6v_256 = _mm256_broadcast_i32x4(bit_6v); - - // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F - // 00 01 02 03 - const __m256i shuffle_mask = _mm256_setr_epi16( - 0xFF00, 0x0100, 0x0201, 0xFF02, - 0xFF03, 0x0403, 0x0504, 0xFF05, - 0xFF06, 0x0706, 0x0807, 0xFF08, - 0xFF09, 0x0A09, 0x0B0A, 0xFF0B); - const __m256i shuffled = _mm256_shuffle_epi8(bit_6v_256, shuffle_mask); - - // 0: xxxxxxxx xx543210 - // 1: xxxx5432 10xxxxxx - // 2: xxxxxx54 3210xxxx - // 3: xxxxxxxx 543210xx - const __m256i shift_right_v = _mm256_setr_epi16( - 0x0U, 0x6U, 0x4U, 0x2U, - 0x0U, 0x6U, 0x4U, 0x2U, - 0x0U, 0x6U, 0x4U, 0x2U, - 0x0U, 0x6U, 0x4U, 0x2U); - __m256i shuffled_shifted = _mm256_srlv_epi16(shuffled, shift_right_v); - - // remove unneeded bits - shuffled_shifted = - _mm256_and_si256(shuffled_shifted, _mm256_set1_epi16(0x003F)); - - // scale - const __m512 f8 = - _mm512_cvtepi32_ps(_mm512_cvtepi16_epi32(shuffled_shifted)); - const __m512 half_one_255 = _mm512_set1_ps(0.5f / 63.f); - const __m512 one_255 = _mm512_set1_ps(1.f / 63.f); - return simd16float32(_mm512_fmadd_ps(f8, one_255, half_one_255)); - - // clang-format on - } -}; - -/********************************************************** - * Quantizers (uniform and non-uniform) - **********************************************************/ - -template -struct QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::AVX512> - : QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) - : QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m512 xi = Codec::decode_16_components(code, i).f; - return simd16float32(_mm512_fmadd_ps( - xi, _mm512_set1_ps(this->vdiff), _mm512_set1_ps(this->vmin))); - } - - /// Raw codec decode without denormalization - FAISS_ALWAYS_INLINE simd16float32 - decode_16_raw(const uint8_t* code, int i) const { - return Codec::decode_16_components(code, i); - } -}; - -template -struct QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::AVX512> - : QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) - : QuantizerTemplate< - Codec, - scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m512 xi = Codec::decode_16_components(code, i).f; - return simd16float32(_mm512_fmadd_ps( - xi, - _mm512_loadu_ps(this->vdiff + i), - _mm512_loadu_ps(this->vmin + i))); - } -}; - -/********************************************************** - * Lloyd-Max scalar quantizer - **********************************************************/ - -// 1-bit Lloyd-Max AVX512: 16 comparisons → 2 bytes via mask compare. -template <> -struct QuantizerLloydMax<1, SIMDLevel::AVX512> - : QuantizerLloydMax<1, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<1, SIMDLevel::NONE>; - - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - return simd16float32(_mm512_i32gather_ps( - unpack_16x1bit_to_u32(code, i), - this->centroids, - sizeof(float))); - } - - void encode_vector(const float* x, uint8_t* code) const final { - __m512 boundary = _mm512_set1_ps(this->boundaries[0]); - for (size_t i = 0; i < this->d; i += 16) { - __m512 vals = _mm512_loadu_ps(x + i); - __mmask16 mask = _mm512_cmp_ps_mask(vals, boundary, _CMP_GT_OQ); - uint16_t bits = _cvtmask16_u32(mask); - memcpy(code + i / 8, &bits, sizeof(uint16_t)); - } - } - - void decode_vector(const uint8_t* code, float* x) const final { - for (size_t i = 0; i < this->d; i += 16) { - simd16float32 xi = - reconstruct_16_components(code, static_cast(i)); - _mm512_storeu_ps(x + i, xi.f); - } - } -}; - -// 2-4 bit Lloyd-Max AVX512: decode via gather, encode stays scalar. -#define DEFINE_LLOYD_MAX_AVX512_MULTIBIT(NBITS, UNPACK_EXPR) \ - template <> \ - struct QuantizerLloydMax \ - : QuantizerLloydMax { \ - using Base = QuantizerLloydMax; \ - \ - QuantizerLloydMax(size_t d, const std::vector& trained) \ - : Base(d, trained) { \ - assert(d % 16 == 0); \ - } \ - \ - FAISS_ALWAYS_INLINE simd16float32 \ - reconstruct_16_components(const uint8_t* code, int i) const { \ - return simd16float32(_mm512_i32gather_ps( \ - (UNPACK_EXPR), this->centroids, sizeof(float))); \ - } \ - \ - void decode_vector(const uint8_t* code, float* x) const final { \ - for (size_t i = 0; i < this->d; i += 16) { \ - simd16float32 xi = \ - reconstruct_16_components(code, static_cast(i)); \ - _mm512_storeu_ps(x + i, xi.f); \ - } \ - } \ - } - -DEFINE_LLOYD_MAX_AVX512_MULTIBIT(2, unpack_16x2bit_to_u32(code, i)); -DEFINE_LLOYD_MAX_AVX512_MULTIBIT(3, unpack_16x3bit_to_u32(code, i)); -DEFINE_LLOYD_MAX_AVX512_MULTIBIT(4, unpack_16x4bit_to_u32(code, i)); - -#undef DEFINE_LLOYD_MAX_AVX512_MULTIBIT - -// 8-bit Lloyd-Max AVX512 -template <> -struct QuantizerLloydMax<8, SIMDLevel::AVX512> - : QuantizerLloydMax<8, SIMDLevel::NONE> { - using Base = QuantizerLloydMax<8, SIMDLevel::NONE>; - - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - const __m128i packed = _mm_loadu_si128( - (const __m128i*)(code + static_cast(i))); - const __m512i indices = _mm512_cvtepu8_epi32(packed); - return simd16float32( - _mm512_i32gather_ps(indices, this->centroids, sizeof(float))); - } - - void decode_vector(const uint8_t* code, float* x) const final { - for (size_t i = 0; i < this->d; i += 16) { - simd16float32 xi = - reconstruct_16_components(code, static_cast(i)); - _mm512_storeu_ps(x + i, xi.f); - } - } -}; - -/********************************************************** - * FP16 Quantizer - **********************************************************/ - -template <> -struct QuantizerFP16 : QuantizerFP16 { - QuantizerFP16(size_t d, const std::vector& trained) - : QuantizerFP16(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m256i codei = _mm256_loadu_si256((const __m256i*)(code + 2 * i)); - return simd16float32(_mm512_cvtph_ps(codei)); - } -}; - -/********************************************************** - * BF16 Quantizer - **********************************************************/ - -template <> -struct QuantizerBF16 : QuantizerBF16 { - QuantizerBF16(size_t d, const std::vector& trained) - : QuantizerBF16(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m256i code_256i = _mm256_loadu_si256((const __m256i*)(code + 2 * i)); - __m512i code_512i = _mm512_cvtepu16_epi32(code_256i); - code_512i = _mm512_slli_epi32(code_512i, 16); - return simd16float32(_mm512_castsi512_ps(code_512i)); - } -}; - -/********************************************************** - * 8bit Direct Quantizer - **********************************************************/ - -template <> -struct Quantizer8bitDirect - : Quantizer8bitDirect { - Quantizer8bitDirect(size_t d, const std::vector& trained) - : Quantizer8bitDirect(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m128i x16 = _mm_loadu_si128((__m128i*)(code + i)); // 16 * int8 - __m512i y16 = _mm512_cvtepu8_epi32(x16); // 16 * int32 - return simd16float32(_mm512_cvtepi32_ps(y16)); // 16 * float32 - } -}; - -/********************************************************** - * 8bit Direct Signed Quantizer - **********************************************************/ - -template <> -struct Quantizer8bitDirectSigned - : Quantizer8bitDirectSigned { - Quantizer8bitDirectSigned(size_t d, const std::vector& trained) - : Quantizer8bitDirectSigned(d, trained) { - assert(d % 16 == 0); - } - - FAISS_ALWAYS_INLINE simd16float32 - reconstruct_16_components(const uint8_t* code, int i) const { - __m128i x16 = _mm_loadu_si128((__m128i*)(code + i)); // 16 * int8 - __m512i y16 = _mm512_cvtepu8_epi32(x16); // 16 * int32 - __m512i c16 = _mm512_set1_epi32(128); - __m512i z16 = _mm512_sub_epi32(y16, c16); // subtract 128 from all lanes - return simd16float32(_mm512_cvtepi32_ps(z16)); // 16 * float32 - } -}; - -/********************************************************** - * Similarities (L2 and IP) - **********************************************************/ - -template <> -struct SimilarityL2 { - static constexpr int simdwidth = 16; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512; - static constexpr MetricType metric_type = METRIC_L2; - - const float *y, *yi; - - explicit SimilarityL2(const float* y) : y(y), yi(nullptr) {} - - simd16float32 accu16; - - FAISS_ALWAYS_INLINE void begin_16() { - accu16.clear(); - yi = y; - } - - FAISS_ALWAYS_INLINE void add_16_components(simd16float32 x) { - simd16float32 yiv(yi); - yi += 16; - simd16float32 tmp = yiv - x; - accu16 = accu16 + tmp * tmp; - } - - FAISS_ALWAYS_INLINE void add_16_components_2( - simd16float32 x, - simd16float32 y_2) { - simd16float32 tmp = y_2 - x; - accu16 = accu16 + tmp * tmp; - } - - FAISS_ALWAYS_INLINE float result_16() { - return horizontal_add(accu16); - } - - static void adjust_query_for_raw_decode( - const float* x, - float* q_adj, - size_t d, - float vmin, - float vdiff, - float& scale_factor, - float& bias) { - float inv_vdiff = (vdiff != 0) ? 1.0f / vdiff : 0.0f; - for (size_t i = 0; i < d; i++) { - q_adj[i] = (x[i] - vmin) * inv_vdiff; - } - scale_factor = vdiff * vdiff; - bias = 0; - } -}; - -template <> -struct SimilarityIP { - static constexpr int simdwidth = 16; - static constexpr SIMDLevel simd_level = SIMDLevel::AVX512; - static constexpr MetricType metric_type = METRIC_INNER_PRODUCT; - - const float *y, *yi; - - explicit SimilarityIP(const float* y) : y(y), yi(nullptr) {} - - simd16float32 accu16; - - FAISS_ALWAYS_INLINE void begin_16() { - accu16.clear(); - yi = y; - } - - FAISS_ALWAYS_INLINE void add_16_components(simd16float32 x) { - simd16float32 yiv(yi); - yi += 16; - accu16 = accu16 + yiv * x; - } - - FAISS_ALWAYS_INLINE void add_16_components_2( - simd16float32 x1, - simd16float32 x2) { - accu16 = accu16 + x1 * x2; - } - - FAISS_ALWAYS_INLINE float result_16() { - return horizontal_add(accu16); - } - - static void adjust_query_for_raw_decode( - const float* x, - float* q_adj, - size_t d, - float vmin, - float vdiff, - float& scale_factor, - float& bias) { - float sum_q = 0; - for (size_t i = 0; i < d; i++) { - q_adj[i] = x[i]; - sum_q += x[i]; - } - scale_factor = vdiff; - bias = vmin * sum_q; - } -}; - -/********************************************************** - * Distance Computers - **********************************************************/ - -template -struct DCTemplate - : SQDistanceComputer { - using Sim = Similarity; - - Quantizer quant; - - // Pre-adjusted query buffer for uniform quantizers - std::vector q_adj; - float scale_factor = 0; - float bias = 0; - - static constexpr bool has_decode_raw() { - return requires(const Quantizer& q, const uint8_t* c, int i) { - { q.decode_16_raw(c, i) }; - }; - } - - DCTemplate(size_t d, const std::vector& trained) - : quant(d, trained) { - if constexpr (has_decode_raw()) { - q_adj.resize(d); - } - } - - float compute_distance(const float* x, const uint8_t* code) const { - Similarity sim(x); - sim.begin_16(); - for (size_t i = 0; i < quant.d; i += 16) { - simd16float32 xi = quant.reconstruct_16_components(code, i); - sim.add_16_components(xi); - } - return sim.result_16(); - } - - float compute_code_distance(const uint8_t* code1, const uint8_t* code2) - const { - Similarity sim(nullptr); - sim.begin_16(); - for (size_t i = 0; i < quant.d; i += 16) { - simd16float32 x1 = quant.reconstruct_16_components(code1, i); - simd16float32 x2 = quant.reconstruct_16_components(code2, i); - sim.add_16_components_2(x1, x2); - } - return sim.result_16(); - } - - void set_query(const float* x) final { - q = x; - if constexpr (has_decode_raw()) { - Sim::adjust_query_for_raw_decode( - x, - q_adj.data(), - quant.d, - quant.vmin, - quant.vdiff, - scale_factor, - bias); - } - } - - float query_to_code_predecoded(const uint8_t* code) const { - Similarity sim(q_adj.data()); - sim.begin_16(); - for (size_t i = 0; i < quant.d; i += 16) { - simd16float32 xi = quant.decode_16_raw(code, i); - sim.add_16_components(xi); - } - return bias + scale_factor * sim.result_16(); - } - - float symmetric_dis(idx_t i, idx_t j) override { - return compute_code_distance( - codes + i * code_size, codes + j * code_size); - } - - float query_to_code(const uint8_t* code) const final { - if constexpr (has_decode_raw()) { - return query_to_code_predecoded(code); - } else { - return compute_distance(q, code); - } - } - - void query_to_codes_batch_4( - const uint8_t* code_0, - const uint8_t* code_1, - const uint8_t* code_2, - const uint8_t* code_3, - float& dis0, - float& dis1, - float& dis2, - float& dis3) const final { - Similarity sim0(q); - Similarity sim1(q); - Similarity sim2(q); - Similarity sim3(q); - - sim0.begin_16(); - sim1.begin_16(); - sim2.begin_16(); - sim3.begin_16(); - - for (size_t i = 0; i < quant.d; i += 16) { - simd16float32 xi0 = quant.reconstruct_16_components(code_0, i); - simd16float32 xi1 = quant.reconstruct_16_components(code_1, i); - simd16float32 xi2 = quant.reconstruct_16_components(code_2, i); - simd16float32 xi3 = quant.reconstruct_16_components(code_3, i); - sim0.add_16_components(xi0); - sim1.add_16_components(xi1); - sim2.add_16_components(xi2); - sim3.add_16_components(xi3); - } - - dis0 = sim0.result_16(); - dis1 = sim1.result_16(); - dis2 = sim2.result_16(); - dis3 = sim3.result_16(); - } -}; - template struct DistanceComputerByte : SQDistanceComputer { @@ -673,7 +21,8 @@ struct DistanceComputerByte int d; std::vector tmp; - DistanceComputerByte(int d, const std::vector&) : d(d), tmp(d) {} + DistanceComputerByte(int d_in, const std::vector&) + : d(d_in), tmp(d_in) {} int compute_code_distance(const uint8_t* code1, const uint8_t* code2) const { @@ -740,8 +89,8 @@ struct DistanceComputerByteSigned int d; std::vector tmp; - DistanceComputerByteSigned(int d, const std::vector&) - : d(d), tmp(d) {} + DistanceComputerByteSigned(int d_in, const std::vector&) + : d(d_in), tmp(d_in) {} int compute_code_distance(const uint8_t* code1, const uint8_t* code2) const { @@ -787,50 +136,7 @@ struct DistanceComputerByteSigned } }; -/********************************************************** - * TurboQuant masked_sum AVX512 specialization - **********************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - __m512 acc = _mm512_setzero_ps(); - size_t i = 0; - size_t full_16 = (d / 16) * 16; - for (; i < full_16; i += 16) { - uint16_t mask16; - memcpy(&mask16, bits + i / 8, sizeof(mask16)); - __mmask16 k = _cvtu32_mask16(mask16); - __m512 vals = _mm512_loadu_ps(arr + i); - acc = _mm512_mask_add_ps(acc, k, acc, vals); - } - float result = _mm512_reduce_add_ps(acc); - if (i < d) { - size_t remaining = d - i; - __mmask16 tail_mask = _cvtu32_mask16((1u << remaining) - 1); - __m512 tail_vals = _mm512_maskz_loadu_ps(tail_mask, arr + i); - uint16_t bits_tail = 0; - size_t bytes_remaining = (remaining + 7) / 8; - memcpy(&bits_tail, bits + i / 8, bytes_remaining); - __mmask16 bits_k = _cvtu32_mask16(bits_tail); - __mmask16 combined = _kand_mask16(tail_mask, bits_k); - __m512 masked_tail = _mm512_maskz_mov_ps(combined, tail_vals); - result += _mm512_reduce_add_ps(masked_tail); - } - return result; -} - } // namespace scalar_quantizer } // namespace faiss -#ifndef SQ_AVX512_SKIP_DISPATCH -#define THE_LEVEL_TO_DISPATCH SIMDLevel::AVX512 #include -#endif - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h index a02f8fe82..885dad010 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-dispatch.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #ifndef THE_LEVEL_TO_DISPATCH @@ -36,35 +37,6 @@ template inline constexpr SIMDLevel rabitq_popcount_level = SL0 == SIMDLevel::AVX512_SPR ? SIMDLevel::AVX512_VPOPCNT : SL0; -/******************************************************************* - * TurboQuant SIMD kernel: masked_sum - * Compute sum of arr[j] where bit j of the bitmask is set. - * NONE specialization is inline; AVX2/AVX512/NEON specializations - * live in sq-avx2.cpp / sq-avx512.cpp / sq-neon.cpp. - *******************************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -inline float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - float result = 0; - for (size_t byte_idx = 0; byte_idx < (d + 7) / 8; byte_idx++) { - uint8_t b = bits[byte_idx]; - size_t base = byte_idx * 8; - size_t end = std::min(base + 8, d); - for (size_t j = base; j < end; j++) { - if (b & (1 << (j - base))) { - result += arr[j]; - } - } - } - return result; -} - /******************************************************************* * Full TurboQuant DC — lives here because it needs both * quantizers.h (QuantizerTurboQuantFull, SQTurboQFactors) and @@ -73,8 +45,10 @@ inline float turboq_masked_sum( *******************************************************************/ template struct DCTurboQuantFull : ScalarQuantizer::TurboQuantRefine::DistanceComputer { + // The AVX-512 levels share the AVX512 masked_sum specialization. + static constexpr SIMDLevel SUM_LEVEL = simd512_level_selector::value; using Sim = Similarity; - QuantizerTurboQuantFull quant; + QuantizerTurboQuantFull quant; std::vector query; std::vector query_proj; float q_norm_sq = 0; @@ -277,19 +251,19 @@ struct DCTurboQuantFull : ScalarQuantizer::TurboQuantRefine::DistanceComputer { mse_popcnt_scale * static_cast(pop); } else { // Float path: masked accumulation - float pos_sum = turboq_masked_sum(query.data(), code, d); + float pos_sum = masked_sum(query.data(), code, d); mse_dot = scaled_c0 * total_q_sum + delta_centroid * pos_sum; } } else if constexpr (NBits == 3) { // 2-bit MSE: decompose into 3 masked sums over bit-planes. size_t pb = quant.mse_plane_bytes; - float s0 = turboq_masked_sum(query.data(), code, d); - float s1 = turboq_masked_sum(query.data(), code + pb, d); + float s0 = masked_sum(query.data(), code, d); + float s1 = masked_sum(query.data(), code + pb, d); for (size_t i = 0; i < pb; i++) { scratch_and[i] = code[i] & code[pb + i]; } float s01 = - turboq_masked_sum(query.data(), scratch_and.data(), d); + masked_sum(query.data(), scratch_and.data(), d); mse_dot = mse_multi_base + mse_coeff_s0 * s0 + mse_coeff_s1 * s1 + mse_coeff_s01 * s01; } else { @@ -336,7 +310,7 @@ struct DCTurboQuantFull : ScalarQuantizer::TurboQuantRefine::DistanceComputer { qjl_dot = qjl_coeff * gamma * (2.0f * pos_sum - total_qproj_sum); } else { float pos_sum = - turboq_masked_sum(query_proj.data(), qjl_code, d); + masked_sum(query_proj.data(), qjl_code, d); qjl_dot = qjl_coeff * gamma * (2.0f * pos_sum - total_qproj_sum); } @@ -373,6 +347,50 @@ constexpr bool is_dimension_compatible(size_t d) { } } +// Distance computers and scanners. At AVX512 the 16-bit float codecs decode +// a partial last block, so they take any d. +template +constexpr bool is_dimension_compatible( + size_t d, + ScalarQuantizer::QuantizerType qtype) { + return (SL2 == SIMDLevel::AVX512 && + (qtype == ScalarQuantizer::QT_fp16 || + qtype == ScalarQuantizer::QT_bf16)) || + is_dimension_compatible(d); +} + +/// Calls f with the DCTemplate type for (Quantizer, Sim, SL2) and d. The +/// 16-bit float quantizers and the QT_8bit inner product use it. Four +/// accumulators per code hide the FMA latency at a large d. At a small d their +/// reduction costs more than it saves. At AVX512 they are faster only on AMD +/// (SIMDConfig::sq_avx512_4_accumulators). +template +auto with_dc_template(size_t d, F f) { + if constexpr (SL2 == SIMDLevel::AVX2 || SL2 == SIMDLevel::AVX512) { + if (d >= 384 && + (SL2 == SIMDLevel::AVX2 || SIMDConfig::sq_avx512_4_accumulators)) { + return f.template + operator()>(); + } + } + return f.template operator()>(); +} + +/// with_dc_template for QT_8bit. Only its inner product has a four-accumulator +/// loop. +template +auto with_8bit_dc_template(size_t d, F f) { + using Quantizer = QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + SL2>; + if constexpr (Sim::metric_type == METRIC_INNER_PRODUCT) { + return with_dc_template(d, f); + } else { + return f.template operator()>(); + } +} + /******************************************************************* * sq_select_quantizer: the big switch returning SQuantizer* *******************************************************************/ @@ -487,10 +505,13 @@ SQDistanceComputer* select_distance_computer_body( const std::vector& trained) { // Return nullptr for incompatible dimensions in SIMD cases if constexpr (SL2 != SIMDLevel::NONE) { - if (!is_dimension_compatible(d)) { + if (!is_dimension_compatible(d, qtype)) { return nullptr; } } + auto new_dc = [&]() -> SQDistanceComputer* { + return new DC(d, trained); + }; switch (qtype) { case ScalarQuantizer::QT_8bit_uniform: return new DCTemplate< @@ -511,13 +532,7 @@ SQDistanceComputer* select_distance_computer_body( SL2>(d, trained); case ScalarQuantizer::QT_8bit: - return new DCTemplate< - QuantizerTemplate< - Codec8bit, - QuantizerTemplateScaling::NON_UNIFORM, - SL2>, - Sim, - SL2>(d, trained); + return with_8bit_dc_template(d, new_dc); case ScalarQuantizer::QT_6bit: return new DCTemplate< @@ -538,10 +553,10 @@ SQDistanceComputer* select_distance_computer_body( SL2>(d, trained); case ScalarQuantizer::QT_fp16: - return new DCTemplate, Sim, SL2>(d, trained); + return with_dc_template, Sim, SL2>(d, new_dc); case ScalarQuantizer::QT_bf16: - return new DCTemplate, Sim, SL2>(d, trained); + return with_dc_template, Sim, SL2>(d, new_dc); case ScalarQuantizer::QT_8bit_direct: if constexpr (is_avx512_family) { @@ -705,7 +720,7 @@ InvertedListScanner* sq_select_InvertedListScanner( [&]() -> InvertedListScanner* { // Return nullptr for incompatible dimensions in SIMD cases if constexpr (SL2 != SIMDLevel::NONE) { - if (!is_dimension_compatible(d)) { + if (!is_dimension_compatible(d, qtype)) { return nullptr; } } @@ -727,13 +742,7 @@ InvertedListScanner* sq_select_InvertedListScanner( Similarity, SL2>>(); case ScalarQuantizer::QT_8bit: - return scan.template operator(), - QuantizerTemplateScaling::NON_UNIFORM, - SL2>, - Similarity, - SL2>>(); + return with_8bit_dc_template(d, scan); case ScalarQuantizer::QT_4bit: return scan.template operator()( Similarity, SL2>>(); case ScalarQuantizer::QT_fp16: - return scan.template - operator(), Similarity, SL2>>(); + return with_dc_template, Similarity, SL2>( + d, scan); case ScalarQuantizer::QT_bf16: - return scan.template - operator(), Similarity, SL2>>(); + return with_dc_template, Similarity, SL2>( + d, scan); case ScalarQuantizer::QT_8bit_direct: if constexpr (is_avx512_family) { if (d % 32 == 0) { diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp index b3fd6346c..ecc53cb3b 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-neon.cpp @@ -5,11 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #include -#include #include #include @@ -17,6 +14,7 @@ #include #include #include +#include namespace faiss { @@ -105,14 +103,15 @@ template <> struct Codec8bit : Codec8bit { static FAISS_ALWAYS_INLINE simd8float32 decode_8_components(const uint8_t* code, size_t i) { - float32_t result[8] = {}; - for (size_t j = 0; j < 8; j++) { - result[j] = - Codec8bit::decode_component(code, i + j); - } - float32x4_t res1 = vld1q_f32(result); - float32x4_t res2 = vld1q_f32(result + 4); - return simd8float32(float32x4x2_t{res1, res2}); + const uint16x8_t c16 = vmovl_u8(vld1_u8(code + i)); + const float32x4_t lo = vcvtq_f32_u32(vmovl_u16(vget_low_u16(c16))); + const float32x4_t hi = vcvtq_f32_u32(vmovl_u16(vget_high_u16(c16))); + const float32x4_t one_255 = vdupq_n_f32(1.f / 255.f); + const float32x4_t half_one_255 = vdupq_n_f32(0.5f / 255.f); + return simd8float32( + float32x4x2_t{ + vfmaq_f32(half_one_255, lo, one_255), + vfmaq_f32(half_one_255, hi, one_255)}); } }; @@ -159,12 +158,12 @@ struct QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 8 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -198,12 +197,12 @@ struct QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, SIMDLevel::NONE> { - QuantizerTemplate(size_t d, const std::vector& trained) + QuantizerTemplate(size_t d_in, const std::vector& trained) : QuantizerTemplate< Codec, scalar_quantizer::QuantizerTemplateScaling::NON_UNIFORM, - SIMDLevel::NONE>(d, trained) { - assert(d % 8 == 0); + SIMDLevel::NONE>(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -234,9 +233,9 @@ struct QuantizerTemplate< : QuantizerLloydMax { \ using Base = QuantizerLloydMax; \ \ - QuantizerLloydMax(size_t d, const std::vector& trained) \ - : Base(d, trained) { \ - assert(d % 8 == 0); \ + QuantizerLloydMax(size_t d_in, const std::vector& trained) \ + : Base(d_in, trained) { \ + assert(d_in % 8 == 0); \ } \ \ FAISS_ALWAYS_INLINE simd8float32 \ @@ -268,9 +267,9 @@ struct QuantizerLloydMax<8, SIMDLevel::ARM_NEON> : QuantizerLloydMax<8, SIMDLevel::NONE> { using Base = QuantizerLloydMax<8, SIMDLevel::NONE>; - QuantizerLloydMax(size_t d, const std::vector& trained) - : Base(d, trained) { - assert(d % 8 == 0); + QuantizerLloydMax(size_t d_in, const std::vector& trained) + : Base(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -296,9 +295,9 @@ struct QuantizerLloydMax<8, SIMDLevel::ARM_NEON> template <> struct QuantizerFP16 : QuantizerFP16 { - QuantizerFP16(size_t d, const std::vector& trained) - : QuantizerFP16(d, trained) { - assert(d % 8 == 0); + QuantizerFP16(size_t d_in, const std::vector& trained) + : QuantizerFP16(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -317,9 +316,9 @@ struct QuantizerFP16 : QuantizerFP16 { template <> struct QuantizerBF16 : QuantizerBF16 { - QuantizerBF16(size_t d, const std::vector& trained) - : QuantizerBF16(d, trained) { - assert(d % 8 == 0); + QuantizerBF16(size_t d_in, const std::vector& trained) + : QuantizerBF16(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -341,9 +340,9 @@ struct QuantizerBF16 : QuantizerBF16 { template <> struct Quantizer8bitDirect : Quantizer8bitDirect { - Quantizer8bitDirect(size_t d, const std::vector& trained) - : Quantizer8bitDirect(d, trained) { - assert(d % 8 == 0); + Quantizer8bitDirect(size_t d_in, const std::vector& trained) + : Quantizer8bitDirect(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -366,9 +365,9 @@ struct Quantizer8bitDirect template <> struct Quantizer8bitDirectSigned : Quantizer8bitDirectSigned { - Quantizer8bitDirectSigned(size_t d, const std::vector& trained) - : Quantizer8bitDirectSigned(d, trained) { - assert(d % 8 == 0); + Quantizer8bitDirectSigned(size_t d_in, const std::vector& trained) + : Quantizer8bitDirectSigned(d_in, trained) { + assert(d_in % 8 == 0); } FAISS_ALWAYS_INLINE simd8float32 @@ -398,7 +397,7 @@ struct SimilarityL2 { const float *y, *yi; - explicit SimilarityL2(const float* y) : y(y), yi(nullptr) {} + explicit SimilarityL2(const float* y_in) : y(y_in), yi(nullptr) {} simd8float32 accu8; @@ -450,7 +449,7 @@ struct SimilarityIP { const float *y, *yi; - explicit SimilarityIP(const float* y) : y(y), yi(nullptr) {} + explicit SimilarityIP(const float* y_in) : y(y_in), yi(nullptr) {} simd8float32 accu8; @@ -618,6 +617,97 @@ struct DCTemplate } }; +// QT_8bit + L2. With a, rmin from sq8_coefficients.h and e = q - rmin, each +// term is (e_i - a_i * c_i)^2: one fmls and one fmla per 4 dims, instead of +// separate codec, vmin/vdiff, sub, mul and add steps. +template <> +struct DCTemplate< + QuantizerTemplate< + Codec8bit, + QuantizerTemplateScaling::NON_UNIFORM, + SIMDLevel::ARM_NEON>, + SimilarityL2, + SIMDLevel::ARM_NEON> : SQDistanceComputer { + using Sim = SimilarityL2; + + size_t d; + std::vector a, rmin, e; + + DCTemplate(size_t d_in, const std::vector& trained) + : d(d_in), a(d_in), rmin(d_in), e(d_in) { + assert(d % 8 == 0); + sq8::make_coefficients(trained.data(), d, a.data(), rmin.data()); + } + + void set_query(const float* x) final { + q = x; + for (size_t i = 0; i < d; i++) { + e[i] = x[i] - rmin[i]; + } + } + + // Each code has its own accumulators, so the batched results equal the + // single-code ones bit for bit. + template + FAISS_ALWAYS_INLINE void l2( + const uint8_t* const (&code_ptrs)[N], + float (&dis)[N]) const { + float32x4_t acc[N][2] = {}; + for (size_t i = 0; i < d; i += 8) { + const float32x4_t a0 = vld1q_f32(a.data() + i); + const float32x4_t a1 = vld1q_f32(a.data() + i + 4); + const float32x4_t e0 = vld1q_f32(e.data() + i); + const float32x4_t e1 = vld1q_f32(e.data() + i + 4); + for (size_t n = 0; n < N; n++) { + const uint16x8_t c16 = vmovl_u8(vld1_u8(code_ptrs[n] + i)); + const float32x4_t t0 = vfmsq_f32( + e0, a0, vcvtq_f32_u32(vmovl_u16(vget_low_u16(c16)))); + const float32x4_t t1 = + vfmsq_f32(e1, a1, vcvtq_f32_u32(vmovl_high_u16(c16))); + acc[n][0] = vfmaq_f32(acc[n][0], t0, t0); + acc[n][1] = vfmaq_f32(acc[n][1], t1, t1); + } + } + for (size_t n = 0; n < N; n++) { + dis[n] = vaddvq_f32(vaddq_f32(acc[n][0], acc[n][1])); + } + } + + float query_to_code(const uint8_t* code) const final { + float dis[1]; + l2<1>({code}, dis); + return dis[0]; + } + + void query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const final { + float dis[4]; + l2<4>({code_0, code_1, code_2, code_3}, dis); + dis0 = dis[0]; + dis1 = dis[1]; + dis2 = dis[2]; + dis3 = dis[3]; + } + + float symmetric_dis(idx_t i, idx_t j) override { + const uint8_t* c1 = codes + i * code_size; + const uint8_t* c2 = codes + j * code_size; + float accu = 0; + for (size_t k = 0; k < d; k++) { + const float diff = a[k] * float(int(c1[k]) - int(c2[k])); + accu += diff * diff; + } + return accu; + } +}; + // Byte-domain kernels for QT_8bit_direct{,_signed}. The dispatch only // selects them when d % 16 == 0, so no loop needs a tail. @@ -684,8 +774,9 @@ struct DistanceComputerByte int d; std::vector tmp; - DistanceComputerByte(int d, const std::vector&) : d(d), tmp(d) { - FAISS_THROW_IF_NOT(d % 16 == 0); + DistanceComputerByte(int d_in, const std::vector&) + : d(d_in), tmp(d_in) { + FAISS_THROW_IF_NOT(d_in % 16 == 0); } int compute_code_distance(const uint8_t* code1, const uint8_t* code2) @@ -726,9 +817,9 @@ struct DistanceComputerByteSigned int d; std::vector tmp; - DistanceComputerByteSigned(int d, const std::vector&) - : d(d), tmp(d) { - FAISS_THROW_IF_NOT(d % 16 == 0); + DistanceComputerByteSigned(int d_in, const std::vector&) + : d(d_in), tmp(d_in) { + FAISS_THROW_IF_NOT(d_in % 16 == 0); } int compute_code_distance(const uint8_t* code1, const uint8_t* code2) @@ -762,93 +853,8 @@ struct DistanceComputerByteSigned } }; -/********************************************************** - * TurboQuant masked_sum NEON specialization (scalar fallback) - **********************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - float result = 0; - for (size_t byte_idx = 0; byte_idx < (d + 7) / 8; byte_idx++) { - uint8_t b = bits[byte_idx]; - size_t base = byte_idx * 8; - size_t end = std::min(base + 8, d); - for (size_t j = base; j < end; j++) { - if (b & (1 << (j - base))) { - result += arr[j]; - } - } - } - return result; -} - } // namespace scalar_quantizer } // namespace faiss #define THE_LEVEL_TO_DISPATCH SIMDLevel::ARM_NEON #include - -#ifdef COMPILE_SIMD_ARM_SVE - -// ARM_SVE: SVE is a superset of NEON. Forward to the NEON implementation -// until a dedicated SVE specialization is written. - -namespace faiss { -namespace scalar_quantizer { - -// NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) -template <> -ScalarQuantizer::SQuantizer* sq_select_quantizer( - QuantizerType qtype, - size_t d, - const std::vector& trained) { - return sq_select_quantizer(qtype, d, trained); -} - -// NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) -template <> -SQDistanceComputer* sq_select_distance_computer( - MetricType metric, - ScalarQuantizer::QuantizerType qtype, - size_t d, - const std::vector& trained) { - return sq_select_distance_computer( - metric, qtype, d, trained); -} - -// NOLINTNEXTLINE(facebook-hte-MisplacedTemplateSpecialization) -template <> -InvertedListScanner* sq_select_InvertedListScanner( - QuantizerType qtype, - MetricType mt, - size_t d, - size_t code_size, - const std::vector& trained, - const Index* quantizer, - bool store_pairs, - const IDSelector* sel, - bool by_residual) { - return sq_select_InvertedListScanner( - qtype, - mt, - d, - code_size, - trained, - quantizer, - store_pairs, - sel, - by_residual); -} - -} // namespace scalar_quantizer -} // namespace faiss - -#endif // COMPILE_SIMD_ARM_SVE - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp index 5c79174a2..8a83718d2 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq-rvv.cpp @@ -5,19 +5,22 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_RISCV_RVV - #include #include #include #include #include +#include +#include #include -#include #include #include +#if !defined(__riscv_zvfhmin) && !defined(__riscv_zvfh) +#error "RISCV_RVV scalar quantizers require Zvfhmin; compile this file with -march including _zvfhmin (e.g. rv64gcv_zvfhmin)" +#endif + namespace faiss { namespace scalar_quantizer { @@ -84,39 +87,379 @@ struct QuantizerTemplate< }; template <> -struct QuantizerFP16 : QuantizerFP16 { +struct QuantizerFP16 + : QuantizerFP16Base { QuantizerFP16(size_t d, const std::vector& trained) - : QuantizerFP16(d, trained) {} + : QuantizerFP16Base(d, trained) {} + + void decode_vector(const uint8_t* code, float* x) const final { + const auto* code16 = reinterpret_cast(code); + size_t i = 0; + const size_t d = this->d; + while (i < d) { + const size_t vl = __riscv_vsetvl_e16m4(d - i); + vuint16m4_t vh = __riscv_vle16_v_u16m4(code16 + i, vl); + vbool4_t is_nan = __riscv_vmsgtu_vx_u16m4_b4( + __riscv_vand_vx_u16m4(vh, 0x7FFF, vl), 0x7C00, vl); + vfloat32m8_t vf = __riscv_vfwcvt_f_f_v_f32m8_m( + __riscv_vmnot_m_b4(is_nan, vl), + __riscv_vreinterpret_v_u16m4_f16m4(vh), + vl); + vf = __riscv_vfsub_vf_f32m8_m( + __riscv_vmnot_m_b4(is_nan, vl), vf, 0.0f, vl); + if (__riscv_vfirst_m_b4(is_nan, vl) >= 0) { + vint32m8_t bits = __riscv_vsext_vf2_i32m8( + __riscv_vreinterpret_v_u16m4_i16m4(vh), vl); + bits = __riscv_vsll_vx_i32m8(bits, 13, vl); + bits = __riscv_vand_vx_i32m8(bits, -0x70002000, vl); + bits = __riscv_vor_vx_i32m8(bits, 0x70000000, vl); + vf = __riscv_vmerge_vvm_f32m8( + vf, + __riscv_vreinterpret_v_i32m8_f32m8(bits), + is_nan, + vl); + } + __riscv_vse32_v_f32m8(x + i, vf, vl); + i += vl; + } + } }; template <> -struct QuantizerBF16 : QuantizerBF16 { +struct QuantizerBF16 + : QuantizerBF16Base { QuantizerBF16(size_t d, const std::vector& trained) - : QuantizerBF16(d, trained) {} + : QuantizerBF16Base(d, trained) {} + + void decode_vector(const uint8_t* code, float* x) const final { + const auto* code16 = reinterpret_cast(code); + size_t i = 0; + const size_t d = this->d; + while (i < d) { + const size_t vl = __riscv_vsetvl_e16m4(d - i); + vuint16m4_t v = __riscv_vle16_v_u16m4(code16 + i, vl); + vuint32m8_t w = __riscv_vzext_vf2_u32m8(v, vl); + w = __riscv_vsll_vx_u32m8(w, 16, vl); + __riscv_vse32_v_f32m8( + x + i, __riscv_vreinterpret_v_u32m8_f32m8(w), vl); + i += vl; + } + } }; template <> struct Quantizer8bitDirect - : Quantizer8bitDirect { + : Quantizer8bitDirectBase { Quantizer8bitDirect(size_t d, const std::vector& trained) - : Quantizer8bitDirect(d, trained) {} + : Quantizer8bitDirectBase(d, trained) {} + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + const size_t d = this->d; + while (i < d) { + const size_t vl = __riscv_vsetvl_e8m2(d - i); + vuint8m2_t b = __riscv_vle8_v_u8m2(code + i, vl); + vuint16m4_t u = __riscv_vzext_vf2_u16m4(b, vl); + vfloat32m8_t f = __riscv_vfwcvt_f_xu_v_f32m8(u, vl); + __riscv_vse32_v_f32m8(x + i, f, vl); + i += vl; + } + } + + void encode_vector(const float* x, uint8_t* code) const final { + std::size_t i = 0; + while (i < this->d) { + const std::size_t vl = __riscv_vsetvl_e32m4(this->d - i); + const vfloat32m4_t input = __riscv_vle32_v_f32m4(x + i, vl); + const vuint32m4_t converted = + __riscv_vfcvt_rtz_xu_f_v_u32m4(input, vl); + const vuint16m2_t half = __riscv_vnsrl_wx_u16m2(converted, 0, vl); + const vuint8m1_t bytes = __riscv_vnsrl_wx_u8m1(half, 0, vl); + __riscv_vse8_v_u8m1(code + i, bytes, vl); + i += vl; + } + } }; template <> struct Quantizer8bitDirectSigned - : Quantizer8bitDirectSigned { + : Quantizer8bitDirectSignedBase { Quantizer8bitDirectSigned(size_t d, const std::vector& trained) - : Quantizer8bitDirectSigned(d, trained) {} + : Quantizer8bitDirectSignedBase(d, trained) {} + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + const size_t d = this->d; + while (i < d) { + const size_t vl = __riscv_vsetvl_e8m2(d - i); + vint8m2_t v = __riscv_vle8_v_i8m2( + reinterpret_cast(code) + i, vl); + v = __riscv_vxor_vx_i8m2(v, -128, vl); + vint16m4_t v16 = __riscv_vsext_vf2_i16m4(v, vl); + vfloat32m8_t f = __riscv_vfwcvt_f_x_v_f32m8(v16, vl); + __riscv_vse32_v_f32m8(x + i, f, vl); + i += vl; + } + } +}; + +template <> +struct QuantizerLloydMax<1, SIMDLevel::RISCV_RVV> + : QuantizerLloydMaxBase<1, SIMDLevel::RISCV_RVV> { + using Base = QuantizerLloydMaxBase<1, SIMDLevel::RISCV_RVV>; + + QuantizerLloydMax(size_t d, const std::vector& trained) + : Base(d, trained) {} + + FAISS_ALWAYS_INLINE vfloat32m8_t + reconstruct_m8_components(const uint8_t* code, size_t i, size_t vl) const { + const size_t byte_base = i >> 3; + const size_t byte_vl = ((i + vl - 1) >> 3) - byte_base + 1; + vuint8m2_t packed = __riscv_vle8_v_u8m2(code + byte_base, byte_vl); + vuint32m8_t packed32 = __riscv_vzext_vf4_u32m8(packed, byte_vl); + vuint32m8_t comp = + __riscv_vadd_vx_u32m8(__riscv_vid_v_u32m8(vl), i, vl); + vuint32m8_t rel = __riscv_vsub_vx_u32m8( + __riscv_vsrl_vx_u32m8(comp, 3, vl), byte_base, vl); + vuint32m8_t bytes = __riscv_vrgather_vv_u32m8(packed32, rel, vl); + vuint32m8_t shift = __riscv_vand_vx_u32m8(comp, 7, vl); + vuint32m8_t idx = __riscv_vand_vx_u32m8( + __riscv_vsrl_vv_u32m8(bytes, shift, vl), 1, vl); + vuint32m8_t off = __riscv_vsll_vx_u32m8(idx, 2, vl); + return __riscv_vluxei32_v_f32m8(this->centroids, off, vl); + } + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + while (i < this->d) { + size_t vl = __riscv_vsetvl_e32m8(this->d - i); + vfloat32m8_t v = reconstruct_m8_components(code, i, vl); + __riscv_vse32_v_f32m8(x + i, v, vl); + i += vl; + } + } +}; + +template <> +struct QuantizerLloydMax<2, SIMDLevel::RISCV_RVV> + : QuantizerLloydMaxBase<2, SIMDLevel::RISCV_RVV> { + using Base = QuantizerLloydMaxBase<2, SIMDLevel::RISCV_RVV>; + + QuantizerLloydMax(size_t d, const std::vector& trained) + : Base(d, trained) {} + + FAISS_ALWAYS_INLINE vfloat32m8_t + reconstruct_m8_components(const uint8_t* code, size_t i, size_t vl) const { + const size_t byte_base = i >> 2; + const size_t byte_vl = ((i + vl - 1) >> 2) - byte_base + 1; + vuint8m2_t packed = __riscv_vle8_v_u8m2(code + byte_base, byte_vl); + vuint32m8_t packed32 = __riscv_vzext_vf4_u32m8(packed, byte_vl); + vuint32m8_t comp = + __riscv_vadd_vx_u32m8(__riscv_vid_v_u32m8(vl), i, vl); + vuint32m8_t rel = __riscv_vsub_vx_u32m8( + __riscv_vsrl_vx_u32m8(comp, 2, vl), byte_base, vl); + vuint32m8_t bytes = __riscv_vrgather_vv_u32m8(packed32, rel, vl); + vuint32m8_t shift = __riscv_vsll_vx_u32m8( + __riscv_vand_vx_u32m8(comp, 3, vl), 1, vl); + vuint32m8_t idx = __riscv_vand_vx_u32m8( + __riscv_vsrl_vv_u32m8(bytes, shift, vl), 3, vl); + vuint32m8_t off = __riscv_vsll_vx_u32m8(idx, 2, vl); + return __riscv_vluxei32_v_f32m8(this->centroids, off, vl); + } + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + while (i < this->d) { + size_t vl = __riscv_vsetvl_e32m8(this->d - i); + vfloat32m8_t v = reconstruct_m8_components(code, i, vl); + __riscv_vse32_v_f32m8(x + i, v, vl); + i += vl; + } + } +}; + +template <> +struct QuantizerLloydMax<3, SIMDLevel::RISCV_RVV> + : QuantizerLloydMaxBase<3, SIMDLevel::RISCV_RVV> { + using Base = QuantizerLloydMaxBase<3, SIMDLevel::RISCV_RVV>; + + QuantizerLloydMax(size_t d, const std::vector& trained) + : Base(d, trained) {} + + FAISS_ALWAYS_INLINE vfloat32m8_t + reconstruct_m8_components(const uint8_t* code, size_t i, size_t vl) const { + vuint32m8_t idx0 = + __riscv_vadd_vx_u32m8(__riscv_vid_v_u32m8(vl), i, vl); + vuint32m8_t bitpos = __riscv_vmul_vx_u32m8(idx0, 3, vl); + vuint32m8_t byteoff = __riscv_vsrl_vx_u32m8(bitpos, 3, vl); + vuint32m8_t shift = __riscv_vand_vx_u32m8(bitpos, 7, vl); + size_t last = i + vl - 1; + size_t last_used = (3 * last + 2) >> 3; + vuint8m2_t lo = __riscv_vluxei32_v_u8m2(code, byteoff, vl); + vuint8m2_t hi = __riscv_vluxei32_v_u8m2( + code, + __riscv_vminu_vx_u32m8( + __riscv_vadd_vx_u32m8(byteoff, 1, vl), last_used, vl), + vl); + vuint32m8_t w = __riscv_vor_vv_u32m8( + __riscv_vzext_vf4_u32m8(lo, vl), + __riscv_vsll_vx_u32m8(__riscv_vzext_vf4_u32m8(hi, vl), 8, vl), + vl); + vuint32m8_t idx = __riscv_vand_vx_u32m8( + __riscv_vsrl_vv_u32m8(w, shift, vl), 7, vl); + vuint32m8_t off = __riscv_vsll_vx_u32m8(idx, 2, vl); + return __riscv_vluxei32_v_f32m8(this->centroids, off, vl); + } + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + while (i < this->d) { + size_t vl = __riscv_vsetvl_e32m8(this->d - i); + vfloat32m8_t v = reconstruct_m8_components(code, i, vl); + __riscv_vse32_v_f32m8(x + i, v, vl); + i += vl; + } + } +}; + +template <> +struct QuantizerLloydMax<4, SIMDLevel::RISCV_RVV> + : QuantizerLloydMaxBase<4, SIMDLevel::RISCV_RVV> { + using Base = QuantizerLloydMaxBase<4, SIMDLevel::RISCV_RVV>; + + QuantizerLloydMax(size_t d, const std::vector& trained) + : Base(d, trained) {} + + FAISS_ALWAYS_INLINE vfloat32m8_t + reconstruct_m8_components(const uint8_t* code, size_t i, size_t vl) const { + const size_t byte_base = i >> 1; + const size_t byte_vl = ((i + vl - 1) >> 1) - byte_base + 1; + vuint8m2_t packed = __riscv_vle8_v_u8m2(code + byte_base, byte_vl); + vuint32m8_t packed32 = __riscv_vzext_vf4_u32m8(packed, byte_vl); + vuint32m8_t comp = + __riscv_vadd_vx_u32m8(__riscv_vid_v_u32m8(vl), i, vl); + vuint32m8_t rel = __riscv_vsub_vx_u32m8( + __riscv_vsrl_vx_u32m8(comp, 1, vl), byte_base, vl); + vuint32m8_t bytes = __riscv_vrgather_vv_u32m8(packed32, rel, vl); + vuint32m8_t lo = __riscv_vand_vx_u32m8(bytes, 0xf, vl); + vuint32m8_t hi = __riscv_vsrl_vx_u32m8(bytes, 4, vl); + vbool4_t odd = __riscv_vmsne_vx_u32m8_b4( + __riscv_vand_vx_u32m8(comp, 1, vl), 0, vl); + vuint32m8_t idx = __riscv_vmerge_vvm_u32m8(lo, hi, odd, vl); + vuint32m8_t off = __riscv_vsll_vx_u32m8(idx, 2, vl); + return __riscv_vluxei32_v_f32m8(this->centroids, off, vl); + } + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + while (i < this->d) { + size_t vl = __riscv_vsetvl_e32m8(this->d - i); + vfloat32m8_t v = reconstruct_m8_components(code, i, vl); + __riscv_vse32_v_f32m8(x + i, v, vl); + i += vl; + } + } +}; + +template <> +struct QuantizerLloydMax<8, SIMDLevel::RISCV_RVV> + : QuantizerLloydMaxBase<8, SIMDLevel::RISCV_RVV> { + using Base = QuantizerLloydMaxBase<8, SIMDLevel::RISCV_RVV>; + + QuantizerLloydMax(size_t d, const std::vector& trained) + : Base(d, trained) {} + + FAISS_ALWAYS_INLINE vfloat32m8_t + reconstruct_m8_components(const uint8_t* code, size_t i, size_t vl) const { + vuint8m2_t vb = __riscv_vle8_v_u8m2(code + i, vl); + vuint32m8_t off = + __riscv_vsll_vx_u32m8(__riscv_vzext_vf4_u32m8(vb, vl), 2, vl); + return __riscv_vluxei32_v_f32m8(this->centroids, off, vl); + } + + void decode_vector(const uint8_t* code, float* x) const final { + size_t i = 0; + while (i < this->d) { + size_t vl = __riscv_vsetvl_e32m8(this->d - i); + vfloat32m8_t v = reconstruct_m8_components(code, i, vl); + __riscv_vse32_v_f32m8(x + i, v, vl); + i += vl; + } + } }; template <> struct SimilarityL2 : SimilarityL2 { using SimilarityL2::SimilarityL2; + + static constexpr SIMDLevel simd_level = SIMDLevel::RISCV_RVV; + + FAISS_ALWAYS_INLINE void begin_m8() { + yi = y; + } + + static FAISS_ALWAYS_INLINE vfloat32m8_t zero_m8(size_t vl) { + return __riscv_vfmv_v_f_f32m8(0.0f, vl); + } + + FAISS_ALWAYS_INLINE vfloat32m8_t + add_m8_components(vfloat32m8_t accu, vfloat32m8_t x, size_t vl) { + vfloat32m8_t yiv = __riscv_vle32_v_f32m8(yi, vl); + yi += vl; + vfloat32m8_t tmp = __riscv_vfsub_vv_f32m8(yiv, x, vl); + return __riscv_vfmacc_vv_f32m8_tu(accu, tmp, tmp, vl); + } + + static FAISS_ALWAYS_INLINE vfloat32m8_t add_m8_components_2( + vfloat32m8_t accu, + vfloat32m8_t x, + vfloat32m8_t y_2, + size_t vl) { + vfloat32m8_t tmp = __riscv_vfsub_vv_f32m8(y_2, x, vl); + return __riscv_vfmacc_vv_f32m8_tu(accu, tmp, tmp, vl); + } + + static FAISS_ALWAYS_INLINE float result_m8(vfloat32m8_t accu, size_t vl) { + vfloat32m1_t zero = __riscv_vfmv_v_f_f32m1(0.0f, 1); + vfloat32m1_t sum = __riscv_vfredusum_vs_f32m8_f32m1(accu, zero, vl); + return __riscv_vfmv_f_s_f32m1_f32(sum); + } }; template <> struct SimilarityIP : SimilarityIP { using SimilarityIP::SimilarityIP; + + static constexpr SIMDLevel simd_level = SIMDLevel::RISCV_RVV; + + FAISS_ALWAYS_INLINE void begin_m8() { + yi = y; + } + + static FAISS_ALWAYS_INLINE vfloat32m8_t zero_m8(size_t vl) { + return __riscv_vfmv_v_f_f32m8(0.0f, vl); + } + + FAISS_ALWAYS_INLINE vfloat32m8_t + add_m8_components(vfloat32m8_t accu, vfloat32m8_t x, size_t vl) { + vfloat32m8_t yiv = __riscv_vle32_v_f32m8(yi, vl); + yi += vl; + return __riscv_vfmacc_vv_f32m8_tu(accu, yiv, x, vl); + } + + static FAISS_ALWAYS_INLINE vfloat32m8_t add_m8_components_2( + vfloat32m8_t accu, + vfloat32m8_t x1, + vfloat32m8_t x2, + size_t vl) { + return __riscv_vfmacc_vv_f32m8_tu(accu, x1, x2, vl); + } + + static FAISS_ALWAYS_INLINE float result_m8(vfloat32m8_t accu, size_t vl) { + vfloat32m1_t zero = __riscv_vfmv_v_f_f32m1(0.0f, 1); + vfloat32m1_t sum = __riscv_vfredusum_vs_f32m8_f32m1(accu, zero, vl); + return __riscv_vfmv_f_s_f32m1_f32(sum); + } }; /************************************************************************* @@ -127,7 +470,14 @@ struct SimilarityIP : SimilarityIP { * falls through to scalar code. Callers and the dispatcher don't know or care. ************************************************************************/ +template +inline constexpr bool has_reconstruct_m8_v = + requires(const Quantizer& q, const uint8_t* code, size_t i, size_t vl) { + q.reconstruct_m8_components(code, i, vl); + }; + template + requires(!has_reconstruct_m8_v) struct DCTemplate : DCTemplate { using Base = DCTemplate; @@ -141,6 +491,84 @@ struct DistanceComputerByte using Base::Base; }; +template + requires(has_reconstruct_m8_v) +struct DCTemplate + : SQDistanceComputer { + using Sim = Similarity; + + Quantizer quant; + + DCTemplate(size_t d, const std::vector& trained) + : quant(d, trained) {} + + float compute_distance(const float* x, const uint8_t* code) const { + if (quant.d == 0) { + return 0.0f; + } + Similarity sim(x); + sim.begin_m8(); + const size_t first_vl = __riscv_vsetvl_e32m8(quant.d); + vfloat32m8_t accu = Sim::zero_m8(first_vl); + size_t i = 0; + while (i < quant.d) { + size_t vl = __riscv_vsetvl_e32m8(quant.d - i); + vfloat32m8_t xi = quant.reconstruct_m8_components(code, i, vl); + accu = sim.add_m8_components(accu, xi, vl); + i += vl; + } + return Sim::result_m8(accu, first_vl); + } + + float compute_code_distance(const uint8_t* code1, const uint8_t* code2) + const { + if (quant.d == 0) { + return 0.0f; + } + Similarity sim(nullptr); + sim.begin_m8(); + const size_t first_vl = __riscv_vsetvl_e32m8(quant.d); + vfloat32m8_t accu = Sim::zero_m8(first_vl); + size_t i = 0; + while (i < quant.d) { + size_t vl = __riscv_vsetvl_e32m8(quant.d - i); + vfloat32m8_t x1 = quant.reconstruct_m8_components(code1, i, vl); + vfloat32m8_t x2 = quant.reconstruct_m8_components(code2, i, vl); + accu = Sim::add_m8_components_2(accu, x1, x2, vl); + i += vl; + } + return Sim::result_m8(accu, first_vl); + } + + void set_query(const float* x) final { + q = x; + } + + float symmetric_dis(idx_t i, idx_t j) override { + return compute_code_distance( + codes + i * code_size, codes + j * code_size); + } + + float query_to_code(const uint8_t* code) const final { + return compute_distance(q, code); + } + + void query_to_codes_batch_4( + const uint8_t* code_0, + const uint8_t* code_1, + const uint8_t* code_2, + const uint8_t* code_3, + float& dis0, + float& dis1, + float& dis2, + float& dis3) const final { + dis0 = compute_distance(q, code_0); + dis1 = compute_distance(q, code_1); + dis2 = compute_distance(q, code_2); + dis3 = compute_distance(q, code_3); + } +}; + // * Fast path — QT_4bit_uniform + L2 (float domain) // * // * 4-bit UNIFORM scaling: every component reconstructs as @@ -1615,13 +2043,7 @@ struct DCTemplate< DCTemplate(size_t d_in, const std::vector& trained) : d(d_in), a_v(d_in, 0.0f), rmin_v(d_in, 0.0f), e_v(d_in, 0.0f) { - const float* vmin = trained.data(); - const float* vdiff = trained.data() + d_in; - for (size_t i = 0; i < d_in; i++) { - float a = vdiff[i] / 255.0f; - a_v[i] = a; - rmin_v[i] = vmin[i] + 0.5f * a; - } + sq8::make_coefficients(trained.data(), d_in, a_v.data(), rmin_v.data()); } void set_query(const float* x) final { @@ -1634,61 +2056,7 @@ struct DCTemplate< /// Full-precision vector L2 over the 1-byte-per-dim code. float compute_l2(const uint8_t* code) const { - const float* pa = a_v.data(); - const float* pe = e_v.data(); - - // Hoist vsetvl: VLMAX for e8m1 (== f32 lanes per m4 group). - // d==0: guard so vsetvl(0) doesn't return 0 and the prologue - // `if (i + vl <= d)` + chunk loop don't stall. - const size_t vl = __riscv_vsetvl_e8m1(d > 0 ? d : 1); - vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); - - size_t i = 0; - if (i + vl <= d) { - // Software pipeline depth 1: preload the next chunk's code - // bytes at the top of this iteration. - vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vl); // prologue - i += vl; - - for (; i + vl <= d; i += vl) { - vuint8m1_t c8_next = __riscv_vle8_v_u8m1(code + i, vl); - vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( - __riscv_vzext_vf4_u32m4(c8, vl), vl); - vfloat32m4_t t = __riscv_vle32_v_f32m4(pe + i - vl, vl); - t = __riscv_vfnmsac_vv_f32m4( - t, __riscv_vle32_v_f32m4(pa + i - vl, vl), cf, vl); - acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); - c8 = c8_next; // rotate - } - - // Epilogue: process the last full chunk (already loaded). - { - vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( - __riscv_vzext_vf4_u32m4(c8, vl), vl); - vfloat32m4_t t = __riscv_vle32_v_f32m4(pe + i - vl, vl); - t = __riscv_vfnmsac_vv_f32m4( - t, __riscv_vle32_v_f32m4(pa + i - vl, vl), cf, vl); - acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); - } - } - - // Tail: fewer than vl dims left; accumulates into the first - // lanes of acc (safe: reduction below covers all vl lanes). - if (i < d) { - size_t vt = __riscv_vsetvl_e8m1(d - i); - vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vt); - vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( - __riscv_vzext_vf4_u32m4(c8, vt), vt); - vfloat32m4_t t = __riscv_vle32_v_f32m4(pe + i, vt); - t = __riscv_vfnmsac_vv_f32m4( - t, __riscv_vle32_v_f32m4(pa + i, vt), cf, vt); - acc = __riscv_vfmacc_vv_f32m4_tu(acc, t, t, vt); - } - - // Horizontal reduce over all vl lanes - vfloat32m1_t red = __riscv_vfredusum_vs_f32m4_f32m1( - acc, __riscv_vfmv_v_f_f32m1(0.0f, 1), vl); - return __riscv_vfmv_f_s_f32m1_f32(red); + return sq8_rvv::l2_distance(code, a_v.data(), e_v.data(), d); } float query_to_code(const uint8_t* code) const final { @@ -1760,13 +2128,7 @@ struct DCTemplate< // vle32 loads stay in bounds (padding lanes never used). b_v(d_in + 2 * __riscv_vsetvlmax_e8m1(), 0.0f), k_q(0.0f) { - const float* vmin = trained.data(); - const float* vdiff = trained.data() + d_in; - for (size_t i = 0; i < d_in; i++) { - float a = vdiff[i] / 255.0f; - a_v[i] = a; - rmin_v[i] = vmin[i] + 0.5f * a; - } + sq8::make_coefficients(trained.data(), d_in, a_v.data(), rmin_v.data()); } void set_query(const float* x) final { @@ -3009,36 +3371,8 @@ struct DCTemplate< } }; -/********************************************************** - * TurboQuant masked_sum RVV specialization (scalar fallback) - **********************************************************/ - -template -float turboq_masked_sum(const float* arr, const uint8_t* bits, size_t d); - -template <> -float turboq_masked_sum( - const float* arr, - const uint8_t* bits, - size_t d) { - float result = 0; - for (size_t byte_idx = 0; byte_idx < (d + 7) / 8; byte_idx++) { - uint8_t b = bits[byte_idx]; - size_t base = byte_idx * 8; - size_t end = std::min(base + 8, d); - for (size_t j = base; j < end; j++) { - if (b & (1 << (j - base))) { - result += arr[j]; - } - } - } - return result; -} - } // namespace scalar_quantizer } // namespace faiss #define THE_LEVEL_TO_DISPATCH SIMDLevel::RISCV_RVV #include - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_coefficients.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_coefficients.h new file mode 100644 index 000000000..500e4f199 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_coefficients.h @@ -0,0 +1,48 @@ +/* + * 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. + */ + +#pragma once + +/* QT_8bit reconstruction coefficients. + * + * Scalar and portable. A caller on any architecture may include this. + * + * For a QT_8bit non-uniform quantizer with trained values vmin and vdiff: + * + * a[i] = vdiff[i] / 255 + * rmin[i] = vmin[i] + 0.5 * a[i] + * e[i] = query[i] - rmin[i] + * + * so reconstruct(code)[i] = rmin[i] + a[i] * code[i]. + */ + +#include + +namespace faiss { +namespace sq8 { + +/// Derive the per-dimension scale and offset from a trained quantizer. +/// @param trained 2*d floats: vmin[0..d) then vdiff[0..d) +/// @param levels the largest code value: 255 for QT_8bit, 15 for QT_4bit. +/// Both quantizers reconstruct as rmin[i] + a[i] * code[i], +/// so only the divisor differs. +inline void make_coefficients( + const float* trained, + size_t d, + float* a, + float* rmin, + float levels = 255.0f) { + const float* vmin = trained; + const float* vdiff = trained + d; + for (size_t i = 0; i < d; i++) { + a[i] = vdiff[i] / levels; + rmin[i] = vmin[i] + 0.5f * a[i]; + } +} + +} // namespace sq8 +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_rvv_kernel.h b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_rvv_kernel.h new file mode 100644 index 000000000..51143b806 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/sq8_rvv_kernel.h @@ -0,0 +1,546 @@ +/* + * 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. + */ + +#pragma once + +/* QT_8bit distance kernel for RISC-V Vector. + * + * Free-standing (no exceptions, heap or threads), so a freestanding RISC-V + * target can compile it. sq-rvv.cpp calls `l2_distance`; the block, strided + * and 4-bit forms serve callers that store codes transposed, such as the + * MTIA kernels in faiss/fb/mtia. No Buck target here builds the RISC-V CPU + * path. See sq8_coefficients.h for the meaning of a and e. + */ + +#include + +#include +#include + +namespace faiss { +namespace sq8_rvv { + +/// Candidates per transposed block. One block fills an f32 LMUL 4 group at +/// VLEN=512, so every lane holds one candidate. On a smaller VLEN the block +/// functions loop over the block in pieces of one vector length. +constexpr size_t kBlockVectors = 64; + +/// Squared L2 for a whole block, from codes stored transposed: the byte for +/// dimension i of lane c sits at `block[i * kBlockVectors + c]`. Each lane +/// accumulates one candidate, so no reduction is needed. +inline void l2_distance_block( + const uint8_t* block, + const float* a, + const float* e, + size_t d, + float* out) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d; i++) { + vuint8m1_t c8 = + __riscv_vle8_v_u8m1(block + c + i * kBlockVectors, vl); + vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(c8, vl), vl); + // a[i] and e[i] are the same for every candidate in the block. + vfloat32m4_t t = __riscv_vfmv_v_f_f32m4(e[i], vl); + t = __riscv_vfnmsac_vf_f32m4(t, a[i], cf, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + } + __riscv_vse32_v_f32m4(out + c, acc, vl); + c += vl; + } +} + +/// Squared L2 for two transposed blocks at once. +/// +/// Issuing the loads of both blocks first keeps two loads in flight. Four +/// blocks would need 16 of the 32 vector registers for accumulators and +/// spill. +inline void l2_distance_block_x2( + const uint8_t* block0, + const uint8_t* block1, + const float* a, + const float* e, + size_t d, + float* out0, + float* out1) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc0 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + vfloat32m4_t acc1 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d; i++) { + vuint8m1_t v0 = + __riscv_vle8_v_u8m1(block0 + c + i * kBlockVectors, vl); + vuint8m1_t v1 = + __riscv_vle8_v_u8m1(block1 + c + i * kBlockVectors, vl); + const float ei = e[i]; + const float ai = a[i]; + vfloat32m4_t c0 = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(v0, vl), vl); + vfloat32m4_t t0 = __riscv_vfmv_v_f_f32m4(ei, vl); + t0 = __riscv_vfnmsac_vf_f32m4(t0, ai, c0, vl); + acc0 = __riscv_vfmacc_vv_f32m4(acc0, t0, t0, vl); + vfloat32m4_t c1 = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(v1, vl), vl); + vfloat32m4_t t1 = __riscv_vfmv_v_f_f32m4(ei, vl); + t1 = __riscv_vfnmsac_vf_f32m4(t1, ai, c1, vl); + acc1 = __riscv_vfmacc_vv_f32m4(acc1, t1, t1, vl); + } + __riscv_vse32_v_f32m4(out0 + c, acc0, vl); + __riscv_vse32_v_f32m4(out1 + c, acc1, vl); + c += vl; + } +} + +/// The code-dependent inner product term for two transposed blocks at once. +inline void ip_partial_block_x2( + const uint8_t* block0, + const uint8_t* block1, + const float* eq, + size_t d, + float* out0, + float* out1) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc0 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + vfloat32m4_t acc1 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d; i++) { + vuint8m1_t v0 = + __riscv_vle8_v_u8m1(block0 + c + i * kBlockVectors, vl); + vuint8m1_t v1 = + __riscv_vle8_v_u8m1(block1 + c + i * kBlockVectors, vl); + const float q = eq[i]; + acc0 = __riscv_vfmacc_vf_f32m4( + acc0, + q, + __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(v0, vl), vl), + vl); + acc1 = __riscv_vfmacc_vf_f32m4( + acc1, + q, + __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(v1, vl), vl), + vl); + } + __riscv_vse32_v_f32m4(out0 + c, acc0, vl); + __riscv_vse32_v_f32m4(out1 + c, acc1, vl); + c += vl; + } +} + +/// The low nibbles of a row of packed QT_4bit codes, as floats. +inline vfloat32m4_t low_nibbles(vuint8m1_t packed, size_t vl) { + return __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(__riscv_vand_vx_u8m1(packed, 0x0F, vl), vl), + vl); +} + +/// Squared L2 for a transposed block of QT_4bit codes. Faiss packs +/// dimension i into `code[i / 2]`, even dimensions in the low nibble and odd +/// in the high one, so d dimensions occupy (d + 1) / 2 bytes. For an odd d +/// the last byte holds one dimension, in its low nibble. +inline void l2_distance_4bit_block( + const uint8_t* block, + const float* a, + const float* e, + size_t d, + float* out) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d / 2; i++) { + vuint8m1_t packed = + __riscv_vle8_v_u8m1(block + c + i * kBlockVectors, vl); + vfloat32m4_t lo = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vand_vx_u8m1(packed, 0x0F, vl), vl), + vl); + vfloat32m4_t hi = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vsrl_vx_u8m1(packed, 4, vl), vl), + vl); + vfloat32m4_t t = __riscv_vfmv_v_f_f32m4(e[2 * i], vl); + t = __riscv_vfnmsac_vf_f32m4(t, a[2 * i], lo, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + t = __riscv_vfmv_v_f_f32m4(e[2 * i + 1], vl); + t = __riscv_vfnmsac_vf_f32m4(t, a[2 * i + 1], hi, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + } + if (d % 2 != 0) { + vfloat32m4_t lo = low_nibbles( + __riscv_vle8_v_u8m1( + block + c + (d / 2) * kBlockVectors, vl), + vl); + vfloat32m4_t t = __riscv_vfmv_v_f_f32m4(e[d - 1], vl); + t = __riscv_vfnmsac_vf_f32m4(t, a[d - 1], lo, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + } + __riscv_vse32_v_f32m4(out + c, acc, vl); + c += vl; + } +} + +/// The code-dependent inner product term for a transposed QT_4bit block. +inline void ip_partial_4bit_block( + const uint8_t* block, + const float* eq, + size_t d, + float* out) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d / 2; i++) { + vuint8m1_t packed = + __riscv_vle8_v_u8m1(block + c + i * kBlockVectors, vl); + vfloat32m4_t lo = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vand_vx_u8m1(packed, 0x0F, vl), vl), + vl); + vfloat32m4_t hi = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vsrl_vx_u8m1(packed, 4, vl), vl), + vl); + acc = __riscv_vfmacc_vf_f32m4(acc, eq[2 * i], lo, vl); + acc = __riscv_vfmacc_vf_f32m4(acc, eq[2 * i + 1], hi, vl); + } + if (d % 2 != 0) { + vfloat32m4_t lo = low_nibbles( + __riscv_vle8_v_u8m1( + block + c + (d / 2) * kBlockVectors, vl), + vl); + acc = __riscv_vfmacc_vf_f32m4(acc, eq[d - 1], lo, vl); + } + __riscv_vse32_v_f32m4(out + c, acc, vl); + c += vl; + } +} + +/// Squared L2 for one QT_4bit candidate in the transposed layout, for the +/// runs an `IDSelector` produces, which start anywhere. +inline float l2_distance_4bit_strided( + const uint8_t* p, + const float* a, + const float* e, + size_t d) { + float acc = 0.0f; + for (size_t i = 0; i < d / 2; i++) { + const uint8_t packed = p[i * kBlockVectors]; + const float t0 = + e[2 * i] - a[2 * i] * static_cast(packed & 0x0F); + const float t1 = + e[2 * i + 1] - a[2 * i + 1] * static_cast(packed >> 4); + acc += t0 * t0 + t1 * t1; + } + if (d % 2 != 0) { + const uint8_t packed = p[(d / 2) * kBlockVectors]; + const float t = e[d - 1] - a[d - 1] * static_cast(packed & 0x0F); + acc += t * t; + } + return acc; +} + +/// The code-dependent inner product term for one strided QT_4bit candidate. +inline float ip_partial_4bit_strided( + const uint8_t* p, + const float* eq, + size_t d) { + float acc = 0.0f; + for (size_t i = 0; i < d / 2; i++) { + const uint8_t packed = p[i * kBlockVectors]; + acc += eq[2 * i] * static_cast(packed & 0x0F); + acc += eq[2 * i + 1] * static_cast(packed >> 4); + } + if (d % 2 != 0) { + const uint8_t packed = p[(d / 2) * kBlockVectors]; + acc += eq[d - 1] * static_cast(packed & 0x0F); + } + return acc; +} + +/// Squared L2 for two transposed QT_4bit blocks at once: half the bytes of +/// QT_8bit and two loads in flight. +inline void l2_distance_4bit_block_x2( + const uint8_t* block0, + const uint8_t* block1, + const float* a, + const float* e, + size_t d, + float* out0, + float* out1) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc0 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + vfloat32m4_t acc1 = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d / 2; i++) { + vuint8m1_t p0 = + __riscv_vle8_v_u8m1(block0 + c + i * kBlockVectors, vl); + vuint8m1_t p1 = + __riscv_vle8_v_u8m1(block1 + c + i * kBlockVectors, vl); + const float e0 = e[2 * i]; + const float e1 = e[2 * i + 1]; + const float a0 = a[2 * i]; + const float a1 = a[2 * i + 1]; + auto step = [&](vuint8m1_t p, vfloat32m4_t acc) { + vfloat32m4_t lo = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vand_vx_u8m1(p, 0x0F, vl), vl), + vl); + vfloat32m4_t hi = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4( + __riscv_vsrl_vx_u8m1(p, 4, vl), vl), + vl); + vfloat32m4_t t = __riscv_vfmv_v_f_f32m4(e0, vl); + t = __riscv_vfnmsac_vf_f32m4(t, a0, lo, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + t = __riscv_vfmv_v_f_f32m4(e1, vl); + t = __riscv_vfnmsac_vf_f32m4(t, a1, hi, vl); + return __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + }; + acc0 = step(p0, acc0); + acc1 = step(p1, acc1); + } + if (d % 2 != 0) { + const size_t last = (d / 2) * kBlockVectors; + auto tail = [&](vuint8m1_t p, vfloat32m4_t acc) { + vfloat32m4_t t = __riscv_vfmv_v_f_f32m4(e[d - 1], vl); + t = __riscv_vfnmsac_vf_f32m4( + t, a[d - 1], low_nibbles(p, vl), vl); + return __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + }; + acc0 = tail(__riscv_vle8_v_u8m1(block0 + c + last, vl), acc0); + acc1 = tail(__riscv_vle8_v_u8m1(block1 + c + last, vl), acc1); + } + __riscv_vse32_v_f32m4(out0 + c, acc0, vl); + __riscv_vse32_v_f32m4(out1 + c, acc1, vl); + c += vl; + } +} + +/// Squared L2 for one candidate whose code is stored transposed: its d bytes +/// sit `kBlockVectors` apart. For runs that do not start on a block +/// boundary, such as the runs an `IDSelector` produces. +inline float l2_distance_strided( + const uint8_t* p, + const float* a, + const float* e, + size_t d) { + const size_t vl = __riscv_vsetvl_e8m1(d > 0 ? d : 1); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + size_t i = 0; + while (i < d) { + const size_t v = __riscv_vsetvl_e8m1(d - i); + vuint8m1_t c8 = __riscv_vlse8_v_u8m1( + p + i * kBlockVectors, + static_cast(kBlockVectors), + v); + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, v), v); + vfloat32m4_t t = __riscv_vle32_v_f32m4(e + i, v); + t = __riscv_vfnmsac_vv_f32m4(t, __riscv_vle32_v_f32m4(a + i, v), cf, v); + acc = __riscv_vfmacc_vv_f32m4_tu(acc, t, t, v); + i += v; + } + vfloat32m1_t red = __riscv_vfredusum_vs_f32m4_f32m1( + acc, __riscv_vfmv_v_f_f32m1(0.0f, 1), vl); + return __riscv_vfmv_f_s_f32m1_f32(red); +} + +/// The code-dependent inner product term for one transposed candidate. +inline float ip_partial_strided(const uint8_t* p, const float* eq, size_t d) { + const size_t vl = __riscv_vsetvl_e8m1(d > 0 ? d : 1); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + size_t i = 0; + while (i < d) { + const size_t v = __riscv_vsetvl_e8m1(d - i); + vuint8m1_t c8 = __riscv_vlse8_v_u8m1( + p + i * kBlockVectors, + static_cast(kBlockVectors), + v); + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, v), v); + acc = __riscv_vfmacc_vv_f32m4_tu( + acc, __riscv_vle32_v_f32m4(eq + i, v), cf, v); + i += v; + } + vfloat32m1_t red = __riscv_vfredusum_vs_f32m4_f32m1( + acc, __riscv_vfmv_v_f_f32m1(0.0f, 1), vl); + return __riscv_vfmv_f_s_f32m1_f32(red); +} + +/// Squared L2 on the 8-bit grid for a transposed block, with integer +/// weights. The host scales the result back. +inline void l2_distance_int_block( + const uint8_t* block, + const uint8_t* qcode, + const int32_t* w, + size_t d, + float* out) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vint32m4_t acc = __riscv_vmv_v_x_i32m4(0, vl); + for (size_t i = 0; i < d; i++) { + vuint8m1_t c8 = + __riscv_vle8_v_u8m1(block + c + i * kBlockVectors, vl); + vint32m4_t c = __riscv_vreinterpret_v_u32m4_i32m4( + __riscv_vzext_vf4_u32m4(c8, vl)); + vint32m4_t diff = __riscv_vsub_vx_i32m4( + c, static_cast(qcode[i]), vl); + vint32m4_t sq = __riscv_vmul_vv_i32m4(diff, diff, vl); + acc = __riscv_vmacc_vx_i32m4(acc, w[i], sq, vl); + } + __riscv_vse32_v_f32m4(out + c, __riscv_vfcvt_f_x_v_f32m4(acc, vl), vl); + c += vl; + } +} + +/// The code-dependent term of the inner product, for a transposed block. +inline void ip_partial_block( + const uint8_t* block, + const float* eq, + size_t d, + float* out) { + for (size_t c = 0; c < kBlockVectors;) { + const size_t vl = __riscv_vsetvl_e32m4(kBlockVectors - c); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (size_t i = 0; i < d; i++) { + vuint8m1_t c8 = + __riscv_vle8_v_u8m1(block + c + i * kBlockVectors, vl); + vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(c8, vl), vl); + acc = __riscv_vfmacc_vf_f32m4(acc, eq[i], cf, vl); + } + __riscv_vse32_v_f32m4(out + c, acc, vl); + c += vl; + } +} + +/// Squared L2 distance between a query and one 8-bit code. +inline float l2_distance( + const uint8_t* code, + const float* a, + const float* e, + size_t d) { + // VLMAX for e8m1 equals the f32 lane count of an m4 group. Guard d == 0, + // because vsetvl then returns 0 and the chunk loop stalls. + const size_t vl = __riscv_vsetvl_e8m1(d > 0 ? d : 1); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + + size_t i = 0; + if (i + vl <= d) { + // Software pipeline: load the next chunk's code bytes at the top. + vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vl); + i += vl; + + for (; i + vl <= d; i += vl) { + vuint8m1_t c8_next = __riscv_vle8_v_u8m1(code + i, vl); + vfloat32m4_t cf = __riscv_vfcvt_f_xu_v_f32m4( + __riscv_vzext_vf4_u32m4(c8, vl), vl); + vfloat32m4_t t = __riscv_vle32_v_f32m4(e + i - vl, vl); + t = __riscv_vfnmsac_vv_f32m4( + t, __riscv_vle32_v_f32m4(a + i - vl, vl), cf, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + c8 = c8_next; + } + + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, vl), vl); + vfloat32m4_t t = __riscv_vle32_v_f32m4(e + i - vl, vl); + t = __riscv_vfnmsac_vv_f32m4( + t, __riscv_vle32_v_f32m4(a + i - vl, vl), cf, vl); + acc = __riscv_vfmacc_vv_f32m4(acc, t, t, vl); + } + + // Tail: fewer than vl dimensions remain. The reduction covers every lane. + if (i < d) { + const size_t vt = __riscv_vsetvl_e8m1(d - i); + vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vt); + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, vt), vt); + vfloat32m4_t t = __riscv_vle32_v_f32m4(e + i, vt); + t = __riscv_vfnmsac_vv_f32m4( + t, __riscv_vle32_v_f32m4(a + i, vt), cf, vt); + acc = __riscv_vfmacc_vv_f32m4_tu(acc, t, t, vt); + } + + vfloat32m1_t red = __riscv_vfredusum_vs_f32m4_f32m1( + acc, __riscv_vfmv_v_f_f32m1(0.0f, 1), vl); + return __riscv_vfmv_f_s_f32m1_f32(red); +} + +/// Inner product between a query and one 8-bit code, without the constant. +/// +/// Expanding the reconstruction, +/// +/// sum q[i] * v[i] = sum q[i]*rmin[i] + sum (q[i]*a[i]) * code[i] +/// +/// the first term does not depend on the code, so the caller adds it. This +/// computes the second, with u[i] = q[i] * a[i]. +inline float ip_partial(const uint8_t* code, const float* u, size_t d) { + const size_t vl = __riscv_vsetvl_e8m1(d > 0 ? d : 1); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + + size_t i = 0; + for (; i + vl <= d; i += vl) { + vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vl); + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, vl), vl); + acc = __riscv_vfmacc_vv_f32m4( + acc, cf, __riscv_vle32_v_f32m4(u + i, vl), vl); + } + if (i < d) { + const size_t vt = __riscv_vsetvl_e8m1(d - i); + vuint8m1_t c8 = __riscv_vle8_v_u8m1(code + i, vt); + vfloat32m4_t cf = + __riscv_vfcvt_f_xu_v_f32m4(__riscv_vzext_vf4_u32m4(c8, vt), vt); + acc = __riscv_vfmacc_vv_f32m4_tu( + acc, cf, __riscv_vle32_v_f32m4(u + i, vt), vt); + } + + vfloat32m1_t red = __riscv_vfredusum_vs_f32m4_f32m1( + acc, __riscv_vfmv_v_f_f32m1(0.0f, 1), vl); + return __riscv_vfmv_f_s_f32m1_f32(red); +} + +/// Squared L2 distance with the query quantized onto the same 8-bit grid. +/// +/// sum (q[i] - v[i])^2 = sum a[i]^2 * (qcode[i] - code[i])^2 +/// +/// The weights hold a[i]^2 as integers, so the loop is integer only. The +/// caller scales the result back and must keep max(w) * 65025 * d inside +/// int32. +inline float l2_distance_int( + const uint8_t* code, + const uint8_t* qcode, + const int32_t* w, + size_t d) { + // Accumulate at LMUL 4, not 8. A group of eight uses eight of the 32 + // vector registers and leaves only four groups, which is slower. + vint32m4_t sum = __riscv_vmv_v_x_i32m4(0, __riscv_vsetvlmax_e32m4()); + size_t i = 0; + while (i < d) { + const size_t vl = __riscv_vsetvl_e16m2(d - i); + vint16m2_t c = __riscv_vreinterpret_v_u16m2_i16m2( + __riscv_vzext_vf2_u16m2(__riscv_vle8_v_u8m1(code + i, vl), vl)); + vint16m2_t q = + __riscv_vreinterpret_v_u16m2_i16m2(__riscv_vzext_vf2_u16m2( + __riscv_vle8_v_u8m1(qcode + i, vl), vl)); + vint16m2_t diff = __riscv_vsub_vv_i16m2(q, c, vl); + // A difference of two bytes fits in int16 and its square in int32. + vint32m4_t sq = __riscv_vwmul_vv_i32m4(diff, diff, vl); + sum = __riscv_vmacc_vv_i32m4_tu( + sum, sq, __riscv_vle32_v_i32m4(w + i, vl), vl); + i += vl; + } + vint32m1_t r = __riscv_vredsum_vs_i32m4_i32m1( + sum, __riscv_vmv_v_x_i32m1(0, 1), __riscv_vsetvlmax_e32m4()); + return static_cast(__riscv_vmv_x_s_i32m1_i32(r)); +} + +} // namespace sq8_rvv +} // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/scalar_quantizer/training.cpp b/thirdparty/faiss/faiss/impl/scalar_quantizer/training.cpp index e17df31d5..1c58b0fc8 100644 --- a/thirdparty/faiss/faiss/impl/scalar_quantizer/training.cpp +++ b/thirdparty/faiss/faiss/impl/scalar_quantizer/training.cpp @@ -366,15 +366,15 @@ void train_NonUniform( } else { // transpose std::vector xt(n * d); - for (idx_t i = 1; i < n; i++) { + for (idx_t i = 0; i < n; i++) { const float* xi = x + i * d; for (int j = 0; j < d; j++) { xt[j * n + i] = xi[j]; } } - std::vector trained_d(2); #pragma omp parallel for for (int j = 0; j < d; j++) { + std::vector trained_d(2); train_Uniform(rs, rs_arg, n, k, xt.data() + j * n, trained_d); vmin[j] = trained_d[0]; vmax[j] = trained_d[1]; diff --git a/thirdparty/faiss/faiss/impl/simd_dispatch.h b/thirdparty/faiss/faiss/impl/simd_dispatch.h index 8a275327d..8c7030ba0 100644 --- a/thirdparty/faiss/faiss/impl/simd_dispatch.h +++ b/thirdparty/faiss/faiss/impl/simd_dispatch.h @@ -36,6 +36,13 @@ constexpr int AVAILABLE_SIMD_LEVELS_AVX2_NEON = AVAILABLE_SIMD_LEVELS_NONE | constexpr int AVAILABLE_SIMD_LEVELS_BASE = AVAILABLE_SIMD_LEVELS_AVX2_NEON | (1 << int(SIMDLevel::AVX512)) | (1 << int(SIMDLevel::RISCV_RVV)); +// BASE_NO_AVX512: BASE minus AVX512, for functions implemented at NONE, +// AVX2, ARM_NEON and RISCV_RVV but with no AVX512 specialization. AVX512 +// machines fall through to AVX2, while RISC-V dispatches directly to the +// native vector-length-agnostic RVV kernels. +constexpr int AVAILABLE_SIMD_LEVELS_BASE_NO_AVX512 = + AVAILABLE_SIMD_LEVELS_BASE & ~(1 << int(SIMDLevel::AVX512)); + // BASE_WITH_VPOPCNT: BASE + AVX512_VPOPCNT, for kernels that need only // VPOPCNTDQ on top of baseline AVX-512 (Ice Lake, Zen 4, Zen 5). constexpr int AVAILABLE_SIMD_LEVELS_BASE_WITH_VPOPCNT = diff --git a/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx2.h b/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx2.h index 734c4095a..04b1ed5fd 100644 --- a/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx2.h +++ b/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx2.h @@ -901,6 +901,20 @@ inline float horizontal_add(const simd8float32_tpl& a) { return _mm_cvtss_f32(v3); } +/// (s[0] + s[2]) + (s[1] + s[3]) +FAISS_ALWAYS_INLINE float reduce_4(__m128 s) { + const __m128 h = _mm_add_ps(s, _mm_movehl_ps(s, s)); + return _mm_cvtss_f32(_mm_add_ss(h, _mm_movehdup_ps(h))); +} + +/// reduce_4 of four vectors at once, with the same order for each, so a +/// batched distance is bit-identical to the single one. +FAISS_ALWAYS_INLINE __m128 reduce_4x4(__m128 a, __m128 b, __m128 c, __m128 d) { + const __m128 ab = _mm_add_ps(_mm_unpacklo_ps(a, b), _mm_unpackhi_ps(a, b)); + const __m128 cd = _mm_add_ps(_mm_unpacklo_ps(c, d), _mm_unpackhi_ps(c, d)); + return _mm_add_ps(_mm_movelh_ps(ab, cd), _mm_movehl_ps(cd, ab)); +} + } // namespace } // namespace faiss diff --git a/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx512.h b/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx512.h index 1968b8ae2..824fe9834 100644 --- a/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx512.h +++ b/thirdparty/faiss/faiss/impl/simdlib/simdlib_avx512.h @@ -37,9 +37,9 @@ struct simd512bit_tpl { simd512bit_tpl() {} - explicit simd512bit_tpl(__m512i i) : i(i) {} + explicit simd512bit_tpl(__m512i val) : i(val) {} - explicit simd512bit_tpl(__m512 f) : f(f) {} + explicit simd512bit_tpl(__m512 val) : f(val) {} explicit simd512bit_tpl(const void* x) : i(_mm512_loadu_si512((__m512i const*)x)) {} @@ -79,8 +79,8 @@ struct simd512bit_tpl { void bin(char bits[513]) const { char bytes[64]; storeu((void*)bytes); - for (int i = 0; i < 512; i++) { - bits[i] = '0' + ((bytes[i / 8] >> (i % 8)) & 1); + for (int idx = 0; idx < 512; idx++) { + bits[idx] = '0' + ((bytes[idx / 8] >> (idx % 8)) & 1); } bits[512] = 0; } @@ -97,8 +97,8 @@ template <> struct simd32uint16_tpl : simd512bit_tpl { simd32uint16_tpl() {} - explicit simd32uint16_tpl(__m512i i) - : simd512bit_tpl(i) {} + explicit simd32uint16_tpl(__m512i val) + : simd512bit_tpl(val) {} explicit simd32uint16_tpl(int x) : simd512bit_tpl(_mm512_set1_epi16(x)) {} @@ -131,9 +131,9 @@ struct simd32uint16_tpl : simd512bit_tpl { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif - for (int i = 0; i < 32; i++) { + for (int idx = 0; idx < 32; idx++) { ptr += snprintf( - ptr, (size_t)(res + sizeof(res) - ptr), fmt, bytes[i]); + ptr, (size_t)(res + sizeof(res) - ptr), fmt, bytes[idx]); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop @@ -213,10 +213,10 @@ struct simd32uint16_tpl : simd512bit_tpl { } // for debugging only - uint16_t operator[](int i) const { + uint16_t operator[](int idx) const { ALIGNED(64) uint16_t tab[32]; store(tab); - return tab[i]; + return tab[idx]; } void accu_min(simd32uint16_tpl incoming) { @@ -241,8 +241,8 @@ template <> struct simd64uint8_tpl : simd512bit_tpl { simd64uint8_tpl() {} - explicit simd64uint8_tpl(__m512i i) - : simd512bit_tpl(i) {} + explicit simd64uint8_tpl(__m512i val) + : simd512bit_tpl(val) {} explicit simd64uint8_tpl(int x) : simd512bit_tpl(_mm512_set1_epi8(x)) {} @@ -275,9 +275,9 @@ struct simd64uint8_tpl : simd512bit_tpl { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif - for (int i = 0; i < 64; i++) { + for (int idx = 0; idx < 64; idx++) { ptr += snprintf( - ptr, (size_t)(res + sizeof(res) - ptr), fmt, bytes[i]); + ptr, (size_t)(res + sizeof(res) - ptr), fmt, bytes[idx]); } #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop @@ -329,10 +329,10 @@ struct simd64uint8_tpl : simd512bit_tpl { } // for debugging only - uint8_t operator[](int i) const { + uint8_t operator[](int idx) const { ALIGNED(64) uint8_t tab[64]; store(tab); - return tab[i]; + return tab[idx]; } }; @@ -342,8 +342,8 @@ struct simd16float32_tpl : simd512bit_tpl { simd16float32_tpl() {} - explicit simd16float32_tpl(__m512 f) - : simd512bit_tpl(f) {} + explicit simd16float32_tpl(__m512 val) + : simd512bit_tpl(val) {} explicit simd16float32_tpl(float x) : simd512bit_tpl(_mm512_set1_ps(x)) {} @@ -389,9 +389,9 @@ struct simd16float32_tpl storeu(tab); char res[1000]; char* ptr = res; - for (int i = 0; i < 16; i++) { + for (int idx = 0; idx < 16; idx++) { ptr += snprintf( - ptr, (size_t)(res + sizeof(res) - ptr), "%g,", tab[i]); + ptr, (size_t)(res + sizeof(res) - ptr), "%g,", tab[idx]); } ptr[-1] = 0; return std::string(res); diff --git a/thirdparty/faiss/faiss/impl/simdlib/simdlib_dispatch.h b/thirdparty/faiss/faiss/impl/simdlib/simdlib_dispatch.h index c4be6732a..606ae2bb2 100644 --- a/thirdparty/faiss/faiss/impl/simdlib/simdlib_dispatch.h +++ b/thirdparty/faiss/faiss/impl/simdlib/simdlib_dispatch.h @@ -16,23 +16,22 @@ */ #include +#include -// Platform specializations — guarded by COMPILE_SIMD_* AND compiler macros. -// In DD mode: COMPILE_SIMD_* are target-wide, compiler macros are per-file. -// Only per-SIMD TUs (compiled with -mavx2 etc.) see the platform -// specializations. In static mode: only the compiled-in level is available. +// Platform specializations — guarded by FAISS_SIMD_TU, so that only per-SIMD +// TUs (compiled with -mavx2 etc.) see them. In static mode: only the +// compiled-in level is available. -#if (defined(COMPILE_SIMD_AVX512) || defined(COMPILE_SIMD_AVX512_SPR)) && \ - defined(__AVX512F__) +#if FAISS_SIMD_TU(AVX512) || FAISS_SIMD_TU(AVX512_SPR) // AVX512 includes AVX2 (simdlib_avx512.h includes simdlib_avx2.h) #include -#elif defined(COMPILE_SIMD_AVX2) && defined(__AVX2__) +#elif FAISS_SIMD_TU(AVX2) #include -#elif defined(COMPILE_SIMD_ARM_NEON) && defined(__aarch64__) +#elif FAISS_SIMD_TU(ARM_NEON) #include diff --git a/thirdparty/faiss/faiss/impl/simdlib/simdlib_neon.h b/thirdparty/faiss/faiss/impl/simdlib/simdlib_neon.h index 7309554cd..510fc2144 100644 --- a/thirdparty/faiss/faiss/impl/simdlib/simdlib_neon.h +++ b/thirdparty/faiss/faiss/impl/simdlib/simdlib_neon.h @@ -1376,7 +1376,7 @@ inline void cmplt_min_max_fast( namespace { // get even float32's of a and b, interleaved -simd8float32_tpl geteven( +inline simd8float32_tpl geteven( const simd8float32_tpl& a, const simd8float32_tpl& b) { return simd8float32_tpl{ @@ -1384,7 +1384,7 @@ simd8float32_tpl geteven( } // get odd float32's of a and b, interleaved -simd8float32_tpl getodd( +inline simd8float32_tpl getodd( const simd8float32_tpl& a, const simd8float32_tpl& b) { return simd8float32_tpl{ @@ -1393,14 +1393,14 @@ simd8float32_tpl getodd( // 3 cycles // if the lanes are a = [a0 a1] and b = [b0 b1], return [a0 b0] -simd8float32_tpl getlow128( +inline simd8float32_tpl getlow128( const simd8float32_tpl& a, const simd8float32_tpl& b) { return simd8float32_tpl{ float32x4x2_t{a.data.val[0], b.data.val[0]}}; } -simd8float32_tpl gethigh128( +inline simd8float32_tpl gethigh128( const simd8float32_tpl& a, const simd8float32_tpl& b) { return simd8float32_tpl{ diff --git a/thirdparty/faiss/faiss/impl/sq_fastscan_utils.h b/thirdparty/faiss/faiss/impl/sq_fastscan_utils.h new file mode 100644 index 000000000..683c21fa4 --- /dev/null +++ b/thirdparty/faiss/faiss/impl/sq_fastscan_utils.h @@ -0,0 +1,232 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include +#include + +/** Helpers shared by IndexSQFastScan and IndexIVFSQFastScan. + * + * Both re-quantise a higher-precision scalar quantizer down to 4-bit nibbles + * for the SIMD scan and keep the original codes to rerank with, so the + * classification of quantizer types and the nibble packing have to agree + * between them. + */ + +namespace faiss { +namespace sq_fastscan { + +inline size_t roundup(size_t a, size_t b) { + return (a + b - 1) / b * b; +} + +inline bool is_native_4bit(ScalarQuantizer::QuantizerType qtype) { + return qtype == ScalarQuantizer::QT_4bit || + qtype == ScalarQuantizer::QT_4bit_uniform; +} + +inline bool needs_rerank(ScalarQuantizer::QuantizerType qtype) { + return qtype == ScalarQuantizer::QT_6bit || + qtype == ScalarQuantizer::QT_8bit || + qtype == ScalarQuantizer::QT_8bit_uniform || + qtype == ScalarQuantizer::QT_8bit_direct || + qtype == ScalarQuantizer::QT_8bit_direct_signed; +} + +inline bool is_fallback(ScalarQuantizer::QuantizerType qtype) { + return !is_native_4bit(qtype) && !needs_rerank(qtype); +} + +inline bool is_uniform_range(ScalarQuantizer::QuantizerType qtype) { + return qtype == ScalarQuantizer::QT_8bit_uniform || + qtype == ScalarQuantizer::QT_8bit_direct || + qtype == ScalarQuantizer::QT_8bit_direct_signed; +} + +inline void get_uniform_range( + const ScalarQuantizer& sq, + float& vmin, + float& vdiff) { + if (sq.qtype == ScalarQuantizer::QT_8bit_direct) { + vmin = 0; + vdiff = 255; + } else if (sq.qtype == ScalarQuantizer::QT_8bit_direct_signed) { + vmin = -128; + vdiff = 255; + } else { + vmin = sq.trained[0]; + vdiff = sq.trained[1]; + } +} + +/// Bits per dimension the quantizer stores. +inline int sq_bits(ScalarQuantizer::QuantizerType qtype) { + if (qtype == ScalarQuantizer::QT_6bit) { + return 6; + } + return is_native_4bit(qtype) ? 4 : 8; +} + +/// Bits left over once the scan has taken its 4. Zero for a native 4-bit +/// code, which needs no rerank and therefore stores nothing extra. +inline int sq_rerank_bits(ScalarQuantizer::QuantizerType qtype) { + return sq_bits(qtype) - 4; +} + +/// Bytes per vector needed to hold the leftover bits of every dimension. +inline size_t sq_rerank_size(int d, ScalarQuantizer::QuantizerType qtype) { + const int bits = sq_rerank_bits(qtype); + return bits > 0 ? (size_t(d) * bits + 7) / 8 : 0; +} + +/// The code for one value at the quantizer's own width. +inline int sq_code_of(float x, float vmin, float vdiff, int bits) { + const int maxv = (1 << bits) - 1; + const float f = (vdiff > 0) ? (x - vmin) / vdiff : 0.0f; + return std::min(maxv, std::max(0, int(f * float(maxv)))); +} + +/// Per-dimension range of the trained quantizer, resolved once for a batch. +struct SQRanges { + SQRanges(const ScalarQuantizer& sq, int d) + : uniform(is_uniform_range(sq.qtype) || + sq.qtype == ScalarQuantizer::QT_4bit_uniform) { + if (uniform) { + get_uniform_range(sq, vmin_s, vdiff_s); + } else { + vmin_arr = sq.trained.data(); + vdiff_arr = sq.trained.data() + d; + } + } + + float vmin(int m) const { + return uniform ? vmin_s : vmin_arr[m]; + } + float vdiff(int m) const { + return uniform ? vdiff_s : vdiff_arr[m]; + } + + const bool uniform; + const float* vmin_arr = nullptr; + const float* vdiff_arr = nullptr; + float vmin_s = 0, vdiff_s = 0; +}; + +/** Split each code into the top 4 bits the SIMD kernel scans and the rest, + * which rerank keeps. `hi` is packed two dimensions per byte as + * pq4_pack_codes expects. `lo` is bit-packed at `bits - 4` per dimension. + * Total width is the quantizer's own, not that width plus 4. + */ +inline void float_to_split_codes( + const float* x, + uint8_t* hi, + uint8_t* lo, + idx_t n, + int d, + size_t M2, + const ScalarQuantizer& sq) { + const int bits = sq_bits(sq.qtype); + const int lo_bits = bits - 4; + const size_t hi_stride = M2 / 2; + const size_t lo_stride = sq_rerank_size(d, sq.qtype); + const SQRanges ranges(sq, d); + for (idx_t i = 0; i < n; i++) { + const float* xi = x + i * d; + uint8_t* hdst = hi + i * hi_stride; + memset(hdst, 0, hi_stride); + uint8_t* ldst = lo + i * lo_stride; + memset(ldst, 0, lo_stride); + BitstringWriter bsw(ldst, lo_stride); + for (int m = 0; m < d; m++) { + const int code = + sq_code_of(xi[m], ranges.vmin(m), ranges.vdiff(m), bits); + const int h = code >> lo_bits; + hdst[m / 2] |= (m & 1) ? uint8_t(h << 4) : uint8_t(h); + bsw.write(code & ((1 << lo_bits) - 1), lo_bits); + } + } +} + +/// Rebuild the code values of one vector from its two halves. +inline void split_to_codes( + const uint8_t* hi, + const uint8_t* lo, + int d, + ScalarQuantizer::QuantizerType qtype, + int* codes_out) { + const int lo_bits = sq_rerank_bits(qtype); + BitstringReader bsr(lo, sq_rerank_size(d, qtype)); + for (int m = 0; m < d; m++) { + const int h = (m & 1) ? (hi[m / 2] >> 4) : (hi[m / 2] & 0xF); + codes_out[m] = (h << lo_bits) | int(bsr.read(lo_bits)); + } +} + +inline void float_to_4bit_nibbles( + const float* x, + uint8_t* nibbles, + idx_t n, + int d, + int M2, + const ScalarQuantizer& sq) { + const bool is_uniform = is_uniform_range(sq.qtype) || + sq.qtype == ScalarQuantizer::QT_4bit_uniform; + const float* vmin_arr = nullptr; + const float* vdiff_arr = nullptr; + float vmin_s = 0, inv_vdiff_s = 0; + + if (is_uniform) { + float vdiff; + get_uniform_range(sq, vmin_s, vdiff); + inv_vdiff_s = (vdiff > 0) ? (1.0f / vdiff) : 0; + } else { + vmin_arr = sq.trained.data(); + vdiff_arr = sq.trained.data() + d; + } + + const int half = M2 / 2; + for (idx_t i = 0; i < n; i++) { + const float* xi = x + i * d; + uint8_t* dst = nibbles + i * half; + memset(dst, 0, half); + for (int m = 0; m + 1 < d; m += 2) { + float f0, f1; + if (is_uniform) { + f0 = (xi[m] - vmin_s) * inv_vdiff_s; + f1 = (xi[m + 1] - vmin_s) * inv_vdiff_s; + } else { + f0 = (vdiff_arr[m] > 0) ? (xi[m] - vmin_arr[m]) / vdiff_arr[m] + : 0; + f1 = (vdiff_arr[m + 1] > 0) + ? (xi[m + 1] - vmin_arr[m + 1]) / vdiff_arr[m + 1] + : 0; + } + uint8_t lo = (uint8_t)std::min(15, std::max(0, (int)(f0 * 15.0f))); + uint8_t hi = (uint8_t)std::min(15, std::max(0, (int)(f1 * 15.0f))); + dst[m / 2] = lo | (hi << 4); + } + if (d & 1) { + float f; + if (is_uniform) { + f = (xi[d - 1] - vmin_s) * inv_vdiff_s; + } else { + f = (vdiff_arr[d - 1] > 0) + ? (xi[d - 1] - vmin_arr[d - 1]) / vdiff_arr[d - 1] + : 0; + } + dst[(d - 1) / 2] = + (uint8_t)std::min(15, std::max(0, (int)(f * 15.0f))); + } + } +} + +} // namespace sq_fastscan +} // namespace faiss diff --git a/thirdparty/faiss/faiss/index_factory.cpp b/thirdparty/faiss/faiss/index_factory.cpp index 94fa1a45c..a191899c2 100644 --- a/thirdparty/faiss/faiss/index_factory.cpp +++ b/thirdparty/faiss/faiss/index_factory.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -56,6 +57,10 @@ #include #include +#ifdef FAISS_ENABLE_DISK_IVF +#include +#endif + #ifdef FAISS_ENABLE_SVS #include #include @@ -179,8 +184,8 @@ std::map sq_types = { }; const std::string sq_pattern = "(SQ0|SQ4|SQ8|SQ6|SQfp16|SQbf16|SQ8_direct_signed|SQ8_direct|SQtqmse1|SQtqmse2|SQtqmse3|SQtqmse4|SQtqmse8|SQtq2|SQtq3|SQtq4|SQtq5)"; -// Native 4-bit types with "fs" suffix for IndexSQFastScan, optional _bbs -const std::string sq_fs_pattern = "(SQ4)fs(_[0-9]+)?"; +const std::string sq_fs_pattern = + "(SQ4|SQ6|SQ8|SQ8_direct_signed|SQ8_direct)fs(_[0-9]+)?"; // All SQ types with "fs" suffix for IndexIVFSQFastScan, optional _bbs const std::string ivf_sq_fs_pattern = "(SQ0|SQ4|SQ8|SQ6|SQfp16|SQbf16|SQ8_direct_signed|SQ8_direct|SQtqmse1|SQtqmse2|SQtqmse3|SQtqmse4|SQtqmse8|SQtq2|SQtq3|SQtq4|SQtq5)fs(_[0-9]+)?"; @@ -246,8 +251,11 @@ VectorTransform* parse_VectorTransform(const std::string& description, int d) { if (match("RR([0-9]+)?")) { return new RandomRotationMatrix(d, mres_to_int(sm[1], d)); } - if (match("HR([0-9]+)?")) { - return new HadamardRotation(d, mres_to_int(sm[1], 12345)); + // "HR" pads d to a power of 2, "HRk" to a multiple of 64 (the FHT-Kac + // rotation, see HadamardRotation). An optional seed follows: "HRk7". + if (match("HR(k?)([0-9]+)?")) { + return new HadamardRotation( + d, mres_to_int(sm[2], 12345), sm[1].length() == 0); } if (match("ITQ([0-9]+)?")) { return new ITQTransform(d, mres_to_int(sm[1], d), sm[1].length() > 0); @@ -317,6 +325,11 @@ Index* parse_coarse_quantizer( int R = std::stoi(sm[2]); return new IndexNSGFlat(d, R, mt); } + if (match("IVF([0-9]+[kM]?)_PiPNN([0-9]*)")) { + nlist = parse_nlist(sm[1].str()); + int R = mres_to_int(sm[2], 64); + return new IndexPiPNNFlat(d, R, mt); + } #ifdef FAISS_ENABLE_SVS if (match("IVF([0-9]+[kM]?)_SVSVamana([0-9]*)(_.+)?")) { nlist = parse_nlist(sm[1].str()); @@ -381,7 +394,10 @@ IndexIVF* parse_IndexIVF( auto match = [&sm, &code_string](const std::string pattern) { return re_match(code_string, pattern, sm); }; - auto get_q = [&quantizer] { return quantizer.release(); }; + // we cannot release the quantizer until we know no error happens and + // destroys the owning index since in this path the index does not own + // quantizer + auto get_q = [&quantizer] { return quantizer.get(); }; int d = quantizer->d; if (match("Flat")) { @@ -528,6 +544,18 @@ IndexIVF* parse_IndexIVF( } return index_ivf; } +#ifdef FAISS_ENABLE_DISK_IVF + // "RaBitQSSD_". Call attach_file() before add/search. + if (match("RaBitQSSD([2-9])_([0-9]+)")) { + uint8_t nb_bits = mres_to_int(sm[1]); + size_t mem_dim = mres_to_int(sm[2]); + auto* index_ivf = new IndexIVFRaBitQSSD( + quantizer.get(), d, nlist, mem_dim, nb_bits, mt); + quantizer.release(); + index_ivf->own_invlists = own_il; + return index_ivf; + } +#endif // IndexIVFRaBitQ with optional nb_bits (1-9) // Accepts: "RaBitQ" (default 1-bit) or "RaBitQ{nb_bits}" (e.g., "RaBitQ4") if (match("RaBitQ([1-9])?")) { @@ -655,6 +683,30 @@ IndexNSG* parse_IndexNSG( return nullptr; } +/*************************************************************** + * Parse IndexPiPNN + */ + +IndexPiPNN* parse_IndexPiPNN( + const std::string& code_string, + int d, + MetricType mt, + int pipnn_R) { + std::smatch sm; + auto match = [&sm, &code_string](const std::string& pattern) { + return re_match(code_string, pattern, sm); + }; + + if (match("Flat|")) { + return new IndexPiPNNFlat(d, pipnn_R, mt); + } + if (match(sq_pattern)) { + return new IndexPiPNNSQ(d, sq_types[sm[1].str()], pipnn_R, mt); + } + + return nullptr; +} + #ifdef FAISS_ENABLE_SVS /*************************************************************** * Parse IndexSVS @@ -1180,6 +1232,28 @@ std::unique_ptr index_factory_sub( return std::unique_ptr(index); } + // PiPNN variants (separator "," or "_", as for HNSW and NSG) + if (re_match(description, "PiPNN([0-9]*)([,_].*)?", sm)) { + int pipnn_R = mres_to_int(sm[1], 64); + // We also accept empty code string (synonym of Flat) + std::string code_string = + sm[2].length() > 0 ? sm[2].str().substr(1) : ""; + if (verbose) { + printf("parsing PiPNN string %s code_string=%s pipnn_R=%d\n", + description.c_str(), + code_string.c_str(), + pipnn_R); + } + + IndexPiPNN* index = parse_IndexPiPNN(code_string, d, metric, pipnn_R); + FAISS_THROW_IF_NOT_FMT( + index, + "could not parse PiPNN code description %s in %s", + code_string.c_str(), + description.c_str()); + return std::unique_ptr(index); + } + // IndexRowwiseMinMax, fp32 version if (description.compare(0, 7, "MinMax,") == 0) { size_t comma = description.find(','); @@ -1206,8 +1280,8 @@ std::unique_ptr index_factory_sub( // IndexIVF { - size_t nlist; - bool use_2layer; + size_t nlist = 0; + bool use_2layer = false; size_t comma = description.find(','); std::string coarse_string = description.substr(0, comma); // Match coarse quantizer part first @@ -1231,7 +1305,8 @@ std::unique_ptr index_factory_sub( description.c_str()); int M = std::stoi(sm[1].str()), nbit = mres_to_int(sm[2], 8, 1); Index2Layer* index_2l = - new Index2Layer(quantizer.release(), nlist, M, nbit); + new Index2Layer(quantizer.get(), nlist, M, nbit); + (void)quantizer.release(); // now owned by index_2l index_2l->q1.own_fields = true; index_2l->q1.quantizer_trains_alone = get_trains_alone(index_2l->q1.quantizer); @@ -1246,6 +1321,7 @@ std::unique_ptr index_factory_sub( "could not parse code description %s in %s", code_description.c_str(), description.c_str()); + (void)quantizer.release(); // now owned by index_ivf return std::unique_ptr(fix_ivf_fields(index_ivf)); } } diff --git a/thirdparty/faiss/faiss/invlists/DirectMap.cpp b/thirdparty/faiss/faiss/invlists/DirectMap.cpp index b093538cc..68f82ff50 100644 --- a/thirdparty/faiss/faiss/invlists/DirectMap.cpp +++ b/thirdparty/faiss/faiss/invlists/DirectMap.cpp @@ -93,7 +93,7 @@ void DirectMap::add_single_id(idx_t id, idx_t list_no, size_t offset) { } if (type == Array) { - assert(id == array.size()); + assert(static_cast(id) == array.size()); if (list_no >= 0) { array.push_back(lo_build(list_no, offset)); } else { diff --git a/thirdparty/faiss/faiss/invlists/DiskIOBackend.cpp b/thirdparty/faiss/faiss/invlists/DiskIOBackend.cpp new file mode 100644 index 000000000..e0db5e17e --- /dev/null +++ b/thirdparty/faiss/faiss/invlists/DiskIOBackend.cpp @@ -0,0 +1,121 @@ +/* + * 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. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace faiss { + +DiskIOBackend::DiskIOBackend(int max_events_in) { + FAISS_THROW_IF_NOT(max_events_in > 0); + const int ret = io_setup(max_events_in, &ctx); + FAISS_THROW_IF_NOT_FMT( + ret == 0, + "io_setup failed: %s%s", + strerror(-ret), + ret == -EAGAIN ? " (too many libaio contexts, see fs.aio-max-nr)" + : ""); + pid = getpid(); + max_events = max_events_in; + iocbs.resize(max_events); + iocb_ptrs.resize(max_events); + events.resize(max_events); +} + +DiskIOBackend::~DiskIOBackend() { + // blocks until the reads in flight are done, so the caller can free their + // buffers afterwards. The context of a parent process is not ours to + // destroy. + if (owned_by_this_process()) { + io_destroy(ctx); + } +} + +void DiskIOBackend::stage( + int fd, + void* buf, + size_t len, + size_t offset, + void* user_data) { + FAISS_THROW_IF_NOT_MSG( + n_staged < max_events, "DiskIOBackend: too many reads staged"); + iocb* cb = &iocbs[n_staged]; + io_prep_pread(cb, fd, buf, len, static_cast(offset)); + cb->data = user_data; + iocb_ptrs[n_staged] = cb; + n_staged++; +} + +void DiskIOBackend::submit() { + int done = 0; + while (done < n_staged) { + const int ret = + io_submit(ctx, n_staged - done, iocb_ptrs.data() + done); + if (ret == -EINTR || ret == -EAGAIN) { + continue; // transient, the queue is sized for all reads in flight + } + FAISS_THROW_IF_NOT_FMT( + ret > 0, + "io_submit failed: %s", + ret < 0 ? strerror(-ret) : "no read accepted"); + done += ret; + n_in_flight += ret; + } + n_staged = 0; +} + +int DiskIOBackend::reap(void** user_data, long* res, int max, int min_nr) { + max = std::min(max, max_events); + min_nr = std::min(min_nr, std::min(max, n_in_flight)); + struct timespec no_wait = {0, 0}; + const int ret = io_getevents( + ctx, min_nr, max, events.data(), min_nr > 0 ? nullptr : &no_wait); + if (ret == -EINTR) { + return 0; + } + FAISS_THROW_IF_NOT_FMT(ret >= 0, "io_getevents failed: %s", strerror(-ret)); + n_in_flight -= ret; + for (int i = 0; i < ret; i++) { + user_data[i] = events[i].data; + // bytes read or a negative errno, in an unsigned field + res[i] = static_cast(events[i].res); + } + return ret; +} + +bool DiskIOBackend::wait_all() noexcept { + n_staged = 0; + while (n_in_flight > 0) { + const int ret = io_getevents( + ctx, n_in_flight, max_events, events.data(), nullptr); + if (ret == -EINTR) { + continue; + } + if (ret < 0) { + return false; + } + n_in_flight -= ret; + } + return true; +} + +bool DiskIOBackend::owned_by_this_process() const { + return pid == getpid(); +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/invlists/DiskIOBackend.h b/thirdparty/faiss/faiss/invlists/DiskIOBackend.h new file mode 100644 index 000000000..648f31068 --- /dev/null +++ b/thirdparty/faiss/faiss/invlists/DiskIOBackend.h @@ -0,0 +1,71 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include +#include + +namespace faiss { + +/** Asynchronous reads with Linux libaio, for one thread. + * + * Reads are staged with stage(), sent to the kernel together with submit(), + * and collected with reap(). With a file opened with + * O_DIRECT, the buffer address, offset and length of every read must be + * multiples of the device sector size. + */ +struct DiskIOBackend { + io_context_t ctx = nullptr; + pid_t pid = 0; ///< process that created ctx + int max_events = 0; ///< at most max_events reads can be in flight + int n_staged = 0; ///< reads staged for the next submit() + int n_in_flight = 0; ///< submitted and not reaped + std::vector iocbs; + std::vector iocb_ptrs; + std::vector events; + + explicit DiskIOBackend(int max_events); + ~DiskIOBackend(); + + DiskIOBackend(const DiskIOBackend&) = delete; + DiskIOBackend& operator=(const DiskIOBackend&) = delete; + + /// add a read of len bytes at offset into buf to the next submit(); + /// user_data identifies it in reap() + void stage(int fd, void* buf, size_t len, size_t offset, void* user_data); + + /// send the staged reads to the kernel + void submit(); + + /** Collect up to max completed reads, waiting until at least min_nr + * have completed (without waiting if min_nr is 0). min_nr is capped by + * max and by the reads in flight, and a signal can end the wait early. + * + * @param user_data output, the user_data of each completed read + * @param res output, the bytes read, or a negative errno + * @return number of completed reads + */ + int reap(void** user_data, long* res, int max, int min_nr = 0); + + /** Drop the staged reads and wait for the submitted ones to complete, + * ignoring their results, so that their buffers can be freed and the + * context reused. + * + * @return false if waiting failed: reads may still be in flight + */ + bool wait_all() noexcept; + + /// false in a process forked after the context was created: the context + /// belongs to the parent process and cannot be used + bool owned_by_this_process() const; +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/invlists/InvertedLists.cpp b/thirdparty/faiss/faiss/invlists/InvertedLists.cpp index 59f062c47..338129486 100644 --- a/thirdparty/faiss/faiss/invlists/InvertedLists.cpp +++ b/thirdparty/faiss/faiss/invlists/InvertedLists.cpp @@ -127,7 +127,9 @@ size_t InvertedLists::copy_subset_to( } else if (subset_type == SUBSET_TYPE_ID_MOD) { for (size_t i = 0; i < n; i++) { idx_t id = ids_in[i]; - if (id % a1 == a2) { + // C++ gives a negative remainder, so a plain `id % a1` never + // matches for a negative id. Fold it into [0, a1) instead. + if (((id % a1) + a1) % a1 == a2) { oivf.add_entry( list_no, get_single_id(list_no, i), @@ -296,23 +298,24 @@ size_t ArrayInvertedLists::add_entries( } size_t ArrayInvertedLists::list_size(size_t list_no) const { - assert(list_no < nlist); + FAISS_THROW_IF_NOT(list_no < nlist); return ids[list_no].size(); } bool ArrayInvertedLists::is_empty(size_t list_no, void* inverted_list_context) const { FAISS_THROW_IF_NOT(inverted_list_context == nullptr); + FAISS_THROW_IF_NOT(list_no < nlist); return ids[list_no].size() == 0; } const uint8_t* ArrayInvertedLists::get_codes(size_t list_no) const { - assert(list_no < nlist); + FAISS_THROW_IF_NOT(list_no < nlist); return codes[list_no].data(); } const idx_t* ArrayInvertedLists::get_ids(size_t list_no) const { - assert(list_no < nlist); + FAISS_THROW_IF_NOT(list_no < nlist); return ids[list_no].data(); } @@ -929,10 +932,12 @@ void StopWordsInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist_in) * CappedInvertedLists implementation ******************************************/ -CappedInvertedLists::CappedInvertedLists(InvertedLists* il0, size_t maxsize) - : InvertedLists(il0->nlist, il0->code_size), - il0(il0), - maxsize(maxsize) {} +CappedInvertedLists::CappedInvertedLists( + InvertedLists* il0_in, + size_t maxsize_in) + : InvertedLists(il0_in->nlist, il0_in->code_size), + il0(il0_in), + maxsize(maxsize_in) {} size_t CappedInvertedLists::list_size(size_t list_no) const { size_t sz = il0->list_size(list_no); @@ -972,9 +977,9 @@ const uint8_t* CappedInvertedLists::get_single_code( return il0->get_single_code(list_no, offset); } -void CappedInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist) +void CappedInvertedLists::prefetch_lists(const idx_t* list_nos, int nlist_in) const { - il0->prefetch_lists(list_nos, nlist); + il0->prefetch_lists(list_nos, nlist_in); } size_t CappedInvertedLists::add_entries( diff --git a/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.cpp b/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.cpp index d8ff655c8..f936de74b 100644 --- a/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.cpp +++ b/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.cpp @@ -17,6 +17,10 @@ #include #endif // !_WIN32 +#ifdef FAISS_ENABLE_DISK_IVF +#include +#endif + namespace faiss { /********************************************************** @@ -35,6 +39,9 @@ struct IOHookTable : std::vector { IOHookTable() { #ifndef _WIN32 push_back(new OnDiskInvertedListsIOHook()); +#endif +#ifdef FAISS_ENABLE_DISK_IVF + push_back(new RaBitQSSDInvertedListsIOHook()); #endif push_back(new BlockInvertedListsIOHook()); } @@ -90,6 +97,25 @@ void InvertedListsIOHook::print_callbacks() { } } +std::string ondisk_same_dir_filename(IOReader* f, const std::string& filename) { + FileIOReader* reader = dynamic_cast(f); + FAISS_THROW_IF_NOT_MSG( + reader, + "IO_FLAG_ONDISK_SAME_DIR only supported " + "when reading from file"); + std::string dirname = "./"; + size_t slash = reader->name.find_last_of('/'); + if (slash != std::string::npos) { + dirname = reader->name.substr(0, slash + 1); + } + std::string basename = filename; + slash = basename.find_last_of('/'); + if (slash != std::string::npos) { + basename = basename.substr(slash + 1); + } + return dirname + basename; +} + InvertedLists* InvertedListsIOHook::read_ArrayInvertedLists( IOReader*, int, diff --git a/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.h b/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.h index cfeeac8c5..96d5b85c2 100644 --- a/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.h +++ b/thirdparty/faiss/faiss/invlists/InvertedListsIOHook.h @@ -59,4 +59,9 @@ struct InvertedListsIOHook { static InvertedListsIOHook* lookup_classname(const std::string& classname); }; +/** For IO_FLAG_ONDISK_SAME_DIR: the path of a data file with the base name of + * filename, in the directory of the index file f is reading from. + */ +std::string ondisk_same_dir_filename(IOReader* f, const std::string& filename); + } // namespace faiss diff --git a/thirdparty/faiss/faiss/invlists/OnDiskInvertedLists.cpp b/thirdparty/faiss/faiss/invlists/OnDiskInvertedLists.cpp index 66b2568be..84fd02929 100644 --- a/thirdparty/faiss/faiss/invlists/OnDiskInvertedLists.cpp +++ b/thirdparty/faiss/faiss/invlists/OnDiskInvertedLists.cpp @@ -11,6 +11,7 @@ #include +#include #include #include @@ -152,22 +153,22 @@ struct OnDiskInvertedLists::OngoingPrefetch { if (list_no == -1) { return false; } - const OnDiskInvertedLists* od = pf->od; - od->locks->lock_1(list_no); - size_t n = od->list_size(list_no); - const idx_t* idx = od->get_ids(list_no); - const uint8_t* codes = od->get_codes(list_no); + const OnDiskInvertedLists* invlists = pf->od; + invlists->locks->lock_1(static_cast(list_no)); + size_t n = invlists->list_size(list_no); + const idx_t* idx = invlists->get_ids(list_no); + const uint8_t* codes = invlists->get_codes(list_no); int cs = 0; for (size_t i = 0; i < n; i++) { cs += idx[i]; } const idx_t* codes8 = (const idx_t*)codes; - size_t n8 = n * od->code_size / 8; + size_t n8 = n * invlists->code_size / 8; for (size_t i = 0; i < n8; i++) { cs += codes8[i]; } - od->locks->unlock_1(list_no); + invlists->locks->unlock_1(static_cast(list_no)); global_cs += cs & 1; return true; @@ -737,23 +738,7 @@ InvertedLists* OnDiskInvertedListsIOHook::read(IOReader* f, int io_flags) od->filename.assign(x.begin(), x.end()); if (io_flags & IO_FLAG_ONDISK_SAME_DIR) { - FileIOReader* reader = dynamic_cast(f); - FAISS_THROW_IF_NOT_MSG( - reader, - "IO_FLAG_ONDISK_SAME_DIR only supported " - "when reading from file"); - std::string indexname = reader->name; - std::string dirname = "./"; - size_t slash = indexname.find_last_of('/'); - if (slash != std::string::npos) { - dirname = indexname.substr(0, slash + 1); - } - std::string filename = od->filename; - slash = filename.find_last_of('/'); - if (slash != std::string::npos) { - filename = filename.substr(slash + 1); - } - filename = dirname + filename; + std::string filename = ondisk_same_dir_filename(f, od->filename); printf("IO_FLAG_ONDISK_SAME_DIR: " "updating ondisk filename from %s to %s\n", od->filename.c_str(), diff --git a/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp b/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp new file mode 100644 index 000000000..b9a038afa --- /dev/null +++ b/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.cpp @@ -0,0 +1,751 @@ +/* + * 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. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace faiss { + +namespace { + +constexpr size_t kSectorSize = RaBitQSSDInvertedLists::kSectorSize; +constexpr char kFileMagic[8] = {'F', 'A', 'I', 'S', 'S', 'D', 'R', 'Q'}; +constexpr uint32_t kFileVersion = 1; + +/// stored at the start of the file +struct FileHeader { + char magic[8]; + uint32_t version; + uint32_t reserved; + uint64_t d; + uint64_t mem_dim; + uint64_t ex_bits; + uint64_t record_size; + uint64_t page_size; + uint64_t file_id; +}; + +static_assert(sizeof(FileHeader) <= kSectorSize); + +/// I/O buffers are aligned for O_DIRECT +constexpr int kBufferAlignment = 4096; +static_assert(kBufferAlignment == kSectorSize); +using IOBuffer = AlignedTableTightAlloc; + +/// largest single read or write issued when processing a whole list +constexpr size_t kMaxIOBytes = size_t(1) << 23; + +/// Open a file with O_DIRECT, so that reads bypass the page cache. +int open_direct(const std::string& fname, int flags) { + return open(fname.c_str(), flags | O_DIRECT, 0644); +} + +void pread_all( + int fd, + uint8_t* buf, + size_t len, + size_t offset, + const std::string& fname) { + while (len > 0) { + ssize_t ret = pread(fd, buf, len, static_cast(offset)); + if (ret < 0 && errno == EINTR) { + continue; + } + FAISS_THROW_IF_NOT_FMT( + ret >= 0, + "read of %s at offset %zu failed: %s", + fname.c_str(), + offset, + strerror(errno)); + FAISS_THROW_IF_NOT_FMT( + ret > 0, + "read of %s at offset %zu: unexpected end of file", + fname.c_str(), + offset); + buf += ret; + len -= ret; + offset += ret; + } +} + +void pwrite_all( + int fd, + const uint8_t* buf, + size_t len, + size_t offset, + const std::string& fname) { + while (len > 0) { + ssize_t ret = pwrite(fd, buf, len, static_cast(offset)); + if (ret < 0 && errno == EINTR) { + continue; + } + FAISS_THROW_IF_NOT_FMT( + ret > 0, + "write of %s at offset %zu failed: %s", + fname.c_str(), + offset, + strerror(errno)); + buf += ret; + len -= ret; + offset += ret; + } +} + +uint64_t random_file_id() { + std::random_device rd; + uint64_t id = (uint64_t(rd()) << 32) ^ rd(); + return id ^ + uint64_t( + std::chrono::steady_clock::now() + .time_since_epoch() + .count()); +} + +/// pages from page_no to the end of its extent +size_t pages_left_in_extent( + const RaBitQSSDInvertedLists& il, + size_t list_no, + size_t page_no) { + for (const RaBitQSSDInvertedLists::Extent& e : il.extents[list_no]) { + if (page_no < e.n_pages) { + return e.n_pages - page_no; + } + page_no -= e.n_pages; + } + FAISS_THROW_FMT( + "RaBitQSSDInvertedLists: page beyond the end of list %zu", list_no); +} + +/// read or write n_pages consecutive pages of a list, which must lie in one +/// extent, with a blocking call +void read_pages( + const RaBitQSSDInvertedLists& il, + size_t list_no, + size_t page_no, + size_t n_pages, + uint8_t* buf) { + FAISS_THROW_IF_NOT_MSG( + il.fd >= 0, "RaBitQSSDInvertedLists: the file is not open"); + FAISS_ASSERT(n_pages <= pages_left_in_extent(il, list_no, page_no)); + pread_all( + il.fd, + buf, + n_pages * il.page_size, + il.page_offset(list_no, page_no), + il.filename); +} + +void write_pages( + RaBitQSSDInvertedLists& il, + size_t list_no, + size_t page_no, + size_t n_pages, + const uint8_t* buf) { + FAISS_ASSERT(n_pages <= pages_left_in_extent(il, list_no, page_no)); + pwrite_all( + il.fd, + buf, + n_pages * il.page_size, + il.page_offset(list_no, page_no), + il.filename); +} + +void write_header(RaBitQSSDInvertedLists& il) { + FileHeader h; + memcpy(h.magic, kFileMagic, sizeof(kFileMagic)); + h.version = kFileVersion; + h.reserved = 0; + h.d = il.d; + h.mem_dim = il.mem_dim; + h.ex_bits = il.ex_bits; + h.record_size = il.record_size; + h.page_size = il.page_size; + h.file_id = il.file_id; + IOBuffer buf(kSectorSize); + memset(buf.get(), 0, kSectorSize); + memcpy(buf.get(), &h, sizeof(h)); + pwrite_all(il.fd, buf.get(), kSectorSize, 0, il.filename); +} + +void check_header(const RaBitQSSDInvertedLists& il) { + IOBuffer buf(kSectorSize); + pread_all(il.fd, buf.get(), kSectorSize, 0, il.filename); + FileHeader h; + memcpy(&h, buf.get(), sizeof(h)); + FAISS_THROW_IF_NOT_FMT( + memcmp(h.magic, kFileMagic, sizeof(kFileMagic)) == 0, + "%s is not a RaBitQSSDInvertedLists file", + il.filename.c_str()); + FAISS_THROW_IF_NOT_FMT( + h.version == kFileVersion, + "%s: unsupported file version %u", + il.filename.c_str(), + h.version); + FAISS_THROW_IF_NOT_FMT( + h.d == il.d && h.mem_dim == il.mem_dim && h.ex_bits == il.ex_bits && + h.record_size == il.record_size && + h.page_size == il.page_size, + "%s does not match the inverted lists: file has d=%" PRIu64 + " mem_dim=%" PRIu64 " ex_bits=%" PRIu64 + ", lists have d=%zu mem_dim=%zu ex_bits=%zu", + il.filename.c_str(), + h.d, + h.mem_dim, + h.ex_bits, + il.d, + il.mem_dim, + il.ex_bits); + FAISS_THROW_IF_NOT_FMT( + h.file_id == il.file_id, + "%s was written for another index (file id %016" PRIx64 + ", expected %016" PRIx64 ")", + il.filename.c_str(), + h.file_id, + il.file_id); +} + +} // namespace + +struct RaBitQSSDInvertedLists::IOState { + /// contexts of acquire_io() that are not in use + std::vector> io_pool; + std::mutex io_pool_mutex; ///< protects io_pool + std::mutex alloc_mutex; ///< protects total_pages +}; + +/********************************************************* + * RaBitQSSDInvertedLists + *********************************************************/ + +RaBitQSSDInvertedLists::RaBitQSSDInvertedLists( + size_t nlist_in, + size_t d_in, + size_t mem_dim_in, + size_t ex_bits_in, + const char* filename_in) + : InvertedLists(nlist_in, INVALID_CODE_SIZE), + d(d_in), + mem_dim(mem_dim_in), + ex_bits(ex_bits_in) { + FAISS_THROW_IF_NOT_MSG( + filename_in && filename_in[0], + "RaBitQSSDInvertedLists needs a file name"); + filename = filename_in; + set_derived_values(); + sizes.resize(nlist, 0); + mem_data.resize(nlist); + extents.resize(nlist); + file_id = random_file_id(); + + fd = open_direct(filename, O_RDWR | O_CREAT | O_TRUNC); + FAISS_THROW_IF_NOT_FMT( + fd >= 0, + "could not create %s with O_DIRECT: %s", + filename.c_str(), + strerror(errno)); + try { + write_header(*this); + } catch (...) { + close(fd); + fd = -1; + throw; + } + io_state = new IOState; +} + +RaBitQSSDInvertedLists::RaBitQSSDInvertedLists() + : InvertedLists(0, INVALID_CODE_SIZE), io_state(new IOState) {} + +RaBitQSSDInvertedLists::~RaBitQSSDInvertedLists() { + // destroying a libaio context waits for an RCU grace period, tens of + // milliseconds: destroy them in parallel. The contexts of a parent + // process, before a fork(), are only dropped, without a parallel region: + // OpenMP can hang in a forked child. + std::vector>& io_pool = io_state->io_pool; + const auto own_end = std::partition( + io_pool.begin(), + io_pool.end(), + [](const std::unique_ptr& io) { + return io->owned_by_this_process(); + }); + const int n_io = int(own_end - io_pool.begin()); + if (n_io > 1) { +#pragma omp parallel for num_threads(n_io) + for (int i = 0; i < n_io; i++) { + io_pool[i].reset(); + } + } + delete io_state; + if (fd >= 0) { + close(fd); + } +} + +void RaBitQSSDInvertedLists::set_derived_values() { + FAISS_THROW_IF_NOT_FMT( + d > 0 && d % 64 == 0 && d < (size_t(1) << 31), + "d=%zu must be a positive multiple of 64", + d); + FAISS_THROW_IF_NOT_FMT( + mem_dim >= 64 && mem_dim <= d && mem_dim % 64 == 0, + "mem_dim=%zu must be a multiple of 64 in [64, d=%zu]", + mem_dim, + d); + FAISS_THROW_IF_NOT_FMT( + ex_bits >= 1 && ex_bits <= 8, + "ex_bits=%zu must be in [1, 8]", + ex_bits); + batch_bytes = + kBatchSize * mem_dim / 8 + kBatchSize * kMemFactors * sizeof(float); + record_size = (d - mem_dim) / 8 + d * ex_bits / 8 + + sizeof(rabitq_utils::ExtraBitsFactors) + sizeof(idx_t); + page_size = (record_size + kSectorSize - 1) / kSectorSize * kSectorSize; + records_per_page = page_size / record_size; +} + +size_t RaBitQSSDInvertedLists::list_batches(size_t list_no) const { + return (sizes[list_no] + kBatchSize - 1) / kBatchSize; +} + +size_t RaBitQSSDInvertedLists::list_pages(size_t list_no) const { + return (sizes[list_no] + records_per_page - 1) / records_per_page; +} + +std::unique_ptr RaBitQSSDInvertedLists::acquire_io( + int max_events) const { + std::unique_ptr too_small; + { + std::lock_guard lock(io_state->io_pool_mutex); + std::vector>& io_pool = + io_state->io_pool; + for (size_t i = io_pool.size(); i > 0; i--) { + DiskIOBackend& io = *io_pool[i - 1]; + if (!io.owned_by_this_process()) { + // kept by a parent process before a fork() + io_pool.erase(io_pool.begin() + (i - 1)); + } else if (io.max_events >= max_events) { + std::unique_ptr taken = + std::move(io_pool[i - 1]); + io_pool.erase(io_pool.begin() + (i - 1)); + return taken; + } + } + // the contexts left are too small: replace one, so that the pool + // does not grow each time qd_per_thread increases + if (!io_pool.empty()) { + too_small = std::move(io_pool.back()); + io_pool.pop_back(); + } + } + // destroyed out of the lock (io_destroy takes milliseconds), and before + // the new context takes its share of fs.aio-max-nr + too_small.reset(); + return std::make_unique(max_events); +} + +void RaBitQSSDInvertedLists::release_io( + std::unique_ptr io) const noexcept { + try { + std::lock_guard lock(io_state->io_pool_mutex); + io_state->io_pool.push_back(std::move(io)); + } catch (...) { + // the context is destroyed instead of kept + } +} + +size_t RaBitQSSDInvertedLists::list_size(size_t list_no) const { + return sizes[list_no]; +} + +const uint8_t* RaBitQSSDInvertedLists::get_codes(size_t) const { + FAISS_THROW_MSG( + "RaBitQSSDInvertedLists: the codes are split between memory " + "and disk and cannot be accessed as flat codes"); +} + +const idx_t* RaBitQSSDInvertedLists::get_ids(size_t list_no) const { + const size_t n = sizes[list_no]; + if (n == 0) { + return nullptr; + } + std::unique_ptr ids(new idx_t[n]); + const size_t n_pages = list_pages(list_no); + const size_t max_pages = std::max(1, kMaxIOBytes / page_size); + const size_t id_offset = record_size - sizeof(idx_t); + IOBuffer buf(std::min(n_pages, max_pages) * page_size); + + for (size_t page = 0; page < n_pages;) { + size_t n_read = std::min( + {n_pages - page, + max_pages, + pages_left_in_extent(*this, list_no, page)}); + read_pages(*this, list_no, page, n_read, buf.get()); + for (size_t i = page * records_per_page; + i < std::min(n, (page + n_read) * records_per_page); + i++) { + const size_t pos = i - page * records_per_page; + const uint8_t* rec = buf.get() + + pos / records_per_page * page_size + + pos % records_per_page * record_size; + memcpy(&ids[i], rec + id_offset, sizeof(idx_t)); + } + page += n_read; + } + return ids.release(); +} + +void RaBitQSSDInvertedLists::release_ids(size_t, const idx_t* ids) const { + delete[] ids; +} + +idx_t RaBitQSSDInvertedLists::get_single_id(size_t list_no, size_t offset) + const { + FAISS_THROW_IF_NOT(offset < sizes[list_no]); + IOBuffer buf(page_size); + read_pages(*this, list_no, offset / records_per_page, 1, buf.get()); + idx_t id; + memcpy(&id, + buf.get() + offset % records_per_page * record_size + record_size - + sizeof(idx_t), + sizeof(idx_t)); + return id; +} + +size_t RaBitQSSDInvertedLists::add_entries( + size_t, + size_t, + const idx_t*, + const uint8_t*) { + FAISS_THROW_MSG( + "RaBitQSSDInvertedLists: add vectors with " + "IndexIVFRaBitQSSD::add"); +} + +void RaBitQSSDInvertedLists::update_entries( + size_t, + size_t, + size_t, + const idx_t*, + const uint8_t*) { + FAISS_THROW_MSG("RaBitQSSDInvertedLists: update_entries not supported"); +} + +void RaBitQSSDInvertedLists::resize(size_t list_no, size_t new_size) { + FAISS_THROW_IF_NOT_MSG( + new_size == sizes[list_no], + "RaBitQSSDInvertedLists: lists cannot be resized"); +} + +void RaBitQSSDInvertedLists::reset() { + FAISS_THROW_IF_MSG(read_only, "RaBitQSSDInvertedLists: opened read-only"); + std::fill(sizes.begin(), sizes.end(), 0); + for (auto& table : mem_data) { + table.resize(0); + } + for (auto& list_extents : extents) { + list_extents.clear(); + } + total_pages = 0; + if (fd >= 0) { + FAISS_THROW_IF_NOT_FMT( + ftruncate(fd, kSectorSize) == 0, + "could not truncate %s: %s", + filename.c_str(), + strerror(errno)); + file_id = random_file_id(); + write_header(*this); + } +} + +void RaBitQSSDInvertedLists::reserve(size_t list_no, size_t n_more) { + FAISS_THROW_IF_MSG(read_only, "RaBitQSSDInvertedLists: opened read-only"); + const size_t needed = + (sizes[list_no] + n_more + records_per_page - 1) / records_per_page; + std::vector& list_extents = extents[list_no]; + size_t capacity = 0; + for (const Extent& e : list_extents) { + capacity += e.n_pages; + } + if (needed <= capacity) { + return; + } + // grow by at least half the capacity, so that a list made by many + // appends has few extents while at most a third of its pages are unused + const size_t n_pages = std::max(needed - capacity, capacity / 2); + size_t first_page; + { + std::lock_guard lock(io_state->alloc_mutex); + first_page = total_pages; + total_pages += n_pages; + } + if (!list_extents.empty() && + list_extents.back().first_page + list_extents.back().n_pages == + first_page) { + list_extents.back().n_pages += n_pages; + } else { + list_extents.push_back(Extent{first_page, n_pages}); + } +} + +void RaBitQSSDInvertedLists::append( + size_t list_no, + size_t n, + const uint8_t* mem_codes_in, + const float* factors, + const uint8_t* records) { + if (n == 0) { + return; + } + FAISS_THROW_IF_NOT_MSG( + fd >= 0, "RaBitQSSDInvertedLists: the file is not open"); + reserve(list_no, n); + const size_t n0 = sizes[list_no]; + const size_t n1 = n0 + n; + + // write the records to the pages [page0, page1) + const size_t page0 = n0 / records_per_page; + const size_t page1 = (n1 + records_per_page - 1) / records_per_page; + const size_t max_pages = std::max(1, kMaxIOBytes / page_size); + IOBuffer buf(std::min(page1 - page0, max_pages) * page_size); + size_t i = 0; // next record to write + for (size_t page = page0; page < page1;) { + const size_t n_write = std::min( + {page1 - page, + max_pages, + pages_left_in_extent(*this, list_no, page)}); + memset(buf.get(), 0, n_write * page_size); + // the first page may already hold records of this list + size_t slot = n0 + i - page * records_per_page; + if (slot > 0) { + read_pages(*this, list_no, page, 1, buf.get()); + } + for (size_t j = 0; j < n_write; j++) { + uint8_t* page_buf = buf.get() + j * page_size; + for (; slot < records_per_page && i < n; slot++, i++) { + memcpy(page_buf + slot * record_size, + records + i * record_size, + record_size); + } + slot = 0; + } + write_pages(*this, list_no, page, n_write, buf.get()); + page += n_write; + } + + // in-memory batches: the sign bits in the FastScan layout, then the + // factors. pq4_pack_codes_range only ORs the new codes in, so the bytes + // after the used ones are kept at 0. + const size_t n_batches = (n1 + kBatchSize - 1) / kBatchSize; + AlignedTableTightAlloc& table = mem_data[list_no]; + if (table.size() < n_batches * batch_bytes) { + const size_t old_size = table.size(); + table.resize(std::max(n_batches * batch_bytes, 2 * old_size)); + memset(table.get() + old_size, 0, table.size() - old_size); + } + const size_t nsq = mem_dim / 4; + pq4_pack_codes_range( + mem_codes_in, + nsq, + n0, + n1, + kBatchSize, + nsq, + table.get(), + mem_dim / 8, + batch_bytes); + const size_t code_bytes = kBatchSize * mem_dim / 8; + for (size_t j = 0; j < n; j++) { + const size_t pos = n0 + j; + uint8_t* batch = table.get() + pos / kBatchSize * batch_bytes; + for (size_t k = 0; k < kMemFactors; k++) { + memcpy(batch + code_bytes + + (k * kBatchSize + pos % kBatchSize) * sizeof(float), + factors + j * kMemFactors + k, + sizeof(float)); + } + } + + sizes[list_no] = n1; +} + +size_t RaBitQSSDInvertedLists::page_offset(size_t list_no, size_t page_no) + const { + for (const Extent& e : extents[list_no]) { + if (page_no < e.n_pages) { + return kSectorSize + (e.first_page + page_no) * page_size; + } + page_no -= e.n_pages; + } + FAISS_THROW_FMT( + "RaBitQSSDInvertedLists: page beyond the end of list %zu", list_no); +} + +void RaBitQSSDInvertedLists::open_file() { + FAISS_THROW_IF_NOT_MSG( + fd < 0, "RaBitQSSDInvertedLists: the file is already open"); + fd = open_direct(filename, read_only ? O_RDONLY : O_RDWR); + FAISS_THROW_IF_NOT_FMT( + fd >= 0, + "could not open %s with O_DIRECT: %s", + filename.c_str(), + strerror(errno)); + check_header(*this); +} + +/********************************************************* + * I/O hook + *********************************************************/ + +RaBitQSSDInvertedListsIOHook::RaBitQSSDInvertedListsIOHook() + : InvertedListsIOHook("ildr", typeid(RaBitQSSDInvertedLists).name()) {} + +void RaBitQSSDInvertedListsIOHook::write( + const InvertedLists* ils_in, + IOWriter* f) const { + const auto* ils = dynamic_cast(ils_in); + FAISS_THROW_IF_NOT(ils); + uint32_t h = fourcc("ildr"); + WRITE1(h); + WRITE1(ils->nlist); + WRITE1(ils->d); + WRITE1(ils->mem_dim); + WRITE1(ils->ex_bits); + WRITE1(ils->file_id); + WRITE1(ils->total_pages); + { + std::vector x(ils->filename.begin(), ils->filename.end()); + WRITEVECTOR(x); + } + WRITEVECTOR(ils->sizes); + { + std::vector n_extents, flat_extents; + for (const auto& list_extents : ils->extents) { + n_extents.push_back(list_extents.size()); + for (const auto& e : list_extents) { + flat_extents.push_back(e.first_page); + flat_extents.push_back(e.n_pages); + } + } + WRITEVECTOR(n_extents); + WRITEVECTOR(flat_extents); + } + for (size_t l = 0; l < ils->nlist; l++) { + if (ils->sizes[l] > 0) { + WRITEANDCHECK( + ils->mem_data[l].get(), + ils->list_batches(l) * ils->batch_bytes); + } + } +} + +InvertedLists* RaBitQSSDInvertedListsIOHook::read(IOReader* f, int io_flags) + const { + FAISS_THROW_IF_MSG( + io_flags & IO_FLAG_SKIP_IVF_DATA, + "RaBitQSSDInvertedLists: IO_FLAG_SKIP_IVF_DATA and IO_FLAG_MMAP " + "are not supported"); + auto ils = std::make_unique(); + ils->read_only = io_flags & IO_FLAG_READ_ONLY; + READ1(ils->nlist); + READ1(ils->d); + READ1(ils->mem_dim); + READ1(ils->ex_bits); + ils->set_derived_values(); + READ1(ils->file_id); + READ1(ils->total_pages); + FAISS_THROW_IF_NOT_MSG( + ils->total_pages <= (SIZE_MAX - kSectorSize) / ils->page_size, + "RaBitQSSDInvertedLists: total_pages too large"); + { + std::vector x; + READVECTOR(x); + ils->filename.assign(x.begin(), x.end()); + } + if (io_flags & IO_FLAG_ONDISK_SAME_DIR) { + ils->filename = ondisk_same_dir_filename(f, ils->filename); + } + + const size_t nlist = ils->nlist; + const size_t byte_limit = get_deserialization_vector_byte_limit(); + READVECTOR(ils->sizes); + FAISS_THROW_IF_NOT_FMT( + ils->sizes.size() == nlist, + "RaBitQSSDInvertedLists: %zu list sizes for nlist=%zu", + ils->sizes.size(), + nlist); + for (size_t size : ils->sizes) { + FAISS_THROW_IF_NOT_MSG( + size < byte_limit, "RaBitQSSDInvertedLists: invalid size"); + } + { + std::vector n_extents, flat_extents; + READVECTOR(n_extents); + READVECTOR(flat_extents); + FAISS_THROW_IF_NOT(n_extents.size() == nlist); + ils->extents.resize(nlist); + size_t k = 0; + for (size_t l = 0; l < nlist; l++) { + size_t capacity = 0; + for (size_t j = 0; j < n_extents[l]; j++) { + FAISS_THROW_IF_NOT(k + 2 <= flat_extents.size()); + RaBitQSSDInvertedLists::Extent e{ + flat_extents[k], flat_extents[k + 1]}; + k += 2; + FAISS_THROW_IF_NOT_MSG( + e.first_page <= ils->total_pages && + e.n_pages <= ils->total_pages - e.first_page, + "RaBitQSSDInvertedLists: extent out of the file"); + capacity += e.n_pages; + ils->extents[l].push_back(e); + } + FAISS_THROW_IF_NOT_MSG( + ils->list_pages(l) <= capacity, + "RaBitQSSDInvertedLists: list larger than its extents"); + } + FAISS_THROW_IF_NOT(k == flat_extents.size()); + } + + ils->mem_data.resize(nlist); + for (size_t l = 0; l < nlist; l++) { + const size_t nbytes = mul_no_overflow( + ils->list_batches(l), + ils->batch_bytes, + "RaBitQSSDInvertedLists batches"); + FAISS_THROW_IF_NOT(nbytes < byte_limit); + ils->mem_data[l].resize(nbytes); + if (nbytes > 0) { + READANDCHECK(ils->mem_data[l].get(), nbytes); + } + } + + ils->open_file(); + return ils.release(); +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.h b/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.h new file mode 100644 index 000000000..ab139cb8e --- /dev/null +++ b/thirdparty/faiss/faiss/invlists/RaBitQSSDInvertedLists.h @@ -0,0 +1,224 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace faiss { + +struct DiskIOBackend; + +/** Inverted lists of IndexIVFRaBitQSSD: the RaBitQ code of each vector is + * split between memory and a file on an SSD. + * + * Memory holds each list as batches of 32 vectors. A batch is the sign bits + * of dimensions [0, mem_dim) of its vectors, packed in the FastScan block + * layout, followed by kMemFactors arrays of 32 floats (f_add, f_rescale, + * f_error). + * + * The file holds one fixed-size record per vector: + * + * sign bits of dimensions [mem_dim, d) ((d - mem_dim) / 8 bytes) + * extra-bit code (d * ex_bits / 8 bytes) + * f_add_ex, f_rescale_ex (2 floats) + * id (int64) + * + * The file starts with a kSectorSize-byte header. Records are packed into + * pages of page_size bytes, the smallest multiple of kSectorSize that holds + * one record, and never straddle two pages. The pages of a list are stored + * in a few extents, allocated as the list grows, so the records of a list + * are in add order and a page is one aligned read. + * + * The file is opened with O_DIRECT, so that searches read from the device + * and not from the page cache. Searches read it with libaio, one context per + * search thread. The contexts are kept between searches and destroyed with + * the inverted lists. + * + * The codes are written by IndexIVFRaBitQSSD::add, through append(); the + * generic add_entries / update_entries / get_codes calls are not supported. + * + * read_index supports IO_FLAG_READ_ONLY and IO_FLAG_ONDISK_SAME_DIR; + * IO_FLAG_SKIP_IVF_DATA and IO_FLAG_MMAP are not supported. + */ +struct RaBitQSSDInvertedLists : InvertedLists { + /// alignment and size unit of all file accesses + static constexpr size_t kSectorSize = 4096; + /// vectors per in-memory batch, the FastScan block size + static constexpr size_t kBatchSize = 32; + /// floats stored in memory per vector + static constexpr size_t kMemFactors = 3; + + size_t d = 0; ///< dimensionality + size_t mem_dim = 0; ///< dimensions whose sign bits stay in memory + size_t ex_bits = 0; ///< extra bits per dimension, in the file + + // derived from d, mem_dim and ex_bits by set_derived_values() + size_t batch_bytes = 0; ///< bytes per in-memory batch + size_t record_size = 0; ///< bytes per record in the file + size_t page_size = 0; ///< bytes per page in the file + size_t records_per_page = 0; ///< records per page + + std::string filename; ///< path of the file + int fd = -1; ///< descriptor of filename, opened with O_DIRECT + bool read_only = false; + + /// a run of pages of the file, owned by one list + struct Extent { + size_t first_page; ///< in the file + size_t n_pages; + }; + + std::vector sizes; ///< number of vectors in each list + + /// in-memory batches of each list. The capacity of a table may exceed + /// the bytes in use, batch_bytes per started batch. + std::vector> mem_data; + + /// pages of each list, in list order + std::vector> extents; + + size_t total_pages = 0; ///< pages allocated in the file + uint64_t file_id = 0; ///< random tag, also written to the file header + + /** Create the inverted lists and their file (truncating it). + * + * @param nlist number of lists + * @param d dimensionality, a multiple of 64 + * @param mem_dim dimensions whose sign bits stay in memory, a + * multiple of 64 in [64, d] + * @param ex_bits extra bits per dimension, in [1, 8] + * @param filename path of the file + */ + RaBitQSSDInvertedLists( + size_t nlist, + size_t d, + size_t mem_dim, + size_t ex_bits, + const char* filename); + + /// for the I/O functions + RaBitQSSDInvertedLists(); + + RaBitQSSDInvertedLists(const RaBitQSSDInvertedLists&) = delete; + RaBitQSSDInvertedLists& operator=(const RaBitQSSDInvertedLists&) = delete; + + ~RaBitQSSDInvertedLists() override; + + /// check d, mem_dim and ex_bits, and compute the derived sizes + void set_derived_values(); + + /// number of in-memory batches of a list + size_t list_batches(size_t list_no) const; + + /// pages of the file used by a list + size_t list_pages(size_t list_no) const; + + /// byte offset in the file of page page_no of a list + size_t page_offset(size_t list_no, size_t page_no) const; + + // hidden from SWIG, which does not handle std::unique_ptr well +#ifndef SWIG + /** A libaio context for one search thread, for up to max_events reads + * in flight. Creating and destroying a context takes tens of + * milliseconds, so the contexts are kept for the next searches. + * Thread-safe. + */ + std::unique_ptr acquire_io(int max_events) const; + + /// give back a context of acquire_io(), with no read in flight + void release_io(std::unique_ptr io) const noexcept; +#endif + + /************************* + * InvertedLists interface */ + + size_t list_size(size_t list_no) const override; + + /// not supported: the codes are split between memory and the file + const uint8_t* get_codes(size_t list_no) const override; + + /// read the ids of a list from the file. Release with release_ids. + const idx_t* get_ids(size_t list_no) const override; + + void release_ids(size_t list_no, const idx_t* ids) const override; + + /// read one id from the file + idx_t get_single_id(size_t list_no, size_t offset) const override; + + /// not supported, use IndexIVFRaBitQSSD::add + size_t add_entries( + size_t list_no, + size_t n_entry, + const idx_t* ids, + const uint8_t* code) override; + + /// not supported + void update_entries( + size_t list_no, + size_t offset, + size_t n_entry, + const idx_t* ids, + const uint8_t* code) override; + + /// only new_size == list_size(list_no) is supported + void resize(size_t list_no, size_t new_size) override; + + /// empty all lists, truncate the file to its header and invalidate + /// previously written index files by changing the file identifier + void reset() override; + + /************************* + * split-code interface */ + + /// make room in the file for n_more vectors in a list. append() does it + /// as needed; calling it first with the total count of a batch of + /// appends gives the list a single extent. + void reserve(size_t list_no, size_t n_more); + + /** Append vectors to a list. Not thread-safe for the same list. + * + * @param n number of vectors + * @param mem_codes sign bits of dimensions [0, mem_dim), mem_dim / 8 + * bytes per vector + * @param factors kMemFactors floats per vector + * @param records record_size bytes per vector, in the file format + */ + void append( + size_t list_no, + size_t n, + const uint8_t* mem_codes, + const float* factors, + const uint8_t* records); + + /// open the file of deserialized inverted lists and check its header + void open_file(); + + // opaque, so hidden from SWIG +#ifndef SWIG + /// pool of libaio contexts for the searches and its mutex, and the + /// mutex of total_pages + struct IOState; + IOState* io_state = nullptr; +#endif +}; + +struct RaBitQSSDInvertedListsIOHook : InvertedListsIOHook { + RaBitQSSDInvertedListsIOHook(); + void write(const InvertedLists* ils, IOWriter* f) const override; + InvertedLists* read(IOReader* f, int io_flags) const override; +}; + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/python/CMakeLists.txt b/thirdparty/faiss/faiss/python/CMakeLists.txt index 2c0275606..c0b62911b 100644 --- a/thirdparty/faiss/faiss/python/CMakeLists.txt +++ b/thirdparty/faiss/faiss/python/CMakeLists.txt @@ -38,6 +38,11 @@ macro(configure_swigfaiss source) SWIG_FLAGS -DFAISS_ENABLE_SVS -DFAISS_SVS_RUNTIME_VERSION=${FAISS_SVS_RUNTIME_VERSION} ) endif() + if(FAISS_ENABLE_DISK_IVF) + set_property(SOURCE ${source} APPEND PROPERTY + SWIG_FLAGS -DFAISS_ENABLE_DISK_IVF + ) + endif() if(FAISS_OPT_LEVEL STREQUAL "dd") set_property(SOURCE ${source} APPEND PROPERTY SWIG_FLAGS -DFAISS_ENABLE_DD @@ -217,6 +222,15 @@ if(FAISS_ENABLE_SVS) target_compile_definitions(faiss_example_external_module PRIVATE FAISS_ENABLE_SVS FAISS_SVS_RUNTIME_VERSION=${FAISS_SVS_RUNTIME_VERSION}) endif() +if(FAISS_ENABLE_DISK_IVF) + target_compile_definitions(swigfaiss PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(swigfaiss_avx2 PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(swigfaiss_avx512 PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(swigfaiss_avx512_spr PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(swigfaiss_sve PRIVATE FAISS_ENABLE_DISK_IVF) + target_compile_definitions(faiss_example_external_module PRIVATE FAISS_ENABLE_DISK_IVF) +endif() + # Enable DD support in Python bindings when building with Dynamic Dispatch if(FAISS_OPT_LEVEL STREQUAL "dd") # Add compile definition for the generated C++ wrapper @@ -233,7 +247,7 @@ if(FAISS_ENABLE_GPU) else() find_package(CUDAToolkit REQUIRED) if(FAISS_ENABLE_CUVS AND NOT TARGET cuvs::cuvs) - find_package(cuvs) + find_package(cuvs REQUIRED) endif() target_link_libraries(swigfaiss PRIVATE CUDA::cudart $<$:cuvs::cuvs>) target_link_libraries(swigfaiss_avx2 PRIVATE CUDA::cudart $<$:cuvs::cuvs>) @@ -514,6 +528,11 @@ install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../../contrib/" PATTERN "*_fb.py" EXCLUDE ) +# Install contrib/e_means subpackage documentation +install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/../../contrib/e_means/README.md" + DESTINATION faiss/contrib/e_means +) + # Install contrib/torch subpackage data files install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../../contrib/torch/" DESTINATION faiss/contrib/torch diff --git a/thirdparty/faiss/faiss/python/__init__.py b/thirdparty/faiss/faiss/python/__init__.py index b6f54da9e..b4e04f50c 100644 --- a/thirdparty/faiss/faiss/python/__init__.py +++ b/thirdparty/faiss/faiss/python/__init__.py @@ -121,8 +121,8 @@ def _nvidia_lib_dir(import_name, pip_spec): raise RuntimeError( "faiss-gpu-cuvs installed but the cuVS runtime wheels are " "missing — " - "pip install 'libcuvs-cu13==26.06.*' 'libraft-cu13==26.06.*' " - "'librmm-cu13==26.06.*' " + "pip install 'libcuvs-cu13==26.10.*' " + "'libraft-cu13==26.10.*' 'librmm-cu13==26.10.*' " "--extra-index-url https://pypi.nvidia.com" ) from e @@ -233,6 +233,14 @@ def _nvidia_lib_dir(import_name, pip_spec): if issubclass(the_class, CodePacker): class_wrappers.handle_CodePacker(the_class) +# Dataset and CAGRA are present only in builds with cuVS CAGRA support. +if hasattr(this_module, "Dataset"): + class_wrappers.handle_Dataset(Dataset) + class_wrappers.handle_GpuIndexCagra(GpuIndexCagra) + class_wrappers.handle_GpuIndexCagra(GpuIndexBinaryCagra) + for the_class in (IndexIDMap, IndexIDMap2, IndexBinaryIDMap, IndexBinaryIDMap2): + class_wrappers.handle_IndexIDMapDataset(the_class) + ############################################################################## # For some classes (IndexIVF, IDSelector), the object holds a reference to # a C++ object (eg. the quantizer object of IndexIVF). We don't transfer the @@ -346,6 +354,7 @@ def replacement_function(*args): add_ref_in_constructor(IndexIDMap, 0) add_ref_in_constructor(IndexIDMap2, 0) add_ref_in_constructor(IndexHNSW, 0) +add_ref_in_constructor(IndexPiPNN, {2: [0], 1: [0], 0: []}) add_ref_in_method(IndexShards, "add_shard", 0) add_ref_in_method(IndexBinaryShards, "add_shard", 0) add_ref_in_constructor(IndexRefineFlat, {2: [0], 1: [0]}) @@ -374,6 +383,8 @@ def replacement_function(*args): add_ref_in_constructor(IndexIVFRaBitQ, 0) add_ref_in_constructor(IndexIVFRaBitQFastScan, 0) +if "IndexIVFRaBitQSSD" in globals(): # built with FAISS_ENABLE_DISK_IVF + add_ref_in_constructor(IndexIVFRaBitQSSD, 0) add_ref_in_constructor(IndexIVFEDEN, 0) if "SVS" in get_compile_options(): @@ -430,6 +441,23 @@ def search_with_parameters(index, x, k, params=None, output_stats=False): return distances, labels, stats +search_with_distance_to_code_c = search_with_distance_to_code + + +def search_with_distance_to_code(index, x, k, nprobe=None): + x = np.ascontiguousarray(x, dtype="float32") + n, d = x.shape + assert d == index.d + if nprobe is None: + nprobe = extract_index_ivf(index).nprobe + distances = np.empty((n, k), dtype=np.float32) + labels = np.empty((n, k), dtype=np.int64) + search_with_distance_to_code_c( + index, n, swig_ptr(x), k, swig_ptr(distances), swig_ptr(labels), nprobe + ) + return distances, labels + + range_search_with_parameters_c = range_search_with_parameters diff --git a/thirdparty/faiss/faiss/python/__init__.pyi b/thirdparty/faiss/faiss/python/__init__.pyi index 152349526..5f7b46ab9 100644 --- a/thirdparty/faiss/faiss/python/__init__.pyi +++ b/thirdparty/faiss/faiss/python/__init__.pyi @@ -291,6 +291,12 @@ class SearchParametersPreTransform(SearchParameters): index_params: SearchParameters | None def __init__(self) -> None: ... +class SearchParametersHNSW(SearchParameters): + efSearch: int + check_relative_distance: bool + bounded_queue: bool + def __init__(self) -> None: ... + class SearchParametersSVSVamana(SearchParameters): search_window_size: int search_buffer_capacity: int @@ -301,6 +307,10 @@ class SearchParametersSVSIVF(SearchParameters): k_reorder: float def __init__(self) -> None: ... +class SearchParametersPiPNN(SearchParameters): + search_L: int + def __init__(self) -> None: ... + # Base Index class class Index: d: int # vector dimension @@ -570,11 +580,14 @@ class HadamardRotation(VectorTransform): """Three rounds of random sign-flip + Fast Walsh-Hadamard Transform. Produces a pseudo-random rotation in O(d log d) time. d_out is the smallest power of 2 >= d_in (zero-padded as needed). + With pad_to_power_of_2=False, d_out is the smallest multiple of 64 >= d_in + (four FHT-Kac rounds when d_out is not a power of 2). """ seed: int + pad_to_power_of_2: bool - def __init__(self, d: int, seed: int = 12345) -> None: ... + def __init__(self, d: int, seed: int = 12345, pad_to_power_of_2: bool = True) -> None: ... def init(self, seed: int) -> None: ... class PCAMatrix(LinearTransform): @@ -760,8 +773,15 @@ class IndexFlatIPPanorama(IndexFlatPanorama): self, d: int, n_levels: int, batch_size: int = 512 ) -> None: ... +class VectorTransformVector: + def __init__(self) -> None: ... + def push_back(self, x: VectorTransform) -> None: ... + def clear(self) -> None: ... + def size(self) -> int: ... + def at(self, n: int) -> VectorTransform: ... + class IndexPreTransform(Index): - chain: list[VectorTransform] # std::vector chain + chain: VectorTransformVector # std::vector chain index: Index own_fields: bool @@ -1531,6 +1551,8 @@ class InvertedLists: def list_size(self, list_no: int) -> int: ... def get_codes(self, list_no: int) -> npt.NDArray[np.uint8]: ... def get_ids(self, list_no: int) -> npt.NDArray[np.int64]: ... + def release_codes(self, list_no: int, codes: Any) -> None: ... + def release_ids(self, list_no: int, ids: Any) -> None: ... def add_entries( self, list_no: int, @@ -1672,6 +1694,50 @@ class OnDiskInvertedListsIOHook(InvertedListsIOHook): sizes: list[int], ) -> InvertedLists: ... +# Inverted lists of IndexIVFRaBitQSSD, built with FAISS_ENABLE_DISK_IVF +class RaBitQSSDInvertedLists(InvertedLists): + kSectorSize: int + kBatchSize: int + kMemFactors: int + d: int + mem_dim: int + ex_bits: int + batch_bytes: int + record_size: int + page_size: int + records_per_page: int + filename: str + fd: int + read_only: bool + sizes: UInt64Vector + total_pages: int + file_id: int + + @overload + def __init__( + self, nlist: int, d: int, mem_dim: int, ex_bits: int, filename: str + ) -> None: ... + @overload + def __init__(self) -> None: ... + def set_derived_values(self) -> None: ... + def list_batches(self, list_no: int) -> int: ... + def list_pages(self, list_no: int) -> int: ... + def page_offset(self, list_no: int, page_no: int) -> int: ... + def list_size(self, list_no: int) -> int: ... + def get_ids(self, list_no: int) -> Any: ... + def get_single_id(self, list_no: int, offset: int) -> int: ... + def reset(self) -> None: ... + def reserve(self, list_no: int, n_more: int) -> None: ... + def append( + self, + list_no: int, + n: int, + mem_codes: Any, + factors: Any, + records: Any, + ) -> None: ... + def open_file(self) -> None: ... + class IndexIVF(Index): # Core attributes from C++ struct invlists: InvertedLists | None @@ -1939,6 +2005,23 @@ class HNSWStats: n3: int ndis: int nreorder: int + +class HNSWLevel0LinkParameters: + search_params: SearchParametersHNSW | None + min_mean_factor: float + min_closer_fraction: float + max_links_per_sink: int + max_rounds: int + def __init__(self) -> None: ... + +class HNSWLevel0LinkStats: + n_sinks_found: int + n_sinks_remaining: int + n_links_added: int + n_links_replaced: int + n_rounds: int + n_exact_searches: int + class RaBitQStats: n_1bit: int n_refine: int @@ -1969,6 +2052,7 @@ class IndexHNSW(Index): hnsw: HNSW storage: Index own_fields: bool + level_0_link_samples_per_node: int reconstruct_from_neighbors: Callable[ [int, npt.NDArray[np.float32], npt.NDArray[np.float32]], None ] @@ -1976,6 +2060,14 @@ class IndexHNSW(Index): def __init__( self, d: int, M: int, metric: MetricType = METRIC_L2 ) -> None: ... + def add_level_0_links_from_sample( + self, + x: npt.NDArray[np.float32] | npt.NDArray[np.float16], + *, + params: HNSWLevel0LinkParameters | None = None, + numeric_type: int = ..., + ) -> HNSWLevel0LinkStats: ... + class IndexHNSWFlat(IndexHNSW): def __init__( @@ -2251,8 +2343,16 @@ class IndexBinaryHNSW(IndexBinary): hnsw: Any storage: IndexBinary own_fields: bool + level_0_link_samples_per_node: int def __init__(self, d: int, M: int) -> None: ... + def add_level_0_links_from_sample( + self, + x: npt.NDArray[np.uint8], + *, + params: HNSWLevel0LinkParameters | None = None, + ) -> HNSWLevel0LinkStats: ... + class IndexBinaryHash(IndexBinary): nflip: int @@ -2465,6 +2565,12 @@ def search_with_parameters( tuple[npt.NDArray[np.float32], npt.NDArray[np.int64]] | tuple[npt.NDArray[np.float32], npt.NDArray[np.int64], dict[str, Any]] ): ... +def search_with_distance_to_code( + index: Index, + x: npt.NDArray[np.float32], + k: int, + nprobe: int | None = None, +) -> tuple[npt.NDArray[np.float32], npt.NDArray[np.int64]]: ... @overload def range_search_with_parameters( index: Index, @@ -2500,6 +2606,7 @@ class IVFSearchParameters(SearchParameters): max_lists_num: int ensure_topk_full: bool max_empty_result_buckets: int + sel_after_distance: bool quantizer_params: SearchParameters | None inverted_list_context: Any sel: IDSelector | None @@ -3096,6 +3203,7 @@ class SIMDConfig: level: int supported_simd_levels: int avx512_split: bool + scalar_gather: bool @staticmethod def auto_detect_simd_level() -> int: ... @staticmethod @@ -3114,9 +3222,11 @@ class SIMDConfig: # Utility functions def get_mem_usage_kb() -> int: ... def get_compile_options() -> str: ... +def set_search_stats_enabled(enabled: bool) -> None: ... +def get_search_stats_enabled() -> bool: ... def check_openmp() -> bool: ... def shard_ivf_index_centroids( - index: IndexIVF, + index: IndexIVF | IndexPreTransform, shard_count: int = 20, filename_template: str = "shard.%d.index", sharding_function: ShardingFunction | None = None, @@ -3411,6 +3521,57 @@ class IndexNSGSQ(IndexNSG): def __init__(self, d: int, sq: ScalarQuantizer, R: int) -> None: ... +# IndexPiPNN (PiPNN graph index) +class PiPNN: + R: int + leaf_k: int + hash_bits: int + reservoir_size: int + c_max: int + c_min: int + leader_cap: int + leader_fraction: float + alpha: float + fanout: Int32Vector + seed: int + ip_partition_by_angle: bool + partition_wave_budget: int + search_L: int + graph: MaybeOwnedVectorInt32 + next_copy: MaybeOwnedVectorInt32 + entry_point: int + ntotal: int + + def __init__(self, R: int = 64) -> None: ... + def effective_alpha(self, metric: MetricType) -> float: ... + def check_params(self) -> None: ... + def reset(self) -> None: ... + +class IndexPiPNN(Index): + pipnn: PiPNN + storage: Index + own_fields: bool + defer_build: bool + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, storage: Index, R: int = 64) -> None: ... + def build(self) -> None: ... + def is_built(self) -> bool: ... + @staticmethod + def check_storage_supported(storage: Index) -> None: ... + +class IndexPiPNNFlat(IndexPiPNN): + def __init__( + self, d: int, R: int, metric: MetricType = METRIC_L2 + ) -> None: ... + +class IndexPiPNNSQ(IndexPiPNN): + def __init__( + self, d: int, qtype: int, R: int, metric: MetricType = METRIC_L2 + ) -> None: ... + # IndexNNDescent class IndexNNDescent(Index): nndescent: Any # faiss::nndescent::NNDescent @@ -3426,6 +3587,124 @@ class IndexNNDescentFlat(IndexNNDescent): self, d: int, K: int, metric: MetricType = METRIC_L2 ) -> None: ... +class NNDescentParams: + K: int + R: int + sample: int + + def __init__(self) -> None: ... + def nreverse(self) -> int: ... + def nsample(self) -> int: ... + +class DeterministicNNDescent(NNDescentParams): + ntrees: int + max_rounds: int + delta: float + seed: int + verbose: bool + n: idx_t + d: int + metric_type: MetricType + ids: Int32Vector + dis: Float32Vector + ndis: int + is_new: UInt8Vector + order: Int32Vector + + def __init__(self) -> None: ... + def init(self, storage: Index) -> None: ... + def round(self, storage: Index) -> idx_t: ... + def build(self, storage: Index) -> None: ... + def check_params(self) -> None: ... + +class NNDescentShard(NNDescentParams): + ids: Int64Vector + dis: Float32Vector + remote_ids: Int64Vector + ndis: int + metric_type: MetricType + d: int + rank: int + owner_begin: Int64Vector + x: Any # const float* + is_new: UInt8Vector + reverse_ids: Int64Vector + reverse_new: UInt8Vector + next_ids: Int64Vector + next_dis: Float32Vector + next_new: UInt8Vector + selected_begin: idx_t + selected_end: idx_t + + def __init__(self) -> None: ... + def has_new_member(self, t: idx_t) -> bool: ... + def collect_remote_ids( + self, with_reverse: bool, begin: idx_t, end: idx_t + ) -> None: ... + def set_rows( + self, + K: int, + metric_type: MetricType, + d: int, + rank: int, + world: int, + owner_begin: Any, + x: Any, + ids: Any, + dis: Any, + ) -> None: ... + def nhome(self) -> idx_t: ... + def reverse_edges( + self, + counts: Int64Vector, + target: Int64Vector, + source: Int64Vector, + edge_dis: Float32Vector, + edge_new: UInt8Vector, + ) -> None: ... + def set_reverse_edges( + self, n: int, target: Any, source: Any, edge_dis: Any, edge_new: Any + ) -> None: ... + def select_rows(self, begin: idx_t, end: idx_t) -> None: ... + def remote_counts(self, counts: Int64Vector) -> None: ... + def join( + self, + remote_x: Any, + remote_kth: Any, + counts: Int64Vector, + target: Int64Vector, + candidate: Int64Vector, + candidate_dis: Float32Vector, + ) -> None: ... + def join_fp16( + self, + remote_x: Any, + remote_kth: Any, + counts: Int64Vector, + target: Int64Vector, + candidate: Int64Vector, + candidate_dis: Float32Vector, + ) -> None: ... + def join_sq8( + self, + remote_codes: Any, + vmin: Any, + vdiff: Any, + remote_kth: Any, + counts: Int64Vector, + target: Int64Vector, + candidate: Int64Vector, + candidate_dis: Float32Vector, + ) -> None: ... + def set_remote_ids_of_rows(self) -> None: ... + def original_ids( + self, home_original: Any, remote_original: Any, out: Any + ) -> None: ... + def insert_candidates( + self, n: int, target: Any, candidate: Any, candidate_dis: Any + ) -> None: ... + def end_round(self) -> idx_t: ... + # Index2Layer class Index2Layer(Index): q1: Quantizer @@ -3808,6 +4087,7 @@ class IndexQINCo(IndexNeuralNetCodec): class RaBitQSearchParameters(SearchParameters): qb: int # number of bits to quantize a query with (0 = raw fp32) centered: bool # quantize with zero-centered scalar quantizer + sel_after_distance: bool # test sel after the distance when that saves work def __init__(self) -> None: ... @@ -3844,6 +4124,48 @@ class IndexIVFRaBitQ(IndexIVF): nb_bits: int = 1, ) -> None: ... +# Built with FAISS_ENABLE_DISK_IVF +class IVFRaBitQSSDSearchParameters(IVFSearchParameters): + use_hacc: bool + drain_alpha: float + qd_per_thread: int + + def __init__(self) -> None: ... + +class IndexIVFRaBitQSSD(IndexIVF): + kMaxReadsInFlight: int + rabitq: RaBitQuantizer + mem_dim: int + use_hacc: bool + drain_alpha: float + qd_per_thread: int + centroid_norms: Float32Vector + centroid_scales: Float32Vector + + @overload + def __init__( + self, + quantizer: Index, + d: int, + nlist: int, + mem_dim: int, + nb_bits: int, + metric: MetricType = METRIC_L2, + ) -> None: ... + @overload + def __init__(self) -> None: ... + def attach_file(self, filename: str) -> None: ... + def get_ssd_invlists(self) -> RaBitQSSDInvertedLists: ... + def update_centroid_norms(self) -> None: ... + +class IndexIVFRaBitQSSDStats: + n_pages_read: int # pages read from the file + n_reranked: int # vectors re-ranked with their full code + + def __init__(self) -> None: ... + def reset(self) -> None: ... + def add(self, other: IndexIVFRaBitQSSDStats) -> None: ... + # EDEN indices class IndexEDEN(IndexFlatCodes): sq: ScalarQuantizer @@ -4157,6 +4479,8 @@ class GpuIndexIVF(GpuIndex, IndexIVFInterface): ... class GpuIndexIVFConfig(GpuIndexConfig): """Configuration for GPU IVF indices""" + deterministic_tie_break: bool + def __init__(self) -> None: ... class GpuIndexIVFPQConfig(GpuIndexIVFConfig): @@ -4384,6 +4708,8 @@ class _SwigGlobals: distance_compute_blas_database_bs: int distance_compute_min_k_reservoir: int index_factory_verbose: int + SIMDConfig_scalar_gather: bool + indexIVFRaBitQSSD_stats: IndexIVFRaBitQSSDStats cvar: _SwigGlobals @@ -4520,6 +4846,7 @@ class GpuClonerOptions: verbose: bool use_cuvs: bool allowCpuCoarseQuantizer: bool + deterministic_tie_break: bool def __init__(self) -> None: ... diff --git a/thirdparty/faiss/faiss/python/class_wrappers.py b/thirdparty/faiss/faiss/python/class_wrappers.py index dfe6e3f1a..1ccec468d 100644 --- a/thirdparty/faiss/faiss/python/class_wrappers.py +++ b/thirdparty/faiss/faiss/python/class_wrappers.py @@ -74,6 +74,193 @@ def replace_method(the_class, name, replacement, ignore_missing=False): setattr(the_class, name, replacement) +def handle_Dataset(the_class): + """NumPy adapters for the existing Dataset storage operations.""" + numeric_types = { + np.dtype("float32"): faiss.Float32, + np.dtype("float16"): faiss.Float16, + np.dtype("int8"): faiss.Int8, + np.dtype("uint8"): faiss.UInt8, + } + dtypes = {value: key for key, value in numeric_types.items()} + + def replacement_viewHost(x): + """View a two-dimensional NumPy array without copying it. + + Supports float32, float16, int8 and uint8, with contiguous columns + and a positive row stride. Dimensions and strides are in elements; + binary vectors use uint8 with a dimension in bytes, not bits. + The Dataset retains the array. Keep its contents unchanged while + in use. For caller-managed raw pointers use viewHost_c. + """ + if not isinstance(x, np.ndarray) or x.ndim != 2: + raise TypeError( + "Dataset.viewHost requires a two-dimensional NumPy array" + ) + if x.dtype not in numeric_types: + raise TypeError("Dataset supports float32, float16, int8 and uint8") + n, d = x.shape + if x.size and ( + x.strides[1] != x.itemsize + or x.strides[0] < d * x.itemsize + or x.strides[0] % x.itemsize + ): + raise ValueError( + "Dataset requires contiguous columns and nonoverlapping rows" + ) + stride = x.strides[0] // x.itemsize if x.size else d + result = the_class.viewHost_c( + faiss.cast_integer_to_void_ptr(x.ctypes.data), + n, + d, + numeric_types[x.dtype], + stride, + ) + result.referenced_objects = [x] + return result + + def replacement_view(self): + """Return a non-owning Dataset view that retains its source Dataset.""" + result = self.view_c() + result.referenced_objects = [self] + return result + + def replacement_copyToHost(self): + """Return a packed NumPy copy, waiting for device work to finish. + + The result owns its storage and has the Dataset's logical shape + and dtype. For a caller-supplied raw destination use copyToHost_c. + """ + result = np.empty( + (self.getNumRows(), self.getDim()), + dtype=dtypes[self.getNumericType()], + ) + self.copyToHost_c(swig_ptr(result)) + return result + + the_class.viewHost_c = staticmethod(the_class.viewHost) + the_class.viewHost = staticmethod(replacement_viewHost) + replace_method(the_class, "view", replacement_view) + replace_method(the_class, "copyToHost", replacement_copyToHost) + + +def handle_GpuIndexCagra(the_class): + """Use Dataset build overloads and retain the current Dataset in Python.""" + # Declare this attribute for handle_Index's checked __setattr__. + the_class._dataset = None + + def replacement_train(self, dataset): + """Build the entire graph from a Dataset, borrowing its vector storage. + + Compatible device storage makes the index search ready. Otherwise, + attach populated padded device storage with updateDataset before + searching. The index retains the Dataset until replacement or reset. + """ + if not isinstance(dataset, faiss.Dataset): + raise TypeError( + "CAGRA train requires a Dataset; " + "use Dataset.viewHost or makeDevicePadded" + ) + if self.is_trained: + return + self.train_c(dataset) + self._dataset = dataset + + def replacement_add(self, dataset): + """Build from a Dataset, with the same semantics as train(dataset). + + Incremental additions are unsupported; reset before rebuilding. + """ + if not isinstance(dataset, faiss.Dataset): + raise TypeError( + "CAGRA add requires a Dataset; " + "use Dataset.viewHost or makeDevicePadded" + ) + if self.is_trained: + return + self.add_c(dataset) + self._dataset = dataset + + def replacement_updateDataset(self, dataset): + """Attach populated device storage and retain its Dataset.""" + self.updateDataset_c(dataset) + self._dataset = dataset + + def replacement_copyFrom(self, index, dataset=None): + """Import a CPU graph, optionally filling and retaining a Dataset. + + Without a Dataset, the import is graph-only and not search ready. + """ + self.copyFrom_c(index, dataset) + self._dataset = dataset + + def replacement_reset(self): + """Clear the index and release its reference to the Dataset.""" + self.reset_c() + self._dataset = None + + # handle_Index / handle_IndexBinary already preserved the SWIG methods. + the_class.train = replacement_train + the_class.add = replacement_add + replace_method(the_class, "updateDataset", replacement_updateDataset) + replace_method(the_class, "copyFrom", replacement_copyFrom) + replace_method(the_class, "reset", replacement_reset) + + +def handle_IndexIDMapDataset(the_class): + """Forward Dataset builds and keep storage alive on the wrapped index.""" + original_train = the_class.train + original_add_with_ids = the_class.add_with_ids + the_class._dataset = None + + def dataset_owner(self): + # Constructors retain the original Python child. Cloned IDMaps own + # their C++ child instead, so retain the Dataset on that IDMap. + owner = self + while isinstance(owner, (faiss.IndexIDMap, faiss.IndexBinaryIDMap)): + refs = getattr(owner, "referenced_objects", ()) + if not refs or not isinstance(refs[0], (faiss.Index, faiss.IndexBinary)): + break + owner = refs[0] + return owner + + def replacement_train(self, x, *args, **kwargs): + if not isinstance(x, faiss.Dataset): + return original_train(self, x, *args, **kwargs) + if args or kwargs: + raise TypeError("Dataset training takes no additional arguments") + owner = dataset_owner(self) + was_trained = owner.is_trained + self.train_dataset(x) + if not was_trained: + owner._dataset = x + + def replacement_add_with_ids(self, x, ids, *args, **kwargs): + if not isinstance(x, faiss.Dataset): + return original_add_with_ids(self, x, ids, *args, **kwargs) + if args or kwargs: + raise TypeError("Dataset addition takes no additional arguments") + owner = dataset_owner(self) + was_trained = owner.is_trained + n = self.index.ntotal - self.ntotal if was_trained else x.getNumRows() + ids = np.ascontiguousarray(ids, dtype="int64") + if ids.shape != (n,): + raise ValueError("expected one ID for each unmapped vector") + self.add_with_ids_c(x, swig_ptr(ids)) + if not was_trained: + owner._dataset = x + + def replacement_reset(self): + owner = dataset_owner(self) + self.reset_c() + if hasattr(owner, "_dataset"): + owner._dataset = None + + the_class.train = replacement_train + the_class.add_with_ids = replacement_add_with_ids + replace_method(the_class, "reset", replacement_reset) + + def handle_Clustering(the_class): def replacement_train(self, x, index, weights=None): @@ -141,18 +328,23 @@ def replacement_train_encoded(self, x, codec, index, weights=None): def handle_SuperKMeans(the_class): - def replacement_train(self, x): + def replacement_train(self, x, *, numeric_type=faiss.Float32): """Perform SuperKMeans clustering on a set of vectors. Parameters ---------- x : array_like - Training vectors, shape (n, self.d). `dtype` must be float32. + Training vectors, shape (n, self.d). + numeric_type : faiss.NumericType, optional + Numeric type of the input vectors. """ n, d = x.shape assert d == self.d - x = np.ascontiguousarray(x, dtype="float32") - self.train_c(n, swig_ptr(x)) + x = np.ascontiguousarray(x, dtype=_numeric_to_str(numeric_type)) + if numeric_type == faiss.Float32: + self.train_c(n, swig_ptr(x)) + else: + self.train_ex(n, swig_ptr(x), numeric_type) replace_method(the_class, "train", replacement_train) @@ -960,6 +1152,21 @@ def replacement_permute_entries(self, perm): perm = np.ascontiguousarray(perm, dtype="int64") self.permute_entries_c(faiss.swig_ptr(perm)) + def replacement_add_level_0_links_from_sample( + self, x, *, params=None, numeric_type=faiss.Float32 + ): + """Adds level-0 links so that the HNSW search no longer stops at + sinks. See IndexHNSW::add_level_0_links_from_sample. + """ + n, d = x.shape + assert d == self.d + x = np.ascontiguousarray(x, dtype=_numeric_to_str(numeric_type)) + if params is None: + params = faiss.HNSWLevel0LinkParameters() + return self.add_level_0_links_from_sample_ex( + n, swig_ptr(x), numeric_type, params + ) + replace_method(the_class, "add", replacement_add) replace_method(the_class, "add_with_ids", replacement_add_with_ids) replace_method(the_class, "assign", replacement_assign) @@ -1013,6 +1220,12 @@ def replacement_permute_entries(self, perm): replacement_permute_entries, ignore_missing=True, ) + replace_method( + the_class, + "add_level_0_links_from_sample", + replacement_add_level_0_links_from_sample, + ignore_missing=True, + ) # Store the original __setattr__ method original_setattr = ( @@ -1078,6 +1291,17 @@ def replacement_reconstruct_n(self, n0=0, ni=-1, x=None): self.reconstruct_n_c(n0, ni, swig_ptr(x)) return x + def replacement_add_level_0_links_from_sample(self, x, *, params=None): + """Adds level-0 links so that the HNSW search no longer stops at + sinks. See IndexBinaryHNSW::add_level_0_links_from_sample. + """ + n, d = x.shape + x = _check_dtype_uint8(x) + assert d == self.code_size + if params is None: + params = faiss.HNSWLevel0LinkParameters() + return self.add_level_0_links_from_sample_c(n, swig_ptr(x), params) + def replacement_search(self, x, k, *, params=None): x = _check_dtype_uint8(x) n, d = x.shape @@ -1225,6 +1449,12 @@ def replacement_assign(self, x, k, labels=None): replacement_range_search_preassigned, ignore_missing=True, ) + replace_method( + the_class, + "add_level_0_links_from_sample", + replacement_add_level_0_links_from_sample, + ignore_missing=True, + ) def handle_VectorTransform(the_class): diff --git a/thirdparty/faiss/faiss/python/extra_wrappers.py b/thirdparty/faiss/faiss/python/extra_wrappers.py index 8ffdc99f1..a965ca7d6 100644 --- a/thirdparty/faiss/faiss/python/extra_wrappers.py +++ b/thirdparty/faiss/faiss/python/extra_wrappers.py @@ -564,7 +564,11 @@ def set_index(self): self.index, ngpu=self.gpu ) else: + self.index = IndexFlatL2(d) if self.gpu: + self.index = faiss.index_cpu_to_all_gpus( + self.index, ngpu=self.gpu + ) fac = GpuProgressiveDimIndexFactory(ngpu=self.gpu) else: fac = ProgressiveDimIndexFactory() @@ -726,7 +730,7 @@ def pack_bitstrings(a, nbit): """ n, M = a.shape a = np.ascontiguousarray(a, dtype="int32") - if is_sequence(nbit): + if is_sequence(nbit) or isinstance(nbit, np.ndarray): nbit = np.ascontiguousarray(nbit, dtype="int32") assert nbit.shape == (M,) code_size = int((nbit.sum() + 7) // 8) diff --git a/thirdparty/faiss/faiss/python/gpu_wrappers.py b/thirdparty/faiss/faiss/python/gpu_wrappers.py index c8a2e0a8f..390e862f7 100644 --- a/thirdparty/faiss/faiss/python/gpu_wrappers.py +++ b/thirdparty/faiss/faiss/python/gpu_wrappers.py @@ -49,6 +49,14 @@ def index_cpu_to_gpus_list(index, co=None, gpus=None, ngpu=-1): gpus = range(get_num_gpus()) elif (gpus is None) and (ngpu != -1): # Get number of GPU's only gpus = range(ngpu) + if "GpuResourcesVector" not in globals(): + # The Metal backend has a single device and no multi-device cloner, + # so co (sharding, replicas) does not apply. + if len(gpus) != 1: + raise ValueError( + f"this build supports exactly one GPU, got {len(gpus)}" + ) + return index_cpu_to_gpu(StandardGpuResources(), gpus[0], index) res = [StandardGpuResources() for _ in gpus] index_gpu = index_cpu_to_gpu_multiple_py(res, index, co, gpus) return index_gpu diff --git a/thirdparty/faiss/faiss/python/setup.py b/thirdparty/faiss/faiss/python/setup.py index 5f8b4305e..788f64e69 100644 --- a/thirdparty/faiss/faiss/python/setup.py +++ b/thirdparty/faiss/faiss/python/setup.py @@ -22,6 +22,16 @@ shutil.copyfile("extra_wrappers.py", "faiss/extra_wrappers.py") shutil.copyfile("array_conversions.py", "faiss/array_conversions.py") +# setup.py runs either beside staged build inputs or in the CMake Python +# build directory, whose sibling gpu_metal directory contains the shaders. +for metallib in ( + "MetalDistance.metallib", + "../gpu_metal/MetalDistance.metallib", +): + if os.path.exists(metallib): + shutil.copyfile(metallib, "faiss/MetalDistance.metallib") + break + if os.path.exists("__init__.pyi"): shutil.copyfile("__init__.pyi", "faiss/__init__.pyi") if os.path.exists("py.typed"): @@ -119,7 +129,7 @@ """ setup( name="faiss", - version="1.15.1", + version="1.16.0", description=( "A library for efficient similarity search and clustering of dense " "vectors" @@ -132,9 +142,10 @@ license="MIT", keywords="search nearest neighbors", install_requires=["numpy", "packaging"], - packages=["faiss", "faiss.contrib", "faiss.contrib.torch"], + packages=["faiss", "faiss.contrib", "faiss.contrib.torch", "faiss.contrib.e_means"], package_data={ - "faiss": ["*.so", "*.pyd", "*.a", "*.pyi", "py.typed"], + "faiss": ["*.so", "*.pyd", "*.a", "*.metallib", "*.pyi", "py.typed"], + "faiss.contrib.e_means": ["README.md"], }, zip_safe=False, ) diff --git a/thirdparty/faiss/faiss/python/swigfaiss.swig b/thirdparty/faiss/faiss/python/swigfaiss.swig index f43a29122..219ce7af7 100644 --- a/thirdparty/faiss/faiss/python/swigfaiss.swig +++ b/thirdparty/faiss/faiss/python/swigfaiss.swig @@ -130,11 +130,15 @@ typedef uint64_t size_t; #include #include +#include #include #include #include +#include +#include + #include #include #include @@ -189,6 +193,11 @@ typedef uint64_t size_t; #include #endif // !_MSC_VER +#ifdef FAISS_ENABLE_DISK_IVF +#include +#include +#endif // FAISS_ENABLE_DISK_IVF + #include #include #include @@ -439,20 +448,19 @@ int64_t cast_cudastream_t_to_integer(hipStream_t x) { #else // FAISS_ENABLE_ROCM -// CAGRA is absent from the aarch64 cuVS build (cuvs-ivfpq subset), so gate the -// CAGRA bindings on FAISS_CUVS_NO_CAGRA too, else the wrapper references -// undefined GpuIndexCagra symbols when linked against the aarch64 faiss_cuvs. -#if defined(FAISS_ENABLE_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#ifdef FAISS_ENABLE_CUVS %shared_ptr(faiss::gpu::IVFPQBuildCagraConfig); %shared_ptr(faiss::gpu::IVFPQSearchCagraConfig); %{ +#include #include #include +#include %} -#endif // FAISS_ENABLE_CUVS && !FAISS_CUVS_NO_CAGRA +#endif // FAISS_ENABLE_CUVS typedef CUstream_st* cudaStream_t; @@ -505,6 +513,8 @@ void gpu_sync_all_devices() %newobject faiss::gpu_metal::index_cpu_to_gpu; %newobject faiss::gpu_metal::index_gpu_to_cpu; +%newobject faiss::gpu_metal::index_binary_cpu_to_gpu; +%newobject faiss::gpu_metal::index_binary_gpu_to_cpu; %include @@ -620,6 +630,7 @@ void gpu_sync_all_devices() %ignore faiss::nndescent::Nhood::lock; %include +%include %include // IndexIVFFlatDedup::instances is a std::unordered_multimap which SWIG has no @@ -643,6 +654,9 @@ void gpu_sync_all_devices() %include +%include +%include + #ifndef SWIGWIN %warnfilter(401) faiss::OnDiskInvertedListsIOHook; %ignore OnDiskInvertedListsIOHook; @@ -737,6 +751,13 @@ void gpu_sync_all_devices() %include %include +#ifdef FAISS_ENABLE_DISK_IVF +%warnfilter(401) faiss::RaBitQSSDInvertedListsIOHook; +%ignore RaBitQSSDInvertedListsIOHook; +%include +%include +#endif // FAISS_ENABLE_DISK_IVF + %ignore faiss::BufferList::Buffer; %ignore faiss::RangeSearchPartialResult::QueryResult; %ignore faiss::IDSelectorBatch::set; @@ -779,7 +800,7 @@ void gpu_sync_all_devices() %include %include %include -#if defined(FAISS_ENABLE_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#ifdef FAISS_ENABLE_CUVS // IVFPQSearchCagraConfig.lut_dtype and .internal_distance_dtype are typed as // cudaDataType_t (a C enum from ). Without an int typemap // SWIG generates accessors that read/write a cudaDataType_t* SwigPyObject, @@ -799,6 +820,35 @@ typedef int cudaDataType_t; %constant int CUDA_R_16F = 2; %constant int CUDA_R_8I = 3; %constant int CUDA_R_8U = 8; +// Dataset factories return move-only descriptors by value. Python owns the +// returned descriptor; the Dataset itself determines ownership of its storage. +%{ +// SWIG < 4.1 has a copy-only SwigValueWrapper. Dataset is move-only. +#if SWIG_VERSION < 0x040100 +template <> +class SwigValueWrapper { + std::unique_ptr value_; + +public: + SwigValueWrapper& operator=(faiss::gpu::Dataset&& value) { + value_.reset(new faiss::gpu::Dataset(std::move(value))); + return *this; + } + operator faiss::gpu::Dataset&&() const { + return std::move(*value_); + } +}; +#endif +%} +%ignore faiss::gpu::Dataset::Dataset; +%ignore faiss::gpu::Dataset::operator=; +%feature("valuewrapper") faiss::gpu::Dataset; +%typemap(out) faiss::gpu::Dataset { + $result = SWIG_NewPointerObj( + new faiss::gpu::Dataset(std::move($1)), + $descriptor(faiss::gpu::Dataset *), SWIG_POINTER_OWN); +} +%include %include %include #endif @@ -868,6 +918,9 @@ typedef int cudaDataType_t; DOWNCAST ( IndexRaBitQ ) DOWNCAST ( IndexIVFRaBitQ ) DOWNCAST ( IndexIVFRaBitQFastScan ) +#ifdef FAISS_ENABLE_DISK_IVF + DOWNCAST ( IndexIVFRaBitQSSD ) +#endif // FAISS_ENABLE_DISK_IVF DOWNCAST ( IndexIVFIndependentQuantizer) DOWNCAST ( IndexIVFPQR ) DOWNCAST ( IndexIVFPQ ) @@ -926,6 +979,9 @@ typedef int cudaDataType_t; DOWNCAST ( IndexNSGFlat ) DOWNCAST ( IndexNSGPQ ) DOWNCAST ( IndexNSGSQ ) + DOWNCAST ( IndexPiPNNFlat ) + DOWNCAST ( IndexPiPNNSQ ) + DOWNCAST ( IndexPiPNN ) DOWNCAST ( Index2Layer ) DOWNCAST ( IndexRandom ) DOWNCAST ( IndexRowwiseMinMax ) @@ -940,9 +996,8 @@ typedef int cudaDataType_t; DOWNCAST ( IndexSVSIVF ) #endif // FAISS_ENABLE_SVS #ifdef GPU_WRAPPER -#if defined(FAISS_ENABLE_CUVS) && !defined(FAISS_CUVS_NO_CAGRA) +#ifdef FAISS_ENABLE_CUVS DOWNCAST_GPU ( GpuIndexCagra ) - DOWNCAST_GPU ( GpuIndexBinaryCagra ) #endif DOWNCAST_GPU ( GpuIndexIVFPQ ) DOWNCAST_GPU ( GpuIndexIVFFlat ) @@ -974,6 +1029,9 @@ typedef int cudaDataType_t; DOWNCAST ( IndexBinaryHash ) DOWNCAST ( IndexBinaryMultiHash ) #ifdef GPU_WRAPPER +#ifdef FAISS_ENABLE_CUVS + DOWNCAST_GPU ( GpuIndexBinaryCagra ) +#endif DOWNCAST_GPU ( GpuIndexBinaryFlat ) #endif // default for non-recognized classes @@ -1012,6 +1070,9 @@ typedef int cudaDataType_t; #ifndef SWIGWIN DOWNCAST (OnDiskInvertedLists) #endif // !SWIGWIN +#ifdef FAISS_ENABLE_DISK_IVF + DOWNCAST (RaBitQSSDInvertedLists) +#endif // FAISS_ENABLE_DISK_IVF DOWNCAST (VStackInvertedLists) DOWNCAST (HStackInvertedLists) DOWNCAST (SliceInvertedLists) @@ -1090,6 +1151,7 @@ faiss::Quantizer * downcast_Quantizer (faiss::Quantizer *aq) %newobject index_gpu_to_cpu; %newobject index_cpu_to_gpu; +%newobject index_binary_cpu_to_gpu; %newobject index_cpu_to_gpu_multiple; %include diff --git a/thirdparty/faiss/faiss/svs/IndexSVSFaissUtils.h b/thirdparty/faiss/faiss/svs/IndexSVSFaissUtils.h index ae64e7c64..c52be117a 100644 --- a/thirdparty/faiss/faiss/svs/IndexSVSFaissUtils.h +++ b/thirdparty/faiss/faiss/svs/IndexSVSFaissUtils.h @@ -66,7 +66,6 @@ struct FaissIDFilter : public svs_runtime::IDFilter { return selector.is_member(static_cast(id)); } - private: const faiss::IDSelector& selector; }; @@ -104,7 +103,6 @@ struct InputBufferConverter { return buffer; } - private: std::vector buffer; }; @@ -134,7 +132,6 @@ struct InputBufferConverter< reinterpret_cast(data_span.data()), data_span.size()); } - private: std::span data_span; }; @@ -162,7 +159,6 @@ struct OutputBufferConverter { return buffer; } - private: std::span data_span; std::vector buffer; }; @@ -186,7 +182,6 @@ struct OutputBufferConverter< reinterpret_cast(data_span.data()), data_span.size()); } - private: std::span data_span; }; @@ -220,7 +215,8 @@ auto convert_output_buffer(U* data, size_t size) { } struct FaissResultsAllocator : public svs_runtime::ResultsAllocator { - FaissResultsAllocator(faiss::RangeSearchResult* result) : result(result) { + FaissResultsAllocator(faiss::RangeSearchResult* result_in) + : result(result_in) { FAISS_ASSERT(result != nullptr); } @@ -244,7 +240,6 @@ struct FaissResultsAllocator : public svs_runtime::ResultsAllocator { result->distances, result->lims[result_counts.size()])}; } - private: faiss::RangeSearchResult* result; using LabelsConverter = OutputBufferConverter; mutable LabelsConverter labels_converter; diff --git a/thirdparty/faiss/faiss/svs/IndexSVSFlat.cpp b/thirdparty/faiss/faiss/svs/IndexSVSFlat.cpp index 50cead8b9..b1fe09a70 100644 --- a/thirdparty/faiss/faiss/svs/IndexSVSFlat.cpp +++ b/thirdparty/faiss/faiss/svs/IndexSVSFlat.cpp @@ -75,7 +75,7 @@ void IndexSVSFlat::search( idx_t k, float* distances, idx_t* labels, - const SearchParameters* params) const { + const SearchParameters* /* params */) const { FAISS_THROW_IF_NOT(impl); auto status = impl->search( n, diff --git a/thirdparty/faiss/faiss/svs/IndexSVSIVF.cpp b/thirdparty/faiss/faiss/svs/IndexSVSIVF.cpp index a1217f279..77787fe10 100644 --- a/thirdparty/faiss/faiss/svs/IndexSVSIVF.cpp +++ b/thirdparty/faiss/faiss/svs/IndexSVSIVF.cpp @@ -66,10 +66,10 @@ IndexSVSIVF::IndexSVSIVF( size_t nlist, MetricType metric, SVSStorageKind storage, - bool is_static) + bool is_static_in) : Index(d, metric), num_centroids{nlist}, - is_static{is_static}, + is_static{is_static_in}, storage_kind{storage} { is_trained = false; diff --git a/thirdparty/faiss/faiss/svs/IndexSVSVamana.cpp b/thirdparty/faiss/faiss/svs/IndexSVSVamana.cpp index 35adee393..8068dbacc 100644 --- a/thirdparty/faiss/faiss/svs/IndexSVSVamana.cpp +++ b/thirdparty/faiss/faiss/svs/IndexSVSVamana.cpp @@ -67,13 +67,13 @@ IndexSVSVamana::IndexSVSVamana( size_t degree, MetricType metric, SVSStorageKind storage, - bool is_static, - bool store_vectors) + bool is_static_in, + bool store_vectors_in) : Index(d, metric), graph_max_degree{degree}, - is_static{is_static}, + is_static{is_static_in}, storage_kind{storage}, - store_vectors{store_vectors} { + store_vectors{store_vectors_in} { prune_to = graph_max_degree < 4 ? graph_max_degree : graph_max_degree - 4; alpha = metric == METRIC_L2 ? 1.2f : 0.95f; diff --git a/thirdparty/faiss/faiss/svs/IndexSVSVamana.h b/thirdparty/faiss/faiss/svs/IndexSVSVamana.h index fbaaeb042..88acc4b3c 100644 --- a/thirdparty/faiss/faiss/svs/IndexSVSVamana.h +++ b/thirdparty/faiss/faiss/svs/IndexSVSVamana.h @@ -90,8 +90,9 @@ inline svs_runtime::StorageKind to_svs_storage_kind(SVSStorageKind kind) { } struct IndexSVSVamana : Index { - size_t graph_max_degree; - size_t prune_to; + // Same defaults as IndexSVSVamana(d, /*degree=*/64). + size_t graph_max_degree = 64; + size_t prune_to = 60; float alpha = 1.2; size_t search_window_size = 10; size_t search_buffer_capacity = 10; diff --git a/thirdparty/faiss/faiss/utils/AlignedTable.h b/thirdparty/faiss/faiss/utils/AlignedTable.h index db2dd66d1..d0e2d8073 100644 --- a/thirdparty/faiss/faiss/utils/AlignedTable.h +++ b/thirdparty/faiss/faiss/utils/AlignedTable.h @@ -117,6 +117,8 @@ template struct AlignedTable { AlignedTableTightAlloc tab; size_t numel = 0; + // If true, resize() reallocates only when n is larger than the capacity. + bool keep_capacity = false; static size_t round_capacity(size_t n) { if (n == 0) { @@ -141,7 +143,10 @@ struct AlignedTable { } void resize(size_t n) { - tab.resize(round_capacity(n)); + const size_t capacity = round_capacity(n); + if (!keep_capacity || capacity > tab.numel) { + tab.resize(capacity); + } numel = n; } diff --git a/thirdparty/faiss/faiss/utils/Heap.cpp b/thirdparty/faiss/faiss/utils/Heap.cpp index 3b126256c..a94c03041 100644 --- a/thirdparty/faiss/faiss/utils/Heap.cpp +++ b/thirdparty/faiss/faiss/utils/Heap.cpp @@ -194,10 +194,11 @@ void merge_knn_results( const idx_t* I_in = all_labels + i * k; int heap_size = 0; - // push the first element of each shard (if not -1) + // push the first element of each shard (if not -1). A caller id + // may be negative, so only -1 marks a missing result. for (long s = 0; s < static_cast(nshard); s++) { pointer[s] = 0; - if (I_in[stride * s] >= 0) { + if (I_in[stride * s] != -1) { heap_push( ++heap_size, heap_vals, @@ -221,7 +222,7 @@ void merge_knn_results( // pop from shard, advance pointer for this shard heap_pop(heap_size--, heap_vals, shard_ids); p++; - if (static_cast(p) < k && I_in[stride * s + p] >= 0) { + if (static_cast(p) < k && I_in[stride * s + p] != -1) { heap_push( ++heap_size, heap_vals, diff --git a/thirdparty/faiss/faiss/utils/WorkerThread.h b/thirdparty/faiss/faiss/utils/WorkerThread.h index 78d7505d5..fd35c42f2 100644 --- a/thirdparty/faiss/faiss/utils/WorkerThread.h +++ b/thirdparty/faiss/faiss/utils/WorkerThread.h @@ -37,7 +37,6 @@ class WorkerThread { /// exiting or has exited. std::future add(std::function f); - private: void startThread(); void threadMain(); void threadLoop(); diff --git a/thirdparty/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h b/thirdparty/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h index f10669d24..ee5848de4 100644 --- a/thirdparty/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h +++ b/thirdparty/faiss/faiss/utils/approx_topk_hamming/approx_topk_hamming.h @@ -21,19 +21,30 @@ using simd8uint32 = simd8uint32_tpl; using simd16uint16 = simd16uint16_tpl; // HeapWithBucketsForHamming32 uses simd8uint32 under the -// hood. - -template +// hood. SL is the SIMD level of the file that uses it, so each level compiles +// its own copy under its own name. + +template < + typename C, + uint32_t NBUCKETS, + uint32_t N, + typename HammingComputerT, + SIMDLevel SL> struct HeapWithBucketsForHamming32 { // this case was not implemented yet. }; -template +template < + uint32_t NBUCKETS, + uint32_t N, + typename HammingComputerT, + SIMDLevel SL> struct HeapWithBucketsForHamming32< CMax, NBUCKETS, N, - HammingComputerT> { + HammingComputerT, + SL> { static constexpr uint32_t NBUCKETS_8 = NBUCKETS / 8; static_assert( (NBUCKETS) > 0 && ((NBUCKETS % 8) == 0), diff --git a/thirdparty/faiss/faiss/utils/bf16.h b/thirdparty/faiss/faiss/utils/bf16.h index 454628004..1ebc24f8a 100644 --- a/thirdparty/faiss/faiss/utils/bf16.h +++ b/thirdparty/faiss/faiss/utils/bf16.h @@ -14,6 +14,10 @@ #include #endif +#if defined(__riscv_vector) +#include +#endif + namespace faiss { namespace { @@ -38,6 +42,8 @@ inline float decode_bf16(const uint16_t v) { return fp.as_f32; } +namespace { + inline void encode_bf16_simd(const float* src, uint16_t* dst, size_t n) { size_t i = 0; #ifdef __AVX512BF16__ @@ -61,10 +67,40 @@ inline void decode_bf16_simd(const uint16_t* src, float* dst, size_t n) { w = _mm512_slli_epi32(w, 16); _mm512_storeu_ps(dst + i, _mm512_castsi512_ps(w)); } +#elif defined(__riscv_vector) + if (n == 1) { + dst[0] = decode_bf16(src[0]); + return; + } + if (n < 16) { + for (; i < n; ++i) { + dst[i] = decode_bf16(src[i]); + } + return; + } + const size_t vlmax = __riscv_vsetvlmax_e16m1(); + for (; i + vlmax <= n; i += vlmax) { + vuint16m1_t v = __riscv_vle16_v_u16m1(src + i, vlmax); + vuint32m2_t w = __riscv_vzext_vf2_u32m2(v, vlmax); + w = __riscv_vsll_vx_u32m2(w, 16, vlmax); + __riscv_vse32_v_f32m2( + dst + i, __riscv_vreinterpret_v_u32m2_f32m2(w), vlmax); + } + if (i < n) { + const size_t vl = __riscv_vsetvl_e16m1(n - i); + vuint16m1_t v = __riscv_vle16_v_u16m1(src + i, vl); + vuint32m2_t w = __riscv_vzext_vf2_u32m2(v, vl); + w = __riscv_vsll_vx_u32m2(w, 16, vl); + __riscv_vse32_v_f32m2( + dst + i, __riscv_vreinterpret_v_u32m2_f32m2(w), vl); + i += vl; + } #endif for (; i < n; i++) { dst[i] = decode_bf16(src[i]); } } +} // namespace + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/distances.cpp b/thirdparty/faiss/faiss/utils/distances.cpp index 2702b8ffc..4f420224d 100644 --- a/thirdparty/faiss/faiss/utils/distances.cpp +++ b/thirdparty/faiss/faiss/utils/distances.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -26,6 +27,7 @@ #include #include #include +#include #ifndef FINTEGER #define FINTEGER long @@ -361,10 +363,11 @@ void exhaustive_L2sqr_seq( } } -/** Find the nearest neighbors for nx queries in a set of ny vectors */ -template -void exhaustive_inner_product_blas( - const float* x, +/** Find the nearest neighbors for nx queries (see Fp32QueryTiles) in a set + * of ny vectors */ +template +void exhaustive_inner_product_blas_tiles( + QueryTiles& queries, const float* y, size_t d, size_t nx, @@ -386,6 +389,8 @@ void exhaustive_inner_product_blas( i1 = nx; } + const float* xt = queries.tile(i0, i1, nullptr); + res.begin_multiple(i0, i1); for (size_t j0 = 0; j0 < ny; j0 += bs_y) { @@ -405,7 +410,7 @@ void exhaustive_inner_product_blas( &one, y + j0 * d, &di, - x + i0 * d, + xt, &di, &zero, ip_block.get(), @@ -421,9 +426,9 @@ void exhaustive_inner_product_blas( // distance correction is an operator that can be applied to transform // the distances -template -void exhaustive_L2sqr_blas_default_impl( - const float* x, +template +void exhaustive_L2sqr_blas_tiles( + QueryTiles& queries, const float* y, size_t d, size_t nx, @@ -438,12 +443,15 @@ void exhaustive_L2sqr_blas_default_impl( /* block sizes */ const size_t bs_x = distance_compute_blas_query_bs; const size_t bs_y = distance_compute_blas_database_bs; + [[maybe_unused]] constexpr bool parallel_distances = std::is_same_v< + BlockResultHandler, + Top2BlockResultHandler>>; // const size_t bs_x = 16, bs_y = 16; std::unique_ptr ip_block(new float[bs_x * bs_y]); std::unique_ptr x_norms(new float[nx]); std::unique_ptr del2; - fvec_norms_L2sqr(x_norms.get(), x, d, nx); + queries.prepare_norms(nx, x_norms.get()); if (!y_norms) { float* y_norms2 = new float[ny]; @@ -458,6 +466,8 @@ void exhaustive_L2sqr_blas_default_impl( i1 = nx; } + const float* xt = queries.tile(i0, i1, x_norms.get()); + res.begin_multiple(i0, i1); for (size_t j0 = 0; j0 < ny; j0 += bs_y) { @@ -477,13 +487,15 @@ void exhaustive_L2sqr_blas_default_impl( &one, y + j0 * d, &di, - x + i0 * d, + xt, &di, &zero, ip_block.get(), &nyi); } - for (size_t i = i0; i < i1; i++) { + // The top-2 handler is too cheap to hide this pass: share it. +#pragma omp parallel for if (parallel_distances && i1 - i0 >= 16) + for (int64_t i = i0; i < static_cast(i1); i++) { float* ip_line = ip_block.get() + (i - i0) * (j1 - j0); for (size_t j = j0; j < j1; j++) { @@ -510,6 +522,31 @@ void exhaustive_L2sqr_blas_default_impl( } } +template +void exhaustive_inner_product_blas( + const float* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + BlockResultHandler& res) { + Fp32QueryTiles queries{x, d}; + exhaustive_inner_product_blas_tiles(queries, y, d, nx, ny, res); +} + +template +void exhaustive_L2sqr_blas_default_impl( + const float* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + BlockResultHandler& res, + const float* y_norms = nullptr) { + Fp32QueryTiles queries{x, d}; + exhaustive_L2sqr_blas_tiles(queries, y, d, nx, ny, res, y_norms); +} + template void exhaustive_L2sqr_blas( const float* x, @@ -556,6 +593,44 @@ void exhaustive_L2sqr_blas>>( }); } +/// exhaustive_L2sqr_blas for packed IEEE binary16 queries +template +void exhaustive_L2sqr_blas_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + BlockResultHandler& res, + const float* y_norms) { + Fp16QueryTiles queries(x, d, nx); + exhaustive_L2sqr_blas_tiles(queries, y, d, nx, ny, res, y_norms); +} + +template <> +void exhaustive_L2sqr_blas_fp16>>( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + with_selected_simd_levels( + [&]() { + if constexpr ( + SL == SIMDLevel::AVX2 || SL == SIMDLevel::AVX512 || + SL == SIMDLevel::ARM_SVE) { + exhaustive_L2sqr_blas_cmax_fp16( + x, y, d, nx, ny, res, y_norms); + } else { + Fp16QueryTiles queries(x, d, nx); + exhaustive_L2sqr_blas_tiles( + queries, y, d, nx, ny, res, y_norms); + } + }); +} + struct Run_search_inner_product { using T = void; template @@ -598,6 +673,35 @@ struct Run_search_L2sqr { } }; +// fp16 consumers only run the BLAS kernels, see use_fp16_blas_kernels +struct Run_search_inner_product_fp16 { + using T = void; + template + void f(BlockResultHandler& res, + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny) { + Fp16QueryTiles queries(x, d, nx); + exhaustive_inner_product_blas_tiles(queries, y, d, nx, ny, res); + } +}; + +struct Run_search_L2sqr_fp16 { + using T = void; + template + void f(BlockResultHandler& res, + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + const float* y_norm2) { + exhaustive_L2sqr_blas_fp16(x, y, d, nx, ny, res, y_norm2); + } +}; + } // anonymous namespace /******************************************************* @@ -610,8 +714,21 @@ int distance_compute_blas_database_bs = 1024; int distance_compute_min_k_reservoir = 100; // Database-parallel KNN: parallelizes over database segments instead of -// queries, for the case where nx < nthreads and the database is large. +// queries, for a large database and as many queries as its buffers allow. static constexpr size_t kDbParallelMinVectors = 10000; +// Bound on its per-thread result heaps and inner-product blocks when +// nx >= nthreads. +static constexpr size_t kDbParallelMaxBytes = size_t(256) << 20; +// Inner-product block of one thread, in floats. +static constexpr size_t kDbParallelBlockFloats = size_t(1) << 16; + +// Database vectors per inner-product block: fewer for more queries, so that +// the block stays near kDbParallelBlockFloats. +static size_t db_parallel_block(size_t nx) { + return std::min( + distance_compute_blas_database_bs, + std::max(32, kDbParallelBlockFloats / nx)); +} template static void knn_db_parallel_impl( @@ -628,9 +745,9 @@ static void knn_db_parallel_impl( using TI = typename C::TI; int nt = omp_get_max_threads(); - const size_t bs_y = distance_compute_blas_database_bs; + const size_t bs_y = db_parallel_block(nx); - // Per-thread result heaps: nt threads x nx queries x k results + // Result heaps: nt segments x nx queries x k results std::vector all_dis(static_cast(nt) * nx * k); std::vector all_ids(static_cast(nt) * nx * k); @@ -649,9 +766,8 @@ static void knn_db_parallel_impl( } } -#pragma omp parallel num_threads(nt) - { - int tid = omp_get_thread_num(); +#pragma omp parallel for + for (int tid = 0; tid < nt; tid++) { size_t j_begin = static_cast(tid) * ny / nt; size_t j_end = static_cast(tid + 1) * ny / nt; size_t local_ny = j_end - j_begin; @@ -734,7 +850,7 @@ static void knn_db_parallel_impl( } } - // Merge per-thread heaps into output, parallelized over queries + // Merge per-segment heaps into output, parallelized over queries #pragma omp parallel for for (int64_t i = 0; i < static_cast(nx); i++) { heap_heapify(k, vals + i * k, ids + i * k); @@ -760,16 +876,28 @@ static void knn_db_parallel_impl( static bool should_use_db_parallel( size_t nx, size_t ny, + size_t k, const IDSelector* sel) { if (sel) { return false; } - int nt = omp_get_max_threads(); - size_t min_ny = std::max( + const size_t nt = omp_get_max_threads(); + const size_t min_ny = std::max( kDbParallelMinVectors, - static_cast(nt) * - static_cast(distance_compute_blas_database_bs)); - return nt > 1 && nx < static_cast(nt) && ny >= min_ny; + nt * static_cast(distance_compute_blas_database_bs)); + if (nt <= 1 || ny < min_ny) { + return false; + } + if (nx < nt) { + return true; + } + // Otherwise the sequential scan or BLAS runs. The sequential scan reads + // the whole database once per query per thread, and BLAS synchronizes + // all threads twice per database block. + const size_t bytes = nt * + (nx * k * (sizeof(float) + sizeof(int64_t)) + + nx * db_parallel_block(nx) * sizeof(float)); + return bytes <= kDbParallelMaxBytes; } void knn_inner_product( @@ -796,7 +924,7 @@ void knn_inner_product( return; } - if (should_use_db_parallel(nx, ny, sel)) { + if (should_use_db_parallel(nx, ny, k, sel)) { knn_db_parallel_impl>( x, y, d, nx, ny, k, vals, ids, nullptr); } else { @@ -862,7 +990,7 @@ void knn_L2sqr( return; } - if (should_use_db_parallel(nx, ny, sel)) { + if (should_use_db_parallel(nx, ny, k, sel)) { knn_db_parallel_impl>( x, y, d, nx, ny, k, vals, ids, y_norm2); } else { @@ -894,6 +1022,204 @@ void knn_L2sqr( knn_L2sqr(x, y, d, nx, ny, res->k, res->val, res->ids, y_norm2, sel); } +void accumulate_cluster_sums( + size_t d, + size_t n, + size_t k, + const float* x, + const int64_t* labels, + float* sums) { + // Each thread owns a range of labels, so no two threads write one row. +#pragma omp parallel if (n * d > 65536) + { + const int64_t nt = omp_get_num_threads(), rank = omp_get_thread_num(); + const int64_t a0 = k * rank / nt, a1 = k * (rank + 1) / nt; + for (size_t i = 0; i < n; i++) { + const int64_t a = labels[i]; + if (a >= a0 && a < a1) { + float* row = sums + a * (d + 1); + fvec_add(d, row, x + i * d, row); + row[d] += 1; + } + } + } +} + +void accumulate_removal_stats( + size_t d, + size_t n, + size_t k, + const float* x, + const int64_t* labels, + const float* d1, + const float* d2, + const float* centroids, + const float* axes, + float* stats) { + // Each thread owns a range of labels, so no two threads write one row. +#pragma omp parallel if (n * d > 65536) + { + const int64_t nt = omp_get_num_threads(), rank = omp_get_thread_num(); + const int64_t a0 = k * rank / nt, a1 = k * (rank + 1) / nt; + std::vector y(d); + for (size_t i = 0; i < n; i++) { + const int64_t a = labels[i]; + if (a < a0 || a >= a1) { + continue; + } + fvec_sub(d, x + i * d, centroids + a * d, y.data()); + const float p = fvec_inner_product(y.data(), axes + a * d, d); + float* row = stats + a * (d + 1); + fvec_madd(d, row, p, y.data(), row); + const float margin = d2[i] - d1[i]; + row[d] += std::isfinite(margin) ? margin : 0; + } + } +} + +void update_removal_axes( + size_t d, + size_t n, + const int64_t* ids, + float weight, + float* batch, + float* axis, + float* axes) { +#pragma omp parallel for if (n * d > 65536) + for (int64_t i = 0; i < static_cast(n); i++) { + const int64_t a = ids[i]; + float* b = batch + a * (d + 1); + float* u = axis + a * (d + 1); + fvec_madd(d, u, weight, b, u); + double norm2 = 0; + for (size_t j = 0; j < d; j++) { + norm2 += double(u[j]) * u[j]; + } + const double norm = std::sqrt(norm2); + if (norm > 0) { + for (size_t j = 0; j < d; j++) { + axes[a * d + j] = u[j] / norm; + } + } + std::fill(b, b + d + 1, 0.0f); + } +} + +namespace { + +/** Whether fp16 queries go to the BLAS kernels directly. + * + * Other cases widen chunks of queries and run the fp32 search: selectors, + * sequential and database-parallel searches, and small d, where the fused + * top-1 kernels need fp32 rows. + */ +bool use_fp16_blas_kernels( + size_t d, + size_t nx, + size_t ny, + size_t k, + const IDSelector* sel) { + return !sel && ny > 0 && d > 32 && + nx * d >= static_cast(distance_compute_blas_threshold) && + !should_use_db_parallel(nx, ny, k, sel); +} + +/// widens chunks of queries and calls search(x_chunk, n_chunk, i0) on them +template +void search_fp16_by_chunks( + const uint16_t* x, + size_t d, + size_t nx, + const Fp32Search& search) { + // a multiple of the query tile, so the fp32 kernels see the same tiles + const size_t bs_x = std::max(distance_compute_blas_query_bs, 1); + const size_t chunk = bs_x * + std::max(1, (size_t(8) << 20) / (bs_x * d * sizeof(float))); + std::vector buffer(std::min(nx, chunk) * d); + for (size_t i0 = 0; i0 < nx; i0 += chunk) { + const size_t i1 = std::min(nx, i0 + chunk); + fp16_to_fp32((i1 - i0) * d, x + i0 * d, buffer.data()); + search(buffer.data(), i1 - i0, i0); + } +} + +} // namespace + +void knn_inner_product_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + size_t k, + float* vals, + int64_t* ids, + const IDSelector* sel) { + if (!use_fp16_blas_kernels(d, nx, ny, k, sel)) { + search_fp16_by_chunks( + x, d, nx, [&](const float* xc, size_t nc, size_t i0) { + knn_inner_product( + xc, + y, + d, + nc, + ny, + k, + vals + i0 * k, + ids + i0 * k, + sel); + }); + return; + } + Run_search_inner_product_fp16 r; + dispatch_knn_ResultHandler( + nx, + vals, + ids, + k, + METRIC_INNER_PRODUCT, + nullptr, + r, + x, + y, + d, + nx, + ny); +} + +void knn_L2sqr_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + size_t k, + float* vals, + int64_t* ids, + const float* y_norm2, + const IDSelector* sel) { + if (!use_fp16_blas_kernels(d, nx, ny, k, sel)) { + search_fp16_by_chunks( + x, d, nx, [&](const float* xc, size_t nc, size_t i0) { + knn_L2sqr( + xc, + y, + d, + nc, + ny, + k, + vals + i0 * k, + ids + i0 * k, + y_norm2, + sel); + }); + return; + } + Run_search_L2sqr_fp16 r; + dispatch_knn_ResultHandler( + nx, vals, ids, k, METRIC_L2, nullptr, r, x, y, d, nx, ny, y_norm2); +} + /*************************************************************************** * Range search ***************************************************************************/ diff --git a/thirdparty/faiss/faiss/utils/distances.h b/thirdparty/faiss/faiss/utils/distances.h index f2d4a80a7..574f705a2 100644 --- a/thirdparty/faiss/faiss/utils/distances.h +++ b/thirdparty/faiss/faiss/utils/distances.h @@ -455,6 +455,36 @@ void knn_L2sqr( const float* y_norm2 = nullptr, const IDSelector* sel = nullptr); +/** knn_inner_product for packed IEEE binary16 queries (x: nx * d uint16_t). + * + * The BLAS kernels widen each query tile once and reuse it for all database + * tiles, so there is no fp32 copy of the queries. Results are the same as + * knn_inner_product on the widened queries. + */ +void knn_inner_product_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + size_t k, + float* distances, + int64_t* indexes, + const IDSelector* sel = nullptr); + +/// knn_L2sqr for packed IEEE binary16 queries, see knn_inner_product_fp16 +void knn_L2sqr_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + size_t k, + float* distances, + int64_t* indexes, + const float* y_norm2 = nullptr, + const IDSelector* sel = nullptr); + /** Find the max inner product neighbors for nx queries in a set of ny vectors * indexed by ids. May be useful for re-ranking a pre-selected vector list * @@ -569,6 +599,108 @@ void compute_PQ_dis_tables_dsub2( * Misc matrix and vector manipulation functions ***************************************************************************/ +/** Per-cluster sums and counts of labeled vectors. + * + * For each i < n, adds x[i] to sums[labels[i], 0:d] and 1 to + * sums[labels[i], d]. The result equals numpy.add.at(sums[:, :d], labels, x) + * and numpy.add.at(sums[:, d], labels, 1) bit for bit: the rows of each + * cluster are added in increasing i, whatever the number of threads. + * Unlike numpy.add.at, which is single-threaded, it runs with OpenMP when + * n * d > 65536: each thread owns a contiguous range of labels and scans all + * rows, so no two threads write the same row of sums and no reduction is + * needed. + * + * All arrays are contiguous and row-major; x and sums are float32, labels + * int64; sums must not overlap x or labels. + * + * @param d dimension of the vectors + * @param n number of vectors + * @param k number of clusters + * @param x input vectors, size n * d + * @param labels input cluster of each vector, size n, in [0, k) + * @param sums in/out sums and counts, size k * (d + 1): row a holds the + * d components of the sum and then the count; results are + * added to its contents + */ +void accumulate_cluster_sums( + size_t d, + size_t n, + size_t k, + const float* x, + const int64_t* labels, + float* sums); + +/** Per-cluster removal costs and Oja long-axis terms of an assignment. + * + * Used by e-means' cost-based revival. For each i < n, with a = labels[i], + * y = x[i] - centroids[a] and p = , adds p * y to + * stats[a, 0:d] and the removal cost d2[i] - d1[i] to stats[a, d] (zero is + * added when the computed difference is not finite). The rows of each + * cluster are added in increasing i, so the result does not depend on the + * number of threads. OpenMP as in accumulate_cluster_sums: each thread owns + * a range of labels. + * + * All arrays are contiguous and row-major, float32 except the int64 + * labels; stats must not overlap any input. + * + * @param d dimension of the vectors + * @param n number of vectors + * @param k number of clusters + * @param x input vectors, size n * d + * @param labels input nearest centroid of each vector, size n, in [0, k) + * @param d1 input squared distance to the nearest centroid, size n + * @param d2 input squared distance to the second-nearest centroid, + * size n + * @param centroids input centroids used for the assignment, size k * d + * @param axes input unit long axis of each cluster, size k * d + * @param stats in/out per-cluster sums, size k * (d + 1): row a holds + * the sum of p * y and then the sum of d2 - d1; results + * are added to its contents + */ +void accumulate_removal_stats( + size_t d, + size_t n, + size_t k, + const float* x, + const int64_t* labels, + const float* d1, + const float* d2, + const float* centroids, + const float* axes, + float* stats); + +/** Oja update of the cluster axes from accumulate_removal_stats sums. + * + * For each cluster a = ids[i], i < n: u = axis[a, 0:d] += weight * + * batch[a, 0:d]; if |u| > 0 (computed in double), axes[a] = u / |u|; + * batch[a] is then zeroed. Clusters are independent; OpenMP over ids when + * n * d > 65536. Rows not in ids keep their contents, and so does axes[a] + * when |u| = 0. + * + * All arrays are contiguous and row-major, float32 except the int64 ids; + * batch, axis and axes have k rows (k is the number of clusters they were + * allocated for) and must not overlap each other or ids. + * + * @param d dimension of the vectors + * @param n number of clusters to update + * @param ids input clusters to update, size n, distinct, each in [0, k) + * @param weight input weight of the batch sums + * @param batch in/out batch sums, k rows of size d + 1 (as stats in + * accumulate_removal_stats); rows ids are zeroed + * @param axis in/out running sums u, k rows of size d + 1 (component d + * is not used) + * @param axes out unit axes, k rows of size d; rows ids with |u| > 0 are + * overwritten + */ +void update_removal_axes( + size_t d, + size_t n, + const int64_t* ids, + float weight, + float* batch, + float* axis, + float* axes); + /** compute c := a + bf * b for a, b and c tables * * @param n size of the tables @@ -600,4 +732,8 @@ int fvec_madd_and_argmin( const float* b, float* c); +/// sum of x[j] for every j < d whose bit is set in bits (LSB-first per byte) +template +float fvec_masked_sum(const float* x, const uint8_t* bits, size_t d); + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/distances_dispatch.h b/thirdparty/faiss/faiss/utils/distances_dispatch.h index 03827a30f..760f8f58b 100644 --- a/thirdparty/faiss/faiss/utils/distances_dispatch.h +++ b/thirdparty/faiss/faiss/utils/distances_dispatch.h @@ -184,7 +184,7 @@ inline void fvec_sub_dispatch( const float* a, const float* b, float* c) { - with_simd_level_256bit( + with_selected_simd_levels( [&]() { fvec_sub(d, a, b, c); }); } @@ -193,7 +193,7 @@ inline void fvec_add_dispatch( const float* a, const float* b, float* c) { - with_simd_level_256bit( + with_selected_simd_levels( [&]() { fvec_add(d, a, b, c); }); } @@ -202,7 +202,7 @@ inline void fvec_add_scalar_dispatch( const float* a, float b, float* c) { - with_simd_level_256bit( + with_selected_simd_levels( [&]() { fvec_add(d, a, b, c); }); } @@ -214,7 +214,9 @@ inline void compute_PQ_dis_tables_dsub2_dispatch( const float* x, bool is_inner_product, float* dis_tables) { - with_simd_level_256bit([&]() { + constexpr int dsub2_mask = + AVAILABLE_SIMD_LEVELS_AVX2_NEON | (1 << int(SIMDLevel::RISCV_RVV)); + with_selected_simd_levels([&]() { compute_PQ_dis_tables_dsub2( d, ksub, centroids, nx, x, is_inner_product, dis_tables); }); diff --git a/thirdparty/faiss/faiss/utils/distances_fused/avx512.cpp b/thirdparty/faiss/faiss/utils/distances_fused/avx512.cpp index 82bb4ac31..83970911b 100644 --- a/thirdparty/faiss/faiss/utils/distances_fused/avx512.cpp +++ b/thirdparty/faiss/faiss/utils/distances_fused/avx512.cpp @@ -7,10 +7,9 @@ // -*- c++ -*- +#include #include -#ifdef COMPILE_SIMD_AVX512 - #include namespace faiss { @@ -264,7 +263,7 @@ void exhaustive_L2sqr_fused_cmax( const idx_t nx_p = (nx / NX_POINTS_PER_LOOP) * NX_POINTS_PER_LOOP; // the main loop. -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) for (idx_t i = 0; i < nx_p; i += NX_POINTS_PER_LOOP) { kernel( x, y, y_transposed.data(), ny, res, y_norms, i); @@ -343,5 +342,3 @@ bool exhaustive_L2sqr_fused_cmax( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/utils/distances_fused/distances_fused.cpp b/thirdparty/faiss/faiss/utils/distances_fused/distances_fused.cpp index fcbcd2d74..f05a068ba 100644 --- a/thirdparty/faiss/faiss/utils/distances_fused/distances_fused.cpp +++ b/thirdparty/faiss/faiss/utils/distances_fused/distances_fused.cpp @@ -24,20 +24,6 @@ bool exhaustive_L2sqr_fused_cmax( return false; } -#ifdef COMPILE_SIMD_RISCV_RVV -template <> -bool exhaustive_L2sqr_fused_cmax( - const float*, - const float*, - size_t, - size_t, - size_t, - Top1BlockResultHandler>&, - const float*) { - return false; -} -#endif // COMPILE_SIMD_RISCV_RVV - bool exhaustive_L2sqr_fused_cmax( const float* x, const float* y, diff --git a/thirdparty/faiss/faiss/utils/distances_fused/rvv.cpp b/thirdparty/faiss/faiss/utils/distances_fused/rvv.cpp new file mode 100644 index 000000000..1958f657c --- /dev/null +++ b/thirdparty/faiss/faiss/utils/distances_fused/rvv.cpp @@ -0,0 +1,25 @@ +/* + * 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. + */ + +#include + +namespace faiss { + +// Scalar fallback: no fused kernel available. +template <> +bool exhaustive_L2sqr_fused_cmax( + const float*, + const float*, + size_t, + size_t, + size_t, + Top1BlockResultHandler>&, + const float*) { + return false; +} + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based.cpp b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based.cpp index 59ee77d7c..a5de53366 100644 --- a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based.cpp +++ b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based.cpp @@ -7,8 +7,6 @@ // AVX2 compilation unit for the simdlib-based fused distance kernel. -#ifdef COMPILE_SIMD_AVX2 - #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include @@ -71,5 +69,3 @@ bool exhaustive_L2sqr_fused_cmax( } } // namespace faiss - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp index c638d4a86..132f5351b 100644 --- a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp +++ b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_based_neon.cpp @@ -7,8 +7,6 @@ // ARM NEON compilation unit for the simdlib-based fused distance kernel. -#ifdef COMPILE_SIMD_ARM_NEON - #include // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include @@ -53,5 +51,3 @@ bool exhaustive_L2sqr_fused_cmax( } } // namespace faiss - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h index 5321708d1..d7e73705c 100644 --- a/thirdparty/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h +++ b/thirdparty/faiss/faiss/utils/distances_fused/simdlib_kernel-inl.h @@ -14,6 +14,7 @@ #pragma once +#include #include namespace faiss { @@ -267,7 +268,7 @@ void exhaustive_L2sqr_fused_cmax( const size_t nx_p = (nx / NX_POINTS_PER_LOOP) * NX_POINTS_PER_LOOP; // the main loop. -#pragma omp parallel for schedule(dynamic) +#pragma omp parallel for schedule(FAISS_OMP_DYNAMIC) for (int64_t i = 0; i < static_cast(nx_p); i += NX_POINTS_PER_LOOP) { kernel( diff --git a/thirdparty/faiss/faiss/utils/distances_simd.cpp b/thirdparty/faiss/faiss/utils/distances_simd.cpp index 39dc72b5b..e44f1fa16 100644 --- a/thirdparty/faiss/faiss/utils/distances_simd.cpp +++ b/thirdparty/faiss/faiss/utils/distances_simd.cpp @@ -8,6 +8,7 @@ // -*- c++ -*- #include +#include #include #include @@ -42,6 +43,14 @@ void fvec_madd( } } +template <> +float fvec_masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + return masked_sum(x, bits, d); +} + template <> void fvec_L2sqr_ny_transposed( float* dis, diff --git a/thirdparty/faiss/faiss/utils/extra_distances.h b/thirdparty/faiss/faiss/utils/extra_distances.h index a59ad59e6..07c1d5964 100644 --- a/thirdparty/faiss/faiss/utils/extra_distances.h +++ b/thirdparty/faiss/faiss/utils/extra_distances.h @@ -112,7 +112,8 @@ struct VectorDistance { size_t d; float metric_arg; - VectorDistance(size_t d, float metric_arg) : d(d), metric_arg(metric_arg) {} + VectorDistance(size_t d_in, float metric_arg_in) + : d(d_in), metric_arg(metric_arg_in) {} static constexpr MetricType metric = mt; static constexpr bool is_similarity = is_similarity_metric(mt); diff --git a/thirdparty/faiss/faiss/utils/fp16-fp16c.h b/thirdparty/faiss/faiss/utils/fp16-fp16c.h index 8bf7844f3..28f20baac 100644 --- a/thirdparty/faiss/faiss/utils/fp16-fp16c.h +++ b/thirdparty/faiss/faiss/utils/fp16-fp16c.h @@ -12,6 +12,8 @@ namespace faiss { +namespace { + inline uint16_t encode_fp16(float x) { __m128 xf = _mm_set1_ps(x); __m128i xi = @@ -25,4 +27,6 @@ inline float decode_fp16(uint16_t x) { return _mm_cvtss_f32(xf); } +} // namespace + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/fp16-inl.h b/thirdparty/faiss/faiss/utils/fp16-inl.h index 6c376e016..5f490783c 100644 --- a/thirdparty/faiss/faiss/utils/fp16-inl.h +++ b/thirdparty/faiss/faiss/utils/fp16-inl.h @@ -27,63 +27,35 @@ inline uint32_t intbits(float f) { return *(uint32_t*)fptr; } -} // namespace - inline uint16_t encode_fp16(float f) { - // via Fabian "ryg" Giesen. - // https://gist.github.com/2156668 - uint32_t sign_mask = 0x80000000u; - int32_t o; + // Rounds to nearest even, as the F16C and Arm conversions do, so that + // every SIMD level encodes the same bits. Via Fabian "ryg" Giesen + // (float_to_half_fast3_rtne): https://gist.github.com/2156668 + const uint32_t f32infty = 255u << 23; + const uint32_t f16max = (127u + 16u) << 23; + const uint32_t denorm_magic = ((127u - 15u) + (23u - 10u) + 1u) << 23; + const uint32_t sign_mask = 0x80000000u; uint32_t fint = intbits(f); - uint32_t sign = fint & sign_mask; + const uint32_t sign = fint & sign_mask; fint ^= sign; - // NOTE all the integer compares in this function can be safely - // compiled into signed compares since all operands are below - // 0x80000000. Important if you want fast straight SSE2 code (since - // there's no unsigned PCMPGTD). - - // Inf or NaN (all exponent bits set) - // NaN->qNaN and Inf->Inf - // unconditional assignment here, will override with right value for - // the regular case below. - uint32_t f32infty = 255u << 23; - o = (fint > f32infty) ? 0x7e00u : 0x7c00u; - - // (De)normalized number or zero - // update fint unconditionally to save the blending; we don't need it - // anymore for the Inf/NaN case anyway. - - const uint32_t round_mask = ~0xfffu; - const uint32_t magic = 15u << 23; - - // Shift exponent down, denormalize if necessary. - // NOTE This represents half-float denormals using single - // precision denormals. The main reason to do this is that - // there's no shift with per-lane variable shifts in SSE*, which - // we'd otherwise need. It has some funky side effects though: - // - This conversion will actually respect the FTZ (Flush To Zero) - // flag in MXCSR - if it's set, no half-float denormals will be - // generated. I'm honestly not sure whether this is good or - // bad. It's definitely interesting. - // - If the underlying HW doesn't support denormals (not an issue - // with Intel CPUs, but might be a problem on GPUs or PS3 SPUs), - // you will always get flush-to-zero behavior. This is bad, - // unless you're on a CPU where you don't care. - // - Denormals tend to be slow. FP32 denormals are rare in - // practice outside of things like recursive filters in DSP - - // not a typical half-float application. Whether FP16 denormals - // are rare in practice, I don't know. Whatever slow path your - // HW may or may not have for denormals, this may well hit it. - float fscale = floatbits(fint & round_mask) * floatbits(magic); - fscale = std::min(fscale, floatbits((31u << 23) - 0x1000u)); - int32_t fint2 = intbits(fscale) - round_mask; - - if (fint < f32infty) - o = fint2 >> 13; // Take the bits! - - return (o | (sign >> 16)); + uint32_t o; + if (fint >= f16max) { + // Inf->Inf. NaN->qNaN with the top bits of the payload, as F16C. + o = (fint > f32infty) ? 0x7e00u | ((fint >> 13) & 0x3ffu) : 0x7c00u; + } else if (fint < (113u << 23)) { + // The result is subnormal or zero. Adding a magic value aligns the 10 + // mantissa bits at the bottom of the float, and the float addition + // rounds to nearest even. + o = intbits(floatbits(fint) + floatbits(denorm_magic)) - denorm_magic; + } else { + const uint32_t mant_odd = (fint >> 13) & 1; + // rebias the exponent, and round to nearest even + fint += ((15u - 127u) << 23) + 0xfffu + mant_odd; + o = fint >> 13; + } + return static_cast(o | (sign >> 16)); } inline float decode_fp16(uint16_t h) { @@ -105,4 +77,6 @@ inline float decode_fp16(uint16_t h) { return floatbits(((exp == shifted_exp) ? infnan_val : reg_val) | sign_bit); } +} // namespace + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/hamming-inl.h b/thirdparty/faiss/faiss/utils/hamming-inl.h index 72aaf5bfc..b772065c5 100644 --- a/thirdparty/faiss/faiss/utils/hamming-inl.h +++ b/thirdparty/faiss/faiss/utils/hamming-inl.h @@ -42,6 +42,9 @@ inline BitstringReader::BitstringReader( : code(code_in), code_size(code_size_in), i(0) {} inline uint64_t BitstringReader::read(int nbit) { + if (nbit <= 0) { + return 0; + } assert(code_size * 8 >= nbit + i); // nb of available bits in i / 8 int na = 8 - (i & 7); diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp index e08c85032..4024b3603 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx2.cpp @@ -5,12 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #define THE_SIMD_LEVEL SIMDLevel::AVX2 // NOLINTBEGIN(facebook-hte-InlineHeader,facebook-unused-include-check) #include #include // NOLINTEND(facebook-hte-InlineHeader,facebook-unused-include-check) - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp index 1e13c55ae..02831a816 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512.cpp @@ -5,11 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #define THE_SIMD_LEVEL SIMDLevel::AVX512 // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include #include - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp index 6faa86d2a..cfa7991a1 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_avx512_vpopcnt.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512_VPOPCNT - #define THE_SIMD_LEVEL SIMDLevel::AVX512_VPOPCNT #include #include @@ -20,5 +18,3 @@ // Fails the build if the batch path stops being selected for this computer. static_assert(faiss::has_hamming_batch< faiss::HammingComputer20_tpl>); - -#endif // COMPILE_SIMD_AVX512_VPOPCNT diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h index a52b62e5a..a31e2b609 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512.h @@ -103,12 +103,40 @@ struct HammingComputerDefault_tpl { remainder8 = code_size % 8; } + /// No VPOPCNTDQ at this level: count the bits of each nibble with a + /// 16-entry table (vpshufb), then sum the bytes per 64-bit lane (vpsadbw). + /// The partial last block is a masked load, so no byte past the code is + /// read. int hamming(const uint8_t* b8) const { - const uint64_t* a64 = reinterpret_cast(a8); - const uint64_t* b64 = reinterpret_cast(b8); - - return hamming_popcount_tail( - a64, b64, 0, quotient8, a8, b8, remainder8); + const int code_size = quotient8 * 8 + remainder8; + const __m512i lut = _mm512_broadcast_i32x4( + _mm_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4)); + const __m512i low4 = _mm512_set1_epi8(0x0f); + const auto count = [&](__m512i x) { + const __m512i lo = _mm512_and_si512(x, low4); + const __m512i hi = _mm512_and_si512(_mm512_srli_epi16(x, 4), low4); + const __m512i c = _mm512_add_epi8( + _mm512_shuffle_epi8(lut, lo), _mm512_shuffle_epi8(lut, hi)); + return _mm512_sad_epu8(c, _mm512_setzero_si512()); + }; + __m512i accu = _mm512_setzero_si512(); + int i = 0; + for (; i + 64 <= code_size; i += 64) { + accu = _mm512_add_epi64( + accu, + count(_mm512_xor_si512( + _mm512_loadu_si512(a8 + i), + _mm512_loadu_si512(b8 + i)))); + } + if (i < code_size) { + const __mmask64 mask = _bzhi_u64(~uint64_t(0), code_size - i); + accu = _mm512_add_epi64( + accu, + count(_mm512_xor_si512( + _mm512_maskz_loadu_epi8(mask, a8 + i), + _mm512_maskz_loadu_epi8(mask, b8 + i)))); + } + return static_cast(_mm512_reduce_add_epi64(accu)); } inline int get_code_size() const { diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h index 807b389d6..42db887f7 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-avx512_vpopcnt.h @@ -186,40 +186,25 @@ struct HammingComputerDefault_tpl { remainder8 = code_size % 8; } + /// One vector accumulator, reduced once. The partial last block is a + /// masked load, so no byte past the code is read. int hamming(const uint8_t* b8) const { - int accu = 0; - - const uint64_t* a64 = reinterpret_cast(a8); - const uint64_t* b64 = reinterpret_cast(b8); - + const int code_size = quotient8 * 8 + remainder8; + __m512i accu = _mm512_setzero_si512(); int i = 0; - int quotient64 = quotient8 / 8; - for (; i < quotient64; ++i) { - __m512i vxor = _mm512_xor_si512( - _mm512_loadu_si512(&a64[i * 8]), - _mm512_loadu_si512(&b64[i * 8])); - __m512i vpcnt = _mm512_popcnt_epi64(vxor); - accu += _mm512_reduce_add_epi32(vpcnt); + for (; i + 64 <= code_size; i += 64) { + const __m512i vxor = _mm512_xor_si512( + _mm512_loadu_si512(a8 + i), _mm512_loadu_si512(b8 + i)); + accu = _mm512_add_epi64(accu, _mm512_popcnt_epi64(vxor)); } - i *= 8; - - // Handle 4-word (256-bit) remainder with VPOPCNTDQ VL - if (i + 4 <= quotient8) { - __m256i vxor = _mm256_xor_si256( - _mm256_loadu_si256((const __m256i*)&a64[i]), - _mm256_loadu_si256((const __m256i*)&b64[i])); - __m256i vpcnt = _mm256_popcnt_epi64(vxor); - __m128i lo = _mm256_castsi256_si128(vpcnt); - __m128i hi = _mm256_extracti128_si256(vpcnt, 1); - __m128i sum = _mm_add_epi64(lo, hi); - accu += static_cast( - _mm_extract_epi64(sum, 0) + _mm_extract_epi64(sum, 1)); - i += 4; + if (i < code_size) { + const __mmask64 mask = _bzhi_u64(~uint64_t(0), code_size - i); + const __m512i vxor = _mm512_xor_si512( + _mm512_maskz_loadu_epi8(mask, a8 + i), + _mm512_maskz_loadu_epi8(mask, b8 + i)); + accu = _mm512_add_epi64(accu, _mm512_popcnt_epi64(vxor)); } - - accu += hamming_popcount_tail( - a64, b64, i, quotient8, a8, b8, remainder8); - return accu; + return static_cast(_mm512_reduce_add_epi64(accu)); } inline int get_code_size() const { diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h index 1053d1ead..78e458966 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_computer-neon.h @@ -16,8 +16,6 @@ // hamming_computer-generic.h. SIMDLevel::ARM_NEON specializations for the // ISA-varying HammingComputer and GenHammingComputer structs live in this file. -#ifdef __aarch64__ - #include #include @@ -318,5 +316,3 @@ struct GenHammingComputerM8_tpl { } // namespace faiss #endif - -#endif diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_impl.h b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_impl.h index 76d41e474..4e9b3172a 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_impl.h +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_impl.h @@ -102,7 +102,8 @@ void hammings_knn_hc_impl( CMax, \ NB, \ BD, \ - HammingComputer>:: \ + HammingComputer, \ + THE_SIMD_LEVEL>:: \ addn(j1 - j0, hc, bs2_, k, bh_val_, bh_ids_, sel); \ break; diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_neon.cpp b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_neon.cpp index 56b20e67d..20c444852 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_neon.cpp +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_neon.cpp @@ -5,11 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #define THE_SIMD_LEVEL SIMDLevel::ARM_NEON // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include #include - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp index 88f6fa2c5..6b02b6eb0 100644 --- a/thirdparty/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp +++ b/thirdparty/faiss/faiss/utils/hamming_distance/hamming_rvv.cpp @@ -5,11 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_RISCV_RVV - #define THE_SIMD_LEVEL SIMDLevel::RISCV_RVV // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include #include - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/utils/partitioning.cpp b/thirdparty/faiss/faiss/utils/partitioning.cpp index 416eb041f..4f099d199 100644 --- a/thirdparty/faiss/faiss/utils/partitioning.cpp +++ b/thirdparty/faiss/faiss/utils/partitioning.cpp @@ -204,13 +204,13 @@ typename C::T partition_fuzzy_median3( thresh = C::Crev::nextafter(thresh); n_eq_1 = q; } else { - assert(n_eq_1 <= n_eq); + assert(static_cast(n_eq_1) <= n_eq); } [[maybe_unused]] const int wp = compress_array(vals, ids, n, thresh, n_eq_1); - assert(wp == q); + assert(static_cast(wp) == q); if (q_out) { *q_out = q; } diff --git a/thirdparty/faiss/faiss/utils/pq_code_distance.h b/thirdparty/faiss/faiss/utils/pq_code_distance.h index a2dd4f901..46604df9b 100644 --- a/thirdparty/faiss/faiss/utils/pq_code_distance.h +++ b/thirdparty/faiss/faiss/utils/pq_code_distance.h @@ -53,10 +53,14 @@ namespace pq_code_distance { *********************************************************************/ /// Scalar PQ code distance implementation. -/// Templated only on decoder type, independent of SIMD level. /// Used directly by non-PQDecoder8 decoders (PQDecoder16, /// PQDecoderGeneric) and as fallback for PQDecoder8 at NONE/NEON. -template +// SL keeps each SIMD-level TU's instantiation a distinct symbol. Without it +// the linker merges them and may keep one compiled with -mavx512*, which +// then runs on the AVX2 path and raises SIGILL on CPUs without AVX512. +// The default keeps callers outside faiss that name only the decoder (e.g. +// unicorn/features/encoders/PQFSTable.h) compiling; faiss passes SL itself. +template struct PQCodeDistanceScalar { using PQDecoder = PQDecoderT; @@ -160,7 +164,7 @@ struct PQCodeDistance { if constexpr (std::is_same_v) { return pq_code_distance_single_impl(M, nbits, sim_table, code); } else { - return PQCodeDistanceScalar::distance_single_code( + return PQCodeDistanceScalar::distance_single_code( M, nbits, sim_table, code); } } @@ -191,7 +195,7 @@ struct PQCodeDistance { result2, result3); } else { - PQCodeDistanceScalar::distance_four_codes( + PQCodeDistanceScalar::distance_four_codes( M, nbits, sim_table, diff --git a/thirdparty/faiss/faiss/utils/prefetch.h b/thirdparty/faiss/faiss/utils/prefetch.h index 666b31976..654c613d5 100644 --- a/thirdparty/faiss/faiss/utils/prefetch.h +++ b/thirdparty/faiss/faiss/utils/prefetch.h @@ -25,34 +25,9 @@ inline void prefetch_L3(const void* address) { _mm_prefetch((const char*)address, _MM_HINT_T2); } -#elif defined(__aarch64__) - -// ARM64 - -#ifdef _MSC_VER - -// todo: arm on MSVC -inline void prefetch_L1(const void* address) {} -inline void prefetch_L2(const void* address) {} -inline void prefetch_L3(const void* address) {} - -#else -// arm on non-MSVC - -inline void prefetch_L1(const void* address) { - __builtin_prefetch(address, 0, 3); -} -inline void prefetch_L2(const void* address) { - __builtin_prefetch(address, 0, 2); -} -inline void prefetch_L3(const void* address) { - __builtin_prefetch(address, 0, 1); -} -#endif - #else -// a generic platform +// other platforms, including ARM64 #ifdef _MSC_VER diff --git a/thirdparty/faiss/faiss/utils/quantize_lut.cpp b/thirdparty/faiss/faiss/utils/quantize_lut.cpp index 29abf3d6c..987ca68de 100644 --- a/thirdparty/faiss/faiss/utils/quantize_lut.cpp +++ b/thirdparty/faiss/faiss/utils/quantize_lut.cpp @@ -60,6 +60,19 @@ void round_tab(const float* tab, size_t n, float a, float bi, T* tab_out) { } // anonymous namespace +float fastscan_lut_scale( + float max_column_span, + float max_sum_span, + size_t n_rounded_terms) { + const float headroom = 0.5f * float(n_rounded_terms); + const float sum_budget = 65535.0f - headroom; + const float a = std::min( + max_column_span > 0 ? 255.0f / max_column_span : HUGE_VALF, + (max_sum_span > 0 && sum_budget > 0) ? sum_budget / max_sum_span + : HUGE_VALF); + return std::isfinite(a) ? a : 0.0f; +} + void round_uint8_per_column( float* tab, size_t n, @@ -67,6 +80,7 @@ void round_uint8_per_column( float* a_out, float* b_out) { float max_span = 0; + float total_span = 0; std::vector mins(n); for (size_t i = 0; i < n; i++) { mins[i] = tab_min(tab + i * d, d); @@ -74,8 +88,9 @@ void round_uint8_per_column( if (span > max_span) { max_span = span; } + total_span += span; } - float a = max_span > 0 ? 255.0f / max_span : 0.0f; + float a = fastscan_lut_scale(max_span, total_span, n); float b = 0; for (size_t i = 0; i < n; i++) { b += mins[i]; @@ -97,6 +112,7 @@ void round_uint8_per_column_multi( float* a_out, float* b_out) { float max_span = 0; + float total_span = 0; std::vector mins(n); for (size_t i = 0; i < n; i++) { float min_i = HUGE_VAL; @@ -110,8 +126,9 @@ void round_uint8_per_column_multi( if (span > max_span) { max_span = span; } + total_span += span; } - float a = max_span > 0 ? 255.0f / max_span : 0.0f; + float a = fastscan_lut_scale(max_span, total_span, n); float b = 0; for (size_t i = 0; i < n; i++) { b += mins[i]; @@ -155,12 +172,7 @@ void quantize_LUT_and_bias( max_span_dis += span; b += mins[i]; } - a = std::min( - max_span_LUT > 0 ? 255.0f / max_span_LUT : HUGE_VALF, - max_span_dis > 0 ? 65535.0f / max_span_dis : HUGE_VALF); - if (!std::isfinite(a)) { - a = 0.0f; - } + a = fastscan_lut_scale(max_span_LUT, max_span_dis, M); for (size_t i = 0; i < M; i++) { round_tab(LUT + i * ksub, ksub, a, mins[i], LUTq + i * ksub); @@ -180,12 +192,7 @@ void quantize_LUT_and_bias( max_span_dis += span; b += mins[i]; } - a = std::min( - max_span_LUT > 0 ? 255.0f / max_span_LUT : HUGE_VALF, - max_span_dis > 0 ? 65535.0f / max_span_dis : HUGE_VALF); - if (!std::isfinite(a)) { - a = 0.0f; - } + a = fastscan_lut_scale(max_span_LUT, max_span_dis, M); b += bias_min; for (size_t i = 0; i < M; i++) { @@ -219,12 +226,7 @@ void quantize_LUT_and_bias( b = std::min(b, b2j); } - a = std::min( - max_span_LUT > 0 ? 255.0f / max_span_LUT : HUGE_VALF, - max_span_dis > 0 ? 65535.0f / max_span_dis : HUGE_VALF); - if (!std::isfinite(a)) { - a = 0.0f; - } + a = fastscan_lut_scale(max_span_LUT, max_span_dis, M); ij = 0; size_t ij_2 = 0; @@ -266,13 +268,15 @@ void quantize_LUT_and_bias( } float max_span = -HUGE_VAL; + float total_span = 0; b = 0; for (size_t i = 0; i < M; i++) { float span = maxs[i] - mins[i]; max_span = std::max(max_span, span); + total_span += span; b += mins[i]; } - a = max_span > 0 ? 255.0f / max_span : 0.0f; + a = fastscan_lut_scale(max_span, total_span, M); ij = 0; size_t ij_2 = 0; for (size_t j = 0; j < nprobe; j++) { @@ -321,12 +325,7 @@ void aq_quantize_LUT_and_bias( max_span_dis += (i >= M - M_norm ? span * norm_scale : span); b += mins[i]; } - a = std::min( - max_span_LUT > 0 ? 255.0f / max_span_LUT : HUGE_VALF, - max_span_dis > 0 ? 65535.0f / max_span_dis : HUGE_VALF); - if (!std::isfinite(a)) { - a = 0.0f; - } + a = fastscan_lut_scale(max_span_LUT, max_span_dis, M); b += bias_min; for (size_t i = 0; i < M; i++) { diff --git a/thirdparty/faiss/faiss/utils/quantize_lut.h b/thirdparty/faiss/faiss/utils/quantize_lut.h index 9adaad39d..72dbfe101 100644 --- a/thirdparty/faiss/faiss/utils/quantize_lut.h +++ b/thirdparty/faiss/faiss/utils/quantize_lut.h @@ -7,6 +7,8 @@ #pragma once +#include + #include #include @@ -25,6 +27,15 @@ namespace faiss { namespace quantize_lut { +/** Scale for a fast scan LUT, bounding both the uint8 entry and the uint16 + * sum the kernel accumulates. `n_rounded_terms` is how many rounded values + * land in one accumulator: the columns, plus one for a rounded bias term. + */ +float fastscan_lut_scale( + float max_column_span, + float max_sum_span, + size_t n_rounded_terms); + /* affine quantizer, a and b are the affine coefficients, marginalize over d * * @param tab input/output, size (n, d) diff --git a/thirdparty/faiss/faiss/utils/rabitq_simd.h b/thirdparty/faiss/faiss/utils/rabitq_simd.h index ccc6a0ed3..59c1b3c9b 100644 --- a/thirdparty/faiss/faiss/utils/rabitq_simd.h +++ b/thirdparty/faiss/faiss/utils/rabitq_simd.h @@ -54,7 +54,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount( size_t qb); /// Four independent AND-dot-product/popcount pairs for a four-plane query. -/// Query contains 4 * size bytes; each data pointer contains size bytes. +/// Query contains 4 * size bytes; each data pointer contains `size` bytes. /// Byte-aligned buffers and arbitrary byte counts are supported. template inline void bitwise_q4_batch_4( @@ -164,7 +164,7 @@ inline uint64_t bitwise_and_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv & yv) << j; @@ -172,7 +172,7 @@ inline uint64_t bitwise_and_dot_product( } for (; offset < size; ++offset) { const auto yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); sum += popcount32(qv & yv) << j; } @@ -194,7 +194,7 @@ inline BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); popcount_sum += popcount64(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); dot_product += popcount64(qv & yv) << j; @@ -203,7 +203,7 @@ inline BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset < size; ++offset) { const auto yv = *(data + offset); popcount_sum += popcount32(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); dot_product += popcount32(qv & yv) << j; } @@ -222,7 +222,7 @@ inline uint64_t bitwise_xor_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv ^ yv) << j; @@ -230,7 +230,7 @@ inline uint64_t bitwise_xor_dot_product( } for (; offset < size; ++offset) { const auto yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); sum += popcount32(qv ^ yv) << j; } @@ -361,16 +361,12 @@ inline void quantize_query_values( /********************************************************* * Multi-bit RaBitQ inner product kernels. * - * Compute: sum_i rotated_q[i] * ((sign_bit_i << ex_bits) + ex_code_val_i + cb) + * Score = sum_i rotated_q[i] * ((sign_i << ex_bits) + ex_i + cb) * - * Strategy: - * ex_bits == 1: Specialized kernel — both sign_bits and ex_code are - * 1-bit-per-dim packed, enabling direct bit→mask→float - * conversion with zero per-element extraction. - * ex_bits >= 2: Bit-plane decomposition (BMI2 required) — PEXT extracts - * each bit plane in one instruction, then the same - * bit→mask→float kernel computes each plane's dot product. - * Fallback: Scalar extraction via 64-bit window read + shift + mask. + * ex_bits == 1: bits map straight to floats. No extraction. + * ex_bits 2..7: BMI2 PEXT extracts each bit plane. + * ex_bits == 8: whole bytes. No extraction and no BMI2. + * Fallback: scalar math reads one code at a time. *********************************************************/ namespace faiss::rabitq::multibit { @@ -444,4 +440,118 @@ inline float compute_inner_product( return ip_scalar(sign_bits, ex_code, rotated_q, 0, d, ex_bits, cb); } +/** + * compute_inner_product with the sign term supplied by the caller: + * + * (1 << ex_bits) * sign_ip + sum_i rotated_q[i] * ex_i + cb * q_sum + * + * With sign_ip = fvec_masked_sum(rotated_q, sign_bits, d) and + * q_sum = sum_i rotated_q[i], this equals + * compute_inner_product(sign_bits, ex_code, rotated_q, d, ex_bits, cb) up to + * float rounding. It serves codes whose sign bits are not stored next to + * ex_code, e.g. split between memory and disk: the caller accumulates the + * sign term piece by piece with fvec_masked_sum. q_sum depends on the + * query only, so it can be computed once per query. + * + * Unlike compute_inner_product, this reads only the (d * ex_bits + 7) / 8 + * bytes of ex_code and never the bytes after them. + * + * @param ex_code packed extra-bit codes (ex_bits bits/dim); may be null + * when ex_bits == 0 + * @param rotated_q rotated query vector (float[d]) + * @param d dimensionality + * @param ex_bits number of extra bits per dimension, in [0, 8] + * @param cb constant bias: -(2^ex_bits - 0.5) + * @param sign_ip sum_i rotated_q[i] * sign_i + * @param q_sum sum_i rotated_q[i] + * @return inner product value + */ +template +float compute_inner_product_with_sign_ip( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits, + float cb, + float sign_ip, + float q_sum); + +/// SIMD levels with a split inner-product kernel. +constexpr int RABITQ_SPLIT_IP_SIMD_LEVELS = (1 << int(SIMDLevel::NONE)) | + (1 << int(SIMDLevel::AVX2)) | (1 << int(SIMDLevel::AVX512)); + +/// Load the code bytes at ex_code + offset into the low bytes of a uint64, +/// reading 8 bytes when they all lie within the first total_bytes bytes of +/// ex_code and only the remaining ones otherwise. +static inline uint64_t load_ex_code_window( + const uint8_t* ex_code, + size_t offset, + size_t total_bytes) { + uint64_t window = 0; + if (offset + sizeof(window) <= total_bytes) { + memcpy(&window, ex_code + offset, sizeof(window)); + } else { + memcpy(&window, ex_code + offset, total_bytes - offset); + } + return window; +} + +/// Scalar sum over [start, d) of rotated_q[i] * ex_i, for ex_bits in [1, 8]. +/// Reads only the (d * ex_bits + 7) / 8 bytes of ex_code. Also serves as the +/// tail handler of the SIMD kernels. +static inline float ex_ip_scalar( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t start, + size_t d, + size_t ex_bits) { + float result = 0.0f; + if (ex_bits == 8) { + for (size_t i = start; i < d; ++i) { + result += rotated_q[i] * static_cast(ex_code[i]); + } + return result; + } + const unsigned code_mask = (1u << ex_bits) - 1; + for (size_t i = start; i < d; i++) { + const size_t bit_pos = i * ex_bits; + const size_t byte_idx = bit_pos / 8; + const size_t bit_offset = bit_pos % 8; + // With ex_bits <= 8 a code spans at most two bytes. + unsigned raw = ex_code[byte_idx]; + if (bit_offset + ex_bits > 8) { + raw |= static_cast(ex_code[byte_idx + 1]) << 8; + } + const unsigned ex_val = (raw >> bit_offset) & code_mask; + result += rotated_q[i] * static_cast(ex_val); + } + return result; +} + +/// The terms compute_inner_product_with_sign_ip adds to the extra-bit inner +/// product ex_ip. +static inline float add_sign_and_bias_terms( + float ex_ip, + size_t ex_bits, + float cb, + float sign_ip, + float q_sum) { + return static_cast(1u << ex_bits) * sign_ip + ex_ip + cb * q_sum; +} + +template <> +inline float compute_inner_product_with_sign_ip( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits, + float cb, + float sign_ip, + float q_sum) { + const float ex_ip = ex_bits == 0 + ? 0.0f + : ex_ip_scalar(ex_code, rotated_q, 0, d, ex_bits); + return add_sign_and_bias_terms(ex_ip, ex_bits, cb, sign_ip, q_sum); +} + } // namespace faiss::rabitq::multibit diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_aarch64.cpp b/thirdparty/faiss/faiss/utils/simd_impl/distances_aarch64.cpp index 47234aa93..d6da252b7 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_aarch64.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_aarch64.cpp @@ -6,8 +6,7 @@ */ #include - -#ifdef __aarch64__ +#include #include #include @@ -41,6 +40,14 @@ void fvec_madd( c[i] = a[i] + bf * b[i]; } +template <> +float fvec_masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + return masked_sum(x, bits, d); +} + template <> void fvec_L2sqr_ny_transposed( float* dis, @@ -150,5 +157,3 @@ int fvec_madd_and_argmin( } } // namespace faiss - -#endif // __aarch64__ diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp b/thirdparty/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp index ad020cef4..0fed90d8d 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_arm_sve.cpp @@ -758,9 +758,11 @@ size_t fvec_L2sqr_ny_nearest_y_transposed( return current_min_idx; } -template <> -void exhaustive_L2sqr_blas_cmax( - const float* x, +namespace { + +template +void exhaustive_L2sqr_blas_cmax_sve( + QueryTiles& queries, const float* y, size_t d, size_t nx, @@ -779,7 +781,7 @@ void exhaustive_L2sqr_blas_cmax( std::unique_ptr x_norms(new float[nx]); std::unique_ptr del2; - fvec_norms_L2sqr(x_norms.get(), x, d, nx); + queries.prepare_norms(nx, x_norms.get()); const size_t lanes = svcntw(); @@ -795,6 +797,8 @@ void exhaustive_L2sqr_blas_cmax( if (i1 > nx) i1 = nx; + const float* xt = queries.tile(i0, i1, x_norms.get()); + res.begin_multiple(i0, i1); for (size_t j0 = 0; j0 < ny; j0 += bs_y) { @@ -813,7 +817,7 @@ void exhaustive_L2sqr_blas_cmax( &one, y + j0 * d, &di, - x + i0 * d, + xt, &di, &zero, ip_block.get(), @@ -938,4 +942,32 @@ void exhaustive_L2sqr_blas_cmax( } } +} // namespace + +template <> +void exhaustive_L2sqr_blas_cmax( + const float* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp32QueryTiles queries{x, d}; + exhaustive_L2sqr_blas_cmax_sve(queries, y, d, nx, ny, res, y_norms); +} + +template <> +void exhaustive_L2sqr_blas_cmax_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp16QueryTiles queries(x, d, nx); + exhaustive_L2sqr_blas_cmax_sve(queries, y, d, nx, ny, res, y_norms); +} + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_autovec-inl.h b/thirdparty/faiss/faiss/utils/simd_impl/distances_autovec-inl.h index 5c2f9a564..f536c49e3 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_autovec-inl.h +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_autovec-inl.h @@ -208,7 +208,10 @@ float VectorDistance::operator()( float accu = 0; for (size_t i = 0; i < this->d; i++) { float xi = x[i], yi = y[i]; - accu += fabs(xi - yi) / (fabs(xi) + fabs(yi)); + float denominator = fabs(xi) + fabs(yi); + if (denominator != 0.0f) { + accu += fabs(xi - yi) / denominator; + } } return accu; } @@ -230,12 +233,13 @@ template <> float VectorDistance::operator()( const float* x, const float* y) const { + constexpr float kLn2 = 0.6931471805599453f; float accu = 0; for (size_t i = 0; i < this->d; i++) { float xi = x[i], yi = y[i]; float mi = 0.5 * (xi + yi); - float kl1 = -xi * log(mi / xi); - float kl2 = -yi * log(mi / yi); + float kl1 = xi > 0 ? (yi == 0 ? xi * kLn2 : -xi * log(mi / xi)) : 0.0f; + float kl2 = yi > 0 ? (xi == 0 ? yi * kLn2 : -yi * log(mi / yi)) : 0.0f; accu += kl1 + kl2; } return 0.5 * accu; diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_avx2.cpp b/thirdparty/faiss/faiss/utils/simd_impl/distances_avx2.cpp index f7d9711ba..eb74ee367 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_avx2.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_avx2.cpp @@ -6,6 +6,7 @@ */ #include +#include #include @@ -105,6 +106,19 @@ void fvec_madd( } } +template <> +float fvec_masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + return masked_sum(x, bits, d); +} + +// Internal linkage: the same template is compiled with other -m flags in +// the other per-SIMD distances TU, and a shared symbol would let the linker +// hand one level the other's code. +namespace { + template void fvec_L2sqr_ny_y_transposed_D( float* distances, @@ -181,6 +195,8 @@ void fvec_L2sqr_ny_y_transposed_D( } } +} // namespace + template <> void fvec_L2sqr_ny_transposed( float* dis, @@ -199,8 +215,12 @@ void fvec_L2sqr_ny_transposed( switch (d) { DISPATCH(1) DISPATCH(2) + DISPATCH(3) DISPATCH(4) + DISPATCH(6) DISPATCH(8) + DISPATCH(12) + DISPATCH(16) default: return fvec_L2sqr_ny_transposed( dis, x, y, y_sqlen, d, d_offset, ny); @@ -1060,6 +1080,11 @@ size_t fvec_L2sqr_ny_nearest( &fvec_L2sqr_ny_nearest_D8); } +// Internal linkage: the same template is compiled with other -m flags in +// the other per-SIMD distances TU, and a shared symbol would let the linker +// hand one level the other's code. +namespace { + template size_t fvec_L2sqr_ny_nearest_y_transposed_D( float* /*distances_tmp_buffer*/, @@ -1176,6 +1201,8 @@ size_t fvec_L2sqr_ny_nearest_y_transposed_D( return current_min_index; } +} // namespace + template <> size_t fvec_L2sqr_ny_nearest_y_transposed( float* distances_tmp_buffer, @@ -1213,9 +1240,11 @@ int fvec_madd_and_argmin( return fvec_madd_and_argmin_sse(n, a, bf, b, c); } -template <> -void exhaustive_L2sqr_blas_cmax( - const float* x, +namespace { + +template +void exhaustive_L2sqr_blas_cmax_avx2( + QueryTiles& queries, const float* y, size_t d, size_t nx, @@ -1235,7 +1264,7 @@ void exhaustive_L2sqr_blas_cmax( std::unique_ptr x_norms(new float[nx]); std::unique_ptr del2; - fvec_norms_L2sqr(x_norms.get(), x, d, nx); + queries.prepare_norms(nx, x_norms.get()); if (!y_norms) { float* y_norms2 = new float[ny]; @@ -1250,6 +1279,8 @@ void exhaustive_L2sqr_blas_cmax( i1 = nx; } + const float* xt = queries.tile(i0, i1, x_norms.get()); + res.begin_multiple(i0, i1); for (size_t j0 = 0; j0 < ny; j0 += bs_y) { @@ -1269,7 +1300,7 @@ void exhaustive_L2sqr_blas_cmax( &one, y + j0 * d, &di, - x + i0 * d, + xt, &di, &zero, ip_block.get(), @@ -1427,4 +1458,32 @@ void exhaustive_L2sqr_blas_cmax( } } +} // namespace + +template <> +void exhaustive_L2sqr_blas_cmax( + const float* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp32QueryTiles queries{x, d}; + exhaustive_L2sqr_blas_cmax_avx2(queries, y, d, nx, ny, res, y_norms); +} + +template <> +void exhaustive_L2sqr_blas_cmax_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp16QueryTiles queries(x, d, nx); + exhaustive_L2sqr_blas_cmax_avx2(queries, y, d, nx, ny, res, y_norms); +} + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_avx512.cpp b/thirdparty/faiss/faiss/utils/simd_impl/distances_avx512.cpp index 13dd4197d..013a1a43d 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_avx512.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_avx512.cpp @@ -6,6 +6,7 @@ */ #include +#include #include @@ -78,6 +79,19 @@ void fvec_madd( } } +template <> +float fvec_masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + return masked_sum(x, bits, d); +} + +// Internal linkage: the same template is compiled with other -m flags in +// the other per-SIMD distances TU, and a shared symbol would let the linker +// hand one level the other's code. +namespace { + template void fvec_L2sqr_ny_y_transposed_D( float* distances, @@ -151,6 +165,8 @@ void fvec_L2sqr_ny_y_transposed_D( } } +} // namespace + template <> void fvec_L2sqr_ny_transposed( float* dis, @@ -169,8 +185,12 @@ void fvec_L2sqr_ny_transposed( switch (d) { DISPATCH(1) DISPATCH(2) + DISPATCH(3) DISPATCH(4) + DISPATCH(6) DISPATCH(8) + DISPATCH(12) + DISPATCH(16) default: return fvec_L2sqr_ny_transposed( dis, x, y, y_sqlen, d, d_offset, ny); @@ -657,7 +677,7 @@ void fvec_L2sqr_ny( template <> size_t fvec_L2sqr_ny_nearest_D2( - float* distances_tmp_buffer, + float* /*distances_tmp_buffer*/, const float* x, const float* y, size_t ny) { @@ -749,7 +769,7 @@ size_t fvec_L2sqr_ny_nearest_D2( template <> size_t fvec_L2sqr_ny_nearest_D4( - float* distances_tmp_buffer, + float* /*distances_tmp_buffer*/, const float* x, const float* y, size_t ny) { @@ -846,7 +866,7 @@ size_t fvec_L2sqr_ny_nearest_D4( template <> size_t fvec_L2sqr_ny_nearest_D8( - float* distances_tmp_buffer, + float* /*distances_tmp_buffer*/, const float* x, const float* y, size_t ny) { @@ -983,6 +1003,11 @@ size_t fvec_L2sqr_ny_nearest( &fvec_L2sqr_ny_nearest_D8); } +// Internal linkage: the same template is compiled with other -m flags in +// the other per-SIMD distances TU, and a shared symbol would let the linker +// hand one level the other's code. +namespace { + template size_t fvec_L2sqr_ny_nearest_y_transposed_D( float* /* distances_tmp_buffer */, @@ -1096,6 +1121,8 @@ size_t fvec_L2sqr_ny_nearest_y_transposed_D( return current_min_index; } +} // namespace + template <> size_t fvec_L2sqr_ny_nearest_y_transposed( float* distances_tmp_buffer, @@ -1133,9 +1160,11 @@ int fvec_madd_and_argmin( return fvec_madd_and_argmin_sse(n, a, bf, b, c); } -template <> -void exhaustive_L2sqr_blas_cmax( - const float* x, +namespace { + +template +void exhaustive_L2sqr_blas_cmax_avx512( + QueryTiles& queries, const float* y, size_t d, size_t nx, @@ -1154,7 +1183,7 @@ void exhaustive_L2sqr_blas_cmax( std::unique_ptr x_norms(new float[nx]); std::unique_ptr del2; - fvec_norms_L2sqr(x_norms.get(), x, d, nx); + queries.prepare_norms(nx, x_norms.get()); if (!y_norms) { float* y_norms2 = new float[ny]; @@ -1169,6 +1198,8 @@ void exhaustive_L2sqr_blas_cmax( i1 = nx; } + const float* xt = queries.tile(i0, i1, x_norms.get()); + res.begin_multiple(i0, i1); for (size_t j0 = 0; j0 < ny; j0 += bs_y) { @@ -1188,7 +1219,7 @@ void exhaustive_L2sqr_blas_cmax( &one, y + j0 * d, &di, - x + i0 * d, + xt, &di, &zero, ip_block.get(), @@ -1340,4 +1371,32 @@ void exhaustive_L2sqr_blas_cmax( } } +} // namespace + +template <> +void exhaustive_L2sqr_blas_cmax( + const float* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp32QueryTiles queries{x, d}; + exhaustive_L2sqr_blas_cmax_avx512(queries, y, d, nx, ny, res, y_norms); +} + +template <> +void exhaustive_L2sqr_blas_cmax_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms) { + Fp16QueryTiles queries(x, d, nx); + exhaustive_L2sqr_blas_cmax_avx512(queries, y, d, nx, ny, res, y_norms); +} + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv.cpp b/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv.cpp index 0eee6e196..afe1c3375 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv.cpp @@ -9,13 +9,22 @@ #include -#ifdef COMPILE_SIMD_RISCV_RVV - +#include #include #include +#include +#include + namespace faiss { +// Clang rejects a builtin used as a function argument, so wrap the call in a +// lambda. GCC accepts the bare name; the wrapper compiles on both. +#define FAISS_RVV_REDUCE_OP(intrinsic) \ + [](auto value_, auto init_, size_t vl_) { \ + return intrinsic(value_, init_, vl_); \ + } + template static inline float rvv_reduce( Vec value, @@ -38,7 +47,10 @@ static inline size_t rvv_argmin(const float* values, size_t n) { i += vl; } float min_val = rvv_reduce( - vmin, vlmax, __builtin_inff(), __riscv_vfredmin_vs_f32m8_f32m1); + vmin, + vlmax, + __builtin_inff(), + FAISS_RVV_REDUCE_OP(__riscv_vfredmin_vs_f32m8_f32m1)); i = 0; while (i < n) { size_t vl = __riscv_vsetvl_e32m8(n - i); @@ -52,6 +64,126 @@ static inline size_t rvv_argmin(const float* values, size_t n) { return n; } +// Write the ksub table entries of one subquantizer that has dsub = 2. +// The function computes one of these 2 results: +// inner product: out[k] = x0 * c0[k] + x1 * c1[k] +// L2: out[k] = (c0[k] - x0)^2 + (c1[k] - x1)^2 +template +static inline void rvv_pq2_row( + const float* c0, + const float* c1, + float x0, + float x1, + size_t ksub, + size_t vl, + float* out) { + for (size_t k = 0; k < ksub; k += vl) { + vfloat32m1_t vc0 = __riscv_vle32_v_f32m1(c0 + k, vl); + vfloat32m1_t vc1 = __riscv_vle32_v_f32m1(c1 + k, vl); + if constexpr (is_inner_product) { + vfloat32m1_t r = __riscv_vfmacc_vf_f32m1( + __riscv_vfmul_vf_f32m1(vc0, x0, vl), x1, vc1, vl); + __riscv_vse32_v_f32m1(out + k, r, vl); + } else { + vfloat32m1_t d0 = __riscv_vfsub_vf_f32m1(vc0, x0, vl); + vfloat32m1_t d1 = __riscv_vfsub_vf_f32m1(vc1, x1, vl); + d0 = __riscv_vfmul_vv_f32m1(d0, d0, vl); + d1 = __riscv_vfmul_vv_f32m1(d1, d1, vl); + vfloat32m1_t r = __riscv_vfadd_vv_f32m1(d0, d1, vl); + __riscv_vse32_v_f32m1(out + k, r, vl); + } + } +} + +template +static void rvv_pq2_tables( + size_t M, + size_t ksub, + const float* c0_all, + const float* c1_all, + size_t nx, + const float* x, + size_t vl, + float* dis_tables) { + const size_t d = 2 * M; + for (size_t i = 0; i < nx; i++) { + const float* xi = x + i * d; + float* oi = dis_tables + i * M * ksub; + size_t m = 0; + // The loop computes 2 subquantizers per iteration. The 2 computations + // are independent, so the processor can run them at the same time. + for (; m + 1 < M; m += 2) { + rvv_pq2_row( + c0_all + m * ksub, + c1_all + m * ksub, + xi[2 * m], + xi[2 * m + 1], + ksub, + vl, + oi + m * ksub); + rvv_pq2_row( + c0_all + (m + 1) * ksub, + c1_all + (m + 1) * ksub, + xi[2 * (m + 1)], + xi[2 * (m + 1) + 1], + ksub, + vl, + oi + (m + 1) * ksub); + } + // If M is odd, the loop above skips the last subquantizer. This loop + // computes it. + for (; m < M; m++) { + rvv_pq2_row( + c0_all + m * ksub, + c1_all + m * ksub, + xi[2 * m], + xi[2 * m + 1], + ksub, + vl, + oi + m * ksub); + } + } +} + +template <> +void compute_PQ_dis_tables_dsub2( + size_t d, + size_t ksub, + const float* all_centroids, + size_t nx, + const float* x, + bool is_inner_product, + float* dis_tables) { + const size_t M = d / 2; + FAISS_THROW_IF_NOT(ksub % 8 == 0); + + // Separate the centroids into 2 planes. Each plane holds one component of + // every centroid, so a unit-stride load can read the plane. + std::vector c0_all(M * ksub); + std::vector c1_all(M * ksub); + for (size_t m = 0; m < M; m++) { + const float* cm = all_centroids + m * ksub * 2; + float* c0m = c0_all.data() + m * ksub; + float* c1m = c1_all.data() + m * ksub; + for (size_t k = 0; k < ksub; k++) { + c0m[k] = cm[2 * k]; + c1m[k] = cm[2 * k + 1]; + } + } + + // ksub is a power of 2, and ksub is a multiple of 8. Therefore vl divides + // ksub exactly. + const size_t vl = __riscv_vsetvl_e32m1(ksub); + + if (is_inner_product) { + rvv_pq2_tables( + M, ksub, c0_all.data(), c1_all.data(), nx, x, vl, dis_tables); + } else { + rvv_pq2_tables( + M, ksub, c0_all.data(), c1_all.data(), nx, x, vl, dis_tables); + } +} + template <> float fvec_norm_L2sqr(const float* x, size_t d) { size_t vlmax = __riscv_vsetvlmax_e32m8(); @@ -63,7 +195,11 @@ float fvec_norm_L2sqr(const float* x, size_t d) { acc = __riscv_vfmacc_vv_f32m8_tu(acc, vx, vx, vl); i += vl; } - return rvv_reduce(acc, vlmax, 0.0f, __riscv_vfredusum_vs_f32m8_f32m1); + return rvv_reduce( + acc, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m8_f32m1)); } template <> @@ -71,18 +207,7 @@ float fvec_L2sqr( const float* x, const float* y, size_t d) { - size_t vlmax = __riscv_vsetvlmax_e32m8(); - vfloat32m8_t acc = __riscv_vfmv_v_f_f32m8(0.0f, vlmax); - size_t i = 0; - while (i < d) { - size_t vl = __riscv_vsetvl_e32m8(d - i); - vfloat32m8_t vx = __riscv_vle32_v_f32m8(x + i, vl); - vfloat32m8_t vy = __riscv_vle32_v_f32m8(y + i, vl); - vx = __riscv_vfsub_vv_f32m8(vx, vy, vl); - acc = __riscv_vfmacc_vv_f32m8_tu(acc, vx, vx, vl); - i += vl; - } - return rvv_reduce(acc, vlmax, 0.0f, __riscv_vfredusum_vs_f32m8_f32m1); + return rvv_kernel::l2_sqr(x, y, d); } template <> @@ -90,17 +215,7 @@ float fvec_inner_product( const float* x, const float* y, size_t d) { - size_t vlmax = __riscv_vsetvlmax_e32m8(); - vfloat32m8_t acc = __riscv_vfmv_v_f_f32m8(0.0f, vlmax); - size_t i = 0; - while (i < d) { - size_t vl = __riscv_vsetvl_e32m8(d - i); - vfloat32m8_t vx = __riscv_vle32_v_f32m8(x + i, vl); - vfloat32m8_t vy = __riscv_vle32_v_f32m8(y + i, vl); - acc = __riscv_vfmacc_vv_f32m8_tu(acc, vx, vy, vl); - i += vl; - } - return rvv_reduce(acc, vlmax, 0.0f, __riscv_vfredusum_vs_f32m8_f32m1); + return rvv_kernel::inner_product(x, y, d); } template <> @@ -117,7 +232,11 @@ float fvec_L1(const float* x, const float* y, size_t d) { acc = __riscv_vfadd_vv_f32m8_tu(acc, acc, vx, vl); i += vl; } - return rvv_reduce(acc, vlmax, 0.0f, __riscv_vfredusum_vs_f32m8_f32m1); + return rvv_reduce( + acc, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m8_f32m1)); } template <> @@ -137,7 +256,11 @@ float fvec_Linf( vmax = __riscv_vfmax_vv_f32m8_tu(vmax, vmax, vx, vl); i += vl; } - return rvv_reduce(vmax, vlmax, 0.0f, __riscv_vfredmax_vs_f32m8_f32m1); + return rvv_reduce( + vmax, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredmax_vs_f32m8_f32m1)); } template <> @@ -171,10 +294,26 @@ void fvec_inner_product_batch_4( vacc3 = __riscv_vfmacc_vv_f32m4_tu(vacc3, vx, vy, vl); i += vl; } - dis0 = rvv_reduce(vacc0, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis1 = rvv_reduce(vacc1, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis2 = rvv_reduce(vacc2, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis3 = rvv_reduce(vacc3, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); + dis0 = rvv_reduce( + vacc0, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis1 = rvv_reduce( + vacc1, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis2 = rvv_reduce( + vacc2, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis3 = rvv_reduce( + vacc3, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); } template <> @@ -212,10 +351,26 @@ void fvec_L2sqr_batch_4( vacc3 = __riscv_vfmacc_vv_f32m4_tu(vacc3, vy, vy, vl); i += vl; } - dis0 = rvv_reduce(vacc0, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis1 = rvv_reduce(vacc1, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis2 = rvv_reduce(vacc2, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); - dis3 = rvv_reduce(vacc3, vlmax, 0.0f, __riscv_vfredusum_vs_f32m4_f32m1); + dis0 = rvv_reduce( + vacc0, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis1 = rvv_reduce( + vacc1, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis2 = rvv_reduce( + vacc2, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); + dis3 = rvv_reduce( + vacc3, + vlmax, + 0.0f, + FAISS_RVV_REDUCE_OP(__riscv_vfredusum_vs_f32m4_f32m1)); } template <> @@ -227,31 +382,56 @@ void fvec_L2sqr_ny_transposed( size_t d, size_t d_offset, size_t ny) { - size_t vlmax = __riscv_vsetvlmax_e32m8(); - vfloat32m8_t acc = __riscv_vfmv_v_f_f32m8(0.0f, vlmax); + // Compute the squared length of the query subvector. + float x_sqlen = 0; + for (size_t j = 0; j < d; j++) { + x_sqlen += x[j] * x[j]; + } + + // The loop below divides the ny dimension into chunks. Each chunk uses + // e32m8. The chunk size is VLMAX, so the kernel fills the whole vector + // register at every VLEN. + const size_t chunk = __riscv_vsetvlmax_e32m8(); size_t i = 0; - while (i < d) { - size_t vl = __riscv_vsetvl_e32m8(d - i); - vfloat32m8_t vx = __riscv_vle32_v_f32m8(x + i, vl); - acc = __riscv_vfmacc_vv_f32m8_tu(acc, vx, vx, vl); - i += vl; + + // dis[i] = x_sqlen + y_sqlen[i] - 2 * sum_j x[j] * y[j * d_offset + i] + // + // The code accumulates the dot product first, and it applies the factor + // of 2 afterwards. Matches SIMDLevel::NONE implementation which scales the + // accumulated dot product in the same way. + for (; i + chunk <= ny; i += chunk) { + vfloat32m8_t dp = __riscv_vfmv_v_f_f32m8(0.0f, chunk); + for (size_t j = 0; j < d; j++) { + vfloat32m8_t y_vec = + __riscv_vle32_v_f32m8(y + j * d_offset + i, chunk); + dp = __riscv_vfmacc_vf_f32m8(dp, x[j], y_vec, chunk); + } + + vfloat32m8_t acc = __riscv_vle32_v_f32m8(y_sqlen + i, chunk); + acc = __riscv_vfadd_vf_f32m8(acc, x_sqlen, chunk); + dp = __riscv_vfmul_vf_f32m8(dp, 2.0f, chunk); + acc = __riscv_vfsub_vv_f32m8(acc, dp, chunk); + + __riscv_vse32_v_f32m8(dis + i, acc, chunk); } - float x_sqlen = - rvv_reduce(acc, vlmax, 0.0f, __riscv_vfredusum_vs_f32m8_f32m1); - i = 0; - while (i < ny) { + + // This block computes the last ny % chunk elements. + if (i < ny) { size_t vl = __riscv_vsetvl_e32m8(ny - i); - acc = __riscv_vfmv_v_f_f32m8(0.0f, vl); + + vfloat32m8_t dp = __riscv_vfmv_v_f_f32m8(0.0f, vl); for (size_t j = 0; j < d; j++) { - vfloat32m8_t vy = __riscv_vle32_v_f32m8(y + j * d_offset + i, vl); - acc = __riscv_vfmacc_vf_f32m8(acc, x[j], vy, vl); + vfloat32m8_t y_vec = + __riscv_vle32_v_f32m8(y + j * d_offset + i, vl); + dp = __riscv_vfmacc_vf_f32m8(dp, x[j], y_vec, vl); } - vfloat32m8_t vres = __riscv_vle32_v_f32m8(y_sqlen + i, vl); - vres = __riscv_vfadd_vf_f32m8(vres, x_sqlen, vl); - acc = __riscv_vfmul_vf_f32m8(acc, 2.0f, vl); - vres = __riscv_vfsub_vv_f32m8(vres, acc, vl); - __riscv_vse32_v_f32m8(dis + i, vres, vl); - i += vl; + + vfloat32m8_t acc = __riscv_vle32_v_f32m8(y_sqlen + i, vl); + acc = __riscv_vfadd_vf_f32m8(acc, x_sqlen, vl); + dp = __riscv_vfmul_vf_f32m8(dp, 2.0f, vl); + acc = __riscv_vfsub_vv_f32m8(acc, dp, vl); + + __riscv_vse32_v_f32m8(dis + i, acc, vl); } } @@ -262,9 +442,40 @@ void fvec_inner_products_ny( const float* y, size_t d, size_t ny) { - for (size_t i = 0; i < ny; i++) { - ip[i] = fvec_inner_product(x, y, d); - y += d; + // The loop below divides the ny dimension into chunks. Each chunk uses + // e32m4. + // ip[i] = sum_{j=0}^{d-1} x[j] * y[i * d + j] + const size_t chunk = __riscv_vsetvlmax_e32m4(); + const ptrdiff_t stride_bytes = (ptrdiff_t)d * (ptrdiff_t)sizeof(float); + size_t i = 0; + + for (; i + chunk <= ny; i += chunk) { + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, chunk); + const float* yb = y + i * d; // the first vector of this chunk + + for (size_t j = 0; j < d; j++) { + vfloat32m4_t y_vec = + __riscv_vlse32_v_f32m4(yb + j, stride_bytes, chunk); + acc = __riscv_vfmacc_vf_f32m4(acc, x[j], y_vec, chunk); + } + + __riscv_vse32_v_f32m4(ip + i, acc, chunk); + } + + // This block computes the last ny % chunk elements. + if (i < ny) { + size_t vl = __riscv_vsetvl_e32m4(ny - i); + + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vl); + const float* yb = y + i * d; + + for (size_t j = 0; j < d; j++) { + vfloat32m4_t y_vec = + __riscv_vlse32_v_f32m4(yb + j, stride_bytes, vl); + acc = __riscv_vfmacc_vf_f32m4(acc, x[j], y_vec, vl); + } + + __riscv_vse32_v_f32m4(ip + i, acc, vl); } } @@ -275,9 +486,35 @@ void fvec_L2sqr_ny( const float* y, size_t d, size_t ny) { - for (size_t i = 0; i < ny; i++) { - dis[i] = fvec_L2sqr(x, y, d); - y += d; + // The loop below divides the ny dimension into chunks. Each chunk uses + // e32m8. + const size_t chunk = __riscv_vsetvlmax_e32m8(); + const ptrdiff_t stride_bytes = (ptrdiff_t)d * (ptrdiff_t)sizeof(float); + size_t i = 0; + + for (; i + chunk <= ny; i += chunk) { + vfloat32m8_t acc = __riscv_vfmv_v_f_f32m8(0.0f, chunk); + const float* yb = y + i * d; // the first vector of this chunk + for (size_t j = 0; j < d; j++) { + vfloat32m8_t y_vec = + __riscv_vlse32_v_f32m8(yb + j, stride_bytes, chunk); + vfloat32m8_t diff = __riscv_vfsub_vf_f32m8(y_vec, x[j], chunk); + acc = __riscv_vfmacc_vv_f32m8(acc, diff, diff, chunk); + } + __riscv_vse32_v_f32m8(dis + i, acc, chunk); + } + + if (i < ny) { + size_t vl = __riscv_vsetvl_e32m8(ny - i); + vfloat32m8_t acc = __riscv_vfmv_v_f_f32m8(0.0f, vl); + const float* yb = y + i * d; + for (size_t j = 0; j < d; j++) { + vfloat32m8_t y_vec = + __riscv_vlse32_v_f32m8(yb + j, stride_bytes, vl); + vfloat32m8_t diff = __riscv_vfsub_vf_f32m8(y_vec, x[j], vl); + acc = __riscv_vfmacc_vv_f32m8(acc, diff, diff, vl); + } + __riscv_vse32_v_f32m8(dis + i, acc, vl); } } @@ -288,9 +525,8 @@ size_t fvec_L2sqr_ny_nearest( const float* y, size_t d, size_t ny) { - fvec_L2sqr_ny(distances_tmp_buffer, x, y, d, ny); - const size_t j = rvv_argmin(distances_tmp_buffer, ny); - return j < ny ? j : 0; + return fvec_L2sqr_ny_nearest( + distances_tmp_buffer, x, y, d, ny); } template <> @@ -302,10 +538,8 @@ size_t fvec_L2sqr_ny_nearest_y_transposed( size_t d, size_t d_offset, size_t ny) { - fvec_L2sqr_ny_transposed( + return fvec_L2sqr_ny_nearest_y_transposed( distances_tmp_buffer, x, y, y_sqlen, d, d_offset, ny); - const size_t j = rvv_argmin(distances_tmp_buffer, ny); - return j < ny ? j : 0; } template <> @@ -338,6 +572,56 @@ int fvec_madd_and_argmin( return j < n ? static_cast(j) : -1; } +template <> +void fvec_add( + size_t d, + const float* a, + const float* b, + float* c) { + size_t i = 0; + while (i < d) { + size_t vl = __riscv_vsetvl_e32m8(d - i); + vfloat32m8_t va = __riscv_vle32_v_f32m8(a + i, vl); + vfloat32m8_t vb = __riscv_vle32_v_f32m8(b + i, vl); + va = __riscv_vfadd_vv_f32m8(va, vb, vl); + __riscv_vse32_v_f32m8(c + i, va, vl); + i += vl; + } +} + +template <> +void fvec_add( + size_t d, + const float* a, + float b, + float* c) { + size_t i = 0; + while (i < d) { + size_t vl = __riscv_vsetvl_e32m8(d - i); + vfloat32m8_t va = __riscv_vle32_v_f32m8(a + i, vl); + va = __riscv_vfadd_vf_f32m8(va, b, vl); + __riscv_vse32_v_f32m8(c + i, va, vl); + i += vl; + } +} + +template <> +void fvec_sub( + size_t d, + const float* a, + const float* b, + float* c) { + size_t i = 0; + while (i < d) { + size_t vl = __riscv_vsetvl_e32m8(d - i); + vfloat32m8_t va = __riscv_vle32_v_f32m8(a + i, vl); + vfloat32m8_t vb = __riscv_vle32_v_f32m8(b + i, vl); + va = __riscv_vfsub_vv_f32m8(va, vb, vl); + __riscv_vse32_v_f32m8(c + i, va, vl); + i += vl; + } +} + #define DEFINE_VECTOR_DISTANCE_RVV_FALLBACK(metric) \ template <> \ float VectorDistance::operator()( \ @@ -365,5 +649,3 @@ DEFINE_VECTOR_DISTANCE_RVV_FALLBACK(METRIC_GOWER) #define THE_SIMD_LEVEL SIMDLevel::RISCV_RVV // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv_kernel.h b/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv_kernel.h new file mode 100644 index 000000000..4cd429924 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_rvv_kernel.h @@ -0,0 +1,68 @@ +/* + * 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. + */ + +#pragma once + +/* Vector-to-vector distance kernels for RISC-V Vector. + * + * Free-standing (no exceptions, heap or threads), so a freestanding RISC-V + * target can compile it. distances_rvv.cpp calls these; no Buck target here + * builds that RISC-V CPU path. + * + * These inline the horizontal reduction rather than passing the intrinsic to + * a helper. Clang rejects a builtin used as a function argument. + * + * They accumulate at LMUL 4, not 8: a group of eight leaves only four + * register groups, which is slower in a scan loop. The order of the + * additions differs from LMUL 8, so the last bits can differ. + + */ + +#include + +#include + +namespace faiss { +namespace rvv_kernel { + +/// Squared L2 distance between two fp32 vectors. +inline float l2_sqr(const float* x, const float* y, size_t d) { + const size_t vlmax = __riscv_vsetvlmax_e32m4(); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + size_t i = 0; + while (i < d) { + const size_t vl = __riscv_vsetvl_e32m4(d - i); + vfloat32m4_t vx = __riscv_vle32_v_f32m4(x + i, vl); + vfloat32m4_t vy = __riscv_vle32_v_f32m4(y + i, vl); + vx = __riscv_vfsub_vv_f32m4(vx, vy, vl); + acc = __riscv_vfmacc_vv_f32m4_tu(acc, vx, vx, vl); + i += vl; + } + vfloat32m1_t init = __riscv_vfmv_s_f_f32m1(0.0f, 1); + vfloat32m1_t r = __riscv_vfredusum_vs_f32m4_f32m1(acc, init, vlmax); + return __riscv_vfmv_f_s_f32m1_f32(r); +} + +/// Inner product of two fp32 vectors. +inline float inner_product(const float* x, const float* y, size_t d) { + const size_t vlmax = __riscv_vsetvlmax_e32m4(); + vfloat32m4_t acc = __riscv_vfmv_v_f_f32m4(0.0f, vlmax); + size_t i = 0; + while (i < d) { + const size_t vl = __riscv_vsetvl_e32m4(d - i); + vfloat32m4_t vx = __riscv_vle32_v_f32m4(x + i, vl); + vfloat32m4_t vy = __riscv_vle32_v_f32m4(y + i, vl); + acc = __riscv_vfmacc_vv_f32m4_tu(acc, vx, vy, vl); + i += vl; + } + vfloat32m1_t init = __riscv_vfmv_s_f_f32m1(0.0f, 1); + vfloat32m1_t r = __riscv_vfredusum_vs_f32m4_f32m1(acc, init, vlmax); + return __riscv_vfmv_f_s_f32m1_f32(r); +} + +} // namespace rvv_kernel +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/distances_simdlib256.h b/thirdparty/faiss/faiss/utils/simd_impl/distances_simdlib256.h index 67f169a3c..4fff1074a 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/distances_simdlib256.h +++ b/thirdparty/faiss/faiss/utils/simd_impl/distances_simdlib256.h @@ -149,14 +149,14 @@ void compute_PQ_dis_tables_dsub2( FAISS_THROW_IF_NOT(ksub % 8 == 0); for (size_t m0 = 0; m0 < M; m0 += 4) { - int m1 = std::min(M, m0 + 4); - for (int k0 = 0; k0 < ksub; k0 += 8) { + size_t m1 = std::min(M, m0 + 4); + for (size_t k0 = 0; k0 < ksub; k0 += 8) { simd8float32_tpl centroids[8]; for (int k = 0; k < 8; k++) { ALIGNED(32) float centroid[8]; size_t wp = 0; size_t rp = (m0 * ksub + k + k0) * 2; - for (int m = m0; m < m1; m++) { + for (size_t m = m0; m < m1; m++) { centroid[wp++] = all_centroids[rp]; centroid[wp++] = all_centroids[rp + 1]; rp += 2 * ksub; diff --git a/thirdparty/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h b/thirdparty/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h index 021d50133..e84269f78 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h +++ b/thirdparty/faiss/faiss/utils/simd_impl/exhaustive_L2sqr_blas_cmax.h @@ -7,11 +7,93 @@ #pragma once +#include +#include +#include +#include + #include +#include #include +#include namespace faiss { +/** fp32 query tiles for the BLAS exhaustive-search kernels. + * + * A kernel calls prepare_norms() once, then tile(i0, i1, x_norms) for each + * query tile; the returned rows stay valid until the next tile() call. + */ +struct Fp32QueryTiles { + const float* x; + size_t d; + + /// squared L2 norms of all nx queries + void prepare_norms(size_t nx, float* x_norms) const { + fvec_norms_L2sqr(x_norms, x, d, nx); + } + + const float* tile(size_t i0, size_t /*i1*/, float* /*x_norms*/) const { + return x + i0 * d; + } +}; + +/** Packed IEEE binary16 query tiles for the BLAS exhaustive-search kernels. + * + * Queries are widened in chunks of whole tiles (at most chunk_bytes of fp32, + * at least one tile) into a buffer reused across chunks: the fp32 copy stays + * bounded and each widened tile serves all database tiles. Norms are computed + * from the widened rows, so results match the fp32 kernels on the widened + * queries. + */ +struct Fp16QueryTiles { + static constexpr size_t chunk_bytes = size_t(16) << 20; + + const uint16_t* x; + size_t d; + size_t nx; + std::unique_ptr buffer; + size_t chunk_rows = 0; + size_t chunk_begin = 0; + size_t chunk_end = 0; + + Fp16QueryTiles(const uint16_t* x_in, size_t d_in, size_t nx_in) + : x(x_in), d(d_in), nx(nx_in) {} + + void prepare_norms(size_t /*nx*/, float* /*x_norms*/) const {} + + /** widened rows [i0, i1), and their norms if x_norms is not null + * + * Tiles are requested in order, all of the same size except the last. + */ + const float* tile(size_t i0, size_t i1, float* x_norms) { + if (i1 > chunk_end) { + if (!buffer) { + const size_t tile_rows = i1 - i0; + chunk_rows = + tile_rows * + std::max( + 1, + chunk_bytes / (tile_rows * d * sizeof(float))); + chunk_rows = std::min(chunk_rows, nx - i0); + buffer.reset(new float[chunk_rows * d]); + } + chunk_begin = i0; + chunk_end = std::min(nx, i0 + chunk_rows); + const int64_t n = static_cast(chunk_end - chunk_begin); +#pragma omp parallel for if (n * static_cast(d) > (1 << 16)) + for (int64_t i = 0; i < n; i++) { + float* row = buffer.get() + i * d; + fp16_to_fp32(d, x + (chunk_begin + i) * d, row); + if (x_norms) { + x_norms[chunk_begin + i] = fvec_norm_L2sqr(row, d); + } + } + } + return buffer.get() + (i0 - chunk_begin) * d; + } +}; + /// BLAS-accelerated exhaustive L2 search for the k=1 (top-1) case. /// Specializations live in the per-SIMD translation units under simd_impl/. template @@ -24,4 +106,15 @@ void exhaustive_L2sqr_blas_cmax( Top1BlockResultHandler>& res, const float* y_norms); +/// Same as exhaustive_L2sqr_blas_cmax for packed IEEE binary16 queries. +template +void exhaustive_L2sqr_blas_cmax_fp16( + const uint16_t* x, + const float* y, + size_t d, + size_t nx, + size_t ny, + Top1BlockResultHandler>& res, + const float* y_norms); + } // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels.h b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels.h new file mode 100644 index 000000000..b813ea166 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels.h @@ -0,0 +1,76 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include +#include + +namespace faiss { +namespace detail { + +// c[j] += fp32(x[j]) * w for j < d +template +inline void fp16_madd(size_t d, const uint16_t* x, float w, float* c) { + for (size_t j = 0; j < d; ++j) { + c[j] += decode_fp16(x[j]) * w; + } +} + +template +inline void fp16_to_fp32_kernel(size_t n, const uint16_t* x, float* out) { + for (size_t j = 0; j < n; ++j) { + out[j] = decode_fp16(x[j]); + } +} + +#ifdef COMPILE_SIMD_AVX2 +template <> +void fp16_madd(size_t d, const uint16_t* x, float w, float* c); + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out); +#endif + +#ifdef COMPILE_SIMD_AVX512 +template <> +void fp16_madd( + size_t d, + const uint16_t* x, + float w, + float* c); + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out); +#endif + +#ifdef COMPILE_SIMD_ARM_NEON +template <> +void fp16_madd( + size_t d, + const uint16_t* x, + float w, + float* c); + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out); +#endif + +} // namespace detail +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp new file mode 100644 index 000000000..774ff2b09 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx2.cpp @@ -0,0 +1,52 @@ +/* + * 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. + */ + +#include + +#include + +namespace faiss { +namespace detail { + +template <> +void fp16_madd( + size_t d, + const uint16_t* x, + float w, + float* c) { + const __m256 wv = _mm256_set1_ps(w); + size_t j = 0; + for (; j + 8 <= d; j += 8) { + const __m256 xv = _mm256_cvtph_ps( + _mm_loadu_si128(reinterpret_cast(x + j))); + _mm256_storeu_ps( + c + j, + _mm256_add_ps(_mm256_loadu_ps(c + j), _mm256_mul_ps(xv, wv))); + } + for (; j < d; ++j) { + c[j] += decode_fp16(x[j]) * w; + } +} + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out) { + size_t j = 0; + for (; j + 8 <= n; j += 8) { + const __m128i h = + _mm_loadu_si128(reinterpret_cast(x + j)); + _mm256_storeu_ps(out + j, _mm256_cvtph_ps(h)); + } + for (; j < n; ++j) { + out[j] = decode_fp16(x[j]); + } +} + +} // namespace detail +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp new file mode 100644 index 000000000..a320f1b6a --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_avx512.cpp @@ -0,0 +1,52 @@ +/* + * 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. + */ + +#include + +#include + +namespace faiss { +namespace detail { + +template <> +void fp16_madd( + size_t d, + const uint16_t* x, + float w, + float* c) { + const __m512 wv = _mm512_set1_ps(w); + size_t j = 0; + for (; j + 16 <= d; j += 16) { + const __m512 xv = _mm512_cvtph_ps( + _mm256_loadu_si256(reinterpret_cast(x + j))); + _mm512_storeu_ps( + c + j, + _mm512_add_ps(_mm512_loadu_ps(c + j), _mm512_mul_ps(xv, wv))); + } + for (; j < d; ++j) { + c[j] += decode_fp16(x[j]) * w; + } +} + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out) { + size_t j = 0; + for (; j + 16 <= n; j += 16) { + const __m256i h = + _mm256_loadu_si256(reinterpret_cast(x + j)); + _mm512_storeu_ps(out + j, _mm512_cvtph_ps(h)); + } + for (; j < n; ++j) { + out[j] = decode_fp16(x[j]); + } +} + +} // namespace detail +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp new file mode 100644 index 000000000..57b447647 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/fp16_kernels_neon.cpp @@ -0,0 +1,48 @@ +/* + * 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. + */ + +#include + +#include + +namespace faiss { +namespace detail { + +template <> +void fp16_madd( + size_t d, + const uint16_t* x, + float w, + float* c) { + const float32x4_t wv = vdupq_n_f32(w); + size_t j = 0; + for (; j + 4 <= d; j += 4) { + const float32x4_t xv = + vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16(x + j))); + vst1q_f32(c + j, vaddq_f32(vld1q_f32(c + j), vmulq_f32(xv, wv))); + } + for (; j < d; ++j) { + c[j] += decode_fp16(x[j]) * w; + } +} + +template <> +void fp16_to_fp32_kernel( + size_t n, + const uint16_t* x, + float* out) { + size_t j = 0; + for (; j + 4 <= n; j += 4) { + vst1q_f32(out + j, vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16(x + j)))); + } + for (; j < n; ++j) { + out[j] = decode_fp16(x[j]); + } +} + +} // namespace detail +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx2.h b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx2.h new file mode 100644 index 000000000..5c4de02db --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx2.h @@ -0,0 +1,44 @@ +/* + * 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. + */ + +#pragma once + +#include + +#include + +namespace faiss { +namespace { + +template <> +inline float masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + const __m256i bit_masks = _mm256_set_epi32(128, 64, 32, 16, 8, 4, 2, 1); + __m256 acc = _mm256_setzero_ps(); + const size_t full_bytes = d / 8; + for (size_t byte_idx = 0; byte_idx < full_bytes; byte_idx++) { + const __m256i byte_broadcast = _mm256_set1_epi32(bits[byte_idx]); + const __m256i masked = _mm256_and_si256(byte_broadcast, bit_masks); + const __m256 mask = + _mm256_castsi256_ps(_mm256_cmpeq_epi32(masked, bit_masks)); + const __m256 vals = _mm256_loadu_ps(x + byte_idx * 8); + acc = _mm256_add_ps(acc, _mm256_and_ps(mask, vals)); + } + __m128 sum128 = _mm_add_ps( + _mm256_castps256_ps128(acc), _mm256_extractf128_ps(acc, 1)); + __m128 shuf = _mm_movehdup_ps(sum128); + __m128 sums = _mm_add_ps(sum128, shuf); + shuf = _mm_movehl_ps(shuf, sums); + sums = _mm_add_ss(sums, shuf); + return _mm_cvtss_f32(sums) + + masked_sum_scalar(x + full_bytes * 8, bits + full_bytes, d % 8); +} + +} // namespace +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx512.h b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx512.h new file mode 100644 index 000000000..26993bb60 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum-avx512.h @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#pragma once + +#include + +#include + +#include + +namespace faiss { +namespace { + +template <> +inline float masked_sum( + const float* x, + const uint8_t* bits, + size_t d) { + __m512 acc = _mm512_setzero_ps(); + size_t i = 0; + for (; i + 16 <= d; i += 16) { + uint16_t mask16; + memcpy(&mask16, bits + i / 8, sizeof(mask16)); + acc = _mm512_mask_add_ps(acc, mask16, acc, _mm512_loadu_ps(x + i)); + } + if (i < d) { + uint32_t mask = bits[i / 8]; + if (d - i > 8) { + mask |= uint32_t(bits[i / 8 + 1]) << 8; + } + const __mmask16 k = mask & ((1u << (d - i)) - 1); + acc = _mm512_add_ps(acc, _mm512_maskz_loadu_ps(k, x + i)); + } + return _mm512_reduce_add_ps(acc); +} + +} // namespace +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/masked_sum.h b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum.h new file mode 100644 index 000000000..9a6e51259 --- /dev/null +++ b/thirdparty/faiss/faiss/utils/simd_impl/masked_sum.h @@ -0,0 +1,38 @@ +/* + * 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. + */ + +#pragma once + +#include +#include + +#include + +namespace faiss { + +// Internal linkage: each file compiles these with its own flags. +// masked_sum-avx2.h and masked_sum-avx512.h specialize masked_sum. +namespace { + +inline float masked_sum_scalar(const float* x, const uint8_t* bits, size_t d) { + float sum = 0; + for (size_t j = 0; j < d; j++) { + if ((bits[j / 8] >> (j % 8)) & 1) { + sum += x[j]; + } + } + return sum; +} + +template +inline float masked_sum(const float* x, const uint8_t* bits, size_t d) { + return masked_sum_scalar(x, bits, d); +} + +} // namespace + +} // namespace faiss diff --git a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp index 197097eba..bd4f49df4 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_avx2.cpp @@ -5,10 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #define THE_SIMD_LEVEL SIMDLevel::AVX2 // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_neon.cpp b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_neon.cpp index c8bb7bda1..d16304769 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_neon.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_neon.cpp @@ -5,10 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_NEON - #define THE_SIMD_LEVEL SIMDLevel::ARM_NEON // NOLINTNEXTLINE(facebook-hte-InlineHeader) #include - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h index a86f3ac70..2fc4cbfc4 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h +++ b/thirdparty/faiss/faiss/utils/simd_impl/partitioning_simdlib256.h @@ -66,6 +66,21 @@ using simd8float32 = simd8float32_tpl; * SIMD routines when vals is an aligned array of uint16_t ******************************************************************/ +// Forward declarations of histogram functions defined below, outside +// simd_partitioning +void local_simd_histogram_8( + const uint16_t* data, + int n, + uint16_t min, + int shift, + int* hist); +void local_simd_histogram_16( + const uint16_t* data, + int n, + uint16_t min, + int shift, + int* hist); + namespace simd_partitioning { void find_minimax( @@ -338,7 +353,7 @@ uint16_t simd_partition_fuzzy_with_bounds( IFV printf( " override: thresh=%d n_eq_1=%" PRId64 "\n", thresh, n_eq_1); } else { - assert(n_eq_1 <= n_eq); + assert(static_cast(n_eq_1) <= n_eq); } size_t wp = simd_compress_array(vals, ids, n, thresh, n_eq_1); @@ -357,20 +372,6 @@ uint16_t simd_partition_fuzzy_with_bounds( return thresh; } -// Forward declarations of histogram functions defined below -void local_simd_histogram_8( - const uint16_t* data, - int n, - uint16_t min, - int shift, - int* hist); -void local_simd_histogram_16( - const uint16_t* data, - int n, - uint16_t min, - int shift, - int* hist); - template uint16_t simd_partition_fuzzy_with_bounds_histogram( uint16_t* vals, diff --git a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp index b33316a4a..cc947a934 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx2.cpp @@ -5,8 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - +#include #include #include #include @@ -250,7 +249,7 @@ uint64_t bitwise_and_dot_product( __m256i sum_256 = _mm256_setzero_si256(); for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); @@ -264,7 +263,7 @@ uint64_t bitwise_and_dot_product( __m128i sum_128 = _mm_setzero_si128(); for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); @@ -277,7 +276,7 @@ uint64_t bitwise_and_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv & yv) << j; @@ -285,7 +284,7 @@ uint64_t bitwise_and_dot_product( } for (; offset < size; ++offset) { const uint8_t yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const uint8_t qv = *(query + j * size + offset); sum += popcount32(qv & yv) << j; } @@ -309,7 +308,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); pop_256 = _mm256_add_epi64(pop_256, popcount_256(v_x)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); @@ -326,7 +325,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); pop_128 = _mm_add_epi64(pop_128, popcount_128(v_x)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); @@ -341,7 +340,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); popcount_sum += popcount64(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); dot_product += popcount64(qv & yv) << j; @@ -350,7 +349,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset < size; ++offset) { const uint8_t yv = *(data + offset); popcount_sum += popcount32(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const uint8_t qv = *(query + j * size + offset); dot_product += popcount32(qv & yv) << j; } @@ -370,7 +369,7 @@ uint64_t bitwise_xor_dot_product( __m256i sum_256 = _mm256_setzero_si256(); for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_xor = _mm256_xor_si256(v_q, v_x); @@ -384,7 +383,7 @@ uint64_t bitwise_xor_dot_product( __m128i sum_128 = _mm_setzero_si128(); for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_xor = _mm_xor_si128(v_q, v_x); @@ -397,7 +396,7 @@ uint64_t bitwise_xor_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv ^ yv) << j; @@ -405,7 +404,7 @@ uint64_t bitwise_xor_dot_product( } for (; offset < size; ++offset) { const auto yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); sum += popcount32(qv ^ yv) << j; } @@ -524,13 +523,44 @@ inline float ip_1exbit_avx2( return result; } -#if defined(__GNUC__) && defined(__x86_64__) -#define FAISS_RABITQ_BMI2_TARGET __attribute__((target("bmi2"), noinline)) -#elif defined(__BMI2__) -#define FAISS_RABITQ_BMI2_TARGET -#endif -#ifdef FAISS_RABITQ_BMI2_TARGET -FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx2( +/// Bit-plane extraction for ex_bits in [2, 7]: plane b of 8 codes packed in +/// a uint64 is _pext_u64(codes, masks[b]), and has weight 2^b. +struct BitplaneTablesAVX2 { + uint64_t masks[7]; + __m256 weights[8]; ///< weights[ex_bits] = 2^ex_bits, for the sign bit + + explicit BitplaneTablesAVX2(size_t ex_bits) { + for (size_t b = 0; b < ex_bits; b++) { + uint64_t m = 0; + for (int j = 0; j < 8; j++) { + m |= (1ULL << (b + j * ex_bits)); + } + masks[b] = m; + weights[b] = _mm256_set1_ps(static_cast(1u << b)); + } + weights[ex_bits] = _mm256_set1_ps(static_cast(1u << ex_bits)); + } +}; + +/// recon plus the extra-bit values of the 8 codes packed in ex64 +inline __m256 add_bitplanes_avx2( + __m256 recon, + uint64_t ex64, + const BitplaneTablesAVX2& t, + size_t ex_bits) { + const __m256i bit_pos = _mm256_setr_epi32(1, 2, 4, 8, 16, 32, 64, 128); + const __m256i zero = _mm256_setzero_si256(); + for (size_t b = 0; b < ex_bits; b++) { + auto plane = static_cast(_pext_u64(ex64, t.masks[b])); + __m256i p_cmp = _mm256_cmpgt_epi32( + _mm256_and_si256(_mm256_set1_epi32(plane), bit_pos), zero); + recon = _mm256_add_ps( + recon, _mm256_and_ps(_mm256_castsi256_ps(p_cmp), t.weights[b])); + } + return recon; +} + +inline float ip_bitplane_avx2( const uint8_t* __restrict sign_bits, const uint8_t* __restrict ex_code, const float* __restrict rotated_q, @@ -538,42 +568,22 @@ FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx2( size_t ex_bits, float cb) { __m256 acc = _mm256_setzero_ps(); - const __m256 v_one = _mm256_set1_ps(1.0f); const __m256i bit_pos = _mm256_setr_epi32(1, 2, 4, 8, 16, 32, 64, 128); const __m256i zero = _mm256_setzero_si256(); const __m256 v_cb = _mm256_set1_ps(cb); - - uint64_t pext_masks[7]; - __m256 v_weights[8]; - for (size_t b = 0; b < ex_bits; b++) { - uint64_t m = 0; - for (int j = 0; j < 8; j++) { - m |= (1ULL << (b + j * ex_bits)); - } - pext_masks[b] = m; - v_weights[b] = _mm256_set1_ps(static_cast(1u << b)); - } - v_weights[ex_bits] = _mm256_set1_ps(static_cast(1u << ex_bits)); + const BitplaneTablesAVX2 tables(ex_bits); size_t i = 0; for (; i + 8 <= d; i += 8) { __m256i sb_cmp = _mm256_cmpgt_epi32( _mm256_and_si256(_mm256_set1_epi32(sign_bits[i / 8]), bit_pos), zero); - __m256 recon = _mm256_mul_ps( - _mm256_and_ps(_mm256_castsi256_ps(sb_cmp), v_one), - v_weights[ex_bits]); + __m256 recon = _mm256_and_ps( + _mm256_castsi256_ps(sb_cmp), tables.weights[ex_bits]); uint64_t ex64 = 0; memcpy(&ex64, ex_code + (i / 8) * ex_bits, sizeof(uint64_t)); - - for (size_t b = 0; b < ex_bits; b++) { - auto plane = static_cast(_pext_u64(ex64, pext_masks[b])); - __m256i p_cmp = _mm256_cmpgt_epi32( - _mm256_and_si256(_mm256_set1_epi32(plane), bit_pos), zero); - __m256 p_f = _mm256_and_ps(_mm256_castsi256_ps(p_cmp), v_one); - recon = _mm256_fmadd_ps(p_f, v_weights[b], recon); - } + recon = add_bitplanes_avx2(recon, ex64, tables, ex_bits); __m256 rq = _mm256_loadu_ps(rotated_q + i); acc = _mm256_fmadd_ps(rq, _mm256_add_ps(recon, v_cb), acc); @@ -583,7 +593,62 @@ FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx2( result += ip_scalar(sign_bits, ex_code, rotated_q, i, d, ex_bits, cb); return result; } -#endif // __BMI2__ + +// sum_i rotated_q[i] * ex_code[i] for one-byte extra codes. +inline float ex_ip_8bit_avx2( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d) { + __m256 acc0 = _mm256_setzero_ps(); + __m256 acc1 = _mm256_setzero_ps(); + size_t i = 0; + for (; i + 16 <= d; i += 16) { + const __m128i bytes = + _mm_loadu_si128(reinterpret_cast(ex_code + i)); + acc0 = _mm256_fmadd_ps( + _mm256_loadu_ps(rotated_q + i), + _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)), + acc0); + acc1 = _mm256_fmadd_ps( + _mm256_loadu_ps(rotated_q + i + 8), + _mm256_cvtepi32_ps( + _mm256_cvtepu8_epi32(_mm_srli_si128(bytes, 8))), + acc1); + } + for (; i + 8 <= d; i += 8) { + const __m128i bytes = + _mm_loadl_epi64(reinterpret_cast(ex_code + i)); + acc0 = _mm256_fmadd_ps( + _mm256_loadu_ps(rotated_q + i), + _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)), + acc0); + } + return hsum_avx2(_mm256_add_ps(acc0, acc1)) + + ex_ip_scalar(ex_code, rotated_q, i, d, 8); +} + +// sum_i rotated_q[i] * ex_i for ex_bits in [2, 7]: ip_bitplane_avx2 without +// the sign bits, and without reading past the codes. +inline float ex_ip_bitplane_avx2( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits) { + __m256 acc = _mm256_setzero_ps(); + const BitplaneTablesAVX2 tables(ex_bits); + + const size_t total_bytes = (d * ex_bits + 7) / 8; + size_t i = 0; + for (; i + 8 <= d; i += 8) { + const uint64_t ex64 = + load_ex_code_window(ex_code, (i / 8) * ex_bits, total_bytes); + const __m256 recon = + add_bitplanes_avx2(_mm256_setzero_ps(), ex64, tables, ex_bits); + acc = _mm256_fmadd_ps(_mm256_loadu_ps(rotated_q + i), recon, acc); + } + + return hsum_avx2(acc) + ex_ip_scalar(ex_code, rotated_q, i, d, ex_bits); +} } // namespace @@ -597,51 +662,73 @@ float compute_inner_product( float cb) { if (ex_bits == 8) { // Eight byte-aligned extra codes, plus their independent sign bits. - __m256 acc = _mm256_setzero_ps(); + // One sign-word broadcast serves 32 dims, to save shuffle-port uops. + __m256 acc0 = _mm256_setzero_ps(); + __m256 acc1 = _mm256_setzero_ps(); const __m256 weight = _mm256_set1_ps(256.f); const __m256 offset = _mm256_set1_ps(cb); const __m256i positions = _mm256_setr_epi32(1, 2, 4, 8, 16, 32, 64, 128); - size_t i = 0; - for (; i + 8 <= d; i += 8) { + // cmpeq, not cmpgt: bit 31 of the shifted positions is a sign bit. + auto step = [&](__m256& acc, size_t i, __m256i signs, __m256i pos) { const __m128i bytes = _mm_loadl_epi64( reinterpret_cast(ex_code + i)); const __m256 extra = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)); - const __m256i mask = _mm256_cmpgt_epi32( - _mm256_and_si256( - _mm256_set1_epi32(sign_bits[i / 8]), positions), - _mm256_setzero_si256()); + const __m256i mask = + _mm256_cmpeq_epi32(_mm256_and_si256(signs, pos), pos); const __m256 recon = _mm256_add_ps( extra, _mm256_and_ps(_mm256_castsi256_ps(mask), weight)); acc = _mm256_fmadd_ps( _mm256_loadu_ps(rotated_q + i), _mm256_add_ps(recon, offset), acc); + }; + size_t i = 0; + for (; i + 32 <= d; i += 32) { + uint32_t word; + memcpy(&word, sign_bits + i / 8, sizeof(word)); + const __m256i signs = _mm256_set1_epi32(static_cast(word)); + step(acc0, i, signs, positions); + step(acc1, i + 8, signs, _mm256_slli_epi32(positions, 8)); + step(acc0, i + 16, signs, _mm256_slli_epi32(positions, 16)); + step(acc1, i + 24, signs, _mm256_slli_epi32(positions, 24)); } - return hsum_avx2(acc) + + for (; i + 8 <= d; i += 8) { + step(acc0, i, _mm256_set1_epi32(sign_bits[i / 8]), positions); + } + return hsum_avx2(_mm256_add_ps(acc0, acc1)) + ip_scalar(sign_bits, ex_code, rotated_q, i, d, ex_bits, cb); } if (ex_bits == 1) { return ip_1exbit_avx2(sign_bits, ex_code, rotated_q, d, cb); } -#ifdef FAISS_RABITQ_BMI2_TARGET - bool has_bmi2 = true; -#if defined(__GNUC__) && defined(__x86_64__) - has_bmi2 = __builtin_cpu_supports("bmi2"); -#endif - if (ex_bits <= 7 && has_bmi2) { + if (ex_bits <= 7) { return ip_bitplane_avx2(sign_bits, ex_code, rotated_q, d, ex_bits, cb); } -#endif return ip_scalar(sign_bits, ex_code, rotated_q, 0, d, ex_bits, cb); } -} // namespace faiss::rabitq::multibit - -#endif // COMPILE_SIMD_AVX2 +template <> +float compute_inner_product_with_sign_ip( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits, + float cb, + float sign_ip, + float q_sum) { + float ex_ip = 0.0f; + if (ex_bits == 8) { + ex_ip = ex_ip_8bit_avx2(ex_code, rotated_q, d); + } else if (ex_bits == 1) { + // One extra bit per dim has the sign-bit layout. + ex_ip = fvec_masked_sum(rotated_q, ex_code, d); + } else if (ex_bits >= 2 && ex_bits <= 7) { + ex_ip = ex_ip_bitplane_avx2(ex_code, rotated_q, d, ex_bits); + } + return add_sign_and_bias_terms(ex_ip, ex_bits, cb, sign_ip, q_sum); +} -#ifdef FAISS_RABITQ_BMI2_TARGET -#undef FAISS_RABITQ_BMI2_TARGET -#endif +} // namespace faiss::rabitq::multibit diff --git a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp index b1213c992..19b5d5a55 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512.cpp @@ -5,8 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - +#include #include #include #include @@ -338,7 +337,7 @@ uint64_t bitwise_and_dot_product( __m512i sum_512 = _mm512_setzero_si512(); for (; offset + step <= size; offset += step) { __m512i v_x = _mm512_loadu_si512((const __m512i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m512i v_q = _mm512_loadu_si512( (const __m512i*)(query + j * size + offset)); __m512i v_and = _mm512_and_si512(v_q, v_x); @@ -353,7 +352,7 @@ uint64_t bitwise_and_dot_product( __m256i sum_256 = _mm256_setzero_si256(); for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); @@ -367,7 +366,7 @@ uint64_t bitwise_and_dot_product( __m128i sum_128 = _mm_setzero_si128(); for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); @@ -380,7 +379,7 @@ uint64_t bitwise_and_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv & yv) << j; @@ -388,7 +387,7 @@ uint64_t bitwise_and_dot_product( } for (; offset < size; ++offset) { const auto yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); sum += popcount32(qv & yv) << j; } @@ -412,7 +411,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset + step <= size; offset += step) { __m512i v_x = _mm512_loadu_si512((const __m512i*)(data + offset)); pop_512 = _mm512_add_epi64(pop_512, popcount_512(v_x)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m512i v_q = _mm512_loadu_si512( (const __m512i*)(query + j * size + offset)); __m512i v_and = _mm512_and_si512(v_q, v_x); @@ -430,7 +429,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); pop_256 = _mm256_add_epi64(pop_256, popcount_256(v_x)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); @@ -447,7 +446,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); pop_128 = _mm_add_epi64(pop_128, popcount_128(v_x)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); @@ -462,7 +461,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); popcount_sum += popcount64(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); dot_product += popcount64(qv & yv) << j; @@ -471,7 +470,7 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< for (; offset < size; ++offset) { const auto yv = *(data + offset); popcount_sum += popcount32(yv); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); dot_product += popcount32(qv & yv) << j; } @@ -491,7 +490,7 @@ uint64_t bitwise_xor_dot_product( __m512i sum_512 = _mm512_setzero_si512(); for (; offset + step <= size; offset += step) { __m512i v_x = _mm512_loadu_si512((const __m512i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m512i v_q = _mm512_loadu_si512( (const __m512i*)(query + j * size + offset)); __m512i v_xor = _mm512_xor_si512(v_q, v_x); @@ -506,7 +505,7 @@ uint64_t bitwise_xor_dot_product( __m256i sum_256 = _mm256_setzero_si256(); for (; offset + step <= size; offset += step) { __m256i v_x = _mm256_loadu_si256((const __m256i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m256i v_q = _mm256_loadu_si256( (const __m256i*)(query + j * size + offset)); __m256i v_xor = _mm256_xor_si256(v_q, v_x); @@ -520,7 +519,7 @@ uint64_t bitwise_xor_dot_product( __m128i sum_128 = _mm_setzero_si128(); for (size_t step = 128 / 8; offset + step <= size; offset += step) { __m128i v_x = _mm_loadu_si128((const __m128i*)(data + offset)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { __m128i v_q = _mm_loadu_si128( (const __m128i*)(query + j * size + offset)); __m128i v_xor = _mm_xor_si128(v_q, v_x); @@ -533,7 +532,7 @@ uint64_t bitwise_xor_dot_product( for (size_t step = 64 / 8; offset + step <= size; offset += step) { uint64_t yv; std::memcpy(&yv, data + offset, sizeof(yv)); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { uint64_t qv; std::memcpy(&qv, query + j * size + offset, sizeof(qv)); sum += popcount64(qv ^ yv) << j; @@ -541,7 +540,7 @@ uint64_t bitwise_xor_dot_product( } for (; offset < size; ++offset) { const auto yv = *(data + offset); - for (int j = 0; j < qb; j++) { + for (size_t j = 0; j < qb; j++) { const auto qv = *(query + j * size + offset); sum += popcount32(qv ^ yv) << j; } @@ -661,19 +660,47 @@ inline float ip_1exbit_avx512( return result; } -// Needs BMI2 for _pext_u64. Some AVX2 CPUs lack it, and FAISS_BMI2_FLAGS can -// be empty, so the dispatcher falls back to the scalar path without it. -#if defined(__GNUC__) && defined(__x86_64__) -#define FAISS_RABITQ_BMI2_TARGET __attribute__((target("bmi2"), noinline)) -#elif defined(__BMI2__) -#define FAISS_RABITQ_BMI2_TARGET -#endif -#ifdef FAISS_RABITQ_BMI2_TARGET -// Bitplane kernel for ex_bits >= 2, 16 dims per iteration. A bitplane is -// already a bitmask, so it goes into a mask register and one masked add -// applies its weight. Reads of ex_code run a few bytes past the ex-code -// section into the record's own trailing factors, so they stay in bounds. -FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx512( +/// Bit-plane extraction for ex_bits in [2, 7]: plane b of 8 codes packed in +/// a uint64 is _pext_u64(codes, masks[b]), and has weight 2^b. +struct BitplaneTablesAVX512 { + uint64_t masks[7]; + __m512 weights[8]; ///< weights[ex_bits] = 2^ex_bits, for the sign bit + + explicit BitplaneTablesAVX512(size_t ex_bits) { + for (size_t b = 0; b < ex_bits; b++) { + uint64_t m = 0; + for (int j = 0; j < 8; j++) { + m |= (1ULL << (b + j * ex_bits)); + } + masks[b] = m; + weights[b] = _mm512_set1_ps(static_cast(1u << b)); + } + weights[ex_bits] = _mm512_set1_ps(static_cast(1u << ex_bits)); + } +}; + +/// recon plus the extra-bit values of 16 codes, the first 8 packed in lo64 +/// and the next 8 in hi64 +inline __m512 add_bitplanes_avx512( + __m512 recon, + uint64_t lo64, + uint64_t hi64, + const BitplaneTablesAVX512& t, + size_t ex_bits) { + for (size_t b = 0; b < ex_bits; b++) { + const uint32_t plane = + static_cast(_pext_u64(lo64, t.masks[b])) | + (static_cast(_pext_u64(hi64, t.masks[b])) << 8); + recon = _mm512_mask_add_ps( + recon, static_cast<__mmask16>(plane), recon, t.weights[b]); + } + return recon; +} + +// Bit-plane kernel for ex_bits >= 2. It scores 16 dims per pass. +// Each plane acts as a mask for one weighted add. Reads can run +// past the codes into the row tail, which stays in bounds. +inline float ip_bitplane_avx512( const uint8_t* __restrict sign_bits, const uint8_t* __restrict ex_code, const float* __restrict rotated_q, @@ -682,39 +709,20 @@ FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx512( float cb) { __m512 acc = _mm512_setzero_ps(); const __m512 v_cb = _mm512_set1_ps(cb); - - uint64_t pext_masks[7]; - __m512 v_weights[8]; - for (size_t b = 0; b < ex_bits; b++) { - uint64_t m = 0; - for (int j = 0; j < 8; j++) { - m |= (1ULL << (b + j * ex_bits)); - } - pext_masks[b] = m; - v_weights[b] = _mm512_set1_ps(static_cast(1u << b)); - } - v_weights[ex_bits] = _mm512_set1_ps(static_cast(1u << ex_bits)); + const BitplaneTablesAVX512 tables(ex_bits); size_t i = 0; for (; i + 16 <= d; i += 16) { uint16_t sb = 0; memcpy(&sb, sign_bits + (i / 8), sizeof(uint16_t)); __m512 recon = _mm512_maskz_mov_ps( - static_cast<__mmask16>(sb), v_weights[ex_bits]); + static_cast<__mmask16>(sb), tables.weights[ex_bits]); uint64_t lo64 = 0; uint64_t hi64 = 0; memcpy(&lo64, ex_code + (i / 8) * ex_bits, sizeof(uint64_t)); memcpy(&hi64, ex_code + ((i / 8) + 1) * ex_bits, sizeof(uint64_t)); - - for (size_t b = 0; b < ex_bits; b++) { - const uint32_t plane = - static_cast(_pext_u64(lo64, pext_masks[b])) | - (static_cast(_pext_u64(hi64, pext_masks[b])) - << 8); - recon = _mm512_mask_add_ps( - recon, static_cast<__mmask16>(plane), recon, v_weights[b]); - } + recon = add_bitplanes_avx512(recon, lo64, hi64, tables, ex_bits); __m512 rq = _mm512_loadu_ps(rotated_q + i); acc = _mm512_fmadd_ps(rq, _mm512_add_ps(recon, v_cb), acc); @@ -727,17 +735,12 @@ FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx512( if (i + 8 <= d) { const __mmask16 low8 = static_cast<__mmask16>(0x00ff); __m512 recon = _mm512_maskz_mov_ps( - static_cast<__mmask16>(sign_bits[i / 8]), v_weights[ex_bits]); + static_cast<__mmask16>(sign_bits[i / 8]), + tables.weights[ex_bits]); uint64_t lo64 = 0; memcpy(&lo64, ex_code + (i / 8) * ex_bits, sizeof(uint64_t)); - - for (size_t b = 0; b < ex_bits; b++) { - const uint32_t plane = - static_cast(_pext_u64(lo64, pext_masks[b])); - recon = _mm512_mask_add_ps( - recon, static_cast<__mmask16>(plane), recon, v_weights[b]); - } + recon = add_bitplanes_avx512(recon, lo64, 0, tables, ex_bits); __m512 rq = _mm512_maskz_loadu_ps(low8, rotated_q + i); acc = _mm512_fmadd_ps( @@ -749,7 +752,82 @@ FAISS_RABITQ_BMI2_TARGET float ip_bitplane_avx512( result += ip_scalar(sign_bits, ex_code, rotated_q, i, d, ex_bits, cb); return result; } -#endif // __BMI2__ + +// sum_i rotated_q[i] * ex_code[i] for one-byte extra codes. Two accumulators, +// so that consecutive FMAs do not wait on each other. +inline float ex_ip_8bit_avx512( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d) { + __m512 acc0 = _mm512_setzero_ps(); + __m512 acc1 = _mm512_setzero_ps(); + auto step = [&](__m512& acc, size_t i) { + const __m128i bytes = + _mm_loadu_si128(reinterpret_cast(ex_code + i)); + acc = _mm512_fmadd_ps( + _mm512_loadu_ps(rotated_q + i), + _mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(bytes)), + acc); + }; + size_t i = 0; + for (; i + 32 <= d; i += 32) { + step(acc0, i); + step(acc1, i + 16); + } + if (i + 16 <= d) { + step(acc0, i); + i += 16; + } + // Half-width step: the upper 8 lanes see zero codes and a masked load. + if (i + 8 <= d) { + const __m128i bytes = + _mm_loadl_epi64(reinterpret_cast(ex_code + i)); + acc1 = _mm512_fmadd_ps( + _mm512_maskz_loadu_ps(0x00ff, rotated_q + i), + _mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(bytes)), + acc1); + i += 8; + } + return _mm512_reduce_add_ps(_mm512_add_ps(acc0, acc1)) + + ex_ip_scalar(ex_code, rotated_q, i, d, 8); +} + +// sum_i rotated_q[i] * ex_i for ex_bits in [2, 7]: ip_bitplane_avx512 +// without the sign bits, and without reading past the codes. +inline float ex_ip_bitplane_avx512( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits) { + __m512 acc = _mm512_setzero_ps(); + const BitplaneTablesAVX512 tables(ex_bits); + + const size_t total_bytes = (d * ex_bits + 7) / 8; + size_t i = 0; + for (; i + 16 <= d; i += 16) { + const uint64_t lo64 = + load_ex_code_window(ex_code, (i / 8) * ex_bits, total_bytes); + const uint64_t hi64 = load_ex_code_window( + ex_code, ((i / 8) + 1) * ex_bits, total_bytes); + const __m512 recon = add_bitplanes_avx512( + _mm512_setzero_ps(), lo64, hi64, tables, ex_bits); + acc = _mm512_fmadd_ps(_mm512_loadu_ps(rotated_q + i), recon, acc); + } + + // Half-width step, as in ip_bitplane_avx512. + if (i + 8 <= d) { + const uint64_t lo64 = + load_ex_code_window(ex_code, (i / 8) * ex_bits, total_bytes); + const __m512 recon = add_bitplanes_avx512( + _mm512_setzero_ps(), lo64, 0, tables, ex_bits); + acc = _mm512_fmadd_ps( + _mm512_maskz_loadu_ps(0x00ff, rotated_q + i), recon, acc); + i += 8; + } + + return _mm512_reduce_add_ps(acc) + + ex_ip_scalar(ex_code, rotated_q, i, d, ex_bits); +} } // namespace @@ -786,23 +864,32 @@ float compute_inner_product( return ip_1exbit_avx512(sign_bits, ex_code, rotated_q, d, cb); } -#ifdef FAISS_RABITQ_BMI2_TARGET - bool has_bmi2 = true; -#if defined(__GNUC__) && defined(__x86_64__) - has_bmi2 = __builtin_cpu_supports("bmi2"); -#endif - if (ex_bits <= 7 && has_bmi2) { + if (ex_bits <= 7) { return ip_bitplane_avx512( sign_bits, ex_code, rotated_q, d, ex_bits, cb); } -#endif return ip_scalar(sign_bits, ex_code, rotated_q, 0, d, ex_bits, cb); } -} // namespace faiss::rabitq::multibit - -#endif // COMPILE_SIMD_AVX512 +template <> +float compute_inner_product_with_sign_ip( + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + size_t ex_bits, + float cb, + float sign_ip, + float q_sum) { + float ex_ip = 0.0f; + if (ex_bits == 8) { + ex_ip = ex_ip_8bit_avx512(ex_code, rotated_q, d); + } else if (ex_bits == 1) { + // One extra bit per dim has the sign-bit layout. + ex_ip = fvec_masked_sum(rotated_q, ex_code, d); + } else if (ex_bits >= 2 && ex_bits <= 7) { + ex_ip = ex_ip_bitplane_avx512(ex_code, rotated_q, d, ex_bits); + } + return add_sign_and_bias_terms(ex_ip, ex_bits, cb, sign_ip, q_sum); +} -#ifdef FAISS_RABITQ_BMI2_TARGET -#undef FAISS_RABITQ_BMI2_TARGET -#endif +} // namespace faiss::rabitq::multibit diff --git a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512_vpopcnt.cpp b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512_vpopcnt.cpp index 4b1ed598b..16b534f32 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512_vpopcnt.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_avx512_vpopcnt.cpp @@ -30,8 +30,6 @@ * the AVX512 implementation to avoid duplicating that code path. */ -#ifdef COMPILE_SIMD_AVX512_VPOPCNT - #include #include #include @@ -151,8 +149,8 @@ uint64_t bitwise_and_dot_product( __m512i v_x = _mm512_loadu_si512( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m512i v_q = - _mm512_loadu_si512(reinterpret_cast( + __m512i v_q = _mm512_loadu_si512( + reinterpret_cast( query + j * size + offset)); __m512i v_and = _mm512_and_si512(v_q, v_x); __m512i v_popcnt = popcount_512_vpopcntdq(v_and); @@ -170,8 +168,8 @@ uint64_t bitwise_and_dot_product( __m256i v_x = _mm256_loadu_si256( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m256i v_q = - _mm256_loadu_si256(reinterpret_cast( + __m256i v_q = _mm256_loadu_si256( + reinterpret_cast( query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); __m256i v_popcnt = popcount_256_vpopcntdq(v_and); @@ -188,8 +186,9 @@ uint64_t bitwise_and_dot_product( __m128i v_x = _mm_loadu_si128( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m128i v_q = _mm_loadu_si128(reinterpret_cast( - query + j * size + offset)); + __m128i v_q = _mm_loadu_si128( + reinterpret_cast( + query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); __m128i v_popcnt = popcount_128_vpopcntdq(v_and); __m128i v_shifted = _mm_slli_epi64(v_popcnt, j); @@ -238,8 +237,8 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< reinterpret_cast(data + offset)); pop_512 = _mm512_add_epi64(pop_512, popcount_512_vpopcntdq(v_x)); for (size_t j = 0; j < qb; j++) { - __m512i v_q = - _mm512_loadu_si512(reinterpret_cast( + __m512i v_q = _mm512_loadu_si512( + reinterpret_cast( query + j * size + offset)); __m512i v_and = _mm512_and_si512(v_q, v_x); __m512i v_popcnt = popcount_512_vpopcntdq(v_and); @@ -259,8 +258,8 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< reinterpret_cast(data + offset)); pop_256 = _mm256_add_epi64(pop_256, popcount_256_vpopcntdq(v_x)); for (size_t j = 0; j < qb; j++) { - __m256i v_q = - _mm256_loadu_si256(reinterpret_cast( + __m256i v_q = _mm256_loadu_si256( + reinterpret_cast( query + j * size + offset)); __m256i v_and = _mm256_and_si256(v_q, v_x); __m256i v_popcnt = popcount_256_vpopcntdq(v_and); @@ -279,8 +278,9 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< reinterpret_cast(data + offset)); pop_128 = _mm_add_epi64(pop_128, popcount_128_vpopcntdq(v_x)); for (size_t j = 0; j < qb; j++) { - __m128i v_q = _mm_loadu_si128(reinterpret_cast( - query + j * size + offset)); + __m128i v_q = _mm_loadu_si128( + reinterpret_cast( + query + j * size + offset)); __m128i v_and = _mm_and_si128(v_q, v_x); __m128i v_popcnt = popcount_128_vpopcntdq(v_and); __m128i v_shifted = _mm_slli_epi64(v_popcnt, j); @@ -326,8 +326,8 @@ uint64_t bitwise_xor_dot_product( __m512i v_x = _mm512_loadu_si512( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m512i v_q = - _mm512_loadu_si512(reinterpret_cast( + __m512i v_q = _mm512_loadu_si512( + reinterpret_cast( query + j * size + offset)); __m512i v_xor = _mm512_xor_si512(v_q, v_x); __m512i v_popcnt = popcount_512_vpopcntdq(v_xor); @@ -344,8 +344,8 @@ uint64_t bitwise_xor_dot_product( __m256i v_x = _mm256_loadu_si256( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m256i v_q = - _mm256_loadu_si256(reinterpret_cast( + __m256i v_q = _mm256_loadu_si256( + reinterpret_cast( query + j * size + offset)); __m256i v_xor = _mm256_xor_si256(v_q, v_x); __m256i v_popcnt = popcount_256_vpopcntdq(v_xor); @@ -361,8 +361,9 @@ uint64_t bitwise_xor_dot_product( __m128i v_x = _mm_loadu_si128( reinterpret_cast(data + offset)); for (size_t j = 0; j < qb; j++) { - __m128i v_q = _mm_loadu_si128(reinterpret_cast( - query + j * size + offset)); + __m128i v_q = _mm_loadu_si128( + reinterpret_cast( + query + j * size + offset)); __m128i v_xor = _mm_xor_si128(v_q, v_x); __m128i v_popcnt = popcount_128_vpopcntdq(v_xor); __m128i v_shifted = _mm_slli_epi64(v_popcnt, j); @@ -466,5 +467,3 @@ float compute_inner_product( } } // namespace faiss::rabitq::multibit - -#endif // COMPILE_SIMD_AVX512_VPOPCNT diff --git a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_neon.cpp b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_neon.cpp index 6294aa5f2..0d11cdfa9 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_neon.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_neon.cpp @@ -7,17 +7,78 @@ #include -#ifdef COMPILE_SIMD_ARM_NEON +#include + +#include + +#include namespace faiss::rabitq { +namespace { + +// One accumulator per query bit plane. RaBitQuantizer caps qb at 8, so the +// accumulator arrays below are fixed size rather than heap allocated. +constexpr size_t kMaxQueryBits = 8; + +inline uint32x4_t accumulate_popcount(uint32x4_t acc, uint8x16_t value) { + const uint16x8_t pair_counts = vpaddlq_u8(vcntq_u8(value)); + return vpadalq_u16(acc, pair_counts); +} + +inline uint64_t reduce_popcount(uint32x4_t acc) { + return vaddlvq_u32(acc); +} + +} // namespace + template <> uint64_t bitwise_and_dot_product( const uint8_t* query, const uint8_t* data, size_t size, size_t qb) { - return bitwise_and_dot_product(query, data, size, qb); + FAISS_THROW_IF_NOT(qb <= kMaxQueryBits); + std::array accumulators; + for (size_t j = 0; j < qb; j++) { + accumulators[j] = vdupq_n_u32(0); + } + + size_t offset = 0; + for (; offset + 16 <= size; offset += 16) { + const uint8x16_t value = vld1q_u8(data + offset); + for (size_t j = 0; j < qb; j++) { + const uint8x16_t query_value = vld1q_u8(query + j * size + offset); + accumulators[j] = accumulate_popcount( + accumulators[j], vandq_u8(query_value, value)); + } + } + + uint64_t result = 0; + for (size_t j = 0; j < qb; j++) { + result += reduce_popcount(accumulators[j]) << j; + } + for (; offset + 8 <= size; offset += 8) { + uint64_t value; + memcpy(&value, data + offset, sizeof(value)); + for (size_t j = 0; j < qb; j++) { + uint64_t query_value; + memcpy(&query_value, + query + j * size + offset, + sizeof(query_value)); + result += static_cast(popcount64(query_value & value)) + << j; + } + } + for (; offset < size; offset++) { + const uint8_t value = data[offset]; + for (size_t j = 0; j < qb; j++) { + result += static_cast( + popcount32(query[j * size + offset] & value)) + << j; + } + } + return result; } template <> @@ -27,8 +88,52 @@ BitwiseAndDotProductResult bitwise_and_dot_product_with_popcount< const uint8_t* data, size_t size, size_t qb) { - return bitwise_and_dot_product_with_popcount( - query, data, size, qb); + FAISS_THROW_IF_NOT(qb <= kMaxQueryBits); + std::array dot_accumulators; + for (size_t j = 0; j < qb; j++) { + dot_accumulators[j] = vdupq_n_u32(0); + } + uint32x4_t popcount_accumulator = vdupq_n_u32(0); + + size_t offset = 0; + for (; offset + 16 <= size; offset += 16) { + const uint8x16_t value = vld1q_u8(data + offset); + popcount_accumulator = accumulate_popcount(popcount_accumulator, value); + for (size_t j = 0; j < qb; j++) { + const uint8x16_t query_value = vld1q_u8(query + j * size + offset); + dot_accumulators[j] = accumulate_popcount( + dot_accumulators[j], vandq_u8(query_value, value)); + } + } + + uint64_t dot_product = 0; + for (size_t j = 0; j < qb; j++) { + dot_product += reduce_popcount(dot_accumulators[j]) << j; + } + uint64_t popcount_sum = reduce_popcount(popcount_accumulator); + for (; offset + 8 <= size; offset += 8) { + uint64_t value; + memcpy(&value, data + offset, sizeof(value)); + popcount_sum += popcount64(value); + for (size_t j = 0; j < qb; j++) { + uint64_t query_value; + memcpy(&query_value, + query + j * size + offset, + sizeof(query_value)); + dot_product += + static_cast(popcount64(query_value & value)) << j; + } + } + for (; offset < size; offset++) { + const uint8_t value = data[offset]; + popcount_sum += popcount32(value); + for (size_t j = 0; j < qb; j++) { + dot_product += static_cast( + popcount32(query[j * size + offset] & value)) + << j; + } + } + return {dot_product, popcount_sum}; } template <> @@ -37,18 +142,185 @@ uint64_t bitwise_xor_dot_product( const uint8_t* data, size_t size, size_t qb) { - return bitwise_xor_dot_product(query, data, size, qb); + FAISS_THROW_IF_NOT(qb <= kMaxQueryBits); + std::array accumulators; + for (size_t j = 0; j < qb; j++) { + accumulators[j] = vdupq_n_u32(0); + } + + size_t offset = 0; + for (; offset + 16 <= size; offset += 16) { + const uint8x16_t value = vld1q_u8(data + offset); + for (size_t j = 0; j < qb; j++) { + const uint8x16_t query_value = vld1q_u8(query + j * size + offset); + accumulators[j] = accumulate_popcount( + accumulators[j], veorq_u8(query_value, value)); + } + } + + uint64_t result = 0; + for (size_t j = 0; j < qb; j++) { + result += reduce_popcount(accumulators[j]) << j; + } + for (; offset + 8 <= size; offset += 8) { + uint64_t value; + memcpy(&value, data + offset, sizeof(value)); + for (size_t j = 0; j < qb; j++) { + uint64_t query_value; + memcpy(&query_value, + query + j * size + offset, + sizeof(query_value)); + result += static_cast(popcount64(query_value ^ value)) + << j; + } + } + for (; offset < size; offset++) { + const uint8_t value = data[offset]; + for (size_t j = 0; j < qb; j++) { + result += static_cast( + popcount32(query[j * size + offset] ^ value)) + << j; + } + } + return result; } template <> uint64_t popcount(const uint8_t* data, size_t size) { - return popcount(data, size); + uint32x4_t accumulator = vdupq_n_u32(0); + size_t offset = 0; + for (; offset + 16 <= size; offset += 16) { + accumulator = accumulate_popcount(accumulator, vld1q_u8(data + offset)); + } + + uint64_t result = reduce_popcount(accumulator); + for (; offset + 8 <= size; offset += 8) { + uint64_t value; + memcpy(&value, data + offset, sizeof(value)); + result += popcount64(value); + } + for (; offset < size; offset++) { + result += popcount32(data[offset]); + } + return result; } } // namespace faiss::rabitq namespace faiss::rabitq::multibit { +namespace { + +inline float horizontal_sum(float32x4_t low, float32x4_t high) { + return vaddvq_f32(vaddq_f32(low, high)); +} + +inline float ip_1exbit_neon( + const uint8_t* __restrict sign_bits, + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + float cb) { + const uint32x4_t low_bit_positions = {1, 2, 4, 8}; + const uint32x4_t high_bit_positions = {16, 32, 64, 128}; + const uint32x4_t sign_weight = vdupq_n_u32(2); + const uint32x4_t ex_weight = vdupq_n_u32(1); + const float32x4_t bias = vdupq_n_f32(cb); + float32x4_t low_accumulator = vdupq_n_f32(0.0f); + float32x4_t high_accumulator = vdupq_n_f32(0.0f); + + size_t i = 0; + for (; i + 8 <= d; i += 8) { + const uint32x4_t sign = vdupq_n_u32(sign_bits[i / 8]); + const uint32x4_t extra = vdupq_n_u32(ex_code[i / 8]); + + const uint32x4_t low_values = vaddq_u32( + vandq_u32(vtstq_u32(sign, low_bit_positions), sign_weight), + vandq_u32(vtstq_u32(extra, low_bit_positions), ex_weight)); + const uint32x4_t high_values = vaddq_u32( + vandq_u32(vtstq_u32(sign, high_bit_positions), sign_weight), + vandq_u32(vtstq_u32(extra, high_bit_positions), ex_weight)); + + const float32x4_t low_reconstruction = + vaddq_f32(vcvtq_f32_u32(low_values), bias); + const float32x4_t high_reconstruction = + vaddq_f32(vcvtq_f32_u32(high_values), bias); + low_accumulator = vfmaq_f32( + low_accumulator, vld1q_f32(rotated_q + i), low_reconstruction); + high_accumulator = vfmaq_f32( + high_accumulator, + vld1q_f32(rotated_q + i + 4), + high_reconstruction); + } + + float result = horizontal_sum(low_accumulator, high_accumulator); + result += ip_scalar(sign_bits, ex_code, rotated_q, i, d, 1, cb); + return result; +} + +template +inline float ip_multibit_neon( + const uint8_t* __restrict sign_bits, + const uint8_t* __restrict ex_code, + const float* __restrict rotated_q, + size_t d, + float cb) { + static_assert(ExBits >= 2 && ExBits <= 7); + const uint32x4_t low_bit_positions = {1, 2, 4, 8}; + const uint32x4_t high_bit_positions = {16, 32, 64, 128}; + const uint32x4_t sign_weight = + vdupq_n_u32(static_cast(1u << ExBits)); + const uint64x2_t code_mask = + vdupq_n_u64(static_cast((1u << ExBits) - 1)); + constexpr int64_t bit_width = static_cast(ExBits); + const int64x2_t shifts_01 = {0, -bit_width}; + const int64x2_t shifts_23 = {-2 * bit_width, -3 * bit_width}; + const int64x2_t shifts_45 = {-4 * bit_width, -5 * bit_width}; + const int64x2_t shifts_67 = {-6 * bit_width, -7 * bit_width}; + const float32x4_t bias = vdupq_n_f32(cb); + float32x4_t low_accumulator = vdupq_n_f32(0.0f); + float32x4_t high_accumulator = vdupq_n_f32(0.0f); + + size_t i = 0; + for (; i + 8 <= d; i += 8) { + uint64_t packed_codes = 0; + memcpy(&packed_codes, ex_code + (i / 8) * ExBits, ExBits); + const uint64x2_t packed = vdupq_n_u64(packed_codes); + + const uint32x4_t low_codes = vcombine_u32( + vmovn_u64(vandq_u64(vshlq_u64(packed, shifts_01), code_mask)), + vmovn_u64(vandq_u64(vshlq_u64(packed, shifts_23), code_mask))); + const uint32x4_t high_codes = vcombine_u32( + vmovn_u64(vandq_u64(vshlq_u64(packed, shifts_45), code_mask)), + vmovn_u64(vandq_u64(vshlq_u64(packed, shifts_67), code_mask))); + + const uint32x4_t sign = vdupq_n_u32(sign_bits[i / 8]); + const uint32x4_t low_values = vaddq_u32( + low_codes, + vandq_u32(vtstq_u32(sign, low_bit_positions), sign_weight)); + const uint32x4_t high_values = vaddq_u32( + high_codes, + vandq_u32(vtstq_u32(sign, high_bit_positions), sign_weight)); + + const float32x4_t low_reconstruction = + vaddq_f32(vcvtq_f32_u32(low_values), bias); + const float32x4_t high_reconstruction = + vaddq_f32(vcvtq_f32_u32(high_values), bias); + low_accumulator = vfmaq_f32( + low_accumulator, vld1q_f32(rotated_q + i), low_reconstruction); + high_accumulator = vfmaq_f32( + high_accumulator, + vld1q_f32(rotated_q + i + 4), + high_reconstruction); + } + + float result = horizontal_sum(low_accumulator, high_accumulator); + result += ip_scalar(sign_bits, ex_code, rotated_q, i, d, ExBits, cb); + return result; +} + +} // namespace + template <> float compute_inner_product( const uint8_t* __restrict sign_bits, @@ -57,10 +329,25 @@ float compute_inner_product( size_t d, size_t ex_bits, float cb) { - return compute_inner_product( - sign_bits, ex_code, rotated_q, d, ex_bits, cb); + if (ex_bits == 1) { + return ip_1exbit_neon(sign_bits, ex_code, rotated_q, d, cb); + } + switch (ex_bits) { + case 2: + return ip_multibit_neon<2>(sign_bits, ex_code, rotated_q, d, cb); + case 3: + return ip_multibit_neon<3>(sign_bits, ex_code, rotated_q, d, cb); + case 4: + return ip_multibit_neon<4>(sign_bits, ex_code, rotated_q, d, cb); + case 5: + return ip_multibit_neon<5>(sign_bits, ex_code, rotated_q, d, cb); + case 6: + return ip_multibit_neon<6>(sign_bits, ex_code, rotated_q, d, cb); + case 7: + return ip_multibit_neon<7>(sign_bits, ex_code, rotated_q, d, cb); + default: + return ip_scalar(sign_bits, ex_code, rotated_q, 0, d, ex_bits, cb); + } } } // namespace faiss::rabitq::multibit - -#endif // COMPILE_SIMD_ARM_NEON diff --git a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp index 1850a6d86..ef9422eb3 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/rabitq_rvv.cpp @@ -9,8 +9,6 @@ #include -#ifdef COMPILE_SIMD_RISCV_RVV - #include namespace faiss::rabitq { @@ -188,5 +186,3 @@ compute_inner_product( } } // namespace faiss::rabitq::multibit - -#endif // COMPILE_SIMD_RISCV_RVV diff --git a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp index d5759a75a..bd9c9a041 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx2.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX2 - #include #include @@ -53,5 +51,3 @@ float block_l2(const float* x, const float* y, int n) { } // namespace detail } // namespace faiss - -#endif // COMPILE_SIMD_AVX2 diff --git a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp index dcb155bac..10906888b 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_avx512.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_AVX512 - #include #include @@ -41,5 +39,3 @@ float block_l2(const float* x, const float* y, int n) { } // namespace detail } // namespace faiss - -#endif // COMPILE_SIMD_AVX512 diff --git a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp index e41ef5d2b..e70ee73ca 100644 --- a/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp +++ b/thirdparty/faiss/faiss/utils/simd_impl/super_kmeans_kernels_sve.cpp @@ -5,8 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#ifdef COMPILE_SIMD_ARM_SVE - #include #include @@ -30,5 +28,3 @@ float block_l2(const float* x, const float* y, int n) { } // namespace detail } // namespace faiss - -#endif // COMPILE_SIMD_ARM_SVE diff --git a/thirdparty/faiss/faiss/utils/simd_levels.cpp b/thirdparty/faiss/faiss/utils/simd_levels.cpp index 3190cec2a..2e2ea55a4 100644 --- a/thirdparty/faiss/faiss/utils/simd_levels.cpp +++ b/thirdparty/faiss/faiss/utils/simd_levels.cpp @@ -30,6 +30,8 @@ uint64_t SIMDConfig::supported_simd_levels = 0; // Microarchitecture flags (x86). Default false; set by // detect_x86_uarch_flags() at load time. bool SIMDConfig::avx512_split = false; +bool SIMDConfig::scalar_gather = false; +bool SIMDConfig::sq_avx512_4_accumulators = false; // Resolved here rather than in the header so that dependents, which never see // FAISS_ENABLE_DD, still get the answer for the faiss they link against. @@ -50,19 +52,19 @@ bool SIMDConfig::has_dynamic_dispatch() { #define HWCAP_SVE (1 << 22) #endif -static bool has_sve() { +[[maybe_unused]] static bool has_sve() { return (getauxval(AT_HWCAP) & HWCAP_SVE) != 0; } #elif defined(__APPLE__) // Apple Silicon does NOT support SVE -static bool has_sve() { +[[maybe_unused]] static bool has_sve() { return false; } #else // Other aarch64 platforms: conservatively report no SVE -static bool has_sve() { +[[maybe_unused]] static bool has_sve() { return false; } @@ -137,6 +139,13 @@ void detect_x86_uarch_flags() { // AMD Zen 4 / Zen 4c (Bergamo) is family 0x19 and splits AVX-512. // (Zen 5, family 0x1A, has a native 512-bit datapath and is excluded.) SIMDConfig::avx512_split = is_amd && display_family == 0x19u; + // Measured on Milan, Bergamo (0x19) and Turin (0x1A); other AMD families + // keep the gather kernels. + SIMDConfig::scalar_gather = + is_amd && (display_family == 0x19u || display_family == 0x1Au); + // Measured on Bergamo (0x19) and Turin (0x1A). Intel Skylake and Sapphire + // Rapids are faster with one accumulator. + SIMDConfig::sq_avx512_4_accumulators = SIMDConfig::scalar_gather; } #else // Not x86-64 @@ -191,6 +200,8 @@ SIMDConfig::SIMDConfig(const char** faiss_simd_level_env) { if (!env_var) { level = auto_detect_simd_level(); } else { + // The microarchitecture flags describe the CPU, not the forced level. + detect_x86_uarch_flags(); // Forcing a level the CPU lacks is allowed. Forcing one the binary // does not hold is not: dispatch would fall to NONE and skip every // level between. Walk down to the nearest compiled level instead. @@ -274,7 +285,9 @@ SIMDLevel SIMDConfig::auto_detect_simd_level() { #if defined(COMPILE_SIMD_AVX2) || defined(COMPILE_SIMD_AVX512) bool has_avx2 = (ebx7 & (1 << 5)) != 0; - if (has_avx2) { + // The AVX2 and higher SIMD files compile with -mbmi2. + bool has_bmi2 = (ebx7 & (1 << 8)) != 0; + if (has_avx2 && has_bmi2) { supported_simd_levels |= (1 << static_cast(SIMDLevel::AVX2)); detected_level = SIMDLevel::AVX2; } @@ -282,7 +295,7 @@ SIMDLevel SIMDConfig::auto_detect_simd_level() { #if defined(COMPILE_SIMD_AVX512) bool cpu_has_avx512f = (ebx7 & (1 << 16)) != 0; bool os_supports_avx512 = (xcr0 & 0xE0) == 0xE0; - bool has_avx512f = cpu_has_avx512f && os_supports_avx512; + bool has_avx512f = cpu_has_avx512f && os_supports_avx512 && has_bmi2; if (has_avx512f) { bool has_avx512cd = (ebx7 & (1 << 28)) != 0; bool has_avx512vl = (ebx7 & (1 << 31)) != 0; @@ -342,7 +355,10 @@ SIMDLevel SIMDConfig::auto_detect_simd_level() { #endif #if defined(__riscv) && defined(COMPILE_SIMD_RISCV_RVV) - // RVV is always available on RISC-V builds compiled with rv64gcv. + // RVV is always available on RISC-V builds compiled with + // rv64gcv_zvfhmin: that ISA (including Zvfhmin, used by the QT_fp16 + // kernels) is the minimum requirement to run such binaries at all, + // so no runtime feature check is needed beyond the build contract. supported_simd_levels |= (1 << static_cast(SIMDLevel::RISCV_RVV)); detected_level = SIMDLevel::RISCV_RVV; #endif diff --git a/thirdparty/faiss/faiss/utils/simd_levels.h b/thirdparty/faiss/faiss/utils/simd_levels.h index 80e15a85f..3749e52a2 100644 --- a/thirdparty/faiss/faiss/utils/simd_levels.h +++ b/thirdparty/faiss/faiss/utils/simd_levels.h @@ -26,7 +26,11 @@ enum class SIMDLevel { ARM_NEON, ARM_SVE, // Scalable Vector Extension (ARMv8.2+) // riscv - RISCV_RVV, // RISC-V Vector Extension (rv64gcv) + // RISC-V Vector Extension. The minimum ISA for this level is rv64gcv + // plus Zvfhmin (FP16 vector conversion), which the QT_fp16 kernels + // require; RVV translation units are compiled with + // -march=rv64gcv_zvfhmin. + RISCV_RVV, // Appended to preserve the numeric values of the existing public enum. // AVX-512 core features plus AVX512_VPOPCNTDQ and AVX512_BITALG @@ -36,6 +40,65 @@ enum class SIMDLevel { COUNT }; +/*************************************************************** + * FAISS_SIMD_TU(L): 1 if the library contains SIMD level L + * (COMPILE_SIMD_L) and the current translation unit can use the + * instructions of L (compiler macro), else 0. Use it to guard level + * code in headers that common files also include, for example + * `#if FAISS_SIMD_TU(AVX512)`. It is function-like, so a header that + * uses it without including this file fails to compile. + ***************************************************************/ +#ifdef SWIG +#define FAISS_SIMD_TU(level) 0 +#else + +#if defined(COMPILE_SIMD_AVX2) && defined(__AVX2__) +#define FAISS_SIMD_TU_AVX2 1 +#else +#define FAISS_SIMD_TU_AVX2 0 +#endif + +#if defined(COMPILE_SIMD_AVX512) && defined(__AVX512F__) +#define FAISS_SIMD_TU_AVX512 1 +#else +#define FAISS_SIMD_TU_AVX512 0 +#endif + +#if defined(COMPILE_SIMD_AVX512_VPOPCNT) && defined(__AVX512VPOPCNTDQ__) +#define FAISS_SIMD_TU_AVX512_VPOPCNT 1 +#else +#define FAISS_SIMD_TU_AVX512_VPOPCNT 0 +#endif + +#if defined(COMPILE_SIMD_AVX512_SPR) && defined(__AVX512FP16__) +#define FAISS_SIMD_TU_AVX512_SPR 1 +#else +#define FAISS_SIMD_TU_AVX512_SPR 0 +#endif + +// __aarch64__ is not defined by MSVC, which cannot compile the NEON code. +#if defined(COMPILE_SIMD_ARM_NEON) && defined(__aarch64__) +#define FAISS_SIMD_TU_ARM_NEON 1 +#else +#define FAISS_SIMD_TU_ARM_NEON 0 +#endif + +#if defined(COMPILE_SIMD_ARM_SVE) && defined(__ARM_FEATURE_SVE) +#define FAISS_SIMD_TU_ARM_SVE 1 +#else +#define FAISS_SIMD_TU_ARM_SVE 0 +#endif + +#if defined(COMPILE_SIMD_RISCV_RVV) && defined(__riscv_vector) +#define FAISS_SIMD_TU_RISCV_RVV 1 +#else +#define FAISS_SIMD_TU_RISCV_RVV 0 +#endif + +#define FAISS_SIMD_TU(level) FAISS_SIMD_TU_##level + +#endif // SWIG + /*************************************************************** * SINGLE_SIMD_LEVEL: the SIMD level for code without explicit SL context. * @@ -183,6 +246,16 @@ struct FAISS_API SIMDConfig { /// 256-bit kernel. static bool avx512_split; + /// Scalar table lookups beat gathers (AMD Zen 3, Zen 4 and Zen 5, + /// families 0x19 and 0x1A), so the 8-bit PQ code-distance kernels use + /// the scalar path instead of gathers. + static bool scalar_gather; + + /// Same CPUs as scalar_gather. The AVX-512 QT_fp16, QT_bf16 and QT_8bit + /// inner-product distance loops use four accumulators per code at a + /// large d. + static bool sq_avx512_4_accumulators; + static SIMDLevel auto_detect_simd_level(); /// Whether this faiss build dispatches SIMD at runtime. diff --git a/thirdparty/faiss/faiss/utils/sorting.cpp b/thirdparty/faiss/faiss/utils/sorting.cpp index 29ee75024..dfd791ff8 100644 --- a/thirdparty/faiss/faiss/utils/sorting.cpp +++ b/thirdparty/faiss/faiss/utils/sorting.cpp @@ -252,7 +252,7 @@ void bucket_sort_parallel( uint64_t vmax, int64_t* lims, int64_t* perm, - int nt_in) { + [[maybe_unused]] int nt_in) { memset(lims, 0, sizeof(*lims) * (vmax + 1)); #pragma omp parallel num_threads(nt_in) { @@ -368,7 +368,7 @@ void bucket_sort_inplace_ref( if (row >= 0) { ptrs[bucket_no] += 1; } - assert(idx < lims[bucket_no + 1]); + assert(idx < static_cast(lims[bucket_no + 1])); TI next_bucket_no = vals[idx]; vals[idx] = row; if (next_bucket_no != -1) { @@ -391,7 +391,7 @@ void bucket_sort_inplace_ref( } for (size_t i = 0; i < static_cast(nbucket); i++) { - assert(ptrs[i] == lims[i + 1]); + assert(ptrs[i] == static_cast(lims[i + 1])); } double t3 = getmillisecs(); if (bucket_sort_verbose) { @@ -758,8 +758,9 @@ void hashtable_int64_to_int64_add( i < static_cast(lims[bucket + 1]); i++) { int64_t j = perm[i]; - assert(bucket_no[j] == bucket); - assert(hk[j] >= k0 && hk[j] < k1); + assert(bucket_no[j] == static_cast(bucket)); + assert(static_cast(hk[j]) >= k0 && + static_cast(hk[j]) < k1); size_t slot = hk[j]; for (;;) { if (tab[slot * 2] == -1) { // found! diff --git a/thirdparty/faiss/faiss/utils/transpose/transpose-avx2-inl.h b/thirdparty/faiss/faiss/utils/transpose/transpose-avx2-inl.h index 464f44ccc..87b29e5f6 100644 --- a/thirdparty/faiss/faiss/utils/transpose/transpose-avx2-inl.h +++ b/thirdparty/faiss/faiss/utils/transpose/transpose-avx2-inl.h @@ -10,8 +10,6 @@ // This file contains transposing kernels for AVX2 for // tiny float/int32 matrices, such as 8x2. -#ifdef __AVX2__ - #include namespace faiss { @@ -161,5 +159,3 @@ inline void transpose_8x8( } } // namespace faiss - -#endif diff --git a/thirdparty/faiss/faiss/utils/transpose/transpose-avx512-inl.h b/thirdparty/faiss/faiss/utils/transpose/transpose-avx512-inl.h index 6cbfda87e..8bfcaf6a8 100644 --- a/thirdparty/faiss/faiss/utils/transpose/transpose-avx512-inl.h +++ b/thirdparty/faiss/faiss/utils/transpose/transpose-avx512-inl.h @@ -10,8 +10,6 @@ // This file contains transposing kernels for AVX512 for // tiny float/int32 // matrices, such as 16x2. -#ifdef __AVX512F__ - #include namespace faiss { @@ -172,5 +170,3 @@ inline void transpose_16x8( } } // namespace faiss - -#endif diff --git a/thirdparty/faiss/faiss/utils/utils.cpp b/thirdparty/faiss/faiss/utils/utils.cpp index 7a14fc2cf..ab1383e46 100644 --- a/thirdparty/faiss/faiss/utils/utils.cpp +++ b/thirdparty/faiss/faiss/utils/utils.cpp @@ -28,14 +28,19 @@ #include #include +#include #include #include #include +#include #include #include #include +#include #include +#include +#include #ifndef FINTEGER #define FINTEGER long @@ -139,6 +144,10 @@ std::string get_compile_options() { options += "SVS "; #endif +#ifdef FAISS_ENABLE_DISK_IVF + options += "DISK_IVF "; +#endif + options += ref_gpu_compile_options(); return options; @@ -175,6 +184,18 @@ uint64_t get_cycles() { #endif } +namespace { +std::atomic search_stats_enabled{true}; +} // namespace + +void set_search_stats_enabled(bool enabled) { + search_stats_enabled.store(enabled, std::memory_order_relaxed); +} + +bool get_search_stats_enabled() { + return search_stats_enabled.load(std::memory_order_relaxed); +} + #ifdef __linux__ size_t get_mem_usage_kb() { @@ -461,6 +482,51 @@ void bvecs_checksum(size_t n, size_t d, const uint8_t* a, uint64_t* cs) { } } +size_t find_duplicate_codes( + size_t n, + size_t code_size, + const uint8_t* codes, + int64_t* rep) { + constexpr int64_t nbucket = 1 << 16; + std::vector hash(n), bucket(n); + // the low bits of a checksum only depend on the low bits of its inputs +#pragma omp parallel for + for (int64_t i = 0; i < int64_t(n); i++) { + hash[i] = SplitMix64RandomGenerator( + bvec_checksum(code_size, codes + i * code_size)) + .next(); + bucket[i] = hash[i] % nbucket; + } + std::vector lims(nbucket + 1), order(n); + bucket_sort(n, bucket.data(), nbucket, lims.data(), order.data()); + + size_t n_distinct = 0; +#pragma omp parallel for schedule(dynamic) reduction(+ : n_distinct) + for (int64_t b = 0; b < nbucket; b++) { + int64_t* begin = order.data() + lims[b]; + int64_t* end = order.data() + lims[b + 1]; + std::sort(begin, end, [&](int64_t x, int64_t y) { + return std::pair(hash[x], x) < std::pair(hash[y], y); + }); + const int64_t* group = begin; + for (const int64_t* r = begin; r < end; r++) { + if (hash[*r] != hash[*group]) { + group = r; + } + const int64_t* q = group; + while (q < r && + memcmp(codes + *q * code_size, + codes + *r * code_size, + code_size) != 0) { + q++; + } + rep[*r] = *q; + n_distinct += q == r; + } + } + return n_distinct; +} + const float* fvecs_maybe_subsample( size_t d, size_t* n, @@ -626,6 +692,24 @@ void CombinerRangeKNN::write_result(T* D_res, int64_t* I_res) { template struct CombinerRangeKNN; template struct CombinerRangeKNN; +void fp16_to_fp32(size_t n, const uint16_t* x, float* out) { + // below this many values, stay on the calling thread + constexpr size_t block = size_t(1) << 16; + with_selected_simd_levels([&]() { + if (n <= block) { + detail::fp16_to_fp32_kernel(n, x, out); + return; + } + const int64_t nblock = static_cast((n + block - 1) / block); +#pragma omp parallel for + for (int64_t b = 0; b < nblock; b++) { + const size_t j0 = static_cast(b) * block; + detail::fp16_to_fp32_kernel( + std::min(block, n - j0), x + j0, out + j0); + } + }); +} + void CodeSet::insert(size_t n, const uint8_t* codes, bool* inserted) { for (size_t i = 0; i < n; i++) { auto res = s.insert( diff --git a/thirdparty/faiss/faiss/utils/utils.h b/thirdparty/faiss/faiss/utils/utils.h index 3af2590dc..ca4d37e3c 100644 --- a/thirdparty/faiss/faiss/utils/utils.h +++ b/thirdparty/faiss/faiss/utils/utils.h @@ -48,6 +48,14 @@ size_t get_mem_usage_kb(); uint64_t get_cycles(); +/** Enable or disable the collection of global search statistics (enabled by + * default). The flag is process-wide. When it is disabled, searches may skip + * updates to global stats objects, so their values are unspecified. At the + * moment, the flag controls hnsw_stats and rabitq_stats. + */ +void set_search_stats_enabled(bool enabled); +bool get_search_stats_enabled(); + /*************************************************************************** * Misc matrix and vector manipulation functions ***************************************************************************/ @@ -122,6 +130,14 @@ uint64_t bvec_checksum(size_t n, const uint8_t* a); */ void bvecs_checksum(size_t n, size_t d, const uint8_t* a, uint64_t* cs); +/// rep[i]: lowest row whose code equals code i (codes: n x code_size). +/// Returns the number of distinct codes. +size_t find_duplicate_codes( + size_t n, + size_t code_size, + const uint8_t* codes, + int64_t* rep); + /** random subsamples a set of vectors if there are too many of them * * @param d dimension of the vectors @@ -156,6 +172,14 @@ void binary_to_real(size_t d, const uint8_t* x_in, float* x_out); */ void real_to_binary(size_t d, const float* x_in, uint8_t* x_out); +/** Convert packed IEEE binary16 values to fp32 (exact). + * + * @param n number of values + * @param x input fp16 values, size n + * @param out output fp32 values, size n + */ +void fp16_to_fp32(size_t n, const uint16_t* x, float* out); + /** A reasonable hashing function */ uint64_t hash_bytes(const uint8_t* bytes, int64_t n); diff --git a/thirdparty/faiss/perf_tests/CMakeLists.txt b/thirdparty/faiss/perf_tests/CMakeLists.txt index db79f59c9..b2b3adb44 100644 --- a/thirdparty/faiss/perf_tests/CMakeLists.txt +++ b/thirdparty/faiss/perf_tests/CMakeLists.txt @@ -30,6 +30,7 @@ target_include_directories(faiss_perf_tests_utils PRIVATE include(../cmake/link_to_faiss_lib.cmake) link_to_faiss_lib(faiss_perf_tests_utils) +target_link_libraries(faiss_perf_tests_utils PRIVATE OpenMP::OpenMP_CXX) set(FAISS_PERF_TEST_SRC bench_no_multithreading_rcq_search.cpp diff --git a/thirdparty/faiss/pyproject-gpu-cuvs.toml b/thirdparty/faiss/pyproject-gpu-cuvs.toml index e634acfc4..37498c6bb 100644 --- a/thirdparty/faiss/pyproject-gpu-cuvs.toml +++ b/thirdparty/faiss/pyproject-gpu-cuvs.toml @@ -44,13 +44,9 @@ dependencies = [ "nvidia-cublas>=13.2,<14", "nvidia-curand>=10.3.7,<11", "nvidia-nvjitlink>=13.2,<14", - # Exact-series pin, not a range: RAPIDS >=26.08 wraps RMM in a per-release - # inline namespace (rmm::_RMM_26_8::), so each minor series renames the - # symbols libfaiss.so is linked against. libraft is listed because - # _preload_gpu_libs dlopens it directly. - "libcuvs-cu13==26.06.*", - "libraft-cu13==26.06.*", - "librmm-cu13==26.06.*", + "libcuvs-cu13>=26.10,<26.11", + "libraft-cu13>=26.10,<26.11", + "librmm-cu13>=26.10,<26.11", ] [project.urls] @@ -93,13 +89,14 @@ CMAKE_SHARED_LINKER_FLAGS = "-Wl,--gc-sections -Wl,--strip-all" CMAKE_MODULE_LINKER_FLAGS = "-Wl,--gc-sections -Wl,--strip-all" BUILD_TESTING = "OFF" BUILD_SHARED_LIBS = "ON" -# cuVS + transitive deps (raft, rmm, rapids_logger, header-only cutlass/cuco/nvtx3) -# are found via CMAKE_PREFIX_PATH (environment block below) at the RAPIDS wheel roots, -# mirroring the conda build — no explicit *_DIR, agnostic to lib/ vs lib64/. +# cuVS + transitive deps (raft, rmm, kvikio, rapids_logger, header-only +# cutlass/cuco/nvtx3) are found via CMAKE_PREFIX_PATH (environment block below) +# at the RAPIDS wheel roots, mirroring the conda build — no explicit *_DIR, +# agnostic to lib/ vs lib64/. # Stable ABI (abi3): one cp311 wheel covers all 3.11+. -# Floor is 3.11 because the runtime dep libcuvs-cu13>=26.06 (RAPIDS) requires -# Python >=3.11 — RAPIDS dropped 3.10 in the 26.04 release. +# Floor is 3.11 because the runtime dep libcuvs-cu13>=26.10 (RAPIDS) +# requires Python >=3.11 — RAPIDS dropped 3.10 in the 26.04 release. # GPU is Linux-only; free-threaded Python (cp3*t) cannot use abi3. [[tool.scikit-build.overrides]] if.platform-system = "linux" @@ -119,9 +116,9 @@ test-requires = [ "nvidia-cublas>=13.2,<14", "nvidia-curand>=10.3.7,<11", "nvidia-nvjitlink>=13.2,<14", - "libcuvs-cu13==26.06.*", - "libraft-cu13==26.06.*", - "librmm-cu13==26.06.*", + "libcuvs-cu13>=26.10,<26.11", + "libraft-cu13>=26.10,<26.11", + "librmm-cu13>=26.10,<26.11", ] test-command = "python -m pytest {project}/tests/test_wheel_smoke_gpu.py -v" @@ -137,7 +134,7 @@ test-command = "python -m pytest {project}/tests/test_wheel_smoke_gpu.py -v" # `pip install --target /opt/cuvs` — ABI-clean, so no libstdc++/libgcc_s/libgomp strip # or RMM symlink shim. cp311 interpreter is explicit (manylinux puts no `pip` on PATH). manylinux-x86_64-image = "manylinux_2_28" -before-all = "dnf install -y gcc-toolset-14 epel-release && dnf install -y openblas-devel openblas-openmp swig && dnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/cuda-rhel8.repo && dnf install -y --setopt=obsoletes=0 cuda-toolkit-13-2 && /opt/python/cp311-cp311/bin/python -m pip install --target /opt/cuvs --no-deps --only-binary ':all:' --extra-index-url https://pypi.nvidia.com 'libcuvs-cu13==26.06.*' 'libraft-cu13==26.06.*' 'librmm-cu13==26.06.*' 'rapids-logger'" +before-all = "dnf install -y gcc-toolset-14 epel-release && dnf install -y openblas-devel openblas-openmp swig && dnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/cuda-rhel8.repo && dnf install -y --setopt=obsoletes=0 cuda-toolkit-13-2 && /opt/python/cp311-cp311/bin/python -m pip install --target /opt/cuvs --no-deps --only-binary ':all:' --extra-index-url https://pypi.nvidia.com 'libcuvs-cu13==26.10.*' 'libraft-cu13==26.10.*' 'librmm-cu13==26.10.*' 'libkvikio-cu13==26.10.*' 'rapids-logger'" # auditwheel excludes (not vendored; supplied at runtime by nvidia-* / libcuvs-cu13 # wheels): host driver libcuda, CUDA runtime/math libs (cusparse/cusolver are explicit — # under the cuda-toolkit RPM, not /opt/cuvs), and every RAPIDS .so found under /opt/cuvs. @@ -157,12 +154,13 @@ repair-wheel-command = "pipx run abi3audit --strict --report {wheel}" # Build-tool paths. CUDA from /usr/local/cuda-13.2 (NVIDIA RPM convention); # GCC pinned to toolset-14 for CUDA 13.2 support. # CUDAHOSTCXX must match CXX or nvcc host TUs get an ABI-mismatched libstdc++. -# CMAKE_PREFIX_PATH points at the RAPIDS wheel roots so find_package(cuvs) resolves. -# Set as env (not cmake.define) so CMake merges it with scikit-build-core's own path. +# CMAKE_PREFIX_PATH points at the RAPIDS wheel roots so find_package(cuvs) +# (and the find_dependency(kvikio) it issues) resolves. Set as env (not +# cmake.define) so CMake merges it with scikit-build-core's own path. [tool.cibuildwheel.linux.environment] CUDA_HOME = "/usr/local/cuda-13.2" CUDACXX = "/usr/local/cuda-13.2/bin/nvcc" CC = "/opt/rh/gcc-toolset-14/root/usr/bin/gcc" CXX = "/opt/rh/gcc-toolset-14/root/usr/bin/g++" CUDAHOSTCXX = "/opt/rh/gcc-toolset-14/root/usr/bin/g++" -CMAKE_PREFIX_PATH = "/opt/cuvs/libcuvs:/opt/cuvs/libraft:/opt/cuvs/librmm:/opt/cuvs/rapids_logger" +CMAKE_PREFIX_PATH = "/opt/cuvs/libcuvs:/opt/cuvs/libraft:/opt/cuvs/librmm:/opt/cuvs/libkvikio:/opt/cuvs/rapids_logger" diff --git a/thirdparty/faiss/pyproject.toml b/thirdparty/faiss/pyproject.toml index 384b3bddc..f2c43e6d0 100644 --- a/thirdparty/faiss/pyproject.toml +++ b/thirdparty/faiss/pyproject.toml @@ -160,13 +160,9 @@ test-command = "OMP_STACKSIZE=8M python -m pytest {project}/tests/test_wheel_smo before-all = "brew install libomp" # Deployment target must match brew dylibs' minos for delocate compatibility. +# The macOS runners use macOS 15, so brew dylibs have minos 15.0. [[tool.cibuildwheel.overrides]] -select = "*-macosx_arm64" -environment = {MACOSX_DEPLOYMENT_TARGET = "14.0"} - -# macOS Intel: runner uses macOS 15, so brew dylibs have minos 15.0. -[[tool.cibuildwheel.overrides]] -select = "*-macosx_x86_64" +select = "*-macosx*" environment = {MACOSX_DEPLOYMENT_TARGET = "15.0"} # Windows arm64: drop scipy for the same reason as musllinux above — the smoke diff --git a/thirdparty/faiss/tests/CMakeLists.txt b/thirdparty/faiss/tests/CMakeLists.txt index 2be0ef50b..8c4bddcee 100644 --- a/thirdparty/faiss/tests/CMakeLists.txt +++ b/thirdparty/faiss/tests/CMakeLists.txt @@ -4,24 +4,16 @@ # LICENSE file in the root directory of this source tree. set(FAISS_TEST_SRC - test_binary_flat.cpp test_dealloc_invlists.cpp - test_ivfpq_codec.cpp - test_ivfpq_indexing.cpp test_lowlevel_ivf.cpp test_ivf_index.cpp - test_omp_threads.cpp - test_pairs_decoding.cpp test_params_override.cpp test_pq_encoding.cpp - test_sliding_ivf.cpp test_threaded_index.cpp - test_transfer_invlists.cpp test_cppcontrib_sa_decode.cpp test_cppcontrib_uintreader.cpp test_simdlib.cpp test_approx_topk.cpp - test_RCQ_cropping.cpp test_heap.cpp test_pq_code_distance.cpp test_hnsw.cpp @@ -31,31 +23,30 @@ set(FAISS_TEST_SRC test_pqfs_unaligned.cpp test_common_ivf_empty_index.cpp test_ivf_early_termination.cpp - test_callback.cpp test_utils.cpp test_hamming.cpp test_zerocopy.cpp test_scalar_quantizer.cpp test_factory_tools.cpp test_custom_result_handler.cpp - test_fastscan_filter.cpp test_single_query_collect_handler.cpp # These tests work in both static and DD modes (uniform SIMDConfig API) test_distances_simd.cpp test_simd_levels.cpp test_fast_scan_distance_to_code.cpp + test_fast_scan_hacc.cpp test_rabitq_fastscan.cpp test_rabitq_batch_estimates.cpp + test_rabitq_split_inner_product.cpp test_super_kmeans_foundations.cpp + test_pipnn.cpp ) # Tests that use POSIX APIs or have platform-specific issues on Windows if(NOT WIN32) list(APPEND FAISS_TEST_SRC - test_merge.cpp test_ondisk_ivf.cpp test_disable_pq_sdc_tables.cpp - test_mmap.cpp ) endif() @@ -63,6 +54,10 @@ if(FAISS_ENABLE_SVS) list(APPEND FAISS_TEST_SRC test_svs.cpp) endif() +if(FAISS_ENABLE_DISK_IVF) + list(APPEND FAISS_TEST_SRC test_ivf_rabitq_ssd.cpp) +endif() + # DD-only tests; x86-specific raw-intrinsic tests are added separately below. if(FAISS_OPT_LEVEL STREQUAL "dd") list(APPEND FAISS_TEST_SRC @@ -70,8 +65,8 @@ if(FAISS_OPT_LEVEL STREQUAL "dd") test_simd_perf.cpp ) if(CMAKE_SYSTEM_PROCESSOR MATCHES "(x86_64|amd64|AMD64)") - # Exercise the VPOPCNT specialization through header-side dispatch too. - # The common test target only enables AVX2/AVX512 dispatch declarations. + # Enable VPOPCNT dispatch for this test. The common + # target enables AVX2/AVX512 only. set_source_files_properties(test_rabitq_batch_estimates.cpp PROPERTIES COMPILE_DEFINITIONS COMPILE_SIMD_AVX512_VPOPCNT) list(APPEND FAISS_TEST_SRC @@ -99,6 +94,10 @@ if(FAISS_OPT_LEVEL STREQUAL "dd") PROPERTIES COMPILE_OPTIONS "/arch:AVX512" ) endif() + elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "(aarch64|arm64|ARM64)") + list(APPEND FAISS_TEST_SRC + test_rabitq_simd_neon.cpp + ) endif() endif() @@ -127,6 +126,12 @@ if(FAISS_ENABLE_SVS) target_compile_definitions(faiss_test PRIVATE FAISS_ENABLE_SVS FAISS_SVS_RUNTIME_VERSION=${FAISS_SVS_RUNTIME_VERSION}) endif() +if(FAISS_ENABLE_DISK_IVF) + # test_ivf_rabitq_ssd.cpp calls libaio, and DiskIOBackend.h includes libaio.h + find_package(LibAIO REQUIRED) + target_link_libraries(faiss_test PRIVATE LibAIO::LibAIO) +endif() + include(../cmake/link_to_faiss_lib.cmake) link_to_faiss_lib(faiss_test) diff --git a/thirdparty/faiss/tests/bench_hnsw_deterministic.py b/thirdparty/faiss/tests/bench_hnsw_deterministic.py index 69c71f7f3..334153221 100644 --- a/thirdparty/faiss/tests/bench_hnsw_deterministic.py +++ b/thirdparty/faiss/tests/bench_hnsw_deterministic.py @@ -23,7 +23,7 @@ # (1_000), FAISS_DET_SEED (1234), FAISS_DET_DATA_DIR (a tempdir, reused across # runs), FAISS_DET_GRAPH_OUT (dump last graph), FAISS_DET_TAG. # -# Run with: +# Run with (tests/BUCK sets FAISS_DET_NB=50000): # buck2 run fbcode//faiss/tests:bench_hnsw_deterministic from __future__ import annotations @@ -247,9 +247,6 @@ def main() -> None: k = 10 tag = os.environ.get("FAISS_DET_TAG", "") - # Fixed thread count: the build guarantees reproducibility at a fixed - # thread count. - faiss.omp_set_num_threads(faiss.omp_get_max_threads()) threads = faiss.omp_get_max_threads() print("faiss HNSW deterministic-build benchmark") diff --git a/thirdparty/faiss/tests/common_faiss_tests.py b/thirdparty/faiss/tests/common_faiss_tests.py index 02b33ec82..3e466693c 100644 --- a/thirdparty/faiss/tests/common_faiss_tests.py +++ b/thirdparty/faiss/tests/common_faiss_tests.py @@ -3,15 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -# a few common functions for the tests - -from __future__ import ( - absolute_import, - division, - print_function, - unicode_literals, -) - import sys import unittest @@ -78,7 +69,6 @@ def __init__(self): dotprods = np.dot(self.xq, self.xb.T) self.gt = dotprods.argmax(1) - self.k = 100 def get_dataset(d, nb, nt, nq): @@ -130,7 +120,7 @@ def normalize_DI(D, I): norm = I.max() + 1.0 Dr = D.astype("float64") + I / norm # ignore -1s and elements on last column - Dr[I1 == -1] = 1e20 + Dr[I == -1] = 1e20 Dr[D == D[:, -1:]] = 1e20 Dr.sort(axis=1) return Dr @@ -139,7 +129,6 @@ def normalize_DI(D, I): assert ndiff == 0, "%d differences in normalized D matrix" % ndiff -# Map SIMDLevel enum values to their string names. _SIMD_LEVEL_NAMES = { faiss.SIMDLevel_NONE: "NONE", faiss.SIMDLevel_AVX2: "AVX2", diff --git a/thirdparty/faiss/tests/e_means_test_utils.py b/thirdparty/faiss/tests/e_means_test_utils.py new file mode 100644 index 000000000..ad637b8ab --- /dev/null +++ b/thirdparty/faiss/tests/e_means_test_utils.py @@ -0,0 +1,1204 @@ +# 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. + +"""Shared NumPy/native-Torch reference contracts; no optional imports at load.""" +import numpy as np +from contextlib import contextmanager +from unittest import mock +import weakref + +from faiss.contrib.e_means import NumpyEmeans +from faiss.contrib.e_means import e_means + + +def backend_class(backend): + if backend == "numpy": + return NumpyEmeans + if backend == "cpu": + from faiss.contrib.e_means.e_means_torch import Emeans + + return Emeans + from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans + + return QuantizedEmeans + + +def native_options(backend): + """Explicit native CUDA configuration for the reference fixtures.""" + return {"quantizer": None} if backend == "cuda" else {} + + +def backend_helpers(backend): + if backend == "numpy": + return e_means + from faiss.contrib.e_means import e_means_torch + + return e_means_torch + + +def as_numpy(value): + return ( + value.detach().cpu().numpy() + if hasattr(value, "detach") + else np.asarray(value) + ) + + +def known_torch_centroids(centroids, *, model_class=None, **kwargs): + """Install fixed means through the documented external-statistics API.""" + import torch + + k, d = centroids.shape + from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans + + if model_class is None: + model_class = QuantizedEmeans + if issubclass(model_class, QuantizedEmeans): + kwargs.setdefault("quantizer", None) + # Fixed means use caller-made statistics and do not need revival. + kwargs.setdefault("unused_threshold", 0) + + model = model_class(d, k, nepochs=1, batch_size=k, alpha0=1, **kwargs) + model.begin(k, centroids) + model.update( + { + "sums": centroids.clone(), + "counts": torch.ones(k, device=centroids.device), + "objective": torch.zeros( + (), dtype=torch.float64, device=centroids.device + ), + "n": k, + } + ) + model.end_epoch() + torch.testing.assert_close(model.finalize(), centroids, rtol=0, atol=0) + return model + + +@contextmanager +def highest_fp32(backend): + if backend == "numpy": + yield + return + import torch + + previous = torch.get_float32_matmul_precision() + try: + torch.set_float32_matmul_precision("highest") + yield + finally: + torch.set_float32_matmul_precision(previous) + + +class EmeansReferenceContracts: + """The two public test modules supply their own array/device constructors.""" + + def test_single_run_guard_preserves_final_result_and_failed_state(self): + for backend, array in self.reference_arrays(): + with self.subTest(backend=backend): + cls = backend_class(backend) + rows, initial = array([[0.], [2.], [10.], [12.]]), array([[0.], [10.]]) + model = cls(1, 2, nepochs=1, batch_size=4, alpha0=.5, **native_options(backend)) + model.train(rows, initial) + result = model.centroids + with self.assertRaisesRegex(RuntimeError, "new object"): + model.train(rows + 100, initial + 100) + with self.assertRaisesRegex(RuntimeError, "new object"): + model.begin(4, initial) + self.assertIs(model.finalize(), result) + np.testing.assert_array_equal(as_numpy(result), [[1.], [11.]]) + failed = cls(1, 2, nepochs=1, batch_size=4, alpha0=.5, **native_options(backend)) + failed.begin(4, initial) + with mock.patch.object(failed, "_assign_rows", side_effect=RuntimeError("injected assignment")): + with self.assertRaisesRegex(RuntimeError, "injected assignment"): + failed.accumulate(rows) + with self.assertRaisesRegex(RuntimeError, "new object"): + failed.begin(4, initial) + + def test_spherical_ip_zero_objective_and_represented_statistics(self): + initial = np.array([[0, 0], [1, 0], [-1, 0]], dtype="float32") + rows = np.array( + [[0, 0], [0.25, np.sqrt(15) / 4], [1, 0], [-1, 0], [0, 1], [0, -1]], + dtype="float32", + ) + expected_labels = np.array([0, 1, 1, 2, 0, 0]) + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend), highest_fp32(backend): + model = Emeans( + 2, + 3, + nepochs=1, + batch_size=6, + alpha0=1, + spherical=True, + capture_assignments=True, + assignment_chunk_size=2, + **native_options(backend), + ) + source = array(initial) + model.begin(6, source) + stats = model.accumulate(array(rows)) + np.testing.assert_array_equal( + as_numpy(stats["labels"]), expected_labels + ) + counts = np.bincount(expected_labels, minlength=3) + sums = np.zeros_like(initial) + np.add.at(sums, expected_labels, rows) + np.testing.assert_array_equal(as_numpy(stats["counts"]), counts) + np.testing.assert_array_equal(as_numpy(stats["sums"]), sums) + self.assertAlmostEqual(float(stats["objective"]), 7.5, places=6) + model.update(stats) + model.end_epoch() + final = as_numpy(model.finalize()) + np.testing.assert_array_equal(final[0], [0, 0]) + similarity, labels = model.assign(array(rows)) + scores = rows @ final.T + np.testing.assert_array_equal( + as_numpy(labels), scores.argmax(axis=1) + ) + np.testing.assert_allclose( + as_numpy(similarity), scores.max(axis=1), atol=2e-7 + ) + np.testing.assert_array_equal(as_numpy(source), initial) + self.assertAlmostEqual( + float(as_numpy(model.obj)[0]), 7.5, places=6 + ) + + def test_spherical_deferred_ema_borrowed_cache_and_chunks(self): + rows = np.array([[1, 0], [0, 1], [-1, 0]], dtype="float32") + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend), highest_fp32(backend): + args = { + "nepochs": 1, + "batch_size": 3, + "alpha0": 0.25, + "spherical": True, + } + model, control = Emeans(2, 1, **args, **native_options(backend)), Emeans(2, 1, **args, **native_options(backend)) + for km in (model, control): + km.begin(6, array([[3, 4]])) + raw = as_numpy(model._centroids).copy() + usage = as_numpy(model._usage).copy() + handle = model.current_centroids() + cache = model._unit_centroids + version = getattr(cache, "_version", None) + before = as_numpy(handle).copy() + model.accumulate(array(rows[:1])) + for _ in range(3): + np.testing.assert_array_equal( + as_numpy(model.current_centroids()), before + ) + if backend != "numpy": + model._prepare_torch_assignment(model._centroids) + stats = model.accumulate(array(rows[1:])) + self.assertIs(model._unit_centroids, cache) + self.assertEqual(getattr(cache, "_version", None), version) + np.testing.assert_array_equal(as_numpy(handle), before) + self.assertAlmostEqual(float(stats["objective"]), 4.4, places=5) + mass = 0.75 * usage + 0.25 * 3 + expected = raw + (0.25 * 3 / mass)[:, None] * ( + rows.mean(axis=0) - raw + ) + model.update(stats) + control.update(control.accumulate(array(rows))) + np.testing.assert_allclose( + as_numpy(model._centroids), expected, atol=1e-7 + ) + self.assertLess( + np.linalg.norm(as_numpy(model._centroids)[0]), 0.999 + ) + np.testing.assert_allclose( + as_numpy(model.current_centroids()), + expected / np.linalg.norm(expected, axis=1)[:, None], + atol=1e-7, + ) + self.assertIs(model._unit_centroids, cache) + for km in (model, control): + km.update(km.accumulate(array(rows))) + km.end_epoch() + np.testing.assert_array_equal( + as_numpy(model.finalize()), as_numpy(control.finalize()) + ) + np.testing.assert_array_equal( + as_numpy(model.obj), as_numpy(control.obj) + ) + + def test_spherical_projection_extremes_and_wide_closing(self): + from faiss.contrib.e_means.e_means_spherical import normalize_into + + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + source = array([[3e38, -3e38], [1e-38, 0], [0, 0]]) + saved = as_numpy(source).copy() + output = array(np.empty((3, 2), dtype="float32")) + normalize_into(source, output) + np.testing.assert_allclose( + as_numpy(output), + [[2**-0.5, -(2**-0.5)], [1, 0], [0, 0]], + atol=1e-7, + ) + np.testing.assert_array_equal(as_numpy(source), saved) + model = Emeans( + 2, 3, nepochs=1, batch_size=3, alpha0=1, spherical=True, + **native_options(backend), + ) + model.begin(3, source) + np.testing.assert_allclose( + as_numpy(model.current_centroids()), + as_numpy(output), + atol=1e-7, + ) + model = Emeans( + 2, 3, nepochs=1, batch_size=3, alpha0=1, spherical=True, + **native_options(backend), + ) + model.begin(3, array([[1, 0], [0, 1], [-1, 0]])) + model.update(model.accumulate(array([[1, 0], [0, 1], [-1, 0]]))) + model.end_epoch() + # Direct finalize seam: no huge dataset; mean must project before F32. + model._pass_sums = array( + [[1e300, -1e300], [0, 0], [0, 0]], dtype="float64" + ) + model._pass_counts = array([1, 1, 0], dtype="float64") + np.testing.assert_allclose( + as_numpy(model.finalize()), + [[2**-0.5, -(2**-0.5)], [0, 0], [-1, 0]], + atol=1e-7, + ) + self.assertIsNone(model._unit_centroids) + + def test_spherical_zero_beats_negative_similarity(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + model = Emeans( + 2, + 2, + nepochs=1, + batch_size=2, + alpha0=1, + spherical=True, + capture_assignments=True, + **native_options(backend), + ) + model.begin(2, array([[0, 0], [1, 0]])) + stats = model.accumulate(array([[-1, 0], [0, 0]])) + np.testing.assert_array_equal(as_numpy(stats["labels"]), [0, 0]) + self.assertEqual(float(stats["objective"]), 4) + + def test_spherical_torch_version_and_inference_invalidation(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + if backend == "numpy": + continue + import torch + + for inference in (False, True): + with self.subTest( + backend=backend, inference=inference + ), torch.inference_mode(inference): + model = Emeans( + 2, 1, nepochs=1, batch_size=2, alpha0=1, spherical=True, + **native_options(backend), + ) + model.begin(2, array([[1, 0]])) + before = model.current_centroids() + cache = model._unit_centroids + model.current_centroids() + self.assertIs(model._unit_centroids, cache) + if not inference: + # Version counters also catch ATen raw writes, independent of hooks. + model._centroids.copy_(array([[0, 2]])) + np.testing.assert_array_equal( + as_numpy(model.current_centroids()), [[0, 1]] + ) + model.update(model.accumulate(array([[0, -1], [0, -1]]))) + np.testing.assert_array_equal( + as_numpy(model.current_centroids()), [[0, -1]] + ) + self.assertIs(model._unit_centroids, cache) + self.assertTrue(torch.isfinite(before).all()) + model.end_epoch() + model.finalize() + + def test_spherical_fractional_caller_and_matrix(self): + rng = np.random.RandomState(73) + rows = rng.randn(31, 5).astype("float32") + rows /= np.linalg.norm(rows, axis=1)[:, None] + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + helpers = backend_helpers(backend) + for budget in (0.5, 1.5): + with self.subTest(backend=backend, budget=budget), highest_fp32( + backend + ): + args = { + "nepochs": budget, + "spherical": True, + "batch_size": 7, + "alpha0": 0.2, + "seed": 7, + "capture_assignments": True, + "assignment_chunk_size": 3, + } + if backend in ("numpy", "cpu"): + # train() alone can hand a revived centroid's captured + # rows to their second-nearest: the caller owns its labels. + args["closing_handover"] = False + matrix, caller = Emeans(5, 4, **args, **native_options(backend)), Emeans(5, 4, **args, **native_options(backend)) + matrix.train(array(rows), array(rows[:4])) + caller.begin(31, array(rows[:4])) + labels = np.full(31, -1, dtype="int64") + for epoch, n in enumerate(caller.recipe["epoch_rows"]): + seed = e_means._epoch_seed(7, epoch) + if backend == "numpy": + order = np.random.RandomState(seed).permutation(31) + else: + import torch + + x = array(rows) + order = ( + torch.randperm( + 31, + device=x.device, + generator=helpers._torch_generator( + x.device, seed + ), + ) + .cpu() + .numpy() + ) + for begin in range(0, n, 7): + ids = order[begin : min(n, begin + 7)] + stats = caller.accumulate(array(rows[ids])) + if epoch == len(caller.recipe["epoch_rows"]) - 1: + labels[ids] = as_numpy(stats["labels"]) + caller.update(stats) + caller.end_epoch() + np.testing.assert_allclose( + as_numpy(matrix.centroids), + as_numpy(caller.finalize()), + atol=2e-7, + ) + np.testing.assert_array_equal( + as_numpy(matrix.assignments), labels + ) + np.testing.assert_allclose( + as_numpy(matrix.obj), as_numpy(caller.obj), atol=2e-6 + ) + + def test_fractional_epochs_preserve_batches_and_closing_labels(self): + cases = ( + (2, [31, 31]), + (2.5, [31, 16, 31]), + (1.25, [8, 31]), + (0.5, [16]), + (0.1, [3]), + ) + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + for budget, epoch_rows in cases: + with self.subTest(backend=backend, budget=budget), highest_fp32( + backend + ): + x = array(np.arange(31, dtype="float32")[:, None] / 4) + initial = x[[0, 10, 20, 30]] + args = { + "nepochs": budget, + "batch_size": 7, + "alpha0": 0.2, + "seed": 7, + "assignment_chunk_size": 3, + "capture_assignments": True, + } + matrix, caller = Emeans(1, 4, **args, **native_options(backend)), Emeans(1, 4, **args, **native_options(backend)) + matrix.train(x, initial) + caller.begin(len(x), initial) + steps = [(n + 6) // 7 for n in epoch_rows] + self.assertEqual(matrix.recipe["epoch_rows"], epoch_rows) + self.assertEqual(matrix.recipe["epoch_steps"], steps) + self.assertEqual(matrix.recipe["total_steps"], sum(steps)) + for epoch, rows in enumerate(epoch_rows): + seed = e_means._epoch_seed(7, epoch) + if backend == "numpy": + order = np.random.RandomState(seed).permutation( + len(x) + ) + else: + import torch + + generator = torch.Generator( + device=x.device + ).manual_seed(seed) + order = torch.randperm( + len(x), generator=generator, device=x.device + ) + for start in range(0, rows, 7): + batch = x[order[start : min(start + 7, rows)]] + frozen = as_numpy(caller.current_centroids()).copy() + stats = caller.accumulate(batch[:2]) + if len(batch) > 2: + stats = caller.accumulate(batch[2:]) + np.testing.assert_array_equal( + as_numpy(caller.current_centroids()), frozen + ) + caller.update(stats) + self.assertEqual(caller._epoch_steps, steps[epoch]) + caller.end_epoch() + self.assertEqual(matrix._step, sum(steps)) + np.testing.assert_allclose( + as_numpy(caller.finalize()), + as_numpy(matrix.centroids), + atol=1e-6, + rtol=1e-6, + ) + np.testing.assert_allclose( + as_numpy(caller.obj), + as_numpy(matrix.obj), + atol=1e-5, + rtol=1e-6, + ) + captured = as_numpy(matrix.assignments) + visited = as_numpy(order)[: epoch_rows[-1]] + absent = np.ones(len(x), dtype=bool) + absent[visited] = False + np.testing.assert_array_equal(captured[absent], -1) + self.assertTrue(np.all(captured[visited] >= 0)) + for centroid in range(4): + assigned = visited[captured[visited] == centroid] + if len(assigned): + expected = ( + as_numpy(x)[assigned].astype("float64").mean(0) + ) + np.testing.assert_allclose( + as_numpy(matrix.centroids)[centroid], + expected, + atol=1e-6, + rtol=1e-6, + ) + counts = np.bincount(captured[visited], minlength=4).astype( + "float64" + ) + self.assertEqual( + matrix.iteration_stats[-1]["imbalance_factor"], + 4 * counts.dot(counts) / len(visited) ** 2, + ) + + def test_supplied_chunks_share_one_frozen_batch(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend), highest_fp32(backend): + rows = array( + [ + [0.25, 0.0], + [10.0, 10.25], + [0.5, 0.25], + [10.25, 10.0], + [0.0, 0.25], + [10.5, 10.25], + [0.5, 0.0], + [10.0, 10.5], + [0.25, 0.5], + [10.25, 10.5], + [0.5, 0.5], + [10.5, 10.5], + [0.0, 0.0], + ] + ) + initial = array([[0.0, 0.0], [10.0, 10.0]]) + args = { + "nepochs": 2, + "batch_size": 4, + "alpha0": 0.3, + "seed": 7, + "assignment_chunk_size": 2, + "capture_assignments": True, + } + whole, chunked = Emeans(2, 2, **args, **native_options(backend)), Emeans(2, 2, **args, **native_options(backend)) + whole.begin(len(rows), initial) + chunked.begin(len(rows), initial) + empty = chunked.accumulate(rows[:0]) + self.assertEqual(empty["n"], 0) + np.testing.assert_array_equal(as_numpy(empty["counts"]), [0, 0]) + saved_labels = [] + for epoch in range(2): + for start in range(0, len(rows), 4): + batch = rows[start : start + 4] + reference = whole.accumulate(batch) + frozen = as_numpy(chunked.current_centroids()).copy() + count = 0 + for offset in range(0, len(batch), 2): + part = batch[offset : offset + 2] + stats = chunked.accumulate(part) + count += len(part) + self.assertEqual(stats["n"], count) + np.testing.assert_array_equal( + as_numpy(chunked.current_centroids()), frozen + ) + self.assertEqual(chunked._step, whole._step) + if count < len(batch): + self.assertIsNone(stats["sums"]) + self.assertIsNone(stats["counts"]) + if epoch == 1: + labels = stats["labels"] + expected = ( + ( + ( + as_numpy(part).astype("float64")[ + :, None, : + ] + - frozen.astype("float64")[ + None, :, : + ] + ) + ** 2 + ) + .sum(axis=2) + .argmin(axis=1) + ) + np.testing.assert_array_equal( + as_numpy(labels), expected + ) + self.assertEqual( + as_numpy(labels).dtype, np.dtype("int64") + ) + if backend != "numpy": + self.assertEqual(labels.device, rows.device) + self.assertFalse(labels.requires_grad) + saved_labels.append( + (labels, as_numpy(labels).copy()) + ) + else: + self.assertNotIn("labels", stats) + empty = chunked.accumulate(rows[:0]) + self.assertEqual(empty["n"], count) + if count < len(batch): + self.assertIsNone(empty["sums"]) + self.assertIsNone(empty["counts"]) + else: + for field in ("sums", "counts", "objective"): + np.testing.assert_array_equal( + as_numpy(empty[field]), + as_numpy(stats[field]), + ) + if epoch == 1: + self.assertEqual(len(empty["labels"]), 0) + for field in ("sums", "counts", "objective"): + np.testing.assert_allclose( + as_numpy(stats[field]), + as_numpy(reference[field]), + rtol=1e-6, + atol=1e-6, + ) + whole.update(reference) + chunked.update(stats) + for labels, snapshot in saved_labels: + np.testing.assert_array_equal( + as_numpy(labels), snapshot + ) + whole.end_epoch() + chunked.end_epoch() + np.testing.assert_allclose( + as_numpy(chunked.finalize()), + as_numpy(whole.finalize()), + rtol=1e-6, + atol=1e-6, + ) + np.testing.assert_allclose( + as_numpy(chunked.obj), + as_numpy(whole.obj), + rtol=1e-6, + atol=1e-6, + ) + self.assertEqual(chunked.n_splits, whole.n_splits) + self.assertIsNone(chunked.assignments) + + def test_max_points_per_centroid_trains_on_a_seeded_subset(self): + data = np.random.RandomState(0).rand(400, 4).astype("float32") + args = dict(nepochs=2, batch_size=32, alpha0=0.3, seed=5) + for backend, array in self.reference_arrays(): + cls = backend_class(backend) + options = dict(args, **native_options(backend)) + exact = backend in ("numpy", "cpu") + check = np.testing.assert_array_equal if exact else ( + lambda a, b: np.testing.assert_allclose(a, b, rtol=1e-4, atol=1e-5)) + with self.subTest(backend=backend), highest_fp32(backend): + rows = array(data) + capped = cls(4, 8, max_points_per_centroid=10, **options) + centroids, labels = capped.train(rows) + labels = as_numpy(labels) + self.assertEqual(labels.shape, (400,)) + kept = np.flatnonzero(labels >= 0) + self.assertEqual(len(kept), 80) + self.assertEqual(max(capped.recipe["epoch_rows"]), 80) + ref_centroids, ref_labels = cls(4, 8, **options).train(array(data[kept])) + check(as_numpy(centroids), as_numpy(ref_centroids)) + if exact: + np.testing.assert_array_equal(labels[kept], as_numpy(ref_labels)) + loose = cls(4, 8, max_points_per_centroid=50, **options).train(rows) + plain = cls(4, 8, **options).train(rows) + check(as_numpy(loose[0]), as_numpy(plain[0])) + with self.assertRaisesRegex(ValueError, "max_points_per_centroid"): + cls(4, 8, max_points_per_centroid=0) + if backend != "numpy": + # Seeds the tensor model accepts also work when the cap binds. + for seed in (-1, 2**40): + model = cls(4, 8, max_points_per_centroid=10, nepochs=1, + batch_size=32, alpha0=0.3, seed=seed, + **native_options(backend)) + _, labels = model.train(rows) + self.assertEqual(int((as_numpy(labels) >= 0).sum()), 80) + self.assertEqual(model.seed, seed) + # A failure while mapping labels back marks the run failed and + # exposes no partial labels. + failing = cls(4, 8, max_points_per_centroid=10, **options) + wrong_length = array([0, 0, 0], "int64") # cannot fill the 80 sampled rows + with mock.patch.object(failing, "_train_rows", return_value=(None, wrong_length)): + with self.assertRaises((ValueError, RuntimeError, IndexError)): + failing.train(rows) + self.assertTrue(failing._failed) + self.assertIsNone(failing.assignments) + + def test_last_pass_labels_are_owned_and_not_final_nearest(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend), highest_fp32(backend): + rows = array([[0.0], [1.0], [49.0], [51.0], [52.0], [53.0]]) + initial = array([[0.0], [100.0]]) + args = {"nepochs": 1, "batch_size": 6, "alpha0": 0.5, "seed": 7} + model = Emeans(1, 2, capture_assignments=True, **args, **native_options(backend)) + self.assertIsNone(model.assignments) + model.train(rows, initial) + labels = model.assignments + np.testing.assert_array_equal( + as_numpy(labels), [0, 0, 0, 1, 1, 1] + ) + self.assertEqual(as_numpy(labels).dtype, np.dtype("int64")) + np.testing.assert_allclose( + as_numpy(model.centroids), [[50 / 3], [52]], rtol=1e-6 + ) + _, nearest = model.assign(rows) + self.assertEqual(int(nearest[2]), 1) + self.assertEqual(int(labels[2]), 0) + disabled = Emeans(1, 2, capture_assignments=False, **args, **native_options(backend)) + disabled.train(rows, initial) + self.assertIsNone(disabled.assignments) + np.testing.assert_array_equal( + as_numpy(model.centroids), as_numpy(disabled.centroids) + ) + np.testing.assert_array_equal( + as_numpy(model.obj), as_numpy(disabled.obj) + ) + model = Emeans(1, 2, capture_assignments=True, **args, **native_options(backend)) + self.assertIsNone(model.assignments) + np.testing.assert_array_equal( + as_numpy(labels), [0, 0, 0, 1, 1, 1] + ) + model.begin(6, initial) + model.accumulate(rows[:2]) + model = Emeans(1, 2, capture_assignments=True, **args, **native_options(backend)) + self.assertIsNone(model.assignments) + model.train(rows, initial) + np.testing.assert_array_equal( + as_numpy(model.assignments), as_numpy(labels) + ) + + def test_pending_execution_failure_requires_new_run(self): + class InjectedFailure(BaseException): + pass + + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + # The view forces real input preparation for the three-row + # continuation rather than testing only contiguous aliases. + rows = array( + [[0.0, 99.0], [2.0, 99.0], [10.0, 99.0], [12.0, 99.0]] + )[:, :1] + initial = rows[[0, 2]] + model = Emeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + capture_assignments=True, + **native_options(backend), + ) + for stage in ("assignment",): + with self.subTest(stage=stage): + model.begin(4, initial) + first = model.accumulate(rows[:1]) + labels, saved = ( + first["labels"], + as_numpy(first["labels"]).copy(), + ) + owner = model + name = "_assign_rows" + original = getattr(owner, name) + + def fail_after_work(*args, original=original): + original(*args) + raise InjectedFailure("after tensor work") + + with mock.patch.object( + owner, name, side_effect=fail_after_work + ): + with self.assertRaises(InjectedFailure): + model.accumulate(rows[1:]) + self.assertIsNone(model.assignments) + for operation in ( + lambda model=model, rows=rows: model.accumulate( + rows + ), + lambda model=model: model.update({}), + model.end_epoch, + model.finalize, + model.current_centroids, + ): + with self.assertRaises(RuntimeError): + operation() + np.testing.assert_array_equal(as_numpy(labels), saved) + model = Emeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + capture_assignments=True, + **native_options(backend), + ) + model.begin(4, initial) + model.update(model.accumulate(rows)) + model.end_epoch() + np.testing.assert_array_equal( + as_numpy(model.finalize()), [[1.0], [11.0]] + ) + + def test_external_statistics_and_result_ownership(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + initial = array([[0.0], [10.0]]) + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5, unused_threshold=0, + **native_options(backend)) + model.begin(4, initial) + initial[...] = 7 + self.assertIsNone(model.centroids) + current = model.current_centroids() + np.testing.assert_array_equal( + as_numpy(current), [[0.0], [10.0]] + ) + self.assertEqual(tuple(current.shape), (2, 1)) + if backend == "numpy": + import faiss + + self.assertEqual(current.dtype, np.dtype("float32")) + self.assertTrue( + np.shares_memory(current, model.current_centroids()) + ) + self.assertFalse(current.flags.writeable) + with self.assertRaises(ValueError): + current[0, 0] = 1 + distance, labels = faiss.knn( + array([[0.0], [10.0]]), current, 1 + ) + np.testing.assert_array_equal(distance, [[0.0], [0.0]]) + np.testing.assert_array_equal(labels, [[0], [1]]) + snapshot = current.copy() + else: + self.assertEqual(current.dtype, initial.dtype) + self.assertEqual(current.device, initial.device) + self.assertFalse(current.requires_grad) + self.assertIsNone(current.grad_fn) + self.assertEqual( + current.data_ptr(), model.current_centroids().data_ptr() + ) + snapshot = current.clone() + empty = model.accumulate(array(np.empty((0, 1)))) + self.assertEqual(empty["n"], 0) + np.testing.assert_array_equal(as_numpy(empty["counts"]), [0, 0]) + # Closing leaves one cluster untouched: a begin alias cannot + # be masked by overwriting every centroid with new means. + combined = { + "sums": array([[8.0], [0.0]]), + "counts": array([4.0, 0.0]), + "objective": array(8.0, "float64"), + "n": 4, + } + model.update(combined) + expected = np.float32(8.0 / (4.0 + 2**-16)) + np.testing.assert_allclose( + as_numpy(model.current_centroids()), + [[expected], [10.0]], + rtol=2e-7, + ) + np.testing.assert_array_equal( + as_numpy(snapshot), [[0.0], [10.0]] + ) + self.assertIsNone(model.centroids) + before_end = as_numpy(model.current_centroids()).copy() + model.end_epoch() + np.testing.assert_array_equal( + as_numpy(model.current_centroids()), before_end + ) + result = model.finalize() + np.testing.assert_array_equal(as_numpy(result), [[2.0], [10.0]]) + self.assertIs(model.finalize(), result) + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5, unused_threshold=0, + **native_options(backend)) + np.testing.assert_array_equal(as_numpy(result), [[2.0], [10.0]]) + model.begin(4, array([[3.0], [13.0]])) + np.testing.assert_array_equal( + as_numpy(model.current_centroids()), [[3.0], [13.0]] + ) + rows = array([[3.0], [5.0], [3.0], [5.0]]) + model.accumulate(rows[:0]) + partial = model.accumulate(rows[:2]) + self.assertEqual(partial["n"], 2) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + complete = model.accumulate(rows[2:]) + empty = model.accumulate(rows[:0]) + for field in ("sums", "counts", "objective"): + np.testing.assert_array_equal( + as_numpy(empty[field]), as_numpy(complete[field]) + ) + copied = { + field: ( + empty[field].copy() + if backend == "numpy" + else empty[field].clone() + ) + for field in ("sums", "counts", "objective") + } + copied["n"] = empty["n"] + model.update(copied) + model.end_epoch() + np.testing.assert_array_equal( + as_numpy(model.finalize()), [[4.0], [13.0]] + ) + + def test_fractional_near_tie_selected_distance(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend), highest_fp32(backend): + model = Emeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + assignment_chunk_size=1, + **({"centroid_chunk_size": 1} if backend != "numpy" else {}), + **native_options(backend), + ) + model.train( + array([[0.0], [0.0], [1.0], [1.0]]), array([[0.0], [1.0]]) + ) + query = array([[0.5 + 2**-12], [0.5 - 2**-12], [0.5]]) + distance, labels = model.assign(query) + direct = ( + as_numpy(query).astype("float64") + - as_numpy(model.centroids).astype("float64").T + ) ** 2 + np.testing.assert_array_equal(as_numpy(labels), [1, 0, 0]) + # Dyadic inputs and a resolved margin, not a requirement that + # arbitrary near-ties survive expanded-L2 cancellation. + np.testing.assert_allclose( + as_numpy(distance), direct.min(axis=1), rtol=0, atol=1e-7 + ) + + def test_initial_mass_first_update_and_zero_mass_reentry(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + for alpha, zero_mass, position in ( + (0.5, False, 3.0), + (1.0, False, 1e8), + (0.5, True, 1e8), + ): + with self.subTest( + backend=backend, alpha=alpha, zero_mass=zero_mass + ): + # Caller-made statistics need mass-based revival. + model = Emeans(1, 2, nepochs=2, batch_size=2, alpha0=alpha, unused_threshold=0, + **native_options(backend)) + model.begin(2, array([[position], [8.25]])) + self.assertEqual(model.recipe["init_usage"], 2**-16) + # First-step state is not exposed before closing. Inject + # zero mass only to isolate the documented reentry case. + if zero_mass: + model._usage[0] = 0 + mass = 0.0 if zero_mass else 2**-16 + count = 2.0 + weight = ( + alpha * count / ((1 - alpha) * mass + alpha * count) + ) + expected = ( + 1.0 + if weight == 1 + else position + weight * (1 - position) + ) + model.update( + { + "sums": array([[2.0], [0.0]]), + "counts": array([2.0, 0.0]), + "objective": array(7.0, "float64"), + "n": 2, + } + ) + np.testing.assert_allclose( + as_numpy(model._centroids), + [[expected], [8.25]], + rtol=2e-7, + ) + unused_mass = 2**-16 if alpha == 1 else (1 - alpha) * 2**-16 + self.assertEqual(float(model._usage[1]), unused_mass) + del model + + def test_untouched_underflow_and_independent_ema(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + model = Emeans(1, 2, nepochs=1, batch_size=1, alpha0=0.9, unused_threshold=0, + **native_options(backend)) + model.begin(400, array([[0.0], [8.25]])) + mass, position = 2**-16, 0.0 + # Disable revival only to isolate decay/EMA; separate tests + # exercise real revival and closing without this probe. + with mock.patch.object(model, "_revive_unused", return_value=0): + for step in range(400): + value = (step % 7 - 3) / 8 + alpha = e_means._scheduled_alpha(0.9, step, 400) + mass = (1 - alpha) * mass + alpha + position += alpha / mass * (value - position) + model.update( + { + "sums": array([[value], [0.0]]), + "counts": array([1.0, 0.0]), + "objective": array(0.0, "float64"), + "n": 1, + } + ) + # Retained bounded fixture's FP64 scalar oracle and + # tolerance, not a new universal rounding guarantee. + np.testing.assert_allclose( + float(model._centroids[0, 0]), + position, + rtol=3e-6, + atol=3e-7, + ) + self.assertEqual(float(model._centroids[1, 0]), 8.25) + self.assertLessEqual( + float(model._usage[1]), np.finfo("float32").tiny + ) + model.end_epoch() + self.assertEqual(float(model.finalize()[1, 0]), 8.25) + + def test_revival_threshold_separation_and_conservation(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + helpers = backend_helpers(backend) + with self.subTest(backend=backend): + model = Emeans(1, 3, unused_threshold=0.1, **native_options(backend)) + model.begin(3, array([[10.0], [20.0], [30.0]])) + # Controlled masses make the otherwise private revival + # threshold/conservation boundary directly observable. + model._usage[:] = array([27.715767, 0.38280505, 803.37445]) + before = as_numpy(model._usage).copy() + coefficient = np.float32(model.recipe["unused_threshold"]) + expected = np.float32( + np.float32(before.sum(dtype="float32") * coefficient) / 3 + ) + large = array([69938690.0]) + if backend == "numpy": + actual = e_means._numpy_unused_threshold(before, 3) + large_threshold = e_means._numpy_unused_threshold( + large, 52359 + ) + else: + # Exercise Torch's own reduction/multiply/divide path, + # rather than repeating the NumPy helper for CUDA inputs. + actual = ( + model._usage.sum() + * model.recipe["unused_threshold"] + / model.k + ) + large_threshold = ( + large.sum() * model.recipe["unused_threshold"] / 52359 + ) + self.assertEqual(as_numpy(actual).dtype, np.dtype("float32")) + self.assertEqual(float(actual), expected) + self.assertEqual( + int(as_numpy(actual).view("uint32")), 1105050084 + ) + self.assertEqual( + as_numpy(large_threshold).dtype, np.dtype("float32") + ) + self.assertEqual( + int(as_numpy(large_threshold).view("uint32")), 1124438855 + ) + np.testing.assert_array_equal( + before < float(actual), [False, True, False] + ) + weighted = (as_numpy(model._centroids) * before[:, None]).sum( + axis=0 + ) + discarded = as_numpy(model._centroids)[1] * before[1] + if backend == "numpy": + rng = np.random.RandomState(123) + else: + import torch + + rng = torch.Generator( + device=model._usage.device + ).manual_seed(123) + self.assertEqual(model._revive_unused(rng), 1) + # Infer the sampled donor rather than pinning CPU/CUDA RNG. + # No rows yet (U = 0): both copies start at the donor and the + # child moves to the next representable value. + after = as_numpy(model._usage) + source = np.flatnonzero((before != after) & (np.arange(3) != 1)) + self.assertEqual(len(source), 1) + source = int(source[0]) + initial_position = np.float32([10.0, 20.0, 30.0][source]) + state = as_numpy(model._centroids) + np.testing.assert_array_equal(state[source], [initial_position]) + np.testing.assert_array_equal( + state[1], [np.nextafter(initial_position, np.float32(np.inf))] + ) + other = 2 if source == 0 else 0 + np.testing.assert_array_equal( + state[other], [[10.0], [20.0], [30.0]][other] + ) + np.testing.assert_allclose( + as_numpy(model._usage).sum(), before.sum() - before[1] + ) + np.testing.assert_allclose( + ( + as_numpy(model._centroids) + * as_numpy(model._usage)[:, None] + ).sum(axis=0), + weighted - discarded, + ) + donor = array([[0.0, 0.0], [2.0, 3.0], [1.0, 0.0]]) + child = array([[0.0, 0.0], [2.0002, 2.9997], [1.0, 0.0]]) + ordinary = as_numpy(child)[1].copy() + helpers._separate_splits(donor, child) + result = as_numpy(child) + self.assertEqual( + result[0, 0], + np.nextafter(np.float32(0), np.float32(np.inf)), + ) + self.assertEqual( + result[2, 0], + np.nextafter(np.float32(1), np.float32(np.inf)), + ) + np.testing.assert_array_equal(result[1], ordinary) + # One donor and two unused clusters: at most one is revived, + # the donor/child separate, and the third is left untouched. + unique = Emeans(2, 3, unused_threshold=0.1, **native_options(backend)) + unique.begin(3, array([[0.0, 0.0], [10.0, 10.0], [20.0, 20.0]])) + unique._usage[:] = array([10.0, 0.0, 0.0]) + self.assertEqual(unique._revive_unused(rng), 1) + np.testing.assert_array_equal( + as_numpy(unique._usage), [5.0, 5.0, 0.0] + ) + state = as_numpy(unique._centroids) + self.assertFalse(np.array_equal(state[0], state[1])) + np.testing.assert_array_equal(state[2], [20.0, 20.0]) + + def test_closing_statistics_survive_revival_and_object_deletion(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + model = Emeans(1, 2, nepochs=1, batch_size=1, alpha0=0.5, unused_threshold=0.1, + **native_options(backend)) + model.begin(5, array([[0.0], [100.0]])) + # No caller holds these working allocations. Check release, + # not cache keys or an optimization's storage identity. + batch_owner = weakref.ref(model._batch_stats) + closing_owner = weakref.ref(model._pass_sums) + for value in range(5): + model.update( + { + "sums": array([[float(value)], [0.0]]), + "counts": array([1.0, 0.0]), + "objective": array(1.0, "float64"), + "n": 1, + } + ) + self.assertEqual(model.n_splits, 1) + revived = float(model._centroids[1, 0]) + model.end_epoch() + result = model.finalize() + np.testing.assert_array_equal( + as_numpy(result), [[2.0], [revived]] + ) + self.assertEqual(float(model.obj[0]), 5.0) + self.assertEqual( + model.iteration_stats[0]["imbalance_factor"], 2.0 + ) + self.assertIs(model.finalize(), result) + before = as_numpy(result).copy() + del model + np.testing.assert_array_equal(as_numpy(result), before) + self.assertIsNone(batch_owner()) + self.assertIsNone(closing_owner()) + + def test_fractional_caller_and_matrix_training(self): + for backend, array in self.reference_arrays(): + Emeans = backend_class(backend) + with self.subTest(backend=backend): + x = array(np.arange(51, dtype="float32").reshape(17, 3) / 10) + initial = x[[0, 5, 10, 16]] + args = dict( + nepochs=3, + batch_size=4, + alpha0=0.2, + seed=7, + assignment_chunk_size=2, + **({"centroid_chunk_size": 2} if backend != "numpy" else {}) + ) + matrix, caller = Emeans(3, 4, **args, **native_options(backend)), Emeans(3, 4, **args, **native_options(backend)) + matrix.train(x, initial) + caller.begin(len(x), initial) + for epoch in range(3): + seed = e_means._epoch_seed(7, epoch) + if backend == "numpy": + order = np.random.RandomState(seed).permutation(len(x)) + else: + import torch + + generator = torch.Generator( + device=x.device + ).manual_seed(seed) + order = torch.randperm( + len(x), generator=generator, device=x.device + ) + for begin in range(0, len(x), 4): + caller.update( + caller.accumulate(x[order[begin : begin + 4]]) + ) + caller.end_epoch() + np.testing.assert_allclose( + as_numpy(caller.finalize()), + as_numpy(matrix.centroids), + rtol=1e-6, + atol=1e-6, + ) + # Existing decimal-fixture limits account for the retained + # FP32 addition/cancellation order; exact binary coverage stays. + atol = 3e-5 if backend == "cuda" else 1e-5 + np.testing.assert_allclose( + as_numpy(caller.obj), + as_numpy(matrix.obj), + rtol=1e-6, + atol=atol, + ) + self.assertEqual(caller.n_splits, matrix.n_splits) diff --git a/thirdparty/faiss/tests/external_module_test.py b/thirdparty/faiss/tests/external_module_test.py index 15f280918..af69806e8 100644 --- a/thirdparty/faiss/tests/external_module_test.py +++ b/thirdparty/faiss/tests/external_module_test.py @@ -13,7 +13,6 @@ class TestCustomIDSelector(unittest.TestCase): - """test if we can construct a custom IDSelector""" def test_IDSelector(self): ids = external_module.IDSelectorModulo(3) @@ -28,39 +27,21 @@ def test_idx_array(self): new_sum = external_module.sum_of_idx(len(tab), faiss.swig_ptr(tab)) self.assertEqual(new_sum, tab.sum()) - def do_array_test(self, ty): - tab = np.arange(10).astype(ty) - func = getattr(external_module, "sum_of_" + ty) - print("perceived type", faiss.swig_ptr(tab)) - new_sum = func(len(tab), faiss.swig_ptr(tab)) - self.assertEqual(new_sum, tab.sum()) - - def test_sum_uint8(self): - self.do_array_test("uint8") - - def test_sum_uint16(self): - self.do_array_test("uint16") - - def test_sum_uint32(self): - self.do_array_test("uint32") - - def test_sum_uint64(self): - self.do_array_test("uint64") - - def test_sum_int8(self): - self.do_array_test("int8") - - def test_sum_int16(self): - self.do_array_test("int16") - - def test_sum_int32(self): - self.do_array_test("int32") - - def test_sum_int64(self): - self.do_array_test("int64") - - def test_sum_float32(self): - self.do_array_test("float32") - - def test_sum_float64(self): - self.do_array_test("float64") + def test_sum_all_types(self): + for ty in ( + "uint8", + "uint16", + "uint32", + "uint64", + "int8", + "int16", + "int32", + "int64", + "float32", + "float64", + ): + with self.subTest(ty=ty): + tab = np.arange(10).astype(ty) + func = getattr(external_module, "sum_of_" + ty) + new_sum = func(len(tab), faiss.swig_ptr(tab)) + self.assertEqual(new_sum, tab.sum()) diff --git a/thirdparty/faiss/tests/test_NSG_compressed_graph.cpp b/thirdparty/faiss/tests/test_NSG_compressed_graph.cpp index ab0f4f468..db13b7dd2 100644 --- a/thirdparty/faiss/tests/test_NSG_compressed_graph.cpp +++ b/thirdparty/faiss/tests/test_NSG_compressed_graph.cpp @@ -73,7 +73,6 @@ TEST(NSGCompressed, test_compressed) { std::vector Dref(nq * k); index.search(nq, xq, k, Dref.data(), Iref.data()); - // replace the shared ptr index.nsg.final_graph.reset( new CompressedNSGGraph(*index.nsg.final_graph, 13)); @@ -81,20 +80,12 @@ TEST(NSGCompressed, test_compressed) { std::vector D(nq * k); index.search(nq, xq, k, D.data(), I.data()); - // make sure we find back the original results EXPECT_EQ(Iref, I); EXPECT_EQ(Dref, D); } -// Regression test for sync_prune out-of-bounds bug. -// -// With ntotal=1 and L=1, search_on_graph produces pool = [{id:0}]. -// sync_prune(q=0): pool[0].id == q → start++ → start == pool.size(). -// Old code: pool[start] is out-of-bounds → undefined behavior. -// Fix: guard returns early and fills graph row with EMPTY_ID. -// -// Calls NSG::build() directly (bypassing IndexNSG::check_knn_graph) -// to reach the edge case with ntotal=1. +// Regression: sync_prune read past the pool end with ntotal=1, L=1. Calls +// NSG::build directly to bypass IndexNSG::check_knn_graph. TEST(NSGBugs, SyncPruneSingleNode) { constexpr int d = 4; constexpr int R = 1; @@ -109,12 +100,9 @@ TEST(NSGBugs, SyncPruneSingleNode) { faiss::NSG nsg_obj(R); nsg_obj.L = 1; - // Old code crashes here. Fixed code handles it. ASSERT_NO_THROW(nsg_obj.build(&storage, 1, knn_graph, false)); - EXPECT_TRUE(nsg_obj.is_built); EXPECT_EQ(nsg_obj.enterpoint, 0); - // Search returns the only node nsg_obj.search_L = 1; std::unique_ptr vt = faiss::VisitedTable::create(1); auto dis = std::unique_ptr( diff --git a/thirdparty/faiss/tests/test_RCQ_cropping.cpp b/thirdparty/faiss/tests/test_RCQ_cropping.cpp deleted file mode 100644 index 4d59f6e38..000000000 --- a/thirdparty/faiss/tests/test_RCQ_cropping.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include - -/* This test creates a 3-level RCQ and performs a search on it. - * Then it crops the RCQ to just the 2 first levels and verifies that - * the 3-level vectors are in a subtree that was visited in the 2-level RCQ. */ -TEST(RCQCropping, test_cropping) { - size_t nq = 10, nt = 2000, nb = 1000, d = 32; - - using idx_t = faiss::idx_t; - - std::vector buf((nq + nb + nt) * d); - faiss::rand_smooth_vectors(nq + nb + nt, d, buf.data(), 1234); - const float* xt = buf.data(); - const float* xb = xt + nt * d; - const float* xq = xb + nb * d; - - std::vector nbits = {5, 4, 4}; - faiss::ResidualCoarseQuantizer rcq(d, nbits); - - rcq.train(nt, xt); - - // the test below works only for beam size == nprobe - rcq.set_beam_factor(1.0); - - // perform search - int nprobe = 15; - std::vector Iref(nq * nprobe); - std::vector Dref(nq * nprobe); - rcq.search(nq, xq, nprobe, Dref.data(), Iref.data()); - - // crop to the first 2 quantization levels - int last_nbits = nbits.back(); - nbits.pop_back(); - faiss::ResidualCoarseQuantizer rcq_cropped(d, nbits); - rcq_cropped.initialize_from(rcq); - - EXPECT_EQ(rcq_cropped.ntotal, rcq.ntotal >> last_nbits); - - // perform search - std::vector Inew(nq * nprobe); - std::vector Dnew(nq * nprobe); - rcq_cropped.search(nq, xq, nprobe, Dnew.data(), Inew.data()); - - // these bits are in common between the two RCQs - idx_t mask = ((idx_t)1 << rcq_cropped.rq.tot_bits) - 1; - for (size_t q = 0; q < nq; q++) { - for (int i = 0; i < nprobe; i++) { - idx_t fine = Iref[q * nprobe + i]; - EXPECT_GE(fine, 0); - bool found = false; - - // fine should be generated from a path that passes through coarse - for (int j = 0; j < nprobe; j++) { - idx_t coarse = Inew[q * nprobe + j]; - if ((fine & mask) == coarse) { - found = true; - break; - } - } - EXPECT_TRUE(found); - } - } -} - -TEST(RCQCropping, search_params) { - size_t nq = 10, nt = 2000, nb = 1000, d = 32; - - using idx_t = faiss::idx_t; - - std::vector buf((nq + nb + nt) * d); - faiss::rand_smooth_vectors(nq + nb + nt, d, buf.data(), 1234); - const float* xt = buf.data(); - const float* xb = xt + nt * d; - const float* xq = xb + nb * d; - - std::vector nbits = {3, 6, 3}; - faiss::ResidualCoarseQuantizer quantizer(d, nbits); - size_t ntotal = (size_t)1 << quantizer.rq.tot_bits; - faiss::IndexIVFScalarQuantizer index( - &quantizer, d, ntotal, faiss::ScalarQuantizer::QT_8bit); - index.quantizer_trains_alone = true; - - index.train(nt, xt); - index.add(nb, xb); - - index.nprobe = 10; - - int k = 4; - float beam_factor_1 = 8.0; - quantizer.set_beam_factor(beam_factor_1); - std::vector I1(nq * k); - std::vector D1(nq * k); - index.search(nq, xq, k, D1.data(), I1.data()); - - // change from 8 to 1 - quantizer.set_beam_factor(1.0f); - std::vector I2(nq * k); - std::vector D2(nq * k); - index.search(nq, xq, k, D2.data(), I2.data()); - - // make sure it changes the result - EXPECT_NE(I1, I2); - EXPECT_NE(D1, D2); - - // override the class level beam factor - faiss::SearchParametersResidualCoarseQuantizer params1; - params1.beam_factor = beam_factor_1; - faiss::SearchParametersIVF params; - params.nprobe = index.nprobe; - params.quantizer_params = ¶ms1; - - std::vector I3(nq * k); - std::vector D3(nq * k); - index.search(nq, xq, k, D3.data(), I3.data(), ¶ms); - - // make sure we find back the original results - EXPECT_EQ(I1, I3); - EXPECT_EQ(D1, D3); -} diff --git a/thirdparty/faiss/tests/test_approx_topk.cpp b/thirdparty/faiss/tests/test_approx_topk.cpp index ebfe01f8a..572ddc851 100644 --- a/thirdparty/faiss/tests/test_approx_topk.cpp +++ b/thirdparty/faiss/tests/test_approx_topk.cpp @@ -7,54 +7,30 @@ #include -#include #include #include -#include -#include #include #include #include -#include #include -// using namespace faiss; -// template void test_approx_topk( const uint32_t beamSize, const uint32_t nPerBeam, const uint32_t k, - const uint32_t nDatasetsToTest, - const bool verbose) { - if (verbose) { - printf("-----------\n"); - } - - // generate random data + const uint32_t nDatasetsToTest) { std::default_random_engine rng(123); std::uniform_real_distribution u(0, 1); - // matches - size_t nMatches = 0; // the element was completely missed in approx version. size_t nMissed = 0; // the element is available size_t nAvailable = 0; - // the distance is the same, but the index is different. - size_t nSoftMismatches = 0; - // the distances are different - size_t nHardMismatches = 0; - // error of distances - double sqrError = 0.0; - - // - double timeBaseline = 0.0; - double timeApprox = 0.0; for (size_t iDataset = 0; iDataset < nDatasetsToTest; iDataset++) { const size_t n = (size_t)(nPerBeam)*beamSize; @@ -63,14 +39,11 @@ void test_approx_topk( distances[i] = u(rng); } - // using C = CMax; - // do a regular beam search std::vector baselineDistances(k, C::neutral()); std::vector baselineIndices(k, -1); - auto startBaseline = std::chrono::high_resolution_clock::now(); heap_addn( k, baselineDistances.data(), @@ -78,76 +51,18 @@ void test_approx_topk( distances.data(), nullptr, nPerBeam * beamSize); - auto endBaseline = std::chrono::high_resolution_clock::now(); - std::chrono::duration diffBaseline = - endBaseline - startBaseline; - timeBaseline += diffBaseline.count(); - - heap_reorder(k, baselineDistances.data(), baselineIndices.data()); - // do an approximate beam search std::vector approxDistances(k, C::neutral()); std::vector approxIndices(k, -1); - auto startApprox = std::chrono::high_resolution_clock::now(); - try { - HeapWithBuckets::bs_addn( - beamSize, - nPerBeam, - distances.data(), - k, - approxDistances.data(), - approxIndices.data()); - } catch (const faiss::FaissException&) { - // - if (verbose) { - printf("Skipping the case.\n"); - } - return; - } - - auto endApprox = std::chrono::high_resolution_clock::now(); - std::chrono::duration diffApprox = endApprox - startApprox; - timeApprox += diffApprox.count(); - - heap_reorder(k, approxDistances.data(), approxIndices.data()); - - bool bGotMismatches = false; - - // the error - for (uint32_t i = 0; i < k; i++) { - if (baselineDistances[i] != approxDistances[i]) { - nHardMismatches += 1; - - double diff = baselineDistances[i] - approxDistances[i]; - sqrError += diff * diff; - - bGotMismatches = true; - - if (verbose) { - printf("i=%d, bs.d=%f, bs.i=%d, app.d=%f, app.i=%d\n", - i, - baselineDistances[i], - baselineIndices[i], - approxDistances[i], - approxIndices[i]); - } - } else { - if (baselineIndices[i] != approxIndices[i]) { - nSoftMismatches += 1; - } else { - nMatches += 1; - } - } - } - - if (bGotMismatches) { - if (verbose) { - printf("\n"); - } - } + HeapWithBuckets::bs_addn( + beamSize, + nPerBeam, + distances.data(), + k, + approxDistances.data(), + approxIndices.data()); - // std::unordered_set bsIndicesHS( baselineIndices.cbegin(), baselineIndices.cend()); for (uint32_t i = 0; i < k; i++) { @@ -160,65 +75,29 @@ void test_approx_topk( } } - if (verbose) { - printf("%d, %d, %d, %d, %d, %d: %ld, %ld, %ld, %f, %ld, %ld, %f, %f\n", - NBUCKETS, - N, - beamSize, - nPerBeam, - k, - nDatasetsToTest, - nMatches, - nSoftMismatches, - nHardMismatches, - sqrError, - nAvailable, - nMissed, - timeBaseline, - timeApprox); - } - // just confirm that the error is not crazy if (NBUCKETS * N * beamSize >= k) { EXPECT_TRUE(nAvailable > nMissed); - } else { - // it is possible that the results are crazy here. Skip it. } } -// TEST(testApproxTopk, COMMON) { - constexpr bool verbose = false; - - // const uint32_t nDifferentDatasets = 8; uint32_t kValues[] = {1, 2, 3, 5, 8, 13, 21, 34}; - for (size_t codebookBitSize = 8; codebookBitSize <= 10; codebookBitSize++) { - const uint32_t codebookSize = 1 << codebookBitSize; - for (const auto k : kValues) { - test_approx_topk<1 * 8, 3>( - 1, codebookSize, k, nDifferentDatasets, verbose); - test_approx_topk<1 * 8, 3>( - k, codebookSize, k, nDifferentDatasets, verbose); - - test_approx_topk<1 * 8, 2>( - 1, codebookSize, k, nDifferentDatasets, verbose); - test_approx_topk<1 * 8, 2>( - k, codebookSize, k, nDifferentDatasets, verbose); - - test_approx_topk<2 * 8, 2>( - 1, codebookSize, k, nDifferentDatasets, verbose); - test_approx_topk<2 * 8, 2>( - k, codebookSize, k, nDifferentDatasets, verbose); - - test_approx_topk<4 * 8, 2>( - 1, codebookSize, k, nDifferentDatasets, verbose); - test_approx_topk<4 * 8, 2>( - k, codebookSize, k, nDifferentDatasets, verbose); - } + const uint32_t codebookSize = 256; + for (const auto k : kValues) { + test_approx_topk<1 * 8, 3>(1, codebookSize, k, nDifferentDatasets); + test_approx_topk<1 * 8, 3>(k, codebookSize, k, nDifferentDatasets); + + test_approx_topk<1 * 8, 2>(1, codebookSize, k, nDifferentDatasets); + test_approx_topk<1 * 8, 2>(k, codebookSize, k, nDifferentDatasets); + + test_approx_topk<2 * 8, 2>(1, codebookSize, k, nDifferentDatasets); + test_approx_topk<2 * 8, 2>(k, codebookSize, k, nDifferentDatasets); + + test_approx_topk<4 * 8, 2>(1, codebookSize, k, nDifferentDatasets); + test_approx_topk<4 * 8, 2>(k, codebookSize, k, nDifferentDatasets); } } - -// diff --git a/thirdparty/faiss/tests/test_autotune.py b/thirdparty/faiss/tests/test_autotune.py index c7ca82eb6..374470d20 100644 --- a/thirdparty/faiss/tests/test_autotune.py +++ b/thirdparty/faiss/tests/test_autotune.py @@ -8,18 +8,9 @@ import numpy as np import faiss -from common_faiss_tests import for_all_simd_levels - -@for_all_simd_levels class TestParameterSpace(unittest.TestCase): - def test_nprobe(self): - index = faiss.index_factory(32, "IVF32,Flat") - ps = faiss.ParameterSpace() - ps.set_index_parameter(index, "nprobe", 5) - self.assertEqual(index.nprobe, 5) - def test_nprobe_2(self): index = faiss.index_factory(32, "IDMap,IVF32,Flat") ps = faiss.ParameterSpace() @@ -27,13 +18,6 @@ def test_nprobe_2(self): index2 = faiss.downcast_index(index.index) self.assertEqual(index2.nprobe, 5) - def test_nprobe_3(self): - index = faiss.index_factory(32, "IVF32,SQ8,RFlat") - ps = faiss.ParameterSpace() - ps.set_index_parameter(index, "nprobe", 5) - index2 = faiss.downcast_index(index.base_index) - self.assertEqual(index2.nprobe, 5) - def test_nprobe_4(self): index = faiss.index_factory(32, "PCAR32,IVF32,SQ8,RFlat") ps = faiss.ParameterSpace() @@ -53,25 +37,18 @@ def test_efSearch(self): class TestAutoTuneCriterion(unittest.TestCase): - def test_set_groundtruth_with_distances(self): + def test_set_groundtruth(self): nq, gt_nnn = 10, 5 crit = faiss.OneRecallAtRCriterion(nq, gt_nnn) rng = np.random.default_rng(42) gt_I = rng.integers(0, 100, size=(nq, gt_nnn)).astype("int64") gt_D = rng.random(size=(nq, gt_nnn)).astype("float32") - crit.set_groundtruth(gt_D, gt_I) - self.assertEqual(crit.gt_nnn, gt_nnn) - self.assertEqual(crit.gt_I.size(), nq * gt_nnn) - - def test_set_groundtruth_null_distances(self): # gt_D is documented as optional (None skips the distances copy). - nq, gt_nnn = 10, 5 - crit = faiss.OneRecallAtRCriterion(nq, gt_nnn) - rng = np.random.default_rng(42) - gt_I = rng.integers(0, 100, size=(nq, gt_nnn)).astype("int64") crit.set_groundtruth(None, gt_I) self.assertEqual(crit.gt_nnn, gt_nnn) self.assertEqual(crit.gt_I.size(), nq * gt_nnn) + crit.set_groundtruth(gt_D, gt_I) + self.assertEqual(crit.gt_D.size(), nq * gt_nnn) class TestOperatingPoints(unittest.TestCase): @@ -79,45 +56,15 @@ def _keys(self, ops): n = ops.optimal_pts.size() return [ops.optimal_pts.at(i).key for i in range(n)] - def test_equal_time_better_perf_removes_dominated(self): - # B (perf=0.9, t=1.0) dominates A (perf=0.5, t=1.0) — same time, - # strictly better perf. A must be pruned from the optimal frontier. - ops = faiss.OperatingPoints() - self.assertTrue(ops.add(0.5, 1.0, "A")) - self.assertTrue(ops.add(0.9, 1.0, "B")) - keys = self._keys(ops) - # origin ("") + B only — A must not survive - self.assertEqual(len(keys), 2) - self.assertNotIn("A", keys, "A dominated by B; must not remain") - self.assertIn("B", keys) - def test_middle_insert_equal_time_removes_dominated(self): - # Frontier has P1=(0.5, t=1.0) and P2=(0.9, t=2.0). Adding - # P3=(0.7, t=1.0) inserts P3 in the middle and must prune P1 (same - # time, worse perf) — exercises the else-branch insertion path. + # P3 is inserted before P2 (else-branch) and prunes P1 (same time) ops = faiss.OperatingPoints() self.assertTrue(ops.add(0.5, 1.0, "P1")) self.assertTrue(ops.add(0.9, 2.0, "P2")) self.assertTrue(ops.add(0.7, 1.0, "P3")) - keys = self._keys(ops) - # origin ("") + P3 + P2 — P1 dominated by P3 at equal time - self.assertEqual(len(keys), 3) - self.assertNotIn("P1", keys, "P1 dominated by P3; must not remain") - self.assertIn("P3", keys) - self.assertIn("P2", keys) - - def test_normal_pareto_frontier_preserved(self): - # Two points where neither dominates the other: higher perf at higher - # cost vs lower perf at lower cost. Both must remain on the frontier. - ops = faiss.OperatingPoints() - self.assertTrue(ops.add(0.5, 0.5, "approximate")) - self.assertTrue(ops.add(0.9, 2.0, "accurate")) - keys = self._keys(ops) - self.assertIn("approximate", keys) - self.assertIn("accurate", keys) + self.assertEqual(self._keys(ops), ["", "P3", "P2"]) def test_worse_perf_at_equal_time_rejected(self): - # A point with worse perf and equal time is not admitted. ops = faiss.OperatingPoints() self.assertTrue(ops.add(0.9, 1.0, "good")) admitted = ops.add(0.5, 1.0, "bad") diff --git a/thirdparty/faiss/tests/test_binary_autotune.py b/thirdparty/faiss/tests/test_binary_autotune.py index 101c2b150..2aa73a641 100644 --- a/thirdparty/faiss/tests/test_binary_autotune.py +++ b/thirdparty/faiss/tests/test_binary_autotune.py @@ -10,14 +10,6 @@ class TestBinaryParameterSpace(unittest.TestCase): - def test_nprobe(self): - d = 64 - quantizer = faiss.IndexBinaryFlat(d) - index = faiss.IndexBinaryIVF(quantizer, d, 32) - ps = faiss.ParameterSpace() - ps.set_index_parameter(index, "nprobe", 5) - self.assertEqual(index.nprobe, 5) - def test_nprobe_2(self): d = 64 quantizer = faiss.IndexBinaryFlat(d) @@ -28,20 +20,6 @@ def test_nprobe_2(self): index2 = faiss.downcast_IndexBinary(index.index) self.assertEqual(index2.nprobe, 5) - def test_efSearch(self): - d = 64 - index = faiss.IndexBinaryHNSW(d, 32) - ps = faiss.ParameterSpace() - ps.set_index_parameter(index, "efSearch", 10) - self.assertEqual(index.hnsw.efSearch, 10) - - def test_efConstruction(self): - d = 64 - index = faiss.IndexBinaryHNSW(d, 32) - ps = faiss.ParameterSpace() - ps.set_index_parameter(index, "efConstruction", 40) - self.assertEqual(index.hnsw.efConstruction, 40) - def test_quantizer_efSearch(self): d = 64 quantizer = faiss.IndexBinaryHNSW(d, 32) diff --git a/thirdparty/faiss/tests/test_binary_factory.py b/thirdparty/faiss/tests/test_binary_factory.py index fc9267fe8..120147d64 100644 --- a/thirdparty/faiss/tests/test_binary_factory.py +++ b/thirdparty/faiss/tests/test_binary_factory.py @@ -14,15 +14,9 @@ class TestBinaryFactory(unittest.TestCase): def test_factory_IVF(self): index = faiss.index_binary_factory(16, "BIVF10") - assert index.invlists is not None assert index.nlist == 10 assert index.code_size == 2 - def test_factory_Flat(self): - - index = faiss.index_binary_factory(16, "BFlat") - assert index.code_size == 2 - def test_factory_HNSW(self): index = faiss.index_binary_factory(256, "BHNSW32") @@ -30,7 +24,9 @@ def test_factory_HNSW(self): def test_factory_IVF_HNSW(self): - index = faiss.index_binary_factory(256, "BIVF1024_BHNSW32") + index = faiss.index_binary_factory(256, "BIVF1024_HNSW32") + quantizer = faiss.downcast_IndexBinary(index.quantizer) + assert isinstance(quantizer, faiss.IndexBinaryHNSW) assert index.code_size == 32 assert index.nlist == 1024 diff --git a/thirdparty/faiss/tests/test_binary_flat.cpp b/thirdparty/faiss/tests/test_binary_flat.cpp deleted file mode 100644 index a3a3380b6..000000000 --- a/thirdparty/faiss/tests/test_binary_flat.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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. - */ - -#include -#include - -#include - -#include -#include - -TEST(BinaryFlat, accuracy) { - // dimension of the vectors to index - int d = 64; - - // size of the database we plan to index - size_t nb = 1000; - - // make the index object and train it - faiss::IndexBinaryFlat index(d); - - std::vector database(nb * (d / 8)); - for (size_t i = 0; i < nb * (d / 8); i++) { - database[i] = rand() % 0x100; - } - - { // populating the database - index.add(nb, database.data()); - } - - size_t nq = 200; - - { // searching the database - - std::vector queries(nq * (d / 8)); - for (size_t i = 0; i < nq * (d / 8); i++) { - queries[i] = rand() % 0x100; - } - - int k = 5; - std::vector nns(k * nq); - std::vector dis(k * nq); - - index.search(nq, queries.data(), k, dis.data(), nns.data()); - - for (size_t i = 0; i < nq; ++i) { - faiss::HammingComputer8 hc(queries.data() + i * (d / 8), d / 8); - hamdis_t dist_min = hc.hamming(database.data()); - for (size_t j = 1; j < nb; ++j) { - hamdis_t dist = hc.hamming(database.data() + j * (d / 8)); - if (dist < dist_min) { - dist_min = dist; - } - } - EXPECT_EQ(dist_min, dis[k * i]); - } - } -} diff --git a/thirdparty/faiss/tests/test_binary_hash.cpp b/thirdparty/faiss/tests/test_binary_hash.cpp index 3835ffb3b..e75d963df 100644 --- a/thirdparty/faiss/tests/test_binary_hash.cpp +++ b/thirdparty/faiss/tests/test_binary_hash.cpp @@ -16,16 +16,12 @@ // resulting index data is not an even multiple of sizeof(uint64_t), // testing that the uint64_t sized hash key extraction at the end of // the allocation boundary doesn't trigger a heap-buffer-overflow under -// ASAN. -// -// NOTE: These are not python based tests because we have more control -// over allocation behavior in C++, ensuring these tests -// deterministically fail without proper handling of access near -// the end of the allocation. +// ASAN. They are in C++ because Python does not control the allocation +// size exactly, so they would not fail deterministically. TEST(BinaryHash, SmallCodeSizeRoundTrip) { int d = 16; - int b = 5; // hash on 5 bits + int b = 5; faiss::IndexBinaryHash idx(d, b); idx.nflip = 1; @@ -73,7 +69,6 @@ TEST(BinaryHash, MultiHashResetClearsMaps) { faiss::IndexBinaryMultiHash idx(d, nhash, b); idx.nflip = 0; - // Add a vector int n = 1; std::vector data(n * idx.code_size); data[0] = 0xAA; @@ -82,24 +77,20 @@ TEST(BinaryHash, MultiHashResetClearsMaps) { EXPECT_EQ(idx.ntotal, 1); EXPECT_GT(idx.hashtable_size(), 0u); - // Reset should clear everything idx.reset(); EXPECT_EQ(idx.ntotal, 0); EXPECT_EQ(idx.hashtable_size(), 0u); - // Searching for the old vector after reset should not find it int k = 1; std::vector distances(k); std::vector labels(k); idx.search(1, data.data(), k, distances.data(), labels.data()); EXPECT_EQ(labels[0], -1); - // After reset, add a new vector and verify the index is functional std::vector data2(n * idx.code_size); data2[0] = 0x55; data2[1] = 0xAA; idx.add(n, data2.data()); - EXPECT_EQ(idx.ntotal, 1); idx.search(1, data2.data(), k, distances.data(), labels.data()); EXPECT_EQ(distances[0], 0); diff --git a/thirdparty/faiss/tests/test_binary_hashindex.py b/thirdparty/faiss/tests/test_binary_hashindex.py index e37ce44da..bc4fb1407 100644 --- a/thirdparty/faiss/tests/test_binary_hashindex.py +++ b/thirdparty/faiss/tests/test_binary_hashindex.py @@ -65,24 +65,17 @@ def test_hash(self): index = faiss.IndexBinaryHash(d, 10) index.add(xb) - # index.display() nfound = [] - ndis = [] - stats = faiss.cvar.indexBinaryHash_stats for n_bitflips in range(index.b + 1): index.nflip = n_bitflips - stats.reset() Lnew, Dnew, Inew = index.range_search(xq, radius) for i in range(nq): ref = Iref[Lref[i] : Lref[i + 1]] new = Inew[Lnew[i] : Lnew[i + 1]] snew = set(new) - # no duplicates self.assertTrue(len(new) == len(snew)) - # subset of real results self.assertTrue(snew <= set(ref)) nfound.append(Lnew[-1]) - ndis.append(stats.ndis) nfound = np.array(nfound) self.assertTrue(nfound[-1] == Lref[-1]) self.assertTrue(np.all(nfound[1:] >= nfound[:-1])) @@ -102,28 +95,20 @@ def test_multihash(self): Lref, Dref, Iref = index_ref.range_search(xq, radius) nfound = [] - ndis = [] for nh in 1, 3, 5: index = faiss.IndexBinaryMultiHash(d, nh, 10) index.add(xb) - # index.display() - stats = faiss.cvar.indexBinaryHash_stats index.nflip = 2 - stats.reset() Lnew, Dnew, Inew = index.range_search(xq, radius) for i in range(nq): ref = Iref[Lref[i] : Lref[i + 1]] new = Inew[Lnew[i] : Lnew[i + 1]] snew = set(new) - # no duplicates self.assertTrue(len(new) == len(snew)) - # subset of real results self.assertTrue(snew <= set(ref)) nfound.append(Lnew[-1]) - ndis.append(stats.ndis) nfound = np.array(nfound) - # self.assertTrue(nfound[-1] == Lref[-1]) self.assertTrue(np.all(nfound[1:] >= nfound[:-1])) @@ -158,13 +143,11 @@ def test_hash_and_multihash(self): ref = Iref[i] new = Inew[i] snew = set(new) - # no duplicates self.assertTrue(len(new) == len(snew)) nf += len(set(ref) & snew) nfound[(nh, nbit)] = nf self.assertGreater(nfound[(nh, 4)], nfound[(nh, 7)]) - # test serialization index2 = faiss.deserialize_index_binary( faiss.serialize_index_binary(index) ) @@ -185,6 +168,25 @@ def test_hash_and_multihash(self): self.assertGreater(nfound[(3, 7)], nfound[(1, 7)]) self.assertGreater(nfound[(5, 7)], nfound[(3, 7)]) + def test_multihash_serialize_single_bucket(self): + # when all the vectors fall in the same bucket, the bucket size is + # ntotal, which must survive serialization also when ntotal is a + # power of 2 + d = 64 + for nb in 1, 2, 4, 5, 8: + xb = np.zeros((nb, d // 8), dtype="uint8") + index = faiss.IndexBinaryMultiHash(d, 2, 8) + index.add(xb) + D, I = index.search(xb[:1], nb) + np.testing.assert_array_equal(np.sort(I[0]), np.arange(nb)) + + index2 = faiss.deserialize_index_binary( + faiss.serialize_index_binary(index) + ) + D2, I2 = index2.search(xb[:1], nb) + np.testing.assert_array_equal(I, I2) + np.testing.assert_array_equal(D, D2) + def subtest_result_order(self, nh): d = 128 @@ -209,22 +211,3 @@ def test_result_order_binhash(self): def test_result_order_multihash(self): self.subtest_result_order(3) - - -""" -I suspect this test crashes CircleCI on Linux - -# this is an expensive test, so we don't run it by default -class TestLargeIndexWrite: # (unittest.TestCase): - - def test_write_580M(self): - dim = 8 - nhash = 1 - num_million = 580 # changing to 570 works - index1 = faiss.IndexBinaryMultiHash(dim, nhash, int(dim/nhash)) - random_hash_codes = np.random.randint(0, 256, ( - num_million * int(1e6), int(dim/8))).astype("uint8") - index1.add(random_hash_codes) - faiss.write_index_binary(index1, "/tmp/tmp.faiss") - index2 = faiss.read_index_binary("/tmp/tmp.faiss") -""" diff --git a/thirdparty/faiss/tests/test_binary_io.py b/thirdparty/faiss/tests/test_binary_io.py index 1075b6192..598277a99 100644 --- a/thirdparty/faiss/tests/test_binary_io.py +++ b/thirdparty/faiss/tests/test_binary_io.py @@ -43,6 +43,7 @@ def test_flat(self): index2 = faiss.deserialize_index_binary( faiss.serialize_index_binary(index) ) + assert index2.thisown D2, I2 = index2.search(self.xq, 3) @@ -98,37 +99,6 @@ def test_ivf_flat(self): assert (D3 == D).all() -class TestObjectOwnership(unittest.TestCase): - - def __init__(self, *args, **kwargs): - unittest.TestCase.__init__(self, *args, **kwargs) - d = 32 - nt = 200 - nb = 1500 - nq = 500 - - (self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq) - - def test_read_index_ownership(self): - d = self.xq.shape[1] * 8 - - index = faiss.IndexBinaryFlat(d) - index.add(self.xb) - - # this is the output of read_index_binary (==> checks ownership) - index2 = faiss.deserialize_index_binary( - faiss.serialize_index_binary(index) - ) - - assert index2.thisown - - # Verify deserialized index is serializable again - index3 = faiss.deserialize_index_binary( - faiss.serialize_index_binary(index2) - ) - assert index3.thisown - - class TestBinaryFromFloat(unittest.TestCase): def __init__(self, *args, **kwargs): @@ -174,7 +144,7 @@ def __init__(self, *args, **kwargs): nb = 1500 nq = 500 - (self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq) + (_, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq) def test_hnsw(self): d = self.xq.shape[1] * 8 @@ -199,31 +169,3 @@ def test_hnsw(self): D3, I3 = index3.search(self.xq, 3) assert (I3 == I).all() assert (D3 == D).all() - - def test_ivf_hnsw(self): - d = self.xq.shape[1] * 8 - - quantizer = faiss.IndexBinaryHNSW(d) - index = faiss.IndexBinaryIVF(quantizer, d, 8) - index.cp.min_points_per_centroid = 5 # quiet warning - index.nprobe = 4 - index.train(self.xt) - index.add(self.xb) - D, I = index.search(self.xq, 3) - - index2 = faiss.deserialize_index_binary( - faiss.serialize_index_binary(index) - ) - - D2, I2 = index2.search(self.xq, 3) - - assert (I2 == I).all() - assert (D2 == D).all() - - # Verify deserialized index is serializable again - index3 = faiss.deserialize_index_binary( - faiss.serialize_index_binary(index2) - ) - D3, I3 = index3.search(self.xq, 3) - assert (I3 == I).all() - assert (D3 == D).all() diff --git a/thirdparty/faiss/tests/test_binary_ivf_scanner.py b/thirdparty/faiss/tests/test_binary_ivf_scanner.py index 54c3dcf25..6a804e9de 100644 --- a/thirdparty/faiss/tests/test_binary_ivf_scanner.py +++ b/thirdparty/faiss/tests/test_binary_ivf_scanner.py @@ -8,8 +8,7 @@ caller uses to fold an inverted list into a heap it owns. Each test compares against a NumPy popcount-xor reference, which is -level-independent, so per-level dispatch drift surfaces as a failure. The -@for_all_simd_levels decorator runs every case at each available level. +level-independent, so per-level dispatch drift surfaces as a failure. """ import unittest @@ -82,8 +81,6 @@ def run_scan(self, scanner, codes, ids, slice_sizes, k, radius=None): return simi[keep][order].tolist(), idxi[keep][order].tolist() def test_unseeded_heap_keeps_the_k_nearest(self): - """Every code width, so the shared scan loop is covered for each - HammingComputer specialization and for the generic one.""" rs = np.random.RandomState(1234) n, k = 2000, 10 for cs in WIDTHS: @@ -97,7 +94,6 @@ def test_unseeded_heap_keeps_the_k_nearest(self): self.assertEqual(got, _expected(query, codes, k), f"code_size={cs}") def test_seeded_heap_bounds_every_width(self): - """The radius seed must behave the same for every computer.""" rs = np.random.RandomState(1235) n, k = 1500, 12 for cs in WIDTHS: @@ -179,6 +175,19 @@ def test_every_distance_matches_at_this_level(self): ) self.assertEqual(got, _expected(query, codes, k), f"n={n}") + def test_distance_to_code_outside_the_specialized_sizes(self): + """Code sizes outside WIDTHS use the default computer.""" + rs = np.random.RandomState(789) + for cs in [3, 13, 96, 100, 128, 200]: + with self.subTest(code_size=cs): + query = self.random_codes(rs, 1, cs) + scanner = self.make_scanner(rs, query, cs=cs) + codes = self.random_codes(rs, 50, cs) + dis = [ + scanner.distance_to_code(faiss.swig_ptr(c)) for c in codes + ] + np.testing.assert_array_equal(dis, _hamming(query, codes)) + def test_range_search_matches_the_reference(self): """range_search reaches scan_codes_range. n is not a multiple of the batch size, so the batch loop and the tail both run.""" @@ -218,12 +227,8 @@ def test_store_pairs_offsets(self): distances, labels = self.run_scan( self.make_scanner(rs, query, store_pairs=True), codes, ids, [n], k ) - self.assertEqual(len(distances), k) - self.assertEqual([faiss.lo_listno(x) for x in labels], [0] * k) - # Each distance must be the distance to the code at the offset the - # same label decodes to. truth = _hamming(query, codes) offsets = [faiss.lo_offset(x) for x in labels] self.assertEqual(distances, [int(truth[o]) for o in offsets]) diff --git a/thirdparty/faiss/tests/test_binary_search_params.py b/thirdparty/faiss/tests/test_binary_search_params.py index 60ee5b40a..5f9522dd0 100644 --- a/thirdparty/faiss/tests/test_binary_search_params.py +++ b/thirdparty/faiss/tests/test_binary_search_params.py @@ -31,7 +31,7 @@ def do_test_with_param( index.add(xb) - I0, D0 = index.search(xq, k) + D0, I0 = index.search(xq, k) Dnew, Inew = index.search(xq, k, params=params) @@ -53,10 +53,6 @@ def test_nprobe(self): index, {"nprobe": 3}, faiss.SearchParametersIVF(nprobe=3), - d=d, - nb=500, - nq=20, - k=5, ) def test_efSearch(self): @@ -66,10 +62,6 @@ def test_efSearch(self): index, {"efSearch": 4}, faiss.SearchParametersHNSW(efSearch=4), - d=d, - nb=500, - nq=20, - k=5, ) def test_quantizer_hnsw(self): @@ -83,10 +75,6 @@ def test_quantizer_hnsw(self): nprobe=10, quantizer_params=faiss.SearchParametersHNSW(efSearch=5), ), - d=d, - nb=500, - nq=20, - k=5, ) def test_max_codes(self): @@ -121,47 +109,3 @@ def test_max_codes(self): self.assertLessEqual(stats.ndis, target_ndis) if stats.ndis < target_ndis: np.testing.assert_equal(I0[q], Iq[0]) - - def test_efSearch(self): - d = 64 - nb = 500 - nq = 20 - k = 5 - - rs = np.random.RandomState(123) - xb = rs.randint(256, size=(nb, d // 8), dtype="uint8") - xq = rs.randint(256, size=(nq, d // 8), dtype="uint8") - - index = faiss.IndexBinaryHNSW(d, 32) - index.add(xb) - - D1, I1 = index.search( - xq, k, params=faiss.SearchParametersHNSW(efSearch=4) - ) - - D2, I2 = index.search( - xq, k, params=faiss.SearchParametersHNSW(efSearch=16) - ) - - self.assertFalse(np.all(I1 == I2)) - - def test_nprobe(self): - d = 64 - nb = 500 - nq = 20 - k = 5 - - rs = np.random.RandomState(123) - xb = rs.randint(256, size=(nb, d // 8), dtype="uint8") - xq = rs.randint(256, size=(nq, d // 8), dtype="uint8") - - quantizer = faiss.IndexBinaryFlat(d) - index = faiss.IndexBinaryIVF(quantizer, d, 32) - index.train(xb) - index.add(xb) - - D1, I1 = index.search(xq, k, params=faiss.SearchParametersIVF(nprobe=1)) - - D2, I2 = index.search(xq, k, params=faiss.SearchParametersIVF(nprobe=8)) - - self.assertFalse(np.all(I1 == I2)) diff --git a/thirdparty/faiss/tests/test_build_blocks.py b/thirdparty/faiss/tests/test_build_blocks.py index 2c5fddd12..4ed0fc129 100644 --- a/thirdparty/faiss/tests/test_build_blocks.py +++ b/thirdparty/faiss/tests/test_build_blocks.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import absolute_import, division, print_function - import numpy as np import faiss @@ -34,12 +32,8 @@ def test_pca(self): prev = o def test_pca_retraining_gram_path(self): - # Regression test for the sgemm_ beta=0 fix in PCAMatrix::train. - # When n < d_in, train() takes the Gram-matrix code path and - # writes PCAMat via sgemm_. Before the fix, beta=1.0 caused the - # second train() call to accumulate stale values from the first - # call, corrupting the PCA basis. Calling train() twice with the - # same data must produce the same projection. + # Regression: a second train() on the Gram path (n < d_in) must not + # accumulate into PCAMat (sgemm_ beta=0). d = 64 n = 20 # n < d_in exercises the Gram-matrix branch np.random.seed(123) @@ -104,42 +98,17 @@ def test_maplong2long(self): class TestHadamardRotation(unittest.TestCase): - def test_shape(self): - d = 128 - n = 100 - np.random.seed(123) - x = np.random.randn(n, d).astype("float32") - - fr = faiss.HadamardRotation(d) - y = fr.apply(x) - # d=128 is a power of 2, so d_out == d_in - self.assertEqual(y.shape, (n, d)) - def test_non_power_of_2(self): """Non-power-of-2 dimensions are zero-padded to next power of 2.""" - cases = {192: 256, 384: 512, 768: 1024, 1536: 2048} - for d, expected_out in cases.items(): - np.random.seed(42) - x = np.random.randn(20, d).astype("float32") - fr = faiss.HadamardRotation(d) - self.assertEqual(fr.d_out, expected_out) - y = fr.apply(x) - self.assertEqual(y.shape, (20, expected_out)) - # output should be finite and non-trivial - self.assertTrue(np.all(np.isfinite(y))) - self.assertFalse(np.allclose(y, 0)) - - def test_deterministic(self): - d = 64 - n = 20 - np.random.seed(789) - x = np.random.randn(n, d).astype("float32") - - fr1 = faiss.HadamardRotation(d, 42) - fr2 = faiss.HadamardRotation(d, 42) - y1 = fr1.apply(x) - y2 = fr2.apply(x) - np.testing.assert_array_equal(y1, y2) + d, expected_out = 192, 256 + np.random.seed(42) + x = np.random.randn(20, d).astype("float32") + fr = faiss.HadamardRotation(d) + self.assertEqual(fr.d_out, expected_out) + y = fr.apply(x) + self.assertEqual(y.shape, (20, expected_out)) + self.assertTrue(np.all(np.isfinite(y))) + self.assertFalse(np.allclose(y, 0)) def test_different_seeds(self): d = 64 @@ -160,6 +129,7 @@ def test_norm_preservation_power_of_2(self): x = np.random.randn(100, d).astype("float32") fr = faiss.HadamardRotation(d) y = fr.apply(x) + self.assertEqual(y.shape, x.shape) norms_in = np.linalg.norm(x, axis=1) norms_out = np.linalg.norm(y, axis=1) np.testing.assert_allclose(norms_in, norms_out, rtol=1e-4) @@ -174,9 +144,87 @@ def test_index_factory(self): index.train(x) index.add(x) D, I = index.search(x[:5], 5) - # first result for each query should be itself np.testing.assert_array_equal(I[:, 0], np.arange(5)) + def test_pad_to_multiple_of_64(self): + """With pad_to_power_of_2=False, d_out is the smallest multiple of 64 + >= d and the transform stays orthogonal, including the FHT-Kac rounds + used when d_out is not a power of 2.""" + cases = {100: 128, 192: 192, 768: 768, 1000: 1024, 1536: 1536} + for d, expected_out in cases.items(): + rs = np.random.RandomState(d) + x = rs.randn(20, d).astype("float32") + fr = faiss.HadamardRotation(d, 12345, False) + self.assertFalse(fr.pad_to_power_of_2) + self.assertEqual(fr.d_out, expected_out) + y = fr.apply(x) + self.assertEqual(y.shape, (20, expected_out)) + np.testing.assert_allclose(y @ y.T, x @ x.T, rtol=1e-4, atol=1e-3) + # not a zero-padding of x, which also keeps the Gram matrix + self.assertGreater(np.abs(y[:, :d] - x).max(), 0.1) + # the fourth round exists only when d_out is not a power of 2 + is_pow2 = (expected_out & (expected_out - 1)) == 0 + self.assertEqual(fr.signs4.size(), 0 if is_pow2 else expected_out) + if expected_out == d: + np.testing.assert_allclose( + fr.reverse_transform(y), x, rtol=1e-4, atol=1e-4 + ) + + def test_index_factory_pad_to_multiple_of_64(self): + """ "HRk" is HadamardRotation(d, seed, False), "HR" keeps padding to + a power of 2. Both take an optional seed.""" + cases = [ + # (d, description, pad_to_power_of_2, d_out, seed) + (1500, "HR", True, 2048, 12345), + (1500, "HRk", False, 1536, 12345), + (1500, "HR7", True, 2048, 7), + (1500, "HRk7", False, 1536, 7), + (1000, "HRk", False, 1024, 12345), + ] + for d, description, pad, d_out, seed in cases: + index = faiss.index_factory(d, description + ",Flat") + hr = faiss.downcast_VectorTransform(index.chain.at(0)) + self.assertIsInstance(hr, faiss.HadamardRotation) + self.assertEqual(hr.pad_to_power_of_2, pad) + self.assertEqual(hr.d_out, d_out) + self.assertEqual(hr.seed, seed) + x = np.random.RandomState(d).randn(10, d).astype("float32") + ref = faiss.HadamardRotation(d, seed, pad) + np.testing.assert_array_equal(hr.apply(x), ref.apply(x)) + + def test_default_mode_keeps_its_format(self): + hr = faiss.HadamardRotation(1280, 2024) + writer = faiss.VectorIOWriter() + faiss.write_VectorTransform(hr, writer) + data = faiss.vector_to_array(writer.data) + self.assertEqual(data[:4].tobytes(), b"HRot") + reader = faiss.VectorIOReader() + faiss.copy_array_to_vector(data, reader.data) + # vt owns the transform, hr2 only points to it + vt = faiss.read_VectorTransform(reader) + hr2 = faiss.downcast_VectorTransform(vt) + self.assertTrue(hr2.pad_to_power_of_2) + self.assertEqual(hr2.d_out, 2048) + self.assertEqual(hr2.signs4.size(), 0) + hr.check_identical(hr2) + + def test_clone_preserves_padding(self): + hr = faiss.HadamardRotation(1280, 3, False) + # vt owns the clone, hr2 only points to it + vt = faiss.Cloner().clone_VectorTransform(hr) + hr2 = faiss.downcast_VectorTransform(vt) + hr.check_identical(hr2) + np.testing.assert_array_equal( + faiss.vector_to_array(hr2.signs4), faiss.vector_to_array(hr.signs4) + ) + + def test_check_identical_compares_padding(self): + # same d_out, different padding modes + pow2 = faiss.HadamardRotation(64, 1, True) + mult64 = faiss.HadamardRotation(64, 1, False) + self.assertEqual(pow2.d_out, mult64.d_out) + self.assertRaises(RuntimeError, pow2.check_identical, mult64) + class TestOrthogonalReconstruct(unittest.TestCase): @@ -244,22 +292,7 @@ def test_1(self): class TestNyFuncs(unittest.TestCase): - def test_l2(self): - rs = np.random.RandomState(123) - swig_ptr = faiss.swig_ptr - for d in 1, 2, 4, 8, 12, 16: - x = rs.rand(d).astype("float32") - for ny in 128, 129, 130: - y = rs.rand(ny, d).astype("float32") - ref = ((x - y) ** 2).sum(1) - new = np.zeros(ny, dtype="float32") - faiss.fvec_L2sqr_ny( - swig_ptr(new), swig_ptr(x), swig_ptr(y), d, ny - ) - assert np.abs(ref - new).max() < 1e-4 - def test_IP(self): - # this one is not optimized with SIMD but just in case rs = np.random.RandomState(123) swig_ptr = faiss.swig_ptr for d in 1, 2, 4, 8, 12, 16: @@ -359,14 +392,12 @@ def test_8bit_equiv(self): # reconstructs x as x + 0.5 D, I = index.search(x[3:], 1) - # assert D[0, 0] == Dref[0, 0] assert D[0, 0] == ((x[3] - x[2]) ** 2).sum() def test_6bit_equiv(self): rs = np.random.RandomState(123) for d in 3, 6, 8, 16, 36: trainset = np.zeros((2, d), dtype="float32") - trainset[0, :] = 0 trainset[0, :] = 63 index = faiss.IndexScalarQuantizer(d, faiss.ScalarQuantizer.QT_6bit) @@ -566,7 +597,6 @@ def do_test_bucket_sort_inplace( tab = rs.randint(nbucket, size=(nrow, ncol), dtype=dtype) tab2 = tab.copy() - faiss.cvar.bucket_sort_verbose faiss.cvar.bucket_sort_verbose = 1 lims = faiss.matrix_bucket_sort_inplace(tab2, nt=nt) @@ -598,10 +628,25 @@ def test_bucket_sort_inplace_parallel_int64(self): self.do_test_bucket_sort_inplace(4, dtype="int64") +class TestFindDuplicateCodes(unittest.TestCase): + + def test_find_duplicate_codes(self): + # two different codes with the same bvec_checksum, then a copy + k_inv = pow(1686049, -1, 2**32) + pair = np.array([[65713 * k_inv % 2**32, 0], [0, k_inv]], "uint32") + codes = pair[[0, 1, 1]].view("uint8") + rep = np.empty(len(codes), dtype="int64") + n_distinct = faiss.find_duplicate_codes( + *codes.shape, faiss.swig_ptr(codes), faiss.swig_ptr(rep) + ) + np.testing.assert_array_equal(rep, [0, 1, 1]) + self.assertEqual(n_distinct, 2) + + class TestMergeKNNResults(unittest.TestCase): def do_test(self, ismax, dtype): - rs = np.random.RandomState() + rs = np.random.RandomState(123) n, k, nshard = 10, 5, 3 all_ids = rs.randint(100000, size=(nshard, n, k)).astype("int64") all_dis = rs.rand(nshard, n, k) @@ -643,9 +688,7 @@ def test_max_float(self): class TestMapInt64ToInt64(unittest.TestCase): def do_test(self, capacity, n): - """test that we are able to lookup""" rs = np.random.RandomState(123) - # make sure we have unique values keys = np.unique(rs.choice(2**29, size=n).astype("int64")) rs.shuffle(keys) n = keys.size @@ -653,7 +696,6 @@ def do_test(self, capacity, n): tab = faiss.MapInt64ToInt64(capacity) tab.add(keys, vals) - # lookup and check vals2 = tab.lookup(keys) np.testing.assert_array_equal(vals, vals2) @@ -667,10 +709,6 @@ def do_test(self, capacity, n): def test_small(self): self.do_test(16384, 10000) - def xx_test_large(self): - # don't run by default because it's slow - self.do_test(2**21, 10**6) - class TestRanklistIntersectionSize(unittest.TestCase): @@ -685,10 +723,6 @@ def _expected(self, v1, v2): """Reference: set intersection of valid (non-negative) IDs.""" return len({x for x in v1 if x >= 0} & {x for x in v2 if x >= 0}) - def test_basic_intersection(self): - v1, v2 = [1, 2, 3], [2, 3, 4] - self.assertEqual(self._intersect(v1, v2), self._expected(v1, v2)) - def test_duplicates_in_v2_not_double_counted(self): # 1 appears twice in v2 but should count only once v1, v2 = [1, 2], [1, 1, 2] diff --git a/thirdparty/faiss/tests/test_callback.cpp b/thirdparty/faiss/tests/test_callback.cpp deleted file mode 100644 index 75d5f42c8..000000000 --- a/thirdparty/faiss/tests/test_callback.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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. - */ - -#include - -#include -#include -#include -#include -#include - -TEST(TestCallback, timeout) { - int n = 20000; - int k = 5000; - int d = 128; - int niter = 1000000000; - int seed = 42; - - std::vector vecs(n * d); - faiss::float_rand(vecs.data(), vecs.size(), seed); - - auto index(new faiss::IndexFlat(d)); - - faiss::ClusteringParameters cp; - cp.niter = niter; - cp.verbose = false; - - faiss::Clustering kmeans(d, k, cp); - - faiss::TimeoutCallback::reset(0.010); - EXPECT_THROW(kmeans.train(n, vecs.data(), *index), faiss::FaissException); - delete index; -} diff --git a/thirdparty/faiss/tests/test_callback_py.py b/thirdparty/faiss/tests/test_callback_py.py deleted file mode 100644 index bbd9047b6..000000000 --- a/thirdparty/faiss/tests/test_callback_py.py +++ /dev/null @@ -1,32 +0,0 @@ -# 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 unittest -import numpy as np -import faiss - - -class TestCallbackPy(unittest.TestCase): - def setUp(self) -> None: - super().setUp() - - def test_timeout(self) -> None: - n = 20000 - k = 5000 - d = 128 - niter = 1_000_000_000 - - x = np.random.rand(n, d).astype("float32") - index = faiss.IndexFlat(d) - - cp = faiss.ClusteringParameters() - cp.niter = niter - cp.verbose = False - - kmeans = faiss.Clustering(d, k, cp) - - with self.assertRaises(RuntimeError): - with faiss.TimeoutGuard(0.010): - kmeans.train(x, index) diff --git a/thirdparty/faiss/tests/test_clone.py b/thirdparty/faiss/tests/test_clone.py index 10fac7adb..94046170f 100644 --- a/thirdparty/faiss/tests/test_clone.py +++ b/thirdparty/faiss/tests/test_clone.py @@ -14,14 +14,8 @@ class TestClone(unittest.TestCase): - """ - Test clone_index for various index combinations. - """ def do_test_clone(self, factory, with_ids=False): - """ - Verify that cloning works for a given index type - """ d = 32 ds = datasets.SyntheticDataset(d, 1000, 2000, 10) index1 = faiss.index_factory(d, factory) @@ -49,9 +43,6 @@ def test_RFlat(self): def test_Refine(self): self.do_test_clone("SQ4,Refine(SQ8)") - def test_IVF(self): - self.do_test_clone("IVF16,Flat") - def test_PCA(self): self.do_test_clone("PCA8,Flat") @@ -62,7 +53,7 @@ def test_IDMap2(self): self.do_test_clone("IVF16,Flat,IDMap2", with_ids=True) def test_NSGPQ(self): - self.do_test_clone("NSG32,Flat") + self.do_test_clone("NSG32,PQ8np") def test_IVFAdditiveQuantizer(self): self.do_test_clone("IVF16,LSQ5x6_Nqint8") @@ -89,9 +80,7 @@ def test_AdditiveQuantizerFastScan(self): self.do_test_clone("PRQ2x3x4fs_Nrq2x4") def test_RowwiseMinMax(self): - # clone_Index for IndexRowwiseMinMaxBase was missing return res, so - # clone_index returned nullptr and leaked the clone allocation plus - # the deep-copied inner index. + # regression: clone_index returned nullptr for IndexRowwiseMinMaxBase d = 32 n = 200 rng = np.random.default_rng(42) diff --git a/thirdparty/faiss/tests/test_clustering.py b/thirdparty/faiss/tests/test_clustering.py index ed57266d9..aa1d68dfb 100644 --- a/thirdparty/faiss/tests/test_clustering.py +++ b/thirdparty/faiss/tests/test_clustering.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import absolute_import, division, print_function - import numpy as np import faiss @@ -26,7 +24,6 @@ def test_clustering(self): km = faiss.Kmeans(d, 32, niter=10) err32 = km.train(x) - # check that objective is decreasing prev = 1e50 for o in km.obj: self.assertGreater(prev, o) @@ -35,13 +32,11 @@ def test_clustering(self): km = faiss.Kmeans(d, 64, niter=10) err64 = km.train(x) - # check that 64 centroids give a lower quantization error than 32 self.assertGreater(err32, err64) km = faiss.Kmeans(d, 32, niter=10, int_centroids=True) err_int = km.train(x) - # check that integer centoids are not as good as float ones self.assertGreater(err_int, err32) self.assertTrue(np.all(km.centroids == np.floor(km.centroids))) @@ -64,7 +59,6 @@ def test_1ptpercluster(self): verbose = True kmeans = faiss.Kmeans(X.shape[1], k, niter=niter, verbose=verbose) kmeans.train(X) - l2_distances, I = kmeans.index.search(X, 1) def test_weighted(self): d = 32 @@ -106,7 +100,6 @@ def test_weighted(self): clus.train(x, index, weights=weights) cdis2, perm2 = index.search(ccent, 1) - # distance^2 of ground-truth centroids to clusters cdis2_first = cdis2[:5].sum() cdis2_last = cdis2[5:].sum() @@ -130,24 +123,17 @@ def test_encoded(self): xt2 = codec.sa_decode(codes) clus = faiss.Clustering(d, k) - # clus.verbose = True clus.niter = 0 index = faiss.IndexFlatL2(d) clus.train(xt2, index) ref_centroids = faiss.vector_to_array(clus.centroids).reshape(-1, d) - _, ref_errs = index.search(xt2, 1) - clus = faiss.Clustering(d, k) - # clus.verbose = True clus.niter = 0 - clus.decode_block_size = 120 index = faiss.IndexFlatL2(d) clus.train_encoded(codes, codec, index) new_centroids = faiss.vector_to_array(clus.centroids).reshape(-1, d) - _, new_errs = index.search(xt2, 1) - # It's the same operation, so should be bit-exact the same self.assertTrue(np.all(ref_centroids == new_centroids)) @@ -161,17 +147,8 @@ def test_init(self): km2 = faiss.Kmeans(d, k, niter=4) km2.train(xt, init_centroids=km.centroids) - # check that the initial objective is better for km2 than km self.assertGreater(km.obj[0], km2.obj[0] * 1.01) - def test_stats(self): - d = 32 - k = 5 - xt, xb, xq = get_dataset_2(d, 1000, 0, 0) - km = faiss.Kmeans(d, k, niter=4) - km.train(xt) - assert list(km.obj) == [st["obj"] for st in km.iteration_stats] - class TestCompositeClustering(unittest.TestCase): @@ -182,8 +159,6 @@ def test_redo(self): rs = np.random.RandomState(123) x = rs.uniform(size=(n, d)).astype("float32") - # make sure that doing 10 redos yields a better objective than just 1 - clus = faiss.Clustering(d, 20) clus.nredo = 1 clus.train(x, faiss.IndexFlatL2(d)) @@ -206,9 +181,6 @@ def test_redo_cosine(self): x = rs.uniform(size=(n, d)).astype("float32") faiss.normalize_L2(x) - # make sure that doing 10 redos yields a better objective than just 1 - # for cosine distance, it is IP so higher is better - clus = faiss.Clustering(d, 20) clus.nredo = 1 clus.train(x, faiss.IndexFlatIP(d)) @@ -221,33 +193,37 @@ def test_redo_cosine(self): self.assertGreater(obj10, obj1) + def test_progressive_dim_assign(self): + rs = np.random.RandomState(123) + x = rs.randn(200, 8).astype("float32") + queries = rs.randn(10, 8).astype("float32") + kmeans = faiss.Kmeans(8, 2, niter=2, progressive_dim_steps=3) + + for training_data in (x, x + 5): + kmeans.train(training_data) + expected = ( + (queries[:, None, :] - kmeans.centroids[None, :, :]) ** 2 + ).sum(axis=2) + for _ in range(2): + distances, labels = kmeans.assign(queries) + np.testing.assert_array_equal(labels, expected.argmin(axis=1)) + np.testing.assert_allclose( + distances, expected.min(axis=1), rtol=1e-5 + ) + self.assertTrue(kmeans.index.thisown) + def test_progressive_dim(self): d = 32 n = 10000 k = 50 xt, _, _ = get_dataset_2(d, n, 0, 0) - # basic kmeans kmeans = faiss.Kmeans(d, k) kmeans.train(xt) - clus = faiss.ProgressiveDimClustering(d, k) - clus.verbose - clus.verbose = True - clus.progressive_dim_steps - clus.progressive_dim_steps = 5 - fac = faiss.ProgressiveDimIndexFactory() - clus.train(n, faiss.swig_ptr(xt), fac) - - stats = clus.iteration_stats - stats = [stats.at(i) for i in range(stats.size())] - obj = np.array([st.obj for st in stats]) - # clustering objective should be a tad better - self.assertLess(obj[-1], kmeans.obj[-1]) - - # same test w/ Kmeans wrapper kmeans2 = faiss.Kmeans(d, k, progressive_dim_steps=5) kmeans2.train(xt) + # clustering objective should be a tad better self.assertLess(kmeans2.obj[-1], kmeans.obj[-1]) diff --git a/thirdparty/faiss/tests/test_clustering_initialization.py b/thirdparty/faiss/tests/test_clustering_initialization.py index 7ee155860..d34dc0535 100644 --- a/thirdparty/faiss/tests/test_clustering_initialization.py +++ b/thirdparty/faiss/tests/test_clustering_initialization.py @@ -11,7 +11,6 @@ def get_method_name(method): - """Get human-readable name for initialization method.""" method_names = { faiss.ClusteringInitMethod_RANDOM: "RANDOM", faiss.ClusteringInitMethod_KMEANS_PLUS_PLUS: "KMEANS++", @@ -21,7 +20,6 @@ def get_method_name(method): def verify_centroids_from_dataset(test_case, centroids, dataset): - """Verify centroids are from the dataset.""" D, _ = faiss.knn(centroids, dataset, 1) threshold = 1e-3 * centroids.shape[1] test_case.assertTrue( @@ -30,13 +28,11 @@ def verify_centroids_from_dataset(test_case, centroids, dataset): def verify_centroids_unique(test_case, centroids): - """Verify all centroids are unique (no duplicates).""" D, _ = faiss.knn(centroids, centroids, 2) test_case.assertTrue(np.all(D[:, 1] > 1e-4), "Duplicate centroids found") def generate_clustered_data(n, d, n_clusters, seed=42): - """Generate well-separated clustered data for testing.""" np.random.seed(seed) centers = np.random.randn(n_clusters, d).astype(np.float32) * 20 labels = np.random.randint(0, n_clusters, n) @@ -46,7 +42,6 @@ def generate_clustered_data(n, d, n_clusters, seed=42): def run_init(method, xt, d, k, seed=42, chain_length=None): - """Run clustering initialization and return centroids.""" init = faiss.ClusteringInitialization(d, k) init.method = method init.seed = seed @@ -58,10 +53,7 @@ def run_init(method, xt, d, k, seed=42, chain_length=None): class TestClusteringInitialization(unittest.TestCase): - """Test ClusteringInitialization standalone API and algorithm behavior.""" - def test_initialization_methods(self): - """Test all init methods produce valid, unique centroids.""" ds = datasets.SyntheticDataset(128, 100000, 0, 0) xt = ds.get_train() k = 64 @@ -77,7 +69,6 @@ def test_initialization_methods(self): verify_centroids_unique(self, centroids) def test_determinism(self): - """Test that initialization is deterministic with the same seed.""" ds = datasets.SyntheticDataset(64, 100000, 0, 0) xt = ds.get_train() k = 32 @@ -93,7 +84,6 @@ def test_determinism(self): np.testing.assert_array_equal(centroids1, centroids2) def test_afkmc2_chain_length_effect(self): - """Test that longer AFK-MC² chain lengths produce better init.""" d, k = 32, 64 xt = generate_clustered_data(10000, d, k) @@ -116,7 +106,6 @@ def test_afkmc2_chain_length_effect(self): total_obj += np.sum(D) results[chain_length] = total_obj / n_trials - # Verify monotonic improvement: each longer chain should not be worse for i in range(1, len(chain_lengths)): prev, curr = chain_lengths[i - 1], chain_lengths[i] self.assertLessEqual( @@ -126,7 +115,6 @@ def test_afkmc2_chain_length_effect(self): ) def test_with_existing_centroids(self): - """Test that considering existing centroids improves initialization.""" n, d, k = 10000, 32, 64 n_existing = 10 xt = generate_clustered_data(n, d, k) diff --git a/thirdparty/faiss/tests/test_common_ivf_empty_index.cpp b/thirdparty/faiss/tests/test_common_ivf_empty_index.cpp index 45cce237b..d45b32f10 100644 --- a/thirdparty/faiss/tests/test_common_ivf_empty_index.cpp +++ b/thirdparty/faiss/tests/test_common_ivf_empty_index.cpp @@ -32,7 +32,6 @@ int d = 64; std::vector get_random_vectors(size_t n, int seed) { std::vector x(n * d); faiss::rand_smooth_vectors(n, d, x.data(), seed); - seed++; return x; } @@ -68,11 +67,11 @@ struct DispatchingInvertedLists : faiss::ReadOnlyInvertedLists { }; TEST(COMMON, test_common_trained_index) { - int N = 3; // number of independent indexes - int nt = 500; // training vectors - int nb = 200; // nb database vectors per index - int nq = 10; // nb queries performed on each index - int k = 4; // restults requested per query + int N = 3; // number of independent indexes + int nt = 500; + int nb = 200; + int nq = 10; + int k = 4; // construct and build an "empty index": a trained index that does not // itself hold any data @@ -88,17 +87,14 @@ TEST(COMMON, test_common_trained_index) { std::vector> ref_I(N); for (int i = 0; i < N; i++) { - // clone the empty index std::unique_ptr index( faiss::clone_index(empty_index.get())); auto xb = get_random_vectors(nb, 1234 + i); auto xq = get_random_vectors(nq, 12345 + i); - // add vectors and perform a search index->add(nb, xb.data()); std::vector D(k * nq); std::vector I(k * nq); index->search(nq, xq.data(), k, D.data(), I.data()); - // record result as reference ref_I[i] = I; } @@ -106,14 +102,11 @@ TEST(COMMON, test_common_trained_index) { std::vector sub_invlists; for (int i = 0; i < N; i++) { - // swap in other inverted lists sub_invlists.emplace_back(empty_index->nlist, empty_index->code_size); faiss::InvertedLists* invlists = &sub_invlists.back(); - // replace_invlists swaps in a new InvertedLists for an existing index empty_index->replace_invlists(invlists, false); empty_index->reset(); // reset id counter to 0 - // populate inverted lists auto xb = get_random_vectors(nb, 1234 + i); empty_index->add(nb, xb.data()); } @@ -142,7 +135,6 @@ TEST(COMMON, test_common_trained_index) { new_I[i] = I; } - // compare with reference result for (int i = 0; i < N; i++) { ASSERT_EQ(ref_I[i], new_I[i]); } diff --git a/thirdparty/faiss/tests/test_contrib.py b/thirdparty/faiss/tests/test_contrib.py index 7d5faeda1..df4434b55 100644 --- a/thirdparty/faiss/tests/test_contrib.py +++ b/thirdparty/faiss/tests/test_contrib.py @@ -26,7 +26,6 @@ ) from faiss.contrib.exhaustive_search import ( exponential_query_iterator, - knn, knn_ground_truth, range_ground_truth, range_search_max_results, @@ -44,8 +43,6 @@ def do_test_compute_GT(self, metric=faiss.METRIC_L2, ngpu=0): index.add(xb) Dref, Iref = index.search(xq, 10) - # iterator function on the matrix - def matrix_iterator(xb, bs): for i0 in range(0, xb.shape[0], bs): yield xb[i0 : i0 + bs] @@ -79,10 +76,6 @@ class TestDatasets(unittest.TestCase): def test_synthetic(self): ds = datasets.SyntheticDataset(32, 1000, 2000, 10) - xq = ds.get_queries() - self.assertEqual(xq.shape, (10, 32)) - xb = ds.get_database() - self.assertEqual(xb.shape, (2000, 32)) ds.check_sizes() def test_synthetic_ip(self): @@ -105,28 +98,6 @@ def test_synthetic_iterator(self): class TestExhaustiveSearch(unittest.TestCase): - def test_knn_cpu(self): - xb = np.random.rand(200, 32).astype("float32") - xq = np.random.rand(100, 32).astype("float32") - - index = faiss.IndexFlatL2(32) - index.add(xb) - Dref, Iref = index.search(xq, 10) - - Dnew, Inew = knn(xq, xb, 10) - - assert np.all(Inew == Iref) - assert np.allclose(Dref, Dnew) - - index = faiss.IndexFlatIP(32) - index.add(xb) - Dref, Iref = index.search(xq, 10) - - Dnew, Inew = knn(xq, xb, 10, metric=faiss.METRIC_INNER_PRODUCT) - - assert np.all(Inew == Iref) - assert np.allclose(Dref, Dnew) - def do_test_range(self, metric): ds = datasets.SyntheticDataset(32, 0, 1000, 10) xq = ds.get_queries() @@ -156,14 +127,14 @@ def test_range_L2(self): def test_range_IP(self): self.do_test_range(faiss.METRIC_INNER_PRODUCT) - def test_query_iterator(self, metric=faiss.METRIC_L2): + def test_query_iterator(self): ds = datasets.SyntheticDataset(32, 0, 1000, 1000) xq = ds.get_queries() xb = ds.get_database() - D, I = faiss.knn(xq, xb, 10, metric=metric) + D, I = faiss.knn(xq, xb, 10) threshold = float(D[:, -1].mean()) - index = faiss.IndexFlat(32, metric) + index = faiss.IndexFlatL2(32) index.add(xb) ref_lims, ref_D, ref_I = index.range_search(xq, threshold) @@ -171,7 +142,6 @@ def matrix_iterator(xb, bs): for i0 in range(0, xb.shape[0], bs): yield xb[i0 : i0 + bs] - # check repro OK _, new_lims, new_D, new_I = range_search_max_results( index, matrix_iterator(xq, 100), threshold, max_results=1e10 ) @@ -195,17 +165,10 @@ def matrix_iterator(xb, bs): ) def test_query_iterator_similarity_metric(self): - """range_search_max_results must keep the highest-scoring results - (and raise the radius) for any similarity metric, not just - METRIC_INNER_PRODUCT. Regression test for a bug where pruning - for METRIC_Jaccard (also a similarity metric, see - faiss.is_similarity_metric) kept the lowest-scoring results - instead of the highest-scoring ones.""" + """Regression: pruning must keep the highest scores for any + similarity metric (e.g. Jaccard), not just inner product.""" class FakeSimilarityIndex: - """Stands in for an Index using a similarity metric (higher - score = better match), exposing only what - range_search_max_results touches.""" def __init__(self, sims, metric_type): self.sims = sims @@ -242,26 +205,20 @@ def range_search(self, xq, radius): ) self.assertGreaterEqual(new_radius, radius) - self.assertGreater(len(D), 0) self.assertGreaterEqual(D.min(), new_radius - 1e-6) class TestInspect(unittest.TestCase): def test_LinearTransform(self): - # training data xt = np.random.rand(1000, 20).astype("float32") - # test data x = np.random.rand(10, 20).astype("float32") - # make the PCA matrix pca = faiss.PCAMatrix(20, 10) pca.train(xt) - # apply it to test data yref = pca.apply_py(x) A, b = inspect_tools.get_LinearTransform_matrix(pca) - # verify ynew = x @ A.T + b np.testing.assert_array_almost_equal(yref, ynew) @@ -282,7 +239,6 @@ def test_make_LT(self): np.testing.assert_allclose(Yref, Ynew, rtol=1e-06) def test_NSG_neighbors(self): - # FIXME number of elements to add should be >> 100 ds = datasets.SyntheticDataset(32, 0, 200, 10) index = faiss.index_factory(ds.d, "NSG") index.add(ds.get_database()) @@ -321,7 +277,6 @@ def test_PR_multiple(self): index.add(xb) ref_lims, ref_D, ref_I = index.range_search(xq, threshold) - # now make a slightly suboptimal index index2 = faiss.index_factory(32, "PCA16,Flat") index2.train(ds.get_train()) index2.add(xb) @@ -366,11 +321,6 @@ def test_equal_time_better_perf_shadows(self): op.add_operating_point("B", 0.9, 1.0) keys = [k for k, _, _ in op.operating_points] self.assertEqual(keys, ["B"]) - # no kept point may be dominated by another kept point - pts = op.operating_points - for _, pi, ti in pts: - for _, pj, tj in pts: - self.assertFalse(pj >= pi and tj <= ti and (pj > pi or tj < ti)) class TestPreassigned(unittest.TestCase): @@ -415,15 +365,11 @@ def test_float(self): fake_centroids = np.zeros((index.nlist, index.d), dtype="float32") index.quantizer.add(fake_centroids) - # train the PQ part index.train(xt) - # add elements xb a = alt_quantizer.search(xb[:, :20].copy(), 1)[1].ravel() ivf_tools.add_preassigned(index, xb, a) - # search elements xq, increase nprobe, check 4 first results w/ - # groundtruth prev_inter_perf = 0 for nprobe in 1, 10, 20: @@ -434,8 +380,6 @@ def test_float(self): self.assertTrue(inter_perf >= prev_inter_perf) prev_inter_perf = inter_perf - # test range search - index.nprobe = 20 a = alt_quantizer.search(xq[:, :20].copy(), index.nprobe)[1] @@ -484,18 +428,14 @@ def test_binary(self): index.quantizer.add(fake_centroids) index.is_trained = True - # add elements xb a = alt_quantizer.search(xb[:, :20].copy(), 1)[1].ravel() ivf_tools.add_preassigned(index, xb_bin, a) - # recompute GT in binary k = 15 ib = faiss.IndexBinaryFlat(128) ib.add(xb_bin) Dgt, Igt = ib.search(xq_bin, k) - # search elements xq, increase nprobe, check 4 first results w/ - # groundtruth prev_inter_perf = 0 for nprobe in 1, 10, 20: @@ -506,8 +446,6 @@ def test_binary(self): self.assertGreaterEqual(inter_perf, prev_inter_perf) prev_inter_perf = inter_perf - # test range search - index.nprobe = 20 a = alt_quantizer.search(xq[:, :20].copy(), index.nprobe)[1] @@ -526,10 +464,9 @@ def test_binary(self): l0, l1 = lims[q], lims[q + 1] self.assertTrue(set(I[q]) <= set(IR[l0:l1])) - def test_range_search_preassigned_coarse_dis_none_matches_zeros(self): - """coarse_dis=None must match coarse_dis=zeros. Before the fix, - np.empty left uninitialized values that IVFPQ by_residual=True - reads for distance correction, producing nondeterministic results.""" + def test_range_search_preassigned_coarse_dis_none(self): + """coarse_dis=None must match the coarse quantizer's distances, + which IVFPQ with by_residual=True reads for distance correction.""" ds = datasets.SyntheticDataset(32, 1000, 500, 50) index = faiss.index_factory(ds.d, "IVF10,PQ4x4") index.train(ds.get_train()) @@ -537,17 +474,39 @@ def test_range_search_preassigned_coarse_dis_none_matches_zeros(self): index.nprobe = 5 self.assertTrue(index.by_residual) xq = ds.get_queries() - _, list_nos = index.quantizer.search(xq, index.nprobe) - zero_dis = np.zeros(list_nos.shape, dtype=np.float32) - lz, Dz, Iz = ivf_tools.range_search_preassigned( - index, xq, 10.0, list_nos, zero_dis + Dq, list_nos = index.quantizer.search(xq, index.nprobe) + lq, Dr, Ir = ivf_tools.range_search_preassigned( + index, xq, 10.0, list_nos, Dq ) ln, Dn, In = ivf_tools.range_search_preassigned( index, xq, 10.0, list_nos ) - np.testing.assert_array_equal(lz, ln) - np.testing.assert_array_equal(Iz, In) - np.testing.assert_array_equal(Dz, Dn) + np.testing.assert_array_equal(lq, ln) + np.testing.assert_array_equal(Ir, In) + np.testing.assert_allclose(Dr, Dn, rtol=1e-5, atol=1e-5) + + def do_test_search_preassigned_coarse_dis_none(self, key, metric): + ds = datasets.SyntheticDataset(32, 2000, 2000, 100) + index = faiss.index_factory(ds.d, key, metric) + index.train(ds.get_train()) + index.add(ds.get_database()) + index.nprobe = 8 + xq = ds.get_queries() + D_ref, I_ref = index.search(xq, 10) + _, list_nos = index.quantizer.search(xq, index.nprobe) + D, I = ivf_tools.search_preassigned(index, xq, 10, list_nos) + np.testing.assert_array_equal(I_ref, I) + np.testing.assert_allclose(D_ref, D, rtol=1e-5, atol=1e-4) + + def test_search_preassigned_coarse_dis_none_ivfpq(self): + self.do_test_search_preassigned_coarse_dis_none( + "IVF32,PQ8", faiss.METRIC_L2 + ) + + def test_search_preassigned_coarse_dis_none_ip(self): + self.do_test_search_preassigned_coarse_dis_none( + "IVF32,SQ8", faiss.METRIC_INNER_PRODUCT + ) class TestRangeSearchMaxResults(unittest.TestCase): @@ -561,7 +520,6 @@ def do_test(self, metric_type): D, _ = index.search(ds.get_queries(), 10) radius0 = float(np.median(D[:, -1])) - # baseline = search with that radius lims_ref, Dref, Iref = index.range_search(ds.get_queries(), radius0) # now see if using just the total number of results, we can get back @@ -600,7 +558,6 @@ def test_binary(self): D, _ = index.search(xq, 10) radius0 = int(np.median(D[:, -1])) - # baseline = search with that radius lims_ref, Dref, Iref = index.range_search(xq, radius0) # now see if using just the total number of results, we can get back @@ -623,7 +580,6 @@ def test_binary(self): class TestClustering(unittest.TestCase): def test_python_kmeans(self): - """Test the python implementation of kmeans""" ds = datasets.SyntheticDataset(32, 5000, 0, 0) x = ds.get_train() @@ -639,7 +595,6 @@ def test_python_kmeans(self): centroids = clustering.kmeans(50, data, 10) err2 = faiss.knn(xt, centroids, 1)[0].sum() - # err=33498.332 err2=33380.477 self.assertLess(err2, err * 1.1) def test_2level(self): @@ -656,7 +611,6 @@ def test_2level(self): self.assertLess(err2, err * 1.1) def test_ivf_train_2level(self): - "check 2-level clustering with IVF training" ds = datasets.SyntheticDataset(32, 10000, 1000, 200) index = faiss.index_factory(ds.d, "PCA16,IVF100,SQ8") faiss.extract_index_ivf(index).nprobe = 10 @@ -677,11 +631,9 @@ def test_ivf_train_2level(self): self.assertLess(ndiff.item(), 57) def test_balanced_clustering(self): - """Test balanced_assignment_with_penalties from notebook N10159950""" ds = datasets.SyntheticDataset(32, 10000, 10000, 0) nc = 100 - # train centroids km = faiss.Kmeans(ds.d, nc) km.train(ds.get_train()) centroids = km.centroids @@ -691,24 +643,17 @@ def test_balanced_clustering(self): rs = np.random.RandomState(123) biased_xb += rs.randn(ds.d).astype("float32") * 0.3 - # unconstrained assignment on biased data d2, assign_unc = faiss.knn(biased_xb, centroids, 1) assign_unc = assign_unc.ravel() imf_unc = clustering.imbalance_factor(nc, assign_unc) mse_unc = float(d2.mean()) - # balanced assignment assign_bal, stats = clustering.balanced_assignment_with_penalties( biased_xb, centroids, alpha=0.03, num_iter=20 ) - # balanced assignment should reduce imbalance factor self.assertLess(stats["imf"], imf_unc / 1.5) - - # MSE may increase but should not be too much worse (< 2x) self.assertLess(stats["mse"], mse_unc * 1.5) - - # all points should be assigned self.assertEqual(len(assign_bal), len(biased_xb)) self.assertTrue(np.all(assign_bal >= 0)) self.assertTrue(np.all(assign_bal < nc)) @@ -743,9 +688,6 @@ def test_Flat_IP(self): def test_PQ(self): self.do_test("IVF64,PQ4np") - def test_SQ(self): - self.do_test("IVF64,SQ8") - def test_checkpoint(self): ds = datasets.SyntheticDataset(32, 2000, 400, 100) k = 10 @@ -758,7 +700,6 @@ def test_checkpoint(self): faiss.omp_set_num_threads(1) checkpoint = tempfile.mktemp() try: - # First big batch search try: Dnew, Inew = big_batch_search.big_batch_search( index, @@ -774,7 +715,6 @@ def test_checkpoint(self): pass else: self.assertFalse("should have crashed") - # Second big batch search Dnew, Inew = big_batch_search.big_batch_search( index, ds.get_queries(), @@ -866,7 +806,6 @@ def do_test_ondisk_merge(self, shift_ids=False): index.train(ds.get_train()) faiss.write_index(index, tmpdir + "/trained.index") - # create 4 shards and add elements to them ns = 4 # number of shards for bno in range(ns): @@ -878,7 +817,6 @@ def do_test_ondisk_merge(self, shift_ids=False): index.add_with_ids(ds.xb[i0:i1], np.arange(i0, i1)) faiss.write_index(index, tmpdir + "/block_%d.index" % bno) - # construct the output index and merge them on disk index = faiss.read_index(tmpdir + "/trained.index") block_fnames = [ tmpdir + "/block_%d.index" % bno for bno in range(4) @@ -889,12 +827,10 @@ def do_test_ondisk_merge(self, shift_ids=False): ) faiss.write_index(index, tmpdir + "/populated.index") - # perform a search from index on disk index = faiss.read_index(tmpdir + "/populated.index") index.nprobe = 5 D, I = index.search(ds.xq, 5) - # ground-truth gtI = ds.get_groundtruth(5) recall_at_1 = (I[:, :1] == gtI[:, :1]).sum() / float(ds.xq.shape[0]) @@ -904,7 +840,6 @@ def test_ondisk_merge(self): self.do_test_ondisk_merge() def test_ondisk_merge_with_shift_ids(self): - # verified that recall is same for test_ondisk_merge and self.do_test_ondisk_merge(True) @@ -925,26 +860,7 @@ def test_ivf_scalar_quantizer_types(self): d = 32 sq_types = { faiss.ScalarQuantizer.QT_8bit: "IVF32,SQ8", - faiss.ScalarQuantizer.QT_4bit: "IVF32,SQ4", - faiss.ScalarQuantizer.QT_8bit_uniform: "IVF32,SQ8u", - faiss.ScalarQuantizer.QT_4bit_uniform: "IVF32,SQ4u", - faiss.ScalarQuantizer.QT_6bit: "IVF32,SQ6", - faiss.ScalarQuantizer.QT_fp16: "IVF32,SQfp16", - faiss.ScalarQuantizer.QT_bf16: "IVF32,SQbf16", - faiss.ScalarQuantizer.QT_8bit_direct: "IVF32,SQ8_direct", - faiss.ScalarQuantizer.QT_8bit_direct_signed: ( - "IVF32,SQ8_direct_signed" - ), faiss.ScalarQuantizer.QT_0bit: "IVF32,SQ0", - faiss.ScalarQuantizer.QT_1bit_tqmse: "IVF32,SQtqmse1", - faiss.ScalarQuantizer.QT_2bit_tqmse: "IVF32,SQtqmse2", - faiss.ScalarQuantizer.QT_3bit_tqmse: "IVF32,SQtqmse3", - faiss.ScalarQuantizer.QT_4bit_tqmse: "IVF32,SQtqmse4", - faiss.ScalarQuantizer.QT_8bit_tqmse: "IVF32,SQtqmse8", - faiss.ScalarQuantizer.QT_2bit_tq: "IVF32,SQtq2", - faiss.ScalarQuantizer.QT_3bit_tq: "IVF32,SQtq3", - faiss.ScalarQuantizer.QT_4bit_tq: "IVF32,SQtq4", - faiss.ScalarQuantizer.QT_5bit_tq: "IVF32,SQtq5", } for qtype, expected in sq_types.items(): index = faiss.IndexIVFScalarQuantizer( @@ -984,21 +900,12 @@ def test_scalar_quantizer_types(self): def test_get_code_size_hnsw_non_default_m(self): d = 128 - # Non-default M values previously raised - # RuntimeError("cannot parse HNSW16") self.assertEqual( factory_tools.get_code_size(d, "HNSW16"), d * 4 + 16 * 2 * 4 ) - self.assertEqual( - factory_tools.get_code_size(d, "HNSW64"), d * 4 + 64 * 2 * 4 - ) self.assertEqual( factory_tools.get_code_size(d, "HNSW16,Flat"), d * 4 + 16 * 2 * 4 ) - # HNSW32 backward compat: formula generalizes correctly - self.assertEqual( - factory_tools.get_code_size(d, "HNSW32"), d * 4 + 32 * 2 * 4 - ) def test_get_code_size_ivf_hnsw_non_default_m(self): d = 128 @@ -1007,19 +914,6 @@ def test_get_code_size_ivf_hnsw_non_default_m(self): self.assertEqual( factory_tools.get_code_size(d, "IVF64_HNSW16,Flat"), d * 4 ) - self.assertEqual( - factory_tools.get_code_size(d, "IVF64_HNSW64,PQ8x8"), - (8 * 8 + 7) // 8, - ) - - def test_get_code_size_hnsw_roundtrip(self): - d = 128 - index = faiss.index_factory(d, "HNSW16,Flat") - factory_str = factory_tools.reverse_index_factory(index) - self.assertEqual(factory_str, "HNSW16") - # get_code_size(reverse_index_factory(index)) must not raise for any M - code_size = factory_tools.get_code_size(d, factory_str) - self.assertEqual(code_size, d * 4 + 16 * 2 * 4) def test_hnsw_storage_reverse_index_factory(self): d = 128 @@ -1027,14 +921,12 @@ def test_hnsw_storage_reverse_index_factory(self): cases = { "HNSW32,Flat": "HNSW32", "HNSW32,SQ8": "HNSW32,SQ8", - "HNSW32,SQfp16": "HNSW32,SQfp16", "HNSW32,PQ16x8": "HNSW32,PQ16x8", } for key, expected in cases.items(): index = faiss.index_factory(d, key) factory_str = factory_tools.reverse_index_factory(index) self.assertEqual(factory_str, expected) - # the string must rebuild the same index class rebuilt = faiss.index_factory(d, factory_str) self.assertEqual(type(rebuilt), type(index)) @@ -1055,7 +947,6 @@ def test_get_code_size_imi(self): # the coarse quantizer adds no per-vector bytes d = 64 self.assertEqual(factory_tools.get_code_size(d, "IMI2x10,PQ16"), 16) - self.assertEqual(factory_tools.get_code_size(d, "IMI2x5,Flat"), d * 4) # round-trip: get_code_size must parse what reverse emits index = faiss.index_factory(d, "IMI2x5,PQ8") factory_str = factory_tools.reverse_index_factory(index) @@ -1074,7 +965,7 @@ def test_ivfpqr_reverse_index_factory(self): def test_rabitq_reverse_index_factory(self): d = 64 quantizer = faiss.IndexFlatL2(d) - for nb_bits in [1, 2, 4]: + for nb_bits in [1, 2]: expected = "RaBitQ" if nb_bits == 1 else f"RaBitQ{nb_bits}" index = faiss.IndexRaBitQ(d, faiss.METRIC_L2, nb_bits) self.assertEqual( diff --git a/thirdparty/faiss/tests/test_contrib_with_scipy.py b/thirdparty/faiss/tests/test_contrib_with_scipy.py index 44716c537..d0fb8e8e6 100644 --- a/thirdparty/faiss/tests/test_contrib_with_scipy.py +++ b/thirdparty/faiss/tests/test_contrib_with_scipy.py @@ -18,7 +18,6 @@ class TestClustering(unittest.TestCase): def test_sparse_routines(self): - """the sparse assignment routine""" ds = datasets.SyntheticDataset(1000, 2000, 0, 200) xt = ds.get_train().copy() faiss.normalize_L2(xt) @@ -27,7 +26,6 @@ def test_sparse_routines(self): xt[np.logical_not(mask)] = 0 centroids = ds.get_queries() - assert len(centroids) == 200 xsparse = scipy.sparse.csr_matrix(xt) @@ -45,8 +43,6 @@ def test_sparse_routines(self): np.testing.assert_array_almost_equal(Dref.ravel(), D, decimal=3) def test_sparse_kmeans(self): - """demo on how to cluster sparse data into dense clusters""" - ds = datasets.SyntheticDataset(1000, 1500, 0, 0) xt = ds.get_train().copy() faiss.normalize_L2(xt) diff --git a/thirdparty/faiss/tests/test_cppcontrib_sa_decode.cpp b/thirdparty/faiss/tests/test_cppcontrib_sa_decode.cpp index 6ba8b471d..4d6707af9 100644 --- a/thirdparty/faiss/tests/test_cppcontrib_sa_decode.cpp +++ b/thirdparty/faiss/tests/test_cppcontrib_sa_decode.cpp @@ -30,12 +30,10 @@ std::tuple, std::vector> trainDataset( const uint64_t n, const uint64_t d, const std::string& description) { - // train an index auto index = std::shared_ptr( faiss::index_factory((int)d, description.c_str())); index->train((int)n, input.data()); - // encode const size_t codeSize = index->sa_code_size(); std::vector encodedData(n * codeSize); @@ -101,18 +99,14 @@ void verifyIndex2LevelDecoder( const uint64_t d, const std::shared_ptr& index, const std::vector& encodedData) { - // const float* pqFineCentroidsQ = nullptr; const float* pqCoarseCentroidsQ = nullptr; - // testIfIVFPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ); testIfResidualPQ(index.get(), &pqCoarseCentroidsQ, &pqFineCentroidsQ); - // const size_t codeSize = index->sa_code_size(); - // std::default_random_engine rng(123); std::uniform_real_distribution u(0, 1); @@ -121,22 +115,18 @@ void verifyIndex2LevelDecoder( std::vector tmpFaiss(d, 0); std::vector tmpContrib(d, 0); for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // compute using contrib T::store( pqCoarseCentroidsQ, pqFineCentroidsQ, encodedData.data() + i * codeSize, tmpContrib.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]); } - // save for the further comparison const float weight = u(rng); for (size_t j = 0; j < d; j++) { outputFaiss[j] += weight * tmpFaiss[j]; @@ -158,7 +148,6 @@ void verifyIndex2LevelDecoder( outputContrib1s.data()); } - // verify for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputFaiss[j], outputContrib1s[j]); } @@ -169,14 +158,12 @@ void verifyIndex2LevelDecoder( std::vector outputContrib2s(d, 0); std::vector outputContrib2sSame(d, 0); for (size_t i = 0; i < n; i += 2) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib2s[j] = (j + 1) * (j + 1); outputContrib2sSame[j] = (j + 1) * (j + 1); } - // do a single step, 2 samples per step const float weight0 = u(rng); const float weight1 = u(rng); @@ -191,7 +178,6 @@ void verifyIndex2LevelDecoder( weight1, outputContrib2s.data()); - // do a single step, 2 samples per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -201,7 +187,6 @@ void verifyIndex2LevelDecoder( weight1, outputContrib2sSame.data()); - // do two steps, 1 sample per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -215,7 +200,6 @@ void verifyIndex2LevelDecoder( weight1, outputContrib1s.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2s[j]); ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2sSame[j]); @@ -229,14 +213,12 @@ void verifyIndex2LevelDecoder( std::vector outputContrib3sSame(d, 0); const size_t n3 = (n / 3) * 3; for (size_t i = 0; i < n3; i += 3) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib3s[j] = (j + 1) * (j + 1); outputContrib3sSame[j] = (j + 1) * (j + 1); } - // do a single step, 3 samples per step const float weight0 = u(rng); const float weight1 = u(rng); const float weight2 = u(rng); @@ -256,7 +238,6 @@ void verifyIndex2LevelDecoder( weight2, outputContrib3s.data()); - // do a single step, 3 samples per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -268,7 +249,6 @@ void verifyIndex2LevelDecoder( weight2, outputContrib3sSame.data()); - // do three steps, 1 sample per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -288,7 +268,6 @@ void verifyIndex2LevelDecoder( weight2, outputContrib1s.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3s[j]); ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3sSame[j]); @@ -302,7 +281,6 @@ void verifyMinMaxIndex2LevelDecoder( const uint64_t d, const std::shared_ptr& index, const std::vector& encodedData) { - // const float* pqFineCentroidsQ = nullptr; const float* pqCoarseCentroidsQ = nullptr; @@ -313,42 +291,29 @@ void verifyMinMaxIndex2LevelDecoder( auto subIndex = indexMinMax->index; - // testIfIVFPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ); testIfResidualPQ(subIndex, &pqCoarseCentroidsQ, &pqFineCentroidsQ); - // const size_t codeSize = index->sa_code_size(); - // std::default_random_engine rng(123); std::uniform_real_distribution u(0, 1); // test general purpose version vs contrib::store - std::vector outputFaiss(d, 0); std::vector tmpFaiss(d, 0); std::vector tmpContrib(d, 0); for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // compute using contrib T::store( pqCoarseCentroidsQ, pqFineCentroidsQ, encodedData.data() + i * codeSize, tmpContrib.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]); } - - // save for the further comparison - const float weight = u(rng); - for (size_t j = 0; j < d; j++) { - outputFaiss[j] += weight * tmpFaiss[j]; - } } // test contrib::accum, 1 sample per iteration. @@ -360,19 +325,15 @@ void verifyMinMaxIndex2LevelDecoder( std::vector outputContrib1s(d, 0); float outputMinv1s = 0; for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // populate some initial data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); } outputMinv1s = 0; - // generate a weight const float weight0 = u(rng); - // T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -381,7 +342,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -397,7 +357,6 @@ void verifyMinMaxIndex2LevelDecoder( float outputMinv2s = 0; float outputMinv2sSame = 0; for (size_t i = 0; i < n; i += 2) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib2s[j] = (j + 1) * (j + 1); @@ -407,7 +366,6 @@ void verifyMinMaxIndex2LevelDecoder( outputMinv2s = 0; outputMinv2sSame = 0; - // do a single step, 2 samples per step const float weight0 = u(rng); const float weight1 = u(rng); @@ -423,7 +381,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib2s.data(), outputMinv2s); - // do a single step, 2 samples per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -434,7 +391,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib2sSame.data(), outputMinv2sSame); - // do two steps, 1 sample per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -450,7 +406,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -470,7 +425,6 @@ void verifyMinMaxIndex2LevelDecoder( float outputMinv3sSame = 0; const size_t n3 = (n / 3) * 3; for (size_t i = 0; i < n3; i += 3) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib3s[j] = (j + 1) * (j + 1); @@ -480,7 +434,6 @@ void verifyMinMaxIndex2LevelDecoder( outputMinv3s = 0; outputMinv3sSame = 0; - // do a single step, 3 samples per step const float weight0 = u(rng); const float weight1 = u(rng); const float weight2 = u(rng); @@ -501,7 +454,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib3s.data(), outputMinv3s); - // do a single step, 3 samples per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -514,7 +466,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib3sSame.data(), outputMinv3sSame); - // do three steps, 1 sample per step T::accum( pqCoarseCentroidsQ, pqFineCentroidsQ, @@ -537,7 +488,6 @@ void verifyMinMaxIndex2LevelDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -555,15 +505,12 @@ void verifyIndexPQDecoder( const uint64_t d, const std::shared_ptr& index, const std::vector& encodedData) { - // const faiss::IndexPQ* const indexQ = dynamic_cast(index.get()); const float* const pqFineCentroidsQ = indexQ->pq.centroids.data(); - // const size_t codeSize = index->sa_code_size(); - // std::default_random_engine rng(123); std::uniform_real_distribution u(0, 1); @@ -572,21 +519,17 @@ void verifyIndexPQDecoder( std::vector tmpFaiss(d, 0); std::vector tmpContrib(d, 0); for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // compute using contrib T::store( pqFineCentroidsQ, encodedData.data() + i * codeSize, tmpContrib.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]); } - // save for the further comparison const float weight = u(rng); for (size_t j = 0; j < d; j++) { outputFaiss[j] += weight * tmpFaiss[j]; @@ -607,7 +550,6 @@ void verifyIndexPQDecoder( outputContrib1s.data()); } - // verify for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputFaiss[j], outputContrib1s[j]); } @@ -618,14 +560,12 @@ void verifyIndexPQDecoder( std::vector outputContrib2s(d, 0); std::vector outputContrib2sSame(d, 0); for (size_t i = 0; i < n; i += 2) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib2s[j] = (j + 1) * (j + 1); outputContrib2sSame[j] = (j + 1) * (j + 1); } - // do a single step, 2 samples per step const float weight0 = u(rng); const float weight1 = u(rng); @@ -638,7 +578,6 @@ void verifyIndexPQDecoder( weight1, outputContrib2s.data()); - // do a single step, 2 samples per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -647,7 +586,6 @@ void verifyIndexPQDecoder( weight1, outputContrib2sSame.data()); - // do two steps, 1 sample per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -659,7 +597,6 @@ void verifyIndexPQDecoder( weight1, outputContrib1s.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2s[j]); ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib2sSame[j]); @@ -673,14 +610,12 @@ void verifyIndexPQDecoder( std::vector outputContrib3sSame(d, 0); const size_t n3 = (n / 3) * 3; for (size_t i = 0; i < n3; i += 3) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib3s[j] = (j + 1) * (j + 1); outputContrib3sSame[j] = (j + 1) * (j + 1); } - // do a single step, 3 samples per step const float weight0 = u(rng); const float weight1 = u(rng); const float weight2 = u(rng); @@ -697,7 +632,6 @@ void verifyIndexPQDecoder( weight2, outputContrib3s.data()); - // do a single step, 3 samples per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -708,7 +642,6 @@ void verifyIndexPQDecoder( weight2, outputContrib3sSame.data()); - // do three steps, 1 sample per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -725,7 +658,6 @@ void verifyIndexPQDecoder( weight2, outputContrib1s.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3s[j]); ASSERT_FLOAT_EQ(outputContrib1s[j], outputContrib3sSame[j]); @@ -746,42 +678,29 @@ void verifyMinMaxIndexPQDecoder( auto subIndex = indexMinMax->index; - // const faiss::IndexPQ* const indexQ = dynamic_cast(subIndex); const float* const pqFineCentroidsQ = indexQ->pq.centroids.data(); - // const size_t codeSize = index->sa_code_size(); - // std::default_random_engine rng(123); std::uniform_real_distribution u(0, 1); // test general purpose version vs contrib::store - std::vector outputFaiss(d, 0); std::vector tmpFaiss(d, 0); std::vector tmpContrib(d, 0); for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // compute using contrib T::store( pqFineCentroidsQ, encodedData.data() + i * codeSize, tmpContrib.data()); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ(tmpFaiss[j], tmpContrib[j]); } - - // save for the further comparison - const float weight = u(rng); - for (size_t j = 0; j < d; j++) { - outputFaiss[j] += weight * tmpFaiss[j]; - } } // test contrib::accum, 1 sample per iteration. @@ -793,19 +712,15 @@ void verifyMinMaxIndexPQDecoder( std::vector outputContrib1s(d, 0); float outputMinv1s = 0; for (size_t i = 0; i < n; i++) { - // compute using faiss index->sa_decode(1, encodedData.data() + i * codeSize, tmpFaiss.data()); - // populate some initial data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); } outputMinv1s = 0; - // generate a weight const float weight0 = u(rng); - // T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -813,7 +728,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -829,7 +743,6 @@ void verifyMinMaxIndexPQDecoder( std::vector outputContrib2sSame(d, 0); float outputMinv2sSame = 0; for (size_t i = 0; i < n; i += 2) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib2s[j] = (j + 1) * (j + 1); @@ -839,7 +752,6 @@ void verifyMinMaxIndexPQDecoder( outputMinv2s = 0; outputMinv2sSame = 0; - // do a single step, 2 samples per step const float weight0 = u(rng); const float weight1 = u(rng); @@ -853,7 +765,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib2s.data(), outputMinv2s); - // do a single step, 2 samples per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -863,7 +774,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib2sSame.data(), outputMinv2sSame); - // do two steps, 1 sample per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -877,7 +787,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -897,7 +806,6 @@ void verifyMinMaxIndexPQDecoder( float outputMinv3sSame = 0; const size_t n3 = (n / 3) * 3; for (size_t i = 0; i < n3; i += 3) { - // populate outputContribs with some existing data for (size_t j = 0; j < d; j++) { outputContrib1s[j] = (j + 1) * (j + 1); outputContrib3s[j] = (j + 1) * (j + 1); @@ -907,7 +815,6 @@ void verifyMinMaxIndexPQDecoder( outputMinv3s = 0; outputMinv3sSame = 0; - // do a single step, 3 samples per step const float weight0 = u(rng); const float weight1 = u(rng); const float weight2 = u(rng); @@ -925,7 +832,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib3s.data(), outputMinv3s); - // do a single step, 3 samples per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -937,7 +843,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib3sSame.data(), outputMinv3sSame); - // do three steps, 1 sample per step T::accum( pqFineCentroidsQ, encodedData.data() + (i + 0) * codeSize, @@ -957,7 +862,6 @@ void verifyMinMaxIndexPQDecoder( outputContrib1s.data(), outputMinv1s); - // compare for (size_t j = 0; j < d; j++) { ASSERT_FLOAT_EQ( outputContrib1s[j] + outputMinv1s, @@ -975,7 +879,6 @@ std::vector generate(const size_t n, const size_t d) { std::minstd_rand rng(345); std::uniform_real_distribution ux(0, 1); - // for (size_t k = 0; k < n; k++) { for (size_t j = 0; j < d; j++) { data[k * d + j] = ux(rng); @@ -1039,7 +942,6 @@ void testMinMaxIndexPQDecoder( constexpr size_t NSAMPLES = 256; -// TEST(testCppcontribSaDecode, D256_IVF256_PQ16) { using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>; testIndex2LevelDecoder(NSAMPLES, 256, "IVF256,PQ16np"); @@ -1050,70 +952,26 @@ TEST(testCppcontribSaDecode, D256_IVF256_PQ8) { testIndex2LevelDecoder(NSAMPLES, 256, "IVF256,PQ8np"); } -// TEST(testCppcontribSaDecode, D192_IVF256_PQ24) { using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 8>; testIndex2LevelDecoder(NSAMPLES, 192, "IVF256,PQ24np"); } -// TEST(testCppcontribSaDecode, D192_IVF256_PQ16) { using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 12>; testIndex2LevelDecoder(NSAMPLES, 192, "IVF256,PQ16np"); } -// -TEST(testCppcontribSaDecode, D192_IVF256_PQ12) { - using T = faiss::cppcontrib::Index2LevelDecoder<192, 192, 16>; - testIndex2LevelDecoder(NSAMPLES, 192, "IVF256,PQ12np"); -} - -// TEST(testCppcontribSaDecode, D160_IVF256_PQ40) { using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 4>; testIndex2LevelDecoder(NSAMPLES, 160, "IVF256,PQ40np"); } -// -TEST(testCppcontribSaDecode, D160_IVF256_PQ20) { - using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 8>; - testIndex2LevelDecoder(NSAMPLES, 160, "IVF256,PQ20np"); -} - -// -TEST(testCppcontribSaDecode, D160_IVF256_PQ10) { - using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 16>; - testIndex2LevelDecoder(NSAMPLES, 160, "IVF256,PQ10np"); -} - -// TEST(testCppcontribSaDecode, D160_IVF256_PQ8) { using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 20>; testIndex2LevelDecoder(NSAMPLES, 160, "IVF256,PQ8np"); } -// -TEST(testCppcontribSaDecode, D128_IVF256_PQ8) { - using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 16>; - testIndex2LevelDecoder(NSAMPLES, 128, "IVF256,PQ8np"); -} - -TEST(testCppcontribSaDecode, D128_IVF256_PQ4) { - using T = faiss::cppcontrib::Index2LevelDecoder<128, 128, 32>; - testIndex2LevelDecoder(NSAMPLES, 128, "IVF256,PQ4np"); -} - -// -TEST(testCppcontribSaDecode, D64_IVF256_PQ16) { - using T = faiss::cppcontrib::Index2LevelDecoder<64, 64, 8>; - testIndex2LevelDecoder(NSAMPLES, 64, "IVF256,PQ8np"); -} - -TEST(testCppcontribSaDecode, D64_IVF256_PQ8) { - using T = faiss::cppcontrib::Index2LevelDecoder<64, 64, 16>; - testIndex2LevelDecoder(NSAMPLES, 64, "IVF256,PQ4np"); -} - #if defined(__AVX2__) TEST(testCppcontribSaDecode, D40_IVF256_PQ20) { using T = faiss::cppcontrib::Index2LevelDecoder<40, 40, 2>; @@ -1121,7 +979,6 @@ TEST(testCppcontribSaDecode, D40_IVF256_PQ20) { } #endif -// TEST(testCppcontribSaDecode, D256_Residual4x8_PQ16) { using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16>; testIndex2LevelDecoder(NSAMPLES, 256, "Residual4x8,PQ16"); @@ -1132,47 +989,11 @@ TEST(testCppcontribSaDecode, D256_Residual4x8_PQ8) { testIndex2LevelDecoder(NSAMPLES, 256, "Residual4x8,PQ8"); } -// TEST(testCppcontribSaDecode, D160_Residual4x8_PQ10) { using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 16>; testIndex2LevelDecoder(NSAMPLES, 160, "Residual4x8,PQ10"); } -// -TEST(testCppcontribSaDecode, D160_Residual2x8_PQ10) { - using T = faiss::cppcontrib::Index2LevelDecoder<160, 80, 16>; - testIndex2LevelDecoder(NSAMPLES, 160, "Residual2x8,PQ10"); -} - -// -TEST(testCppcontribSaDecode, D160_Residual1x8_PQ10) { - using T = faiss::cppcontrib::Index2LevelDecoder<160, 160, 16>; - testIndex2LevelDecoder(NSAMPLES, 160, "Residual1x8,PQ10"); -} - -// -TEST(testCppcontribSaDecode, D128_Residual4x8_PQ8) { - using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 16>; - testIndex2LevelDecoder(NSAMPLES, 128, "Residual4x8,PQ8"); -} - -TEST(testCppcontribSaDecode, D128_Residual4x8_PQ4) { - using T = faiss::cppcontrib::Index2LevelDecoder<128, 32, 32>; - testIndex2LevelDecoder(NSAMPLES, 128, "Residual4x8,PQ4"); -} - -// -TEST(testCppcontribSaDecode, D64_Residual4x8_PQ8) { - using T = faiss::cppcontrib::Index2LevelDecoder<64, 16, 8>; - testIndex2LevelDecoder(NSAMPLES, 64, "Residual4x8,PQ8"); -} - -TEST(testCppcontribSaDecode, D64_Residual4x8_PQ4) { - using T = faiss::cppcontrib::Index2LevelDecoder<64, 16, 16>; - testIndex2LevelDecoder(NSAMPLES, 64, "Residual4x8,PQ4"); -} - -// TEST(testCppcontribSaDecode, D256_IVF1024_PQ16) { // It is acceptable to use COARSE_BITS=16 in this case, // because there's only one coarse quantizer element. @@ -1188,13 +1009,11 @@ TEST(testCppcontribSaDecode, D64_Residual1x9_PQ8) { testIndex2LevelDecoder(NSAMPLES * 2, 64, "Residual1x9,PQ8"); } -// TEST(testCppcontribSaDecode, D256_PQ16) { using T = faiss::cppcontrib::IndexPQDecoder<256, 16>; testIndexPQDecoder(NSAMPLES, 256, "PQ16np"); } -// TEST(testCppcontribSaDecode, D160_PQ20) { using T = faiss::cppcontrib::IndexPQDecoder<160, 8>; testIndexPQDecoder(NSAMPLES, 160, "PQ20np"); @@ -1207,7 +1026,6 @@ TEST(testCppcontribSaDecode, D40_PQ20) { } #endif -// test IndexRowwiseMinMaxFP16 TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF256_PQ16) { using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>; using T = faiss::cppcontrib::IndexMinMaxFP16Decoder; @@ -1220,7 +1038,6 @@ TEST(testCppcontribSaDecode, D256_MINMAXFP16_PQ16) { testMinMaxIndexPQDecoder(NSAMPLES, 256, "MinMaxFP16,PQ16np"); } -// test IndexRowwiseMinMax TEST(testCppcontribSaDecode, D256_MINMAX_IVF256_PQ16) { using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>; using T = faiss::cppcontrib::IndexMinMaxDecoder; @@ -1265,13 +1082,6 @@ TEST(testCppcontribSaDecode, D256_IVF256_PQ16x12) { testIndex2LevelDecoder(NSAMPLES * 16, 256, "IVF256,PQ16x12np"); } -TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF256_PQ16x10) { - using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>; - using T = faiss::cppcontrib::IndexMinMaxFP16Decoder; - testMinMaxIndex2LevelDecoder( - NSAMPLES * 4, 256, "MinMaxFP16,IVF256,PQ16x10np"); -} - TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF1024_PQ16x10) { using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>; using T = faiss::cppcontrib::IndexMinMaxFP16Decoder; @@ -1279,13 +1089,6 @@ TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF1024_PQ16x10) { NSAMPLES * 4, 256, "MinMaxFP16,IVF1024,PQ16x10np"); } -TEST(testCppcontribSaDecode, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) { - using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>; - using T = faiss::cppcontrib::IndexMinMaxFP16Decoder; - testMinMaxIndex2LevelDecoder( - NSAMPLES * 4, 256, "MinMaxFP16,IVF1024,PQ16x10np"); -} - TEST(testCppcontribSaDecode, D160_Residual4x8_PQ8x10) { using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>; testIndex2LevelDecoder(NSAMPLES * 4, 160, "Residual4x8,PQ8x10"); diff --git a/thirdparty/faiss/tests/test_cppcontrib_uintreader.cpp b/thirdparty/faiss/tests/test_cppcontrib_uintreader.cpp index 5b5ae5303..6af477730 100644 --- a/thirdparty/faiss/tests/test_cppcontrib_uintreader.cpp +++ b/thirdparty/faiss/tests/test_cppcontrib_uintreader.cpp @@ -24,7 +24,6 @@ struct TestLoop { static void test( const uint8_t* const container, faiss::BitstringReader& br) { - // validate const intptr_t uintreader_data = faiss::cppcontrib::detail:: UintReaderRaw::get(container); const intptr_t bitstringreader_data = br.read(CODE_BITS); @@ -35,7 +34,6 @@ struct TestLoop { << ") for N_ELEMENTS=" << N_ELEMENTS << ", CODE_BITS=" << CODE_BITS << ", CPOS=" << CPOS; - // TestLoop::test(container, br); } }; @@ -54,22 +52,18 @@ void TestUintReader() { std::default_random_engine rng; std::uniform_int_distribution u(0, 1 << CODE_BITS); - // do several attempts for (size_t attempt = 0; attempt < 10; attempt++) { // allocate a buffer. This way, not std::vector std::unique_ptr container(new uint8_t[CODE_BYTES]); - // make it empty for (size_t i = 0; i < CODE_BYTES; i++) { container.get()[i] = 0; } - // populate it faiss::BitstringWriter bw(container.get(), CODE_BYTES); for (size_t i = 0; i < N_ELEMENTS; i++) { bw.write(u(rng), CODE_BITS); } - // read it back and verify against bitreader faiss::BitstringReader br(container.get(), CODE_BYTES); TestLoop::test(container.get(), br); diff --git a/thirdparty/faiss/tests/test_custom_result_handler.cpp b/thirdparty/faiss/tests/test_custom_result_handler.cpp index a8beebec3..5d2ee611b 100644 --- a/thirdparty/faiss/tests/test_custom_result_handler.cpp +++ b/thirdparty/faiss/tests/test_custom_result_handler.cpp @@ -16,7 +16,9 @@ #include #include +#include #include +#include #include #include #include @@ -35,7 +37,6 @@ struct CollectAllResultHandler : ResultHandler { return true; } - // Sort results by distance and return the top k void get_top_k( size_t top_k, std::vector& out_D, @@ -43,13 +44,11 @@ struct CollectAllResultHandler : ResultHandler { bool is_max) const { size_t n_results = D.size(); - // Create indices for sorting std::vector indices(n_results); for (size_t i = 0; i < n_results; i++) { indices[i] = i; } - // Make local copies for lambda capture const std::vector& distances = D; // Sort by distance (ascending for L2, descending for IP) @@ -69,7 +68,6 @@ struct CollectAllResultHandler : ResultHandler { }); } - // Take top k size_t n_out = std::min(top_k, n_results); out_D.resize(n_out); out_I.resize(n_out); @@ -102,75 +100,46 @@ TEST(TestSingleQueryBlockResultHandler, SynchronizesWrappedThreshold) { EXPECT_FLOAT_EQ(single.threshold, 4.0f); } -// dimension of the vectors to index constexpr int d = 64; - -// nb of training vectors constexpr size_t nt = 5000; - -// size of the database constexpr size_t nb = 2000; - -// nb of queries constexpr size_t nq = 100; - -// k for search constexpr int k = 10; -/** - * Generate smooth random data using Faiss's rand_smooth_vectors. - * This produces data with intrinsic dimensionality ~10 that is harder to - * index than a subspace but easier than uniform random data. - */ +// Intrinsic dimensionality ~10: harder than a subspace, easier than uniform. std::vector make_smooth_data(size_t n, int64_t seed) { std::vector data(n * d); rand_smooth_vectors(n, d, data.data(), seed); return data; } -/** - * Test helper: trains an index, adds data, and performs a search using - * both the standard search method and the custom handler search1 method. - * Compares the results to ensure they match. - */ +// Compares the top-k of search() with search1() through a collect-all handler. void test_index( const char* index_key, MetricType metric, double min_match_ratio = 1.0) { - // Create index using factory std::unique_ptr index(index_factory(d, index_key, metric)); - ASSERT_NE(index, nullptr) << "Failed to create IVF index for " << index_key; - // Generate smooth random data for training and database auto xt = make_smooth_data(nt, 1234); auto xb = make_smooth_data(nb, 4567); auto xq = make_smooth_data(nq, 7890); - // Train the index index->train(nt, xt.data()); - - // Add database vectors index->add(nb, xb.data()); - // Set nprobe for IVF indexes if (IndexIVF* index_ivf = dynamic_cast(index.get())) { index_ivf->nprobe = 4; } - // Perform reference search using standard search method std::vector Iref(nq * k); std::vector Dref(nq * k); index->search(nq, xq.data(), k, Dref.data(), Iref.data()); - // For IP metric, we need to sort in descending order bool is_max = (metric == METRIC_INNER_PRODUCT); - // Now test search1 with custom handler for each query for (size_t q = 0; q < nq; q++) { CollectAllResultHandler handler; - // Set threshold to collect all results - // For L2: use max float (condition: threshold > distance) - // For IP: use min float (condition: threshold < distance) + // threshold that every result passes if (is_max) { handler.threshold = -std::numeric_limits::max(); } else { @@ -178,20 +147,16 @@ void test_index( } index->search1(xq.data() + q * d, handler); - // Sort the handler results and get top k std::vector D_handler; std::vector I_handler; handler.get_top_k(k, D_handler, I_handler, is_max); - // Compare with reference results for this query using set comparison const idx_t* Iref_q = Iref.data() + q * k; - // Create sets of IDs for comparison std::unordered_set ref_set(Iref_q, Iref_q + k); std::unordered_set handler_set( I_handler.begin(), I_handler.end()); - // Count how many results from handler are in the reference set int matches = 0; for (idx_t id : handler_set) { if (ref_set.count(id) > 0) { @@ -199,7 +164,6 @@ void test_index( } } - // Check that matches meet the minimum threshold EXPECT_GE(matches, static_cast(k * min_match_ratio)) << "Query " << q << ": expected at least " << static_cast(k * min_match_ratio) << " matches, got " @@ -207,30 +171,14 @@ void test_index( } } -/************************************************************* - * Test cases for different IVF index types - *************************************************************/ - TEST(TestIndexTypes, IVFFlat_L2) { test_index("IVF32,Flat", METRIC_L2); } -TEST(TestIndexTypes, IVFFlat_IP) { - test_index("IVF32,Flat", METRIC_INNER_PRODUCT); -} - TEST(TestIndexTypes, IVFPQ_L2) { test_index("IVF32,PQ8np", METRIC_L2); } -TEST(TestIndexTypes, IVFPQ_IP) { - test_index("IVF32,PQ8np", METRIC_INNER_PRODUCT); -} - -TEST(TestIndexTypes, IVFSQ_L2) { - test_index("IVF32,SQ8", METRIC_L2); -} - TEST(TestIndexTypes, IVFRaBitQ_IP) { test_index("IVF32,RaBitQ", METRIC_INNER_PRODUCT); } @@ -253,4 +201,52 @@ TEST(TestIndexTypes, SQ8) { test_index("SQ8", METRIC_L2); } +TEST(RaBitQScanner, MatchesDistanceComputer) { + auto xb = make_smooth_data(nb, 4567); + auto xq = make_smooth_data(1, 7890); + for (auto [nb_bits, qb] : {std::pair{1, 4}, std::pair{4, 0}}) { + IndexFlatL2 quantizer(d); + IndexIVFRaBitQ index(&quantizer, d, 1, METRIC_L2, true, nb_bits); + index.qb = qb; + index.train(nb, xb.data()); + index.add(nb, xb.data()); + InvertedLists::ScopedCodes codes(index.invlists, 0); + + std::unique_ptr scanner( + index.get_InvertedListScanner(true, nullptr, nullptr)); + scanner->set_query(xq.data()); + scanner->set_list(0, 0); + + std::vector dis(nb); + for (size_t j = 0; j < nb; j++) { + dis[j] = scanner->distance_to_code( + codes.get() + j * index.code_size); + } + std::vector sorted_dis = dis; + std::sort(sorted_dis.begin(), sorted_dis.end()); + CollectAllResultHandler handler; + handler.threshold = sorted_dis[nb / 2]; + + std::vector expected; + for (size_t j = 0; j < nb; j++) { + if (dis[j] < handler.threshold) { + expected.push_back(j); + } + } + + scanner->scan_codes(nb, codes.get(), nullptr, handler); + if (nb_bits > 1) { + // The probabilistic error-bound prune may drop a true hit. + EXPECT_TRUE( + std::includes( + expected.begin(), + expected.end(), + handler.I.begin(), + handler.I.end())); + } else { + EXPECT_EQ(handler.I, expected); + } + } +} + } // namespace diff --git a/thirdparty/faiss/tests/test_dealloc_invlists.cpp b/thirdparty/faiss/tests/test_dealloc_invlists.cpp index 8a14190c0..aea5814c0 100644 --- a/thirdparty/faiss/tests/test_dealloc_invlists.cpp +++ b/thirdparty/faiss/tests/test_dealloc_invlists.cpp @@ -23,16 +23,9 @@ using namespace faiss; namespace { -// dimension of the vectors to index int d = 32; - -// nb of training vectors size_t nt = 5000; - -// size of the database points per window step size_t nb = 1000; - -// nb of queries size_t nq = 200; std::mt19937 rng; @@ -49,7 +42,7 @@ std::vector make_data(size_t n) { std::unique_ptr make_trained_index(const char* index_type) { auto index = std::unique_ptr(index_factory(d, index_type)); - auto xt = make_data(nt * d); + auto xt = make_data(nt); index->train(nt, xt.data()); ParameterSpace().set_index_parameter(index.get(), "nprobe", 4); return index; @@ -63,10 +56,6 @@ std::vector search_index(Index* index, const float* xq) { return I; } -/************************************************************* - * Test functions for a given index type - *************************************************************/ - struct EncapsulateInvertedLists : InvertedLists { const InvertedLists* il; @@ -129,10 +118,10 @@ int test_dealloc_invlists(const char* index_key) { std::unique_ptr index = make_trained_index(index_key); IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get()); - auto xb = make_data(nb * d); + auto xb = make_data(nb); index->add(nb, xb.data()); - auto xq = make_data(nq * d); + auto xq = make_data(nq); auto ref_res = search_index(index.get(), xq.data()); @@ -144,28 +133,14 @@ int test_dealloc_invlists(const char* index_key) { // TEST: this could crash or leak mem auto new_res = search_index(index.get(), xq.data()); - // delete explicitly delete eil.il; - // just to make sure EXPECT_EQ(ref_res, new_res); return 0; } } // anonymous namespace -/************************************************************* - * Test entry points - *************************************************************/ - TEST(TestIvlistDealloc, IVFFlat) { test_dealloc_invlists("IVF32,Flat"); } - -TEST(TestIvlistDealloc, IVFSQ) { - test_dealloc_invlists("IVF32,SQ8"); -} - -TEST(TestIvlistDealloc, IVFPQ) { - test_dealloc_invlists("IVF32,PQ4np"); -} diff --git a/thirdparty/faiss/tests/test_deterministic_nndescent.py b/thirdparty/faiss/tests/test_deterministic_nndescent.py new file mode 100644 index 000000000..c2d69c432 --- /dev/null +++ b/thirdparty/faiss/tests/test_deterministic_nndescent.py @@ -0,0 +1,453 @@ +# 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. + +"""Tests for DeterministicNNDescent, a KNN graph build that does not depend +on the thread count.""" + +import unittest + +import faiss +import numpy as np + +from common_faiss_tests import for_all_simd_levels, get_dataset_2 + +DIM = 32 +NB = 5000 +K = 10 + + +def graph_recall(dnd, xb, metric, k=K): + """recall of the first k neighbors against the exact KNN graph""" + _, gt = faiss.knn(xb, xb, k + 1, metric) + I = faiss.vector_to_array(dnd.ids).reshape(len(xb), -1)[:, :k] + hits = 0 + for i in range(len(xb)): + hits += len(set(I[i]) & (set(gt[i]) - {i})) + return hits / (len(xb) * k) + + +def build(xb, metric=faiss.METRIC_L2, nthreads=None, **params): + storage = faiss.IndexFlat(xb.shape[1], metric) + storage.add(xb) + dnd = faiss.DeterministicNNDescent() + dnd.K = 2 * K + for name, value in params.items(): + setattr(dnd, name, value) + if nthreads is not None: + faiss.omp_set_num_threads(nthreads) + dnd.build(storage) + return dnd, storage + + +def split_by_counts(arrays, counts): + """the items of each list for each destination process""" + bounds = np.concatenate([[0], np.cumsum(counts)]) + return [ + [a[bounds[q] : bounds[q + 1]] for a in arrays] + for q in range(len(counts)) + ] + + +def expected_remote_ids(rows, prev, lo, hi, received, R, begin, end): + """the remote ids of the home rows [begin, end) of the process that owns + [lo, hi), computed from the rows: an entry is new if it is not in the + row of the previous round (sample = 0), and a home row keeps its R + nearest reverse edges by (distance, source)""" + t, src, ed, en = received + home = rows[lo:hi] + is_new = home >= 0 + if prev is not None: + is_new &= ~(home[:, :, None] == prev[lo:hi, None, :]).any(axis=2) + o = np.lexsort((src, ed, t)) + t, src, en = t[o] - lo, src[o], en[o] + first = np.searchsorted(t, t) + keep = np.arange(len(t)) - first < R + t, src, en = t[keep], src[keep], en[keep] + has_new = is_new.any(axis=1) + has_new[t[en != 0]] = True + sel = np.zeros(hi - lo, dtype=bool) + sel[begin:end] = True + sel &= has_new + ids = np.concatenate([home[sel].ravel(), src[sel[t]]]) + return np.unique(ids[(ids >= 0) & ((ids < lo) | (ids >= hi))]) + + +def sharded_rounds(xb, I, D, metric, K, R, nproc, sample, nrounds, + remote_vectors="float32", chunks=1, + check_remote_ids=False): + """nrounds NNDescentShard rounds over nproc simulated processes; returns + the rows, then the changed rows of each round. + remote_vectors: "float32", "rounded" (float32 vectors rounded to + float16), "float16" (join_fp16()), "sq8_decoded" (float32 vectors + through 8-bit codes) or "sq8" (join_sq8()). chunks: join() calls per + round, each on a range of the home rows (select_rows()). + check_remote_ids: compare remote_ids with expected_remote_ids().""" + n, d = xb.shape + bounds = np.linspace(0, n, nproc + 1).astype("int64") + shards = [] + for p in range(nproc): + lo, hi = bounds[p], bounds[p + 1] + s = faiss.NNDescentShard() + s.R = R + s.sample = sample + s.set_rows( + K, metric, d, p, nproc, faiss.swig_ptr(bounds), + faiss.swig_ptr(xb[lo:hi]), + faiss.swig_ptr(np.ascontiguousarray(I[lo:hi])), + faiss.swig_ptr(np.ascontiguousarray(D[lo:hi])), + ) + shards.append(s) + + def route(lists): + # lists[i] = (counts, arrays) from a process; returns the arrays that + # each process receives, in the order of lists + parts = [split_by_counts(a, c) for c, a in lists] + return [ + [np.concatenate([parts[i][q][j] for i in range(len(lists))]) + for j in range(len(lists[0][1]))] + for q in range(nproc) + ] + + vec = faiss.vector_to_array + changed = [] + vmin = xb.min(axis=0) + vdiff = np.maximum(xb.max(axis=0) - vmin, 1e-12).astype("float32") + + def sq8_encode(v): + return np.clip( + np.floor((v - vmin) / vdiff * 255), 0, 255 + ).astype("uint8") + + def sq8_decode(c): + return (vmin + (c.astype("float32") + 0.5) / 255 * vdiff).astype( + "float32" + ) + + prev = None + for _ in range(nrounds): + sent = [] + for s in shards: + c, t, src, ed, en = (faiss.Int64Vector(), faiss.Int64Vector(), + faiss.Int64Vector(), faiss.Float32Vector(), + faiss.UInt8Vector()) + s.reverse_edges(c, t, src, ed, en) + sent.append((vec(c), [vec(t), vec(src), vec(ed), vec(en)])) + received = route(sent) + for s, (t, src, ed, en) in zip(shards, received): + s.set_reverse_edges(len(t), faiss.swig_ptr(t), + faiss.swig_ptr(src), faiss.swig_ptr(ed), + faiss.swig_ptr(en)) + rows = np.concatenate([vec(s.ids).reshape(-1, K) for s in shards]) + rdis = np.concatenate([vec(s.dis).reshape(-1, K) for s in shards]) + kth = np.where(rows[:, -1] >= 0, rdis[:, -1], np.inf).astype("float32") + sent = [] + keep = [] + for p, s in enumerate(shards): + for ch in range(chunks): + nh = s.nhome() + begin, end = nh * ch // chunks, nh * (ch + 1) // chunks + if chunks > 1: + s.select_rows(begin, end) + h = vec(s.remote_ids) + if check_remote_ids: + np.testing.assert_array_equal(h, expected_remote_ids( + rows, prev, bounds[p], bounds[p + 1], received[p], R, + begin, end)) + hx = np.ascontiguousarray(xb[h]) + hk = np.ascontiguousarray(kth[h]) + if remote_vectors == "rounded": + hx = hx.astype("float16").astype("float32") + if remote_vectors == "sq8_decoded": + hx = np.ascontiguousarray(sq8_decode(sq8_encode(hx))) + keep.append((hx, hk)) + c, t, cand, od = (faiss.Int64Vector(), faiss.Int64Vector(), + faiss.Int64Vector(), faiss.Float32Vector()) + if remote_vectors == "float16": + hx16 = hx.astype("float16").view("uint16") + keep.append(hx16) + s.join_fp16(faiss.swig_ptr(hx16), faiss.swig_ptr(hk), + c, t, cand, od) + elif remote_vectors == "sq8": + codes = np.ascontiguousarray(sq8_encode(hx)) + keep.append(codes) + s.join_sq8(faiss.swig_ptr(codes), faiss.swig_ptr(vmin), + faiss.swig_ptr(vdiff), faiss.swig_ptr(hk), + c, t, cand, od) + else: + s.join(faiss.swig_ptr(hx), faiss.swig_ptr(hk), + c, t, cand, od) + sent.append((vec(c), [vec(t), vec(cand), vec(od)])) + changed.append(0) + for s, (t, cand, od) in zip(shards, route(sent)): + s.insert_candidates(len(t), faiss.swig_ptr(t), + faiss.swig_ptr(cand), faiss.swig_ptr(od)) + changed[-1] += s.end_round() + prev = rows + I2 = np.concatenate([vec(s.ids).reshape(-1, K) for s in shards]) + D2 = np.concatenate([vec(s.dis).reshape(-1, K) for s in shards]) + return I2, D2, changed + + +def init_rows(xb, metric=faiss.METRIC_L2, **params): + """the storage, the DeterministicNNDescent and the rows after a random + init()""" + storage = faiss.IndexFlat(xb.shape[1], metric) + storage.add(xb) + dnd = faiss.DeterministicNNDescent() + dnd.K = 2 * K + dnd.R = 15 + dnd.ntrees = 0 + for name, value in params.items(): + setattr(dnd, name, value) + dnd.init(storage) + I = faiss.vector_to_array(dnd.ids).reshape(-1, dnd.K).astype("int64") + D = faiss.vector_to_array(dnd.dis).reshape(-1, dnd.K) + return storage, dnd, I, D + + +@for_all_simd_levels +class TestDeterministicNNDescent(unittest.TestCase): + + def test_recall(self): + _, xb, _ = get_dataset_2(DIM, 0, NB, 0) + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + for ntrees in 0, 2: + with self.subTest(metric=metric, ntrees=ntrees): + dnd, _ = build(xb, metric, ntrees=ntrees) + self.assertGreater(graph_recall(dnd, xb, metric), 0.97) + + def test_deterministic(self): + # with BLAS, some pairs get two distances (direct in init(), from the + # norms in the joins) at d = 32, and none at d = 8 + self.addCleanup(faiss.omp_set_num_threads, faiss.omp_get_max_threads()) + for d in DIM, 8: + with self.subTest(d=d): + _, xb, _ = get_dataset_2(d, 0, NB, 0) + a, _ = build(xb, nthreads=1, sample=8) + b, _ = build(xb, nthreads=8, sample=8) + for field in "ids", "dis": + np.testing.assert_array_equal( + faiss.vector_to_array(getattr(a, field)), + faiss.vector_to_array(getattr(b, field)), + ) + + def test_rows_sorted_and_distinct(self): + # 601 copies of one vector, more than a leaf: no pivot separates + # them, so each tree splits their segment by position + _, xb, _ = get_dataset_2(DIM, 0, 2000, 0) + xb[1000:1600] = xb[0] + dnd, _ = build(xb, max_rounds=3) + I = faiss.vector_to_array(dnd.ids).reshape(len(xb), -1) + D = faiss.vector_to_array(dnd.dis).reshape(len(xb), -1) + self.assertTrue((I >= 0).all()) + self.assertTrue((I != np.arange(len(xb))[:, None]).all()) + self.assertTrue((np.diff(D, axis=1) >= 0).all()) + for row in I: + self.assertEqual(len(set(row)), len(row)) + + def test_distances(self): + # the joins take the distances from the Gram kernel of the SIMD + # level; d = 33 leaves a tail for each kernel + _, xb, _ = get_dataset_2(33, 0, 2000, 0) + x = xb.astype("float64") + nrm = (x**2).sum(1) + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + with self.subTest(metric=metric): + dnd, _ = build(xb, metric, ntrees=0) + I = faiss.vector_to_array(dnd.ids).reshape(len(xb), -1) + D = faiss.vector_to_array(dnd.dis).reshape(len(xb), -1) + ip = np.einsum("id,ijd->ij", x, x[I]) + if metric == faiss.METRIC_L2: + ref = nrm[:, None] + nrm[I] - 2 * ip + else: + ref = -ip + np.testing.assert_allclose(D, ref, atol=1e-5 * nrm.max()) + + def test_small_n(self): + # K = n - 1 and R > K, as for a small partition of a distributed build + _, xb, _ = get_dataset_2(8, 0, 2, 0) + dnd, _ = build(xb, K=1, R=50, max_rounds=3) + np.testing.assert_array_equal(faiss.vector_to_array(dnd.ids), [1, 0]) + + def test_short_rows_stop(self): + # the padding of rows shorter than K is not new + _, xb, _ = get_dataset_2(DIM, 0, 10, 0) + storage, dnd, _, _ = init_rows(xb, K=64, sample=2, ntrees=8) + changed = [dnd.round(storage) for _ in range(6)] + # a round without changes leaves no new entries, so all later rounds + # also change nothing + self.assertEqual(changed[5], 0) + + def test_ndis(self): + # ndis counts the distances that init() computes, before the cut + _, xb, _ = get_dataset_2(DIM, 0, 1000, 0) + _, dnd, _, _ = init_rows(xb, K=10) + self.assertGreater(dnd.ndis, 1000 * 10) + + def test_inner_product_overflow(self): + # the inner product of these finite vectors overflows to NaN + xb = np.empty((300, 4), dtype="float32") + xb[::2] = (-1e20, 1e20, 1e20, 1e20) + xb[1::2] = (1e20, -1e20, 1e20, 1e20) + dnd, _ = build(xb, faiss.METRIC_INNER_PRODUCT, ntrees=0, max_rounds=3) + self.assertFalse(np.isnan(faiss.vector_to_array(dnd.dis)).any()) + + def test_invalid_storage(self): + dnd = faiss.DeterministicNNDescent() + with self.assertRaisesRegex(RuntimeError, "d must be > 0"): + dnd.init(faiss.IndexFlatL2(0)) + # a quantizer without a decoder + storage = faiss.IndexScalarQuantizer(DIM, faiss.ScalarQuantizer.QT_0bit) + _, xb, _ = get_dataset_2(DIM, 0, 100, 0) + storage.train(xb) + storage.add(xb) + with self.assertRaises(RuntimeError): + dnd.init(storage) + + def test_sharded_rounds_equal_rounds(self): + # random data has no equal distances, so the rows are identical. With + # chunks = 3, join() calls on 3 row ranges give the rows of one call. + _, xb, _ = get_dataset_2(DIM, 0, 3000, 0) + nrounds = 4 + for metric, nproc, sample, chunks in ( + (faiss.METRIC_L2, 3, 0, 1), + (faiss.METRIC_INNER_PRODUCT, 4, 6, 3), + ): + with self.subTest(metric=metric, sample=sample, chunks=chunks): + storage, dnd, I, D = init_rows(xb, metric, sample=sample) + I2, D2, changed = sharded_rounds( + xb, I, D, metric, 2 * K, 15, nproc, sample, nrounds, + chunks=chunks, check_remote_ids=sample == 0, + ) + self.assertEqual( + changed, [dnd.round(storage) for _ in range(nrounds)] + ) + np.testing.assert_array_equal( + I2, faiss.vector_to_array(dnd.ids).reshape(-1, 2 * K) + ) + np.testing.assert_array_equal( + D2, faiss.vector_to_array(dnd.dis).reshape(-1, 2 * K) + ) + + def test_sharded_rounds_with_coded_remote_vectors(self): + # join_fp16() and join_sq8() give the rows of join() with the remote + # vectors rounded to float16 or decoded from the 8-bit codes + _, xb, _ = get_dataset_2(DIM, 0, 3000, 0) + _, _, I, D = init_rows(xb) + for coded, decoded in ("float16", "rounded"), ("sq8", "sq8_decoded"): + with self.subTest(remote_vectors=coded): + results = [ + sharded_rounds(xb, I, D, faiss.METRIC_L2, 2 * K, 15, 3, 0, + 3, remote_vectors=coding) + for coding in (decoded, coded) + ] + np.testing.assert_array_equal(results[0][0], results[1][0]) + np.testing.assert_array_equal(results[0][1], results[1][1]) + self.assertEqual(results[0][2], results[1][2]) + + def test_shard_errors_are_catchable(self): + # process 0 of 2 owns the ids 10 and 11; the remote id checks run in + # OpenMP loops and must throw after the loop + d = 4 + bounds = np.array([10, 12, 14], dtype="int64") + x = np.random.RandomState(1).rand(2, d).astype("float32") + D = np.ones((2, 1), dtype="float32") + s = faiss.NNDescentShard() + + def set_rows(I): + I = np.array(I, dtype="int64") + s.set_rows(1, faiss.METRIC_L2, d, 0, 2, faiss.swig_ptr(bounds), + faiss.swig_ptr(x), faiss.swig_ptr(I), + faiss.swig_ptr(D)) + + def set_reverse_edges(target, source): + t = np.array(target, dtype="int64") + src = np.array(source, dtype="int64") + ed = np.ones(len(t), dtype="float32") + en = np.ones(len(t), dtype="uint8") + s.set_reverse_edges(len(t), faiss.swig_ptr(t), + faiss.swig_ptr(src), faiss.swig_ptr(ed), + faiss.swig_ptr(en)) + + for bad in 9, 14: + with self.assertRaisesRegex(RuntimeError, "row id out of range"): + set_rows([[bad], [10]]) + set_rows([[12], [10]]) + ids = np.arange(14, dtype="int64") + out = np.empty((2, 1), dtype="int64") + with self.assertRaisesRegex(RuntimeError, "not in remote_ids"): + s.original_ids(faiss.swig_ptr(ids), faiss.swig_ptr(ids), + faiss.swig_ptr(out)) + with self.assertRaisesRegex(RuntimeError, "source out of range"): + set_reverse_edges([11], [14]) + set_reverse_edges([11], [13]) + np.testing.assert_array_equal( + faiss.vector_to_array(s.remote_ids), [12, 13]) + # the remote ids of the rows only: 13 of the reverse edge is missing + s.set_remote_ids_of_rows() + c, t, cand, od = (faiss.Int64Vector(), faiss.Int64Vector(), + faiss.Int64Vector(), faiss.Float32Vector()) + with self.assertRaisesRegex(RuntimeError, "not in remote_ids"): + s.join(None, None, c, t, cand, od) + s.select_rows(0, 2) + remote_x = np.random.RandomState(2).rand(2, d).astype("float32") + kth = np.full(2, np.inf, dtype="float32") + s.join(faiss.swig_ptr(remote_x), faiss.swig_ptr(kth), c, t, cand, od) + t = np.array([10], dtype="int64") + cand = np.array([14], dtype="int64") + with self.assertRaisesRegex(RuntimeError, "candidate out of range"): + s.insert_candidates(1, faiss.swig_ptr(t), faiss.swig_ptr(cand), + faiss.swig_ptr(D)) + + def test_storage_types(self): + _, xb, _ = get_dataset_2(DIM, 1000, NB, 0) + # a subclass of IndexFlat with another code layout + storage = faiss.IndexFlatL2Panorama(DIM, 4) + storage.add(xb) + dnd = faiss.DeterministicNNDescent() + dnd.K = 2 * K + dnd.build(storage) + self.assertGreater(graph_recall(dnd, xb, faiss.METRIC_L2), 0.97) + # a storage that cannot reconstruct raises in the calling thread + ivf = faiss.IndexIVFFlat(faiss.IndexFlatL2(DIM), DIM, 16) + ivf.train(xb) + ivf.add(xb) + with self.assertRaises(RuntimeError): + dnd.init(ivf) + # round() checks its storage too + flat = faiss.IndexFlatL2(DIM) + flat.add(xb) + dnd.init(flat) + with self.assertRaises(RuntimeError): + dnd.round(ivf) + + def test_sq8_storage(self): + _, xb, _ = get_dataset_2(DIM, 1000, NB, 0) + storage = faiss.IndexScalarQuantizer(DIM, faiss.ScalarQuantizer.QT_8bit) + storage.train(xb) + storage.add(xb) + dnd = faiss.DeterministicNNDescent() + dnd.K = 2 * K + dnd.build(storage) + self.assertGreater(graph_recall(dnd, xb, faiss.METRIC_L2), 0.9) + + def test_index_nndescent(self): + # the index forwards its settings to DeterministicNNDescent + _, xb, _ = get_dataset_2(DIM, 0, NB, 0) + index = faiss.IndexNNDescentFlat(DIM, 2 * K) + index.nndescent.deterministic = True + index.nndescent.iter = 5 + index.add(xb) + storage = faiss.IndexFlatL2(DIM) + storage.add(xb) + dnd = faiss.DeterministicNNDescent() + dnd.K = 2 * K + dnd.max_rounds = index.nndescent.iter + dnd.seed = index.nndescent.random_seed + dnd.build(storage) + np.testing.assert_array_equal( + faiss.vector_to_array(index.nndescent.final_graph), + faiss.vector_to_array(dnd.ids), + ) diff --git a/thirdparty/faiss/tests/test_dino_data.py b/thirdparty/faiss/tests/test_dino_data.py new file mode 100644 index 000000000..58fd1c785 --- /dev/null +++ b/thirdparty/faiss/tests/test_dino_data.py @@ -0,0 +1,286 @@ +# 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. + +"""CPU checks for the mmap-backed DINO loaders; no GPU needed.""" + +import importlib.util +from pathlib import Path +import tempfile +import unittest + +import numpy as np + + +try: + import dino_data as _module +except ImportError: + _path = Path(__file__).resolve().parents[1] / "benchs/e_means/dino_data.py" + _spec = importlib.util.spec_from_file_location("dino_data", _path) + _module = importlib.util.module_from_spec(_spec) + _spec.loader.exec_module(_module) +DinoBvecs = _module.DinoBvecs +DinoQueries = _module.DinoQueries +DinoTrainset = _module.DinoTrainset + + +class TestDinoBvecs(unittest.TestCase): + def test_import_without_optional_torch_or_faiss(self): + import builtins + + original_import = builtins.__import__ + + def data_import(name, *args, **kwargs): + if name.split(".")[0] in ("torch", "faiss", "triton", "cutlass", "quack"): + raise AssertionError("data loader imported " + name) + return original_import(name, *args, **kwargs) + + from unittest import mock + with mock.patch.object(builtins, "__import__", side_effect=data_import): + spec = importlib.util.spec_from_file_location("dino_data_cpu", _module.__file__) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + self.assertNotIn("Emeans", vars(module)) + self.assertNotIn("torch", vars(module)) + self.assertNotIn("dist", vars(module)) + + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.chunks = self.root / "chunked_base_10B" + self.chunks.mkdir() + self.data = np.arange(65, dtype=np.uint8).reshape(13, 5) + self.write("00.bvecs", self.data[:4]) + self.write("01.bvecs", self.data[4:]) + + def write(self, name, rows): + with (self.chunks / name).open("wb") as stream: + for row in rows: + stream.write(len(row).to_bytes(4, "little", signed=True)) + stream.write(row.tobytes()) + + def test_boundary_prefix_and_owned_output(self): + source = DinoBvecs(self.root, n=11) + self.assertEqual(source.n, 11) + self.assertEqual(source.ends[-1], 13) + self.assertEqual(len(source.maps), 2) + self.assertTrue(all(isinstance(mapping, np.memmap) for mapping in source.maps)) + self.assertTrue(all(not mapping.flags.writeable for mapping in source.maps)) + np.testing.assert_array_equal(source.read(2, 7), self.data[2:7]) + output = source.read(2, 7) + self.assertTrue(output.flags.owndata) + output.fill(0) + np.testing.assert_array_equal(source.read(2, 7), self.data[2:7]) + self.assertEqual(source.read(11, 11).shape, (0, 5)) + with self.assertRaises(IndexError): + source.read(10, 12) + + def test_contiguous_reads_cover_prefix_without_aliasing(self): + source = DinoBvecs(self.root, n=13) + parts = [source.read(a, min(a + 3, source.n)) for a in range(0, source.n, 3)] + self.assertEqual([len(part) for part in parts], [3, 3, 3, 3, 1]) + self.assertTrue(all(part.flags.owndata for part in parts)) + np.testing.assert_array_equal(np.concatenate(parts), self.data) + parts[1].fill(0) + np.testing.assert_array_equal(source.read(3, 6), self.data[3:6]) + + def test_malformed_file_and_first_dimension(self): + (self.chunks / "01.bvecs").write_bytes(b"\x05\x00") + with self.assertRaisesRegex(ValueError, "incomplete"): + DinoBvecs(self.root, n=13) + (self.chunks / "01.bvecs").write_bytes(b"\x05\x00\x00\x00\x01") + with self.assertRaisesRegex(ValueError, "incomplete"): + DinoBvecs(self.root, n=13) + (self.chunks / "01.bvecs").write_bytes(b"\x05\x00\x00\x00\x01\x02\x03\x04\x05") + # A whole row is still valid; the requested population exceeds capacity. + with self.assertRaisesRegex(ValueError, "corpus contains"): + DinoBvecs(self.root, n=13) + with (self.chunks / "00.bvecs").open("r+b") as stream: + stream.write((0).to_bytes(4, "little", signed=True)) + with self.assertRaisesRegex(ValueError, "invalid bvecs dimension"): + DinoBvecs(self.root, n=4) + + def test_population_and_range_validation(self): + for n in (0, -1, 14): + with self.assertRaises(ValueError): + DinoBvecs(self.root, n=n) + source = DinoBvecs(self.root, n=np.int64(13)) + for begin, end in ((-1, 1), (2, 1), (0, 14)): + with self.assertRaises(IndexError): + source.read(begin, end) + + def test_only_required_prefix_is_mapped_and_validated(self): + source = DinoBvecs(self.root, n=4) + self.assertEqual(len(source.maps), 1) + self.assertEqual(source.ends[-1], 4) + del source + # Current bounded loader maps only chunks needed by the requested prefix. + (self.chunks / "02.bvecs").write_bytes(b"\x05\x00") + np.testing.assert_array_equal(DinoBvecs(self.root, n=4).read(0, 4), self.data[:4]) + with self.assertRaisesRegex(ValueError, "incomplete"): + DinoBvecs(self.root, n=14) + (self.chunks / "01.bvecs").write_bytes(b"\x05\x00") + with self.assertRaisesRegex(ValueError, "incomplete"): + DinoBvecs(self.root, n=5) + + @unittest.skipUnless(importlib.util.find_spec("torch"), "Torch required") + def test_read_and_resident_staging_boundary(self): + import torch + + rows = np.arange(65539 * 5, dtype=np.uint32).astype(np.uint8).reshape(-1, 5) + self.write("00.bvecs", rows) + source = DinoBvecs(self.root, n=len(rows) + 9) + np.testing.assert_array_equal(source.read(0, len(rows)), rows) + expected = np.concatenate((rows[-3:], self.data[4:7])) + np.testing.assert_array_equal(source.read(len(rows) - 3, len(rows) + 3), expected) + resident = source.resident(1, source.n - 1, "cpu") + self.assertEqual(resident.dtype, torch.float32) + self.assertEqual(resident.device.type, "cpu") + expected = np.concatenate((rows[1:], self.data[4:-1])).astype(np.float32) + np.testing.assert_array_equal(resident.numpy(), expected) + + def test_unfinished_download_rejects_required_prefix(self): + marker = self.chunks / "01.bvecs.parts.json" + marker.write_text("{}") + # Preallocated size and valid headers do not establish completion. + with self.assertRaisesRegex(ValueError, "unfinished"): + DinoBvecs(self.root, n=13) + with self.assertRaisesRegex(ValueError, "unfinished"): + DinoBvecs(self.root, n=5) + prefix = DinoBvecs(self.root, n=4) + self.assertEqual(len(prefix.maps), 1) + np.testing.assert_array_equal(prefix.read(0, 4), self.data[:4]) + marker.unlink() + # Completion is a constructor gate; original mapped files stay immutable. + (self.chunks / "00.bvecs.parts.json").write_text("{}") + with self.assertRaisesRegex(ValueError, "unfinished"): + DinoBvecs(self.root, n=4) + + def test_numbered_chunk_gap_is_not_skipped(self): + (self.chunks / "00.bvecs").rename(self.chunks / "chunk_0000.bvecs") + (self.chunks / "01.bvecs").rename(self.chunks / "chunk_0002.bvecs") + with self.assertRaisesRegex(ValueError, "missing chunk"): + DinoBvecs(self.root, n=13) + with self.assertRaisesRegex(ValueError, "missing chunk"): + DinoBvecs(self.root, n=5) + source = DinoBvecs(self.root, n=4) + np.testing.assert_array_equal(source.read(0, 4), self.data[:4]) + del source + (self.chunks / "chunk_0000.bvecs").rename(self.chunks / "chunk_0001.bvecs") + with self.assertRaisesRegex(ValueError, "missing chunk"): + DinoBvecs(self.root, n=4) + + def write_queries(self, rows): + packed = np.empty((len(rows), rows.shape[1] + 4), dtype=np.uint8) + packed[:, :4] = np.frombuffer(rows.shape[1].to_bytes(4, "little"), dtype=np.uint8) + packed[:, 4:] = rows + path = self.root / "queries_clean.bvecs" + packed.tofile(path) + return path, packed + + @unittest.skipUnless(importlib.util.find_spec("torch"), "Torch required") + def test_query_batches_transform_tails_and_owned_storage(self): + import torch + + self.write_queries(self.data) + queries = DinoQueries(self.root, d=5, n=len(self.data)) + mean = torch.arange(5, dtype=torch.float32) + indices = np.random.RandomState(1234).permutation(len(self.data))[6:] + expected = (torch.from_numpy(self.data[indices]).float() - mean) / 2.0 + self.assertEqual(queries.n, 7) + for batch_size in (4, 7, 20): + parts = list(queries.batches(mean, 2.0, batch_size)) + self.assertEqual([len(x) for x in parts], + [min(batch_size, len(expected) - a) + for a in range(0, len(expected), batch_size)]) + self.assertTrue(all(x.dtype is torch.float32 for x in parts)) + torch.testing.assert_close(torch.cat(parts), expected, rtol=0, atol=0) + parts[0].fill_(-1) + torch.testing.assert_close(torch.cat(list(queries.batches(mean, 2.0, batch_size))), + expected, rtol=0, atol=0) + with self.assertRaisesRegex(ValueError, "positive"): + list(queries.batches(mean, 2.0, 0)) + + def test_query_file_size_and_every_header_validation(self): + with self.assertRaises(FileNotFoundError): + DinoQueries(self.root, d=5, n=len(self.data)) + path, packed = self.write_queries(self.data) + with self.assertRaisesRegex(ValueError, "expected"): + DinoQueries(self.root, d=5, n=len(self.data) + 1) + packed[-1, :4] = np.frombuffer((4).to_bytes(4, "little"), dtype=np.uint8) + packed.tofile(path) + with self.assertRaisesRegex(ValueError, "headers"): + DinoQueries(self.root, d=5, n=len(self.data)) + + +class TestDinoTrainset(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.path = self.root / "train_queries_99M.bvecs" + self.data = np.arange(65, dtype=np.uint8).reshape(13, 5) + self.packed = np.empty((13, 9), dtype=np.uint8) + self.packed[:, :4] = np.frombuffer((5).to_bytes(4, "little"), dtype=np.uint8) + self.packed[:, 4:] = self.data + self.packed.tofile(self.path) + + @unittest.skipUnless(importlib.util.find_spec("torch"), "Torch required") + def test_prefix_transformed_batches_tails_and_owned_storage(self): + import torch + + source = DinoTrainset(self.root, n=11) + self.assertIsInstance(source.vectors, np.memmap) + self.assertFalse(source.vectors.flags.writeable) + mean = torch.arange(5, dtype=torch.float32) + expected = (torch.from_numpy(self.data[:11]).float() - mean) / 2 + for size in (4, 11, 20): + parts = list(source.batches(mean, 2, size)) + self.assertEqual([len(x) for x in parts], + [min(size, 11 - begin) for begin in range(0, 11, size)]) + torch.testing.assert_close(torch.cat(parts), expected, rtol=0, atol=0) + parts[0].fill_(-1) + torch.testing.assert_close(torch.cat(list(source.batches(mean, 2, size))), expected, rtol=0, atol=0) + with self.assertRaisesRegex(ValueError, "positive"): + list(source.batches(mean, 2, 0)) + + @unittest.skipUnless(importlib.util.find_spec("torch"), "Torch required") + def test_population_size_and_required_headers(self): + import torch + + for n in (0, -1, 14): + with self.assertRaises(ValueError): + DinoTrainset(self.root, n) + self.path.write_bytes(self.path.read_bytes()[:-1]) + with self.assertRaisesRegex(ValueError, "incomplete"): + DinoTrainset(self.root, 4) + self.packed.tofile(self.path) + self.packed[7, :4] = np.frombuffer((4).to_bytes(4, "little"), dtype=np.uint8) + self.packed.tofile(self.path) + with self.assertRaisesRegex(ValueError, "headers"): + list(DinoTrainset(self.root, 8).batches(torch.zeros(5), 1, 4)) + self.packed[0, :4] = 0 + self.packed.tofile(self.path) + with self.assertRaisesRegex(ValueError, "dimension"): + DinoTrainset(self.root, 4) + + @unittest.skipUnless(importlib.util.find_spec("torch"), "Torch required") + def test_bounded_row_norms_preserve_values_and_reject_zero_chunk(self): + import torch + + rows = torch.from_numpy(self.data) + for dtype in (torch.uint8, torch.float32, torch.bfloat16): + values = rows.to(dtype) + expected = values.float().square().sum(1) + for size in (None, 1, 4, 20): + actual = _module._squared_row_norms(values, chunk_rows=size) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + with self.assertRaisesRegex(ValueError, "positive"): + _module._squared_row_norms(rows, chunk_rows=0) + self.assertEqual(_module._squared_row_norms(rows[:0]).shape, (0,)) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/test_disable_pq_sdc_tables.cpp b/thirdparty/faiss/tests/test_disable_pq_sdc_tables.cpp index 172957725..c33f54785 100644 --- a/thirdparty/faiss/tests/test_disable_pq_sdc_tables.cpp +++ b/thirdparty/faiss/tests/test_disable_pq_sdc_tables.cpp @@ -26,7 +26,6 @@ TEST(IO, TestReadHNSWPQ_whenSDCDisabledFlagPassed_thenDisableSDCTable) { "/tmp/faiss_TestReadHNSWPQ" + std::to_string(int(dist(mt))); Tempfilename index_filename(&temp_file_mutex, temp_file_name); - // Create a HNSW index with PQ encoding int d = 32, n = 256; std::default_random_engine rng(123); std::uniform_real_distribution u(0, 100); @@ -35,7 +34,6 @@ TEST(IO, TestReadHNSWPQ_whenSDCDisabledFlagPassed_thenDisableSDCTable) { vectors[i] = u(rng); } - // Build the index and write it to the temp file { std::unique_ptr index_writer( faiss::index_factory(d, "HNSW8,PQ4np", faiss::METRIC_L2)); @@ -45,8 +43,6 @@ TEST(IO, TestReadHNSWPQ_whenSDCDisabledFlagPassed_thenDisableSDCTable) { faiss::write_index(index_writer.get(), index_filename.c_str()); } - // Load index from disk. Confirm that the sdc table is equal to 0 when - // disable sdc is set { std::unique_ptr index_reader_read_write( dynamic_cast( diff --git a/thirdparty/faiss/tests/test_distances_dispatch.cpp b/thirdparty/faiss/tests/test_distances_dispatch.cpp index 91e4911ab..dac94f650 100644 --- a/thirdparty/faiss/tests/test_distances_dispatch.cpp +++ b/thirdparty/faiss/tests/test_distances_dispatch.cpp @@ -5,40 +5,21 @@ * LICENSE file in the root directory of this source tree. */ -// Per-SIMD-level cross-equivalence tests for the templated distance -// functions in faiss/utils/distances.h: -// fvec_L1, fvec_Linf, fvec_L2sqr_batch_4, fvec_inner_product_batch_4, -// fvec_L2sqr_ny_transposed, fvec_L2sqr_ny_nearest. -// -// IndexFlat exercises these transitively via search, but transitive -// coverage can mask tail-handling bugs. This test runs each function at -// every SIMDConfig-available level and asserts equivalence against the -// SIMDLevel::NONE reference. Sweeps dimensions {1, 3, 7, 8, 9, 15, 16, -// 17, 31, 32, 33, 64} so non-multiple-of-8 / non-multiple-of-16 dims -// exercise the tail paths. -// -// Tolerances: -// * Functions returning an integer (fvec_L2sqr_ny_nearest's chosen -// index) are compared bit-exactly via EXPECT_EQ. -// * Functions returning a single float (fvec_L1, fvec_Linf) accumulate -// over d terms; rounding-order differences across SIMD widths can -// reach a few ULPs. Comparison uses an absolute tolerance scaled by -// d to bound worst-case FP-reassociation drift. -// * Functions returning multiple floats (the batch_4 variants and -// fvec_L2sqr_ny_transposed) use the same scaled tolerance per element. -// -// NaN/Inf inputs are out of scope: these paths are not exercised by -// random uniform input in [-1, 1]. +// Each function at every available SIMD level vs SIMDLevel::NONE. Dims cover +// non-multiple-of-8/16 tails, which IndexFlat-level tests can mask. #include #include -#include +#include #include #include +#include #include +#include #include +#include using namespace faiss; @@ -51,7 +32,6 @@ class SIMDLevelGuard { SIMDConfig::set_level(prev_); } - private: SIMDLevel prev_; }; @@ -74,6 +54,26 @@ std::vector available_levels() { return out; } +std::vector available_fp16_levels() { + static const std::vector all = { + SIMDLevel::NONE, + SIMDLevel::AVX2, + SIMDLevel::AVX512, + SIMDLevel::AVX512_SPR, + SIMDLevel::AVX512_VPOPCNT, + SIMDLevel::ARM_NEON, + SIMDLevel::ARM_SVE, + SIMDLevel::RISCV_RVV, + }; + std::vector out; + for (auto lv : all) { + if (SIMDConfig::is_simd_level_available(lv)) { + out.push_back(lv); + } + } + return out; +} + std::vector rand_vec(size_t n, uint32_t seed) { std::mt19937 rng(seed); std::uniform_real_distribution u(-1.f, 1.f); @@ -84,7 +84,6 @@ std::vector rand_vec(size_t n, uint32_t seed) { return v; } -// dimensions covering aligned (multiple of 8 / 16) and tail cases. const std::vector kDims = {1, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 64}; // Tolerance per accumulator term. With inputs in [-1, 1], each squared term @@ -95,8 +94,7 @@ const std::vector kDims = {1, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 64}; constexpr float kPerTermEps = 1e-6f; float tol_for_d(size_t d) { - // Floor at 1e-6 so d=1 still has a sensible (non-zero) tolerance. - return std::max(static_cast(d) * kPerTermEps, 1e-6f); + return d * kPerTermEps; } #define SKIP_IF_SINGLE_LEVEL(levels) \ @@ -116,8 +114,6 @@ void check_floats_at_levels( } SIMDConfig::set_level(lv); auto got = fn(); - ASSERT_EQ(ref.size(), got.size()) - << "size mismatch at level " << static_cast(lv); for (size_t i = 0; i < ref.size(); ++i) { EXPECT_NEAR(ref[i], got[i], tol) << "diverged at level " << static_cast(lv) << " idx " @@ -126,8 +122,7 @@ void check_floats_at_levels( } } -// For functions returning an integer index (cast to size_t). Bit-exact -// comparison: a correct dispatch must return the same chosen index. +// For functions returning an integer index (cast to size_t). template void check_index_at_levels(Fn fn, const std::vector& levels) { auto ref = (SIMDConfig::set_level(SIMDLevel::NONE), fn()); @@ -144,6 +139,118 @@ void check_index_at_levels(Fn fn, const std::vector& levels) { } // namespace +TEST(DistancesDispatch, Fp16ConversionTails_AllLevels) { + SIMDLevelGuard guard; + auto levels = available_fp16_levels(); + constexpr uint16_t kValues[] = { + 0x0000, + 0x8000, + 0x3c00, + 0xc000, + 0x3555, + 0x0400, + 0x03ff, + 0x7bff, + 0x0001, + }; + std::vector sizes; + for (size_t n = 1; n <= 31; ++n) { + sizes.push_back(n); + } + sizes.push_back((size_t(1) << 16) + 17); + + for (size_t n : sizes) { + std::vector input(n); + std::vector expected(n); + for (size_t i = 0; i < n; ++i) { + input[i] = kValues[i % (sizeof(kValues) / sizeof(kValues[0]))]; + expected[i] = decode_fp16(input[i]); + } + for (auto lv : levels) { + SIMDConfig::set_level(lv); + std::vector actual(n); + fp16_to_fp32(n, input.data(), actual.data()); + EXPECT_EQ( + 0, + std::memcmp( + expected.data(), actual.data(), n * sizeof(float))) + << "diverged at level " << static_cast(lv) << " size " + << n; + } + } +} + +TEST(DistancesDispatch, Fp16CentroidMaddTails_AllLevels) { + SIMDLevelGuard guard; + auto levels = available_fp16_levels(); + constexpr size_t n = 3; + constexpr int64_t kUnweightedAssign[n] = {0, 1, 0}; + constexpr int64_t kWeightedAssign[n] = {0, 0, 0}; + constexpr float kWeights[n] = {0.1f, 0.3f, 0.7f}; + constexpr float kValues[] = {0.0f, 0.5f, -1.0f, 2.0f, -0.25f, 4.0f, 0.125f}; + + for (size_t d = 1; d <= 31; ++d) { + std::vector input(n * d); + for (size_t i = 0; i < input.size(); ++i) { + input[i] = encode_fp16( + kValues[i % (sizeof(kValues) / sizeof(kValues[0]))]); + } + + auto check_case = [&](size_t k, + const int64_t* assign, + const float* weights, + const char* case_name) { + std::vector expected_hassign(k, 0.0f); + std::vector expected(k * d, 0.0f); + for (size_t i = 0; i < n; ++i) { + const size_t ci = static_cast(assign[i]); + const float weight = weights ? weights[i] : 1.0f; + expected_hassign[ci] += weight; + for (size_t j = 0; j < d; ++j) { + expected[ci * d + j] += + decode_fp16(input[i * d + j]) * weight; + } + } + for (size_t ci = 0; ci < k; ++ci) { + for (size_t j = 0; j < d; ++j) { + expected[ci * d + j] /= expected_hassign[ci]; + } + } + + for (auto lv : levels) { + SIMDConfig::set_level(lv); + std::vector hassign(k, 0.0f); + std::vector actual(k * d); + detail::compute_centroids_fp16( + d, + k, + n, + 0, + input.data(), + assign, + weights, + hassign.data(), + actual.data()); + for (size_t ci = 0; ci < k; ++ci) { + EXPECT_NEAR(expected_hassign[ci], hassign[ci], tol_for_d(d)) + << case_name << " histogram diverged at level " + << static_cast(lv) << " dimension " << d + << " centroid " << ci; + } + for (size_t i = 0; i < actual.size(); ++i) { + EXPECT_NEAR(expected[i], actual[i], tol_for_d(d)) + << case_name << " centroid diverged at level " + << static_cast(lv) << " dimension " << d + << " index " << i; + } + } + }; + + check_case(2, kUnweightedAssign, nullptr, "unweighted"); + check_case(1, kWeightedAssign, kWeights, "weighted"); + } +} + TEST(DistancesDispatch, FvecL1_AllLevels) { SIMDLevelGuard guard; auto levels = available_levels(); @@ -245,15 +352,11 @@ TEST(DistancesDispatch, FvecL2sqrNyTransposed_AllLevels) { SKIP_IF_SINGLE_LEVEL(levels); constexpr size_t ny = 13; for (size_t d : kDims) { - // d_offset is the stride between consecutive components in the - // transposed y layout; pick > ny to exercise non-trivial striding - // and to cover all (i, k) accesses (i in [0, ny), k in [0, d)). + // y[i + k * d_offset] is component k of vector i; d_offset > ny + // exercises striding. const size_t d_offset = ny + 5; auto x = rand_vec(d, 30); - // y[i + k * d_offset] is the k-th component of the i-th vector - // (per fvec_L2sqr_ny_transposed's contract). Required size is - // (d - 1) * d_offset + ny. - auto y = rand_vec((d == 0 ? 0 : (d - 1) * d_offset) + ny, 31); + auto y = rand_vec((d - 1) * d_offset + ny, 31); std::vector y_sqlen(ny); for (size_t i = 0; i < ny; ++i) { float s = 0; @@ -291,9 +394,7 @@ TEST(DistancesDispatch, FvecL2sqrNyNearest_AllLevels) { auto y = rand_vec(d * ny, 41); check_index_at_levels( [&]() { - // distances_tmp_buffer is an internal scratch; only the - // returned index is part of the public contract. Some - // SIMD impls don't write into the buffer. + // only the returned index is part of the contract std::vector tmp(ny); return fvec_L2sqr_ny_nearest( tmp.data(), x.data(), y.data(), d, ny); diff --git a/thirdparty/faiss/tests/test_distances_simd.cpp b/thirdparty/faiss/tests/test_distances_simd.cpp index 4333e5c17..66a259fa0 100644 --- a/thirdparty/faiss/tests/test_distances_simd.cpp +++ b/thirdparty/faiss/tests/test_distances_simd.cpp @@ -12,9 +12,9 @@ #include #include +#include #include -// reference implementations static void fvec_inner_products_ny_ref( float* ip, const float* x, @@ -39,7 +39,6 @@ static void fvec_L2sqr_ny_ref( } } -// test templated versions of fvec_L2sqr_ny TEST(TestFvecL2sqrNy, D2) { // we're using int values in order to get 100% accurate // results with floats. @@ -76,7 +75,6 @@ TEST(TestFvecL2sqrNy, D2) { } } -// fvec_inner_products_ny TEST(TestFvecInnerProductsNy, D2) { // we're using int values in order to get 100% accurate // results with floats. @@ -119,8 +117,7 @@ TEST(TestFvecL2sqr, distances_L2_squared_y_transposed) { // bit implementations, so they leave no partial-predicate tail; 5 and 11 // do. for (const auto ny : {5, 8, 11, 16, 32}) { - for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 16}) { - // initialize inputs + for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 12, 16}) { std::vector x(d); float x_sqlen = 0; for (size_t i = 0; i < x.size(); i++) { @@ -136,7 +133,6 @@ TEST(TestFvecL2sqr, distances_L2_squared_y_transposed) { } } - // perform function std::vector true_distances(ny, 0); for (int i = 0; i < ny; i++) { float dp = 0; @@ -172,8 +168,7 @@ TEST(TestFvecL2sqr, nearest_L2_squared_y_transposed) { // bit implementations, so they leave no partial-predicate tail; 5 and 11 // do. for (const auto ny : {5, 8, 11, 16, 32}) { - for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 16}) { - // initialize inputs + for (const auto d : {1, 2, 3, 4, 5, 6, 7, 8, 12, 16}) { std::vector x(d); float x_sqlen = 0; for (size_t i = 0; i < x.size(); i++) { @@ -189,7 +184,6 @@ TEST(TestFvecL2sqr, nearest_L2_squared_y_transposed) { } } - // get distances std::vector distances(ny, 0); for (int i = 0; i < ny; i++) { float dp = 0; @@ -198,7 +192,6 @@ TEST(TestFvecL2sqr, nearest_L2_squared_y_transposed) { } distances[i] = x_sqlen + y_sqlens[i] - 2 * dp; } - // find nearest size_t true_nearest_idx = 0; float min_dis = HUGE_VALF; for (int i = 0; i < ny; i++) { @@ -230,7 +223,7 @@ TEST(TestFvecL1, manhattan_distance) { std::default_random_engine rng(123); std::uniform_int_distribution uniform(0, 32); - // modulo 8 results - 16 is to repeat the while loop in the function + // every n % 8 tail, plus 16 for a second full block for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) { std::vector x(nrows); std::vector y(nrows); @@ -253,7 +246,7 @@ TEST(TestFvecLinf, chebyshev_distance) { std::default_random_engine rng(123); std::uniform_int_distribution uniform(0, 32); - // modulo 8 results - 16 is to repeat the while loop in the function + // every n % 8 tail, plus 16 for a second full block for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) { std::vector x(nrows); std::vector y(nrows); @@ -276,7 +269,7 @@ TEST(TestFvecMadd, multiple_add) { std::default_random_engine rng(123); std::uniform_int_distribution uniform(0, 32); - // modulo 8 results - 16 is to repeat the while loop in the function + // every n % 8 tail, plus 16 for a second full block for (const auto nrows : {8, 9, 10, 11, 12, 13, 14, 15, 16}) { std::vector a(nrows); std::vector b(nrows); @@ -296,6 +289,36 @@ TEST(TestFvecMadd, multiple_add) { } } +TEST(TestFvecMaskedSum, masked_sum) { + // ints instead of floats for 100% accuracy + std::default_random_engine rng(123); + std::uniform_int_distribution uniform(0, 32); + + // 0, 1 and 2 full 16-float blocks, each with a tail; the random bits past + // d in the last byte must be ignored + for (const size_t d : {7, 31, 33}) { + std::vector bits((d + 7) / 8); + for (auto& b : bits) { + b = rng(); + } + std::vector x(d); + float expected = 0; + for (size_t j = 0; j < d; j++) { + x[j] = uniform(rng); + if ((bits[j / 8] >> (j % 8)) & 1) { + expected += x[j]; + } + } + + const float actual = faiss::with_simd_level([&]() { + return faiss::fvec_masked_sum< + faiss::simd512_level_selector::value>( + x.data(), bits.data(), d); + }); + ASSERT_EQ(actual, expected) << "d = " << d; + } +} + TEST(TestFvecAdd, add_array) { // ints instead of floats for 100% accuracy std::default_random_engine rng(123); @@ -327,7 +350,7 @@ TEST(TestFvecAdd, add_value) { for (const auto nrows : {1, 2, 5, 10, 15, 20, 25}) { std::vector a(nrows); - const float b = uniform(rng); // value to add + const float b = uniform(rng); std::vector true_distances(nrows); for (size_t i = 0; i < a.size(); i++) { a[i] = uniform(rng); diff --git a/thirdparty/faiss/tests/test_documentation.py b/thirdparty/faiss/tests/test_documentation.py deleted file mode 100644 index bf0b8ef81..000000000 --- a/thirdparty/faiss/tests/test_documentation.py +++ /dev/null @@ -1,15 +0,0 @@ -# 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 unittest -import faiss - - -class TestDocumentation(unittest.TestCase): - - def test_io_error(self): - index = faiss.IndexFlatL2(32) - - self.assertTrue("Adds vectors to the index" in index.add.__doc__) diff --git a/thirdparty/faiss/tests/test_e_means.py b/thirdparty/faiss/tests/test_e_means.py new file mode 100644 index 000000000..6e0c36245 --- /dev/null +++ b/thirdparty/faiss/tests/test_e_means.py @@ -0,0 +1,634 @@ +# 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 contextlib +import io +import unittest +import unittest.mock +import subprocess +import sys +import faiss.contrib.e_means + +import numpy as np + +from faiss.contrib.e_means import NumpyEmeans as Emeans +from faiss.contrib.e_means.base import ( + _resolve_batch_law, + _resolve_unused_threshold, +) +from faiss.contrib.e_means.e_means import ( + _add_rows_at, + _epoch_rows, + _epoch_seed, + _format_passes, + _resolve_recipe, + _scheduled_alpha, + _step_law, +) +from e_means_test_utils import EmeansReferenceContracts + + +class TestEmeansVerbose(unittest.TestCase): + def _capture(self, run): + out = io.StringIO() + with contextlib.redirect_stdout(out): + run() + return out.getvalue() + + def test_verbose_cites_and_reports_epochs_and_iterations(self): + x = np.random.RandomState(0).rand(2000, 8).astype("float32") + model = Emeans(8, 16, nepochs=1.4, verbose=True) + lines = self._capture(lambda: model.train(x)).splitlines() + total = model.recipe["total_steps"] + first = model.recipe["epoch_steps"][0] + self.assertEqual(lines[0], "This is e-means. If you use our work or find it " + "useful, please cite the e-means paper (Bessa et al., " + "see faiss/contrib/e_means/README.md).") + self.assertRegex(lines[1], r"^Clustering 2000 points in 8D to 16 clusters, " + r"1\.4 epochs \(batch \d+, alpha0 " + r"\S+, quality batch law, auto for d <= 16\)$") + self.assertTrue(lines[2].startswith(" Preprocessing in ")) + self.assertIn("assignment: faiss on CPU", lines[2]) + self.assertTrue(lines[3].startswith( + " Epoch 0.4 / 1.4 (800 of 2000 rows), iteration %d / %d (" % (first, total))) + self.assertTrue(lines[4].startswith( + " Epoch 1.4 / 1.4, iteration %d / %d (" % (total, total))) + for line in lines[3:5]: + self.assertRegex(line, r"\(\d+\.\d\d s\): objective=\S+$") + self.assertEqual(len(lines), 5) + + def test_caller_driven_header_waits_for_the_first_batch(self): + x = np.random.RandomState(0).rand(2000, 8).astype("float32") + model = Emeans(8, 16, nepochs=1, verbose=True) + self.assertEqual(self._capture(lambda: model.begin(len(x), x[:16].copy())), "") + + def epoch(): + batch = model.recipe["batch_size"] + for begin in range(0, len(x), batch): + model.update(model.accumulate(x[begin:begin + batch])) + model.end_epoch() + model.finalize() + lines = self._capture(epoch).splitlines() + self.assertEqual(sum(line.startswith("Clustering ") for line in lines), 1) + self.assertFalse(any("Preprocessing" in line for line in lines)) + self.assertTrue(lines[-1].startswith(" Epoch 1 / 1, iteration ")) + + def test_silent_without_verbose(self): + x = np.random.RandomState(0).rand(2000, 8).astype("float32") + self.assertEqual( + self._capture(lambda: Emeans(8, 16, nepochs=1.4).train(x)), "" + ) + + def test_closed_stdout_never_stops_training(self): + x = np.random.RandomState(0).rand(2000, 8).astype("float32") + closed = io.StringIO() + closed.close() + with contextlib.redirect_stdout(closed): + centroids, _ = Emeans(8, 16, nepochs=1.4, verbose=True).train(x) + self.assertEqual(centroids.shape, (16, 8)) + + def test_pass_counts_keep_small_fractions(self): + for value, text in ((25, "25"), (1.4, "1.4"), (0.004, "0.004"), + (1.001, "1.001"), (2.999, "2.999")): + self.assertEqual(_format_passes(value), text) + + +class TestEmeansRecipe(unittest.TestCase): + def test_fractional_epoch_rounding(self): + self.assertEqual( + _epoch_rows(10_000_000_000, 1.9999999995), + [9_999_999_995, 10_000_000_000], + ) + self.assertEqual(_epoch_rows(3, 1.5), [2, 3]) + self.assertEqual(_epoch_rows(5, 1.5), [2, 5]) + self.assertEqual(_epoch_rows(3, 1.01), [3]) + + def test_reference_values(self): + cases = [ + (1_000_000, 16_384, 25, "throughput", 262_144, 1.0), + (1_000_000, 16_384, 25, "quality", 32_768, 0.1545388281304627), + (100_000_000, 262_144, 25, "throughput", 33_554_432, 1.0), + ( + 100_000_000, + 262_144, + 25, + "quality", + 4_194_304, + 0.42718555053293517, + ), + ] + for case in cases: + n, k, nepochs, batch_law, expected_batch, expected_alpha = case + with self.subTest(n=n, k=k, batch_law=batch_law): + batch, alpha = _resolve_recipe( + n, k, nepochs, batch_law, None, None + ) + self.assertEqual(batch, expected_batch) + self.assertAlmostEqual(alpha, expected_alpha) + + def test_batch_size_alone_takes_the_step_law(self): + batch, alpha = _resolve_recipe(1_000_000, 16_384, 3, "throughput", + 8_192, None) + self.assertEqual(batch, 8_192) + self.assertEqual(alpha, _step_law(1_000_000, 16_384, 3, 8_192)) + x = np.arange(64, dtype="float32").reshape(32, 2) + km = Emeans(2, 4, nepochs=1, batch_size=8) + km.train(x) + self.assertEqual(km.recipe["name"], "manual_batch") + self.assertIsNone(km.recipe["batch_law"]) + self.assertEqual(km.recipe["alpha0_source"], "step_law") + self.assertEqual(km.recipe["alpha0"], _step_law(32, 4, 1, 8)) + + def test_auto_batch_law(self): + # (batch_law, d) -> (resolved law, reason) + cases = [ + (("auto", 2), ("quality", "d <= 16")), + (("auto", 16), ("quality", "d <= 16")), + (("auto", 17), ("throughput", "d > 16")), + (("auto", 1024), ("throughput", "d > 16")), + (("throughput", 2), ("throughput", "requested")), + (("quality", 128), ("quality", "requested")), + ] + for args, expected in cases: + with self.subTest(args=args): + self.assertEqual(_resolve_batch_law(*args), expected) + + def test_auto_unused_threshold(self): + self.assertEqual(_resolve_unused_threshold(None, 1), 0.0) + self.assertEqual(_resolve_unused_threshold(None, 2), 0.0) + self.assertEqual(_resolve_unused_threshold(None, 3), 0.1) + self.assertEqual(_resolve_unused_threshold(0.05, 2), 0.05) + self.assertEqual(_resolve_unused_threshold(0, 64), 0.0) + with self.assertRaises(ValueError): + Emeans(8, 4, unused_threshold=-0.1) + + def test_recipe_records_resolved_defaults(self): + x = np.random.RandomState(0).rand(2048, 2).astype("float32") + km = Emeans(2, 4, nepochs=2) + km.train(x) + self.assertEqual(km.recipe["batch_law"], "quality") + self.assertEqual(km.recipe["batch_law_requested"], "auto") + self.assertEqual(km.recipe["batch_law_reason"], "d <= 16") + self.assertIsNone(km.recipe["unused_threshold"]) + quality, _ = _resolve_recipe(2048, 4, 2, "quality", None, None) + self.assertEqual(km.recipe["batch_size"], quality) + + x = np.random.RandomState(0).rand(2048, 32).astype("float32") + km = Emeans(32, 4, nepochs=2, batch_law="throughput") + km.train(x) + self.assertEqual(km.recipe["batch_law"], "throughput") + self.assertEqual(km.recipe["batch_law_reason"], "requested") + self.assertIsNone(km.recipe["unused_threshold"]) + throughput, _ = _resolve_recipe(2048, 4, 2, "throughput", None, None) + self.assertEqual(km.recipe["batch_size"], throughput) + + def test_default_nepochs(self): + km = Emeans(2, 4) + self.assertEqual(km.nepochs, 5) + km.train(np.arange(64, dtype="float32").reshape(32, 2)) + self.assertEqual(len(km.recipe["epoch_rows"]), 5) + + def test_derived_recipe_metadata(self): + x = np.arange(124, dtype="float32").reshape(31, 4) + km = Emeans(4, 3, nepochs=3, assignment_chunk_size=7) + + km.train(x) + + self.assertEqual(km.recipe["name"], "canonical_v1") + batch_size = km.recipe["batch_size"] + steps_per_pass = (len(x) + batch_size - 1) // batch_size + self.assertEqual(km.recipe["steps_per_pass"], steps_per_pass) + self.assertEqual(km.recipe["total_steps"], 3 * steps_per_pass) + self.assertEqual(km.recipe["tail_policy"], "keep") + self.assertEqual(km.recipe["assignment_chunk_size"], 7) + + def test_schedule_uses_logical_steps(self): + alpha0 = 0.4 + self.assertEqual(_scheduled_alpha(alpha0, 0, 10), alpha0) + self.assertAlmostEqual(_scheduled_alpha(alpha0, 10, 10), 0.04) + last = _scheduled_alpha(alpha0, 9, 10) + self.assertGreater(last, 0.04) + self.assertAlmostEqual(last, 0.04880982706687237) + + +class TestAddRowsAt(unittest.TestCase): + def test_equals_add_at(self): + # even labels: the odd centroids stay untouched. 3000 rows take the + # product over all 100 centroids, 30 rows over the touched ones only. + # float64 rows into float32 sums round after each add in np.add.at. + rng = np.random.default_rng(123) + labels = 2 * rng.integers(0, 50, size=3000) + rows64 = rng.standard_normal((3000, 24)) + dtypes = [("float32", "float32"), ("float64", "float32"), + ("float32", "float64")] + for out_dtype, rows_dtype in dtypes: + rows = rows64.astype(rows_dtype) + for n in 3000, 30: + for scipy_sparse in True, False: + with self.subTest(out_dtype=out_dtype, + rows_dtype=rows_dtype, n=n, + scipy_sparse=scipy_sparse): + expected = np.ones((100, 24), dtype=out_dtype) + np.add.at(expected, labels[:n], rows[:n]) + got = np.ones((100, 24), dtype=out_dtype) + hidden = ( + {} if scipy_sparse else {"scipy.sparse": None} + ) + with unittest.mock.patch.dict(sys.modules, hidden): + _add_rows_at(got, labels[:n], rows[:n]) + np.testing.assert_array_equal(got, expected) + + +class TestEmeans(EmeansReferenceContracts, unittest.TestCase): + def reference_arrays(self): + return [("numpy", lambda values, dtype="float32": np.asarray(values, dtype=dtype))] + + def test_numpy_training_does_not_import_torch(self): + # A separate interpreter proves optional-dependency isolation even + # when the surrounding test runner has already imported Torch. + code = """ +import builtins +import pathlib +import sys +import numpy as np +original_import = builtins.__import__ +def without_torch(name, *args, **kwargs): + if name == 'torch' or name.startswith('torch.'): + raise AssertionError('NumPy training imported Torch') + return original_import(name, *args, **kwargs) +builtins.__import__ = without_torch +import faiss.contrib +faiss.contrib.__path__.insert(0, str(pathlib.Path(sys.argv[1]).resolve().parents[1])) +from faiss.contrib.e_means import NumpyEmeans as Emeans +import faiss.contrib.e_means +assert pathlib.Path(faiss.contrib.e_means.__file__).resolve() == pathlib.Path(sys.argv[1]).resolve() +model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5) +model.begin(4, np.array([[0], [10]], dtype='float32')) +np.testing.assert_array_equal(model.current_centroids(), [[0], [10]]) +model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5) +centroids, captured_labels = model.train(np.array([[0], [2], [10], [12]], dtype='float32'), + np.array([[0], [10]], dtype='float32')) +assert model.obj[-1] == 8 +assert centroids is model.centroids and captured_labels is model.assignments +np.testing.assert_array_equal(model.centroids, [[1], [11]]) +assert 'torch' not in sys.modules +""" + subprocess.run([sys.executable, "-c", code, + faiss.contrib.e_means.__file__], check=True, timeout=30) + + def test_large_batch_sums_and_closing_mean(self): + n = 2**24 + 2 + x = np.full((n, 1), 0.25, dtype="float32") + km = Emeans(1, 1, nepochs=1, batch_size=n, alpha0=1.0) + km.begin(n, np.zeros((1, 1), dtype="float32")) + partial = km.accumulate(x[: 2**24]) + self.assertEqual(partial["n"], 2**24) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + stats = km.accumulate(x[2**24 :]) + self.assertEqual(stats["sums"].dtype, np.dtype("float32")) + self.assertEqual(stats["counts"].dtype, np.dtype("float32")) + self.assertEqual(stats["sums"][0, 0], n * 0.25) + self.assertEqual(stats["counts"][0], n) + km.update(stats) + km.end_epoch() + self.assertEqual(km.finalize()[0, 0], 0.25) + + def test_closing_mean_and_assign(self): + x = np.array([[0.0], [2.0], [10.0], [12.0]], dtype="float32") + init = np.array([[0.0], [10.0]], dtype="float32") + km = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5) + + centroids, captured_labels = km.train(x, init_centroids=init) + + np.testing.assert_array_equal(km.centroids, [[1.0], [11.0]]) + self.assertEqual(km.obj[-1], 8.0) + self.assertIs(centroids, km.centroids) + self.assertIs(captured_labels, km.assignments) + self.assertEqual(km.recipe["name"], "manual") + self.assertIsNone(km.recipe["batch_law"]) + self.assertEqual(km.recipe["alpha0_source"], "given") + distance, labels = km.assign(x) + np.testing.assert_array_equal(labels, [0, 0, 1, 1]) + np.testing.assert_array_equal(distance, [1.0, 1.0, 1.0, 1.0]) + + def test_train_tuple_capture_opt_out_and_owned_lifetime(self): + x = np.array([[0.], [2.], [10.], [12.]], dtype="float32") + initial = np.array([[0.], [10.]], dtype="float32") + for capture in (None, False): + options = {} if capture is None else dict(capture_assignments=capture) + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=.5, **options) + calls, original = [], model._assign_rows + + def assignment(*args, _calls=calls, _original=original, **kwargs): + _calls.append(True) + return _original(*args, **kwargs) + + model._assign_rows = assignment + centroids, labels = model.train(x, initial) + self.assertEqual(len(calls), 1) # No extra closing-centroid search. + self.assertIs(centroids, model.centroids) + self.assertIs(labels, model.assignments) + self.assertEqual(model.obj[-1], 8.) + self.assertEqual(model.recipe["backend"], "faiss") + if capture is None: + self.assertEqual(labels.dtype, np.dtype("int64")) + np.testing.assert_array_equal(labels, [0, 0, 1, 1]) + else: + self.assertIsNone(labels) + saved_centroids = centroids.copy() + saved_labels = None if labels is None else labels.copy() + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=.5, **options) + model.train(x + 100, initial + 100) + np.testing.assert_array_equal(centroids, saved_centroids) + if labels is not None: + np.testing.assert_array_equal(labels, saved_labels) + + def test_resident_capture_memory_is_bounded_by_assignment_chunks(self): + # PR3's memory witness: a full-dataset logical batch must not allocate + # another full-dataset label array before scattering its assignments. + import tracemalloc + + n = 400_000 + x = np.random.RandomState(0).randn(n, 2).astype("float32") + Emeans(2, 16, nepochs=1, batch_size=1000, alpha0=0.5).train(x[:1000]) + + def peak(capture): + tracemalloc.start() + try: + base = tracemalloc.get_traced_memory()[0] + Emeans( + 2, + 16, + nepochs=1, + batch_size=n, + alpha0=0.5, + seed=3, + capture_assignments=capture, + ).train(x) + return tracemalloc.get_traced_memory()[1] - base + finally: + tracemalloc.stop() + + extra_bytes_per_row = (peak(True) - peak(False)) / n + self.assertTrue(6 < extra_bytes_per_row < 10, extra_bytes_per_row) + + def test_untouched_centroid_retains_its_position(self): + x = np.arange(4, dtype="float32")[:, None] + init = np.array([[0.0], [100.0]], dtype="float32") + first = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=1.0) + first.train(x, init_centroids=init) + np.testing.assert_array_equal(first.centroids, [[1.5], [100.0]]) + + second = Emeans(1, 2, nepochs=2, batch_size=4, alpha0=1.0) + second.train(x, init_centroids=init) + # A second pass must retain the never-assigned centroid's position. + np.testing.assert_array_equal(second.centroids, [[1.5], [100.0]]) + + def test_caller_batches_match_matrix_training(self): + x = np.random.RandomState(123).randn(17, 3).astype("float32") + init = x[:4].copy() + args = { + "nepochs": 3, + "batch_size": 4, + "alpha0": 0.2, + "seed": 7, + "assignment_chunk_size": 2, + } + matrix, caller = Emeans(3, 4, **args), Emeans(3, 4, **args) + matrix.train(x, init_centroids=init) + caller.begin(len(x), init) + for epoch in range(caller.nepochs): + order = np.random.RandomState( + _epoch_seed(caller.seed, epoch) + ).permutation(len(x)) + for begin in range(0, len(x), caller.recipe["batch_size"]): + caller.update(caller.accumulate(x[order[begin : begin + 4]])) + caller.end_epoch() + result = caller.finalize() + self.assertIs(result, caller.centroids) + np.testing.assert_array_equal(result, matrix.centroids) + np.testing.assert_array_equal(caller.obj, matrix.obj) + self.assertEqual(caller.n_splits, matrix.n_splits) + + def test_revival_starts_on_fifth_update(self): + x = np.zeros((10, 1), dtype="float32") + init = np.array([[0.0], [10.0]], dtype="float32") + + before = Emeans(1, 2, nepochs=4, batch_size=10, alpha0=0.5, + unused_threshold=0.1) + before.train(x, init_centroids=init) + self.assertEqual(before.n_splits, 0) + + on_fifth = Emeans(1, 2, nepochs=5, batch_size=10, alpha0=0.5, + unused_threshold=0.1) + on_fifth.train(x, init_centroids=init) + self.assertEqual(on_fifth.n_splits, 1) + + def test_removal_cost_keeps_far_blob_and_revives_dead(self): + rs = np.random.RandomState(0) + x = np.vstack([rs.randn(4000, 4), rs.randn(40, 4) + 20]).astype("float32") + init = np.vstack([x[:2], x[-1:], np.full((1, 4), -50)]).astype("float32") + for threshold, far_kept in ((None, True), (0.1, False)): + centroids, _ = Emeans(4, 4, nepochs=3, unused_threshold=threshold).train(x, init) + self.assertEqual(np.abs(centroids - 20).max(axis=1).min() < 1, far_kept) + self.assertLess(np.abs(centroids).max(), 30) # the dead centroid moved + + def test_removal_moves_every_candidate(self): + centers = np.array([[0.], [1.], [-2.], [10.]], dtype="float32") + model = Emeans(1, 4, nepochs=1, batch_size=4) + model.begin(4, centers) + sources, victims = model._choose_removal_splits( + np.array([1., 100., 0., 100.]), np.ones(4), np.array([1., 3., 2., 4.])) + np.testing.assert_array_equal(victims, [2, 0]) # cheapest first, neighbours included + np.testing.assert_array_equal(sources, [3, 1]) + + def test_removal_moves_only_pairs_that_pay(self): + # A pair moves only if (2/pi)|U_donor| > R_candidate, or R_candidate <= 0. + centers = np.array([[0.], [.1], [5.], [10.], [20.], [30.]], dtype="float32") + model = Emeans(1, 6, nepochs=1, batch_size=6) + model.begin(6, centers) + removal = np.array([1., 2., 100., 100., 100., 100.]) + sources, victims = model._choose_removal_splits( + removal, np.ones(6), np.array([1., 1., 10., 2., 1., 1.])) + np.testing.assert_array_equal(victims, [0]) # 2/pi*2 < 2: the second pair stays + np.testing.assert_array_equal(sources, [2]) + sources, victims = model._choose_removal_splits( + np.array([0., 2., 100., 100., 100., 100.]), np.ones(6), + np.array([1., 1., .1, .1, 1., 1.])) + np.testing.assert_array_equal(victims, [0]) # dead candidates always move + np.testing.assert_array_equal(sources, [4]) + sources, victims = model._choose_removal_splits(removal, np.ones(6), np.ones(6)) + self.assertIsNone(sources) # no split pays for a removal + self.assertIsNone(victims) + + def test_revival_checks_continue_through_the_last_pass(self): + # Exact first means give zero split gain; later wide donor rows pay. + # Follow the resolved partial-first/full-last recipe in the caller API. + init = np.array([[0.], [1.], [10.], [30.]], dtype="float32") + late = np.array([[27.], [30.], [33.]], dtype="float32") + km, done, moved = Emeans(1, 4, nepochs=1.6, batch_size=10, alpha0=.5), [], [] + km.begin(100, init) + choose, apply = km._choose_splits, km._apply_splits + + def rows_seen(): + return sum(km.recipe["epoch_rows"][:km._epoch]) + km._epoch_rows + + def record(rng): + done.append(rows_seen()) + return choose(rng) + + def record_moves(source, target): + norm = km._axis_scale * np.linalg.norm(km._removal_stats[source, :-1].astype("float64"), axis=1) + gain = (2 / np.pi) * norm.astype("float32").astype("float64") + cost = km._removal_stats[target, -1].astype("float64") + self.assertTrue(np.all((cost <= 0) | (gain > cost))) + moved.append(rows_seen()) + return apply(source, target) + + km._choose_splits, km._apply_splits = record, record_moves + for pattern in (init, late): + while km._epoch_rows < km.recipe["epoch_rows"][km._epoch]: + size = min(km.recipe["batch_size"], km.recipe["epoch_rows"][km._epoch] - km._epoch_rows) + rows = np.tile(pattern, (size // len(pattern) + 1, 1))[:size] + km.update(km.accumulate(rows)) + km.end_epoch() + self.assertTrue(np.isfinite(km.finalize()).all()) + self.assertGreater(max(done), 100) + self.assertTrue(moved) + self.assertGreater(max(moved), 100) # A real profitable split, not just a late check. + + def test_centroid_moved_while_closing_closes_from_its_final_rows(self): + rs = np.random.RandomState(0) + x = np.vstack([rs.randn(4000, 4), rs.randn(40, 4) + 20]).astype("float32") + init = np.vstack([x[:2], x[-1:], np.full((1, 4), -50)]).astype("float32") + km, state = Emeans(4, 4, nepochs=1), {} + finish = km._handover_finish + + def capture(order, rows): + state["splits"], state["rows"] = len(km._handover["events"]), order[:rows].copy() + return finish(order, rows) + + km._handover_finish = capture + centroids, labels = km.train(x, init) + self.assertGreater(state["splits"], 0) + rows = state["rows"] + for j in range(4): # Every centroid with last-pass rows returns their mean. + mine = rows[labels[rows] == j] + if len(mine): + np.testing.assert_allclose(centroids[j], x[mine].mean(axis=0), rtol=1e-5, atol=1e-5) + + def test_rows_of_centroid_revived_while_closing_take_second_nearest(self): + rs = np.random.RandomState(0) + x = ((rs.randn(64, 8) * 4)[rs.randint(0, 64, 20000)] + rs.randn(20000, 8)).astype("float32") + init = x[rs.choice(len(x), 64, replace=False)] + km, state = Emeans(8, 64, nepochs=1, batch_size=500), {} + + def handover_finish(order, rows, finish=km._handover_finish): + state["before"] = km._handover["labels"].copy() + return finish(order, rows) + + km._handover_finish = handover_finish + centroids, labels = km.train(x, init) + self.assertEqual(km.recipe["closing_handover"], "second_nearest") + self.assertGreater(km.closing_handover_stats["second"], 0) + self.assertGreater((labels != state["before"]).sum(), 0) + + def closing(lab): + out = centroids.copy() + for j in np.flatnonzero(np.bincount(lab, minlength=64) > 0): + out[j] = x[lab == j].mean(0) + return out + + # Every centroid closes at the mean of its final rows. + np.testing.assert_allclose(centroids, closing(labels), rtol=1e-4, atol=1e-4) + # The same run without the handover: labels before it, means over them. + before = closing(state["before"]) + error = ((x - centroids[labels]) ** 2).sum(1).mean() + self.assertLess(error, ((x - before[state["before"]]) ** 2).sum(1).mean()) + + def test_first_batch_is_not_the_init_draw(self): + # Seed 0's pass 0 reused the init seed, so its first batch held every init row. + self.assertNotEqual(_epoch_seed(0, 0), 0) + x = np.random.RandomState(3).randn(20000, 4).astype("float32") + km, batches = Emeans(4, 200, nepochs=2, seed=0), [] + accumulate = km._accumulate + km._accumulate = lambda x, rows, *args: batches.append(rows) or accumulate(x, rows, *args) + km.train(x) + init = np.random.RandomState(0).permutation(len(x))[:200] + # An unrelated order shares about 1 of the 128 first rows; the init order shared all 128. + self.assertLess(len(np.intersect1d(init, batches[0])), 10) + + def test_revival_follows_current_batch_update(self): + seed = 7 + order = np.random.RandomState(_epoch_seed(seed, 0)).permutation(5) + x = np.zeros((5, 1), dtype="float32") + x[order[-1]] = 10.0 + init = np.array([[0.0], [10.0]], dtype="float32") + km = Emeans(1, 2, nepochs=1, batch_size=1, alpha0=0.5, seed=seed, unused_threshold=0.1) + + km.train(x, init_centroids=init) + + # The fifth batch makes cluster 1 live before revival checks usage. + self.assertEqual(km.n_splits, 0) + + def test_each_pass_uses_tail(self): + x = np.array([[0.0], [0.0], [0.0], [0.0], [10.0]], dtype="float32") + km = Emeans(1, 1, nepochs=2, batch_size=3, alpha0=0.5) + + km.train(x, init_centroids=np.array([[0.0]], dtype="float32")) + + np.testing.assert_array_equal(km.centroids, [[2.0]]) + self.assertEqual(km.recipe["steps_per_pass"], 2) + self.assertEqual(km.recipe["total_steps"], 4) + self.assertEqual(km.recipe["tail_policy"], "keep") + + def test_assignment_chunking_preserves_logical_updates(self): + rng = np.random.RandomState(123) + x = rng.randn(41, 5).astype("float32") + init = x[:4].copy() + args = {"nepochs": 3, "batch_size": 13, "alpha0": 0.2, "seed": 7} + a = Emeans(5, 4, assignment_chunk_size=4, **args) + b = Emeans(5, 4, assignment_chunk_size=64, **args) + + a.train(x, init_centroids=init) + b.train(x, init_centroids=init) + + # This fixture remains away from assignment boundaries. In general, + # Faiss may choose different exact-search kernels for different query + # sizes, so chunking is not promised to be bitwise invariant. + np.testing.assert_allclose(a.centroids, b.centroids) + np.testing.assert_allclose(a.obj, b.obj) + self.assertEqual(a.recipe["steps_per_pass"], 4) + self.assertEqual(a.recipe["total_steps"], 12) + + def test_fresh_objects_are_deterministic(self): + x = np.random.RandomState(123).randn(40, 4).astype("float32") + km = Emeans(4, 3, nepochs=2, batch_size=11, alpha0=0.2) + km.train(x) + centroids = km.centroids.copy() + objective = km.obj.copy() + + km = Emeans(4, 3, nepochs=2, batch_size=11, alpha0=0.2) + km.train(x) + + np.testing.assert_array_equal(km.centroids, centroids) + np.testing.assert_array_equal(km.obj, objective) + del km + + def test_training_does_not_advance_global_rng(self): + x = np.arange(80, dtype="float32").reshape(20, 4) + state = np.random.get_state() + km = Emeans(4, 3, nepochs=1, batch_size=7, alpha0=0.2) + + km.train(x) + + after = np.random.get_state() + self.assertEqual(state[0], after[0]) + np.testing.assert_array_equal(state[1], after[1]) + self.assertEqual(state[2:], after[2:]) + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/test_eden.py b/thirdparty/faiss/tests/test_eden.py index 8ceb1f8ae..ac7facf23 100644 --- a/thirdparty/faiss/tests/test_eden.py +++ b/thirdparty/faiss/tests/test_eden.py @@ -31,15 +31,8 @@ def lloyd_max_codebook(bits): return trained[:k], trained[k:] -def eden_reference_reconstruct(x, bits, center=None, scale_type="unbiased"): - x = np.asarray(x, dtype="float32") - if center is None: - residual = x.copy() - base = 0 - else: - center = np.asarray(center, dtype="float32") - residual = x - center - base = center +def eden_reference_reconstruct(x, bits, scale_type="unbiased"): + residual = np.asarray(x, dtype="float32") centroids, boundaries = lloyd_max_codebook(bits) d = residual.shape[1] @@ -48,33 +41,23 @@ def eden_reference_reconstruct(x, bits, center=None, scale_type="unbiased"): for i, r in enumerate(residual): norm_sqr = float(np.dot(r, r)) if norm_sqr == 0: - out[i] = base + out[i] = 0 continue z = r * np.sqrt(d / norm_sqr) assignments = np.searchsorted(boundaries, z, side="right") q = centroids[assignments] if scale_type == "unbiased": scale = norm_sqr / float(np.dot(q, r)) - elif scale_type == "biased": - scale = float(np.dot(q, r)) / float(np.dot(q, q)) else: - raise ValueError(f"unknown EDEN scale type: {scale_type}") - out[i] = base + scale * q + scale = float(np.dot(q, r)) / float(np.dot(q, q)) + out[i] = scale * q return out -def eden_reference_l2_distances( - x, query, bits, center=None, scale_type="unbiased" -): - x = np.asarray(x, dtype="float32") - query = np.asarray(query, dtype="float32") - if center is None: - residual = x.copy() - query_residual = query - else: - center = np.asarray(center, dtype="float32") - residual = x - center - query_residual = query - center +def eden_reference_l2_distances(x, query, bits, center): + center = np.asarray(center, dtype="float32") + residual = np.asarray(x, dtype="float32") - center + query_residual = np.asarray(query, dtype="float32") - center centroids, boundaries = lloyd_max_codebook(bits) d = residual.shape[1] @@ -89,19 +72,10 @@ def eden_reference_l2_distances( z = r * np.sqrt(d / norm_sqr) assignments = np.searchsorted(boundaries, z, side="right") q = centroids[assignments] - code_dot_residual = float(np.dot(q, r)) - code_norm_sqr = float(np.dot(q, q)) - if scale_type == "unbiased": - scale = norm_sqr / code_dot_residual - l2_norm_term = norm_sqr - elif scale_type == "biased": - scale = code_dot_residual / code_norm_sqr - l2_norm_term = scale * scale * code_norm_sqr - else: - raise ValueError(f"unknown EDEN scale type: {scale_type}") + scale = norm_sqr / float(np.dot(q, r)) distances[i] = ( query_base - + l2_norm_term + + norm_sqr - 2.0 * scale * float(np.dot(q, query_residual)) ) # The unbiased scale reports an estimator of the squared distance that can @@ -116,42 +90,29 @@ def test_eden_quantizer_uses_scalar_quantizer_qtypes(self): with self.subTest(bits=bits): quantizer = faiss.ScalarQuantizer(64, qtype) quantizer.train(np.zeros((1, 64), dtype="float32")) - self.assertEqual(quantizer.qtype, qtype) self.assertEqual(quantizer.bits, bits) self.assertEqual(quantizer.code_size, (64 * bits + 7) // 8) - def test_decode_matches_original_eden_scale_reference(self): + def test_decode_matches_eden_scale_reference(self): rs = np.random.RandomState(123) xb = rs.randn(16, 64).astype("float32") - for bits in [1, 2, 4]: - with self.subTest(bits=bits): - index = faiss.IndexEDEN(64, faiss.METRIC_L2, bits) - index.train(np.zeros((1, 64), dtype="float32")) - codes = index.sa_encode(xb) - decoded = index.sa_decode(codes) - reference = eden_reference_reconstruct(xb, bits) - np.testing.assert_allclose(decoded, reference, rtol=1e-5) - - def test_decode_matches_biased_eden_scale_reference(self): - rs = np.random.RandomState(321) - xb = rs.randn(16, 64).astype("float32") - - for bits in [1, 2, 4]: - with self.subTest(bits=bits): - index = faiss.IndexEDEN( - 64, - faiss.METRIC_L2, - bits, - faiss.EDENScaleType_BIASED, - ) - index.train(np.zeros((1, 64), dtype="float32")) - codes = index.sa_encode(xb) - decoded = index.sa_decode(codes) - reference = eden_reference_reconstruct( - xb, bits, scale_type="biased" - ) - np.testing.assert_allclose(decoded, reference, rtol=1e-5) + for scale_type, scale_name in [ + (faiss.EDENScaleType_UNBIASED, "unbiased"), + (faiss.EDENScaleType_BIASED, "biased"), + ]: + for bits in [1, 2, 4]: + with self.subTest(scale_type=scale_name, bits=bits): + index = faiss.IndexEDEN( + 64, faiss.METRIC_L2, bits, scale_type + ) + index.train(np.zeros((1, 64), dtype="float32")) + codes = index.sa_encode(xb) + decoded = index.sa_decode(codes) + reference = eden_reference_reconstruct( + xb, bits, scale_type=scale_name + ) + np.testing.assert_allclose(decoded, reference, rtol=1e-5) def test_distance_computer_matches_reference_l2(self): rs = np.random.RandomState(456) @@ -177,37 +138,24 @@ def test_distance_computer_matches_reference_l2(self): actual, reference, rtol=1e-5, atol=1e-5 ) - def test_factory_flat_and_ivf(self): - rs = np.random.RandomState(789) - d, nt, nb, nq = 64, 300, 500, 20 - xt = rs.randn(nt, d).astype("float32") - xb = rs.randn(nb, d).astype("float32") - xq = rs.randn(nq, d).astype("float32") - - index = faiss.index_factory(d, "EDEN4") - self.assertIsInstance(index, faiss.IndexEDEN) - self.assertEqual(index.sq.qtype, faiss.ScalarQuantizer.QT_4bit_eden) - self.assertEqual(index.sq.bits, 4) - self.assertEqual(index.scale_type, faiss.EDENScaleType_UNBIASED) - index.train(xt) - index.add(xb) - D, I = index.search(xq, 10) - self.assertEqual(D.shape, (nq, 10)) - self.assertTrue(np.all(np.isfinite(D))) - self.assertTrue(np.all(I >= 0)) - - index_ivf = faiss.index_factory(d, "IVF16,EDEN4") - self.assertIsInstance(index_ivf, faiss.IndexIVFEDEN) - self.assertEqual(index_ivf.sq.qtype, faiss.ScalarQuantizer.QT_4bit_eden) - self.assertEqual(index_ivf.sq.bits, 4) - self.assertEqual(index_ivf.scale_type, faiss.EDENScaleType_UNBIASED) - index_ivf.nprobe = 4 - index_ivf.train(xt) - index_ivf.add(xb) - D, I = index_ivf.search(xq, 10) - self.assertEqual(D.shape, (nq, 10)) - self.assertTrue(np.all(np.isfinite(D))) - self.assertTrue(np.any(I >= 0)) + def test_factory(self): + for description, index_class, scale_type in [ + ("EDEN4", faiss.IndexEDEN, faiss.EDENScaleType_UNBIASED), + ("IVF16,EDEN4", faiss.IndexIVFEDEN, faiss.EDENScaleType_UNBIASED), + ("EDEN4BIASED", faiss.IndexEDEN, faiss.EDENScaleType_BIASED), + ( + "IVF16,EDEN4BIASED", + faiss.IndexIVFEDEN, + faiss.EDENScaleType_BIASED, + ), + ]: + with self.subTest(description=description): + index = faiss.index_factory(64, description) + self.assertIsInstance(index, index_class) + self.assertEqual( + index.sq.qtype, faiss.ScalarQuantizer.QT_4bit_eden + ) + self.assertEqual(index.scale_type, scale_type) def test_search_matches_none_simd_level(self): if not faiss.SIMDConfig.is_simd_level_available(faiss.SIMDLevel_NONE): @@ -284,10 +232,8 @@ def test_high_dimensional_search_matches_distance_computer(self): ) def test_unbiased_l2_distances_are_non_negative(self): - # Unbiased 1-bit EDEN reports an unbiased estimator of the squared L2 - # distance, which can dip below zero for strongly-aligned residuals - # (self-query below triggers it). Reported distances must still honor - # the METRIC_L2 contract of being non-negative. + # Self-queries drive the unbiased estimator below zero; METRIC_L2 + # distances must still be non-negative. rs = np.random.RandomState(2468) d, nb = 128, 256 xt = rs.randn(400, d).astype("float32") @@ -306,22 +252,6 @@ def test_unbiased_l2_distances_are_non_negative(self): ) self.assertTrue(np.all(vals >= 0.0)) - D, _ = index.search(xq, 10) - self.assertTrue(np.all(D >= 0.0)) - - def test_factory_biased_eden_scale(self): - index = faiss.index_factory(64, "EDEN4BIASED") - self.assertIsInstance(index, faiss.IndexEDEN) - self.assertEqual(index.sq.qtype, faiss.ScalarQuantizer.QT_4bit_eden) - self.assertEqual(index.sq.bits, 4) - self.assertEqual(index.scale_type, faiss.EDENScaleType_BIASED) - - index_ivf = faiss.index_factory(64, "IVF16,EDEN4BIASED") - self.assertIsInstance(index_ivf, faiss.IndexIVFEDEN) - self.assertEqual(index_ivf.sq.qtype, faiss.ScalarQuantizer.QT_4bit_eden) - self.assertEqual(index_ivf.sq.bits, 4) - self.assertEqual(index_ivf.scale_type, faiss.EDENScaleType_BIASED) - def test_serde(self): rs = np.random.RandomState(987) d, nt, nb, nq = 32, 200, 300, 10 @@ -342,6 +272,8 @@ def test_serde(self): index.train(xt) index.add(xb) Dref, Iref = index.search(xq, 5) + self.assertTrue(np.all(np.isfinite(Dref))) + self.assertTrue(np.all(Iref >= 0)) payload = faiss.serialize_index(index) index2 = faiss.deserialize_index(payload) diff --git a/thirdparty/faiss/tests/test_extra_distances.py b/thirdparty/faiss/tests/test_extra_distances.py index b276bd21b..dbb369c7b 100644 --- a/thirdparty/faiss/tests/test_extra_distances.py +++ b/thirdparty/faiss/tests/test_extra_distances.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -# noqa E741 - import numpy as np import faiss @@ -18,8 +16,7 @@ import scipy.spatial.distance -@for_all_simd_levels -class TestExtraDistances(unittest.TestCase): +class ScipyRefMixin: """check wrt. the scipy implementation""" def make_example(self): @@ -34,6 +31,9 @@ def run_simple_dis_test(self, ref_func, metric_type): new_dis = faiss.pairwise_distances(xq, yb, metric_type) self.assertTrue(np.allclose(ref_dis, new_dis)) + +@for_all_simd_levels +class TestSIMDDistances(ScipyRefMixin, unittest.TestCase): def test_L1(self): self.run_simple_dis_test( scipy.spatial.distance.cityblock, faiss.METRIC_L1 @@ -52,12 +52,10 @@ def test_L2(self): new_dis = faiss.pairwise_distances(xq, yb, faiss.METRIC_L2) self.assertTrue(np.allclose(ref_dis, new_dis)) - ref_dis = np.array( - [[scipy.spatial.distance.euclidean(x, y) for y in yb] for x in xq] - ) - new_dis = np.sqrt(new_dis) # post processing - self.assertTrue(np.allclose(ref_dis, new_dis)) +# These metrics always run at SIMDLevel::NONE (with_VectorDistance), so one +# level is enough. +class TestExtraDistances(ScipyRefMixin, unittest.TestCase): def test_Lp(self): p = 1.5 xq, yb = self.make_example() @@ -68,7 +66,7 @@ def test_Lp(self): ] ) new_dis = faiss.pairwise_distances(xq, yb, faiss.METRIC_Lp, p) - new_dis = new_dis ** (1 / p) # post processing + new_dis = new_dis ** (1 / p) self.assertTrue(np.allclose(ref_dis, new_dis)) def test_canberra(self): @@ -76,17 +74,86 @@ def test_canberra(self): scipy.spatial.distance.canberra, faiss.METRIC_Canberra ) + def test_canberra_zero_denominator(self): + xq = np.array([[0.0, 0.0]], dtype="float32") + yb = np.array( + [ + [0.0, 0.0], + [1.0, 0.0], + [0.0, 2.0], + ], + dtype="float32", + ) + expected = np.array([[0.0, 1.0, 1.0]], dtype="float32") + + distances = faiss.pairwise_distances( + xq, yb, faiss.METRIC_Canberra + ) + self.assertTrue(np.all(np.isfinite(distances))) + self.assertTrue(np.allclose(distances, expected)) + + index = faiss.IndexFlat(2, faiss.METRIC_Canberra) + index.add(yb) + distances, labels = index.search(xq, 3) + self.assertTrue(np.all(np.isfinite(distances))) + self.assertNotIn(-1, labels[0]) + self.assertEqual(set(labels[0].tolist()), {0, 1, 2}) + self.assertTrue(np.allclose(np.sort(distances[0]), expected[0])) + def test_braycurtis(self): self.run_simple_dis_test( scipy.spatial.distance.braycurtis, faiss.METRIC_BrayCurtis ) - def xx_test_jensenshannon(self): - # this distance does not seem to be implemented in scipy - # vectors should probably be L1 normalized - self.run_simple_dis_test( - scipy.spatial.distance.jensenshannon, faiss.METRIC_JensenShannon + def test_jensenshannon(self): + xq = np.array( + [[0.0, 0.25, 0.75], [0.5, 0.0, 0.5]], dtype="float32" ) + yb = np.array( + [[0.2, 0.8, 0.0], [0.0, 0.0, 1.0]], dtype="float32" + ) + ref_dis = np.array( + [ + [scipy.spatial.distance.jensenshannon(x, y) ** 2 for y in yb] + for x in xq + ] + ) + new_dis = faiss.pairwise_distances( + xq, yb, faiss.METRIC_JensenShannon + ) + np.testing.assert_allclose(ref_dis, new_dis, rtol=1e-5, atol=1e-7) + + tiny = np.nextafter(np.float32(0), np.float32(1)) + tiny_dis = faiss.pairwise_distances( + np.array([[tiny, 1.0]], dtype="float32"), + np.array([[0.0, 1.0]], dtype="float32"), + faiss.METRIC_JensenShannon, + ) + self.assertTrue(np.isfinite(tiny_dis).all()) + + def test_jensenshannon_hnsw_sparse(self): + xb = np.array( + [ + [1.0, 0.0], + [0.0, 1.0], + [0.5, 0.5], + [0.25, 0.75], + [0.75, 0.25], + [0.0, 1.0], + [1.0, 0.0], + [0.1, 0.9], + [0.9, 0.1], + [0.0, 1.0], + ], + dtype="float32", + ) + index = faiss.IndexHNSWFlat(2, 10, faiss.METRIC_JensenShannon) + index.add(xb) + + distances, labels = index.search(xb[:1], 5) + + self.assertTrue(np.isfinite(distances).all()) + self.assertTrue((labels >= 0).all()) def test_jaccard(self): xq, yb = self.make_example() @@ -130,8 +197,8 @@ def test_gower(self): # (negative integers) xq = np.array( [ - [0.5, 0.3, -1, -2], # First query vector - [0.7, 0.8, -1, -3], # Second query vector + [0.5, 0.3, -1, -2], + [0.7, 0.8, -1, -3], ], dtype="float32", ) @@ -146,7 +213,6 @@ def test_gower(self): dtype="float32", ) - # Compute distances using FAISS dis = faiss.pairwise_distances(xq, yb, faiss.METRIC_GOWER) # Expected distances: @@ -164,8 +230,8 @@ def test_gower(self): expected = np.array( [ - [0.05, 0.15, 0.25, 0.50], # Distances for first query - [0.475, 0.475, 0.675, 0.425], # Distances for second query + [0.05, 0.15, 0.25, 0.50], + [0.475, 0.475, 0.675, 0.425], ], dtype="float32", ) diff --git a/thirdparty/faiss/tests/test_factory.py b/thirdparty/faiss/tests/test_factory.py index e59a1e9e4..19fee33ed 100644 --- a/thirdparty/faiss/tests/test_factory.py +++ b/thirdparty/faiss/tests/test_factory.py @@ -9,7 +9,6 @@ import gc import faiss -from common_faiss_tests import for_all_simd_levels from faiss.contrib import factory_tools from faiss.contrib import datasets @@ -37,21 +36,6 @@ def test_factory_1(self): else: raise AssertionError("should do a runtime error") - def test_factory_2(self): - - index = faiss.index_factory(12, "SQ8") - assert index.code_size == 12 - - def test_factory_3(self): - - index = faiss.index_factory(12, "IVF10,PQ4") - faiss.ParameterSpace().set_index_parameter(index, "nprobe", 3) - assert index.nprobe == 3 - - index = faiss.index_factory(12, "PCAR8,IVF10,PQ4") - faiss.ParameterSpace().set_index_parameter(index, "nprobe", 3) - assert faiss.downcast_index(index.index).nprobe == 3 - def test_factory_4(self): index = faiss.index_factory(12, "IVF10,FlatDedup") assert isinstance(index, faiss.IndexIVFFlatDedup) @@ -63,22 +47,6 @@ def test_factory_5(self): assert index.sa_code_size() == 64 * 4 assert index.chain.at(0).d_out == 64 - def test_factory_6(self): - index = faiss.index_factory(128, "RaBitQ") - assert index.d == 128 - assert index.metric_type == faiss.METRIC_L2 - index = faiss.index_factory(128, "IVF256,RaBitQ") - assert index.d == 128 - assert index.metric_type == faiss.METRIC_L2 - - def test_factory_HNSW(self): - index = faiss.index_factory(12, "HNSW32") - assert index.storage.sa_code_size() == 12 * 4 - index = faiss.index_factory(12, "HNSW32_SQ8") - assert index.storage.sa_code_size() == 12 - index = faiss.index_factory(12, "HNSW32_PQ4") - assert index.storage.sa_code_size() == 4 - def test_factory_HNSW_newstyle(self): index = faiss.index_factory(12, "HNSW32,Flat") assert index.storage.sa_code_size() == 12 * 4 @@ -98,19 +66,11 @@ def test_factory_HNSW_newstyle(self): self.assertEqual(indexpq.pq.nbits, 12) def test_factory_NSG(self): - index = faiss.index_factory(12, "NSG64") - assert isinstance(index, faiss.IndexNSGFlat) - assert index.nsg.R == 64 - index = faiss.index_factory(12, "NSG64", faiss.METRIC_INNER_PRODUCT) assert isinstance(index, faiss.IndexNSGFlat) assert index.nsg.R == 64 assert index.metric_type == faiss.METRIC_INNER_PRODUCT - index = faiss.index_factory(12, "NSG64,Flat") - assert isinstance(index, faiss.IndexNSGFlat) - assert index.nsg.R == 64 - index = faiss.index_factory(12, "NSG64,PQ3x10") assert isinstance(index, faiss.IndexNSGPQ) assert index.nsg.R == 64 @@ -123,13 +83,6 @@ def test_factory_NSG(self): assert isinstance(index_nsg, faiss.IndexNSGFlat) assert index.nlist == 65536 and index_nsg.nsg.R == 64 - index = faiss.index_factory(12, "IVF65536_NSG64,PQ2x8") - index_nsg = faiss.downcast_index(index.quantizer) - assert isinstance(index, faiss.IndexIVFPQ) - assert isinstance(index_nsg, faiss.IndexNSGFlat) - assert index.nlist == 65536 and index_nsg.nsg.R == 64 - assert index.pq.M == 2 and index.pq.nbits == 8 - def test_factory_lsh(self): index = faiss.index_factory(128, "LSHrt") self.assertEqual(index.nbits, 128) @@ -181,13 +134,8 @@ def test_nested_parenteses(self): index = faiss.index_factory(50, "IVF1000(IVF20,SQ4,Refine(SQ8)),Flat") q = faiss.downcast_index(index.quantizer) qref = faiss.downcast_index(q.refine_index) - # check we can access the scalar quantizer self.assertEqual(qref.sq.code_size, 50) - def test_residual(self): - index = faiss.index_factory(50, "IVF1000,PQ25x4fsr") - self.assertTrue(index.by_residual) - class TestCodeSize(unittest.TestCase): @@ -198,28 +146,6 @@ def test_1(self): ) -class TestCloneSize(unittest.TestCase): - - def test_clone_size(self): - index = faiss.index_factory(20, "PCA10,Flat") - xb = faiss.rand((100, 20)) - index.train(xb) - index.add(xb) - index2 = faiss.clone_index(index) - assert index2.ntotal == 100 - - -class TestCloneIVFPQ(unittest.TestCase): - - def test_clone(self): - index = faiss.index_factory(16, "IVF10,PQ4np") - xb = faiss.rand((1000, 16)) - index.train(xb) - index.add(xb) - index2 = faiss.clone_index(index) - assert index2.ntotal == index.ntotal - - class TestVTDowncast(unittest.TestCase): def test_itq_transform(self): @@ -229,27 +155,12 @@ def test_itq_transform(self): itqt.pca_then_itq -# tests after re-factoring class TestFactoryV2(unittest.TestCase): - def test_refine(self): - index = faiss.index_factory(123, "Flat,RFlat") - index.k_factor - - def test_refine_2(self): - index = faiss.index_factory(123, "LSHrt,Refine(Flat)") - index1 = faiss.downcast_index(index.base_index) - self.assertTrue(index1.rotate_data) - self.assertTrue(index1.train_thresholds) - def test_pre_transform(self): index = faiss.index_factory(123, "PCAR100,L2Norm,PCAW50,LSHr") self.assertTrue(index.chain.size() == 3) - def test_ivf(self): - index = faiss.index_factory(123, "IVF456,Flat") - self.assertEqual(index.__class__, faiss.IndexIVFFlat) - def test_ivf_suffix_k(self): index = faiss.index_factory(123, "IVF3k,Flat") self.assertEqual(index.nlist, 3072) @@ -258,24 +169,10 @@ def test_ivf_suffix_M(self): index = faiss.index_factory(123, "IVF1M,Flat") self.assertEqual(index.nlist, 1024 * 1024) - def test_ivf_suffix_HNSW_M(self): - index = faiss.index_factory(123, "IVF1M_HNSW,Flat") - self.assertEqual(index.nlist, 1024 * 1024) - def test_idmap(self): index = faiss.index_factory(123, "Flat,IDMap") self.assertEqual(index.__class__, faiss.IndexIDMap) - def test_idmap2_suffix(self): - index = faiss.index_factory(123, "Flat,IDMap2") - index = faiss.downcast_index(index) - self.assertEqual(index.__class__, faiss.IndexIDMap2) - - def test_idmap2_prefix(self): - index = faiss.index_factory(123, "IDMap2,Flat") - index = faiss.downcast_index(index) - self.assertEqual(index.__class__, faiss.IndexIDMap2) - def test_idmap_refine(self): index = faiss.index_factory(8, "IDMap,PQ4x4fs,RFlat") self.assertEqual(index.__class__, faiss.IndexIDMap) @@ -290,25 +187,14 @@ def test_idmap_refine(self): self.assertRaises(RuntimeError, index.add, np.zeros((16, 8))) def test_ivf_hnsw(self): - index = faiss.index_factory(123, "IVF100_HNSW,Flat") + index = faiss.index_factory(123, "IVF1M_HNSW,Flat") + self.assertEqual(index.nlist, 1024 * 1024) quantizer = faiss.downcast_index(index.quantizer) self.assertEqual(quantizer.hnsw.nb_neighbors(1), 32) - def test_ivf_parent(self): - index = faiss.index_factory(123, "IVF100(LSHr),Flat") - quantizer = faiss.downcast_index(index.quantizer) - self.assertEqual(quantizer.__class__, faiss.IndexLSH) - class TestAdditive(unittest.TestCase): - def test_rcq(self): - index = faiss.index_factory(12, "IVF256(RCQ2x4),RQ3x4") - self.assertEqual( - faiss.downcast_index(index.quantizer).__class__, - faiss.ResidualCoarseQuantizer, - ) - def test_rq3(self): index = faiss.index_factory(5, "RQ2x16_3x8_6x4") @@ -324,7 +210,6 @@ def test_norm(self): ) -@for_all_simd_levels class TestSpectralHash(unittest.TestCase): def test_sh(self): @@ -352,23 +237,6 @@ def test_clone(self): np.testing.assert_array_equal(codes, codes2) -class TestTurboQuantMSESQFactory(unittest.TestCase): - - def test_factory_tqmse(self): - cases = [ - ("SQtqmse1", faiss.ScalarQuantizer.QT_1bit_tqmse), - ("SQtqmse2", faiss.ScalarQuantizer.QT_2bit_tqmse), - ("SQtqmse3", faiss.ScalarQuantizer.QT_3bit_tqmse), - ("SQtqmse4", faiss.ScalarQuantizer.QT_4bit_tqmse), - ("SQtqmse8", faiss.ScalarQuantizer.QT_8bit_tqmse), - ] - for factory_str, qtype in cases: - with self.subTest(factory_str=factory_str): - index = faiss.index_factory(32, factory_str) - self.assertEqual(index.__class__, faiss.IndexScalarQuantizer) - self.assertEqual(index.sq.qtype, qtype) - - class TestIVFSpectralHashOwnership(unittest.TestCase): def test_constructor(self): @@ -381,3 +249,15 @@ def test_replace_vt(self): index.replace_vt(faiss.ITQTransform(10, 10)) gc.collect() index.vt.d_out # this should not crash + + +class TestFactoryConstructorFailure(unittest.TestCase): + def test_ivf_pq_invalid_M(self): + # d = 8 is not divisible by M = 3, PQ throws + self.assertRaises(RuntimeError, faiss.index_factory, 8, "IVF4,PQ3") + + def test_ivf_unknown_code(self): + self.assertRaises(RuntimeError, faiss.index_factory, 8, "IVF4,XYZ") + + def test_2layer_invalid_M(self): + self.assertRaises(RuntimeError, faiss.index_factory, 8, "Residual4,PQ3") diff --git a/thirdparty/faiss/tests/test_factory_tools.cpp b/thirdparty/faiss/tests/test_factory_tools.cpp index f8a7cb934..f0abd4ea6 100644 --- a/thirdparty/faiss/tests/test_factory_tools.cpp +++ b/thirdparty/faiss/tests/test_factory_tools.cpp @@ -20,9 +20,11 @@ TEST(TestFactoryTools, TestReverseIndexFactory) { "IVF8,Flat", "IVF8,SQ4", "IVF8,PQ4x8", + "IVF8,PQ4+4", "LSHrt", "PQ4x8", "HNSW32", + "HNSW32,SQ8", "SQ8", "SQtqmse1", "SQtqmse2", @@ -48,7 +50,6 @@ TEST(TestFactoryTools, TestReverseIndexFactory) { "IVF8,EDEN4BIASED", }) { std::unique_ptr index{index_factory(64, factory)}; - ASSERT_TRUE(index); EXPECT_EQ(factory, reverse_index_factory(index.get())); } using Case = std::pair; @@ -56,17 +57,41 @@ TEST(TestFactoryTools, TestReverseIndexFactory) { Case{"SQ8,RFlat", "SQ8,Refine(Flat)"}, Case{"NSG", "NSG32,Flat"}, Case{"NSG,PQ8", "NSG32,PQ8x8"}, + Case{"HNSW32,PQ16", "HNSW32,PQ16x8"}, }) { std::unique_ptr index{index_factory(64, src)}; - ASSERT_TRUE(index); EXPECT_EQ(dst, reverse_index_factory(index.get())); } } +TEST(TestFactoryTools, TestReverseIndexFactoryPiPNN) { + using Case = std::pair; + for (auto metric : {METRIC_L2, METRIC_INNER_PRODUCT}) { + for (auto [src, expected] : { + Case{"PiPNN", "PiPNN64,Flat"}, + Case{"PiPNN32,Flat", "PiPNN32,Flat"}, + Case{"PiPNN16,SQ8", "PiPNN16,SQ8"}, + Case{"IDMap2,PiPNN32,SQ4", "IDMap2,PiPNN32,SQ4"}, + Case{"IVF16384(PiPNN32,Flat),SQ4", + "IVF16384(PiPNN32,Flat),SQ4"}, + Case{"IVF16384_PiPNN32,SQ4", "IVF16384(PiPNN32,Flat),SQ4"}, + }) { + SCOPED_TRACE(src); + std::unique_ptr index{index_factory(128, src, metric)}; + const auto factory = reverse_index_factory(index.get()); + ASSERT_EQ(expected, factory); + std::unique_ptr rebuilt{ + index_factory(128, factory.c_str(), metric)}; + EXPECT_EQ(index->d, rebuilt->d); + EXPECT_EQ(index->metric_type, rebuilt->metric_type); + EXPECT_EQ(factory, reverse_index_factory(rebuilt.get())); + } + } +} + // IndexIDMap2 inherits IndexIDMap; verify the subclass is distinguished. TEST(TestFactoryTools, TestReverseIndexFactoryIDMap) { std::unique_ptr base{index_factory(64, "Flat")}; - ASSERT_TRUE(base); IndexIDMap idmap(base.get()); EXPECT_EQ("IDMap,Flat", reverse_index_factory(&idmap)); diff --git a/thirdparty/faiss/tests/test_fast_scan.py b/thirdparty/faiss/tests/test_fast_scan.py index b2d014d3b..68f3c516a 100644 --- a/thirdparty/faiss/tests/test_fast_scan.py +++ b/thirdparty/faiss/tests/test_fast_scan.py @@ -25,38 +25,10 @@ @for_all_simd_levels class TestSearch(unittest.TestCase): - def test_PQ4_accuracy(self): - ds = datasets.SyntheticDataset(32, 2000, 5000, 1000) - - index_gt = faiss.IndexFlatL2(32) - index_gt.add(ds.get_database()) - Dref, Iref = index_gt.search(ds.get_queries(), 10) - - index = faiss.index_factory(32, "PQ16x4fs") - index.train(ds.get_train()) - index.add(ds.get_database()) - Da, Ia = index.search(ds.get_queries(), 10) - - nq = Iref.shape[0] - recall_at_1 = (Iref[:, 0] == Ia[:, 0]).sum() / nq - assert recall_at_1 > 0.6 - def test_PQ4_search_matches_none(self): - """Fast-scan PQ search dispatches via the 256/512-bit QBS path. - - The integer QBS kernel is deterministic across SIMD levels *only if* - the upstream float PQ distance table is bit-identical AND the - handler's end() method (int-to-float conversion) compiles to - identical FP code. Two cases break this: - - 1. aarch64 NEON/SVE: float distance-table computation reduces - in a different order, producing non-bit-identical LUT. - 2. DD mode: per-SIMD TUs compile with different flags (-mfma - vs no -mfma), so handler end() may contract mul+add into - fma, producing 1-ULP float distance differences. - - In both cases, fall back to a recall@1 check. - """ + """SIMD and NONE results match exactly unless the float LUT differs + (aarch64) or the DD build contracts end() into fma; then compare + recall@1.""" ds = datasets.SyntheticDataset(32, 2000, 5000, 200) index = faiss.index_factory(32, "PQ16x4fs") index.train(ds.get_train()) @@ -169,16 +141,13 @@ def do_test_rounding(self, implem=4, metric=faiss.METRIC_L2): index2 = faiss.IndexPQFastScan(index) - # simply repro normal search index2.implem = 2 D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, Iref) np.testing.assert_array_equal(D2, Dref) - # rounded LUT with correction index2.implem = implem D4, I4 = index2.search(ds.get_queries(), 10) - # check accuracy of indexes recalls = {} for rank in 1, 10: recalls[rank] = (Iref[:, :1] == I4[:, :rank]).sum() / nq @@ -186,8 +155,6 @@ def do_test_rounding(self, implem=4, metric=faiss.METRIC_L2): min_r1 = 0.98 if metric == faiss.METRIC_INNER_PRODUCT else 0.99 self.assertGreaterEqual(recalls[1], min_r1) self.assertGreater(recalls[10], 0.995) - # check accuracy of distances - # err3 = ((D3 - D2) ** 2).sum() err4 = ((D4 - D2) ** 2).sum() nf = (D2**2).sum() self.assertLess(err4, nf * 1e-4) @@ -201,14 +168,26 @@ def test_implem_4_ip(self): def test_implem_12(self): self.do_test_rounding(12) - def test_implem_12_ip(self): - self.do_test_rounding(12, faiss.METRIC_INNER_PRODUCT) - def test_implem_14(self): self.do_test_rounding(14) - def test_implem_14_ip(self): - self.do_test_rounding(12, faiss.METRIC_INNER_PRODUCT) + +class TestManyPQSubQuantizers(unittest.TestCase): + def test_m_1024(self): + d = 1024 + ds = datasets.SyntheticDataset(d, 2000, 5000, 50) + pq = faiss.IndexPQ(d, d, 4) + pq.train(ds.get_train()) + pq.add(ds.get_database()) + + fs = faiss.IndexPQFastScan(d, d, 4) + fs.train(ds.get_train()) + fs.add(ds.get_database()) + + Dref, Iref = pq.search(ds.get_queries(), 10) + D, I = fs.search(ds.get_queries(), 10) + agree = (Iref[:, :1] == I[:, :1]).sum() / Iref.shape[0] + self.assertGreater(agree, 0.9) @for_all_simd_levels @@ -241,75 +220,6 @@ def test_aqfastscan(self): np.testing.assert_array_equal(recons, recons2) -######################################################### -# Kernel unit test -######################################################### - - -def reference_accu(codes, LUT): - nq, nsp, is_16 = LUT.shape - nb, nsp_2 = codes.shape - assert is_16 == 16 - assert nsp_2 == nsp // 2 - accu = np.zeros((nq, nb), "uint16") - for i in range(nq): - for j in range(nb): - a = np.uint16(0) - for sp in range(0, nsp, 2): - c = codes[j, sp // 2] - a += LUT[i, sp, c & 15].astype("uint16") - a += LUT[i, sp + 1, c >> 4].astype("uint16") - accu[i, j] = a - return accu - - -# disabled because the function to write to mem is not implemented currently - - -class ThisIsNotATestLoop5: # (unittest.TestCase): - - def do_loop5_kernel(self, nq, bb): - """unit test for the accumulation kernel""" - nb = bb * 32 # databse size - nsp = 24 # number of sub-quantizers - - rs = np.random.RandomState(123) - codes = rs.randint(256, size=(nb, nsp // 2)).astype("uint8") - LUT = rs.randint(256, size=(nq, nsp, 16)).astype("uint8") - accu_ref = reference_accu(codes, LUT) - - def to_A(x): - return faiss.array_to_AlignedTable(x.ravel()) - - sp = faiss.swig_ptr - - LUT_a = faiss.AlignedTableUint8(LUT.size) - faiss.pq4_pack_LUT(nq, nsp, sp(LUT), LUT_a.get()) - - codes_a = faiss.AlignedTableUint8(codes.size) - faiss.pq4_pack_codes(sp(codes), nb, nsp, nb, nb, nsp, codes_a.get()) - - accu_a = faiss.AlignedTableUint16(nq * nb) - accu_a.clear() - faiss.loop5_kernel_accumulate_1_block_to_mem( - nq, nb, nsp, codes_a.get(), LUT_a.get(), accu_a.get() - ) - accu = faiss.AlignedTable_to_array(accu_a).reshape(nq, nb) - np.testing.assert_array_equal(accu_ref, accu) - - def test_11(self): - self.do_loop5_kernel(1, 1) - - def test_21(self): - self.do_loop5_kernel(2, 1) - - def test_12(self): - self.do_loop5_kernel(1, 2) - - def test_22(self): - self.do_loop5_kernel(2, 2) - - ########################################################## # Tests for various IndexPQFastScan implementations ########################################################## @@ -319,7 +229,6 @@ def verify_with_draws(testcase, Dref, Iref, Dnew, Inew): """Verify a list of results where there are draws in the distances (because they are integer).""" np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5) - # here we have to be careful because of draws for i in range(len(Iref)): if np.all(Iref[i] == Inew[i]): continue @@ -352,7 +261,6 @@ def get_index(self, d, metric): index2.implem = 4 Dref, Iref = index2.search(ds.get_queries(), 10) - # check CodePacker codes_ref = faiss.vector_to_array(index.codes) codes_ref = codes_ref.reshape(-1, index.code_size) index2codes = faiss.vector_to_array(index2.codes) @@ -379,11 +287,6 @@ def do_with_params(self, d, params, metric=faiss.METRIC_L2): verify_with_draws(self, Dref, Iref, Dnew, Inew) - def build_fast_scan_index(self, index, params): - index2 = faiss.IndexPQFastScan(index) - index2.implem = 5 - return index2 - @for_all_simd_levels class TestImplem12(TestImplems): @@ -461,9 +364,6 @@ def test_qbs_1_64_k1(self): self.k = 1 self.do_with_params(32, (1, 64)) - def test_1_32_odd_dim(self): - self.do_with_params(30, (1, 32)) - def test_1_64_odd_dim(self): self.do_with_params(30, (1, 64)) @@ -478,9 +378,6 @@ def build_fast_scan_index(self, index, params): index2.implem = 15 return index2 - def test_1_32(self): - self.do_with_params(32, (1, 32)) - def test_2_64(self): self.do_with_params(32, (2, 64)) @@ -540,12 +437,25 @@ def test_constructor(self): data = faiss.serialize_index(index2) index3 = faiss.deserialize_index(data) - self.assertEqual(index2.implem, index3.implem) - D3, I3 = index3.search(ds.get_queries(), 10) np.testing.assert_array_equal(D3, Dnew) np.testing.assert_array_equal(I3, Inew) + def test_reset(self): + d = 32 + ds = datasets.SyntheticDataset(d, 2000, 5000, 200) + + index = faiss.IndexPQFastScan(d, d // 2, 4) + index.train(ds.get_train()) + index.add(ds.get_database()) + + index.reset() + self.assertEqual(index.ntotal, 0) + self.assertEqual(index.ntotal2, 0) + + D, I = index.search(ds.get_queries(), 10) + np.testing.assert_array_equal(I, -1) + class TestAQFastScan(unittest.TestCase): @@ -582,12 +492,6 @@ def subtest_accuracy(self, aq, st, implem, metric_type="L2"): assert abs(recall_ref - recall) < 0.05 - def xx_test_accuracy(self): - for metric in "L2", "IP": - for implem in 0, 12, 13, 14, 15: - self.subtest_accuracy("RQ", "rq", implem, metric) - self.subtest_accuracy("LSQ", "lsq", implem, metric) - def subtest_from_idxaq(self, implem, metric): if metric == "L2": metric_type = faiss.METRIC_L2 @@ -613,11 +517,6 @@ def subtest_from_idxaq(self, implem, metric): recall1 = (I1 == gt).sum() / nq assert abs(recall_ref - recall1) < 0.05 - def xx_test_from_idxaq(self): - for implem in 2, 3, 4: - self.subtest_from_idxaq(implem, "L2") - self.subtest_from_idxaq(implem, "IP") - def subtest_factory(self, aq, M, bbs, st): """ Format: {AQ}{M}x4fs_{bbs}_N{st} @@ -637,18 +536,18 @@ def subtest_factory(self, aq, M, bbs, st): bbs = 32 assert index.bbs == bbs - aq = faiss.downcast_AdditiveQuantizer(index.aq) - assert aq.M == M + q = faiss.downcast_AdditiveQuantizer(index.aq) + assert q.M == M if aq == "LSQ": - assert isinstance(aq, faiss.LocalSearchQuantizer) + assert isinstance(q, faiss.LocalSearchQuantizer) if aq == "RQ": - assert isinstance(aq, faiss.ResidualQuantizer) + assert isinstance(q, faiss.ResidualQuantizer) if st == "lsq": - assert aq.search_type == AQ.ST_norm_lsq2x4 + assert q.search_type == AQ.ST_norm_lsq2x4 if st == "rq": - assert aq.search_type == AQ.ST_norm_rq2x4 + assert q.search_type == AQ.ST_norm_rq2x4 def test_factory(self): self.subtest_factory("LSQ", 16, 64, "lsq") @@ -689,7 +588,7 @@ def add_TestAQFastScan_subset_accuracy(aq, st, implem, metric): for metric in "L2", "IP": - for implem in 0, 12, 13, 14, 15: + for implem in 12, 14: add_TestAQFastScan_subset_accuracy("LSQ", "lsq", implem, metric) add_TestAQFastScan_subset_accuracy("RQ", "rq", implem, metric) @@ -785,3 +684,26 @@ def test_issue_2739(self): 0, ::100 ] np.testing.assert_array_equal(decoded, index.reconstruct(0)[::100]) + + +@for_all_simd_levels +class TestImplemDefault(TestImplems): + """QBS values through the default implementation. Its QBS loop is also + instantiated in the AVX512 TU (the AVX2 fallback and the Zen 4 split + path). AVX512 code reached from the AVX2 path only fails here on a CPU + without AVX512 (or under qemu-x86_64); on other hosts the + symbol-isolation scan is what catches it.""" + + def build_fast_scan_index(self, index, qbs): + index2 = faiss.IndexPQFastScan(index) + index2.qbs = qbs + return index2 + + def test_qbs6(self): + self.do_with_params(32, 0x6) + + def test_qbs34(self): + self.do_with_params(32, 0x34) + + def test_qbs222(self): + self.do_with_params(32, 0x222) diff --git a/thirdparty/faiss/tests/test_fast_scan_distance_to_code.cpp b/thirdparty/faiss/tests/test_fast_scan_distance_to_code.cpp index 258258f64..78fa92a9a 100644 --- a/thirdparty/faiss/tests/test_fast_scan_distance_to_code.cpp +++ b/thirdparty/faiss/tests/test_fast_scan_distance_to_code.cpp @@ -5,7 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#include #include #include #include @@ -32,11 +31,9 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { int nq = 100; int k = 10; - // generate smooth random data for training + database std::vector xb((nb1 + nb2) * d); rand_smooth_vectors((nb1 + nb2), d, xb.data(), 1234); - // build the index via factory std::unique_ptr index( dynamic_cast(index_factory(d, factory_string, metric))); @@ -48,7 +45,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { std::vector xq(nq * d); rand_smooth_vectors(nq, d, xq.data(), 5678); - // search std::vector D0(nq * k); std::vector I0(nq * k); @@ -56,8 +52,8 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { const float* xb2 = xb.data() + d * nb1; std::vector list_nos(nb2); - std::vector dis(nb2); - index->quantizer->search(nb2, xb2, 1, dis.data(), list_nos.data()); + std::vector assign_dis(nb2); + index->quantizer->search(nb2, xb2, 1, assign_dis.data(), list_nos.data()); std::vector codes(nb2 * index->code_size); index->encode_vectors(nb2, xb2, list_nos.data(), codes.data()); @@ -65,7 +61,7 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { std::vector> extra_codes(index->nlist); std::vector> extra_ids(index->nlist); - for (size_t i = 0; i < nb2; i++) { + for (int i = 0; i < nb2; i++) { idx_t list_no = list_nos[i]; extra_ids[list_no].push_back(i + nb1); extra_codes[list_no].insert( @@ -78,7 +74,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { std::unique_ptr scanner( index->get_InvertedListScanner(false, nullptr, nullptr)); - // for each query, find its nprobe nearest lists int nprobe = index->nprobe; std::vector coarse_dis(nq * nprobe); std::vector coarse_ids(nq * nprobe); @@ -103,7 +98,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { const float* query = xq.data() + q * d; scanner->set_query(query); - // loop over probed lists for (int p = 0; p < nprobe; p++) { idx_t list_no = coarse_ids[q * nprobe + p]; if (list_no < 0) { @@ -111,7 +105,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { } scanner->set_list(list_no, coarse_dis[q * nprobe + p]); - // scan extra codes for this list size_t n_extra = extra_ids[list_no].size(); for (size_t j = 0; j < n_extra; j++) { float dis = scanner->distance_to_code( @@ -130,7 +123,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { } } - // reorder from heap order to sorted order if (is_similarity) { minheap_reorder(k, D0q, I0q); } else { @@ -153,7 +145,7 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { std::unordered_set S1(I1q, I1q + k); int ndiff = 0; for (idx_t id : S0) { - if (S1.find(id) == S1.end()) { + if (!S1.contains(id)) { ndiff++; } } @@ -161,7 +153,6 @@ void test_search_and_encode(const char* factory_string, MetricType metric) { } // accept a small amount of discrepancy, because the FastScan look-up tables // are quantized to int8 so not as accurate. - printf("total ndiff=%d / %d\n", ndiff_total, nq * k); EXPECT_LE(ndiff_total, nq * k / 200); } diff --git a/thirdparty/faiss/tests/test_fast_scan_hacc.cpp b/thirdparty/faiss/tests/test_fast_scan_hacc.cpp new file mode 100644 index 000000000..f2329e1b1 --- /dev/null +++ b/thirdparty/faiss/tests/test_fast_scan_hacc.cpp @@ -0,0 +1,129 @@ +/* + * 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. + */ + +#include +#include +#include +#include + +#include + +#include +#include + +namespace { + +using faiss::SIMDLevel; + +struct RestoreSIMD { + SIMDLevel saved = faiss::SIMDConfig::get_level(); + ~RestoreSIMD() { + faiss::SIMDConfig::set_level(saved); + } +}; + +std::vector available_levels() { + std::vector levels; + for (auto level : + {faiss::SIMDConfig::get_level(), + SIMDLevel::NONE, + SIMDLevel::AVX2, + SIMDLevel::AVX512, + SIMDLevel::AVX512_VPOPCNT, + SIMDLevel::ARM_NEON}) { + if (faiss::SIMDConfig::is_simd_level_available(level) && + std::find(levels.begin(), levels.end(), level) == levels.end()) { + levels.push_back(level); + } + } + return levels; +} + +/// Compare accumulate_hacc at every available SIMD level with the exact sums +/// computed from the unpacked codes and 16-bit tables. +void check_hacc(int nq, size_t ntotal, int nsq, bool max_entries, int seed) { + SCOPED_TRACE( + "nq=" + std::to_string(nq) + " ntotal=" + std::to_string(ntotal) + + " nsq=" + std::to_string(nsq)); + std::mt19937 rng(seed); + const size_t ntotal2 = (ntotal + 31) / 32 * 32; + + // flat codes: sub-quantizer 2k in the low nibble of byte k + std::vector codes(ntotal * nsq / 2); + for (auto& c : codes) { + c = rng(); + } + std::vector blocks(ntotal2 * nsq / 2); + faiss::pq4_pack_codes( + codes.data(), ntotal, nsq, ntotal2, 32, nsq, blocks.data()); + + std::vector lut(size_t(nq) * nsq * 16); + for (auto& e : lut) { + e = max_entries ? 65535 : uint16_t(rng()); + } + std::vector packed(size_t(nq) * 2 * nsq * 16); + for (int q = 0; q < nq; q++) { + std::vector lo(nsq * 16), hi(nsq * 16); + for (int i = 0; i < nsq * 16; i++) { + lo[i] = lut[size_t(q) * nsq * 16 + i] & 0xff; + hi[i] = lut[size_t(q) * nsq * 16 + i] >> 8; + } + uint8_t* dst = packed.data() + size_t(q) * 2 * nsq * 16; + faiss::pq4_pack_LUT(1, nsq, lo.data(), dst); + faiss::pq4_pack_LUT(1, nsq, hi.data(), dst + nsq * 16); + } + + std::vector ref(nq * ntotal2, 0); + for (int q = 0; q < nq; q++) { + for (size_t i = 0; i < ntotal; i++) { + int32_t sum = 0; + for (int sq = 0; sq < nsq; sq++) { + const uint8_t byte = codes[i * nsq / 2 + sq / 2]; + const int c = sq % 2 == 0 ? byte & 15 : byte >> 4; + sum += lut[(size_t(q) * nsq + sq) * 16 + c]; + } + ref[q * ntotal2 + i] = sum; + } + } + + RestoreSIMD restore; + for (SIMDLevel level : available_levels()) { + SCOPED_TRACE("level=" + faiss::to_string(level)); + faiss::SIMDConfig::set_level(level); + std::vector accu(nq * ntotal2, -1); + faiss::accumulate_hacc( + nq, ntotal2, nsq, blocks.data(), packed.data(), accu.data()); + // one failure per level, so that a level that fails does not hide + // the others + size_t n_bad = 0, first = 0; + for (int q = 0; q < nq; q++) { + for (size_t i = 0; i < ntotal; i++) { + const size_t j = q * ntotal2 + i; + if (accu[j] != ref[j] && n_bad++ == 0) { + first = j; + } + } + } + EXPECT_EQ(n_bad, 0) << "first at query " << first / ntotal2 + << " element " << first % ntotal2 << ": " + << accu[first] << " instead of " << ref[first]; + } +} + +} // namespace + +TEST(FastScanHacc, exact_sums) { + int seed = 0; + // segment boundaries of the kernels (256 and 512 sub-quantizers) and + // numbers of sub-quantizers that are not a multiple of 4 + for (int nsq : {2, 4, 6, 30, 254, 256, 258, 510, 512, 514, 1024}) { + check_hacc(1, 32, nsq, false, seed++); + check_hacc(3, 70, nsq, false, seed++); + // every entry at 65535, the largest possible sums + check_hacc(1, 32, nsq, true, seed++); + } +} diff --git a/thirdparty/faiss/tests/test_fast_scan_ivf.py b/thirdparty/faiss/tests/test_fast_scan_ivf.py index f48ef6909..bdd9debc8 100644 --- a/thirdparty/faiss/tests/test_fast_scan_ivf.py +++ b/thirdparty/faiss/tests/test_fast_scan_ivf.py @@ -144,9 +144,7 @@ def test_by_residual_L2_v2(self): self.do_test(LUT, bias, nprobe, alt_3d=True) def test_zero_span(self): - # All LUT entries identical => max_span == 0. Before the fix this - # divided by zero, giving a = inf and NaN quantized entries. The guard - # makes a = 0 and keeps the output finite. + # All entries equal: max_span == 0 must give a = 0, not inf/NaN. M, ksub, nprobe = 20, 16, 10 LUT = np.full((M, ksub), 5.0, dtype="float32") LUTq = np.zeros(LUT.shape, dtype="uint8") @@ -171,18 +169,13 @@ def test_zero_span(self): self.assertTrue(np.all(LUTq == 0)) -########################################################## -# Tests for various IndexPQFastScan implementations -########################################################## - - def verify_with_draws(testcase, Dref, Iref, Dnew, Inew): """verify a list of results where there are draws in the distances (because they are integer).""" np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5) # here we have to be careful because of draws for i in range(len(Iref)): - if np.all(Iref[i] == Inew[i]): # easy case + if np.all(Iref[i] == Inew[i]): continue # we can deduce nothing about the latest line skip_dis = Dref[i, -1] @@ -214,14 +207,10 @@ class TestIVFImplem1(unittest.TestCase): """Verify implem 1 (search from original invlists) against IndexIVFPQ""" - def do_test( - self, by_residual, metric_type=faiss.METRIC_L2, use_precomputed_table=0 - ): + def do_test(self, by_residual, metric_type=faiss.METRIC_L2): ds = datasets.SyntheticDataset(32, 2000, 5000, 1000) index = faiss.index_factory(32, "IVF32,PQ16x4np", metric_type) - index.use_precomputed_table - index.use_precomputed_table = use_precomputed_table index.train(ds.get_train()) index.add(ds.get_database()) index.nprobe = 4 @@ -231,7 +220,6 @@ def do_test( index2 = faiss.IndexIVFPQFastScan(index) index2.implem = 1 Db, Ib = index2.search(ds.get_queries(), 10) - # self.assertLess((Ia != Ib).sum(), Ia.size * 0.005) np.testing.assert_array_equal(Ia, Ib) np.testing.assert_almost_equal(Da, Db, decimal=5) @@ -241,9 +229,6 @@ def test_no_residual(self): def test_by_residual(self): self.do_test(True) - def test_by_residual_no_precomputed(self): - self.do_test(True, use_precomputed_table=-1) - def test_no_residual_ip(self): self.do_test(False, faiss.METRIC_INNER_PRODUCT) @@ -335,8 +320,6 @@ def test_equiv_pq(self): np.testing.assert_array_equal(Iref, Inew) np.testing.assert_allclose(Dref, Dnew, rtol=1e-5) - # test encode and decode - np.testing.assert_array_equal( index_pq.sa_encode(xq), index2.sa_encode(xq) ) @@ -346,11 +329,6 @@ def test_equiv_pq(self): index2.sa_decode(index2.sa_encode(xq)), ) - np.testing.assert_array_equal( - ((index_pq.sa_decode(index_pq.sa_encode(xq)) - xq) ** 2).sum(1), - ((index2.sa_decode(index2.sa_encode(xq)) - xq) ** 2).sum(1), - ) - def test_equiv_pq_encode_decode(self): ds = datasets.SyntheticDataset(32, 1000, 200, 10) xq = ds.get_queries() @@ -369,15 +347,6 @@ def test_equiv_pq_encode_decode(self): index_ivfpqfs.sa_decode(index_ivfpqfs.sa_encode(xq)), ) - np.testing.assert_array_equal( - ((index_ivfpq.sa_decode(index_ivfpq.sa_encode(xq)) - xq) ** 2).sum( - 1 - ), - ( - (index_ivfpqfs.sa_decode(index_ivfpqfs.sa_encode(xq)) - xq) ** 2 - ).sum(1), - ) - class TestIVFImplem12(unittest.TestCase): @@ -387,8 +356,6 @@ def do_test(self, by_residual, metric=faiss.METRIC_L2, d=32, nq=200): ds = datasets.SyntheticDataset(d, 2000, 5000, nq) index = faiss.index_factory(d, f"IVF32,PQ{d//2}x4np", metric) - # force coarse quantizer - # index.quantizer.add(np.zeros((1, 32), dtype='float32')) index.by_residual = by_residual index.train(ds.get_train()) index.add(ds.get_database()) @@ -436,25 +403,12 @@ def test_no_residual_odd_dim(self): def test_by_residual_odd_dim(self): self.do_test(True, d=30) - # testing single query def test_no_residual_single_query(self): self.do_test(False, nq=1) def test_by_residual_single_query(self): self.do_test(True, nq=1) - def test_no_residual_ip_single_query(self): - self.do_test(False, metric=faiss.METRIC_INNER_PRODUCT, nq=1) - - def test_by_residual_ip_single_query(self): - self.do_test(True, metric=faiss.METRIC_INNER_PRODUCT, nq=1) - - def test_no_residual_odd_dim_single_query(self): - self.do_test(False, d=30, nq=1) - - def test_by_residual_odd_dim_single_query(self): - self.do_test(True, d=30, nq=1) - @for_all_simd_levels class TestIVFImplem10(TestIVFImplem12): @@ -484,12 +438,11 @@ class TestIVFImplem15(TestIVFImplem12): @for_all_simd_levels class TestAdd(unittest.TestCase): - def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32, bbs=32): - bbs = 32 + def do_test(self, d=32, bbs=32): ds = datasets.SyntheticDataset(d, 2000, 5000, 200) - index = faiss.index_factory(d, f"IVF32,PQ{d//2}x4np", metric) - index.by_residual = by_residual + index = faiss.index_factory(d, f"IVF32,PQ{d//2}x4np") + index.by_residual = False index.train(ds.get_train()) index.nprobe = 4 @@ -508,8 +461,6 @@ def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32, bbs=32): np.testing.assert_array_equal(Dref, Dnew) np.testing.assert_array_equal(Iref, Inew) - # direct verification of code content. Not sure the test is correct - # if codes are shuffled. for list_no in range(32): ref_ids, ref_codes = get_invlist(index3.invlists, list_no) new_ids, new_codes = get_invlist(index2.invlists, list_no) @@ -536,8 +487,7 @@ def test_bbs64(self): @for_all_simd_levels class TestTraining(unittest.TestCase): - def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32, bbs=32): - bbs = 32 + def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32): ds = datasets.SyntheticDataset(d, 2000, 5000, 200) index = faiss.index_factory(d, f"IVF32,PQ{d//2}x4np", metric) @@ -548,7 +498,7 @@ def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32, bbs=32): Dref, Iref = index.search(ds.get_queries(), 10) index2 = faiss.IndexIVFPQFastScan( - index.quantizer, d, 32, d // 2, 4, metric, bbs + index.quantizer, d, 32, d // 2, 4, metric, 32 ) index2.by_residual = by_residual index2.train(ds.get_train()) @@ -571,7 +521,6 @@ def do_test(self, by_residual=False, metric=faiss.METRIC_L2, d=32, bbs=32): self.assertGreater(m3[1], ref_m3[1] * 0.99) self.assertGreater(m3[2], ref_m3[2] * 0.99) - # Test I/O data = faiss.serialize_index(index2) index3 = faiss.deserialize_index(data) D3, I3 = index3.search(ds.get_queries(), 10) @@ -600,8 +549,6 @@ def test_by_residual_odd_dim(self): @for_all_simd_levels class TestReconstruct(unittest.TestCase): - """test reconstruct and sa_encode / sa_decode - (also for a few additive quantizer variants)""" def do_test(self, by_residual=False): d = 32 @@ -617,21 +564,12 @@ def do_test(self, by_residual=False): index.train(ds.get_train()) index.add(ds.get_database()) - # Test reconstruction - v123 = index.reconstruct(123) # single id - v120_10 = index.reconstruct_n(120, 10) - np.testing.assert_array_equal(v120_10[3], v123) - v120_10 = index.reconstruct_batch(np.arange(120, 130)) - np.testing.assert_array_equal(v120_10[3], v123) - - # Test original list reconstruction index.orig_invlists = faiss.ArrayInvertedLists( index.nlist, index.code_size ) index.reconstruct_orig_invlists() assert index.orig_invlists.compute_ntotal() == index.ntotal - # compare with non fast-scan index index2 = faiss.IndexIVFPQ(index.quantizer, d, 50, d // 2, 4, metric) index2.by_residual = by_residual index2.pq = index.pq @@ -756,57 +694,7 @@ def subtest_accuracy(self, aq, st, by_residual, implem, metric_type="L2"): assert abs(recall_ref - recall1) < 0.051 - def xx_test_accuracy(self): - # generated programatically below - for metric in "L2", "IP": - for byr in True, False: - for implem in 0, 10, 11, 12, 13, 14, 15: - self.subtest_accuracy("RQ", "rq", byr, implem, metric) - self.subtest_accuracy("LSQ", "lsq", byr, implem, metric) - - def subtest_rescale_accuracy(self, aq, st, by_residual, implem): - """ - we set norm_scale to 2 and compare it with IndexIVFAQ - """ - nlist, d = 16, 8 - ds = datasets.SyntheticDataset(d, 1000, 1000, 500) - gt = ds.get_groundtruth(k=1) - - metric = faiss.METRIC_L2 - postfix1 = "_Nqint8" - postfix2 = f"_N{st}2x4" - - index = faiss.index_factory(d, f"IVF{nlist},{aq}3x4{postfix1}", metric) - index.by_residual = by_residual - index.train(ds.get_train()) - index.add(ds.get_database()) - index.nprobe = 16 - Dref, Iref = index.search(ds.get_queries(), 1) - - indexfs = faiss.index_factory( - d, f"IVF{nlist},{aq}3x4fs_32{postfix2}", metric - ) - indexfs.by_residual = by_residual - indexfs.norm_scale = 2 - indexfs.train(ds.get_train()) - indexfs.add(ds.get_database()) - indexfs.nprobe = 16 - indexfs.implem = implem - D1, I1 = indexfs.search(ds.get_queries(), 1) - - nq = Iref.shape[0] - recall_ref = (Iref == gt).sum() / nq - recall1 = (I1 == gt).sum() / nq - - assert abs(recall_ref - recall1) < 0.05 - - def xx_test_rescale_accuracy(self): - for byr in True, False: - for implem in 0, 10, 11, 12, 13, 14, 15: - self.subtest_accuracy("RQ", "rq", byr, implem, "L2") - self.subtest_accuracy("LSQ", "lsq", byr, implem, "L2") - - def subtest_from_ivfaq(self, implem): + def test_from_ivfaq(self): d = 8 ds = datasets.SyntheticDataset(d, 1000, 2000, 1000, metric="IP") gt = ds.get_groundtruth(k=1) @@ -826,10 +714,6 @@ def subtest_from_ivfaq(self, implem): recall1 = (I1 == gt).sum() / nq assert abs(recall_ref - recall1) < 0.02 - def test_from_ivfaq(self): - for implem in 0, 1, 2: - self.subtest_from_ivfaq(implem) - def subtest_factory(self, aq, M, bbs, st, r="r"): """ Format: IVF{nlist},{AQ}{M}x4fs{r}_{bbs}_N{st} @@ -913,27 +797,14 @@ def add_TestIVFAQFastScan_subtest_accuracy( ) -def add_TestIVFAQFastScan_subtest_rescale_accuracy(aq, st, by_residual, implem): - setattr( - TestIVFAQFastScan, - f"test_rescale_accuracy_{aq}_implem{implem}_residual{by_residual}", - lambda self: self.subtest_rescale_accuracy(aq, st, by_residual, implem), - ) - - for byr in True, False: - for implem in 0, 10, 11, 12, 13, 14, 15: + for implem in 10, 12, 14: for mt in "L2", "IP": add_TestIVFAQFastScan_subtest_accuracy("RQ", "rq", byr, implem, mt) add_TestIVFAQFastScan_subtest_accuracy( "LSQ", "lsq", byr, implem, mt ) - add_TestIVFAQFastScan_subtest_rescale_accuracy( - "LSQ", "lsq", byr, implem - ) - add_TestIVFAQFastScan_subtest_rescale_accuracy("RQ", "rq", byr, implem) - # Apply decorator after dynamic method generation. TestIVFAQFastScan = for_all_simd_levels(TestIVFAQFastScan) @@ -1016,11 +887,8 @@ def test_search_params(self): index.train(ds.get_train()) index.add(ds.get_database()) - index.nprobe index.nprobe = 4 Dref4, Iref4 = index.search(ds.get_queries(), 10) - # index.nprobe = 16 - # Dref16, Iref16 = index.search(ds.get_queries(), 10) index.nprobe = 1 Dnew4, Inew4 = index.search( @@ -1093,19 +961,6 @@ def _build_index(self): index.add(ds.get_database()) return ds, index - def test_fastscan_defaults_roundtrip(self): - ds, index = self._build_index() - k = 10 - - params = faiss.SearchParametersIVF() - params.nprobe = 4 - # defaults should not raise - D_p, I_p = index.search(ds.get_queries(), k, params=params) - # and should match a no-params search with the same nprobe. - index.nprobe = 4 - D_ref, I_ref = index.search(ds.get_queries(), k) - np.testing.assert_array_equal(I_p, I_ref) - def test_fastscan_max_lists_num_caps_probes(self): ds, index = self._build_index() # implem auto-selection should pick 10 when max_lists_num is set @@ -1119,8 +974,7 @@ def test_fastscan_max_lists_num_caps_probes(self): params_cap.max_lists_num = 2 D_cap, I_cap = index.search(ds.get_queries(), 10, params=params_cap) - # Tight cap should produce no more valid hits than full nprobe and - # at least one query should differ (unless data is unusually small). + # A cap can only add misses. miss_full = np.sum(I_full == -1) miss_cap = np.sum(I_cap == -1) self.assertLessEqual(miss_full, miss_cap) @@ -1224,16 +1078,3 @@ def test_fastscan_range_explicit_implem_12_rejects_max_empty(self): params.max_empty_result_buckets = 2 with self.assertRaises(RuntimeError): index.range_search(ds.get_queries()[:1], 1.0, params=params) - - def test_fastscan_fields_exposed(self): - p = faiss.SearchParametersIVF() - self.assertEqual(p.max_lists_num, 0) - self.assertIs(p.ensure_topk_full, False) - self.assertEqual(p.max_empty_result_buckets, 0) - p.max_lists_num = 7 - p.ensure_topk_full = True - p.max_empty_result_buckets = 3 - self.assertEqual(p.max_lists_num, 7) - self.assertIs(p.ensure_topk_full, True) - self.assertEqual(p.max_empty_result_buckets, 3) - self.assertIs(faiss.SearchParametersIVF, faiss.IVFSearchParameters) diff --git a/thirdparty/faiss/tests/test_fastscan_filter.cpp b/thirdparty/faiss/tests/test_fastscan_filter.cpp deleted file mode 100644 index 00e5df382..000000000 --- a/thirdparty/faiss/tests/test_fastscan_filter.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -using namespace faiss; - -namespace { - -constexpr int d = 32; -constexpr size_t nt = 5000; -constexpr size_t nb = 1000; -constexpr size_t nq = 20; - -std::vector make_data(size_t n, int64_t seed) { - std::vector data(n * d); - rand_smooth_vectors(n, d, data.data(), seed); - return data; -} - -/************************************************************* - * Helper: test filtered search on a fastscan IVF index. - * - * Primary check: every returned ID is in the allowed set. - * Secondary check: results have reasonable overlap with Flat - * baseline (loose threshold since PQ is approximate). - *************************************************************/ - -void test_filtered_search( - const char* fs_index_key, - MetricType metric, - const size_t k, - IDSelector& sel, - const std::unordered_set& allowed_ids, - const size_t db_size = nb) { - auto xt = make_data(nt, 1234); - auto xb = make_data(db_size, 4567); - auto xq = make_data(nq, 7890); - - // Build fastscan index - std::unique_ptr fs_index(index_factory(d, fs_index_key, metric)); - fs_index->train(nt, xt.data()); - fs_index->add(db_size, xb.data()); - - // Search fastscan with selector - SearchParametersIVF params; - params.sel = &sel; - params.nprobe = 8; - - std::vector Dfs(nq * k); - std::vector Ifs(nq * k); - - fs_index->search(nq, xq.data(), k, Dfs.data(), Ifs.data(), ¶ms); - - // Primary check: all results are in the allowed set (or -1) - for (size_t i = 0; i < nq * k; i++) { - if (Ifs[i] >= 0) { - EXPECT_TRUE(allowed_ids.count(Ifs[i]) > 0) - << "Fastscan returned id " << Ifs[i] - << " which is not in the allowed set"; - } - } - - // Secondary check: if allowed set is large enough, we should get - // some valid results (not all -1) - if (allowed_ids.size() > k) { - size_t valid_count = 0; - for (size_t i = 0; i < nq * k; i++) { - if (Ifs[i] >= 0) - valid_count++; - } - EXPECT_GT(valid_count, 0) << "Expected some valid results"; - } -} - -/************************************************************* - * Test: IDSelectorBatch with fastscan (batch of allowed IDs) - *************************************************************/ - -// Both tests are needed, because one tests CMax, -// and another tests CMin. - -TEST(TestFastScanFilter, IVFPQfs_Batch_L2) { - std::vector subset; - for (idx_t i = 0; i < nb; i += 3) { // ~333 out of 1000 - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed); -} - -TEST(TestFastScanFilter, IVFPQfs_Batch_IP) { - std::vector subset; - for (idx_t i = 0; i < nb; i += 3) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search( - "IVF32,PQ4x4fs", METRIC_INNER_PRODUCT, 10, sel, allowed); -} - -/************************************************************* - * Test: k=1 (SingleResultHandler path) and k=40 (ReservoirHandler) - *************************************************************/ - -TEST(TestFastScanFilter, IVFPQfs_K1) { - std::vector subset; - for (idx_t i = 0; i < nb; i += 2) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 1, sel, allowed); -} - -TEST(TestFastScanFilter, IVFPQfs_K40) { - std::vector subset; - for (idx_t i = 0; i < nb; i += 2) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 40, sel, allowed); -} - -/************************************************************* - * Test: IDSelectorNot that excludes entire blocks (IDs 0-31, 64-95, etc.) - * This specifically tests the block-skip optimization. - *************************************************************/ - -TEST(TestFastScanFilter, BlockSkip_WholeBlocks) { - // Exclude blocks 0 (ids 0-31) and 2 (ids 64-95) - std::vector excluded; - for (idx_t i = 0; i < 32; i++) { - excluded.push_back(i); - } - for (idx_t i = 64; i < 96; i++) { - excluded.push_back(i); - } - - // Allowed = everything NOT in excluded - std::unordered_set allowed; - std::unordered_set excluded_set(excluded.begin(), excluded.end()); - for (idx_t i = 0; i < nb; i++) { - if (excluded_set.count(i) == 0) { - allowed.insert(i); - } - } - - IDSelectorBatch inner_sel(excluded.size(), excluded.data()); - IDSelectorNot sel(&inner_sel); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed); -} - -/************************************************************* - * Test: Partial block filtering (exclude some IDs within a block) - *************************************************************/ - -TEST(TestFastScanFilter, BlockSkip_PartialBlock) { - // Exclude only a few IDs from the first block (0-31) - std::vector excluded = {5, 10, 20, 31}; - std::unordered_set excluded_set(excluded.begin(), excluded.end()); - - std::unordered_set allowed; - for (idx_t i = 0; i < nb; i++) { - if (excluded_set.count(i) == 0) { - allowed.insert(i); - } - } - - IDSelectorBatch inner_sel(excluded.size(), excluded.data()); - IDSelectorNot sel(&inner_sel); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed); -} - -/************************************************************* - * Test: Empty selector (nothing accepted) -> all results -1 - *************************************************************/ - -TEST(TestFastScanFilter, EmptySelector) { - auto xt = make_data(nt, 1234); - auto xb = make_data(nb, 4567); - auto xq = make_data(nq, 7890); - - std::unique_ptr index(index_factory(d, "IVF32,PQ4x4fs", METRIC_L2)); - index->train(nt, xt.data()); - index->add(nb, xb.data()); - - // Empty batch selector: accepts nothing - std::vector empty_subset; - IDSelectorBatch sel(0, empty_subset.data()); - - size_t k = 10; - std::vector D(nq * k); - std::vector I(nq * k); - - SearchParametersIVF params; - params.sel = &sel; - params.nprobe = 4; - index->search(nq, xq.data(), k, D.data(), I.data(), ¶ms); - - // All results should be -1 (nothing matches) - for (size_t i = 0; i < nq * k; i++) { - EXPECT_EQ(I[i], -1) - << "Expected -1 at position " << i << " but got " << I[i]; - } -} - -/************************************************************* - * Test: ntotal not a multiple of 32 - * Tests the min(32, ntotal - j0) boundary in block-skip check. - *************************************************************/ - -TEST(TestFastScanFilter, NonAlignedNtotal_50) { - std::vector subset; - for (idx_t i = 0; i < 50; i += 2) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed, 50); -} - -TEST(TestFastScanFilter, NonAlignedNtotal_77) { - std::vector subset; - for (idx_t i = 0; i < 77; i += 2) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed, 77); -} - -TEST(TestFastScanFilter, NonAlignedNtotal_150) { - std::vector subset; - for (idx_t i = 0; i < 150; i += 3) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed, 150); -} - -/************************************************************* - * Test: IDSelectorRange with fastscan - *************************************************************/ - -TEST(TestFastScanFilter, IVFPQfs_Range) { - std::unordered_set allowed; - for (idx_t i = 100; i < 500; i++) { - allowed.insert(i); - } - - IDSelectorRange sel(100, 500); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed); -} - -/************************************************************* - * Test: Heavy filtering (>90% excluded) - block-skip should - * skip most blocks entirely. - *************************************************************/ - -TEST(TestFastScanFilter, HeavyFiltering) { - // Allow only ~5% of vectors - std::vector subset; - for (idx_t i = 0; i < nb; i += 20) { - subset.push_back(i); - } - - std::unordered_set allowed(subset.begin(), subset.end()); - IDSelectorBatch sel(subset.size(), subset.data()); - - test_filtered_search("IVF32,PQ4x4fs", METRIC_L2, 10, sel, allowed); -} - -} // namespace diff --git a/thirdparty/faiss/tests/test_fastscan_filter.py b/thirdparty/faiss/tests/test_fastscan_filter.py index afc7ae731..9c8b28445 100644 --- a/thirdparty/faiss/tests/test_fastscan_filter.py +++ b/thirdparty/faiss/tests/test_fastscan_filter.py @@ -16,17 +16,6 @@ @for_all_simd_levels class TestFastScanFiltering(unittest.TestCase): - """ - Test IDSelector filtering on IVF fast_scan indexes. - - The PR adds block-skip filtering to the fast_scan accumulate loops: - before processing each 32-vector block, it checks if all vectors - in the block are filtered out by the IDSelector, and skips the - block entirely if so. - - These tests verify that filtered results only contain allowed IDs. - Only IVF-based fastscan indexes support SearchParameters with sel. - """ def do_test_filter( self, @@ -101,11 +90,6 @@ def do_test_filter( return Ifs - # ------- IVFPQFastScan tests ------- - - def test_IVFPQfs_batch_L2(self): - self.do_test_filter("IVF32,PQ4x4fs", "batch", faiss.METRIC_L2) - def test_IVFPQfs_batch_IP(self): self.do_test_filter( "IVF32,PQ4x4fs", "batch", faiss.METRIC_INNER_PRODUCT @@ -126,229 +110,3 @@ def test_IVFPQfs_empty_selector(self): """Empty selector accepts nothing -> all results -1""" Ifs = self.do_test_filter("IVF32,PQ4x4fs", "empty") np.testing.assert_array_equal(Ifs, -1) - - # ------- Different k values (different handler paths) ------- - - def test_IVFPQfs_k1(self): - """k=1 -> SingleResultHandler path""" - self.do_test_filter("IVF32,PQ4x4fs", "batch", k=1) - - def test_IVFPQfs_k40(self): - """k=40 -> ReservoirHandler path""" - self.do_test_filter("IVF32,PQ4x4fs", "batch", k=40) - - # ------- Non-aligned ntotal ------- - - def test_IVFPQfs_ntotal_50(self): - """ntotal=50, not a multiple of 32""" - self.do_test_filter("IVF32,PQ4x4fs", "batch", nb=50) - - def test_IVFPQfs_ntotal_77(self): - """ntotal=77, partial last block""" - self.do_test_filter("IVF32,PQ4x4fs", "batch", nb=77) - - def test_IVFPQfs_ntotal_150(self): - """ntotal=150, not a multiple of 32""" - self.do_test_filter("IVF32,PQ4x4fs", "batch", nb=150) - - -@for_all_simd_levels -class TestBlockSkipConsistency(unittest.TestCase): - """ - Test that block-skip filtering produces consistent results - across different filter configurations on fastscan IVF indexes. - """ - - def test_consistency_with_ivfpq(self): - """ - Compare IVFPQFastScan filtered results with IVFPQ (non-fastscan) - filtered results. Both should only return allowed IDs. - """ - d = 32 - ds = datasets.SyntheticDataset(d, 2000, 500, 20) - - rs = np.random.RandomState(42) - subset = rs.choice(500, 150, replace=False).astype("int64") - sel = faiss.IDSelectorBatch(subset) - allowed = set(subset.tolist()) - - # FastScan index - index_fs = faiss.index_factory(d, "IVF32,PQ4x4fs") - index_fs.train(ds.get_train()) - index_fs.add(ds.get_database()) - - # Non-fastscan PQ index - index_pq = faiss.index_factory(d, "IVF32,PQ4x4np") - index_pq.train(ds.get_train()) - index_pq.add(ds.get_database()) - - k = 10 - params = faiss.SearchParametersIVF(sel=sel, nprobe=8) - - Dfs, Ifs = index_fs.search(ds.get_queries(), k, params=params) - Dpq, Ipq = index_pq.search(ds.get_queries(), k, params=params) - - # Both should only return allowed IDs - for q in range(ds.nq): - for j in range(k): - if Ifs[q, j] >= 0: - self.assertIn(int(Ifs[q, j]), allowed) - if Ipq[q, j] >= 0: - self.assertIn(int(Ipq[q, j]), allowed) - - def test_blockskip_consistency_with_ivfpq(self): - """ - Compare IVFPQFastScan vs IVFPQ (non-fastscan) when using - IDSelectorNot that excludes entire 32-vector blocks. - This specifically validates the block-skip optimization - against a baseline that doesn't have block-skip logic. - """ - d = 32 - nb = 500 - ds = datasets.SyntheticDataset(d, 2000, nb, 20) - - # Exclude entire blocks: IDs 0-31 and 64-95 - excluded = np.concatenate( - [ - np.arange(0, 32, dtype="int64"), - np.arange(64, 96, dtype="int64"), - ] - ) - inner_sel = faiss.IDSelectorBatch(excluded) - sel = faiss.IDSelectorNot(inner_sel) - allowed = {i for i in range(nb) if i not in excluded} - - # FastScan index - index_fs = faiss.index_factory(d, "IVF32,PQ4x4fs") - index_fs.train(ds.get_train()) - index_fs.add(ds.get_database()) - - # Non-fastscan PQ index (no block-skip logic) - index_pq = faiss.index_factory(d, "IVF32,PQ4x4np") - index_pq.train(ds.get_train()) - index_pq.add(ds.get_database()) - - k = 10 - params = faiss.SearchParametersIVF(sel=sel, nprobe=8) - - Dfs, Ifs = index_fs.search(ds.get_queries(), k, params=params) - Dpq, Ipq = index_pq.search(ds.get_queries(), k, params=params) - - # Both should only return allowed IDs - for q in range(ds.nq): - for j in range(k): - if Ifs[q, j] >= 0: - self.assertIn( - int(Ifs[q, j]), - allowed, - f"FastScan q={q} j={j}: id {Ifs[q, j]} is excluded", - ) - if Ipq[q, j] >= 0: - self.assertIn( - int(Ipq[q, j]), - allowed, - f"IVFPQ q={q} j={j}: id {Ipq[q, j]} is excluded", - ) - - def test_partial_vs_whole_block_filter(self): - """ - Excluding the same set of IDs via two identical IDSelectorNot - configurations should produce identical results. - """ - d = 32 - ds = datasets.SyntheticDataset(d, 2000, 200, 10) - - index = faiss.index_factory(d, "IVF32,PQ4x4fs") - index.train(ds.get_train()) - index.add(ds.get_database()) - - # Exclude the first 32 elements (whole block) - excluded = np.arange(0, 32, dtype="int64") - sel1 = faiss.IDSelectorNot(faiss.IDSelectorBatch(excluded)) - sel2 = faiss.IDSelectorNot(faiss.IDSelectorBatch(excluded)) - - k = 10 - params1 = faiss.SearchParametersIVF(sel=sel1, nprobe=8) - params2 = faiss.SearchParametersIVF(sel=sel2, nprobe=8) - - D1, I1 = index.search(ds.get_queries(), k, params=params1) - D2, I2 = index.search(ds.get_queries(), k, params=params2) - - # Results should be identical - np.testing.assert_array_equal(I1, I2) - np.testing.assert_array_almost_equal(D1, D2, decimal=5) - - def test_heavy_filtering(self): - """ - With >90% of vectors filtered, block-skip should skip most blocks. - Verify correctness under heavy filtering. - """ - d = 32 - ds = datasets.SyntheticDataset(d, 2000, 1000, 20) - - index = faiss.index_factory(d, "IVF32,PQ4x4fs") - index.train(ds.get_train()) - index.add(ds.get_database()) - - # Allow only ~5% of vectors - rs = np.random.RandomState(99) - subset = rs.choice(1000, 50, replace=False).astype("int64") - sel = faiss.IDSelectorBatch(subset) - allowed = set(subset.tolist()) - - k = 10 - params = faiss.SearchParametersIVF(sel=sel, nprobe=16) - Dfs, Ifs = index.search(ds.get_queries(), k, params=params) - - # All fastscan results must be in allowed set - for q in range(ds.nq): - for j in range(k): - idx = int(Ifs[q, j]) - if idx >= 0: - self.assertIn(idx, allowed) - - -@for_all_simd_levels -class TestFastScanRangeSearchFilter(unittest.TestCase): - """Test range_search with IDSelector on fastscan IVF indexes.""" - - def test_range_search_filtered(self): - """Range search with IDSelector should only return allowed IDs.""" - d = 32 - ds = datasets.SyntheticDataset(d, 2000, 500, 10) - - index = faiss.index_factory(d, "IVF32,PQ4x4fs") - index.train(ds.get_train()) - index.add(ds.get_database()) - - # Unfiltered range search to find a reasonable radius - Dref, _ = index.search(ds.get_queries(), 10) - radius = float(Dref.max()) * 1.5 - - rs = np.random.RandomState(123) - subset = rs.choice(500, 150, replace=False).astype("int64") - sel = faiss.IDSelectorBatch(subset) - allowed = set(subset.tolist()) - - params = faiss.SearchParametersIVF(sel=sel, nprobe=8) - - try: - lims, D, I = index.range_search( - ds.get_queries(), radius, params=params - ) - - # All returned IDs should be in the allowed set - for idx in I: - if idx >= 0: - self.assertIn( - int(idx), - allowed, - f"Range search returned id {idx} not in allowed set", - ) - except RuntimeError: - # range_search may not be supported for all fastscan variants - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/thirdparty/faiss/tests/test_fastscan_perf.cpp b/thirdparty/faiss/tests/test_fastscan_perf.cpp index 05a12eb97..8e7c3bed1 100644 --- a/thirdparty/faiss/tests/test_fastscan_perf.cpp +++ b/thirdparty/faiss/tests/test_fastscan_perf.cpp @@ -21,18 +21,15 @@ #include TEST(TestFastScan, knnVSrange) { - // small vectors and database int d = 64; size_t nb = 4000; - // ivf centroids size_t nlist = 4; // more than 2 threads to surface // problems related to multi-threading omp_set_num_threads(8); - // random database, also used as queries std::vector database(nb * d); std::mt19937 rng; std::uniform_real_distribution<> distrib; @@ -40,7 +37,6 @@ TEST(TestFastScan, knnVSrange) { database[i] = distrib(rng); } - // build index faiss::IndexFlatL2 coarse_quantizer(d); faiss::IndexIVFPQFastScan index( &coarse_quantizer, d, nlist, d / 2, 4, faiss::METRIC_L2, 32); diff --git a/thirdparty/faiss/tests/test_flat_panorama.py b/thirdparty/faiss/tests/test_flat_panorama.py index 59bc2220f..c9136fae1 100644 --- a/thirdparty/faiss/tests/test_flat_panorama.py +++ b/thirdparty/faiss/tests/test_flat_panorama.py @@ -3,16 +3,7 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Comprehensive test suite for IndexFlatPanorama. - -Panorama is an adaptation of IndexFlat that uses level-oriented storage -and progressive filtering with Cauchy-Schwarz bounds to achieve significant -speedups (up to 45x when combined with PCA or Cayley transforms) with zero -loss in accuracy. - -Paper: https://www.arxiv.org/pdf/2510.00566 -""" +"""Panorama paper: https://www.arxiv.org/pdf/2510.00566""" import unittest @@ -25,13 +16,8 @@ @for_all_simd_levels class TestIndexFlatPanorama(unittest.TestCase): - """Test Suite for IndexFlatPanorama.""" - - # Metrics to test METRICS = [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT] - # Helper methods for index creation and data generation - def generate_data(self, d, nt, nb, nq, seed=42): ds = SyntheticDataset(d, nt, nb, nq, seed=seed) return ds.get_train(), ds.get_database(), ds.get_queries() @@ -45,7 +31,6 @@ def create_flat(self, d, xb=None, metric=faiss.METRIC_L2): def create_panorama( self, d, nlevels, xb=None, batch_size=128, metric=faiss.METRIC_L2 ): - """Create and initialize IndexFlatPanorama.""" index = faiss.IndexFlatPanorama(d, metric, nlevels, batch_size) if xb is not None: index.add(xb) @@ -57,28 +42,12 @@ def assert_search_results_equal( I_regular, D_panorama, I_panorama, - rtol=1e-5, - atol=1e-4, ): - # The reference IndexFlat kernel is SIMD-dispatched, so its float - # reduction order changes with the runtime SIMD level (wide FMA under - # AVX512_SPR), while the Panorama kernel is compiled once at baseline - # and uses the algebraically equivalent a * a + b * b - 2(a * b) - # decomposition instead of (a - b) * (a - b). Both are exact but round - # differently, so near-tied neighbors can swap order. Compare with the - # tie-aware kNN comparator: distances must match within tolerance and - # ids only need to agree as sets within each distance tie-group. This is - # variant-agnostic (NONE / AVX2 / AVX512 / AVX512_SPR) rather than tuned - # to one dispatch level's gap. - np.testing.assert_allclose( - D_regular, - D_panorama, - rtol=rtol, - atol=atol, - err_msg="Distances mismatch", - ) + # The reference IndexFlat kernel is SIMD-dispatched while Panorama + # computes a * a + b * b - 2 * a * b at baseline, so the two round + # differently and near-tied neighbors can swap: compare tie-aware. check_ref_knn_with_draws( - D_regular, I_regular, D_panorama, I_panorama, rtol=rtol + D_regular, I_regular, D_panorama, I_panorama, rtol=1e-5 ) def assert_range_results_equal( @@ -111,48 +80,7 @@ def assert_range_results_equal( dist_reg[sort_reg], dist_pan[sort_pan], rtol=1e-5 ) - # Core functionality tests - - def test_exact_match_with_flat(self): - """Core test: Panorama must return identical results to IndexFlat""" - d, nb, nt, nq, nlevels, k = 128, 50000, 60000, 10, 8, 20 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=42) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - def test_exact_match_with_flat_medium(self): - """Core test: Medium scale version""" - d, nb, nt, nq, nlevels, k = 64, 10000, 15000, 10, 4, 10 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=42) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_range_search(self): - """Test range search returns correct results within radius""" d, nb, nt, nq, nlevels = 128, 50000, 75000, 10, 8 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=123) @@ -169,23 +97,11 @@ def test_range_search(self): xq, radius ) - is_valid = ( - (D_pan <= radius) - if metric == faiss.METRIC_L2 - else (D_pan >= radius) - ) - self.assertTrue( - np.all(is_valid), - f"Some distances exceed radius={radius}", - ) self.assert_range_results_equal( lims_reg, D_reg, I_reg, lims_pan, D_pan, I_pan, nq ) - # Parameter variation tests - def test_different_n_levels(self): - """Test correctness with various n_levels parameter values""" d, nb, nt, nq, k = 128, 25000, 40000, 10, 15 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=456) @@ -212,7 +128,6 @@ def test_different_n_levels(self): faiss.omp_set_num_threads(nt) def test_uneven_dimension_division(self): - """Test when n_levels doesn't evenly divide dimension""" test_cases = [(65, 4), (63, 8), (100, 7)] for metric in self.METRICS: @@ -233,48 +148,7 @@ def test_uneven_dimension_division(self): D_regular, I_regular, D_panorama, I_panorama ) - def test_single_level(self): - """Test edge case with n_levels=1""" - d, nb, nt, nq, nlevels, k = 32, 500, 700, 10, 1, 5 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=333) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - def test_multiple_levels_small_dimension(self): - """Test edge case: more levels than dimension naturally supports""" - d, nb, nt, nq, nlevels, k = 16, 200, 300, 10, 8, 5 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=1212) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - # ID selector tests - def test_id_selector_range(self): - """Test ID filtering with range selector""" d, nb, nt, nq, nlevels, k = 128, 80000, 120000, 500, 8, 20 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=321) @@ -295,74 +169,10 @@ def test_id_selector_range(self): xq, k, params=params ) - self.assertTrue(np.all(I_panorama >= 10000)) - self.assertTrue(np.all(I_panorama < 50000)) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) - - def test_id_selector_batch(self): - """Test ID filtering with batch selector""" - d, nb, nt, nq, nlevels, k = 128, 60000, 90000, 400, 8, 20 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=522) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - allowed_ids = np.array( - [i * 100 for i in range(500)], dtype=np.int64 - ) - params = faiss.SearchParameters() - params.sel = faiss.IDSelectorBatch(allowed_ids) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - allowed_set = set(allowed_ids) - for id_val in I_panorama.flatten(): - self.assertIn(int(id_val), allowed_set) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) - - def test_selector_with_small_dataset(self): - """Test ID selectors with dataset smaller than batch size""" - d, nb, nt, nq, nlevels, k = 32, 100, 200, 10, 4, 5 - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=888) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - params = faiss.SearchParameters() - params.sel = faiss.IDSelectorRange(20, 60) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - self.assertTrue(np.all(I_panorama >= 20)) - self.assertTrue(np.all(I_panorama < 60)) - np.testing.assert_array_equal(I_regular, I_panorama) np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) def test_selector_excludes_all(self): - """Test selector that excludes all results""" d, nb, nt, nq, nlevels, k = 32, 300, 400, 5, 4, 10 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=999) @@ -378,18 +188,12 @@ def test_selector_excludes_all(self): D, I = index_panorama.search(xq, k, params=params) self.assertTrue(np.all(I == -1)) - # Batch size and edge case tests - def test_batch_boundaries(self): - """Test correctness at various batch size boundaries""" d, nq, k = 128, 10, 15 - # random train not needed for Flat indexes - # seed the (otherwise unseeded) query draw so runs are reproducible np.random.seed(1234) xq = np.random.rand(nq, d).astype("float32") for metric in self.METRICS: - # Use index's batch_size probe_index = self.create_panorama(d, nlevels=8, metric=metric) batch_size = probe_index.batch_size @@ -397,7 +201,6 @@ def test_batch_boundaries(self): batch_size - 1, batch_size, batch_size * 2, - batch_size * 3, batch_size * 5 - 1, ] for nb in test_sizes: @@ -418,14 +221,13 @@ def test_batch_boundaries(self): ) def test_batch_size(self): - """Test correctness across different internal batch sizes""" d, nb, nt, nq, nlevels = 128, 10000, 15000, 10, 8 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=4242) for metric in self.METRICS: index_regular = self.create_flat(d, xb, metric=metric) - for k, bs in [(1, 1), (10, 128), (100, 4096)]: + for k, bs in [(1, 1), (100, 4096)]: with self.subTest(metric=metric, k=k, batch_size=bs): index_panorama = self.create_panorama( d, nlevels, xb=xb, batch_size=bs, metric=metric @@ -436,100 +238,23 @@ def test_batch_size(self): D_regular, I_regular, D_panorama, I_panorama ) - def test_empty_result_handling(self): - """Test handling of empty search results (shapes only)""" - d, nb, nt, nq, nlevels, k = 32, 100, 200, 10, 4, 10 - _, xb, _ = self.generate_data(d, nt, nb, nq, seed=111) - xq = ( - np.random.rand(nq, d).astype("float32") + 10.0 - ) # Queries far from database - - for metric in self.METRICS: - with self.subTest(metric=metric): - index = self.create_panorama(d, nlevels, xb, metric=metric) - D, I = index.search(xq, k) - - self.assertEqual(D.shape, (nq, k)) - self.assertEqual(I.shape, (nq, k)) - - def test_very_small_dataset(self): - """Test with dataset smaller than batch size (< 128 vectors)""" - test_cases = [10, 50, 100] - - for metric in self.METRICS: - for nb in test_cases: - with self.subTest(metric=metric, nb=nb): - d, nt, nlevels, nq = 32, max(nb, 100), 4, 10 - k = min(3, nb) - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=666 + nb) - - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_range_search_edge_cases(self): - """Test range search with extreme radius values""" + # Both indexes are empty: the only search of a Panorama index with + # ntotal == 0. d, nb, nt, nq, nlevels = 32, 500, 700, 10, 4 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=777) - - for metric in self.METRICS: - index_regular = self.create_flat(d, metric=metric) - index_panorama = self.create_panorama(d, nlevels, metric=metric) - - for radius in [0.01, 0.1, 100.0, 1000.0]: - with self.subTest(metric=metric, radius=radius): - lims_reg, D_reg, I_reg = index_regular.range_search( - xq, radius - ) - lims_pan, D_pan, I_pan = index_panorama.range_search( - xq, radius - ) - - np.testing.assert_array_equal(lims_reg, lims_pan) - - if len(I_reg) > 0: - self.assert_range_results_equal( - lims_reg, D_reg, I_reg, lims_pan, D_pan, I_pan, nq - ) - - # Dynamic operations tests - - def test_incremental_add(self): - """Test adding vectors incrementally in multiple batches""" - d, nlevels, k = 128, 8, 15 + _, _, xq = self.generate_data(d, nt, nb, nq, seed=777) for metric in self.METRICS: with self.subTest(metric=metric): index_regular = self.create_flat(d, metric=metric) index_panorama = self.create_panorama(d, nlevels, metric=metric) - # Keep total nb under 100k - batch_sizes = [5000, 10000, 15000, 20000] - for batch_size in batch_sizes: - xb_batch = np.random.rand(batch_size, d).astype("float32") - index_regular.add(xb_batch) - index_panorama.add(xb_batch) - - nq = 10 - xq = np.random.rand(nq, d).astype("float32") - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) + lims_reg, _, _ = index_regular.range_search(xq, 1000.0) + lims_pan, _, _ = index_panorama.range_search(xq, 1000.0) - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) + np.testing.assert_array_equal(lims_reg, lims_pan) def test_add_search_add_search(self): - """Test interleaved add and search operations""" d, nlevels, k = 32, 4, 5 np.random.seed(555) @@ -538,7 +263,6 @@ def test_add_search_add_search(self): index_regular = self.create_flat(d, metric=metric) index_panorama = self.create_panorama(d, nlevels, metric=metric) - # First add and search xb1 = np.random.rand(200, d).astype("float32") index_regular.add(xb1) index_panorama.add(xb1) @@ -551,7 +275,6 @@ def test_add_search_add_search(self): D_reg_1, I_reg_1, D_pan_1, I_pan_1 ) - # Second add and search xb2 = np.random.rand(300, d).astype("float32") index_regular.add(xb2) index_panorama.add(xb2) @@ -564,144 +287,97 @@ def test_add_search_add_search(self): ) def test_reconstruct(self): - """Test reconstruct and reconstruct_n return original vectors""" d, nb, nt, nq, nlevels = 964, 1000, 15000, 10, 128 _, xb, _ = self.generate_data(d, nt, nb, nq, seed=2025) - for metric in self.METRICS: - with self.subTest(metric=metric): - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) + index_panorama = self.create_panorama(d, nlevels, xb) - # Test reconstruct for single vector - idx = 123 - v_panorama = index_panorama.reconstruct(idx) - np.testing.assert_array_equal(xb[idx], v_panorama) + idx = 123 + v_panorama = index_panorama.reconstruct(idx) + np.testing.assert_array_equal(xb[idx], v_panorama) - # Test reconstruct_n for range of vectors - start_idx, n_vectors = 120, 10 - vn_panorama = index_panorama.reconstruct_n(start_idx, n_vectors) - np.testing.assert_array_equal( - xb[start_idx : start_idx + n_vectors], vn_panorama - ) + start_idx, n_vectors = 120, 10 + vn_panorama = index_panorama.reconstruct_n(start_idx, n_vectors) + np.testing.assert_array_equal( + xb[start_idx : start_idx + n_vectors], vn_panorama + ) def test_remove_ids_then_add(self): - """Test removing vectors with remove_ids() then adding more vectors""" d, nb, nt, nq, nlevels, k = 964, 50000, 0, 10, 128, 15 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2026) xb1 = xb[: nb // 2] xb2 = xb[nb // 2 :] - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb1, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb1, metric=metric - ) + index_regular = self.create_flat(d, xb1) + index_panorama = self.create_panorama(d, nlevels, xb1) - # Remove every even ID - ids_to_remove = np.arange(0, nb, 2, dtype=np.int64) + ids_to_remove = np.arange(0, nb, 2, dtype=np.int64) - nremove_regular = index_regular.remove_ids(ids_to_remove) - nremove_panorama = index_panorama.remove_ids(ids_to_remove) + nremove_regular = index_regular.remove_ids(ids_to_remove) + nremove_panorama = index_panorama.remove_ids(ids_to_remove) - # Verify same number of IDs removed - self.assertEqual(nremove_regular, nremove_panorama) - - # Verify ntotal updated correctly - self.assertEqual(index_regular.ntotal, index_panorama.ntotal) - - # Verify search results match between regular and panorama - D_reg_1, I_reg_1 = index_regular.search(xq, k) - D_pan_1, I_pan_1 = index_panorama.search(xq, k) - self.assert_search_results_equal( - D_reg_1, I_reg_1, D_pan_1, I_pan_1 - ) + self.assertEqual(nremove_regular, nremove_panorama) - # Second add and search - index_regular.add(xb2) - index_panorama.add(xb2) + D_reg_1, I_reg_1 = index_regular.search(xq, k) + D_pan_1, I_pan_1 = index_panorama.search(xq, k) + self.assert_search_results_equal(D_reg_1, I_reg_1, D_pan_1, I_pan_1) - # Verify ntotal updated correctly - self.assertEqual(index_regular.ntotal, index_panorama.ntotal) + index_regular.add(xb2) + index_panorama.add(xb2) - # Verify second search results match - D_reg_2, I_reg_2 = index_regular.search(xq, k) - D_pan_2, I_pan_2 = index_panorama.search(xq, k) - self.assert_search_results_equal( - D_reg_2, I_reg_2, D_pan_2, I_pan_2 - ) + D_reg_2, I_reg_2 = index_regular.search(xq, k) + D_pan_2, I_pan_2 = index_panorama.search(xq, k) + self.assert_search_results_equal(D_reg_2, I_reg_2, D_pan_2, I_pan_2) def test_merge_from(self): - """Test merging indexes with merge_from()""" d, nb, nt, nq, nlevels, k, batch_size = 964, 50000, 0, 10, 128, 15, 16 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2027) - # Split data and create two separate indexes split = nb // 2 xb1 = xb[:split] xb2 = xb[split:] - for metric in self.METRICS: - with self.subTest(metric=metric): - index1_regular = self.create_flat(d, xb1, metric=metric) - index2_regular = self.create_flat(d, xb2, metric=metric) + index1_regular = self.create_flat(d, xb1) + index2_regular = self.create_flat(d, xb2) - index1_panorama = self.create_panorama( - d, nlevels, xb1, batch_size, metric=metric - ) - index2_panorama = self.create_panorama( - d, nlevels * 2, xb2, batch_size // 2, metric=metric - ) + index1_panorama = self.create_panorama(d, nlevels, xb1, batch_size) + index2_panorama = self.create_panorama( + d, nlevels * 2, xb2, batch_size // 2 + ) - # Merge second index into first - index1_regular.merge_from(index2_regular, 0) - index1_panorama.merge_from(index2_panorama, 0) + index1_regular.merge_from(index2_regular, 0) + index1_panorama.merge_from(index2_panorama, 0) - # Verify ntotal after merge - self.assertEqual(index1_regular.ntotal, index1_panorama.ntotal) - self.assertEqual(index2_regular.ntotal, index2_panorama.ntotal) + self.assertEqual(index2_regular.ntotal, index2_panorama.ntotal) - # Verify merged index results - D_regular, I_regular = index1_regular.search(xq, k) - D_panorama, I_panorama = index1_panorama.search(xq, k) - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) + D_regular, I_regular = index1_regular.search(xq, k) + D_panorama, I_panorama = index1_panorama.search(xq, k) + self.assert_search_results_equal( + D_regular, I_regular, D_panorama, I_panorama + ) def test_permute_entries(self): - """Test permuting entries with permute_entries()""" d, nb, nt, nq, nlevels, k = 964, 50000, 0, 20, 128, 10 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2028) - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, xb, metric=metric) - index_panorama = self.create_panorama( - d, nlevels, xb, metric=metric - ) + index_regular = self.create_flat(d, xb) + index_panorama = self.create_panorama(d, nlevels, xb) - # Create a random permutation - np.random.seed(1234) - perm = np.random.permutation(nb).astype(np.int64) + np.random.seed(1234) + perm = np.random.permutation(nb).astype(np.int64) - # Apply permutation to both indexes - index_regular.permute_entries(perm) - index_panorama.permute_entries(perm) + index_regular.permute_entries(perm) + index_panorama.permute_entries(perm) - # Search after permutation - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) + D_regular, I_regular = index_regular.search(xq, k) + D_panorama, I_panorama = index_panorama.search(xq, k) - # Verify permuted indexes match each other - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) + self.assert_search_results_equal( + D_regular, I_regular, D_panorama, I_panorama + ) def test_serialization(self): - """Test write/read Panorama indexes preserves search results""" d, nb, nt, nq, nlevels, k = 964, 10000, 15000, 100, 128, 20 _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2024) @@ -719,7 +395,6 @@ def test_serialization(self): np.testing.assert_array_equal(D_before, D_after) def test_ratio_dims_scanned(self): - """Test the correctness of the ratio of dimensions scanned""" d, nb, nq, k = 128, 500000, 10, 1 # Setup: All vectors in the dataset are [1, 1, ..., 1], except for diff --git a/thirdparty/faiss/tests/test_graph_based.py b/thirdparty/faiss/tests/test_graph_based.py index f314aa41a..452f64a8c 100644 --- a/thirdparty/faiss/tests/test_graph_based.py +++ b/thirdparty/faiss/tests/test_graph_based.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""a few tests for graph-based indices (HNSW, nndescent and NSG)""" - import numpy as np import unittest import faiss @@ -12,6 +10,15 @@ from common_faiss_tests import get_dataset_2, for_all_simd_levels +def check_io_and_clone(index, xq, D, I): + index2 = faiss.deserialize_index(faiss.serialize_index(index)) + index2b = faiss.deserialize_index(faiss.serialize_index(index2)) + for index3 in index2, index2b, faiss.clone_index(index): + D3, I3 = index3.search(xq, 1) + np.testing.assert_array_equal(D3, D) + np.testing.assert_array_equal(I3, I) + + @for_all_simd_levels class TestHNSW(unittest.TestCase): @@ -25,7 +32,7 @@ def __init__(self, *args, **kwargs): (_, self.xb, self.xq) = get_dataset_2(d, nt, nb, nq) index = faiss.IndexFlatL2(d) index.add(self.xb) - Dref, Iref = index.search(self.xq, 1) + _, Iref = index.search(self.xq, 1) self.Iref = Iref def test_hnsw(self): @@ -37,11 +44,9 @@ def test_hnsw(self): self.assertGreaterEqual((self.Iref == Ihnsw).sum(), 460) - self.io_and_retest(index, Dhnsw, Ihnsw) + check_io_and_clone(index, self.xq, Dhnsw, Ihnsw) def test_deterministic_build(self): - # The HNSW build is deterministic and lock-free: repeated builds, and - # builds at different thread counts, produce byte-identical graphs. # nb must be large enough that the batch-size cap (2% of n) exceeds # the >100 threshold gating the parallel build region; otherwise the # build runs single-threaded and determinism is trivially untested. @@ -49,8 +54,7 @@ def test_deterministic_build(self): nb = 20000 xb = np.random.RandomState(123).random((nb, d)).astype("float32") - # build() mutates the process-global OpenMP thread count; restore it so - # it does not leak into subsequent tests. + # build() mutates the global OpenMP thread count: restore it. self.addCleanup(faiss.omp_set_num_threads, faiss.omp_get_max_threads()) def build(nthreads): @@ -78,13 +82,11 @@ def graph_of(index): self.assertGreaterEqual(max_level, 1) self.assertGreater(int((g8a >= 0).sum()), nb) - # reproducible across repeated builds and across thread counts g8b = graph_of(build(8))[1] g1 = graph_of(build(1))[1] np.testing.assert_array_equal(g8a, g8b) np.testing.assert_array_equal(g8a, g1) - # no self-loops for i in range(nb): seg = g8a[int(offs[i]) : int(offs[i + 1])] self.assertNotIn(i, seg[seg >= 0].tolist()) @@ -94,14 +96,13 @@ def test_range_search(self): index_flat.add(self.xb) D, _ = index_flat.search(self.xq, 10) radius = np.median(D[:, -1]) - lims_ref, Dref, Iref = index_flat.range_search(self.xq, radius) + lims_ref, _, Iref = index_flat.range_search(self.xq, radius) index = faiss.IndexHNSWFlat(self.xb.shape[1], 16) index.add(self.xb) lims, D, I = index.range_search(self.xq, radius) nmiss = 0 - # check if returned results are a subset of the reference results for i in range(len(self.xq)): ref = Iref[lims_ref[i] : lims_ref[i + 1]] new = I[lims[i] : lims[i + 1]] @@ -120,7 +121,7 @@ def test_hnsw_unbounded_queue(self): self.assertGreaterEqual((self.Iref == Ihnsw).sum(), 460) - self.io_and_retest(index, Dhnsw, Ihnsw) + check_io_and_clone(index, self.xq, Dhnsw, Ihnsw) def test_hnsw_no_init_level0(self): d = self.xq.shape[1] @@ -134,27 +135,7 @@ def test_hnsw_no_init_level0(self): # vectors into level 0. self.assertGreaterEqual((self.Iref == Ihnsw).sum(), 25) - self.io_and_retest(index, Dhnsw, Ihnsw) - - def io_and_retest(self, index, Dhnsw, Ihnsw): - index2 = faiss.deserialize_index(faiss.serialize_index(index)) - Dhnsw2, Ihnsw2 = index2.search(self.xq, 1) - - self.assertTrue(np.all(Dhnsw2 == Dhnsw)) - self.assertTrue(np.all(Ihnsw2 == Ihnsw)) - - # Verify deserialized index is serializable again - index2b = faiss.deserialize_index(faiss.serialize_index(index2)) - Dhnsw2b, Ihnsw2b = index2b.search(self.xq, 1) - self.assertTrue(np.all(Dhnsw2b == Dhnsw)) - self.assertTrue(np.all(Ihnsw2b == Ihnsw)) - - # also test clone - index3 = faiss.clone_index(index) - Dhnsw3, Ihnsw3 = index3.search(self.xq, 1) - - self.assertTrue(np.all(Dhnsw3 == Dhnsw)) - self.assertTrue(np.all(Ihnsw3 == Ihnsw)) + check_io_and_clone(index, self.xq, Dhnsw, Ihnsw) def test_hnsw_2level(self): d = self.xq.shape[1] @@ -168,7 +149,7 @@ def test_hnsw_2level(self): self.assertGreaterEqual((self.Iref == Ihnsw).sum(), 307) - self.io_and_retest(index, Dhnsw, Ihnsw) + check_io_and_clone(index, self.xq, Dhnsw, Ihnsw) def test_hnsw_2level_mixed_search(self): d = self.xq.shape[1] @@ -186,12 +167,12 @@ def test_hnsw_2level_mixed_search(self): # It is expected that the mixed search will perform worse. self.assertGreaterEqual((self.Iref == Ihnsw).sum(), 200) - self.io_and_retest(index, Dhnsw, Ihnsw) + check_io_and_clone(index, self.xq, Dhnsw, Ihnsw) def test_add_0_vecs(self): index = faiss.IndexHNSWFlat(10, 16) zero_vecs = np.zeros((0, 10), dtype="float32") - # infinite loop + # used to loop forever index.add(zero_vecs) self.assertEqual(index.ntotal, 0) @@ -217,8 +198,12 @@ def test_ndis_stats(self): index = faiss.IndexHNSWFlat(d, 16) index.add(self.xb) stats = faiss.cvar.hnsw_stats + self.addCleanup( + faiss.set_search_stats_enabled, faiss.get_search_stats_enabled() + ) + faiss.set_search_stats_enabled(True) stats.reset() - Dhnsw, Ihnsw = index.search(self.xq, 1) + index.search(self.xq, 1) self.assertGreater(stats.ndis, len(self.xq) * index.hnsw.efSearch) def test_io_no_storage(self): @@ -228,7 +213,6 @@ def test_io_no_storage(self): Dref, Iref = index.search(self.xq, 5) - # test writing without storage index2 = faiss.deserialize_index( faiss.serialize_index(index, faiss.IO_FLAG_SKIP_STORAGE) ) @@ -238,7 +222,6 @@ def test_io_no_storage(self): # make sure we can store an index with empty storage faiss.deserialize_index(faiss.serialize_index(index2)) - # add storage afterwards index.storage = faiss.clone_index(index.storage) index.own_fields = True @@ -250,7 +233,6 @@ def test_hnsw_reset(self): d = self.xb.shape[1] index_flat = faiss.IndexFlat(d) index_flat.add(self.xb) - self.assertEqual(index_flat.ntotal, self.xb.shape[0]) index_hnsw = faiss.IndexHNSW(index_flat) index_hnsw.add(self.xb) # * 2 because we add to storage twice. This is just for testing @@ -264,12 +246,7 @@ def test_hnsw_reset(self): class TestHNSWSimilarity(unittest.TestCase): - """Coverage for HNSW variants built with a similarity metric - (METRIC_INNER_PRODUCT). These tests exercise the - HNSW::is_similarity dispatch in IndexHNSW{Flat,PQ,SQ,Cagra}: build, - search, and (for IndexHNSWFlat) save/load round trips that have to - re-derive `hnsw.is_similarity` from the persisted metric type. - """ + """HNSW variants with METRIC_INNER_PRODUCT: is_similarity dispatch.""" def setUp(self): d = 32 @@ -277,27 +254,12 @@ def setUp(self): nb = 1500 nq = 200 (self.xt, self.xb, self.xq) = get_dataset_2(d, nt, nb, nq) - # Reference IP search results. ref = faiss.IndexFlatIP(d) ref.add(self.xb) - self.Dref_ip, self.Iref_ip = ref.search(self.xq, 1) - - def test_hnsw_flat_IP_is_similarity_set(self): - d = self.xb.shape[1] - index = faiss.IndexHNSWFlat(d, 16, faiss.METRIC_INNER_PRODUCT) - self.assertTrue(index.hnsw.is_similarity) - - index_l2 = faiss.IndexHNSWFlat(d, 16, faiss.METRIC_L2) - self.assertFalse(index_l2.hnsw.is_similarity) + _, self.Iref_ip = ref.search(self.xq, 1) def _check_quantized_IP(self, index, min_agreement): - """Build (train if needed), search, then save / load and assert - that the round trip preserves ordering and `hnsw.is_similarity`. - The agreement floors are calibrated against the observed values - on the test dataset with a small (~5%) headroom for RNG noise; - they catch ordering regressions (which collapse agreement to - ~0) and quantizer-quality regressions (which would shift - agreement by tens of points).""" + """An ordering regression collapses agreement to ~0.""" self.assertTrue(index.hnsw.is_similarity) if not index.is_trained: index.train(self.xt) @@ -311,9 +273,9 @@ def _check_quantized_IP(self, index, min_agreement): f"{type(index).__name__} agreement={agreement} < {min_agreement}", ) - index2 = faiss.deserialize_index(faiss.serialize_index(index)) # `hnsw.is_similarity` is not serialized; index_read must # re-derive it from the persisted metric_type. + index2 = faiss.deserialize_index(faiss.serialize_index(index)) self.assertTrue(index2.hnsw.is_similarity) self.assertEqual(index2.metric_type, faiss.METRIC_INNER_PRODUCT) D2, I2 = index2.search(self.xq, 1) @@ -381,10 +343,8 @@ def test_hnsw_cagra_IP_base_level_only(self): class TestHNSWNaN(unittest.TestCase): - """Adding a vector with NaN to an IVF+HNSW index used to crash because - NaN distances corrupt the MinimaxHeap ordering in HNSW search. The fix - converts NaN to +inf in MinimaxHeap::push so the heap stays well-ordered. - """ + """Adding a NaN vector used to crash: NaN distances corrupted the + MinimaxHeap ordering in HNSW.""" def test_add_nan_vector_to_ivf_hnsw(self): d = 64 @@ -397,11 +357,9 @@ def test_add_nan_vector_to_ivf_hnsw(self): index.train(xt) index.add(xb) - # Create a vector with NaN in the first component vec = np.zeros((1, d), dtype="float32") vec[0, 0] = np.nan - # This should not crash index.add(vec) self.assertEqual(index.ntotal, nb + 1) @@ -409,14 +367,14 @@ def test_add_nan_vector_to_ivf_hnsw(self): class Issue3684(unittest.TestCase): def test_issue3684(self): - np.random.seed(1234) # For reproducibility - d = 256 # Example dimension - nb = 10 # Number of database vectors - nq = 2 # Number of query vectors + np.random.seed(1234) + d = 256 + nb = 10 + nq = 2 xb = np.random.random((nb, d)).astype("float32") xq = np.random.random((nq, d)).astype("float32") - faiss.normalize_L2(xb) # Normalize both query and database vectors + faiss.normalize_L2(xb) faiss.normalize_L2(xq) hnsw_index_ip = faiss.IndexHNSWFlat(256, 16, faiss.METRIC_INNER_PRODUCT) @@ -424,12 +382,10 @@ def test_issue3684(self): hnsw_index_ip.hnsw.efSearch = 512 hnsw_index_ip.add(xb) - # test knn D, I = hnsw_index_ip.search(xq, 10) self.assertTrue(np.all(D[:, :-1] >= D[:, 1:])) - # test range search - radius = 0.74 # Cosine similarity threshold + radius = 0.74 lims, D, I = hnsw_index_ip.range_search(xq, radius) self.assertTrue(np.all(D >= radius)) @@ -467,25 +423,6 @@ def make_knn_graph(self, metric): break return knn_graph - def subtest_io_and_clone(self, index, Dnsg, Insg): - index2 = faiss.deserialize_index(faiss.serialize_index(index)) - - Dnsg2, Insg2 = index2.search(self.xq, 1) - np.testing.assert_array_equal(Dnsg2, Dnsg) - np.testing.assert_array_equal(Insg2, Insg) - - # Verify deserialized index is serializable again - index2b = faiss.deserialize_index(faiss.serialize_index(index2)) - Dnsg2b, Insg2b = index2b.search(self.xq, 1) - np.testing.assert_array_equal(Dnsg2b, Dnsg) - np.testing.assert_array_equal(Insg2b, Insg) - - # also test clone - index3 = faiss.clone_index(index) - Dnsg3, Insg3 = index3.search(self.xq, 1) - np.testing.assert_array_equal(Dnsg3, Dnsg) - np.testing.assert_array_equal(Insg3, Insg) - def subtest_connectivity(self, index, nb): vt = faiss.VisitedTableVector(nb) count = index.nsg.dfs(vt, index.nsg.enterpoint, 0) @@ -496,7 +433,7 @@ def subtest_add(self, build_type, thresh, metric=faiss.METRIC_L2): flat_index = faiss.IndexFlat(d, metric) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, 1) + _, Iref = flat_index.search(self.xq, 1) index = faiss.IndexNSGFlat(d, 16, metric) index.verbose = True @@ -508,20 +445,20 @@ def subtest_add(self, build_type, thresh, metric=faiss.METRIC_L2): recalls = (Iref == Insg).sum() self.assertGreaterEqual(recalls, thresh) self.subtest_connectivity(index, self.xb.shape[0]) - self.subtest_io_and_clone(index, Dnsg, Insg) + check_io_and_clone(index, self.xq, Dnsg, Insg) def subtest_build(self, knn_graph, thresh, metric=faiss.METRIC_L2): d = self.xq.shape[1] flat_index = faiss.IndexFlat(d, metric) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, 1) + _, Iref = flat_index.search(self.xq, 1) index = faiss.IndexNSGFlat(d, 16, metric) index.verbose = True index.build(self.xb, knn_graph) - Dnsg, Insg = index.search(self.xq, 1) + _, Insg = index.search(self.xq, 1) recalls = (Iref == Insg).sum() self.assertGreaterEqual(recalls, thresh) @@ -539,14 +476,6 @@ def test_add_bruteforce_IP(self): def test_add_nndescent_IP(self): self.subtest_add(1, 480, faiss.METRIC_INNER_PRODUCT) - def test_build_L2(self): - knn_graph = self.make_knn_graph(faiss.METRIC_L2) - self.subtest_build(knn_graph, 475, faiss.METRIC_L2) - - def test_build_IP(self): - knn_graph = self.make_knn_graph(faiss.METRIC_INNER_PRODUCT) - self.subtest_build(knn_graph, 480, faiss.METRIC_INNER_PRODUCT) - def test_build_invalid_knng(self): """Make some invalid entries in the input knn graph. @@ -562,27 +491,22 @@ def test_build_invalid_knng(self): self.subtest_build(knn_graph, 480, faiss.METRIC_INNER_PRODUCT) def test_reset(self): - """test IndexNSG.reset()""" d = self.xq.shape[1] metric = faiss.METRIC_L2 flat_index = faiss.IndexFlat(d, metric) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, 1) + _, Iref = flat_index.search(self.xq, 1) index = faiss.IndexNSGFlat(d, 16) index.verbose = True index.GK = 32 index.add(self.xb) - Dnsg, Insg = index.search(self.xq, 1) - recalls = (Iref == Insg).sum() - self.assertGreaterEqual(recalls, 475) - self.subtest_connectivity(index, self.xb.shape[0]) index.reset() index.add(self.xb) - Dnsg, Insg = index.search(self.xq, 1) + _, Insg = index.search(self.xq, 1) recalls = (Iref == Insg).sum() self.assertGreaterEqual(recalls, 475) self.subtest_connectivity(index, self.xb.shape[0]) @@ -604,27 +528,14 @@ def test_order(self): gt = np.repeat(gt, nq, axis=0) # [nq, k] np.testing.assert_array_equal(indices, gt) - def test_nsg_supports_pre_built_knn_graph(self): - """Test IndexNSGBuild""" - knn_graph = self.make_knn_graph(faiss.METRIC_L2) - d = self.xq.shape[1] - index = faiss.IndexNSGFlat(d, 16) - index.build(self.xb, knn_graph) - index.search(self.xq, k=1) - self.assertTrue(index.is_built) - def test_nsg_with_pre_built_knn_graph_throws_when_rebuilding_via_add(self): - """Test IndexNSGBuild""" knn_graph = self.make_knn_graph(faiss.METRIC_L2) d = self.xq.shape[1] index = faiss.IndexNSGFlat(d, 16) index.build(self.xb, knn_graph) - index.search(self.xq, k=1) self.assertTrue(index.is_built) - index.GK = 32 - index.train(self.xb) with self.assertRaises(RuntimeError) as context: index.add(self.xb) @@ -633,12 +544,10 @@ def test_nsg_with_pre_built_knn_graph_throws_when_rebuilding_via_add(self): ) def test_nsg_rebuild_throws_with_pre_built_knn_graph(self): - """Test IndexNSGBuild""" knn_graph = self.make_knn_graph(faiss.METRIC_L2) d = self.xq.shape[1] index = faiss.IndexNSGFlat(d, 16) index.build(self.xb, knn_graph) - index.search(self.xq, k=1) with self.assertRaises(RuntimeError) as context: index.build(self.xb, knn_graph) @@ -646,7 +555,6 @@ def test_nsg_rebuild_throws_with_pre_built_knn_graph(self): self.assertIn("The IndexNSG is already built", str(context.exception)) def test_nsg_pq(self): - """Test IndexNSGPQ""" d = self.xq.shape[1] R, pq_M = 32, 4 index = faiss.index_factory(d, f"NSG{R}_PQ{pq_M}np") @@ -657,24 +565,21 @@ def test_nsg_pq(self): flat_index = faiss.IndexFlat(d) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, k=1) + _, Iref = flat_index.search(self.xq, k=1) index.GK = 32 index.train(self.xb) index.add(self.xb) D, I = index.search(self.xq, k=1) - # test accuracy recalls = (Iref == I).sum() # observed ~193/500; PQ4 is coarse -- headroom for OpenMP # FP-reduction / tie-break nondeterminism in NSG build + PQ assign self.assertGreaterEqual(recalls, 180) - # test I/O - self.subtest_io_and_clone(index, D, I) + check_io_and_clone(index, self.xq, D, I) def test_nsg_sq(self): - """Test IndexNSGSQ""" d = self.xq.shape[1] R = 32 index = faiss.index_factory(d, f"NSG{R}_SQ8") @@ -685,19 +590,17 @@ def test_nsg_sq(self): flat_index = faiss.IndexFlat(d) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, k=1) + _, Iref = flat_index.search(self.xq, k=1) index.train(self.xb) index.add(self.xb) D, I = index.search(self.xq, k=1) - # test accuracy recalls = (Iref == I).sum() # nominal ~411/500; loosened for OpenMP graph-build nondeterminism self.assertGreaterEqual(recalls, 395) - # test I/O - self.subtest_io_and_clone(index, D, I) + check_io_and_clone(index, self.xq, D, I) class TestNNDescent(unittest.TestCase): @@ -719,34 +622,16 @@ def test_nndescentflat(self): flat_index = faiss.IndexFlat(d) flat_index.add(self.xb) - Dref, Iref = flat_index.search(self.xq, k=1) + _, Iref = flat_index.search(self.xq, k=1) index.train(self.xb) index.add(self.xb) D, I = index.search(self.xq, k=1) - # test accuracy recalls = (Iref == I).sum() self.assertGreaterEqual(recalls, 450) # 462 - # do some IO tests - index2 = faiss.deserialize_index(faiss.serialize_index(index)) - - D2, I2 = index2.search(self.xq, 1) - np.testing.assert_array_equal(D2, D) - np.testing.assert_array_equal(I2, I) - - # Verify deserialized index is serializable again - index2b = faiss.deserialize_index(faiss.serialize_index(index2)) - D2b, I2b = index2b.search(self.xq, 1) - np.testing.assert_array_equal(D2b, D) - np.testing.assert_array_equal(I2b, I) - - # also test clone - index3 = faiss.clone_index(index) - D3, I3 = index3.search(self.xq, 1) - np.testing.assert_array_equal(D3, D) - np.testing.assert_array_equal(I3, I) + check_io_and_clone(index, self.xq, D, I) def test_order(self): """make sure that output results are sorted""" @@ -770,11 +655,8 @@ class TestNNDescentGenRandom(unittest.TestCase): """Regression tests for gen_random edge cases in NNDescent.""" def test_search_L_equals_ntotal(self): - """gen_random(size, N) crashed with division by zero when size == N. - - In search(), L_2 = max(search_L, topk). When search_L >= ntotal, - gen_random is called with size == N, causing rng() % 0. - """ + """gen_random(size, N) crashed with division by zero when size == N, + which search() reaches when search_L >= ntotal.""" d = 32 nb = 200 # just above NUM_EVAL_POINTS=100 xb = np.random.default_rng(42).random((nb, d)).astype("float32") @@ -785,10 +667,7 @@ def test_search_L_equals_ntotal(self): index.train(xb) index.add(xb) - # This crashed with division by zero before the fix - D, I = index.search(xq, k=1) - self.assertEqual(I.shape, (xq.shape[0], 1)) - self.assertEqual(D.shape, (xq.shape[0], 1)) + index.search(xq, k=1) class TestNNDescentKNNG(unittest.TestCase): diff --git a/thirdparty/faiss/tests/test_hamming.cpp b/thirdparty/faiss/tests/test_hamming.cpp index 69bd411bf..15a72dbd4 100644 --- a/thirdparty/faiss/tests/test_hamming.cpp +++ b/thirdparty/faiss/tests/test_hamming.cpp @@ -44,7 +44,6 @@ std::stringstream get_correct_hamming_example( std::shared_ptr> true_byte_distances) { assert(nb >= k); - // Initialization std::default_random_engine rng(123); std::uniform_int_distribution uniform(0, nb - 1); @@ -70,11 +69,9 @@ std::stringstream get_correct_hamming_example( // replace database vector at id with vector more similar to query // ordered, so earlier ids must be more similar for (size_t nmatches = k; nmatches > 0; --nmatches) { - // get id and erase it const size_t id = *correct_ids.begin(); *correct_ids.erase(correct_ids.begin()); - // assemble true id and distance at locations true_ids->push_back(id); true_bit_distances->push_back( (code_size > nmatches ? code_size - nmatches : 0) * @@ -121,156 +118,50 @@ std::stringstream get_correct_hamming_example( } TEST(TestHamming, test_crosshamming_count_thres) { - // Initialize randomizer - std::default_random_engine rng(123); - std::uniform_int_distribution uniform(0, 255); - - // Initialize inputs - const size_t n = 10; // number of codes - const hamdis_t hamming_threshold = 20; - - // one for each case - 65 is default - for (auto ncodes : {8, 16, 32, 64, 65}) { - // initialize inputs - const int nbits = ncodes * 8; - const size_t nwords = nbits / 64; - // 8 to for later conversion to uint64_t, and 2 for buffer - std::vector dbs(nwords * n * 8 * 2); - for (size_t i = 0; i < dbs.size(); ++i) { - dbs[i] = uniform(rng); - } - - // get true distance - size_t true_count = 0; - uint64_t* bs1 = (uint64_t*)dbs.data(); - for (size_t i = 0; i < n; ++i) { - uint64_t* bs2 = bs1 + 2; - for (size_t j = i + 1; j < n; ++j) { - if (faiss::hamming(bs1 + i * nwords, bs2 + j * nwords, nwords) < - hamming_threshold) { - ++true_count; - } - } - } - - // run test and check correctness - size_t count; - if (ncodes == 65) { - ASSERT_THROW( - faiss::crosshamming_count_thres( - dbs.data(), n, hamming_threshold, ncodes, &count), - faiss::FaissException); - continue; - } - faiss::crosshamming_count_thres( - dbs.data(), n, hamming_threshold, ncodes, &count); - - ASSERT_EQ(count, true_count) << "ncodes = " << ncodes; - } + // 65 bytes hits the unsupported-size default case. + const size_t n = 10; + const size_t ncodes = 65; + std::vector dbs(n * ncodes); + size_t count; + ASSERT_THROW( + faiss::crosshamming_count_thres(dbs.data(), n, 20, ncodes, &count), + faiss::FaissException); } -TEST(TestHamming, test_hamming_thres) { - // Initialize randomizer - std::default_random_engine rng(123); - std::uniform_int_distribution uniform(0, 255); - // Initialize inputs +TEST(TestHamming, test_hamming_thres) { + // 65 bytes hits the unsupported-size default case. const size_t n1 = 10; const size_t n2 = 15; + const size_t ncodes = 65; const hamdis_t hamming_threshold = 100; - - // one for each case - 65 is default - for (auto ncodes : {8, 16, 32, 64, 65}) { - // initialize inputs - const int nbits = ncodes * 8; - const size_t nwords = nbits / 64; - std::vector bs1(nwords * n1 * 8); - std::vector bs2(nwords * n2 * 8); - for (size_t i = 0; i < bs1.size(); ++i) { - bs1[i] = uniform(rng); - } - for (size_t i = 0; i < bs2.size(); ++i) { - bs2[i] = uniform(rng); - } - - // get true distance - size_t true_count = 0; - std::vector true_idx; - std::vector true_dis; - - uint64_t* bs1_64 = (uint64_t*)bs1.data(); - uint64_t* bs2_64 = (uint64_t*)bs2.data(); - for (size_t i = 0; i < n1; ++i) { - for (size_t j = 0; j < n2; ++j) { - hamdis_t ham_dist = faiss::hamming( - bs1_64 + i * nwords, bs2_64 + j * nwords, nwords); - if (ham_dist < hamming_threshold) { - ++true_count; - true_idx.push_back(i); - true_idx.push_back(j); - true_dis.push_back(ham_dist); - } - } - } - - // run test and check correctness for both - // match_hamming_thres and hamming_count_thres - std::vector idx(true_idx.size()); - std::vector dis(true_dis.size()); - if (ncodes == 65) { - ASSERT_THROW( - faiss::match_hamming_thres( - bs1.data(), - bs2.data(), - n1, - n2, - hamming_threshold, - ncodes, - idx.data(), - dis.data()), - faiss::FaissException); - ASSERT_THROW( - faiss::hamming_count_thres( - bs1.data(), - bs2.data(), - n1, - n2, - hamming_threshold, - ncodes, - nullptr), - faiss::FaissException); - continue; - } - size_t match_count = faiss::match_hamming_thres( - bs1.data(), - bs2.data(), - n1, - n2, - hamming_threshold, - ncodes, - idx.data(), - dis.data()); - size_t count_count; - faiss::hamming_count_thres( - bs1.data(), - bs2.data(), - n1, - n2, - hamming_threshold, - ncodes, - &count_count); - - ASSERT_EQ(match_count, true_count) << "ncodes = " << ncodes; - ASSERT_EQ(count_count, true_count) << "ncodes = " << ncodes; - ASSERT_EQ(idx, true_idx) << "ncodes = " << ncodes; - ASSERT_EQ(dis, true_dis) << "ncodes = " << ncodes; - } + std::vector bs1(n1 * ncodes); + std::vector bs2(n2 * ncodes); + std::vector idx(2 * n1 * n2); + std::vector dis(n1 * n2); + ASSERT_THROW( + faiss::match_hamming_thres( + bs1.data(), + bs2.data(), + n1, + n2, + hamming_threshold, + ncodes, + idx.data(), + dis.data()), + faiss::FaissException); + ASSERT_THROW( + faiss::hamming_count_thres( + bs1.data(), + bs2.data(), + n1, + n2, + hamming_threshold, + ncodes, + nullptr), + faiss::FaissException); } TEST(TestHamming, test_hamming_knn) { - // Initialize randomizer - std::default_random_engine rng(123); - std::uniform_int_distribution uniform(0, 32); - // Initialize inputs const size_t na = 4; const size_t nb = 12; // number of candidates @@ -285,7 +176,6 @@ TEST(TestHamming, test_hamming_knn) { // 8, 16, 32 are cases - 24 will hit default case // all should be multiples of 8 for (auto code_size : {8, 16, 24, 32}) { - // get example std::stringstream assert_str = get_correct_hamming_example( na, nb, @@ -297,7 +187,6 @@ TEST(TestHamming, test_hamming_knn) { true_bit_distances, true_byte_distances); - // run test on generalized_hammings_knn_hc std::vector ids_gen(na * k); std::vector dist_gen(na * k); faiss::int_maxheap_array_t res = { @@ -307,7 +196,6 @@ TEST(TestHamming, test_hamming_knn) { ASSERT_EQ(ids_gen, *true_ids) << assert_str.str(); ASSERT_EQ(dist_gen, *true_byte_distances) << assert_str.str(); - // run test on hammings_knn std::vector ids_ham_knn(na * k, 0); std::vector dist_ham_knn(na * k, 0); res = {na, k, ids_ham_knn.data(), dist_ham_knn.data()}; @@ -315,23 +203,6 @@ TEST(TestHamming, test_hamming_knn) { ASSERT_EQ(ids_ham_knn, *true_ids) << assert_str.str(); ASSERT_EQ(dist_ham_knn, *true_bit_distances) << assert_str.str(); } - - for (auto code_size : {8, 16, 24, 32, 64}) { - std::stringstream assert_str = get_correct_hamming_example( - na, - nb, - /* k */ nb, // faiss::hammings computes all distances - code_size, - a, - b, - true_ids, - true_bit_distances, - true_byte_distances); - std::vector dist_gen(na * nb); - faiss::hammings( - a->data(), b->data(), na, nb, code_size, dist_gen.data()); - EXPECT_EQ(dist_gen, *true_bit_distances) << assert_str.str(); - } } TEST(TestHamming, test_hammings_ragged_code_size) { diff --git a/thirdparty/faiss/tests/test_hamming_utils.py b/thirdparty/faiss/tests/test_hamming_utils.py index 2fcda5566..1de921245 100644 --- a/thirdparty/faiss/tests/test_hamming_utils.py +++ b/thirdparty/faiss/tests/test_hamming_utils.py @@ -4,15 +4,10 @@ # LICENSE file in the root directory of this source tree. """ -Tests for the standalone Hamming distance utility functions in -faiss/utils/hamming.h. These are dynamic-dispatch entry points that aren't -exercised by IndexBinary tests, so they otherwise have no per-SIMD-level -coverage. - -Each test computes a result at the current SIMD level (the level set by the -@for_all_simd_levels decorator) and compares against a NumPy popcount-xor -reference. The reference is level-independent, so any per-level dispatch -drift surfaces as an assertion failure. +Tests for the standalone Hamming distance functions in faiss/utils/hamming.h +against a level-independent NumPy popcount-xor reference. IndexBinary tests +do not reach these dynamic-dispatch entry points, so this is their only +per-SIMD-level coverage. Threshold-predicate convention: hamming_distance/common.h uses `h <= ht` for hamming_count_thres, match_hamming_thres, crosshamming_count_thres -- @@ -46,16 +41,13 @@ def _make_codes(n, ncodes, seed): # 4 * ncodes; std grows like sqrt(2 * ncodes)). Picking ht slightly below the # mean produces tens-to-hundreds of matches at the test sizes used here. # A vacuous (zero-match) test would pass against a no-op implementation. -_THRESHOLD_CASES = [(8, 28), (16, 60), (32, 120)] +_THRESHOLD_CASES = [(8, 28), (16, 60), (32, 120), (64, 240)] @for_all_simd_levels class TestHammingUtils(unittest.TestCase): - """Direct tests for hamming.h standalone entry points.""" - def test_hammings_all_pairs(self): - # faiss.hammings: all-pairs Hamming distances. - # ncodes covers SIMD-aligned (8, 16, 32, 64) and tail (24, 40) paths. + # Templated (8, 16, 32, 64) and default-case (24, 40) code sizes. for ncodes in (8, 16, 32, 24, 40, 64): with self.subTest(ncodes=ncodes): na, nb = 23, 47 @@ -93,7 +85,6 @@ def test_hammings_knn_mc(self): ) full = _popcount_xor(a[:, None, :], b[None, :, :]) - # Distance-at-returned-index agrees with the reference. returned = np.take_along_axis(full, I, axis=1) np.testing.assert_array_equal(D, returned) # Each returned distance is no greater than the true k-th @@ -101,7 +92,6 @@ def test_hammings_knn_mc(self): # broken in some impl-defined way). kth = np.partition(full, k - 1, axis=1)[:, k - 1 : k] self.assertTrue(np.all(D <= kth)) - # IDs within a row are unique. for i in range(na): self.assertEqual(len(np.unique(I[i])), k) @@ -154,13 +144,13 @@ def test_match_hamming_thres(self): faiss.swig_ptr(dis), ) self.assertEqual(got, expected_count) - # Decode the (i, j) pairs. i_idx = idx[0 : 2 * got : 2] j_idx = idx[1 : 2 * got : 2] + # Pairs come out in row-major (i, j) order. + np.testing.assert_array_equal( + np.lexsort((j_idx, i_idx)), np.arange(got) + ) dis = dis[:got] - # Every reported pair is within threshold and matches the - # reference distance at (i, j). - self.assertTrue(np.all(dis <= ht)) np.testing.assert_array_equal(dis, full[i_idx, j_idx]) # Every below-threshold pair in the reference appears in the # output exactly once. @@ -207,21 +197,17 @@ def test_generalized_hammings_knn_hc(self): True, ) - # Reference distance: number of bytes that differ. ref_dist = code_size - (a[:, None, :] == b[None, :, :]).sum( axis=-1 ).astype(np.int32) - # Distance at returned index matches the reference. returned = np.take_along_axis(ref_dist, I, axis=1) np.testing.assert_array_equal(D, returned) # Each returned distance is no greater than the true k-th # smallest -- catches an impl that returns I=[0..k-1]. kth = np.partition(ref_dist, k - 1, axis=1)[:, k - 1 : k] self.assertTrue(np.all(D <= kth)) - # ordered=True was passed: distances within each row are - # non-decreasing. + # ordered=True: distances are non-decreasing within each row. self.assertTrue(np.all(np.diff(D, axis=1) >= 0)) - # IDs are unique within a row. for i in range(na): self.assertEqual(len(np.unique(I[i])), k) diff --git a/thirdparty/faiss/tests/test_heap.cpp b/thirdparty/faiss/tests/test_heap.cpp index 62022dfa1..d1aedc374 100644 --- a/thirdparty/faiss/tests/test_heap.cpp +++ b/thirdparty/faiss/tests/test_heap.cpp @@ -13,12 +13,8 @@ using namespace faiss; -// Verify that Top1BlockResultHandler::begin_multiple initializes ids_tab to -1. -// The single-query path (SingleResultHandler::begin) explicitly sets -// min_idx=-1; begin_multiple must be consistent so that -// begin_multiple/end_multiple without an intervening add_results produces the -// "no result found" sentinel -1 in ids_tab rather than leaving it -// uninitialized. +// begin_multiple/end_multiple with no add_results must leave ids = -1, like +// SingleResultHandler::begin. TEST(Top1BlockResultHandler, BeginMultipleInitializesIds) { constexpr size_t nq = 16; std::vector dis_tab(nq, 12345.0f); @@ -47,8 +43,6 @@ TEST(Heap, addn_with_ids) { heaps.heapify(); std::vector labels(n, 1); std::vector distances(n, 0.0f); - std::vector subset(n); - std::iota(subset.begin(), subset.end(), 0); heaps.addn_with_ids(1, distances.data(), labels.data(), 1); heaps.reorder(); EXPECT_TRUE( diff --git a/thirdparty/faiss/tests/test_hnsw.cpp b/thirdparty/faiss/tests/test_hnsw.cpp index 67a1eb573..792dc33d6 100644 --- a/thirdparty/faiss/tests/test_hnsw.cpp +++ b/thirdparty/faiss/tests/test_hnsw.cpp @@ -7,25 +7,32 @@ #include -#include +#include +#include #include +#include #include +#include #include #include #include -#include +#include +#include #include +#include +#include #include #include #include #include #include +#include #include +#include int reference_pop_min(faiss::MinimaxHeap& heap, float* vmin_out) { assert(heap.k > 0); - // returns min. This is an O(n) operation int i = heap.k - 1; while (i >= 0) { if (heap.ids[i] != -1) { @@ -56,103 +63,45 @@ int reference_pop_min(faiss::MinimaxHeap& heap, float* vmin_out) { return ret; } -void test_popmin(int heap_size, int amount_to_put) { - // create a heap - faiss::MinimaxHeap mm_heap(heap_size); - - using storage_idx_t = faiss::HNSW::storage_idx_t; - - std::default_random_engine rng(123 + heap_size * amount_to_put); - std::uniform_int_distribution u(0, 65536); - std::uniform_real_distribution uf(0, 1); - - // generate random unique indices - std::unordered_set indices; - while (static_cast(indices.size()) < amount_to_put) { - const storage_idx_t index = u(rng); - indices.insert(index); - } - - // put ones into the heap - for (const auto index : indices) { - float distance = uf(rng); - if (distance >= 0.7f) { - // add infinity values from time to time - distance = std::numeric_limits::infinity(); - } - mm_heap.push(index, distance); - } - - // clone the heap - faiss::MinimaxHeap cloned_mm_heap = mm_heap; - - // takes ones out one by one - while (mm_heap.size() > 0) { - // compare heaps - ASSERT_EQ(mm_heap.n, cloned_mm_heap.n); - ASSERT_EQ(mm_heap.k, cloned_mm_heap.k); - ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid); - ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids); - ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis); - - // use the reference pop_min for the cloned heap - float cloned_vmin_dis = std::numeric_limits::quiet_NaN(); - storage_idx_t cloned_vmin_idx = - reference_pop_min(cloned_mm_heap, &cloned_vmin_dis); - - float vmin_dis = std::numeric_limits::quiet_NaN(); - storage_idx_t vmin_idx = mm_heap.pop_min(&vmin_dis); - - // compare returns - ASSERT_EQ(vmin_dis, cloned_vmin_dis); - ASSERT_EQ(vmin_idx, cloned_vmin_idx); - } - - // compare heaps again - ASSERT_EQ(mm_heap.n, cloned_mm_heap.n); - ASSERT_EQ(mm_heap.k, cloned_mm_heap.k); - ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid); - ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids); - ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis); -} - -void test_popmin_identical_distances( +void test_popmin( int heap_size, int amount_to_put, - const float distance) { - // create a heap + std::optional fixed_distance = std::nullopt) { faiss::MinimaxHeap mm_heap(heap_size); using storage_idx_t = faiss::HNSW::storage_idx_t; std::default_random_engine rng(123 + heap_size * amount_to_put); std::uniform_int_distribution u(0, 65536); + std::uniform_real_distribution uf(0, 1); - // generate random unique indices std::unordered_set indices; while (static_cast(indices.size()) < amount_to_put) { const storage_idx_t index = u(rng); indices.insert(index); } - // put ones into the heap for (const auto index : indices) { + float distance; + if (fixed_distance) { + distance = *fixed_distance; + } else { + distance = uf(rng); + if (distance >= 0.7f) { + distance = std::numeric_limits::infinity(); + } + } mm_heap.push(index, distance); } - // clone the heap faiss::MinimaxHeap cloned_mm_heap = mm_heap; - // takes ones out one by one while (mm_heap.size() > 0) { - // compare heaps - ASSERT_EQ(mm_heap.n, cloned_mm_heap.n); ASSERT_EQ(mm_heap.k, cloned_mm_heap.k); ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid); ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids); ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis); - // use the reference pop_min for the cloned heap float cloned_vmin_dis = std::numeric_limits::quiet_NaN(); storage_idx_t cloned_vmin_idx = reference_pop_min(cloned_mm_heap, &cloned_vmin_dis); @@ -160,65 +109,16 @@ void test_popmin_identical_distances( float vmin_dis = std::numeric_limits::quiet_NaN(); storage_idx_t vmin_idx = mm_heap.pop_min(&vmin_dis); - // compare returns ASSERT_EQ(vmin_dis, cloned_vmin_dis); ASSERT_EQ(vmin_idx, cloned_vmin_idx); } - // compare heaps again - ASSERT_EQ(mm_heap.n, cloned_mm_heap.n); ASSERT_EQ(mm_heap.k, cloned_mm_heap.k); ASSERT_EQ(mm_heap.nvalid, cloned_mm_heap.nvalid); ASSERT_EQ(mm_heap.ids, cloned_mm_heap.ids); ASSERT_EQ(mm_heap.dis, cloned_mm_heap.dis); } -void copy_base_level_only( - const faiss::IndexHNSWCagra& src, - faiss::IndexHNSWCagra& dst) { - auto n = src.ntotal; - auto d = src.d; - auto M = src.hnsw.nb_neighbors(0) / 2; - auto graph_degree = src.hnsw.nb_neighbors(0); - - if (dst.storage && dst.own_fields) { - delete dst.storage; - } - dst.storage = new faiss::IndexFlatL2(d); - dst.own_fields = true; - dst.d = d; - dst.metric_type = src.metric_type; - dst.is_trained = true; - dst.keep_max_size_level0 = true; - - dst.hnsw.reset(); - dst.hnsw.assign_probas.clear(); - dst.hnsw.cum_nneighbor_per_level.clear(); - dst.hnsw.set_default_probas(M, 1.0 / std::log(M)); - - dst.hnsw.prepare_level_tab(n, false); - - auto src_flat = dynamic_cast(src.storage); - FAISS_THROW_IF_NOT(src_flat); - dst.storage->add(n, src_flat->get_xb()); - dst.ntotal = n; - - for (faiss::idx_t i = 0; i < n; i++) { - size_t src_begin, src_end; - src.hnsw.neighbor_range(i, 0, &src_begin, &src_end); - - size_t dst_begin, dst_end; - dst.hnsw.neighbor_range(i, 0, &dst_begin, &dst_end); - - for (size_t j = 0; j < graph_degree && j < (dst_end - dst_begin); j++) { - dst.hnsw.neighbors[dst_begin + j] = - src.hnsw.neighbors[src_begin + j]; - } - } - - dst.base_level_only = true; -} - TEST(HNSW, Test_popmin) { std::vector sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32, 64, 128}; for (const size_t size : sizes) { @@ -232,7 +132,7 @@ TEST(HNSW, Test_popmin_identical_distances) { std::vector sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32}; for (const size_t size : sizes) { for (size_t amount = size; amount > 0; amount /= 2) { - test_popmin_identical_distances(size, amount, 1.0f); + test_popmin(size, amount, 1.0f); } } } @@ -241,74 +141,20 @@ TEST(HNSW, Test_popmin_infinite_distances) { std::vector sizes = {1, 2, 3, 4, 5, 7, 9, 11, 16, 27, 32}; for (const size_t size : sizes) { for (size_t amount = size; amount > 0; amount /= 2) { - test_popmin_identical_distances( - size, amount, std::numeric_limits::infinity()); + test_popmin(size, amount, std::numeric_limits::infinity()); } } } -TEST(HNSW, Test_IndexHNSW_METRIC_Lp) { - // Create an HNSW index with METRIC_Lp and metric_arg = 3 - faiss::IndexFlat storage_index(1, faiss::METRIC_Lp); - storage_index.metric_arg = 3; - faiss::IndexHNSW index(&storage_index, 32); - - // Add a single data point - float data[1] = {0.0}; - index.add(1, data); - - // Prepare a query - float query[1] = {2.0}; - float distance; - faiss::idx_t label; - - index.search(1, query, 1, &distance, &label); - - EXPECT_NEAR(distance, 8.0, 1e-5); // Distance should be 8.0 (2^3) - EXPECT_EQ(label, 0); // Label should be 0 -} - -TEST(HNSW, Test_IndexHNSWCagra_BaseLevelOnly_RangeSearch) { - int d = 8; - int nb = 100; - int nq = 5; - int M = 4; - - std::vector xb(nb * d); - std::vector xq(nq * d); - faiss::float_rand(xb.data(), xb.size(), 1234); - faiss::float_rand(xq.data(), xq.size(), 4321); - - faiss::IndexHNSWCagra index(d, M, faiss::METRIC_L2); - index.add(nb, xb.data()); - index.base_level_only = true; - index.num_base_level_search_entrypoints = 8; - - faiss::IndexHNSWCagra dst_index; - copy_base_level_only(index, dst_index); - dst_index.num_base_level_search_entrypoints = 8; - - faiss::RangeSearchResult res(nq); - float radius = 1e9f; - dst_index.range_search(nq, xq.data(), radius, &res); - - for (int i = 0; i < nq; i++) { - auto count = res.lims[i + 1] - res.lims[i]; - EXPECT_GT(count, 0); - } -} - class HNSWTest : public testing::Test { protected: HNSWTest() { xb = std::make_unique>(d * nb); - xb->reserve(d * nb); faiss::float_rand(xb->data(), d * nb, 12345); index = std::make_unique(d, M); index->add(nb, xb->data()); xq = std::unique_ptr>( new std::vector(d * nq)); - xq->reserve(d * nq); faiss::float_rand(xq->data(), d * nq, 12345); dis = std::unique_ptr( index->storage->get_distance_computer()); @@ -340,7 +186,6 @@ int reference_search_from_candidates( int nres = nres_in; int ndis = 0; - // can be overridden by search params bool do_dis_check = params ? params->check_relative_distance : hnsw.check_relative_distance; int efSearch = params ? params->efSearch : hnsw.efSearch; @@ -381,7 +226,6 @@ int reference_search_from_candidates( size_t begin, end; hnsw.neighbor_range(v0, level, &begin, &end); - // a reference version for (size_t j = begin; j < end; j++) { int v1 = hnsw.neighbors[j]; if (v1 < 0) { @@ -423,44 +267,6 @@ int reference_search_from_candidates( return nres; } -faiss::HNSWStats reference_greedy_update_nearest( - const faiss::HNSW& hnsw, - faiss::DistanceComputer& qdis, - int level, - faiss::HNSW::storage_idx_t& nearest, - float& d_nearest) { - faiss::HNSWStats stats; - - for (;;) { - faiss::HNSW::storage_idx_t prev_nearest = nearest; - - size_t begin, end; - hnsw.neighbor_range(nearest, level, &begin, &end); - - size_t ndis = 0; - - for (size_t i = begin; i < end; i++) { - faiss::HNSW::storage_idx_t v = hnsw.neighbors[i]; - if (v < 0) { - break; - } - ndis += 1; - float dis = qdis(v); - if (dis < d_nearest) { - nearest = v; - d_nearest = dis; - } - } - // update stats - stats.ndis += ndis; - stats.nhops += 1; - - if (nearest == prev_nearest) { - return stats; - } - } -} - std::priority_queue reference_search_from_candidate_unbounded( const faiss::HNSW& hnsw, const faiss::HNSW::Node& node, @@ -534,7 +340,6 @@ std::priority_queue reference_search_from_candidate_unbounded } TEST_F(HNSWTest, TEST_search_from_candidate_unbounded) { - omp_set_num_threads(1); auto nearest = index->hnsw.entry_point; float d_nearest = (*dis)(nearest); auto node = faiss::HNSW::Node(d_nearest, nearest); @@ -542,7 +347,6 @@ TEST_F(HNSWTest, TEST_search_from_candidate_unbounded) { faiss::VisitedTable::create(index->ntotal); faiss::HNSWStats stats; - // actual version auto top_candidates = faiss::hnsw_detail::search_from_candidate_unbounded( index->hnsw, node, *dis, k, vt.get(), stats); @@ -554,7 +358,6 @@ TEST_F(HNSWTest, TEST_search_from_candidate_unbounded) { faiss::VisitedTable::create(index->ntotal); faiss::HNSWStats reference_stats; - // reference version auto reference_top_candidates = reference_search_from_candidate_unbounded( index->hnsw, reference_node, @@ -569,32 +372,7 @@ TEST_F(HNSWTest, TEST_search_from_candidate_unbounded) { EXPECT_EQ(top_candidates.size(), reference_top_candidates.size()); } -TEST_F(HNSWTest, TEST_greedy_update_nearest) { - omp_set_num_threads(1); - - auto nearest = index->hnsw.entry_point; - float d_nearest = (*dis)(nearest); - auto reference_nearest = index->hnsw.entry_point; - float reference_d_nearest = (*dis)(reference_nearest); - - // actual version - auto stats = faiss::hnsw_detail::greedy_update_nearest( - index->hnsw, *dis, 0, nearest, d_nearest); - - // reference version - auto reference_stats = reference_greedy_update_nearest( - index->hnsw, *dis, 0, reference_nearest, reference_d_nearest); - EXPECT_EQ(stats.ndis, reference_stats.ndis); - EXPECT_EQ(stats.nhops, reference_stats.nhops); - EXPECT_EQ(stats.n1, reference_stats.n1); - EXPECT_EQ(stats.n2, reference_stats.n2); - EXPECT_NEAR(d_nearest, reference_d_nearest, 0.01); - EXPECT_EQ(nearest, reference_nearest); -} - TEST_F(HNSWTest, TEST_search_from_candidates) { - omp_set_num_threads(1); - std::vector I(k * nq); std::vector D(k * nq); std::vector reference_I(k * nq); @@ -642,11 +420,9 @@ TEST_F(HNSWTest, TEST_search_from_candidates) { 0, nullptr); reference_res.end(); - for (int i = 0; i < nq; i++) { - for (int j = 0; j < k; j++) { - EXPECT_NEAR(I[i * k + j], reference_I[i * k + j], 0.1); - EXPECT_NEAR(D[i * k + j], reference_D[i * k + j], 0.1); - } + for (int j = 0; j < k; j++) { + EXPECT_NEAR(I[j], reference_I[j], 0.1); + EXPECT_NEAR(D[j], reference_D[j], 0.1); } EXPECT_EQ(reference_stats.ndis, stats.ndis); EXPECT_EQ(reference_stats.nhops, stats.nhops); @@ -655,8 +431,6 @@ TEST_F(HNSWTest, TEST_search_from_candidates) { } TEST_F(HNSWTest, TEST_search_neighbors_to_add) { - omp_set_num_threads(1); - std::unique_ptr vt = faiss::VisitedTable::create(index->ntotal); std::unique_ptr reference_vt = @@ -696,18 +470,7 @@ TEST_F(HNSWTest, TEST_search_neighbors_to_add) { } } -TEST_F(HNSWTest, TEST_nb_neighbors_bound) { - omp_set_num_threads(1); - EXPECT_EQ(index->hnsw.nb_neighbors(0), 8); - EXPECT_EQ(index->hnsw.nb_neighbors(1), 4); - EXPECT_EQ(index->hnsw.nb_neighbors(2), 4); - EXPECT_EQ(index->hnsw.nb_neighbors(3), 4); - // picking a large number to trigger an exception based on checking bounds - EXPECT_THROW(index->hnsw.nb_neighbors(100), faiss::FaissException); -} - TEST_F(HNSWTest, TEST_search_level_0) { - omp_set_num_threads(1); std::vector I(k * nq); std::vector D(k * nq); @@ -751,32 +514,7 @@ TEST_F(HNSWTest, TEST_search_level_0) { EXPECT_GT(stats1.n2, stats2.n2); } -TEST(VisitedTableReuse, ReusesGrowsAndResets) { - // get_reusable() hands back the same thread-local object across calls - // (no per-call allocation) ... - faiss::VisitedTable& t1 = faiss::VisitedTable::get_reusable(100); - faiss::VisitedTable& t2 = faiss::VisitedTable::get_reusable(100); - EXPECT_EQ(&t1, &t2); - - // ... and hands it back clean: a mark set before re-acquiring must not - // survive, since a reused table may carry stamps from a prior search. - t2.set(42); - EXPECT_TRUE(t2.get(42)); - faiss::VisitedTable& t3 = faiss::VisitedTable::get_reusable(100); - EXPECT_EQ(&t2, &t3); - EXPECT_FALSE(t3.get(42)); - - // Growing to a larger size keeps the same object and exposes the new range. - faiss::VisitedTable& t4 = faiss::VisitedTable::get_reusable(1000); - EXPECT_EQ(&t3, &t4); - EXPECT_FALSE(t4.get(900)); - EXPECT_TRUE(t4.set(900)); - EXPECT_TRUE(t4.get(900)); -} - -// Restores the process-global OpenMP thread count on scope exit, so a test that -// changes it via omp_set_num_threads does not leak the setting into later -// tests. +// Restores the global OpenMP thread count on scope exit. struct ScopedOmpThreads { int saved = omp_get_max_threads(); ~ScopedOmpThreads() { @@ -784,19 +522,34 @@ struct ScopedOmpThreads { } }; +TEST_F(HNSWTest, TEST_search_advances_one_generation_per_query) { + ScopedOmpThreads omp_guard; + omp_set_num_threads(1); + index->hnsw.use_visited_hashset = false; + + auto& reusable = dynamic_cast( + faiss::VisitedTable::get_reusable(index->ntotal, false)); + std::fill(reusable.visited.begin(), reusable.visited.end(), 0); + reusable.visno = 10; + + std::vector labels(k); + std::vector distances(k); + index->search(1, xq->data(), k, distances.data(), labels.data()); + + // Acquiring the reusable table advances 10 -> 11 to clear stale state. + // HNSW::search then advances 11 -> 12 after the query. The outer wrapper + // must not perform a third advance. + EXPECT_EQ(12, reusable.visno); +} + TEST_F(HNSWTest, TEST_search_reuse_correctness) { ScopedOmpThreads omp_guard; - std::vector I1(k * nq), I2(k * nq); - std::vector D1(k * nq), D2(k * nq); + std::vector I1(k * nq); + std::vector D1(k * nq); - // Two back-to-back searches must be identical: the reused visited table - // must not carry state across search() calls. omp_set_num_threads(1); index->search(nq, xq->data(), k, D1.data(), I1.data()); - index->search(nq, xq->data(), k, D2.data(), I2.data()); - EXPECT_EQ(I1, I2); - EXPECT_EQ(D1, D2); // The reused versioned-array path must match a hash-set reference. std::vector Iref(k * nq); @@ -820,3 +573,495 @@ TEST_F(HNSWTest, TEST_search_reuse_correctness) { EXPECT_EQ(I1, Imt); EXPECT_EQ(D1, Dmt); } + +// These tests override virtual functions (the add() of an IVF quantizer, the +// sample searches), which the swig module cannot do in Python. The other tests +// of add_level_0_links_from_sample() are in test_hnsw.py. +namespace { + +constexpr int kSinkDim = 8; +constexpr size_t kSinkNodes = 4096; + +std::vector sink_test_vectors(size_t n, uint32_t seed) { + std::mt19937 rng(seed); + std::normal_distribution normal; + std::vector x(n * kSinkDim); + for (auto& v : x) { + v = normal(rng); + } + return x; +} + +// Vectors near the nodes, cycling through all of them. +std::vector near_nodes( + const std::vector& nodes, + size_t n, + uint32_t seed) { + const std::vector noise = sink_test_vectors(n, seed); + std::vector x(n * kSinkDim); + for (size_t i = 0; i < n; i++) { + for (size_t j = 0; j < kSinkDim; j++) { + x[i * kSinkDim + j] = nodes[(i % kSinkNodes) * kSinkDim + j] + + 0.01f * noise[i * kSinkDim + j]; + } + } + return x; +} + +// Removes all links of the entry point, so that every search stops there. +void plant_sink_at_entry_point(faiss::HNSW& hnsw) { + for (int level = 0; level <= hnsw.max_level; level++) { + size_t begin, end; + hnsw.neighbor_range(hnsw.entry_point, level, &begin, &end); + for (size_t k = begin; k < end; k++) { + hnsw.neighbors[k] = -1; + } + } +} + +std::vector to_fp16(const std::vector& x) { + std::vector x16(x.size()); + for (size_t i = 0; i < x.size(); i++) { + x16[i] = faiss::encode_fp16(x[i]); + } + return x16; +} + +// Fraction of the queries for which the index returns the exact nearest node. +double recall_at_1( + const faiss::IndexHNSW& index, + const std::vector& xq) { + const size_t nq = xq.size() / kSinkDim; + std::vector distances(nq); + std::vector labels(nq), exact(nq); + index.search(nq, xq.data(), 1, distances.data(), labels.data()); + index.storage->search(nq, xq.data(), 1, distances.data(), exact.data()); + size_t correct = 0; + for (size_t i = 0; i < nq; i++) { + correct += labels[i] == exact[i]; + } + return double(correct) / nq; +} + +// An HNSW quantizer whose add() leaves the entry point without links, so that +// every search stops there. +struct SinkHNSWFlat : faiss::IndexHNSWFlat { + SinkHNSWFlat() : faiss::IndexHNSWFlat(kSinkDim, 32) {} + + void add(faiss::idx_t n, const float* x) override { + faiss::IndexHNSWFlat::add(n, x); + plant_sink_at_entry_point(hnsw); + } +}; + +// Trains an IVF index with a SinkHNSWFlat quantizer and returns the recall@1 +// of the quantizer on vectors that training did not see. +double ivf_quantizer_recall( + int samples_per_list, + faiss::NumericType numeric_type = faiss::NumericType::Float32) { + const std::vector nodes = sink_test_vectors(kSinkNodes, 1); + SinkHNSWFlat quantizer; + faiss::IndexIVFFlat ivf(&quantizer, kSinkDim, kSinkNodes); + ivf.quantizer_trains_alone = 2; + quantizer.level_0_link_samples_per_node = samples_per_list; + const std::vector train = near_nodes(nodes, 40000, 2); + if (numeric_type == faiss::NumericType::Float16) { + ivf.train_ex(40000, to_fp16(train).data(), numeric_type); + } else { + ivf.train(40000, train.data()); + } + return recall_at_1(quantizer, near_nodes(nodes, 8192, 3)); +} + +constexpr int kBinaryDim = 128; +constexpr size_t kBinaryCodeSize = kBinaryDim / 8; + +std::vector random_codes(size_t n, uint32_t seed) { + std::mt19937 rng(seed); + std::vector x(n * kBinaryCodeSize); + for (auto& b : x) { + b = rng() & 0xff; + } + return x; +} + +// Codes near the nodes, cycling through all of them: 4 random bits differ. +std::vector near_codes( + const std::vector& nodes, + size_t n, + uint32_t seed) { + const size_t nn = nodes.size() / kBinaryCodeSize; + std::mt19937 rng(seed); + std::vector x(n * kBinaryCodeSize); + for (size_t i = 0; i < n; i++) { + uint8_t* code = x.data() + i * kBinaryCodeSize; + std::copy_n( + nodes.data() + (i % nn) * kBinaryCodeSize, + kBinaryCodeSize, + code); + for (int f = 0; f < 4; f++) { + const int bit = rng() % kBinaryDim; + code[bit / 8] ^= 1 << (bit % 8); + } + } + return x; +} + +// Fraction of the queries for which the index returns a node at the exact +// nearest distance. Hamming distances have ties, so the IDs can differ. +double binary_recall_at_1( + const faiss::IndexBinaryHNSW& index, + const std::vector& xq) { + const size_t nq = xq.size() / kBinaryCodeSize; + std::vector distances(nq), exact(nq); + std::vector labels(nq); + index.search(nq, xq.data(), 1, distances.data(), labels.data()); + index.storage->search(nq, xq.data(), 1, exact.data(), labels.data()); + size_t correct = 0; + for (size_t i = 0; i < nq; i++) { + correct += distances[i] == exact[i]; + } + return double(correct) / nq; +} + +// A binary HNSW quantizer whose add() leaves the entry point without links. +struct SinkBinaryHNSW : faiss::IndexBinaryHNSW { + SinkBinaryHNSW() : faiss::IndexBinaryHNSW(kBinaryDim, 32) {} + + void add(faiss::idx_t n, const uint8_t* x) override { + faiss::IndexBinaryHNSW::add(n, x); + plant_sink_at_entry_point(hnsw); + } +}; + +// Trains an IndexBinaryIVF with a SinkBinaryHNSW quantizer and returns the +// recall@1 of the quantizer on vectors that training did not see. +double binary_ivf_quantizer_recall(int samples_per_node) { + constexpr size_t nlist = 1024; + const std::vector nodes = random_codes(nlist, 1); + SinkBinaryHNSW quantizer; + quantizer.level_0_link_samples_per_node = samples_per_node; + faiss::IndexBinaryIVF ivf(&quantizer, kBinaryDim, nlist); + const std::vector train = near_codes(nodes, 40000, 2); + ivf.train(40000, train.data()); + return binary_recall_at_1(quantizer, near_codes(nodes, 8192, 3)); +} + +// Leaves the entry point of a graph with only level 0 with links to two nodes, +// and the first of them without links. Thus a search with efSearch 1 stops at +// that node when it is nearer than the second one, and the other searches +// continue through the second node. +void plant_partial_sink(faiss::HNSW& hnsw) { + size_t begin, end; + hnsw.neighbor_range(hnsw.entry_point, 0, &begin, &end); + const faiss::HNSW::storage_idx_t sink = hnsw.neighbors[begin]; + for (size_t k = begin + 2; k < end; k++) { + hnsw.neighbors[k] = -1; + } + hnsw.neighbor_range(sink, 0, &begin, &end); + for (size_t k = begin; k < end; k++) { + hnsw.neighbors[k] = -1; + } +} + +// An IndexHNSWFlat with a partial sink. +void build_partial_sink( + faiss::IndexHNSWFlat& index, + const std::vector& nodes) { + index.hnsw.levels.assign(kSinkNodes, 1); + index.add(kSinkNodes, nodes.data()); + plant_partial_sink(index.hnsw); +} + +// Level-0 link parameters that search with efSearch 1. +struct GreedyLinkParameters { + faiss::SearchParametersHNSW search_params; + faiss::HNSWLevel0LinkParameters params; + + GreedyLinkParameters() { + search_params.efSearch = 1; + params.search_params = &search_params; + } + GreedyLinkParameters(const GreedyLinkParameters&) = delete; + GreedyLinkParameters& operator=(const GreedyLinkParameters&) = delete; +}; + +// The sample searches of an IndexHNSWFlat, without the classes of +// IndexHNSW.cpp. It records the number of vectors of the last HNSW search, the +// exact searches, and the exact searches that repeat the label of the previous +// exact search of the same vector. +struct RecordingLinkSample : faiss::HNSWLinkSampleSearch { + const faiss::IndexHNSWFlat& index; + const std::vector& x; + mutable size_t last_m = 0; + mutable size_t n_exact = 0; + mutable size_t n_repeated = 0; + mutable std::vector last_found; + + RecordingLinkSample( + const faiss::IndexHNSWFlat& index_in, + const std::vector& x_in) + : index(index_in), x(x_in), last_found(x_in.size() / kSinkDim, -1) { + n = x_in.size() / kSinkDim; + } + + std::vector rows(size_t m, const faiss::idx_t* ids) const { + std::vector out(m * kSinkDim); + for (size_t j = 0; j < m; j++) { + const faiss::idx_t i = ids ? ids[j] : faiss::idx_t(j); + std::copy_n( + x.data() + i * kSinkDim, + kSinkDim, + out.data() + j * kSinkDim); + } + return out; + } + + void search( + const faiss::SearchParametersHNSW* params, + size_t m, + const faiss::idx_t* ids, + faiss::idx_t* labels) const override { + last_m = m; + std::vector distances(m); + index.search( + m, rows(m, ids).data(), 1, distances.data(), labels, params); + } + + void search_exact( + size_t m, + const faiss::idx_t* ids, + const faiss::idx_t* found, + faiss::idx_t* exact, + uint8_t* nearer) const override { + std::vector distances(m); + index.storage->search( + m, rows(m, ids).data(), 1, distances.data(), exact); + for (size_t j = 0; j < m; j++) { + n_repeated += last_found[ids[j]] == found[j]; + last_found[ids[j]] = found[j]; + // The samples are near distinct nodes, so no distances tie. + nearer[j] = exact[j] != found[j]; + } + n_exact += m; + } +}; + +int hamming(const uint8_t* a, const uint8_t* b) { + int d = 0; + for (size_t k = 0; k < kBinaryCodeSize; k++) { + d += std::popcount(static_cast(a[k] ^ b[k])); + } + return d; +} + +// The sample searches of an IndexBinaryHNSW, without the classes of +// IndexBinaryHNSW.cpp. +struct BinaryReferenceLinkSample : faiss::HNSWLinkSampleSearch { + const faiss::IndexBinaryHNSW& index; + const std::vector& nodes; + const std::vector& x; + + BinaryReferenceLinkSample( + const faiss::IndexBinaryHNSW& index_in, + const std::vector& nodes_in, + const std::vector& x_in) + : index(index_in), nodes(nodes_in), x(x_in) { + n = x_in.size() / kBinaryCodeSize; + } + + std::vector rows(size_t m, const faiss::idx_t* ids) const { + std::vector out(m * kBinaryCodeSize); + for (size_t j = 0; j < m; j++) { + const faiss::idx_t i = ids ? ids[j] : faiss::idx_t(j); + std::copy_n( + x.data() + i * kBinaryCodeSize, + kBinaryCodeSize, + out.data() + j * kBinaryCodeSize); + } + return out; + } + + void search( + const faiss::SearchParametersHNSW* params, + size_t m, + const faiss::idx_t* ids, + faiss::idx_t* labels) const override { + std::vector distances(m); + index.search( + m, rows(m, ids).data(), 1, distances.data(), labels, params); + } + + void search_exact( + size_t m, + const faiss::idx_t* ids, + const faiss::idx_t* found, + faiss::idx_t* exact, + uint8_t* nearer) const override { + const std::vector xq = rows(m, ids); + std::vector distances(m); + index.storage->search(m, xq.data(), 1, distances.data(), exact); + for (size_t j = 0; j < m; j++) { + const uint8_t* q = xq.data() + j * kBinaryCodeSize; + nearer[j] = exact[j] >= 0 && + hamming(q, nodes.data() + exact[j] * kBinaryCodeSize) < + hamming(q, + nodes.data() + found[j] * kBinaryCodeSize); + } + } +}; + +using LinkStep = std::function; + +// The graph after `add_links` on an IndexHNSWFlat with a partial sink. The +// step must make at least 2 rounds, so that the links of the last round come +// from the vectors that were searched again. +std::vector linked_partial_sink( + const std::vector& nodes, + const LinkStep& add_links) { + faiss::IndexHNSWFlat index(kSinkDim, 32); + build_partial_sink(index, nodes); + const GreedyLinkParameters greedy; + const faiss::HNSWLevel0LinkStats stats = add_links(index, greedy.params); + EXPECT_GE(stats.n_rounds, 2); + return {index.hnsw.neighbors.begin(), index.hnsw.neighbors.end()}; +} + +} // namespace + +TEST(HNSWLevel0LinksFromSample, SearchesAgainOnlyTheVectorsAtSinks) { + const std::vector nodes = sink_test_vectors(kSinkNodes, 1); + faiss::IndexHNSWFlat index(kSinkDim, 32); + build_partial_sink(index, nodes); + const std::vector x = near_nodes(nodes, 40000, 2); + RecordingLinkSample sample(index, x); + const GreedyLinkParameters greedy; + std::unique_ptr dis( + index.storage->get_distance_computer()); + + const faiss::HNSWLevel0LinkStats stats = + faiss::hnsw_add_level_0_links_from_sample( + index.hnsw, + index.ntotal, + *dis, + false, + sample, + greedy.params); + + EXPECT_EQ(stats.n_sinks_remaining, 0); + EXPECT_LT(sample.last_m, x.size() / kSinkDim); + EXPECT_EQ(sample.n_repeated, 0); + EXPECT_EQ(stats.n_exact_searches, sample.n_exact); +} + +// With fp32, fp16 and encoded samples, IndexHNSW searches the sample vectors +// that the step asks for: the links are the same as with RecordingLinkSample. +TEST(HNSWLevel0LinksFromSample, SampleSearchesGatherTheRequestedVectors) { + const std::vector nodes = sink_test_vectors(kSinkNodes, 1); + // Values that fp16 represents exactly, so that every sample type decodes + // to the same vectors. + const std::vector x16 = to_fp16(near_nodes(nodes, 40000, 2)); + std::vector x(x16.size()); + for (size_t i = 0; i < x.size(); i++) { + x[i] = faiss::decode_fp16(x16[i]); + } + const faiss::idx_t n = x.size() / kSinkDim; + faiss::IndexScalarQuantizer codec( + kSinkDim, faiss::ScalarQuantizer::QT_fp16); + std::vector codes(n * codec.sa_code_size()); + codec.sa_encode(n, x.data(), codes.data()); + + const auto expected = linked_partial_sink( + nodes, [&](faiss::IndexHNSWFlat& index, const auto& params) { + RecordingLinkSample sample(index, x); + std::unique_ptr dis( + index.storage->get_distance_computer()); + return faiss::hnsw_add_level_0_links_from_sample( + index.hnsw, index.ntotal, *dis, false, sample, params); + }); + + EXPECT_EQ( + linked_partial_sink( + nodes, + [&](faiss::IndexHNSWFlat& index, const auto& params) { + return index.add_level_0_links_from_sample( + n, x.data(), params); + }), + expected); + EXPECT_EQ( + linked_partial_sink( + nodes, + [&](faiss::IndexHNSWFlat& index, const auto& params) { + return index.add_level_0_links_from_sample_ex( + n, + x16.data(), + faiss::NumericType::Float16, + params); + }), + expected); + EXPECT_EQ( + linked_partial_sink( + nodes, + [&](faiss::IndexHNSWFlat& index, const auto& params) { + return index.add_level_0_links_from_sample_encoded( + n, codes.data(), &codec, params); + }), + expected); +} + +// IndexBinaryHNSW searches the sample vectors that the step asks for: the +// links are the same as with BinaryReferenceLinkSample. +TEST(HNSWLevel0LinksFromSample, BinarySampleSearchesGatherTheRequestedVectors) { + const std::vector nodes = random_codes(kSinkNodes, 1); + const std::vector x = near_codes(nodes, 40000, 2); + auto linked = [&](bool reference) { + faiss::IndexBinaryHNSW index(kBinaryDim, 32); + index.hnsw.levels.assign(kSinkNodes, 1); + index.add(kSinkNodes, nodes.data()); + plant_partial_sink(index.hnsw); + const GreedyLinkParameters greedy; + faiss::HNSWLevel0LinkStats stats; + if (reference) { + BinaryReferenceLinkSample sample(index, nodes, x); + std::unique_ptr dis( + index.get_distance_computer()); + stats = faiss::hnsw_add_level_0_links_from_sample( + index.hnsw, + index.ntotal, + *dis, + false, + sample, + greedy.params); + } else { + stats = index.add_level_0_links_from_sample( + x.size() / kBinaryCodeSize, x.data(), greedy.params); + } + EXPECT_GE(stats.n_rounds, 2); + return std::vector( + index.hnsw.neighbors.begin(), index.hnsw.neighbors.end()); + }; + + EXPECT_EQ(linked(false), linked(true)); +} + +TEST(HNSWLevel0LinksFromSample, IVFTrainingLinksHNSWQuantizer) { + EXPECT_GT(ivf_quantizer_recall(3), 0.95); +} + +TEST(HNSWLevel0LinksFromSample, IVFTrainingLinksHNSWQuantizerFloat16) { + EXPECT_GT(ivf_quantizer_recall(3, faiss::NumericType::Float16), 0.95); +} + +TEST(HNSWLevel0LinksFromSample, IVFTrainingSkipsLinksWhenDisabled) { + EXPECT_LT(ivf_quantizer_recall(0), 0.01); +} + +TEST(HNSWLevel0LinksFromSample, BinaryIVFTrainingLinksHNSWQuantizer) { + EXPECT_GT(binary_ivf_quantizer_recall(3), 0.95); +} + +TEST(HNSWLevel0LinksFromSample, BinaryIVFTrainingSkipsLinksWhenDisabled) { + EXPECT_LT(binary_ivf_quantizer_recall(0), 0.01); +} diff --git a/thirdparty/faiss/tests/test_hnsw.py b/thirdparty/faiss/tests/test_hnsw.py new file mode 100644 index 000000000..47abb1ebb --- /dev/null +++ b/thirdparty/faiss/tests/test_hnsw.py @@ -0,0 +1,421 @@ +# 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 math +import threading +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +def get_neighbor_range(hnsw, no, layer_no): + begin = np.zeros(1, dtype=np.uint64) + end = np.zeros(1, dtype=np.uint64) + hnsw.neighbor_range( + no, layer_no, faiss.swig_ptr(begin), faiss.swig_ptr(end) + ) + return int(begin[0]), int(end[0]) + + +def get_neighbors(hnsw): + return faiss.rev_swig_ptr(hnsw.neighbors.data(), hnsw.neighbors.size()) + + +class TestHNSWLpMetric(unittest.TestCase): + def test_index_hnsw_metric_lp(self): + index = faiss.IndexHNSWFlat(1, 32, faiss.METRIC_Lp) + index.storage.metric_arg = 3 + + index.add(np.array([[0.0]], dtype=np.float32)) + D, I = index.search(np.array([[2.0]], dtype=np.float32), 1) + + # distance is 2**3 + self.assertAlmostEqual(D[0][0], 8.0, places=5) + self.assertEqual(I[0][0], 0) + + +class TestHNSWStats(unittest.TestCase): + def set_search_stats_enabled(self, enabled): + previous = faiss.get_search_stats_enabled() + faiss.set_search_stats_enabled(enabled) + self.addCleanup(faiss.set_search_stats_enabled, previous) + + def make_index(self): + index = faiss.IndexBinaryHNSW(8, 2) + database = np.zeros((1, 1), dtype=np.uint8) + index.add(database) + index.hnsw.efSearch = 1 + return index, database + + def test_disabled_collection_skips_global_stats(self): + index, database = self.make_index() + self.set_search_stats_enabled(False) + faiss.cvar.hnsw_stats.reset() + + index.search(database, 1) + + self.assertEqual(0, faiss.cvar.hnsw_stats.n1) + + def test_enabled_collection_aggregates_concurrent_searches_exactly(self): + num_threads = 16 + searches_per_thread = 100 + + index, database = self.make_index() + self.set_search_stats_enabled(True) + self.addCleanup(faiss.omp_set_num_threads, faiss.omp_get_max_threads()) + faiss.cvar.hnsw_stats.reset() + + def run_searches(): + faiss.omp_set_num_threads(1) + for _ in range(searches_per_thread): + index.search(database, 1) + + threads = [ + threading.Thread(target=run_searches) for _ in range(num_threads) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + self.assertEqual( + num_threads * searches_per_thread, faiss.cvar.hnsw_stats.n1 + ) + + +def copy_base_level_only(src, dst): + n = src.ntotal + d = src.d + M = src.hnsw.nb_neighbors(0) // 2 + graph_degree = src.hnsw.nb_neighbors(0) + + storage = faiss.IndexFlatL2(d) + storage.this.disown() + dst.storage = storage + dst.own_fields = True + dst.d = d + dst.metric_type = src.metric_type + dst.is_trained = True + dst.keep_max_size_level0 = True + + dst.hnsw.reset() + dst.hnsw.assign_probas.clear() + dst.hnsw.cum_nneighbor_per_level.clear() + dst.hnsw.set_default_probas(M, 1.0 / math.log(M)) + + dst.hnsw.prepare_level_tab(n, False) + + src_flat = faiss.downcast_index(src.storage) + assert isinstance(src_flat, faiss.IndexFlat) + xb = faiss.rev_swig_ptr(src_flat.get_xb(), n * d).reshape(n, d) + dst.storage.add(xb) + dst.ntotal = n + + src_neighbors = get_neighbors(src.hnsw) + dst_neighbors = get_neighbors(dst.hnsw) + for i in range(n): + src_begin, _ = get_neighbor_range(src.hnsw, i, 0) + dst_begin, dst_end = get_neighbor_range(dst.hnsw, i, 0) + for j in range(min(graph_degree, dst_end - dst_begin)): + dst_neighbors[dst_begin + j] = src_neighbors[src_begin + j] + + dst.base_level_only = True + + +class TestHNSW(unittest.TestCase): + def test_index_hnsw_cagra_base_level_only_range_search(self): + d = 8 + nb = 100 + nq = 5 + M = 4 + + xb = faiss.rand(nb * d, 1234).reshape(nb, d) + xq = faiss.rand(nq * d, 4321).reshape(nq, d) + + index = faiss.IndexHNSWCagra(d, M, faiss.METRIC_L2) + index.add(xb) + + dst_index = faiss.IndexHNSWCagra() + copy_base_level_only(index, dst_index) + dst_index.num_base_level_search_entrypoints = 8 + + radius = 1e9 + lims, _, _ = dst_index.range_search(xq, radius) + + for i in range(nq): + self.assertGreater(lims[i + 1] - lims[i], 0) + + +def reference_greedy_update_nearest(hnsw, qdis, level, nearest, d_nearest): + stats = faiss.HNSWStats() + neighbors = get_neighbors(hnsw) + + while True: + prev_nearest = nearest + begin, end = get_neighbor_range(hnsw, nearest, level) + + ndis = 0 + for i in range(begin, end): + v = int(neighbors[i]) + if v < 0: + break + ndis += 1 + dis = qdis(v) + if dis < d_nearest: + nearest = v + d_nearest = dis + stats.ndis += ndis + stats.nhops += 1 + + if nearest == prev_nearest: + return stats, nearest, d_nearest + + +class TestHNSWTest(unittest.TestCase): + d = 64 + nb = 2000 + M = 4 + nq = 10 + + def setUp(self): + self.xb = faiss.rand(self.d * self.nb, 12345).reshape(self.nb, self.d) + self.index = faiss.IndexHNSWFlat(self.d, self.M) + self.index.add(self.xb) + self.xq = faiss.rand(self.d * self.nq, 12345).reshape(self.nq, self.d) + self.dis = self.index.storage.get_distance_computer() + self.dis.set_query(faiss.swig_ptr(self.xq[0])) + + def test_greedy_update_nearest(self): + hnsw = self.index.hnsw + nearest = np.array([hnsw.entry_point], dtype=np.int32) + d_nearest = np.array([self.dis(int(nearest[0]))], dtype=np.float32) + reference_nearest = hnsw.entry_point + reference_d_nearest = np.float32(self.dis(reference_nearest)) + + stats = faiss.greedy_update_nearest( + hnsw, + self.dis, + 0, + faiss.swig_ptr(nearest), + faiss.swig_ptr(d_nearest), + ) + + reference_stats, reference_nearest, reference_d_nearest = ( + reference_greedy_update_nearest( + hnsw, self.dis, 0, reference_nearest, reference_d_nearest + ) + ) + self.assertEqual(stats.ndis, reference_stats.ndis) + self.assertEqual(stats.nhops, reference_stats.nhops) + self.assertAlmostEqual(d_nearest[0], reference_d_nearest, delta=0.01) + self.assertEqual(nearest[0], reference_nearest) + + def test_nb_neighbors_bound(self): + hnsw = self.index.hnsw + self.assertEqual(hnsw.nb_neighbors(0), 8) + self.assertEqual(hnsw.nb_neighbors(1), 4) + self.assertEqual(hnsw.nb_neighbors(2), 4) + with self.assertRaises(RuntimeError): + hnsw.nb_neighbors(100) + + +class TestVisitedTableReuse(unittest.TestCase): + def test_reuses_grows_and_resets(self): + # get_reusable() hands back the same thread-local object. + t1 = faiss.VisitedTable.get_reusable(100) + t2 = faiss.VisitedTable.get_reusable(100) + self.assertEqual(int(t1.this), int(t2.this)) + + # It comes back clean: a reused table may carry stamps from a prior + # search. + t2.set(42) + self.assertTrue(t2.get(42)) + t3 = faiss.VisitedTable.get_reusable(100) + self.assertEqual(int(t2.this), int(t3.this)) + self.assertFalse(t3.get(42)) + + # Growing keeps the same object. + t4 = faiss.VisitedTable.get_reusable(1000) + self.assertEqual(int(t3.this), int(t4.this)) + self.assertFalse(t4.get(900)) + self.assertTrue(t4.set(900)) + self.assertTrue(t4.get(900)) + + +def plant_sink_at_entry_point(hnsw): + """Removes all links of the entry point, so that every search stops + there.""" + neighbors = get_neighbors(hnsw) + for level in range(hnsw.max_level + 1): + begin, end = get_neighbor_range(hnsw, hnsw.entry_point, level) + neighbors[begin:end] = -1 + + +def near_nodes(nodes, n, seed): + """Vectors near the nodes, cycling through all of them.""" + noise = np.random.default_rng(seed).standard_normal((n, nodes.shape[1])) + x = nodes[np.arange(n) % len(nodes)] + 0.01 * noise + return x.astype(np.float32) + + +def recall_at_1(index, xq): + """Fraction of the queries for which the index returns the exact nearest + node.""" + _, labels = index.search(xq, 1) + _, exact = index.storage.search(xq, 1) + return (labels == exact).mean() + + +def near_codes(nodes, n, seed): + """Binary codes near the nodes, cycling through all of them: 4 random + bits differ.""" + rng = np.random.default_rng(seed) + codes = nodes[np.arange(n) % len(nodes)].copy() + bits = rng.integers(0, nodes.shape[1] * 8, size=(n, 4)) + for f in range(4): + np.bitwise_xor.at( + codes, + (np.arange(n), bits[:, f] // 8), + (1 << (bits[:, f] % 8)).astype(np.uint8), + ) + return codes + + +class TestHNSWLevel0LinksFromSample(unittest.TestCase): + d = 8 + nnodes = 4096 + + def nodes(self): + rng = np.random.default_rng(1) + return rng.standard_normal((self.nnodes, self.d)).astype(np.float32) + + def check_planted_sink_removed(self, index, add_links): + """The intact recall is below 1 when the HNSW search and the storage + search use different distance estimates, for example with RaBitQ.""" + nodes = self.nodes() + index.train(nodes) + index.add(nodes) + queries = near_nodes(nodes, 8192, 3) + intact_recall = recall_at_1(index, queries) + hnsw = index.hnsw + plant_sink_at_entry_point(hnsw) + self.assertLess(recall_at_1(index, queries), 0.01) + + stats = add_links(index, near_nodes(nodes, 40000, 2)) + + self.assertEqual(stats.n_sinks_found, 1) + self.assertEqual(stats.n_sinks_remaining, 0) + self.assertGreater(recall_at_1(index, queries), 0.95 * intact_recall) + + def test_removes_planted_sink_l2(self): + self.check_planted_sink_removed( + faiss.IndexHNSWFlat(self.d, 32), + lambda index, x: index.add_level_0_links_from_sample(x), + ) + + def test_removes_planted_sink_inner_product(self): + self.check_planted_sink_removed( + faiss.IndexHNSWFlat(self.d, 32, faiss.METRIC_INNER_PRODUCT), + lambda index, x: index.add_level_0_links_from_sample(x), + ) + + def test_removes_planted_sink_rabitq_storage(self): + self.check_planted_sink_removed( + faiss.IndexHNSWRaBitQ(self.d, 32), + lambda index, x: index.add_level_0_links_from_sample(x), + ) + + def test_removes_planted_sink_panorama(self): + self.check_planted_sink_removed( + faiss.IndexHNSWFlatPanorama(self.d, 32, 2), + lambda index, x: index.add_level_0_links_from_sample(x), + ) + + def test_removes_planted_sink_float16_samples(self): + self.check_planted_sink_removed( + faiss.IndexHNSWFlat(self.d, 32), + lambda index, x: index.add_level_0_links_from_sample( + x.astype(np.float16), numeric_type=faiss.Float16 + ), + ) + + def test_removes_planted_sink_encoded_samples(self): + def add_links(index, x): + codec = faiss.IndexScalarQuantizer( + self.d, faiss.ScalarQuantizer.QT_8bit + ) + codec.train(x) + codes = codec.sa_encode(x) + return index.add_level_0_links_from_sample_encoded( + len(x), faiss.swig_ptr(codes), codec + ) + + self.check_planted_sink_removed( + faiss.IndexHNSWFlat(self.d, 32), add_links + ) + + def test_removes_planted_sink_binary(self): + nbits = 128 + rng = np.random.default_rng(1) + nodes = rng.integers( + 0, 256, size=(self.nnodes, nbits // 8), dtype=np.uint8 + ) + index = faiss.IndexBinaryHNSW(nbits, 32) + index.add(nodes) + queries = near_codes(nodes, 8192, 3) + + # Hamming distances have ties, so compare distances, not IDs. + def recall(): + distances, _ = index.search(queries, 1) + exact, _ = index.storage.search(queries, 1) + return (distances == exact).mean() + + intact_recall = recall() + hnsw = index.hnsw + plant_sink_at_entry_point(hnsw) + self.assertLess(recall(), 0.01) + + stats = index.add_level_0_links_from_sample( + near_codes(nodes, 40000, 2) + ) + + self.assertEqual(stats.n_sinks_found, 1) + self.assertEqual(stats.n_sinks_remaining, 0) + self.assertGreater(recall(), 0.95 * intact_recall) + + def test_does_not_change_intact_graph(self): + nodes = self.nodes() + index = faiss.IndexHNSWFlat(self.d, 32) + index.add(nodes) + hnsw = index.hnsw + before = get_neighbors(hnsw).copy() + + stats = index.add_level_0_links_from_sample( + near_nodes(nodes, 40000, 2) + ) + + self.assertEqual(stats.n_sinks_found, 0) + np.testing.assert_array_equal(get_neighbors(hnsw), before) + + def test_same_links_for_any_thread_count(self): + nodes = self.nodes() + samples = near_nodes(nodes, 40000, 2) + previous = faiss.omp_get_max_threads() + self.addCleanup(faiss.omp_set_num_threads, previous) + + def linked(threads): + faiss.omp_set_num_threads(threads) + index = faiss.IndexHNSWFlat(self.d, 32) + index.add(nodes) + hnsw = index.hnsw + plant_sink_at_entry_point(hnsw) + index.add_level_0_links_from_sample(samples) + return get_neighbors(hnsw).copy() + + np.testing.assert_array_equal(linked(1), linked(8)) diff --git a/thirdparty/faiss/tests/test_hnsw_panorama.py b/thirdparty/faiss/tests/test_hnsw_panorama.py index 8f8f0ae1c..ab1621d3e 100644 --- a/thirdparty/faiss/tests/test_hnsw_panorama.py +++ b/thirdparty/faiss/tests/test_hnsw_panorama.py @@ -3,15 +3,7 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Comprehensive test suite for IndexHNSWFlatPanorama. - -IndexHNSWFlatPanorama combines the hierarchical navigable small world (HNSW) -graph structure with Panorama's level-oriented storage and progressive -filtering for efficient approximate nearest neighbor search. - -Paper: https://www.arxiv.org/pdf/2510.00566 -""" +"""Panorama paper: https://www.arxiv.org/pdf/2510.00566""" import unittest import tempfile @@ -25,17 +17,11 @@ @for_all_simd_levels class TestIndexHNSWFlatPanorama(unittest.TestCase): - """Test Suite for IndexHNSWFlatPanorama.""" - - # Helper methods for index creation and data generation - def generate_data(self, d, nt, nb, nq, seed=1234): - """Generate synthetic data using SyntheticDataset.""" ds = SyntheticDataset(d, nt, nb, nq, seed=seed) return ds.get_train(), ds.get_database(), ds.get_queries() def compute_ground_truth(self, xb, xq, k): - """Compute ground truth using brute force search.""" d = xb.shape[1] index = faiss.IndexFlatL2(d) index.add(xb) @@ -43,105 +29,21 @@ def compute_ground_truth(self, xb, xq, k): return D, I def compute_recall(self, gt_I, test_I): - """Compute recall@k - fraction of ground truth results found in - test results.""" nq, k = gt_I.shape recalls = [np.isin(gt_I[i], test_I[i]).sum() for i in range(nq)] return sum(recalls) / (nq * k) - # Core functionality tests - - def test_basic_construction(self): - """Test basic index construction and properties.""" - d = 128 - M = 16 - num_levels = 8 - - index = faiss.IndexHNSWFlatPanorama(d, M, num_levels) - - self.assertEqual(index.d, d) - self.assertEqual(index.ntotal, 0) - self.assertTrue(index.is_trained) - self.assertEqual( - index.hnsw.nb_neighbors(0), 2 * M - ) # Level 0 has 2*M neighbors - self.assertEqual(index.num_panorama_levels, num_levels) - self.assertEqual(index.metric_type, faiss.METRIC_L2) - - def test_add_and_search(self): - """Test basic add and search operations.""" - d = 128 - nb = 1000 - nt = 1500 - nq = 10 - k = 10 - - # Generate data - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=1234) - - index = faiss.IndexHNSWFlatPanorama(d, 16, 8) - index.add(xb) - - self.assertEqual(index.ntotal, nb) - self.assertEqual(index.cum_sums.size(), nb * (8 + 1)) - - # Search - D, I = index.search(xq, k) - - # Check that results are valid - self.assertTrue(np.all(I >= -1)) - self.assertTrue(np.all(I < nb)) - self.assertTrue(np.all(D >= 0.0)) - - def test_recall(self): - """Test search recall quality.""" - d = 128 - nb = 1000 - nt = 1500 - nq = 100 - k = 10 - - # Generate data - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=42) - - # Create index - index = faiss.IndexHNSWFlatPanorama(d, 32, 8) - index.hnsw.efConstruction = 40 - index.hnsw.efSearch = 64 - - # Add to index - index.add(xb) - - # Search - D, I = index.search(xq, k) - - # Compute ground truth - gt_D, gt_I = self.compute_ground_truth(xb, xq, k) - - # Check recall - recall = self.compute_recall(gt_I, I) - print(f"Recall@{k}: {recall}") - - # With efSearch=64, we should get reasonably good recall - # The threshold is lower than vanilla HNSW because of approximate - # distances - self.assertGreaterEqual(recall, 0.85) - def test_different_panorama_levels(self): - """Test with different numbers of panorama levels.""" d = 256 nb = 500 nt = 700 nq = 50 k = 5 - # Generate data _, xb, xq = self.generate_data(d, nt, nb, nq, seed=456) - # Compute ground truth - gt_D, gt_I = self.compute_ground_truth(xb, xq, k) + _, gt_I = self.compute_ground_truth(xb, xq, k) - # Test different number of panorama levels for nlevels in [4, 8, 16]: with self.subTest(nlevels=nlevels): index = faiss.IndexHNSWFlatPanorama(d, 32, nlevels) @@ -149,16 +51,12 @@ def test_different_panorama_levels(self): index.add(xb) - D, I = index.search(xq, k) + _, I = index.search(xq, k) recall = self.compute_recall(gt_I, I) - print(f"Recall@{k} with {nlevels} levels: {recall}") - - # More levels should still maintain reasonable recall self.assertGreaterEqual(recall, 0.80) def test_uneven_dimension_division(self): - """Test when n_levels doesn't evenly divide dimension.""" test_cases = [(65, 4), (63, 8), (100, 7), (960, 128), (964, 128)] nb, nt, nq, k = 1000, 700, 20, 5 @@ -183,30 +81,7 @@ def test_uneven_dimension_division(self): f"{recall:.4f}", ) - def test_consistency(self): - """Test that search results are consistent across multiple searches.""" - d = 64 - nb = 500 - nt = 700 - nq = 10 - k = 5 - - # Generate data - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=123) - - index = faiss.IndexHNSWFlatPanorama(d, 16, 8) - index.add(xb) - - # Search twice and compare results - D1, I1 = index.search(xq, k) - D2, I2 = index.search(xq, k) - - # Results should be identical - np.testing.assert_array_equal(I1, I2) - np.testing.assert_array_equal(D1, D2) - def test_io(self): - """Test serialization and deserialization.""" d = 964 nb = 500 nt = 700 @@ -214,30 +89,23 @@ def test_io(self): k = 5 nlevels = 128 - # Generate data _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2024) index = faiss.IndexHNSWFlatPanorama(d, 16, nlevels) index.add(xb) - # Get search results before saving D_before, I_before = index.search(xq, k) - # Save and load using temporary file fname = tempfile.mktemp(suffix=".index") try: faiss.write_index(index, fname) loaded_index = faiss.read_index(fname) self.assertIsInstance(loaded_index, faiss.IndexHNSWFlatPanorama) - self.assertEqual(loaded_index.d, d) - self.assertEqual(loaded_index.ntotal, nb) self.assertEqual(loaded_index.num_panorama_levels, nlevels) - # Search after loading D_after, I_after = loaded_index.search(xq, k) - # Results should be identical after serialization np.testing.assert_array_equal(I_before, I_after) np.testing.assert_array_equal(D_before, D_after) finally: @@ -245,115 +113,60 @@ def test_io(self): os.unlink(fname) def test_clone(self): - """Test index cloning.""" d = 64 nb = 500 nt = 700 nq = 10 k = 5 - # Generate data _, xb, xq = self.generate_data(d, nt, nb, nq, seed=2025) index = faiss.IndexHNSWFlatPanorama(d, 16, 8) index.add(xb) - # Get search results before cloning D_before, I_before = index.search(xq, k) - # Clone cloned_index = faiss.clone_index(index) self.assertIsInstance(cloned_index, faiss.IndexHNSWFlatPanorama) - self.assertEqual(cloned_index.d, d) - self.assertEqual(cloned_index.ntotal, nb) self.assertEqual(cloned_index.num_panorama_levels, 8) - # Search after cloning D_after, I_after = cloned_index.search(xq, k) - # Results should be identical after cloning np.testing.assert_array_equal(I_before, I_after) np.testing.assert_array_equal(D_before, D_after) def test_factory(self): - """Test factory string creation.""" d = 64 - nb = 500 - nt = 700 - # Test factory creation with default levels index1 = faiss.index_factory(d, "HNSW32_FlatPanorama") self.assertIsInstance(index1, faiss.IndexHNSWFlatPanorama) - self.assertEqual(index1.d, d) - self.assertEqual( - index1.hnsw.nb_neighbors(0), 2 * 32 - ) # Level 0 has 2*M neighbors + self.assertEqual(index1.hnsw.nb_neighbors(0), 2 * 32) self.assertEqual(index1.num_panorama_levels, 8) # default - # Test factory creation with explicit levels index2 = faiss.index_factory(d, "HNSW16_FlatPanorama12") self.assertIsInstance(index2, faiss.IndexHNSWFlatPanorama) - self.assertEqual(index2.d, d) - self.assertEqual( - index2.hnsw.nb_neighbors(0), 2 * 16 - ) # Level 0 has 2*M neighbors + self.assertEqual(index2.hnsw.nb_neighbors(0), 2 * 16) self.assertEqual(index2.num_panorama_levels, 12) - # Test that it works - _, xb, _ = self.generate_data(d, nt, nb, 10, seed=888) - index2.add(xb) - self.assertEqual(index2.ntotal, nb) - def test_reset(self): - """Test index reset.""" d = 64 nb = 500 nt = 700 - # Generate data _, xb, _ = self.generate_data(d, nt, nb, 10, seed=999) index = faiss.IndexHNSWFlatPanorama(d, 16, 8) index.add(xb) - self.assertEqual(index.ntotal, nb) self.assertGreater(index.cum_sums.size(), 0) - # Reset index.reset() self.assertEqual(index.ntotal, 0) self.assertEqual(index.cum_sums.size(), 0) - def test_high_dimensional(self): - """Test with high-dimensional data (Panorama is designed for this).""" - d = 512 - nb = 500 - nt = 700 - nq = 50 - k = 10 - - # Generate data - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=789) - - index = faiss.IndexHNSWFlatPanorama(d, 32, 16) - index.hnsw.efSearch = 128 - index.add(xb) - - D, I = index.search(xq, k) - - # Compute ground truth - gt_D, gt_I = self.compute_ground_truth(xb, xq, k) - - recall = self.compute_recall(gt_I, I) - print(f"High-dimensional (d={d}) Recall@{k}: {recall}") - - # Should work well for high-dimensional data - self.assertGreaterEqual(recall, 0.85) - def test_add_after_search(self): - """Test adding vectors after initial search.""" d = 64 nb_initial = 300 nt_initial = 500 @@ -362,7 +175,6 @@ def test_add_after_search(self): nq = 10 k = 5 - # Generate data _, xb_initial, xq = self.generate_data( d, nt_initial, nb_initial, nq, seed=1111 ) @@ -370,80 +182,46 @@ def test_add_after_search(self): index = faiss.IndexHNSWFlatPanorama(d, 16, 8) - # Add initial vectors index.add(xb_initial) - # Search on initial index - D_before, I_before = index.search(xq, k) + index.search(xq, k) - # Add more vectors after search index.add(xb_add) - self.assertEqual(index.ntotal, nb_initial + nb_add) self.assertEqual( index.cum_sums.size(), (nb_initial + nb_add) * (index.num_panorama_levels + 1), ) - # Search again - should work correctly with all vectors - D_after, I_after = index.search(xq, k) + _, I_after = index.search(xq, k) - # Compute ground truth on all vectors xb_all = np.vstack([xb_initial, xb_add]) - gt_D, gt_I = self.compute_ground_truth(xb_all, xq, k) + _, gt_I = self.compute_ground_truth(xb_all, xq, k) recall = self.compute_recall(gt_I, I_after) - print(f"Recall after adding more vectors: {recall}") - - # Recall might be slightly lower than single-batch due to HNSW - # graph structure self.assertGreaterEqual(recall, 0.80) - # Verify that previously found neighbors can still be found - # (they might not be in exact same positions due to new neighbors) - found_count = 0 - for i in range(nq): - for j in range(k): - if I_before[i, j] >= 0: - # Check if this neighbor is still in the result set - if I_before[i, j] in I_after[i, :]: - found_count += 1 - - retention = float(found_count) / (nq * k) - print(f"Retention of previous neighbors: {retention}") - # Should retain a reasonable number of previous neighbors (new ones - # might push some out) - # The threshold is lower to account for the approximate nature of HNSW - self.assertGreaterEqual(retention, 0.5) - def test_permute_entries(self): - """Test permuting entries in the index.""" d = 64 nb = 500 nt = 700 nq = 10 k = 5 - # Generate data _, xb, xq = self.generate_data(d, nt, nb, nq, seed=3333) index = faiss.IndexHNSWFlatPanorama(d, 16, 8) index.add(xb) - # Search before permutation D_before, I_before = index.search(xq, k) - # Create a permutation (reverse order for simplicity) perm = np.arange(nb - 1, -1, -1, dtype=np.int64) - # Store cum_sums before permutation for verification cum_sums_before = faiss.vector_to_array(index.cum_sums).copy() - # Apply permutation index.permute_entries(perm) - # Verify cum_sums were permuted correctly cum_sums_after = faiss.vector_to_array(index.cum_sums) for i in range(nb): src = perm[i] @@ -458,21 +236,15 @@ def test_permute_entries(self): f"cum_sums not permuted correctly at i={i}, j={j}", ) - # Search after permutation D_after, I_after = index.search(xq, k) - # Results should be identical (with permuted IDs) np.testing.assert_allclose( D_before, D_after, err_msg="Distance changed after permutation" ) - # The ID should be the permuted version - # If before we found vector j, after permutation we should find - # the new position of vector j for i in range(nq): for j in range(k): if I_before[i, j] >= 0: - # Find where I_before[i, j] moved to old_id = I_before[i, j] new_id = np.where(perm == old_id)[0][0] self.assertEqual( @@ -481,30 +253,13 @@ def test_permute_entries(self): f"Permuted ID mismatch at position ({i}, {j})", ) - # Verify overall recall is maintained - gt_D, gt_I = self.compute_ground_truth(xb, xq, k) - - # Map ground truth IDs through the permutation - gt_I_permuted = np.copy(gt_I) - for i in range(nq): - for j in range(k): - if gt_I[i, j] >= 0: - # Find where gt_I[i, j] moved to - gt_I_permuted[i, j] = np.where(perm == gt_I[i, j])[0][0] - - recall = self.compute_recall(gt_I_permuted, I_after) - print(f"Recall after permutation: {recall}") - self.assertGreaterEqual(recall, 0.85) - def test_id_selector_range(self): - """Test ID filtering with range selector.""" d = 128 nb = 1000 nt = 1500 nq = 10 k = 10 - # Generate data _, xb, xq = self.generate_data(d, nt, nb, nq, seed=321) index = faiss.IndexHNSWFlatPanorama(d, 32, 8) @@ -515,57 +270,16 @@ def test_id_selector_range(self): params = faiss.SearchParametersHNSW() params.sel = selector - D, I = index.search(xq, k, params=params) + _, I = index.search(xq, k, params=params) - # Verify all returned IDs are in range (HNSW may return < k) - count = 0 + # HNSW may return < k results, padded with -1 for i in range(nq): for j in range(k): if I[i, j] != -1: self.assertGreaterEqual(I[i, j], 200) self.assertLess(I[i, j], 600) - count += 1 - - print(f"IDSelectorRange test: {count} results") - - def test_id_selector_batch(self): - """Test ID filtering with batch selector.""" - d = 128 - nb = 1000 - nt = 1500 - nq = 10 - k = 5 - - # Generate data - _, xb, xq = self.generate_data(d, nt, nb, nq, seed=654) - - index = faiss.IndexHNSWFlatPanorama(d, 32, 8) - index.hnsw.efSearch = 64 - index.add(xb) - - allowed_ids = np.arange(0, nb, 10, dtype=np.int64) - - selector = faiss.IDSelectorBatch(allowed_ids) - params = faiss.SearchParametersHNSW() - params.sel = selector - - D, I = index.search(xq, k, params=params) - - # Verify all returned IDs are in allowed set (HNSW may return < k) - allowed_set = set(allowed_ids) - count = 0 - for i in range(nq): - for j in range(k): - if I[i, j] != -1: - self.assertIn( - I[i, j], allowed_set, f"ID {I[i, j]} not in allowed set" - ) - count += 1 - - print(f"IDSelectorBatch test: {count} results") def test_panorama_stats(self): - """Test that ratio_dims_scanned decreases as nlevels increases.""" d, nb, nq, k = 128, 10000, 10, 10 rs = np.random.RandomState(42) @@ -588,7 +302,6 @@ def test_panorama_stats(self): ratio = faiss.cvar.indexPanorama_stats.ratio_dims_scanned ratios.append(ratio) - print(f" nlevels={nlevels:2d} ratio={ratio:.4f}") for i in range(1, len(ratios)): self.assertLessEqual( diff --git a/thirdparty/faiss/tests/test_hnsw_rabitq.py b/thirdparty/faiss/tests/test_hnsw_rabitq.py index f338a1863..229aaaa89 100644 --- a/thirdparty/faiss/tests/test_hnsw_rabitq.py +++ b/thirdparty/faiss/tests/test_hnsw_rabitq.py @@ -10,15 +10,16 @@ class TestHNSWRaBitQ(unittest.TestCase): - def make_data(self, d=32, nt=400, nb=600, nq=20): - rs = np.random.RandomState(123) - xt = rs.randn(nt, d).astype("float32") - xb = rs.randn(nb, d).astype("float32") - xq = rs.randn(nq, d).astype("float32") - return xt, xb, xq + def setUp(self): + self.addCleanup( + faiss.set_search_stats_enabled, faiss.get_search_stats_enabled() + ) def make_index(self, nb_bits=3): - xt, xb, xq = self.make_data() + rs = np.random.RandomState(123) + xt = rs.randn(400, 32).astype("float32") + xb = rs.randn(600, 32).astype("float32") + xq = rs.randn(20, 32).astype("float32") index = faiss.IndexHNSWRaBitQ( xt.shape[1], 8, nb_bits, faiss.METRIC_L2 ) @@ -28,17 +29,16 @@ def make_index(self, nb_bits=3): index.add(xb) return index, xb, xq - @staticmethod - def recall_at_k(actual, expected): - matches = sum( - len(set(actual[i]).intersection(expected[i])) - for i in range(actual.shape[0]) - ) - return matches / actual.size - def test_staged_search_quality(self): index, xb, xq = self.make_index(nb_bits=3) + faiss.set_search_stats_enabled(False) + faiss.cvar.rabitq_stats.reset() + index.search(xq, 10) + self.assertEqual(faiss.cvar.rabitq_stats.n_1bit, 0) + self.assertEqual(faiss.cvar.rabitq_stats.n_refine, 0) + + faiss.set_search_stats_enabled(True) faiss.cvar.rabitq_stats.reset() D, I = index.search(xq, 10) stats = faiss.cvar.rabitq_stats @@ -49,7 +49,8 @@ def test_staged_search_quality(self): exact = faiss.IndexFlatL2(xb.shape[1]) exact.add(xb) _, Iexact = exact.search(xq, 10) - self.assertGreaterEqual(self.recall_at_k(I, Iexact), 0.8) + recall = faiss.eval_intersection(I, Iexact) / I.size + self.assertGreaterEqual(recall, 0.8) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(np.isfinite(D))) @@ -110,16 +111,6 @@ def test_clone_and_io_remain_mutable(self): loaded.add(xb[:1]) self.assertEqual(loaded.ntotal, len(xb) + 1) - def test_io_and_reset(self): - index, xb, xq = self.make_index(nb_bits=4) - cloned = faiss.clone_index(index) - cloned.add(xb[:1]) - self.assertEqual(cloned.ntotal, len(xb) + 1) - - loaded = faiss.deserialize_index(faiss.serialize_index(index)) - loaded.add(xb[:1]) - self.assertEqual(loaded.ntotal, len(xb) + 1) - loaded.reset() loaded.add(xb) self.assertEqual(loaded.ntotal, len(xb)) @@ -130,6 +121,7 @@ def test_io_and_reset(self): def test_one_bit_fallback(self): index, _, xq = self.make_index(nb_bits=1) self.assertEqual(index.hnsw.search_method, 0) + faiss.set_search_stats_enabled(True) faiss.cvar.rabitq_stats.reset() D, I = index.search(xq, 10) self.assertTrue(np.all(I >= 0)) @@ -169,7 +161,6 @@ def test_factory(self): self.assertIsInstance(default_storage, faiss.IndexRaBitQ) self.assertFalse(default_storage.is_trained) self.assertEqual(default_storage.rabitq.nb_bits, 1) - self.assertEqual(default_index.hnsw.search_method, 0) with self.assertRaises(RuntimeError): default_index.add(np.zeros((1, 32), dtype="float32")) diff --git a/thirdparty/faiss/tests/test_index.py b/thirdparty/faiss/tests/test_index.py index 52de4f73a..e650de843 100644 --- a/thirdparty/faiss/tests/test_index.py +++ b/thirdparty/faiss/tests/test_index.py @@ -3,27 +3,14 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""this is a basic test script for simple indices work""" -from __future__ import absolute_import, division, print_function - -# no unicode_literals because it messes up in py2 - import numpy as np import unittest import faiss -import re from common_faiss_tests import for_all_simd_levels, get_dataset, get_dataset_2 from faiss.contrib.evaluation import check_ref_knn_with_draws -class TestModuleInterface(unittest.TestCase): - - def test_version_attribute(self): - assert hasattr(faiss, "__version__") - assert re.match("^\\d+\\.\\d+\\.\\d+$", faiss.__version__) - - @for_all_simd_levels class TestIndexFlat(unittest.TestCase): @@ -34,9 +21,6 @@ def do_test(self, nq, metric_type=faiss.METRIC_L2, k=10): (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) index = faiss.IndexFlat(d, metric_type) - - ### k-NN search - index.add(xb) D1, I1 = index.search(xq, k) @@ -51,13 +35,9 @@ def do_test(self, nq, metric_type=faiss.METRIC_L2, k=10): Dref = all_dis[np.arange(nq)[:, None], Iref] - # not too many elements are off. self.assertLessEqual((Iref != I1).sum(), Iref.size * 0.0002) - # np.testing.assert_equal(Iref, I1) np.testing.assert_almost_equal(Dref, D1, decimal=5) - ### Range search - radius = float(np.median(Dref[:, -1])) lims, D2, I2 = index.range_search(xq, radius) @@ -80,9 +60,11 @@ def set_blas_blocks(self, small): if small: faiss.cvar.distance_compute_blas_query_bs = 16 faiss.cvar.distance_compute_blas_database_bs = 12 + faiss.cvar.distance_compute_blas_threshold = 0 else: faiss.cvar.distance_compute_blas_query_bs = 4096 faiss.cvar.distance_compute_blas_database_bs = 1024 + faiss.cvar.distance_compute_blas_threshold = 128000 def test_with_blas(self): self.set_blas_blocks(small=True) @@ -92,6 +74,99 @@ def test_with_blas(self): def test_noblas(self): self.do_test(10) + def test_with_blas_top2(self): + self.set_blas_blocks(small=True) + try: + self.do_test(200, k=2) + finally: + self.set_blas_blocks(small=False) + + def test_top2_matches_brute_force_in_every_path(self): + # Database-parallel (nx < threads; nx >= threads below and above the + # BLAS threshold), the BLAS tiles and the sequential scan, on + # near-duplicate database pairs, against an FP64 reference. An + # infinite query gets no result, as in the heaps. + rs = np.random.RandomState(123) + base = rs.rand(6000, 8).astype("float32") + y = np.stack([base, base + 1e-3 * rs.rand(6000, 8).astype("float32")], 1).reshape(-1, 8) + threads, threshold = faiss.omp_get_max_threads(), faiss.cvar.distance_compute_blas_threshold + try: + for nt in (1, 2, 4): + faiss.omp_set_num_threads(nt) + for nx, ny, blas in ((2, 12000, 0), (64, 12000, 10**9), (64, 12000, 0), + (128, 12000, 0), (300, 6000, 0), (300, 6000, 10**9)): + faiss.cvar.distance_compute_blas_threshold = blas + x = rs.rand(nx, 8).astype("float32") + x[0] = np.inf + D, I = faiss.knn(x, y[:ny], 2) + np.testing.assert_array_equal(I[0], [-1, -1]) + np.testing.assert_array_equal(D[0], [np.finfo("float32").max] * 2) + x, D, I = x[1:].astype("float64"), D[1:], I[1:] + exact = (x ** 2).sum(1)[:, None] + (y[:ny].astype("float64") ** 2).sum(1) - 2 * x @ y[:ny].T + top2 = np.sort(exact, axis=1)[:, :2] + self.assertTrue((I >= 0).all() and (I[:, 0] != I[:, 1]).all()) + np.testing.assert_allclose(np.take_along_axis(exact, I, 1), top2, rtol=1e-5, atol=1e-5) + np.testing.assert_allclose(D, top2, rtol=1e-4, atol=1e-5) + finally: + faiss.omp_set_num_threads(threads) + faiss.cvar.distance_compute_blas_threshold = threshold + + def test_top2_inner_product_and_selector(self): + rs = np.random.RandomState(7) + x, y = rs.rand(300, 8).astype("float32"), rs.rand(2000, 8).astype("float32") + subset = rs.choice(2000, 500, replace=False) + ip = x.astype("float64") @ y.T.astype("float64") + threshold = faiss.cvar.distance_compute_blas_threshold + for blas in (0, 10**9): # BLAS tiles and sequential scan + faiss.cvar.distance_compute_blas_threshold = blas + try: + D, I = faiss.knn(x, y, 2, metric=faiss.METRIC_INNER_PRODUCT) + params = faiss.SearchParameters(sel=faiss.IDSelectorBatch(subset)) + index, index_ip = faiss.IndexFlatL2(8), faiss.IndexFlatIP(8) + index.add(y) + index_ip.add(y) + Ds, Is = index.search(x, 2, params=params) + Dp, Ip = index_ip.search(x, 2, params=params) + finally: + faiss.cvar.distance_compute_blas_threshold = threshold + l2 = ((x[:, None].astype("float64") - y[None]) ** 2).sum(-1) + # each returned distance is its id's distance, ids are distinct, + # in the subset, and the two best (best first) + for Dr, Ir, ref, best, ids in ((D, I, ip, -1, None), (Ds, Is, l2, 1, subset), (Dp, Ip, ip, -1, subset)): + pool = ref if ids is None else ref[:, ids] + np.testing.assert_allclose(Dr, np.take_along_axis(ref, Ir, 1), rtol=1e-4, atol=1e-6) + np.testing.assert_allclose(Dr, best * np.sort(best * pool, 1)[:, :2], rtol=1e-4, atol=1e-6) + self.assertTrue((Ir[:, 0] != Ir[:, 1]).all() and (ids is None or np.isin(Ir, ids).all())) + + def test_top2_ties_nan_and_selectors(self): + # 20 equal best L2 distances (ones), 20 equal best inner products + # (twos), 2 NaN rows: ties across AVX2 lanes and BLAS tiles keep the + # heap order, NaN is never a result, selectors leave 0 or 1 results. + y = np.vstack([np.ones((20, 4)), 2 * np.ones((20, 4)), np.full((2, 4), np.nan)]).astype("float32") + big = np.finfo("float32").max + cases = {(faiss.METRIC_L2, -1): ([0, 1], [4, 4]), (faiss.METRIC_INNER_PRODUCT, -1): ([21, 20], [8, 8]), + (faiss.METRIC_L2, 0): ([-1, -1], [big, big]), (faiss.METRIC_INNER_PRODUCT, 0): ([-1, -1], [-big, -big]), + (faiss.METRIC_L2, 1): ([5, -1], [4, big]), (faiss.METRIC_INNER_PRODUCT, 1): ([5, -1], [4, -big])} + try: + for small in (False, True): + self.set_blas_blocks(small=True) + if not small: + faiss.cvar.distance_compute_blas_database_bs = 1024 + for (metric, n_sel), (ids, dis) in cases.items(): + index = faiss.IndexFlat(4, metric) + index.add(y) + sel = None if n_sel < 0 else faiss.IDSelectorBatch(np.array([5][:n_sel], "int64")) + x = np.zeros((40, 4), "float32") + (metric == faiss.METRIC_INNER_PRODUCT) + D, I = index.search(x, 2, params=sel and faiss.SearchParameters(sel=sel)) + np.testing.assert_array_equal(I, np.tile(ids, (40, 1))) + np.testing.assert_array_equal(D, np.tile(np.float32(dis), (40, 1))) + for ny in (0, 1): + D, I = faiss.knn(np.zeros((40, 4), "float32"), y[:ny], 2) + np.testing.assert_array_equal(I, np.tile([0, -1][:ny] + [-1, -1][ny:], (40, 1))) + np.testing.assert_array_equal(D, np.tile(np.float32([4, big][:ny] + [big, big][ny:]), (40, 1))) + finally: + self.set_blas_blocks(small=False) + def test_with_blas_ip(self): self.set_blas_blocks(small=True) self.do_test(200, faiss.METRIC_INNER_PRODUCT) @@ -104,13 +179,17 @@ def test_noblas_reservoir(self): self.do_test(10, k=150) def test_with_blas_reservoir(self): + self.set_blas_blocks(small=True) self.do_test(200, k=150) + self.set_blas_blocks(small=False) def test_noblas_reservoir_ip(self): self.do_test(10, faiss.METRIC_INNER_PRODUCT, k=150) def test_with_blas_reservoir_ip(self): + self.set_blas_blocks(small=True) self.do_test(200, faiss.METRIC_INNER_PRODUCT, k=150) + self.set_blas_blocks(small=False) def test_empty_query_batch(self): """search()/range_search() with nq=0 must not enter an OpenMP @@ -128,9 +207,7 @@ def test_empty_query_batch(self): index = faiss.IndexFlat(d, metric_type) index.add(xb) - D, I = index.search(xq_empty, 10) - self.assertEqual(D.shape, (0, 10)) - self.assertEqual(I.shape, (0, 10)) + index.search(xq_empty, 10) lims, _, _ = index.range_search(xq_empty, 1.0) np.testing.assert_array_equal( @@ -141,7 +218,8 @@ def test_empty_index_with_blas(self): # The threshold is what makes this a regression test: it puts the # search in a configuration that would otherwise select the BLAS path, # which returns early on an empty database without ever initializing - # the result handler. k covers the Top1, heap, and reservoir handlers. + # the result handler. k covers the Top1, Top2, heap, and reservoir + # handlers. saved_threshold = faiss.cvar.distance_compute_blas_threshold faiss.cvar.distance_compute_blas_threshold = 1 try: @@ -153,7 +231,7 @@ def test_empty_index_with_blas(self): else np.finfo("float32").min ) index = faiss.IndexFlat(1, metric_type) - for k in (1, 10, 150): + for k in (1, 2, 10, 150): with self.subTest(metric_type=metric_type, k=k): D = np.full((len(xq), k), 42, dtype="float32") I = np.full((len(xq), k), 99, dtype="int64") @@ -166,10 +244,8 @@ def test_empty_index_with_blas(self): @for_all_simd_levels class TestDbParallelSearch(unittest.TestCase): - """Test the database-parallel search path that activates when - the number of queries is smaller than the thread count and the - database is large enough. Validates correctness for both IP and L2 - metrics, multiple k values, and edge cases.""" + """Database-parallel search: a large database, and nq < thread count or + nq below the BLAS threshold.""" def _check(self, metric_type, nq, nb, k): d = 64 @@ -181,10 +257,10 @@ def _check(self, metric_type, nq, nb, k): index.add(xb) D, I = index.search(xq, k) - # compute ground truth with numpy if metric_type == faiss.METRIC_L2: - all_dis = ((xq.reshape(nq, 1, d) - xb.reshape(1, nb, d)) ** 2).sum( - 2 + xq64, xb64 = xq.astype("float64"), xb.astype("float64") + all_dis = ( + (xq64**2).sum(1)[:, None] + (xb64**2).sum(1) - 2 * xq64 @ xb64.T ) Iref = all_dis.argsort(axis=1)[:, :k] else: @@ -192,22 +268,11 @@ def _check(self, metric_type, nq, nb, k): Iref = all_dis.argsort(axis=1)[:, ::-1][:, :k] Dref = all_dis[np.arange(nq)[:, None], Iref] - np.testing.assert_almost_equal(Dref, D, decimal=5) - - def test_ip_single_query(self): - """nx=1, triggers db-parallel when nthreads > 1""" - self._check(faiss.METRIC_INNER_PRODUCT, nq=1, nb=20000, k=10) - - def test_ip_few_queries(self): - """nx=4, typical case for db-parallel""" - self._check(faiss.METRIC_INNER_PRODUCT, nq=4, nb=20000, k=10) + np.testing.assert_allclose(D, Dref, rtol=1e-5) def test_l2_single_query(self): self._check(faiss.METRIC_L2, nq=1, nb=20000, k=10) - def test_l2_few_queries(self): - self._check(faiss.METRIC_L2, nq=4, nb=20000, k=10) - def test_ip_k1(self): """k=1 uses Top1BlockResultHandler in original path""" self._check(faiss.METRIC_INNER_PRODUCT, nq=2, nb=20000, k=1) @@ -215,12 +280,16 @@ def test_ip_k1(self): def test_l2_k1(self): self._check(faiss.METRIC_L2, nq=2, nb=20000, k=1) - def test_ip_large_k(self): - """k=200 uses ReservoirBlockResultHandler in original path""" - self._check(faiss.METRIC_INNER_PRODUCT, nq=2, nb=20000, k=200) - - def test_l2_large_k(self): - self._check(faiss.METRIC_L2, nq=2, nb=20000, k=200) + def test_nq_at_and_above_thread_count(self): + """nq >= thread count, below and above the BLAS threshold.""" + saved_nt = faiss.omp_get_max_threads() + try: + faiss.omp_set_num_threads(4) + for metric_type in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + for nq in 4, 5, 40, 2500: + self._check(metric_type, nq=nq, nb=20000, k=10) + finally: + faiss.omp_set_num_threads(saved_nt) def test_thread_scaling(self): """Verify results are identical across different thread counts.""" @@ -248,6 +317,16 @@ def test_thread_scaling(self): finally: faiss.omp_set_num_threads(saved_nt) + def test_nested_search(self): + # IndexIVF::search calls the quantizer inside a parallel region + d, nlist = 8, 10000 + _, xb, xq = get_dataset(d, nlist, 0, 2) + quantizer = faiss.IndexFlatL2(d) + quantizer.add(xb) + index = faiss.IndexIVFFlat(quantizer, d, nlist) + index.add(xq) + np.testing.assert_array_equal(index.search(xq, 1)[1], [[0], [1]]) + @for_all_simd_levels class TestIndexFlatL2(unittest.TestCase): @@ -260,7 +339,6 @@ def test_indexflat_l2_sync_norms_1(self): (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - # instantiate IndexHNSWFlat index = faiss.IndexHNSWFlat(d, 32) index.hnsw.efConstruction = 40 @@ -274,63 +352,13 @@ def test_indexflat_l2_sync_norms_1(self): index_l2.clear_l2norms() D3, I3 = index.search(xq, k) - # not too many elements are off. self.assertLessEqual((I2 != I1).sum(), 1) - # np.testing.assert_equal(Iref, I1) np.testing.assert_almost_equal(D2, D1, decimal=5) - # not too many elements are off. self.assertLessEqual((I3 != I1).sum(), 0) - # np.testing.assert_equal(Iref, I1) np.testing.assert_equal(D3, D1) -@for_all_simd_levels -class TestIndexFlatL2Panorama(unittest.TestCase): - def test_indexflat_l2_panorama(self): - d = 32 - nlevels = 8 - batch_size = 128 - nq = 200 - nb = 1000 - nt = 0 - k = 10 - - (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - index = faiss.IndexFlatL2Panorama(d, nlevels, batch_size) - - ### k-NN search - - index.add(xb) - D1, I1 = index.search(xq, k) - - all_dis = ((xq.reshape(nq, 1, d) - xb.reshape(1, nb, d)) ** 2).sum(2) - Iref = all_dis.argsort(axis=1)[:, :k] - - Dref = all_dis[np.arange(nq)[:, None], Iref] - - # not too many elements are off. - self.assertLessEqual((Iref != I1).sum(), Iref.size * 0.0002) - np.testing.assert_almost_equal(Dref, D1, decimal=5) - - ### Range search - - radius = float(np.median(Dref[:, -1])) - - lims, D2, I2 = index.range_search(xq, radius) - - for i in range(nq): - l0, l1 = lims[i : i + 2] - _, Il = D2[l0:l1], I2[l0:l1] - (Ilref,) = np.where(all_dis[i] < radius) - Il.sort() - Ilref.sort() - np.testing.assert_equal(Il, Ilref) - np.testing.assert_almost_equal( - all_dis[i, Ilref], D2[l0:l1], decimal=5 - ) - - @for_all_simd_levels class EvalIVFPQAccuracy(unittest.TestCase): @@ -354,7 +382,6 @@ def test_IndexIVFPQ(self): index.nprobe = 4 D, nns = index.search(xq, 10) n_ok = (nns == gt_nns).sum() - nq = xq.shape[0] self.assertGreater(n_ok, nq * 0.66) @@ -362,11 +389,7 @@ def test_IndexIVFPQ(self): # this is a bit fragile: it assumes 2 runs of training give # the exact same result. index2 = faiss.Index2Layer(coarse_quantizer, 32, 8) - if True: - index2.train(xt) - else: - index2.pq = index.pq - index2.is_trained = True + index2.train(xt) index2.add(xb) ref_recons = index.reconstruct_n(0, nb) new_recons = index2.reconstruct_n(0, nb) @@ -379,7 +402,6 @@ def test_IMI(self): nq = 200 (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - d = xt.shape[1] gt_index = faiss.IndexFlatL2(d) gt_index.add(xb) @@ -398,31 +420,6 @@ def test_IMI(self): # Should return 166 on mac, and 170 on linux. self.assertGreater(n_ok, 165) - ############# replace with explicit assignment indexes - nbits = 5 - pq = coarse_quantizer.pq - centroids = faiss.vector_to_array(pq.centroids) - centroids = centroids.reshape(pq.M, pq.ksub, pq.dsub) - ai0 = faiss.IndexFlatL2(pq.dsub) - ai0.add(centroids[0]) - ai1 = faiss.IndexFlatL2(pq.dsub) - ai1.add(centroids[1]) - - coarse_quantizer_2 = faiss.MultiIndexQuantizer2(d, nbits, ai0, ai1) - coarse_quantizer_2.pq = pq - coarse_quantizer_2.is_trained = True - - index.quantizer = coarse_quantizer_2 - - index.reset() - index.add(xb) - - D, nns = index.search(xq, 10) - n_ok = (nns == gt_nns).sum() - - # should return the same result - self.assertGreater(n_ok, 165) - def test_IMI_2(self): d = 32 nb = 1000 @@ -430,13 +427,11 @@ def test_IMI_2(self): nq = 200 (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - d = xt.shape[1] gt_index = faiss.IndexFlatL2(d) gt_index.add(xb) D, gt_nns = gt_index.search(xq, 1) - ############# redo including training nbits = 5 ai0 = faiss.IndexFlatL2(int(d / 2)) ai1 = faiss.IndexFlatL2(int(d / 2)) @@ -450,7 +445,6 @@ def test_IMI_2(self): D, nns = index.search(xq, 10) n_ok = (nns == gt_nns).sum() - # should return the same result self.assertGreater(n_ok, 165) @@ -490,7 +484,6 @@ def test_4variants_ivf(self): (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - # common quantizer quantizer = faiss.IndexFlatL2(d) ncent = 64 @@ -532,7 +525,6 @@ def test_4variants_ivf(self): # jitter self.assertGreaterEqual(nok["flat"], nok["QT_8bit"]) self.assertGreaterEqual(nok["QT_8bit"], nok["QT_4bit"]) - # flaky: self.assertGreaterEqual(nok['QT_8bit'], nok['QT_8bit_uniform']) self.assertGreaterEqual(nok["QT_4bit"], nok["QT_4bit_uniform"]) self.assertGreaterEqual(nok["QT_fp16"], nok["QT_8bit"]) self.assertGreaterEqual(nok["QT_bf16"], nok["QT_8bit"]) @@ -563,7 +555,6 @@ def test_4variants(self): self.assertGreaterEqual(nok["QT_8bit"], nq * 0.9) self.assertGreaterEqual(nok["QT_8bit"], nok["QT_4bit"]) - # flaky: self.assertGreaterEqual(nok['QT_8bit'], nok['QT_8bit_uniform']) self.assertGreaterEqual(nok["QT_4bit"], nok["QT_4bit_uniform"]) self.assertGreaterEqual(nok["QT_fp16"], nok["QT_8bit"]) self.assertGreaterEqual(nok["QT_bf16"], nq * 0.9) @@ -580,7 +571,6 @@ def test_range_search(self): (xt, xb, xq) = get_dataset(d, nb, nt, nq) for metric, thresh in [ - (faiss.METRIC_L2, 0.1), (faiss.METRIC_L1, 0.5), ]: index = faiss.IndexFlat(d, metric) @@ -605,8 +595,6 @@ class TestSearchAndReconstruct(unittest.TestCase): def run_search_and_reconstruct(self, index, xb, xq, k=10, eps=None): n, d = xb.shape - assert xq.shape[1] == d - assert index.d == d D_ref, I_ref = index.search(xq, k) R_ref = index.reconstruct_n(0, n) @@ -614,10 +602,7 @@ def run_search_and_reconstruct(self, index, xb, xq, k=10, eps=None): np.testing.assert_almost_equal(D, D_ref, decimal=5) check_ref_knn_with_draws(D_ref, I_ref, D, I) - self.assertEqual(R.shape[:2], I.shape) - self.assertEqual(R.shape[2], d) - # (n, k, ..) -> (n * k, ..) I_flat = I.reshape(-1) R_flat = R.reshape(-1, d) # Filter out -1s when not enough results @@ -775,7 +760,7 @@ def test_l2_pos(self): class TestShardReplicas(unittest.TestCase): def test_shard_flag_propagation(self): - d = 64 # dimension + d = 64 nb = 1000 rs = np.random.RandomState(1234) xb = rs.rand(nb, d).astype("float32") @@ -803,7 +788,7 @@ def test_shard_flag_propagation(self): self.assertEqual(index.ntotal, 0) def test_replica_flag_propagation(self): - d = 64 # dimension + d = 64 nb = 1000 rs = np.random.RandomState(1234) xb = rs.rand(nb, d).astype("float32") @@ -835,12 +820,12 @@ class TestReconsException(unittest.TestCase): def test_recons_exception(self): - d = 64 # dimension + d = 64 nb = 1000 rs = np.random.RandomState(1234) xb = rs.rand(nb, d).astype("float32") nlist = 10 - quantizer = faiss.IndexFlatL2(d) # the other index + quantizer = faiss.IndexFlatL2(d) index = faiss.IndexIVFFlat(quantizer, d, nlist) index.train(xb) index.add(xb) @@ -849,6 +834,11 @@ def test_recons_exception(self): index.reconstruct(9) self.assertRaises(RuntimeError, index.reconstruct, 100001) + invlists = index.invlists + self.assertRaises(RuntimeError, invlists.list_size, nlist) + self.assertRaises(RuntimeError, invlists.get_ids, nlist) + self.assertRaises(RuntimeError, invlists.get_codes, nlist) + self.assertRaises(RuntimeError, invlists.is_empty, nlist) def test_reconstruct_after_add(self): index = faiss.index_factory(10, "IVF5,SQfp16") @@ -865,18 +855,15 @@ def test_reconstruct_larger_ntotal(self): vect_dim = 5 n_vectors = 10 - # Create the dataset data = np.random.randint(100, size=(n_vectors, vect_dim)) - # Build index index = faiss.IndexFlatL2(vect_dim) index.add(data) - # Reconstruct < ntotal (10) without an issue index.reconstruct(9) - # Reconstruct >= ntotal (10), assert exception raise self.assertRaises(RuntimeError, index.reconstruct, 10) + self.assertRaises(RuntimeError, index.reconstruct, -1) class TestReconsHash(unittest.TestCase): @@ -886,12 +873,10 @@ def do_test(self, index_key): index = faiss.index_factory(d, index_key) index.train(faiss.randn((100, d), 123)) - # reference reconstruction index.add(faiss.randn((100, d), 345)) index.add(faiss.randn((100, d), 678)) ref_recons = index.reconstruct_n(0, 200) - # with lookup index.reset() rs = np.random.RandomState(123) ids = rs.choice(10000, size=200, replace=False).astype(np.int64) @@ -899,21 +884,17 @@ def do_test(self, index_key): index.set_direct_map_type(faiss.DirectMap.Hashtable) index.add_with_ids(faiss.randn((100, d), 678), ids[100:]) - # compare for i in range(0, 200, 13): recons = index.reconstruct(int(ids[i])) self.assertTrue(np.all(recons == ref_recons[i])) - # test I/O buf = faiss.serialize_index(index) index2 = faiss.deserialize_index(buf) - # compare for i in range(0, 200, 13): recons = index2.reconstruct(int(ids[i])) self.assertTrue(np.all(recons == ref_recons[i])) - # remove toremove = np.ascontiguousarray(ids[0:200:3]) sel = faiss.IDSelectorArray(50, faiss.swig_ptr(toremove[:50])) @@ -931,7 +912,6 @@ def do_test(self, index_key): recons = index2.reconstruct(int(ids[i])) self.assertTrue(np.all(recons == ref_recons[i])) - # index error should raise self.assertRaises(RuntimeError, index.reconstruct, 20000) def test_IVFFlat(self): @@ -960,46 +940,14 @@ def test_IndexIVFPQ(self): index.train(xt) index.add(xb) - # invalid nprobe index.nprobe = 0 k = 10 self.assertRaises(RuntimeError, index.search, xq, k) - # invalid k index.nprobe = 4 k = -10 self.assertRaises(AssertionError, index.search, xq, k) - # valid params - index.nprobe = 4 - k = 10 - D, nns = index.search(xq, k) - - self.assertEqual(D.shape[0], nq) - self.assertEqual(D.shape[1], k) - - def test_IndexFlat(self): - d = 32 - nb = 1000 - nt = 0 - nq = 200 - - (xt, xb, xq) = get_dataset_2(d, nt, nb, nq) - index = faiss.IndexFlat(d, faiss.METRIC_L2) - - index.add(xb) - - # invalid k - k = -5 - self.assertRaises(AssertionError, index.search, xq, k) - - # valid k - k = 5 - D, I = index.search(xq, k) - - self.assertEqual(D.shape[0], nq) - self.assertEqual(D.shape[1], k) - class TestLargeRangeSearch(unittest.TestCase): @@ -1009,15 +957,18 @@ def test_range_search(self): nq = 16 nb = 1000000 - # faiss.cvar.distance_compute_blas_threshold = 10 - faiss.omp_set_num_threads(1) + saved_nt = faiss.omp_get_max_threads() + try: + faiss.omp_set_num_threads(1) - index = faiss.IndexFlatL2(d) - xb = np.zeros((nb, d), dtype="float32") - index.add(xb) + index = faiss.IndexFlatL2(d) + xb = np.zeros((nb, d), dtype="float32") + index.add(xb) - xq = np.zeros((nq, d), dtype="float32") - lims, D, I = index.range_search(xq, 1.0) + xq = np.zeros((nq, d), dtype="float32") + lims, D, I = index.range_search(xq, 1.0) + finally: + faiss.omp_set_num_threads(saved_nt) assert len(D) == len(xb) * len(xq) @@ -1025,8 +976,6 @@ def test_range_search(self): class TestRandomIndex(unittest.TestCase): def test_random(self): - """just check if several runs of search retrieve the - same results""" index = faiss.IndexRandom(32, 1000000000) (xt, xb, xq) = get_dataset_2(32, 0, 0, 10) diff --git a/thirdparty/faiss/tests/test_index_accuracy.py b/thirdparty/faiss/tests/test_index_accuracy.py index ac8f40a2e..d01ee7e49 100644 --- a/thirdparty/faiss/tests/test_index_accuracy.py +++ b/thirdparty/faiss/tests/test_index_accuracy.py @@ -3,15 +3,10 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import absolute_import, division, print_function - import unittest import faiss -# noqa E741 -# translation of test_knn.lua - import numpy as np from common_faiss_tests import ( for_all_simd_levels, @@ -37,33 +32,6 @@ class IndexAccuracy(unittest.TestCase): - def test_IndexFlatIP(self): - q = faiss.IndexFlatIP(d) # Ask inner product - res = ev.launch("FLAT / IP", q) - e = ev.evalres(res) - assert e[1] == 1.0 - - def test_IndexFlatL2(self): - q = faiss.IndexFlatL2(d) - res = ev.launch("FLAT / L2", q) - e = ev.evalres(res) - assert e[1] == 1.0 - - def test_ivf_kmeans(self): - ivfk = faiss.IndexIVFFlat(faiss.IndexFlatL2(d), d, ncentroids) - ivfk.nprobe = kprobe - res = ev.launch("IndexIVFFlat", ivfk) - e = ev.evalres(res) - # should give 0.260 0.260 0.260 - assert e[1] > 0.2 - - # test parallel mode - Dref, Iref = ivfk.search(ev.xq, 100) - ivfk.parallel_mode = 1 - Dnew, Inew = ivfk.search(ev.xq, 100) - assert (Iref != Inew).sum() < Iref.size / 5000.0 - assert np.all(Dref == Dnew) - def test_indexLSH(self): q = faiss.IndexLSH(d, nbits) res = ev.launch("FLAT / LSH Cosine", q) @@ -72,7 +40,6 @@ def test_indexLSH(self): assert e[10] > 0.2 def test_IndexLSH_32_48(self): - # CHECK: the difference between 32 and 48 does not make much sense for nbits2 in 32, 48: q = faiss.IndexLSH(d, nbits2) res = ev.launch("LSH half size", q) @@ -87,7 +54,6 @@ def test_IndexPQ(self): # should give 0.070 0.230 0.260 assert e[10] > 0.2 - # Approximate search module: PQ with inner product distance def test_IndexPQ_ip(self): q = faiss.IndexPQ(d, M, nbits_per_index, faiss.METRIC_INNER_PRODUCT) res = ev.launch("FLAT / PQ IP", q) @@ -101,28 +67,8 @@ def test_IndexIVFPQ(self): ivfpq.nprobe = kprobe res = ev.launch("IVF PQ", ivfpq) e = ev.evalres(res) - # should give 0.070 0.230 0.260 assert e[10] > 0.2 - # TODO: translate evaluation of nested - - # Approximate search: PQ with full vector refinement - def test_IndexPQ_refined(self): - q = faiss.IndexPQ(d, M, nbits_per_index) - res = ev.launch("PQ non-refined", q) - e = ev.evalres(res) - q.reset() - - rq = faiss.IndexRefineFlat(q) - res = ev.launch("PQ refined", rq) - e2 = ev.evalres(res) - assert e2[10] >= e[10] - rq.k_factor = 4 - - res = ev.launch("PQ refined*4", rq) - e3 = ev.evalres(res) - assert e3[10] >= e2[10] - def test_polysemous(self): index = faiss.IndexPQ(d, M, nbits_per_index) index.do_polysemous_training = True @@ -148,17 +94,6 @@ def test_polysemous(self): # TODO check why??? # assert e_polysemous[10] > e_baseline[10] - 0.1 - def test_ScalarQuantizer(self): - quantizer = faiss.IndexFlatL2(d) - ivfpq = faiss.IndexIVFScalarQuantizer( - quantizer, d, ncentroids, faiss.ScalarQuantizer.QT_8bit - ) - ivfpq.nprobe = kprobe - res = ev.launch("IVF SQ", ivfpq) - e = ev.evalres(res) - # should give 0.234 0.236 0.236 - assert e[10] > 0.235 - def test_polysemous_OOM(self): """this used to cause OOM when training polysemous with large nb bits""" @@ -216,7 +151,6 @@ def subtest_add2col(self, xb, xq, index, qname): index2.add(xb2) return index2.search(xq2, 10) - # run on Sept 18, 2018 with nprobe=4 + 4 bit bugfix ref_results = { (0, "8bit"): 984, (0, "4bit"): 978, @@ -228,7 +162,6 @@ def subtest_add2col(self, xb, xq, index, qname): (1, "8bit_uniform"): 979, (1, "4bit_uniform"): 972, (1, "fp16"): 979, - # added 2019-06-26 (0, "6bit"): 985, (1, "6bit"): 987, } @@ -261,8 +194,6 @@ def subtest(self, mt): D2, I2 = self.subtest_add2col(xb, xq, index, qname) assert np.all(I2 == I) - # also test range search - if mt == faiss.METRIC_INNER_PRODUCT: radius = float(D[:, -1].max()) else: @@ -358,8 +289,6 @@ def rescale_signed(x): assert np.all(I == Iref) assert np.all(D == Dref) - # same, with IVF - nlist = 64 quantizer = faiss.IndexFlat(d, metric_type) @@ -398,12 +327,6 @@ def test_L1(self): for search_L, threshold in zip(search_Ls, thresholds): self.subtest(32, faiss.METRIC_L1, 10, search_L, threshold) - def test_L2(self): - search_Ls = [10, 20, 30] - thresholds = [0.83, 0.92, 0.95] - for search_L, threshold in zip(search_Ls, thresholds): - self.subtest(32, faiss.METRIC_L2, 10, search_L, threshold) - def test_IP(self): search_Ls = [10, 20, 30] thresholds = [0.80, 0.90, 0.93] @@ -413,12 +336,6 @@ def test_IP(self): ) def subtest(self, d, metric, topk, search_L, threshold): - metric_names = { - faiss.METRIC_L1: "L1", - faiss.METRIC_L2: "L2", - faiss.METRIC_INNER_PRODUCT: "IP", - } - topk = 10 nt, nb, nq = 2000, 1000, 200 xt, xb, xq = get_dataset_2(d, nt, nb, nq) gt_index = faiss.IndexFlat(d, metric) @@ -445,17 +362,11 @@ def subtest(self, d, metric, topk, search_L, threshold): recalls += 1 break recall = 1.0 * recalls / (nq * topk) - print( - "Metric: {}, L: {}, Recall@{}: {}".format( - metric_names[metric], search_L, topk, recall - ) - ) assert recall > threshold, "{} <= {}".format(recall, threshold) class TestPQFlavors(unittest.TestCase): - # run on Dec 14, 2018 ref_results = { (1, True): 800, (1, True, 20): 794, @@ -520,8 +431,6 @@ def subtest(self, mt): - 4 ) - # also test range search - if mt == faiss.METRIC_INNER_PRODUCT: radius = float(D[:, -1].max()) else: @@ -563,14 +472,7 @@ def test_IVFPQ_non8bit(self): D, I = index.search(xq, 10) ninter[v] = faiss.eval_intersection(I, gt_I) - # this should be the case but we don't observe - # that... Probavly too few test points - # assert ninter['2x8'] > ninter['8x2'] - # ref numbers updated on 2025-01-19 after fixing nprobe typo - # (was 'npobe') - # Old values were 458/465 based on broken test with default nprobe - # New values reflect proper nprobe=16 configuration with much better - # search quality + # 2x8 should beat 8x2 but does not, probably too few test points assert abs(ninter["2x8"] - 929) < 4 assert abs(ninter["8x2"] - 960) < 4 @@ -600,7 +502,6 @@ def test_flat_1d(self): assert max_diff_D < 1e-5 def test_size_0(self): - # just make sure it does not crash on small nb index = faiss.IndexFlat1D() rs = np.random.RandomState(123) for i in range(3): @@ -611,7 +512,6 @@ def test_size_0(self): class OPQRelativeAccuracy(unittest.TestCase): - # translated from test_opq.lua def test_OPQ(self): @@ -626,7 +526,6 @@ def test_OPQ(self): index_pq = faiss.IndexPQ(d, M, 8) opq_matrix = faiss.OPQMatrix(d, M) - # opq_matrix.verbose = true opq_matrix.niter = 10 opq_matrix.niter_pq = 4 index = faiss.IndexPreTransform(opq_matrix, index_pq) @@ -634,41 +533,9 @@ def test_OPQ(self): res = ev.launch("OPQ", index) e_opq = ev.evalres(res) - # verify that OPQ better than PQ for r in 1, 10, 100: assert e_opq[r] > e_pq[r] - def test_OIVFPQ(self): - # Parameters inverted indexes - ncentroids = 50 - M = 4 - - ev = Randu10kUnbalanced() - d = ev.d - quantizer = faiss.IndexFlatL2(d) - index = faiss.IndexIVFPQ(quantizer, d, ncentroids, M, 8) - index.nprobe = 20 - - res = ev.launch("IVFPQ", index) - e_ivfpq = ev.evalres(res) - - quantizer = faiss.IndexFlatL2(d) - index_ivfpq = faiss.IndexIVFPQ(quantizer, d, ncentroids, M, 8) - index_ivfpq.nprobe = 20 - opq_matrix = faiss.OPQMatrix(d, M) - opq_matrix.niter = 12 - index = faiss.IndexPreTransform(opq_matrix, index_ivfpq) - - res = ev.launch("O+IVFPQ", index) - e_oivfpq = ev.evalres(res) - - # verify same on OIVFPQ - for r in 1, 10, 100: - assert e_oivfpq[r] >= e_ivfpq[r] - 0.005, ( - f"recall@{r}: OPQ+IVFPQ ({e_oivfpq[r]:.4f}) " - f"< IVFPQ ({e_ivfpq[r]:.4f})" - ) - class TestRoundoff(unittest.TestCase): def test_roundoff(self): @@ -710,7 +577,6 @@ def test_roundoff(self): @for_all_simd_levels class TestSpectralHash(unittest.TestCase): - # run on 2019-04-02 ref_results = { (32, "global", 10): 505, (32, "centroid", 10): 524, @@ -750,13 +616,6 @@ def test_sh(self): for nbit in 32, 64, 128: quantizer = faiss.IndexFlatL2(d) - index_lsh = faiss.IndexLSH(d, nbit, True) - index_lsh.add(xb) - D, I = index_lsh.search(xq, 10) - ninter = faiss.eval_intersection(I, gt_I) - - print("LSH baseline: %d" % ninter) - for period in 10.0, 1.0: for tt in "global centroid centroid_half median".split(): @@ -792,7 +651,6 @@ def do_test(self, metric): recall1 = (I1 == Iref[:, :1]).sum() - # add refine index on top index_flat = faiss.IndexFlat(d, metric) index_flat.add(xb) @@ -800,7 +658,6 @@ def do_test(self, metric): index2.k_factor = 10.0 D2, I2 = index2.search(xq, 10) - # check distance is computed properly for i in range(len(xq)): x1 = xq[i] x2 = xb[I2[i, 5]] diff --git a/thirdparty/faiss/tests/test_index_binary.py b/thirdparty/faiss/tests/test_index_binary.py index 05597e46c..2ee7ffd0a 100644 --- a/thirdparty/faiss/tests/test_index_binary.py +++ b/thirdparty/faiss/tests/test_index_binary.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""this is a basic test script for simple indices work""" - import os import numpy as np import unittest @@ -114,9 +112,6 @@ def test_flat(self): ref_dis = binary_dis(self.xq[i], self.xb[j]) assert dj == ref_dis - # test reconstruction - assert np.all(index.reconstruct(12) == self.xb[12]) - def test_empty_flat(self): d = self.xq.shape[1] * 8 @@ -127,7 +122,7 @@ def test_empty_flat(self): Dflat, Iflat = index.search(self.xq, 10) assert np.all(Iflat == -1) - assert np.all(Dflat == 2147483647) # NOTE(hoss): int32_t max + assert np.all(Dflat == 2147483647) # int32_t max def test_range_search(self): d = self.xq.shape[1] * 8 @@ -148,7 +143,6 @@ def test_range_search(self): self.assertTrue(set(range_res) <= set(I[i])) nt2 += 1 # in case of equality we have a problem with ties - # nb tests is actually low... self.assertTrue(nt1 > 19 and nt2 > 19) def test_reconstruct(self): @@ -162,6 +156,10 @@ def test_reconstruct(self): assert reconstructed_vector.shape == (4, index.code_size) assert np.all(input_vector[:4] == reconstructed_vector) + np.testing.assert_array_equal(index.reconstruct(9), input_vector[9]) + for key in -1, 10, 10**9: + self.assertRaises(RuntimeError, index.reconstruct, key) + @for_all_simd_levels class TestBinaryIVF(unittest.TestCase): @@ -179,19 +177,6 @@ def __init__(self, *args, **kwargs): Dref, Iref = index.search(self.xq, 10) self.Dref = Dref - def test_ivf_flat_exhaustive(self): - d = self.xq.shape[1] * 8 - - quantizer = faiss.IndexBinaryFlat(d) - index = faiss.IndexBinaryIVF(quantizer, d, 8) - index.cp.min_points_per_centroid = 5 # quiet warning - index.nprobe = 8 - index.train(self.xt) - index.add(self.xb) - Divfflat, _ = index.search(self.xq, 10) - - np.testing.assert_array_equal(self.Dref, Divfflat) - def test_ivf_flat2(self): d = self.xq.shape[1] * 8 @@ -240,7 +225,7 @@ def test_ivf_flat_empty(self): Divfflat, Iivfflat = index.search(self.xq, 10) assert np.all(Iivfflat == -1) - assert np.all(Divfflat == 2147483647) # NOTE(hoss): int32_t max + assert np.all(Divfflat == 2147483647) # int32_t max def test_ivf_reconstruction(self): d = self.xq.shape[1] * 8 @@ -256,7 +241,6 @@ def test_ivf_reconstruction(self): for i in range(0, len(self.xb), 13): np.testing.assert_array_equal(index.reconstruct(i), self.xb[i]) - # try w/ hashtable index = faiss.IndexBinaryIVF(quantizer, d, 8) rs = np.random.RandomState(123) ids = rs.choice(10000, size=len(self.xb), replace=False).astype( @@ -288,7 +272,6 @@ def test_ivf_nprobe(self): d = self.xq.shape[1] * 8 xt, xb, xq = self.xt, self.xb, self.xq - # nlist = 10 index = faiss.index_binary_factory(d, "BIVF10") # When nprobe >= nlist, it is equivalent to an IndexFlat. @@ -298,7 +281,6 @@ def test_ivf_nprobe(self): index.nprobe = 2048 k = 5 - # test kNN search D, I = index.search(xq, k) ref_index = faiss.index_binary_factory(d, "BFlat") @@ -306,15 +288,12 @@ def test_ivf_nprobe(self): ref_D, ref_I = ref_index.search(xq, k) assert np.all(D == ref_D) - # assert np.all(I == ref_I) # id may be different - # test range search - thresh = 5 # *squared* distance + thresh = 5 lims, D, I = index.range_search(xq, thresh) ref_lims, ref_D, ref_I = ref_index.range_search(xq, thresh) assert np.all(lims == ref_lims) assert np.all(D == ref_D) - # assert np.all(I == ref_I) # id may be different def test_search_per_invlist(self): d = self.xq.shape[1] * 8 @@ -360,7 +339,7 @@ def test_hnsw_exact_distances(self): def test_hnsw(self): d = self.xq.shape[1] * 8 - # NOTE(hoss): Ensure the HNSW construction is deterministic. + # Ensure the HNSW construction is deterministic. nthreads = faiss.omp_get_max_threads() faiss.omp_set_num_threads(1) @@ -407,7 +386,6 @@ def test_replicas(self): sub_idx = faiss.IndexBinaryFlat(d) sub_idx.add(xb) index.addIndex(sub_idx) - self.assertEqual(index_ref.code_size, index.code_size) D, I = index.search(xq, 10) diff --git a/thirdparty/faiss/tests/test_index_binary_from_float.py b/thirdparty/faiss/tests/test_index_binary_from_float.py index d162c0509..e2faf70af 100644 --- a/thirdparty/faiss/tests/test_index_binary_from_float.py +++ b/thirdparty/faiss/tests/test_index_binary_from_float.py @@ -19,36 +19,8 @@ def make_binary_dataset(d, nb, nt, nq): return x[:nt], x[nt:-nq], x[-nq:] -def binary_to_float(x): - n, d = x.shape - x8 = x.reshape(n * d, -1) - c8 = 2 * ((x8 >> np.arange(8)) & 1).astype("int8") - 1 - return c8.astype("float32").reshape(n, d * 8) - - @for_all_simd_levels class TestIndexBinaryFromFloat(unittest.TestCase): - """Use a binary index backed by a float index""" - - def test_index_from_float(self): - d = 256 - nt = 0 - nb = 1500 - nq = 500 - (xt, xb, xq) = make_binary_dataset(d, nb, nt, nq) - - index_ref = faiss.IndexFlatL2(d) - index_ref.add(binary_to_float(xb)) - - index = faiss.IndexFlatL2(d) - index_bin = faiss.IndexBinaryFromFloat(index) - index_bin.add(xb) - - D_ref, I_ref = index_ref.search(binary_to_float(xq), 10) - D, I = index_bin.search(xq, 10) - - np.testing.assert_allclose((D_ref / 4.0).astype("int32"), D) - def test_index_from_float_inner_product(self): d = 256 nt = 0 @@ -137,7 +109,6 @@ def test_wrapped_quantizer_IMI(self): wrapped_quantizer, d, float_quantizer.ntotal ) index.nprobe = 2048 - assert index.is_trained index.add(xb) @@ -150,60 +121,6 @@ def test_wrapped_quantizer_IMI(self): assert recall > 0.82, "recall = %g" % recall - def test_wrapped_quantizer_HNSW(self): - - def bin2float2d(v): - n, d = v.shape - vf = ((v.reshape(-1, 1) >> np.arange(8)) & 1).astype("float32") - vf *= 2 - vf -= 1 - return vf.reshape(n, d * 8) - - d = 256 - nt = 12800 - nb = 10000 - nq = 500 - (xt, xb, xq) = make_binary_dataset(d, nb, nt, nq) - - index_ref = faiss.IndexBinaryFlat(d) - - index_ref.add(xb) - - nlist = 256 - clus = faiss.Clustering(d, nlist) - clus_index = faiss.IndexFlatL2(d) - - xt_f = bin2float2d(xt) - clus.train(xt_f, clus_index) - - centroids = faiss.vector_to_array(clus.centroids).reshape(-1, clus.d) - hnsw_quantizer = faiss.IndexHNSWFlat(d, 32) - hnsw_quantizer.add(centroids) - hnsw_quantizer.is_trained = True - wrapped_quantizer = faiss.IndexBinaryFromFloat(hnsw_quantizer) - - assert nlist == hnsw_quantizer.ntotal - assert nlist == wrapped_quantizer.ntotal - assert wrapped_quantizer.is_trained - - index = faiss.IndexBinaryIVF( - wrapped_quantizer, d, hnsw_quantizer.ntotal - ) - index.nprobe = 128 - - assert index.is_trained - - index.add(xb) - - D_ref, I_ref = index_ref.search(xq, 10) - D, I = index.search(xq, 10) - - recall = sum(gti[0] in Di[:10] for gti, Di in zip(D_ref, D)) / float( - D_ref.shape[0] - ) - - assert recall >= 0.77, "recall = %g" % recall - class TestOverrideKmeansQuantizer(unittest.TestCase): diff --git a/thirdparty/faiss/tests/test_index_composite.py b/thirdparty/faiss/tests/test_index_composite.py index a8c176e39..a29811edc 100644 --- a/thirdparty/faiss/tests/test_index_composite.py +++ b/thirdparty/faiss/tests/test_index_composite.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""more elaborate that test_index.py""" - import numpy as np import unittest import faiss @@ -13,7 +11,7 @@ import tempfile import platform -from common_faiss_tests import get_dataset_2, get_dataset +from common_faiss_tests import get_dataset_2 from faiss.contrib.datasets import SyntheticDataset from faiss.contrib.inspect_tools import make_LinearTransform_matrix from faiss.contrib.evaluation import check_ref_knn_with_draws @@ -30,7 +28,6 @@ def do_test(self, ntotal, removed): index.remove_ids(np.array(removed)) for i in range(ntotal): if i in removed: - # should throw RuntimeError as this vector should be removed try: after = index.reconstruct(i) raise AssertionError() @@ -112,8 +109,6 @@ def test_remove_ondisk(self): self.do_merge_then_remove(True) def test_remove(self): - # only tests the python interface - index = faiss.IndexFlat(5) xb = np.zeros((10, 5), dtype="float32") xb[:, 0] = np.arange(10, dtype="int64") + 1000 @@ -193,7 +188,6 @@ def test_remove_id_map_binary(self): else: raise AssertionError("should have raised an exception") - # while we are there, let's test I/O as well... index = faiss.deserialize_index_binary( faiss.serialize_index_binary(index) ) @@ -213,6 +207,55 @@ def test_remove_id_map_binary(self): self.assertEqual(index2.reconstruct(1004)[0], 104) +class TestRemoveShardsReplicas(unittest.TestCase): + + def setUp(self): + self.ds = SyntheticDataset(16, 0, 1000, 20) + self.ids = np.arange(1000) + 5000 + self.sel = faiss.IDSelectorRange(5100, 5300) + self.ref = faiss.IndexIDMap(faiss.IndexFlatL2(self.ds.d)) + self.ref.add_with_ids(self.ds.get_database(), self.ids) + self.nremoved = self.ref.remove_ids(self.sel) + + def check_search(self, index): + Dref, Iref = self.ref.search(self.ds.get_queries(), 10) + D, I = index.search(self.ds.get_queries(), 10) + np.testing.assert_array_equal(I, Iref) + np.testing.assert_allclose(D, Dref, rtol=1e-5) + + def test_shards(self): + index = faiss.IndexShards(self.ds.d, False, False) + subs = [ + faiss.IndexIDMap(faiss.IndexFlatL2(self.ds.d)) for _ in range(3) + ] + for sub in subs: + index.add_shard(sub) + index.add_with_ids(self.ds.get_database(), self.ids) + self.assertEqual(index.remove_ids(self.sel), self.nremoved) + self.assertEqual(index.ntotal, self.ref.ntotal) + self.check_search(index) + + def test_shards_successive_ids(self): + index = faiss.IndexShards(self.ds.d, False, True) + sub = faiss.IndexFlatL2(self.ds.d) + index.add_shard(sub) + with self.assertRaises(RuntimeError): + index.remove_ids(self.sel) + + def test_replicas(self): + index = faiss.IndexReplicas(self.ds.d, False) + subs = [ + faiss.IndexIDMap(faiss.IndexFlatL2(self.ds.d)) for _ in range(2) + ] + for sub in subs: + index.add_replica(sub) + index.add_with_ids(self.ds.get_database(), self.ids) + self.assertEqual(index.ntotal, 1000) + self.assertEqual(index.remove_ids(self.sel), self.nremoved) + self.assertEqual(index.ntotal, self.ref.ntotal) + self.check_search(index) + + class TestRangeSearch(unittest.TestCase): def test_range_search_id_map(self): @@ -275,13 +318,11 @@ class TestPCAWhite(unittest.TestCase): def test_white(self): - # generate data d = 4 nt = 1000 nb = 200 nq = 200 - # normal distribition x = faiss.randn((nt + nb + nq) * d, 1234).reshape(nt + nb + nq, d) index = faiss.index_factory(d, "Flat") @@ -290,7 +331,6 @@ def test_white(self): xb = x[nt:-nq] xq = x[-nq:] - # NN search on normal distribution index.add(xb) Do, Io = index.search(xq, 5) @@ -303,13 +343,11 @@ def test_white(self): xb = x[nt:-nq] xq = x[-nq:] - # L2 search on skewed distribution index = faiss.index_factory(d, "Flat") index.add(xb) Dl2, Il2 = index.search(xq, 5) - # whiten + L2 search on L2 distribution index = faiss.index_factory(d, f"PCAW{d},Flat") index.train(xt) @@ -329,13 +367,11 @@ class TestTransformChain(unittest.TestCase): def test_chain(self): - # generate data d = 4 nt = 1000 nb = 200 nq = 200 - # normal distribition x = faiss.randn((nt + nb + nq) * d, 1234).reshape(nt + nb + nq, d) # make distribution very skewed @@ -454,10 +490,6 @@ def test_dedup(self): quantizer = faiss.IndexFlatL2(d) index_new = faiss.IndexIVFFlatDedup(quantizer, d, 20) - index_new.verbose = True - # should display - # IndexIVFFlatDedup::train: train on 350 points after dedup - # (was 500 points) index_new.train(xt) index_ref = faiss.IndexIVFFlat(quantizer, d, 20) @@ -473,7 +505,6 @@ def test_dedup(self): check_ref_knn_with_draws(Dref, Iref, Dnew, Inew) - # test I/O index_st = faiss.deserialize_index(faiss.serialize_index(index_new)) Dst, Ist = index_st.search(xq, 20) @@ -484,7 +515,6 @@ def test_dedup(self): Dst2, Ist2 = index_st2.search(xq, 20) check_ref_knn_with_draws(Dnew, Inew, Dst2, Ist2) - # test remove toremove = np.hstack((np.arange(3, 1000, 5), np.arange(850, 950))) toremove = toremove.astype(np.int64) index_ref.remove_ids(toremove) @@ -496,46 +526,6 @@ def test_dedup(self): check_ref_knn_with_draws(Dref, Iref, Dnew, Inew) -class TestSerialize(unittest.TestCase): - - def test_serialize_to_vector(self): - d = 10 - nb = 1000 - nq = 200 - nt = 500 - xt, xb, xq = get_dataset_2(d, nt, nb, nq) - - index = faiss.IndexFlatL2(d) - index.add(xb) - - Dref, Iref = index.search(xq, 5) - - writer = faiss.VectorIOWriter() - faiss.write_index(index, writer) - - ar_data = faiss.vector_to_array(writer.data) - - # direct transfer of vector - reader = faiss.VectorIOReader() - reader.data.swap(writer.data) - - index2 = faiss.read_index(reader) - - Dnew, Inew = index2.search(xq, 5) - np.testing.assert_array_equal(Dnew, Dref) - np.testing.assert_array_equal(Inew, Iref) - - # from intermediate numpy array - reader = faiss.VectorIOReader() - faiss.copy_array_to_vector(ar_data, reader.data) - - index3 = faiss.read_index(reader) - - Dnew, Inew = index3.search(xq, 5) - np.testing.assert_array_equal(Dnew, Dref) - np.testing.assert_array_equal(Inew, Iref) - - @unittest.skipIf( platform.system() == "Windows", "OnDiskInvertedLists is unsupported on Windows.", @@ -559,7 +549,6 @@ def test_rename(self): try: - # make an index with ondisk invlists invlists = faiss.OnDiskInvertedLists( index1.nlist, index1.code_size, dirname + "/aa.ondisk" ) @@ -568,20 +557,17 @@ def test_rename(self): D1, I1 = index1.search(xq, 10) faiss.write_index(index1, dirname + "/aa.ivf") - # move the index elsewhere os.mkdir(dirname + "/1") for fname in "aa.ondisk", "aa.ivf": os.rename(dirname + "/" + fname, dirname + "/1/" + fname) - # try to read it: fails! try: index2 = faiss.read_index(dirname + "/1/aa.ivf") except RuntimeError: - pass # normal + pass else: raise AssertionError() - # read it with magic flag index2 = faiss.read_index( dirname + "/1/aa.ivf", faiss.IO_FLAG_ONDISK_SAME_DIR ) @@ -609,8 +595,6 @@ def test_slice_vstack(self): index.add(xb) Dref, Iref = index.search(xq, 10) - # faiss.wait() - il0 = index.invlists ils = [] ilv = faiss.InvertedListsPtrVector() @@ -647,7 +631,6 @@ def test_stop_words(self): maxsz = max(il.list_size(i) for i in range(il.nlist)) il2 = faiss.StopWordsInvertedLists(il, maxsz + 1) - index.own_invlists index.own_invlists = False index.replace_invlists(il2, False) @@ -688,11 +671,9 @@ def test_capped_invlists(self): il = index.invlists maxsz = max(il.list_size(i) for i in range(il.nlist)) - # cap at half the max size cap = max(maxsz // 2, 1) il2 = faiss.CappedInvertedLists(il, cap) - # verify capping works for i in range(il.nlist): orig_sz = il.list_size(i) capped_sz = il2.list_size(i) @@ -702,7 +683,6 @@ def test_capped_invlists(self): index.own_invlists = False index.replace_invlists(il2, False) - # search with capped lists - should still return valid results D1, I1 = index.search(xq, 10) # results may differ due to capping, but should be valid self.assertTrue(np.all(I1 >= -1)) @@ -714,7 +694,6 @@ def test_capped_invlists(self): index.add(xb[:10]) # add through capped wrapper self.assertEqual(index.ntotal, orig_ntotal + 10) - # cleanup index.replace_invlists(il, True) @@ -795,13 +774,11 @@ def test_sidebyside(self): ) xq2 = np.hstack([ds.get_queries()] * 2) - quantizer.search(xq2, 30) Dnew, Inew = index2.search(xq2, 10) np.testing.assert_array_equal(Dref, Dnew) np.testing.assert_array_equal(Iref, Inew) - # test add index2.reset() xb2 = np.hstack([ds.get_database()] * 2) index2.add(xb2) @@ -871,7 +848,6 @@ def test_precomputed_tables(self): # to be honest, it is not clear which one is better... self.assertNotEqual(perf_ref, perf_new) - # check IO while we are at it index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) @@ -885,121 +861,6 @@ def test_precomputed_tables(self): np.testing.assert_array_equal(Inew, I3) -class TestSearchAndReconstruct(unittest.TestCase): - - def run_search_and_reconstruct(self, index, xb, xq, k=10, eps=None): - n, d = xb.shape - self.assertEqual(xq.shape[1], d) - self.assertEqual(index.d, d) - - D_ref, I_ref = index.search(xq, k) - R_ref = index.reconstruct_n(0, n) - D, I, R = index.search_and_reconstruct(xq, k) - - np.testing.assert_almost_equal(D, D_ref, decimal=5) - self.assertTrue((I == I_ref).all()) - self.assertEqual(R.shape[:2], I.shape) - self.assertEqual(R.shape[2], d) - - # (n, k, ..) -> (n * k, ..) - I_flat = I.reshape(-1) - R_flat = R.reshape(-1, d) - # Filter out -1s when not enough results - R_flat = R_flat[I_flat >= 0] - I_flat = I_flat[I_flat >= 0] - - recons_ref_err = np.mean(np.linalg.norm(R_flat - R_ref[I_flat])) - self.assertLessEqual(recons_ref_err, 1e-6) - - def norm1(x): - return np.sqrt((x**2).sum(axis=1)) - - recons_err = np.mean(norm1(R_flat - xb[I_flat])) - - print(f"Reconstruction error = {recons_err:.3f}") - if eps is not None: - self.assertLessEqual(recons_err, eps) - - return D, I, R - - def test_IndexFlat(self): - d = 32 - nb = 1000 - nt = 1500 - nq = 200 - - (xt, xb, xq) = get_dataset(d, nb, nt, nq) - - index = faiss.IndexFlatL2(d) - index.add(xb) - - self.run_search_and_reconstruct(index, xb, xq, eps=0.0) - - def test_IndexIVFFlat(self): - d = 32 - nb = 1000 - nt = 1500 - nq = 200 - - (xt, xb, xq) = get_dataset(d, nb, nt, nq) - - quantizer = faiss.IndexFlatL2(d) - index = faiss.IndexIVFFlat(quantizer, d, 32, faiss.METRIC_L2) - index.cp.min_points_per_centroid = 5 # quiet warning - index.nprobe = 4 - index.train(xt) - index.add(xb) - - self.run_search_and_reconstruct(index, xb, xq, eps=0.0) - - def test_IndexIVFPQ(self): - d = 32 - nb = 1000 - nt = 1500 - nq = 200 - - (xt, xb, xq) = get_dataset(d, nb, nt, nq) - - quantizer = faiss.IndexFlatL2(d) - index = faiss.IndexIVFPQ(quantizer, d, 32, 8, 8) - index.cp.min_points_per_centroid = 5 # quiet warning - index.nprobe = 4 - index.train(xt) - index.add(xb) - - self.run_search_and_reconstruct(index, xb, xq, eps=1.0) - - def test_MultiIndex(self): - d = 32 - nb = 1000 - nt = 1500 - nq = 200 - - (xt, xb, xq) = get_dataset(d, nb, nt, nq) - - index = faiss.index_factory(d, "IMI2x5,PQ8np") - faiss.ParameterSpace().set_index_parameter(index, "nprobe", 4) - index.train(xt) - index.add(xb) - - self.run_search_and_reconstruct(index, xb, xq, eps=1.0) - - def test_IndexTransform(self): - d = 32 - nb = 1000 - nt = 1500 - nq = 200 - - (xt, xb, xq) = get_dataset(d, nb, nt, nq) - - index = faiss.index_factory(d, "L2norm,PCA8,IVF32,PQ8np") - faiss.ParameterSpace().set_index_parameter(index, "nprobe", 4) - index.train(xt) - index.add(xb) - - self.run_search_and_reconstruct(index, xb, xq) - - class TestSearchAndGetCodes(unittest.TestCase): def do_test(self, factory_string): @@ -1010,7 +871,6 @@ def do_test(self, factory_string): index.train(ds.get_train()) index.add(ds.get_database()) - index.nprobe index.nprobe = 10 Dref, Iref = index.search(ds.get_queries(), 10) diff --git a/thirdparty/faiss/tests/test_io.py b/thirdparty/faiss/tests/test_io.py index feaab0681..d1b44de06 100644 --- a/thirdparty/faiss/tests/test_io.py +++ b/thirdparty/faiss/tests/test_io.py @@ -7,7 +7,6 @@ import os import pickle import platform -import sys import tempfile import unittest from multiprocessing.pool import ThreadPool @@ -15,6 +14,7 @@ import faiss import numpy as np from common_faiss_tests import get_dataset_2 +from faiss.contrib.evaluation import check_ref_knn_with_draws d = 32 @@ -35,16 +35,11 @@ def test_io_error(self): try: faiss.write_index(index, fname) - # should be fine - faiss.read_index(fname) - with open(fname, "rb") as f: data = f.read() - # now damage file with open(fname, "wb") as f: f.write(data[: int(len(data) / 2)]) - # should make a nice readable exception that mentions the filename try: faiss.read_index(fname) except RuntimeError as e: @@ -76,10 +71,7 @@ def do_write_callback(self, bsz): faiss.write_index(index, writer) del writer # make sure all writes committed - if sys.version_info[0] < 3: - buf = f.getvalue() - else: - buf = f.getbuffer() + buf = f.getbuffer() index2 = faiss.deserialize_index(np.frombuffer(buf, dtype="uint8")) @@ -89,32 +81,9 @@ def do_write_callback(self, bsz): faiss.vector_to_array(index2.codes), ) - # This is not a callable function: should raise an exception writer = faiss.PyCallbackIOWriter("blabla") self.assertRaises(Exception, faiss.write_index, index, writer) - def test_buf_read(self): - x = np.random.uniform(size=20) - - fd, fname = tempfile.mkstemp() - os.close(fd) - try: - x.tofile(fname) - - with open(fname, "rb") as f: - reader = faiss.PyCallbackIOReader(f.read, 1234) - - bsz = 123 - reader = faiss.BufferedIOReader(reader, bsz) - - y = np.zeros_like(x) - reader(faiss.swig_ptr(y), y.nbytes, 1) - - np.testing.assert_array_equal(x, y) - finally: - if os.path.exists(fname): - os.unlink(fname) - def do_read_callback(self, bsz): d, n = 32, 1000 x = np.random.uniform(size=(n, d)).astype("float32") @@ -140,7 +109,6 @@ def do_read_callback(self, bsz): faiss.vector_to_array(index2.codes), ) - # This is not a callable function: should raise an exception reader = faiss.PyCallbackIOReader("blabla") self.assertRaises(Exception, faiss.read_index, reader) finally: @@ -152,44 +120,14 @@ def test_write_callback(self): def test_write_buffer(self): self.do_write_callback(123) - self.do_write_callback(2345) def test_read_callback(self): self.do_read_callback(0) def test_read_callback_buffered(self): self.do_read_callback(123) - self.do_read_callback(12345) - - def test_read_buffer(self): - d, n = 32, 1000 - x = np.random.uniform(size=(n, d)).astype("float32") - index = faiss.IndexFlatL2(d) - index.add(x) - - fd, fname = tempfile.mkstemp() - os.close(fd) - try: - faiss.write_index(index, fname) - - reader = faiss.BufferedIOReader(faiss.FileIOReader(fname), 1234) - - index2 = faiss.read_index(reader) - - self.assertEqual(index.d, index2.d) - np.testing.assert_array_equal( - faiss.vector_to_array(index.codes), - faiss.vector_to_array(index2.codes), - ) - - finally: - del reader - if os.path.exists(fname): - os.unlink(fname) def test_transfer_pipe(self): - """transfer an index through a Unix pipe""" - d, n = 32, 1000 x = np.random.uniform(size=(n, d)).astype("float32") index = faiss.IndexFlatL2(d) @@ -198,8 +136,6 @@ def test_transfer_pipe(self): rf, wf = os.pipe() - # start thread that will decompress the index - def index_from_pipe(): reader = faiss.PyCallbackIOReader(lambda size: os.read(rf, size)) return faiss.read_index(reader) @@ -207,13 +143,11 @@ def index_from_pipe(): with ThreadPool(1) as pool: fut = pool.apply_async(index_from_pipe, ()) - # write to pipe writer = faiss.PyCallbackIOWriter(lambda b: os.write(wf, b)) faiss.write_index(index, writer) index2 = fut.get() - # closing is not really useful but it does not hurt os.close(wf) os.close(rf) @@ -223,32 +157,6 @@ def index_from_pipe(): np.testing.assert_array_equal(Dref, Dnew) -class PyOndiskInvertedLists: - """wraps an OnDisk object for use from C++""" - - def __init__(self, oil): - self.oil = oil - - def list_size(self, list_no): - return self.oil.list_size(list_no) - - def get_codes(self, list_no): - oil = self.oil - assert 0 <= list_no < oil.lists.size() - l = oil.lists.at(list_no) - with open(oil.filename, "rb") as f: - f.seek(l.offset) - return f.read(l.size * oil.code_size) - - def get_ids(self, list_no): - oil = self.oil - assert 0 <= list_no < oil.lists.size() - l = oil.lists.at(list_no) - with open(oil.filename, "rb") as f: - f.seek(l.offset + l.capacity * oil.code_size) - return f.read(l.size * 8) - - class TestPickle(unittest.TestCase): def dump_load_factory(self, fs): @@ -279,21 +187,11 @@ def dump_load_factory(self, fs): np.testing.assert_array_equal(Iref, Inew3) np.testing.assert_array_equal(Dref, Dnew3) - def test_flat(self): - self.dump_load_factory("Flat") - - def test_hnsw(self): - self.dump_load_factory("HNSW32") - def test_ivf(self): self.dump_load_factory("IVF5,Flat") class Test_IO_VectorTransform(unittest.TestCase): - """ - test write_VectorTransform using IOWriter Pointer - and read_VectorTransform using file name - """ def test_write_vector_transform(self): d, n = 32, 1000 @@ -333,40 +231,8 @@ def test_write_vector_transform(self): if os.path.exists(fname): os.unlink(fname) - """ - test write_VectorTransform using file name - and read_VectorTransform using IOWriter Pointer - """ - - def test_read_vector_transform(self): - d, n = 32, 1000 - x = np.random.uniform(size=(n, d)).astype("float32") - quantizer = faiss.IndexFlatL2(d) - index = faiss.IndexIVFSpectralHash(quantizer, d, n, 8, 1.0) - index.train(x) - index.add(x) - fd, fname = tempfile.mkstemp() - os.close(fd) - try: - - faiss.write_VectorTransform(index.vt, fname) - - reader = faiss.FileIOReader(fname) - vt = faiss.read_VectorTransform(reader) - del reader - - assert vt.d_in == index.vt.d_in - assert vt.d_out == index.vt.d_out - assert vt.is_trained - finally: - if os.path.exists(fname): - os.unlink(fname) - class Test_IO_PQ(unittest.TestCase): - """ - test read and write PQ. - """ def test_io_pq(self): xt, xb, xq = get_dataset_2(d, nt, nb, nq) @@ -384,8 +250,6 @@ def test_io_pq(self): os.unlink(fname) self.assertEqual(index.pq.M, read_pq.M) self.assertEqual(index.pq.nbits, read_pq.nbits) - self.assertEqual(index.pq.dsub, read_pq.dsub) - self.assertEqual(index.pq.ksub, read_pq.ksub) np.testing.assert_array_equal( faiss.vector_to_array(index.pq.centroids), faiss.vector_to_array(read_pq.centroids), @@ -409,9 +273,6 @@ def test_io_pq(self): class Test_IO_IndexLSH(unittest.TestCase): - """ - test read and write IndexLSH. - """ def test_io_lsh(self): xt, xb, xq = get_dataset_2(d, nt, nb, nq) @@ -432,7 +293,6 @@ def test_io_lsh(self): # access the file because it is being used by another process del reader - self.assertEqual(index_lsh.d, read_index_lsh.d) np.testing.assert_array_equal( faiss.vector_to_array(index_lsh.codes), faiss.vector_to_array(read_index_lsh.codes), @@ -455,9 +315,6 @@ def test_io_lsh(self): class Test_IO_IndexIVFSpectralHash(unittest.TestCase): - """ - test read and write IndexIVFSpectralHash. - """ def test_io_ivf_spectral_hash(self): nlist = 1000 @@ -478,11 +335,6 @@ def test_io_ivf_spectral_hash(self): read_index = faiss.read_index(reader) del reader - self.assertEqual(index.d, read_index.d) - self.assertEqual(index.nbit, read_index.nbit) - self.assertEqual(index.period, read_index.period) - self.assertEqual(index.threshold_type, read_index.threshold_type) - D_read, I_read = read_index.search(xq, 10) np.testing.assert_array_equal(D, D_read) np.testing.assert_array_equal(I, I_read) @@ -502,8 +354,9 @@ def test_io_ivf_spectral_hash(self): class TestIVFPQRead(unittest.TestCase): def test_reader(self): d, n = 32, 1000 - xq = np.random.uniform(size=(n, d)).astype("float32") - xb = np.random.uniform(size=(n, d)).astype("float32") + rs = np.random.RandomState(123) + xq = rs.uniform(size=(n, d)).astype("float32") + xb = rs.uniform(size=(n, d)).astype("float32") index = faiss.index_factory(32, "IVF32,PQ16np", faiss.METRIC_L2) index.train(xb) @@ -521,12 +374,9 @@ def test_reader(self): Da, Ia = index_a.search(xq, 10) Db, Ib = index_b.search(xq, 10) - np.testing.assert_array_equal(Ia, Ib) - np.testing.assert_almost_equal(Da, Db, decimal=5) - - codes_a = index_a.sa_encode(xq) - codes_b = index_b.sa_encode(xq) - np.testing.assert_array_equal(codes_a, codes_b) + # The precomputed table changes the order of float operations, so + # near-tied neighbors can swap. + check_ref_knn_with_draws(Da, Ia, Db, Ib) # Verify deserialized indexes are serializable again data3 = faiss.serialize_index(index_a) @@ -545,11 +395,13 @@ class TestIOFlatMMap(unittest.TestCase): platform.system() not in ["Windows", "Linux", "Darwin"], "supported OSes only", ) - def test_mmap(self): - xt, xb, xq = get_dataset_2(32, 0, 100, 50) - index = faiss.index_factory(32, "SQfp16", faiss.METRIC_L2) - # does not need training + def test_mmap_ivf(self): + d, nlist = 32, 64 + xt, xb, xq = get_dataset_2(d, 2000, 5000, 50) + index = faiss.index_factory(d, f"IVF{nlist},Flat") + index.train(xt) index.add(xb) + index.nprobe = 8 Dref, Iref = index.search(xq, 10) fd, fname = tempfile.mkstemp() @@ -559,16 +411,15 @@ def test_mmap(self): try: faiss.write_index(index, fname) index2 = faiss.read_index(fname, faiss.IO_FLAG_MMAP_IFC) + index2.nprobe = 8 Dnew, Inew = index2.search(xq, 10) np.testing.assert_array_equal(Iref, Inew) np.testing.assert_array_equal(Dref, Dnew) finally: del index2 - if os.path.exists(fname): - # skip the error. On Windows, index2 holds the handle file, - # so it cannot be ensured that the file can be deleted - # unless index2 is collected by a GC + # On Windows, index2 holds the file handle until it is + # garbage collected, so the file may not be deletable yet try: os.unlink(fname) except Exception: @@ -578,13 +429,10 @@ def test_mmap(self): platform.system() not in ["Windows", "Linux", "Darwin"], "supported OSes only", ) - def test_mmap_ivf(self): - d, nlist = 32, 64 - xt, xb, xq = get_dataset_2(d, 2000, 5000, 50) - index = faiss.index_factory(d, f"IVF{nlist},Flat") - index.train(xt) + def test_mmap_reset(self): + xt, xb, xq = get_dataset_2(32, 0, 100, 50) + index = faiss.IndexFlatL2(32) index.add(xb) - index.nprobe = 8 Dref, Iref = index.search(xq, 10) fd, fname = tempfile.mkstemp() @@ -594,7 +442,10 @@ def test_mmap_ivf(self): try: faiss.write_index(index, fname) index2 = faiss.read_index(fname, faiss.IO_FLAG_MMAP_IFC) - index2.nprobe = 8 + self.assertFalse(index2.codes.is_owned) + index2.reset() + self.assertEqual(index2.ntotal, 0) + index2.add(xb) Dnew, Inew = index2.search(xq, 10) np.testing.assert_array_equal(Iref, Inew) np.testing.assert_array_equal(Dref, Dnew) @@ -606,36 +457,12 @@ def test_mmap_ivf(self): except Exception: pass - def test_zerocopy(self): - xt, xb, xq = get_dataset_2(32, 0, 100, 50) - index = faiss.index_factory(32, "SQfp16", faiss.METRIC_L2) - # does not need training - index.add(xb) - Dref, Iref = index.search(xq, 10) - - serialized_index = faiss.serialize_index(index) - reader = faiss.ZeroCopyIOReader( - faiss.swig_ptr(serialized_index), serialized_index.size - ) - index2 = faiss.read_index(reader) - Dnew, Inew = index2.search(xq, 10) - np.testing.assert_array_equal(Iref, Inew) - np.testing.assert_array_equal(Dref, Dnew) - - # Verify deserialized index is serializable again - data3 = faiss.serialize_index(index2) - index3 = faiss.deserialize_index(data3) - Dnew3, Inew3 = index3.search(xq, 10) - np.testing.assert_array_equal(Iref, Inew3) - np.testing.assert_array_equal(Dref, Dnew3) - class TestIORoundTrip(unittest.TestCase): """Round-trip serialize/deserialize tests covering index types and sub-objects not covered by other Python tests.""" def test_index_pq(self): - """IndexPQ (full index, not just the PQ component).""" xt, xb, xq = get_dataset_2(d, nt, nb, nq) index = faiss.index_factory(d, "PQ4np") index.train(xt) @@ -647,21 +474,7 @@ def test_index_pq(self): np.testing.assert_array_equal(Iref, I2) np.testing.assert_array_equal(Dref, D2) - def test_index_sq8(self): - """IndexScalarQuantizer with SQ8.""" - xt, xb, xq = get_dataset_2(d, nt, nb, nq) - index = faiss.index_factory(d, "SQ8") - index.train(xt) - index.add(xb) - Dref, Iref = index.search(xq, 5) - - index2 = faiss.deserialize_index(faiss.serialize_index(index)) - D2, I2 = index2.search(xq, 5) - np.testing.assert_array_equal(Iref, I2) - np.testing.assert_array_equal(Dref, D2) - def test_vector_transform_pca(self): - """PCAMatrix VectorTransform with output fidelity check.""" xt, _, xq = get_dataset_2(d, nt, nb, nq) pca = faiss.PCAMatrix(d, 16) pca.train(xt) @@ -675,15 +488,11 @@ def test_vector_transform_pca(self): ) pca2 = faiss.read_VectorTransform(reader) - self.assertEqual(pca2.d_in, d) - self.assertEqual(pca2.d_out, 16) - ref = pca.apply(xq) out = pca2.apply(xq) np.testing.assert_array_equal(ref, out) def test_vector_transform_hadamard_rotation(self): - """HadamardRotation VectorTransform write/read round-trip.""" xt, _, xq = get_dataset_2(d, nt, nb, nq) fr = faiss.HadamardRotation(d, 42) @@ -696,25 +505,33 @@ def test_vector_transform_hadamard_rotation(self): ) fr2 = faiss.read_VectorTransform(reader) - self.assertEqual(fr2.d_in, d) - self.assertEqual(fr2.d_out, d) - ref = fr.apply(xq) out = fr2.apply(xq) np.testing.assert_array_equal(ref, out) - def test_index_pretransform_hadamard_rotation(self): - """Full index with HadamardRotation pre-transform round-trip.""" - xt, xb, xq = get_dataset_2(d, nt, nb, nq) - index = faiss.index_factory(d, "HR,Flat") - index.train(xt) - index.add(xb) - Dref, Iref = index.search(xq, 5) + def test_vector_transform_hadamard_rotation_pad_64(self): + """HadamardRotation padded to a multiple of 64 write/read round-trip. + d = 150 gives d_out = 192, which is not a power of 2.""" + d150 = 150 + xt, _, xq = get_dataset_2(d150, nt, nb, nq) + fr = faiss.HadamardRotation(d150, 42, False) - index2 = faiss.deserialize_index(faiss.serialize_index(index)) - D2, I2 = index2.search(xq, 5) - np.testing.assert_array_equal(Iref, I2) - np.testing.assert_array_equal(Dref, D2) + writer = faiss.VectorIOWriter() + faiss.write_VectorTransform(fr, writer) + + reader = faiss.VectorIOReader() + faiss.copy_array_to_vector( + np.array(faiss.vector_to_array(writer.data)), reader.data + ) + fr2 = faiss.read_VectorTransform(reader) + + self.assertFalse(fr2.pad_to_power_of_2) + self.assertEqual(fr2.d_in, d150) + self.assertEqual(fr2.d_out, 192) + + ref = fr.apply(xq) + out = fr2.apply(xq) + np.testing.assert_array_equal(ref, out) def test_null_index(self): """Serializing None / null index round-trips to None.""" @@ -736,7 +553,7 @@ def __init__(self, methodName="runTest"): self.xt, self.xb, self.xq = get_dataset_2(d, nt, nb, nq) def _test_roundtrip(self, index): - for _trips in range(3): + for _trips in range(2): read_index = faiss.deserialize_index(faiss.serialize_index(index)) self.assertEqual(index.hnsw.efSearch, read_index.hnsw.efSearch) self.assertEqual( @@ -748,19 +565,6 @@ def _test_roundtrip(self, index): np.testing.assert_array_equal(I, I_read) index = read_index # test re-serialization - def _test_io_hnsw(self, index): - index.train(self.xt) - index.add(self.xb) - self._test_roundtrip(index) - - def test_hnsw_flat(self): - index = faiss.IndexHNSWFlat(d, 16) - self._test_io_hnsw(index) - - def test_hnsw_pq(self): - index = faiss.IndexHNSWPQ(d, 16, 16, 4) - self._test_io_hnsw(index) - def test_hnsw_prq(self): """Exercise HNSW with aritrary storage""" storage = faiss.IndexProductResidualQuantizer( @@ -768,7 +572,9 @@ def test_hnsw_prq(self): ) index = faiss.IndexHNSW(storage, 32) del storage - self._test_io_hnsw(index) + index.train(self.xt) + index.add(self.xb) + self._test_roundtrip(index) def test_hnsw_noadd(self): """Exercise HNSW with a swapped-out storage""" diff --git a/thirdparty/faiss/tests/test_io_corrupted.cpp b/thirdparty/faiss/tests/test_io_corrupted.cpp index 2411ecef5..5e7ead90b 100644 --- a/thirdparty/faiss/tests/test_io_corrupted.cpp +++ b/thirdparty/faiss/tests/test_io_corrupted.cpp @@ -20,7 +20,6 @@ using namespace faiss; TEST(IoCorrupted, NSGNeighborIdEqualsNtotal) { - // Build an NSG index int d = 8, nb = 500; std::vector xb(nb * d); faiss::rand_smooth_vectors(nb, d, xb.data(), 1234); @@ -28,15 +27,10 @@ TEST(IoCorrupted, NSGNeighborIdEqualsNtotal) { IndexNSGFlat index(d, 16); index.add(nb, xb.data()); - // Verify that NSG::search_on_graph() skips corrupt neighbor entries - // that would trigger access outside/above the bounds of the index by - // setting the LAST valid neighbor of every node to ntotal. - // get_neighbors returns neighbors until it hits a -1 sentinel, - // so setting the last non-sentinel entry preserves graph connectivity - // while ensuring the inner search loop encounters id == ntotal. + // Set the last non-sentinel neighbor of every node to ntotal: this keeps + // the graph connected and NSG::search_on_graph() must skip the entry. auto* graph = index.nsg.final_graph.get(); for (int i = 0; i < nb; i++) { - // Find the last valid (non-sentinel) neighbor slot int last = -1; for (int j = 0; j < graph->K; j++) { if (graph->at(i, j) >= 0) { @@ -55,10 +49,7 @@ TEST(IoCorrupted, NSGNeighborIdEqualsNtotal) { std::vector I(1); std::vector D(1); - // Safely skipped without an exception or ASAN failure. - EXPECT_NO_THROW(index.search(1, xq.data(), 1, D.data(), I.data())); - - // Result must be a valid node ID + index.search(1, xq.data(), 1, D.data(), I.data()); EXPECT_GE(I[0], 0); EXPECT_LT(I[0], nb); } diff --git a/thirdparty/faiss/tests/test_ivf_early_termination.cpp b/thirdparty/faiss/tests/test_ivf_early_termination.cpp index 8e38780be..1c9608a27 100644 --- a/thirdparty/faiss/tests/test_ivf_early_termination.cpp +++ b/thirdparty/faiss/tests/test_ivf_early_termination.cpp @@ -5,504 +5,14 @@ * LICENSE file in the root directory of this source tree. */ -// Unit tests for the three early-termination knobs on SearchParametersIVF: -// - ensure_topk_full (knn, IndexIVF::search_preassigned) -// - max_empty_result_buckets (range, IndexIVF::range_search_preassigned) -// - max_lists_num (fastscan knn) -// -// The tests establish the default-behavior contract: when the new fields -// are left at their defaults, search results must be byte-for-byte identical -// to a search with no params at all. +// Unit tests for RangeResultHandler::add_result return values. -#include -#include -#include #include -#include #include -#include -#include #include -#include -#include #include -#include - -namespace { - -constexpr int d = 16; -constexpr size_t nb = 500; -constexpr size_t nq = 20; -constexpr size_t nlist = 16; -constexpr int k = 10; - -std::vector make_data(size_t n, uint32_t seed) { - std::mt19937 rng(seed); - std::uniform_real_distribution dist(0.0f, 1.0f); - std::vector out(n * d); - for (auto& v : out) { - v = dist(rng); - } - return out; -} - -std::unique_ptr build_ivf_flat() { - auto xb = make_data(nb, 0xabcdef); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,Flat", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - return index; -} - -} // namespace - -// Default-constructed SearchParametersIVF (all three new fields at 0/false) -// must reproduce the result of a search without any SearchParameters. -TEST(IVFEarlyTermination, DefaultsPreserveBaselineKnn) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->nprobe = 4; - - auto xq = make_data(nq, 0x123456); - std::vector D_ref(k * nq), D_new(k * nq); - std::vector I_ref(k * nq), I_new(k * nq); - - index->search(nq, xq.data(), k, D_ref.data(), I_ref.data()); - - faiss::SearchParametersIVF params; // all defaults - params.nprobe = 4; - index->search(nq, xq.data(), k, D_new.data(), I_new.data(), ¶ms); - - EXPECT_EQ(I_ref, I_new); - EXPECT_EQ(D_ref, D_new); -} - -TEST(IVFEarlyTermination, DefaultsPreserveBaselineRange) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->nprobe = 4; - - auto xq = make_data(nq, 0x789abc); - const float radius = 2.0f; - - faiss::RangeSearchResult ref(nq); - faiss::RangeSearchResult tst(nq); - - index->range_search(nq, xq.data(), radius, &ref); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - index->range_search(nq, xq.data(), radius, &tst, ¶ms); - - ASSERT_EQ(ref.nq, tst.nq); - for (size_t i = 0; i <= ref.nq; i++) { - EXPECT_EQ(ref.lims[i], tst.lims[i]) << "at lims[" << i << "]"; - } - // The underlying result order is implementation-defined across OMP - // threads, so compare as sorted (id, distance) pairs per query. - for (size_t q = 0; q < ref.nq; q++) { - std::vector> ref_pairs; - std::vector> tst_pairs; - for (size_t j = ref.lims[q]; j < ref.lims[q + 1]; j++) { - ref_pairs.emplace_back(ref.labels[j], ref.distances[j]); - } - for (size_t j = tst.lims[q]; j < tst.lims[q + 1]; j++) { - tst_pairs.emplace_back(tst.labels[j], tst.distances[j]); - } - std::sort(ref_pairs.begin(), ref_pairs.end()); - std::sort(tst_pairs.begin(), tst_pairs.end()); - EXPECT_EQ(ref_pairs, tst_pairs); - } -} - -// With a tight max_codes, ensure_topk_full=true must produce at least as -// many valid (non -1) labels as ensure_topk_full=false. -TEST(IVFEarlyTermination, EnsureTopkFullReducesMisses) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - - auto xq = make_data(nq, 0xdeadbe); - std::vector D_tight(k * nq), D_full(k * nq); - std::vector I_tight(k * nq), I_full(k * nq); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - // Tight budget: strictly smaller than k to guarantee truncation. - params.max_codes = k / 2; - params.ensure_topk_full = false; - index->search(nq, xq.data(), k, D_tight.data(), I_tight.data(), ¶ms); - - params.ensure_topk_full = true; - index->search(nq, xq.data(), k, D_full.data(), I_full.data(), ¶ms); - - size_t miss_tight = - std::count(I_tight.begin(), I_tight.end(), (faiss::idx_t)-1); - size_t miss_full = - std::count(I_full.begin(), I_full.end(), (faiss::idx_t)-1); - - EXPECT_LE(miss_full, miss_tight); - EXPECT_GT(miss_tight, size_t(0)) - << "test precondition: tight budget should cause truncation"; - EXPECT_EQ(miss_full, size_t(0)) - << "ensure_topk_full must fill the heap when enough data is " - "available in the probed lists"; -} - -// The field is checked against the existing max_codes throw guard for -// parallel modes other than 0/3. -TEST(IVFEarlyTermination, EnsureTopkFullRejectsUnsupportedParallelMode) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->parallel_mode = 1; - - auto xq = make_data(1, 0xaaaa); - std::vector D(k); - std::vector I(k); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.ensure_topk_full = true; - EXPECT_THROW( - index->search(1, xq.data(), k, D.data(), I.data(), ¶ms), - faiss::FaissException); -} - -// Range-search early-exit: with max_empty_result_buckets set, the result -// set is a subset of the full-scan result set. -TEST(IVFEarlyTermination, RangeEarlyExitProducesSubset) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - - auto xq = make_data(nq, 0xfacefeed); - // Pick a radius tight enough that some probed buckets legitimately - // yield no hits. - const float radius = 0.5f; - - faiss::RangeSearchResult full(nq); - faiss::RangeSearchResult early(nq); - - faiss::SearchParametersIVF p_full; - p_full.nprobe = nlist; - p_full.max_empty_result_buckets = 0; // disabled - index->range_search(nq, xq.data(), radius, &full, &p_full); - - faiss::SearchParametersIVF p_early; - p_early.nprobe = nlist; - p_early.max_empty_result_buckets = 1; // aggressive - index->range_search(nq, xq.data(), radius, &early, &p_early); - - ASSERT_EQ(full.nq, early.nq); - for (size_t q = 0; q < full.nq; q++) { - std::set full_ids( - full.labels + full.lims[q], full.labels + full.lims[q + 1]); - std::set early_ids( - early.labels + early.lims[q], early.labels + early.lims[q + 1]); - // early_ids ⊆ full_ids - for (auto id : early_ids) { - EXPECT_TRUE(full_ids.count(id)) - << "early-exit returned id " << id - << " not present in full-scan result for query " << q; - } - } -} - -// Verify that the empty-bucket early exit actually stops the probe loop. -TEST(IVFEarlyTermination, RangeEarlyExitActuallyTruncates) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - - auto xq = make_data(nq, 0xfacefeed); - // Radius chosen so that the dataset (uniform[0,1]^16, nb=500, - // nlist=16) yields per-query results spread across multiple - // probed lists with interspersed empty buckets — observable - // shrinkage when max_empty_result_buckets fires. - const float radius = 1.0f; - - faiss::RangeSearchResult full(nq); - faiss::RangeSearchResult early(nq); - - faiss::SearchParametersIVF p_full; - p_full.nprobe = nlist; - p_full.max_empty_result_buckets = 0; // disabled - index->range_search(nq, xq.data(), radius, &full, &p_full); - - faiss::SearchParametersIVF p_early; - p_early.nprobe = nlist; - p_early.max_empty_result_buckets = 1; // exit on first empty bucket - index->range_search(nq, xq.data(), radius, &early, &p_early); - - ASSERT_EQ(full.nq, early.nq); - - // Per-query result count must never grow under early-exit. - for (size_t q = 0; q < full.nq; q++) { - EXPECT_LE( - early.lims[q + 1] - early.lims[q], - full.lims[q + 1] - full.lims[q]) - << "early-exit grew result count for query " << q; - } - - // At least one query must strictly shrink — proves the loop broke. - bool any_shrunk = false; - for (size_t q = 0; q < full.nq; q++) { - if ((early.lims[q + 1] - early.lims[q]) < - (full.lims[q + 1] - full.lims[q])) { - any_shrunk = true; - break; - } - } - EXPECT_TRUE(any_shrunk) - << "no query shrank: max_empty_result_buckets has no effect"; -} - -// max_empty_result_buckets counter must reset on probes that add hits. -// Hand-verified: with ndup=2 we should NEVER terminate as long as a -// non-empty bucket appears between any two empty buckets, even if every -// other probe is empty. Test by forcing alternating-empty patterns. -TEST(IVFEarlyTermination, RangeEarlyExitCounterResetsOnHit) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - - auto xq = make_data(nq, 0xc0ffee); - const float radius = 1.0f; - - // With max_empty_result_buckets=1, exit on first empty bucket. - // With =3, only exit on three consecutive empties — strictly more - // results expected (or at least equal) for the latter. - faiss::RangeSearchResult tight(nq); - faiss::RangeSearchResult relaxed(nq); - - faiss::SearchParametersIVF p_tight; - p_tight.nprobe = nlist; - p_tight.max_empty_result_buckets = 1; - index->range_search(nq, xq.data(), radius, &tight, &p_tight); - - faiss::SearchParametersIVF p_relaxed; - p_relaxed.nprobe = nlist; - p_relaxed.max_empty_result_buckets = 3; - index->range_search(nq, xq.data(), radius, &relaxed, &p_relaxed); - - ASSERT_EQ(tight.nq, relaxed.nq); - for (size_t q = 0; q < tight.nq; q++) { - EXPECT_LE( - tight.lims[q + 1] - tight.lims[q], - relaxed.lims[q + 1] - relaxed.lims[q]) - << "relaxed early-exit returned fewer results than tight " - "for query " - << q; - } -} - -// max_empty_result_buckets is only supported in parallel_mode == 0. -TEST(IVFEarlyTermination, RangeEarlyExitRejectsUnsupportedParallelMode) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->parallel_mode = 1; - - auto xq = make_data(1, 0xbbbb); - faiss::RangeSearchResult res(1); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.max_empty_result_buckets = 2; - EXPECT_THROW( - index->range_search(1, xq.data(), 1.0f, &res, ¶ms), - faiss::FaissException); -} - -// IndexIVFStats::ndis is documented as "nb of distances computed". -// Verify that the post-filter scan_count flowing through -// InvertedListScannerStats actually populates ndis according to that -// docstring: under no IDSelector, ndis equals the sum of probed list -// sizes; under a 50%-keep IDSelectorBitmap, ndis is roughly halved -// because only codes that survive the selector have distances -// computed. -TEST(IVFEarlyTermination, NdisStatsMatchesDocstringPostFilter) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->nprobe = nlist; - - auto xq = make_data(nq, 0xb0bafe11); - - // Baseline: no selector. ndis equals the total raw codes the - // scanner saw. - auto& stats = faiss::indexIVF_stats; - stats.reset(); - std::vector D(k * nq); - std::vector I(k * nq); - index->search(nq, xq.data(), k, D.data(), I.data()); - const size_t ndis_no_sel = stats.ndis; - EXPECT_GT(ndis_no_sel, size_t(0)) - << "test precondition: at least some codes should be visited"; - - // 50%-keep bitmap selector. ndis should drop because rejected - // codes don't get a distance computed. - std::vector packed((nb + 7) / 8, 0); - for (size_t i = 0; i < nb; i += 2) { - packed[i / 8] |= 1u << (i % 8); - } - faiss::IDSelectorBitmap sel(nb, packed.data()); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - params.sel = &sel; - - stats.reset(); - index->search(nq, xq.data(), k, D.data(), I.data(), ¶ms); - const size_t ndis_with_sel = stats.ndis; - - // Strict: with a 50%-keep selector, ndis must be strictly less - // than the no-selector ndis (each call processes the same lists - // with the same nprobe). - EXPECT_LT(ndis_with_sel, ndis_no_sel) - << "ndis did not decrease under restrictive IDSelector — " - "check post-filter scan_cnt plumbing"; - // Loose-bound sanity: ~50% retention should put ndis somewhere - // around half. Allow generous slop because per-list size variance - // means the empirical ratio can drift. - EXPECT_LT(ndis_with_sel * 4, ndis_no_sel * 3) - << "ndis_with_sel=" << ndis_with_sel - << " not noticeably below ~75% of ndis_no_sel=" << ndis_no_sel; -} - -// Same docstring contract for IndexIVF::range_search_preassigned: ndis -// must be post-filter for the range path too. -TEST(IVFEarlyTermination, NdisStatsMatchesDocstringPostFilterRange) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->nprobe = nlist; - - auto xq = make_data(nq, 0xc01dca11); - const float radius = 1.0f; - - auto& stats = faiss::indexIVF_stats; - stats.reset(); - faiss::RangeSearchResult res_no_sel(nq); - index->range_search(nq, xq.data(), radius, &res_no_sel); - const size_t ndis_no_sel = stats.ndis; - EXPECT_GT(ndis_no_sel, size_t(0)); - - std::vector packed((nb + 7) / 8, 0); - for (size_t i = 0; i < nb; i += 2) { - packed[i / 8] |= 1u << (i % 8); - } - faiss::IDSelectorBitmap sel(nb, packed.data()); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - params.sel = &sel; - - stats.reset(); - faiss::RangeSearchResult res_with_sel(nq); - index->range_search(nq, xq.data(), radius, &res_with_sel, ¶ms); - const size_t ndis_with_sel = stats.ndis; - - EXPECT_LT(ndis_with_sel, ndis_no_sel); - EXPECT_LT(ndis_with_sel * 4, ndis_no_sel * 3); -} - -// With a restrictive bitmap selector, ensure_topk_full keeps probing until -// enough selector-passing candidates have been scanned. -TEST(IVFEarlyTermination, EnsureTopkFullFillsHeapUnderRestrictiveSelector) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - ivf->nprobe = nlist; - - // ~10%-keep bitmap selector (every 10th id). - std::vector packed((nb + 7) / 8, 0); - for (size_t i = 0; i < nb; i += 10) { - packed[i / 8] |= 1u << (i % 8); - } - faiss::IDSelectorBitmap sel(nb, packed.data()); - - auto xq = make_data(nq, 0xdeadbe); - std::vector D(k * nq); - std::vector I(k * nq); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - params.max_codes = k / 2; // pre-filter budget < k - params.ensure_topk_full = true; // post-filter soft-cap kicks in - params.sel = &sel; - - index->search(nq, xq.data(), k, D.data(), I.data(), ¶ms); - - // Valid hits available per query (~50 across all nlist buckets, - // far exceeding k=10) — the strengthened break should fill the - // heap completely. - EXPECT_EQ(std::count(I.begin(), I.end(), (faiss::idx_t)-1), size_t(0)) - << "ensure_topk_full failed to fill the heap under a " - "restrictive IDSelector"; -} - -// Without a selector, post-filter and raw scan counts are the same. -TEST(IVFEarlyTermination, EnsureTopkFullNoSelectorByteIdentical) { - auto index = build_ivf_flat(); - auto* ivf = dynamic_cast(index.get()); - ASSERT_NE(ivf, nullptr); - - auto xq = make_data(nq, 0xa5a5a5); - - // Reference: ensure_topk_full=false. - faiss::SearchParametersIVF p_ref; - p_ref.nprobe = nlist; - p_ref.max_codes = k / 2; - p_ref.ensure_topk_full = false; - std::vector D_ref(k * nq); - std::vector I_ref(k * nq); - index->search(nq, xq.data(), k, D_ref.data(), I_ref.data(), &p_ref); - - // Soft budget: ensure_topk_full=true. - faiss::SearchParametersIVF p_full; - p_full.nprobe = nlist; - p_full.max_codes = k / 2; - p_full.ensure_topk_full = true; - std::vector D_full(k * nq); - std::vector I_full(k * nq); - index->search(nq, xq.data(), k, D_full.data(), I_full.data(), &p_full); - - // Softening the budget must not increase the number of missing results. - size_t miss_ref = std::count(I_ref.begin(), I_ref.end(), (faiss::idx_t)-1); - size_t miss_full = - std::count(I_full.begin(), I_full.end(), (faiss::idx_t)-1); - EXPECT_LE(miss_full, miss_ref); -} - -// Current FastScan handlers do not report heap update counts. -TEST(IVFEarlyTermination, FastscanNheapUpdatesIsZeroToday) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(nq, 0x5678); - std::vector D(k * nq); - std::vector I(k * nq); - - auto& stats = faiss::indexIVF_stats; - stats.reset(); - index->search(nq, xq.data(), k, D.data(), I.data()); - - // FastScan plumbs nq, ndis, and nlist into indexIVF_stats. - EXPECT_GT(stats.ndis, size_t(0)); - EXPECT_EQ(stats.nheap_updates, size_t(0)) - << "FastScan started reporting nheap_updates — update this " - "test and verify the value is correct."; -} // RangeResultHandler::add_result must return true when a result is added // (distance passes the threshold) so that callers in expanded_scanners.h @@ -518,23 +28,16 @@ TEST(IVFEarlyTermination, RangeResultHandlerAddResultReturnValue) { // CMax::cmp(5.0, 3.0) is true: distance within radius, should add EXPECT_TRUE(handler.add_result(3.0f, 42)); - EXPECT_EQ(qr.nres, size_t(1)); // CMax::cmp(5.0, 5.0) is false: at boundary, should not add EXPECT_FALSE(handler.add_result(5.0f, 43)); - EXPECT_EQ(qr.nres, size_t(1)); // CMax::cmp(5.0, 10.0) is false: distance exceeds radius EXPECT_FALSE(handler.add_result(10.0f, 44)); - EXPECT_EQ(qr.nres, size_t(1)); - // Second valid result EXPECT_TRUE(handler.add_result(1.0f, 45)); - EXPECT_EQ(qr.nres, size_t(2)); - // Finalize and verify stored (dis, id) pairs pres.finalize(); - ASSERT_EQ(rsr.lims[0], size_t(0)); ASSERT_EQ(rsr.lims[1], size_t(2)); std::set ids(rsr.labels, rsr.labels + 2); EXPECT_EQ(ids, (std::set{42, 45})); @@ -554,19 +57,14 @@ TEST(IVFEarlyTermination, RangeResultHandlerAddResultCMin) { // CMin::cmp(5.0, 10.0) is true: dis above threshold, should add EXPECT_TRUE(handler.add_result(10.0f, 100)); - EXPECT_EQ(qr.nres, size_t(1)); // CMin::cmp(5.0, 5.0) is false: at boundary, should not add EXPECT_FALSE(handler.add_result(5.0f, 101)); - EXPECT_EQ(qr.nres, size_t(1)); // CMin::cmp(5.0, 3.0) is false: dis below threshold EXPECT_FALSE(handler.add_result(3.0f, 102)); - EXPECT_EQ(qr.nres, size_t(1)); - // Second valid result EXPECT_TRUE(handler.add_result(7.0f, 103)); - EXPECT_EQ(qr.nres, size_t(2)); pres.finalize(); ASSERT_EQ(rsr.lims[1], size_t(2)); @@ -575,253 +73,3 @@ TEST(IVFEarlyTermination, RangeResultHandlerAddResultCMin) { std::set dists(rsr.distances, rsr.distances + 2); EXPECT_EQ(dists, (std::set{7.0f, 10.0f})); } - -// FastScan early-stop options use the per-query implementations. -TEST(IVFEarlyTermination, FastscanDefaultsWork) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(nq, 0x5678); - std::vector D(k * nq); - std::vector I(k * nq); - - faiss::SearchParametersIVF params; // defaults - params.nprobe = 4; - EXPECT_NO_THROW( - index->search(nq, xq.data(), k, D.data(), I.data(), ¶ms)); -} - -TEST(IVFEarlyTermination, FastscanMaxListsNumHonored) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(1, 0x9999); - std::vector D_full(k), D_cap(k); - std::vector I_full(k), I_cap(k); - - faiss::SearchParametersIVF p_full; - p_full.nprobe = nlist; - EXPECT_NO_THROW(index->search( - 1, xq.data(), k, D_full.data(), I_full.data(), &p_full)); - - faiss::SearchParametersIVF p_cap; - p_cap.nprobe = nlist; - p_cap.max_lists_num = 1; - EXPECT_NO_THROW( - index->search(1, xq.data(), k, D_cap.data(), I_cap.data(), &p_cap)); -} - -TEST(IVFEarlyTermination, FastscanEnsureTopkFullSingleQueryWorks) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(1, 0x9999); - std::vector D(k); - std::vector I(k); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - params.max_codes = 2; - params.ensure_topk_full = true; - EXPECT_NO_THROW( - index->search(1, xq.data(), k, D.data(), I.data(), ¶ms)); -} - -TEST(IVFEarlyTermination, FastscanEnsureTopkFullRestrictiveSelectorWorks) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - std::vector packed((nb + 7) / 8, 0); - for (size_t i = 0; i < nb; i += 10) { - packed[i / 8] |= 1u << (i % 8); - } - faiss::IDSelectorBitmap sel(nb, packed.data()); - - auto xq = make_data(1, 0x9999); - std::vector D(k); - std::vector I(k); - - faiss::SearchParametersIVF params; - params.nprobe = nlist; - params.max_codes = 2; - params.ensure_topk_full = true; - params.sel = &sel; - index->search(1, xq.data(), k, D.data(), I.data(), ¶ms); - - EXPECT_EQ(std::count(I.begin(), I.end(), (faiss::idx_t)-1), size_t(0)) - << "FastScan max_codes must be counted after IDSelector filtering"; -} - -TEST(IVFEarlyTermination, FastscanEnsureTopkFullMultiQueryWorks) { - // Each query independently resets nscan_q; multi-query batches are - // therefore supported. - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(2, 0x9999); - std::vector D(k * 2); - std::vector I(k * 2); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.ensure_topk_full = true; - EXPECT_NO_THROW( - index->search(2, xq.data(), k, D.data(), I.data(), ¶ms)); -} - -TEST(IVFEarlyTermination, FastscanExplicitImplem12RejectsKnobs) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - auto* fs = dynamic_cast(index.get()); - ASSERT_NE(fs, nullptr); - fs->implem = 12; - - auto xq = make_data(1, 0x9999); - std::vector D(k); - std::vector I(k); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.max_lists_num = 2; - EXPECT_THROW( - index->search(1, xq.data(), k, D.data(), I.data(), ¶ms), - faiss::FaissException); -} - -TEST(IVFEarlyTermination, FastscanRangeDefaultsPreserveBaseline) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - auto* fs = dynamic_cast(index.get()); - ASSERT_NE(fs, nullptr); - fs->nprobe = 4; - - auto xq = make_data(nq, 0x9999); - const float radius = 1.0f; - faiss::RangeSearchResult ref(nq); - faiss::RangeSearchResult tst(nq); - - index->range_search(nq, xq.data(), radius, &ref); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.max_empty_result_buckets = 0; - index->range_search(nq, xq.data(), radius, &tst, ¶ms); - - ASSERT_EQ(ref.nq, tst.nq); - for (size_t i = 0; i <= ref.nq; i++) { - EXPECT_EQ(ref.lims[i], tst.lims[i]) << "at lims[" << i << "]"; - } - for (size_t q = 0; q < ref.nq; q++) { - std::vector> ref_pairs; - std::vector> tst_pairs; - for (size_t j = ref.lims[q]; j < ref.lims[q + 1]; j++) { - ref_pairs.emplace_back(ref.labels[j], ref.distances[j]); - } - for (size_t j = tst.lims[q]; j < tst.lims[q + 1]; j++) { - tst_pairs.emplace_back(tst.labels[j], tst.distances[j]); - } - std::sort(ref_pairs.begin(), ref_pairs.end()); - std::sort(tst_pairs.begin(), tst_pairs.end()); - EXPECT_EQ(ref_pairs, tst_pairs); - } -} - -TEST(IVFEarlyTermination, FastscanRangeHonorsMaxEmptyResultBuckets) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - - auto xq = make_data(1, 0x9999); - const float radius = 1.0f; - faiss::RangeSearchResult full(1); - faiss::RangeSearchResult early(1); - std::vector empty_subset; - faiss::IDSelectorBatch empty_sel(0, empty_subset.data()); - - auto& stats = faiss::indexIVF_stats; - faiss::SearchParametersIVF p_full; - p_full.nprobe = nlist; - p_full.max_empty_result_buckets = 0; - p_full.sel = &empty_sel; - stats.reset(); - index->range_search(1, xq.data(), radius, &full, &p_full); - const size_t full_nlist = stats.nlist; - - faiss::SearchParametersIVF p_early; - p_early.nprobe = nlist; - p_early.max_empty_result_buckets = 1; - p_early.sel = &empty_sel; - stats.reset(); - index->range_search(1, xq.data(), radius, &early, &p_early); - const size_t early_nlist = stats.nlist; - - EXPECT_GT(full_nlist, size_t(1)) - << "test precondition: full scan should visit several lists"; - EXPECT_LT(early_nlist, full_nlist) - << "max_empty_result_buckets did not stop fastscan range early"; -} - -TEST(IVFEarlyTermination, FastscanRangeRejectsMaxEmptyWithExplicitImpl12) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - auto* fs = dynamic_cast(index.get()); - ASSERT_NE(fs, nullptr); - fs->implem = 12; - - auto xq = make_data(1, 0x9999); - faiss::RangeSearchResult res(1); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.max_empty_result_buckets = 2; - EXPECT_THROW( - index->range_search(1, xq.data(), 1.0f, &res, ¶ms), - faiss::FaissException); -} - -TEST(IVFEarlyTermination, FastscanRangeRejectsMaxEmptyUnsupportedParallelMode) { - auto xb = make_data(nb, 0xcafebabe); - std::unique_ptr index( - faiss::index_factory(d, "IVF16,PQ4x4fs", faiss::METRIC_L2)); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - auto* fs = dynamic_cast(index.get()); - ASSERT_NE(fs, nullptr); - fs->parallel_mode = 1; - - auto xq = make_data(1, 0x9999); - faiss::RangeSearchResult res(1); - - faiss::SearchParametersIVF params; - params.nprobe = 4; - params.max_empty_result_buckets = 2; - EXPECT_THROW( - index->range_search(1, xq.data(), 1.0f, &res, ¶ms), - faiss::FaissException); -} diff --git a/thirdparty/faiss/tests/test_ivf_early_termination.py b/thirdparty/faiss/tests/test_ivf_early_termination.py new file mode 100644 index 000000000..c065276f8 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivf_early_termination.py @@ -0,0 +1,312 @@ +# 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. + +"""IVF early termination tests.""" + +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +d = 16 +nb = 500 +nq = 20 +nlist = 16 +k = 10 + + +def make_data(n, seed): + return np.random.RandomState(seed).rand(n, d).astype(np.float32) + + +def build_ivf_flat(): + xb = make_data(nb, 0xABCDEF) + index = faiss.index_factory(d, "IVF16,Flat", faiss.METRIC_L2) + index.train(xb) + index.add(xb) + return index + + +def build_fastscan(): + xb = make_data(nb, 0xCAFEBABE) + index = faiss.index_factory(d, "IVF16,PQ4x4fs", faiss.METRIC_L2) + index.train(xb) + index.add(xb) + return index + + +def make_bitmap_selector(step): + bitmap = np.zeros(nb, dtype=bool) + bitmap[0::step] = True + return faiss.IDSelectorBitmap( + np.packbits(bitmap, bitorder="little")) + + +def assert_sorted_pairs_equal(test, lims_a, d_a, i_a, lims_b, d_b, i_b): + test.assertEqual(len(lims_a), len(lims_b)) + for j in range(len(lims_a)): + test.assertEqual(lims_a[j], lims_b[j], f"at lims[{j}]") + nq_ = len(lims_a) - 1 + for q in range(nq_): + pairs_a = sorted( + zip( + i_a[lims_a[q] : lims_a[q + 1]], + d_a[lims_a[q] : lims_a[q + 1]], + ) + ) + pairs_b = sorted( + zip( + i_b[lims_b[q] : lims_b[q + 1]], + d_b[lims_b[q] : lims_b[q + 1]], + ) + ) + test.assertEqual(pairs_a, pairs_b) + + +class TestIVFEarlyTermination(unittest.TestCase): + def test_defaults_preserve_baseline_range(self): + index = build_ivf_flat() + faiss.downcast_index(index).nprobe = 4 + + xq = make_data(nq, 0x789ABC) + radius = 2.0 + + lims_ref, D_ref, I_ref = index.range_search(xq, radius) + + params = faiss.SearchParametersIVF() + params.nprobe = 4 + lims_tst, D_tst, I_tst = index.range_search( + xq, radius, params=params) + + assert_sorted_pairs_equal( + self, lims_ref, D_ref, I_ref, lims_tst, D_tst, I_tst) + + def test_ensure_topk_full_reduces_misses(self): + index = build_ivf_flat() + xq = make_data(nq, 0xDEADBE) + + params = faiss.SearchParametersIVF() + params.nprobe = nlist + params.max_codes = k // 2 + params.ensure_topk_full = False + _, I_tight = index.search(xq, k, params=params) + + params.ensure_topk_full = True + _, I_full = index.search(xq, k, params=params) + + miss_tight = np.count_nonzero(I_tight == -1) + miss_full = np.count_nonzero(I_full == -1) + + self.assertGreater( + miss_tight, 0, + "test precondition: tight budget should cause truncation") + self.assertEqual( + miss_full, 0, + "ensure_topk_full must fill the heap when enough data is " + "available in the probed lists") + + def test_ensure_topk_full_rejects_unsupported_parallel_mode(self): + index = build_ivf_flat() + faiss.downcast_index(index).parallel_mode = 1 + + xq = make_data(1, 0xAAAA) + + params = faiss.SearchParametersIVF() + params.nprobe = 4 + params.ensure_topk_full = True + with self.assertRaises(RuntimeError): + index.search(xq, k, params=params) + + def test_range_early_exit_produces_subset(self): + index = build_ivf_flat() + xq = make_data(nq, 0xFACEFEED) + radius = 0.5 + + p_full = faiss.SearchParametersIVF() + p_full.nprobe = nlist + p_full.max_empty_result_buckets = 0 + lims_full, _, I_full = index.range_search( + xq, radius, params=p_full) + + p_early = faiss.SearchParametersIVF() + p_early.nprobe = nlist + p_early.max_empty_result_buckets = 1 + lims_early, _, I_early = index.range_search( + xq, radius, params=p_early) + + for q in range(nq): + full_ids = set(I_full[lims_full[q] : lims_full[q + 1]]) + early_ids = set(I_early[lims_early[q] : lims_early[q + 1]]) + for i in early_ids: + self.assertIn( + i, full_ids, + f"early-exit returned id {i} not present in " + f"full-scan result for query {q}") + + def test_range_early_exit_actually_truncates(self): + index = build_ivf_flat() + xq = make_data(nq, 0xFACEFEED) + radius = 1.0 + + p_full = faiss.SearchParametersIVF() + p_full.nprobe = nlist + p_full.max_empty_result_buckets = 0 + lims_full, _, _ = index.range_search(xq, radius, params=p_full) + + p_early = faiss.SearchParametersIVF() + p_early.nprobe = nlist + p_early.max_empty_result_buckets = 1 + lims_early, _, _ = index.range_search( + xq, radius, params=p_early) + + for q in range(nq): + self.assertLessEqual( + lims_early[q + 1] - lims_early[q], + lims_full[q + 1] - lims_full[q], + f"early-exit grew result count for query {q}") + + any_shrunk = any( + (lims_early[q + 1] - lims_early[q]) + < (lims_full[q + 1] - lims_full[q]) + for q in range(nq) + ) + self.assertTrue( + any_shrunk, + "no query shrank: max_empty_result_buckets has no effect") + + def test_range_early_exit_counter_resets_on_hit(self): + index = build_ivf_flat() + xq = make_data(nq, 0xC0FFEE) + radius = 1.0 + + p_tight = faiss.SearchParametersIVF() + p_tight.nprobe = nlist + p_tight.max_empty_result_buckets = 1 + lims_tight, _, _ = index.range_search( + xq, radius, params=p_tight) + + p_relaxed = faiss.SearchParametersIVF() + p_relaxed.nprobe = nlist + p_relaxed.max_empty_result_buckets = 3 + lims_relaxed, _, _ = index.range_search( + xq, radius, params=p_relaxed) + + for q in range(nq): + self.assertLessEqual( + lims_tight[q + 1] - lims_tight[q], + lims_relaxed[q + 1] - lims_relaxed[q], + "relaxed early-exit returned fewer results than tight " + f"for query {q}") + + def test_range_early_exit_rejects_unsupported_parallel_mode(self): + index = build_ivf_flat() + faiss.downcast_index(index).parallel_mode = 1 + + xq = make_data(1, 0xBBBB) + + params = faiss.SearchParametersIVF() + params.nprobe = 4 + params.max_empty_result_buckets = 2 + with self.assertRaises(RuntimeError): + index.range_search(xq, 1.0, params=params) + + def test_ndis_stats_matches_docstring_post_filter(self): + index = build_ivf_flat() + faiss.downcast_index(index).nprobe = nlist + + xq = make_data(nq, 0xB0BAFE11) + stats = faiss.cvar.indexIVF_stats + + stats.reset() + index.search(xq, k) + ndis_no_sel = stats.ndis + + sel = make_bitmap_selector(2) + params = faiss.SearchParametersIVF() + params.nprobe = nlist + params.sel = sel + + stats.reset() + index.search(xq, k, params=params) + ndis_with_sel = stats.ndis + + self.assertLess(ndis_with_sel * 4, ndis_no_sel * 3) + + def test_ndis_stats_matches_docstring_post_filter_range(self): + index = build_ivf_flat() + faiss.downcast_index(index).nprobe = nlist + + xq = make_data(nq, 0xC01DCA11) + radius = 1.0 + stats = faiss.cvar.indexIVF_stats + + stats.reset() + index.range_search(xq, radius) + ndis_no_sel = stats.ndis + + sel = make_bitmap_selector(2) + params = faiss.SearchParametersIVF() + params.nprobe = nlist + params.sel = sel + + stats.reset() + index.range_search(xq, radius, params=params) + ndis_with_sel = stats.ndis + + self.assertLess(ndis_with_sel * 4, ndis_no_sel * 3) + + def test_ensure_topk_full_fills_heap_under_restrictive_selector(self): + index = build_ivf_flat() + faiss.downcast_index(index).nprobe = nlist + + sel = make_bitmap_selector(10) + xq = make_data(nq, 0xDEADBE) + + params = faiss.SearchParametersIVF() + params.nprobe = nlist + params.max_codes = k // 2 + params.ensure_topk_full = True + params.sel = sel + + _, I = index.search(xq, k, params=params) + + self.assertEqual( + np.count_nonzero(I == -1), 0, + "ensure_topk_full failed to fill the heap under a " + "restrictive IDSelector") + + def test_fastscan_range_defaults_preserve_baseline(self): + index = build_fastscan() + faiss.downcast_index(index).nprobe = 4 + + xq = make_data(nq, 0x9999) + radius = 1.0 + + lims_ref, D_ref, I_ref = index.range_search(xq, radius) + + params = faiss.SearchParametersIVF() + params.nprobe = 4 + params.max_empty_result_buckets = 0 + lims_tst, D_tst, I_tst = index.range_search( + xq, radius, params=params) + + assert_sorted_pairs_equal( + self, lims_ref, D_ref, I_ref, lims_tst, D_tst, I_tst) + + def test_fastscan_range_rejects_max_empty_unsupported_parallel_mode(self): + index = build_fastscan() + faiss.downcast_index(index).parallel_mode = 1 + + xq = make_data(1, 0x9999) + + params = faiss.SearchParametersIVF() + params.nprobe = 4 + params.max_empty_result_buckets = 2 + with self.assertRaises(RuntimeError): + index.range_search(xq, 1.0, params=params) diff --git a/thirdparty/faiss/tests/test_ivf_flat_panorama.py b/thirdparty/faiss/tests/test_ivf_flat_panorama.py index 72d5ee244..dbb2a396e 100644 --- a/thirdparty/faiss/tests/test_ivf_flat_panorama.py +++ b/thirdparty/faiss/tests/test_ivf_flat_panorama.py @@ -3,16 +3,7 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Comprehensive test suite for IndexIVFFlatPanorama. - -Panorama is an adaptation of IndexIVFFlat that uses level-oriented storage -and progressive filtering with Cauchy-Schwarz bounds to achieve significant -speedups (up to 20x when combined with PCA or Cayley transforms) with zero -loss in accuracy. - -Paper: https://www.arxiv.org/pdf/2510.00566 -""" +"""Panorama paper: https://www.arxiv.org/pdf/2510.00566""" import unittest @@ -25,13 +16,8 @@ @for_all_simd_levels class TestIndexIVFFlatPanorama(unittest.TestCase): - """Test Suite for IndexIVFFlatPanorama.""" - - # Metrics to test METRICS = [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT] - # Helper methods for index creation and data generation - def generate_data(self, d, nt, nb, nq, seed=42): ds = SyntheticDataset(d, nt, nb, nq, seed=seed) return ds.get_train(), ds.get_database(), ds.get_queries() @@ -43,7 +29,6 @@ def create_ivf_flat( xt, xb=None, nprobe=None, - make_direct_map=False, metric=faiss.METRIC_L2, ): quantizer = ( @@ -53,8 +38,6 @@ def create_ivf_flat( ) index = faiss.IndexIVFFlat(quantizer, d, nlist, metric) index.train(xt) - if make_direct_map: - index.make_direct_map() if xb is not None: index.add(xb) if nprobe is not None: @@ -69,11 +52,9 @@ def create_panorama( xt, xb=None, nprobe=None, - make_direct_map=False, metric=faiss.METRIC_L2, batch_size=faiss.Panorama.kDefaultBatchSize, ): - """Create and initialize IndexIVFFlatPanorama.""" quantizer = ( faiss.IndexFlatL2(d) if metric == faiss.METRIC_L2 @@ -83,8 +64,6 @@ def create_panorama( quantizer, d, nlist, nlevels, metric, True, batch_size ) index.train(xt) - if make_direct_map: - index.make_direct_map() if xb is not None: index.add(xb) if nprobe is not None: @@ -97,18 +76,9 @@ def assert_search_results_equal( I_regular, D_panorama, I_panorama, - rtol=1e-5, - atol=1e-4, ): - np.testing.assert_allclose( - D_regular, - D_panorama, - rtol=rtol, - atol=atol, - err_msg="Distances mismatch", - ) check_ref_knn_with_draws( - D_regular, I_regular, D_panorama, I_panorama, rtol=rtol, atol=atol + D_regular, I_regular, D_panorama, I_panorama, rtol=1e-5, atol=1e-4 ) def assert_range_results_equal( @@ -164,8 +134,6 @@ def assert_range_results_equal( def validate_and_compare_range_results( self, metric, radius, lims_reg, D_reg, I_reg, lims_pan, D_pan, I_pan, nq ): - """Helper to validate range search results match between regular - and panorama.""" if metric == faiss.METRIC_L2: self.assertTrue( np.all(D_pan <= radius), @@ -180,54 +148,7 @@ def validate_and_compare_range_results( lims_reg, D_reg, I_reg, lims_pan, D_pan, I_pan, nq ) - # Core functionality tests - - def test_exact_match_with_ivf_flat(self): - """Core test: Panorama must return identical results to IndexIVFFlat""" - d, nb, nt, nq, nlist, nlevels, k = 128, 100000, 150000, 1000, 512, 8, 20 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=42) - - for metric in self.METRICS: - for nprobe in [1, 16, 64, 256]: - with self.subTest(metric=metric, nprobe=nprobe): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - def test_exact_match_with_ivf_flat_medium(self): - """Core test: Medium scale version""" - d, nb, nt, nq, nlist, nlevels, k = 64, 10000, 15000, 200, 128, 4, 10 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=42) - - for metric in self.METRICS: - for nprobe in [1, 4, 8, nlist]: - with self.subTest(metric=metric, nprobe=nprobe): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_range_search(self): - """Test range search returns correct results within radius""" d, nb, nt, nq, nlist, nlevels = 128, 50000, 75000, 500, 256, 8 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=123) @@ -259,10 +180,7 @@ def test_range_search(self): nq, ) - # Parameter variation tests - def test_different_n_levels(self): - """Test correctness with various n_levels parameter values""" d, nb, nt, nq, nlist, k = 128, 25000, 40000, 300, 128, 15 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=456) @@ -272,34 +190,17 @@ def test_different_n_levels(self): ) D_base, I_base = index_base.search(xq, k) - nt = faiss.omp_get_max_threads() - faiss.omp_set_num_threads(1) - - prev_ratio_dims_scanned = float("inf") for nlevels in [1, 2, 4, 8, 16, 32]: with self.subTest(metric=metric, nlevels=nlevels): - faiss.cvar.indexPanorama_stats.reset() index = self.create_panorama( d, nlist, nlevels, xt, xb, nprobe=32, metric=metric ) D, I = index.search(xq, k) self.assert_search_results_equal(D_base, I_base, D, I) - # Verify ratio_dims_scanned decreases as n_levels increases - ratio_dims_scanned = ( - faiss.cvar.indexPanorama_stats.ratio_dims_scanned - ) - self.assertLess(ratio_dims_scanned, prev_ratio_dims_scanned) - prev_ratio_dims_scanned = ratio_dims_scanned - - faiss.omp_set_num_threads(nt) - def test_uneven_dimension_division(self): - """Test when n_levels doesn't evenly divide dimension""" test_cases = [(65, 4), (63, 8), (100, 7), (960, 128), (964, 128)] - # TODO(aknayar): Test functions like get_single_code(). - for metric in self.METRICS: for d, nlevels in test_cases: with self.subTest(metric=metric, d=d, nlevels=nlevels): @@ -320,52 +221,7 @@ def test_uneven_dimension_division(self): D_regular, I_regular, D_panorama, I_panorama ) - def test_single_level(self): - """Test edge case with n_levels=1""" - d, nb, nt, nq, nlist, nlevels, k = 32, 500, 700, 20, 16, 1, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=333) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe=4, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=4, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - def test_multiple_levels_small_dimension(self): - """Test edge case: more levels than dimension naturally supports""" - d, nb, nt, nq, nlist, nlevels, k = 16, 200, 300, 10, 4, 8, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=1212) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe=4, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=4, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - # ID selector tests - def test_id_selector_range(self): - """Test ID filtering with range selector""" d, nb, nt, nq, nlist, nlevels, k = 128, 80000, 120000, 500, 512, 8, 20 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=321) @@ -388,78 +244,10 @@ def test_id_selector_range(self): xq, k, params=params ) - self.assertTrue(np.all(I_panorama >= 10000)) - self.assertTrue(np.all(I_panorama < 50000)) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-4) - - def test_id_selector_batch(self): - """Test ID filtering with batch selector""" - d, nb, nt, nq, nlist, nlevels, k = 128, 60000, 90000, 400, 256, 8, 20 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=654) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe=32, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=32, metric=metric - ) - - allowed_ids = np.array( - [i * 100 for i in range(500)], dtype=np.int64 - ) - params = faiss.SearchParametersIVF() - params.sel = faiss.IDSelectorBatch(allowed_ids) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - allowed_set = set(allowed_ids) | set([-1]) - for id_val in I_panorama.flatten(): - self.assertIn(int(id_val), allowed_set) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-4) - - def test_selector_with_small_dataset(self): - """Test ID selectors with dataset smaller than batch size""" - d, nb, nt, nq, nlist, nlevels, k = 32, 100, 200, 10, 4, 4, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=888) - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe=nlist, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=nlist, metric=metric - ) - - params = faiss.SearchParametersIVF() - params.sel = faiss.IDSelectorRange(20, 60) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - self.assertTrue(np.all(I_panorama >= 20)) - self.assertTrue(np.all(I_panorama < 60)) - np.testing.assert_array_equal(I_regular, I_panorama) np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-4) def test_selector_excludes_all(self): - """Test selector that excludes all results""" d, nb, nt, nq, nlist, nlevels, k = 32, 300, 400, 5, 8, 4, 10 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=999) @@ -475,18 +263,14 @@ def test_selector_excludes_all(self): D, I = index_panorama.search(xq, k, params=params) self.assertTrue(np.all(I == -1)) - # Batch size and edge case tests - def test_batch_boundaries(self): - """Test correctness at various batch size boundaries - (kDefaultBatchSize=128)""" d, nlist, nlevels, nt, nq, k = 128, 64, 8, 10000, 200, 15 np.random.seed(987) xt = np.random.rand(nt, d).astype("float32") xq = np.random.rand(nq, d).astype("float32") for metric in self.METRICS: - for nb in [5000, 10000, 20000, 50000, 75000]: + for nb in [5000, 50000, 75000]: with self.subTest(metric=metric, nb=nb): xb = np.random.rand(nb, d).astype("float32") @@ -504,53 +288,7 @@ def test_batch_boundaries(self): D_regular, I_regular, D_panorama, I_panorama ) - def test_empty_result_handling(self): - """Test handling of empty search results""" - d, nb, nt, nq, nlist, nlevels, k = 32, 100, 200, 5, 8, 4, 10 - xt, xb, _ = self.generate_data(d, nt, nb, nq, seed=111) - xq = ( - np.random.rand(nq, d).astype("float32") + 10.0 - ) # Queries far from database - - for metric in self.METRICS: - with self.subTest(metric=metric): - index = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=1, metric=metric - ) - D, I = index.search(xq, k) - - self.assertEqual(D.shape, (nq, k)) - self.assertEqual(I.shape, (nq, k)) - - def test_very_small_dataset(self): - """Test with dataset smaller than batch size (< 128 vectors)""" - test_cases = [10, 50, 100] - - for metric in self.METRICS: - for nb in test_cases: - with self.subTest(metric=metric, nb=nb): - d, nt, nlist, nlevels, nq = 32, max(nb, 100), 4, 4, 5 - k = min(3, nb) - xt, xb, xq = self.generate_data( - d, nt, nb, nq, seed=666 + nb - ) - - index_regular = self.create_ivf_flat( - d, nlist, xt, xb, nprobe=nlist, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, xb, nprobe=nlist, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_single_vector_per_cluster(self): - """Test extreme case where clusters have very few vectors""" d, nb, nt, nq, nlist, nlevels, k = 32, 20, 100, 5, 16, 4, 3 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=1313) @@ -590,7 +328,6 @@ def test_single_vector_per_cluster(self): ) def test_range_search_edge_cases(self): - """Test range search with extreme radius values""" d, nb, nt, nq, nlist, nlevels = 32, 500, 700, 10, 8, 4 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=777) @@ -622,41 +359,7 @@ def test_range_search_edge_cases(self): nq, ) - # Dynamic operations tests - - def test_incremental_add(self): - """Test adding vectors incrementally in multiple batches""" - d, nt, nlist, nlevels, k = 128, 20000, 256, 8, 15 - np.random.seed(1515) - xt = np.random.rand(nt, d).astype("float32") - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_ivf_flat( - d, nlist, xt, nprobe=32, metric=metric - ) - index_panorama = self.create_panorama( - d, nlist, nlevels, xt, nprobe=32, metric=metric - ) - - batch_sizes = [10000, 15000, 20000, 5000] - for batch_size in batch_sizes: - xb_batch = np.random.rand(batch_size, d).astype("float32") - index_regular.add(xb_batch) - index_panorama.add(xb_batch) - - nq = 300 - xq = np.random.rand(nq, d).astype("float32") - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_add_search_add_search(self): - """Test interleaved add and search operations""" d, nt, nlist, nlevels, k = 32, 500, 8, 4, 5 np.random.seed(555) xt = np.random.rand(nt, d).astype("float32") @@ -670,7 +373,6 @@ def test_add_search_add_search(self): d, nlist, nlevels, xt, metric=metric ) - # First add and search xb1 = np.random.rand(200, d).astype("float32") index_regular.add(xb1) index_panorama.add(xb1) @@ -685,7 +387,6 @@ def test_add_search_add_search(self): D_reg_1, I_reg_1, D_pan_1, I_pan_1 ) - # Second add and search xb2 = np.random.rand(300, d).astype("float32") index_regular.add(xb2) index_panorama.add(xb2) @@ -698,34 +399,21 @@ def test_add_search_add_search(self): ) def test_update_vectors(self): - """Test update operations (single, batch, and interleaved with - search)""" d, nb, nt, nq, nlist, nlevels, k = 128, 40000, 60000, 400, 256, 8, 15 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=1414) for metric in self.METRICS: with self.subTest(metric=metric): index_regular = self.create_ivf_flat( - d, - nlist, - xt, - xb, - nprobe=32, - make_direct_map=True, - metric=metric, + d, nlist, xt, nprobe=32, metric=metric ) index_panorama = self.create_panorama( - d, - nlist, - nlevels, - xt, - xb, - nprobe=32, - make_direct_map=True, - metric=metric, + d, nlist, nlevels, xt, nprobe=32, metric=metric ) + for index in index_regular, index_panorama: + index.make_direct_map() + index.add(xb) - # Test batch update update_ids = np.array( [100, 1000, 5000, 10000, 20000, 30000], dtype=np.int64 ) @@ -737,23 +425,7 @@ def test_update_vectors(self): D_pan, I_pan = index_panorama.search(xq, k) self.assert_search_results_equal(D_reg, I_reg, D_pan, I_pan) - # Test interleaved update/search - update_ids_2 = np.array([50, 500, 2500, 15000], dtype=np.int64) - xb_new_2 = np.random.rand(len(update_ids_2), d).astype( - "float32" - ) - index_regular.update_vectors(update_ids_2, xb_new_2) - index_panorama.update_vectors(update_ids_2, xb_new_2) - - D_reg_2, I_reg_2 = index_regular.search(xq, k) - D_pan_2, I_pan_2 = index_panorama.search(xq, k) - self.assert_search_results_equal( - D_reg_2, I_reg_2, D_pan_2, I_pan_2 - ) - def test_serialization(self): - """Test that writing and reading Panorama indexes preserves - search results""" d, nb, nt, nq, nlist, nlevels, k = 128, 10000, 15000, 100, 128, 8, 20 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=2024) @@ -823,7 +495,6 @@ def test_read_legacy_format(self): np.testing.assert_array_equal(D_ref, D_legacy) def test_ratio_dims_scanned(self): - """Test the correctness of the ratio of dimensions scanned""" d, nb, nq, nlist, k = 128, 500000, 1, 1, 1 # Setup: All vectors in the dataset are [1, 1, ..., 1], except for diff --git a/thirdparty/faiss/tests/test_ivf_index.cpp b/thirdparty/faiss/tests/test_ivf_index.cpp index 27fe907f9..3bc3d4760 100644 --- a/thirdparty/faiss/tests/test_ivf_index.cpp +++ b/thirdparty/faiss/tests/test_ivf_index.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -17,9 +18,14 @@ #include #include +#include #include +#include #include +#include #include +#include +#include namespace { @@ -38,15 +44,12 @@ class TestContext { id++; } - // id to codes map std::unordered_map> codes; - // id to list_no map std::unordered_map list_nos; faiss::idx_t id = 0; std::set lists_probed; }; -// the iterator that iterates over the codes stored in context object class TestInvertedListIterator : public faiss::InvertedListsIterator { public: TestInvertedListIterator(size_t list_no_in, TestContext* context_in) @@ -81,7 +84,6 @@ class TestInvertedListIterator : public faiss::InvertedListsIterator { return std::make_pair(it->first, it->second.data()); } - private: size_t list_no; TestContext* context; decltype(context->codes.cbegin()) it; @@ -114,7 +116,6 @@ class TestInvertedLists : public faiss::InvertedLists { FAISS_THROW_MSG("unexpected call"); } - // store the codes in context object size_t add_entry( size_t list_no, faiss::idx_t /*theid*/, @@ -149,14 +150,9 @@ class TestInvertedLists : public faiss::InvertedLists { } // namespace TEST(IVF, list_context) { - // this test verifies that the context object is passed - // to the InvertedListsIterator and InvertedLists::add_entry. - // the test InvertedLists and InvertedListsIterator reads/writes - // to the test context object. - // the test verifies the context object is modified as expected. - - constexpr int d = 32; // dimension - constexpr int nb = 100000; // database size + // the context object must reach InvertedLists::add_entry and get_iterator + constexpr int d = 32; + constexpr int nb = 100000; constexpr int nlist = 100; std::mt19937 rng; @@ -171,8 +167,7 @@ TEST(IVF, list_context) { TestInvertedLists inverted_lists(nlist, index.code_size); index.replace_invlists(&inverted_lists); { - // training - constexpr size_t nt = 1500; // nb of training vectors + constexpr size_t nt = 1500; std::vector trainvecs(nt * d); for (size_t i = 0; i < nt * d; i++) { trainvecs[i] = distrib(rng); @@ -184,31 +179,24 @@ TEST(IVF, list_context) { std::vector query_vector; constexpr faiss::idx_t query_vector_id = 100; { - // populating the database std::vector database(nb * d); for (size_t i = 0; i < nb * d; i++) { database[i] = distrib(rng); - // populate the query vector if (i >= query_vector_id * d && i < query_vector_id * d + d) { query_vector.push_back(database[i]); } } std::vector coarse_idx(nb); index.quantizer->assign(nb, database.data(), coarse_idx.data()); - // pass dummy ids, the actual ids are assigned in TextContext object + // dummy ids: TestContext assigns the real ones std::vector xids(nb, 42); index.add_core( nb, database.data(), xids.data(), coarse_idx.data(), &context); - // check the context object get updated EXPECT_EQ(nb, context.id) << "should have added all ids"; - EXPECT_EQ(nb, context.codes.size()) - << "should have correct number of codes"; - EXPECT_EQ(nb, context.list_nos.size()) - << "should have correct number of list numbers"; } { - constexpr size_t num_vecs = 5; // number of vectors + constexpr size_t num_vecs = 5; std::vector vecs(num_vecs * d); for (size_t i = 0; i < num_vecs * d; i++) { vecs[i] = distrib(rng); @@ -241,127 +229,135 @@ TEST(IVF, list_context) { // check the result contains the query vector, the probablity of // this fail should be low - auto query_vector_listno = context.list_nos[query_vector_id]; - auto& lists_probed = context.lists_probed; - EXPECT_TRUE( - std::find( - lists_probed.cbegin(), - lists_probed.cend(), - query_vector_listno) != lists_probed.cend()) - << "should probe the list of the query vector"; EXPECT_TRUE( std::find(labels.cbegin(), labels.cend(), query_vector_id) != labels.cend()) << "should return the query vector"; } -} - -TEST(IVF, jaccard_search_returns_most_similar_vector) { - constexpr int d = 3; - constexpr int nb = 3; - const float xb[nb * d] = { - 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f}; - - faiss::IndexFlatL2 quantizer(d); - quantizer.add(1, xb); - faiss::IndexIVFFlat index(&quantizer, d, 1, faiss::METRIC_Jaccard); - index.add(nb, xb); - - for (int parallel_mode = 0; parallel_mode < 4; parallel_mode++) { - index.parallel_mode = parallel_mode; - float distance; - faiss::idx_t label; - index.search(1, xb, 1, &distance, &label); + // assume_sorted picks the bounded-section shortcut on an array-backed + // list. An iterable list has no section to bound, so it must keep the + // selector and filter per entry instead. + for (bool assume_sorted : {false, true}) { + SCOPED_TRACE(testing::Message() << "assume_sorted=" << assume_sorted); + constexpr faiss::idx_t k = 100; + constexpr size_t nprobe = 10; + faiss::IDSelectorRange selector(nb / 2, nb, assume_sorted); + faiss::SearchParametersIVF params; + params.inverted_list_context = &context; + params.nprobe = nprobe; + params.sel = &selector; - EXPECT_EQ(label, 0) << "parallel mode " << parallel_mode; - EXPECT_FLOAT_EQ(distance, 1.0f) << "parallel mode " << parallel_mode; + std::vector distances(k); + std::vector labels(k); + index.search( + 1, + query_vector.data(), + k, + distances.data(), + labels.data(), + ¶ms); + const size_t rejected_knn = std::count_if( + labels.cbegin(), labels.cend(), [&](faiss::idx_t id) { + return id != -1 && !selector.is_member(id); + }); + EXPECT_EQ(0, rejected_knn); + + faiss::RangeSearchResult result(1); + index.range_search( + 1, + query_vector.data(), + std::numeric_limits::max(), + &result, + ¶ms); + const size_t rejected_range = std::count_if( + result.labels, + result.labels + result.lims[1], + [&](faiss::idx_t id) { return !selector.is_member(id); }); + EXPECT_EQ(0, rejected_range); } } -// Test: search_preassigned with out-of-range keys throws a catchable -// FaissException instead of calling std::terminate from an uncaught -// exception inside the OpenMP parallel region. -TEST(IVF, search_preassigned_out_of_range_key) { - int d = 4; - int nlist = 2; - faiss::IndexFlatL2 quantizer(d); - faiss::IndexIVFFlat idx(&quantizer, d, nlist); - idx.own_fields = false; +namespace { - // Train and add some vectors so the index is usable. - std::vector train_data(nlist * d, 0.0f); - for (int i = 0; i < nlist * d; i++) { - train_data[i] = static_cast(i); - } - idx.train(nlist, train_data.data()); - idx.add(nlist, train_data.data()); +// Counts the code fetches that a scan performs, so a test can show that a list +// the range filter empties never reaches its codes. +struct CountingInvertedLists : faiss::ArrayInvertedLists { + mutable size_t code_fetches = 0; - // Query vector. - std::vector xq(d, 1.0f); - std::vector distances(1); - std::vector labels(1); + CountingInvertedLists(size_t nlist_in, size_t code_size_in) + : faiss::ArrayInvertedLists(nlist_in, code_size_in) {} - // Pass a key >= nlist to search_preassigned. - faiss::idx_t bad_key = nlist; // out of range - float coarse_dis = 0.0f; + const uint8_t* get_codes(size_t list_no) const override { + code_fetches++; + return faiss::ArrayInvertedLists::get_codes(list_no); + } +}; - EXPECT_THROW( - idx.search_preassigned( - 1, - xq.data(), - 1, - &bad_key, - &coarse_dis, - distances.data(), - labels.data(), - false), - faiss::FaissException); -} +} // namespace + +TEST(IVF, sorted_range_selector_skips_setup_for_filtered_lists) { + constexpr size_t d = 8; + constexpr size_t nb = 1000; + constexpr size_t nlist = 16; + constexpr faiss::idx_t k = 10; + constexpr faiss::idx_t range_end = 20; -// Test: range_search_preassigned with out-of-range keys throws a catchable -// FaissException instead of calling std::terminate from an uncaught -// exception inside the OpenMP parallel region. -TEST(IVF, range_search_preassigned_out_of_range_key) { - int d = 4; - int nlist = 2; faiss::IndexFlatL2 quantizer(d); - faiss::IndexIVFFlat idx(&quantizer, d, nlist); - idx.own_fields = false; + faiss::IndexIVFFlat index(&quantizer, d, nlist); - std::vector train_data(nlist * d, 0.0f); - for (int i = 0; i < nlist * d; i++) { - train_data[i] = static_cast(i); + std::mt19937 rng(12345); + std::normal_distribution normal(0.0f, 1.0f); + std::vector database(nb * d); + for (float& value : database) { + value = normal(rng); } - idx.train(nlist, train_data.data()); - idx.add(nlist, train_data.data()); - - std::vector xq(d, 1.0f); - faiss::RangeSearchResult result(1); + std::vector ids(nb); + for (size_t i = 0; i < nb; ++i) { + ids[i] = static_cast(i); // ascending, so each list sorts + } + index.train(nb, database.data()); + + auto* counting = new CountingInvertedLists(nlist, index.code_size); + index.replace_invlists(counting, /*own=*/true); + index.add_with_ids(nb, database.data(), ids.data()); + + // Lists that hold no id below range_end cannot contribute a result, so the + // scan must return before it fetches their codes. + size_t lists_in_range = 0; + size_t lists_non_empty = 0; + for (size_t list_no = 0; list_no < nlist; ++list_no) { + const size_t list_size = counting->list_size(list_no); + if (list_size == 0) { + continue; + } + lists_non_empty++; + const faiss::idx_t* list_ids = counting->ids[list_no].data(); + if (list_ids[0] < range_end) { + lists_in_range++; + } + } + ASSERT_GT(lists_in_range, 0u); + ASSERT_LT(lists_in_range, lists_non_empty); - faiss::idx_t bad_key = nlist; // out of range - float coarse_dis = 0.0f; + faiss::IDSelectorRange selector(0, range_end, /*assume_sorted=*/true); + faiss::SearchParametersIVF params; + params.nprobe = nlist; + params.sel = &selector; - EXPECT_THROW( - idx.range_search_preassigned( - 1, - xq.data(), - std::numeric_limits::max(), - &bad_key, - &coarse_dis, - &result, - false), - faiss::FaissException); + std::vector distances(k); + std::vector labels(k); + counting->code_fetches = 0; + index.search( + 1, database.data(), k, distances.data(), labels.data(), ¶ms); + EXPECT_EQ(lists_in_range, counting->code_fetches); } -// Minimal ResultHandler that just collects results presented to it. struct CollectResultHandler : faiss::ResultHandler { bool add_result(float, faiss::idx_t) override { return false; } }; -// Test: search1 with a quantizer that returns out-of-range keys throws -// FaissException. TEST(IVF, search1_out_of_range_key) { int d = 4; int nlist = 2; @@ -369,7 +365,6 @@ TEST(IVF, search1_out_of_range_key) { faiss::IndexIVFFlat idx(&quantizer, d, nlist); idx.own_fields = false; - // Train and add vectors so the index is usable. std::vector train_data(nlist * d, 0.0f); for (int i = 0; i < nlist * d; i++) { train_data[i] = static_cast(i); @@ -381,9 +376,7 @@ TEST(IVF, search1_out_of_range_key) { // can return key == nlist (out of range) for a query near that point. std::vector extra_centroid(d, 1e6f); quantizer.add(1, extra_centroid.data()); - // Now quantizer has nlist+1 centroids, but idx.nlist is still nlist. - // Query near the extra centroid so quantizer returns the bad key. std::vector xq(d, 1e6f); CollectResultHandler handler; handler.threshold = std::numeric_limits::max(); @@ -391,15 +384,14 @@ TEST(IVF, search1_out_of_range_key) { EXPECT_THROW(idx.search1(xq.data(), handler), faiss::FaissException); } -// Iterator that enables search callbacks and tracks invocations. class CallbackTrackingIterator : public TestInvertedListIterator { public: CallbackTrackingIterator( - size_t list_no, - TestContext* context, + size_t list_no_in, + TestContext* context_in, size_t& distance_count, size_t& heap_count) - : TestInvertedListIterator(list_no, context), + : TestInvertedListIterator(list_no_in, context_in), distance_count_{distance_count}, heap_count_{heap_count} { has_search_callbacks_ = true; @@ -418,12 +410,10 @@ class CallbackTrackingIterator : public TestInvertedListIterator { heap_count_++; } - private: size_t& distance_count_; size_t& heap_count_; }; -// InvertedLists that uses CallbackTrackingIterator. class CallbackTrackingInvertedLists : public TestInvertedLists { public: CallbackTrackingInvertedLists( @@ -443,13 +433,10 @@ class CallbackTrackingInvertedLists : public TestInvertedLists { list_no, testContext, distance_count_, heap_count_); } - private: size_t& distance_count_; size_t& heap_count_; }; -// Test: on_distance_computed and on_heap_changed fire during search -// when has_search_callbacks_ is true. TEST(IVF, search_callbacks) { constexpr int d = 8; constexpr int nb = 200; @@ -469,7 +456,6 @@ TEST(IVF, search_callbacks) { nlist, index.code_size, distance_count, heap_count); index.replace_invlists(&invlists); - // Train constexpr size_t nt = 100; std::vector trainvecs(nt * d); for (size_t i = 0; i < nt * d; i++) { @@ -477,7 +463,6 @@ TEST(IVF, search_callbacks) { } index.train(nt, trainvecs.data()); - // Populate via context TestContext context; std::vector database(nb * d); for (size_t i = 0; i < nb * d; i++) { @@ -489,7 +474,6 @@ TEST(IVF, search_callbacks) { index.add_core( nb, database.data(), xids.data(), coarse_idx.data(), &context); - // Search constexpr faiss::idx_t k = 5; constexpr size_t nprobe = 2; std::vector query(d); @@ -511,3 +495,387 @@ TEST(IVF, search_callbacks) { EXPECT_GE(distance_count, heap_count) << "not every distance computation leads to a heap change"; } + +namespace { + +class LimitedEncoderIndex : public faiss::IndexIVFScalarQuantizer { + public: + LimitedEncoderIndex(faiss::Index* quantizer_in, int d_in, int nlist_in) + : faiss::IndexIVFScalarQuantizer( + quantizer_in, + d_in, + nlist_in, + faiss::ScalarQuantizer::QT_8bit) {} + + faiss::idx_t train_encoder_num_vectors() const override { + return 7; + } + + void train_encoder( + faiss::idx_t n, + const float* x, + const faiss::idx_t* assign) override { + encoder_input.assign(x, x + n * d); + encoder_assignments.assign(assign, assign + n); + } + + std::vector encoder_input; + std::vector encoder_assignments; +}; + +class TrackingFp16Codec : public faiss::IndexScalarQuantizer { + public: + explicit TrackingFp16Codec(int d_in) + : faiss::IndexScalarQuantizer( + d_in, + faiss::ScalarQuantizer::QuantizerType::QT_fp16) {} + + void sa_decode(faiss::idx_t n, const uint8_t* bytes, float* x) + const override { + decode_calls.fetch_add(1, std::memory_order_relaxed); + max_decode_rows = std::max(max_decode_rows, static_cast(n)); + faiss::IndexScalarQuantizer::sa_decode(n, bytes, x); + } + + mutable std::atomic decode_calls{0}; + mutable size_t max_decode_rows = 0; +}; + +std::vector encode_fp16(const std::vector& values) { + std::vector encoded(values.size()); + for (size_t i = 0; i < values.size(); ++i) { + encoded[i] = faiss::encode_fp16(values[i]); + } + return encoded; +} + +std::vector decode_fp16(const std::vector& values) { + std::vector decoded(values.size()); + for (size_t i = 0; i < values.size(); ++i) { + decoded[i] = faiss::decode_fp16(values[i]); + } + return decoded; +} + +} // namespace + +TEST(IVF, train_float16_with_super_kmeans_matches_float32) { + constexpr int d = 32; + constexpr int n = 96; + constexpr int nlist = 4; + + std::vector input(n * d); + for (int i = 0; i < n; ++i) { + const float center = static_cast(i % nlist) * 8.0f; + for (int j = 0; j < d; ++j) { + input[static_cast(i) * d + j] = center + + static_cast((i * 17 + j * 13) % 31) / 100.0f; + } + } + auto encoded = encode_fp16(input); + auto rounded = decode_fp16(encoded); + + faiss::IndexFlatL2 float_quantizer(d); + faiss::IndexIVFFlat float_index(&float_quantizer, d, nlist); + float_index.cp.seed = 1234; + float_index.cp.niter = 3; + float_index.cp.min_points_per_centroid = 1; + float_index.cp.use_super_kmeans = true; + float_index.train(n, rounded.data()); + + faiss::IndexFlatL2 half_quantizer(d); + faiss::IndexIVFFlat half_index(&half_quantizer, d, nlist); + half_index.cp = float_index.cp; + half_index.cp.decode_block_size = n; + half_index.train_ex(n, encoded.data(), faiss::NumericType::Float16); + + std::vector float_centroids(nlist * d); + std::vector half_centroids(nlist * d); + float_quantizer.reconstruct_n(0, nlist, float_centroids.data()); + half_quantizer.reconstruct_n(0, nlist, half_centroids.data()); + EXPECT_EQ(half_centroids, float_centroids); + + TrackingFp16Codec codec(d); + faiss::IndexFlatL2 encoded_quantizer(d); + faiss::IndexIVFFlat encoded_index(&encoded_quantizer, d, nlist); + encoded_index.cp = float_index.cp; + EXPECT_THROW( + encoded_index.train_encoded( + n, + reinterpret_cast(encoded.data()), + &codec), + faiss::FaissException); + + faiss::IndexFlatIP ip_quantizer(d); + faiss::IndexIVFFlat ip_index( + &ip_quantizer, d, nlist, faiss::METRIC_INNER_PRODUCT); + ip_index.cp = float_index.cp; + EXPECT_THROW( + ip_index.train_ex(n, encoded.data(), faiss::NumericType::Float16), + faiss::FaissException); +} + +TEST(IVF, encoded_training_decodes_in_bounded_batches) { + constexpr int d = 4; + constexpr int n = 40; + constexpr int nlist = 2; + constexpr size_t decode_block_size = 5; + + std::vector input(n * d); + for (size_t i = 0; i < input.size(); ++i) { + input[i] = static_cast((i * 11) % 97) / 17.0f; + } + auto encoded = encode_fp16(input); + TrackingFp16Codec codec(d); + faiss::IndexFlatL2 quantizer(d); + faiss::IndexIVFFlat index(&quantizer, d, nlist); + index.cp.decode_block_size = decode_block_size; + index.cp.niter = 2; + index.cp.min_points_per_centroid = 1; + index.train_encoded( + n, reinterpret_cast(encoded.data()), &codec); + + EXPECT_TRUE(index.is_trained); + EXPECT_GT(codec.max_decode_rows, 0); + EXPECT_LE(codec.max_decode_rows, decode_block_size); +} + +TEST(IVF, encoded_training_skips_nan_scan) { + constexpr int d = 2; + constexpr int n = 2; + auto encoded = encode_fp16({0.0f, 1.0f, 2.0f, 3.0f}); + TrackingFp16Codec codec(d); + faiss::Clustering clustering(d, n); + faiss::IndexFlatL2 index(d); + + clustering.train_encoded( + n, reinterpret_cast(encoded.data()), &codec, index); + + EXPECT_EQ(codec.decode_calls.load(std::memory_order_relaxed), 1); +} + +TEST(IVF, encoded_training_validates_codec) { + constexpr int d = 4; + constexpr int n = 4; + constexpr int nlist = 2; + std::vector encoded(n * (d + 1), faiss::encode_fp16(1.0f)); + + faiss::IndexFlatL2 quantizer(d); + std::vector centroids(nlist * d, 0.0f); + quantizer.add(nlist, centroids.data()); + faiss::IndexIVFFlat index(&quantizer, d, nlist); + TrackingFp16Codec wrong_dimension_codec(d + 1); + + EXPECT_THROW( + index.train_encoded( + n, + reinterpret_cast(encoded.data()), + &wrong_dimension_codec), + faiss::FaissException); + EXPECT_THROW( + index.train_encoded( + n, + reinterpret_cast(encoded.data()), + nullptr), + faiss::FaissException); +} + +TEST(IVF, encoded_encoder_subsampling_matches_float32) { + constexpr int d = 4; + constexpr int n = 40; + constexpr int nlist = 2; + + std::vector input(n * d); + for (size_t i = 0; i < input.size(); ++i) { + input[i] = static_cast((i * 23) % 127) / 29.0f; + } + auto encoded = encode_fp16(input); + auto rounded = decode_fp16(encoded); + + faiss::IndexFlatL2 float_quantizer(d); + LimitedEncoderIndex float_index(&float_quantizer, d, nlist); + float_index.cp.seed = 1234; + float_index.cp.niter = 2; + float_index.cp.min_points_per_centroid = 1; + float_index.train(n, rounded.data()); + + faiss::IndexFlatL2 half_quantizer(d); + LimitedEncoderIndex half_index(&half_quantizer, d, nlist); + half_index.cp.seed = 1234; + half_index.cp.niter = 2; + half_index.cp.min_points_per_centroid = 1; + half_index.train_ex(n, encoded.data(), faiss::NumericType::Float16); + + EXPECT_EQ(half_index.encoder_input, float_index.encoder_input); + EXPECT_EQ(half_index.encoder_assignments, float_index.encoder_assignments); +} + +namespace { + +class TrackingFlatL2 : public faiss::IndexFlatL2 { + public: + explicit TrackingFlatL2(faiss::idx_t d_in) : faiss::IndexFlatL2(d_in) {} + + void search( + faiss::idx_t n, + const float* x, + faiss::idx_t k, + float* distances, + faiss::idx_t* labels, + const faiss::SearchParameters* params = nullptr) const override { + max_search_rows = std::max(max_search_rows, static_cast(n)); + faiss::IndexFlatL2::search(n, x, k, distances, labels, params); + } + + void search_ex( + faiss::idx_t n, + const void* x, + faiss::NumericType numeric_type, + faiss::idx_t k, + float* distances, + faiss::idx_t* labels, + const faiss::SearchParameters* params = nullptr) const override { + max_search_rows = std::max(max_search_rows, static_cast(n)); + if (numeric_type == faiss::NumericType::Float16) { + fp16_search_calls++; + } + faiss::IndexFlatL2::search_ex( + n, x, numeric_type, k, distances, labels, params); + } + + mutable size_t max_search_rows = 0; + mutable size_t fp16_search_calls = 0; +}; + +class InvalidAssignmentIndex : public faiss::IndexFlatL2 { + public: + explicit InvalidAssignmentIndex(faiss::idx_t d_in) + : faiss::IndexFlatL2(d_in) {} + + void search_ex( + faiss::idx_t n, + const void* /*x*/, + faiss::NumericType /*numeric_type*/, + faiss::idx_t k, + float* distances, + faiss::idx_t* labels, + const faiss::SearchParameters* /*params*/ = + nullptr) const override { + const size_t result_size = + static_cast(n) * static_cast(k); + std::fill_n(distances, result_size, 0.0f); + std::fill_n(labels, result_size, faiss::idx_t{-1}); + } +}; + +std::vector make_training_data(size_t n, size_t d) { + std::vector x(n * d); + for (size_t i = 0; i < x.size(); ++i) { + x[i] = static_cast((i * 29) % 131) / 17.0f - 3.0f; + } + return x; +} + +faiss::ClusteringParameters small_clustering_params(int niter) { + faiss::ClusteringParameters cp; + cp.niter = niter; + cp.seed = 1234; + cp.min_points_per_centroid = 1; + return cp; +} + +} // namespace + +TEST(Clustering, float16_initializers_match_with_existing_and_early_return) { + constexpr size_t n = 24; + constexpr size_t d = 5; + constexpr size_t k = 3; + auto encoded = encode_fp16(make_training_data(n, d)); + auto rounded = decode_fp16(encoded); + const std::vector existing = {-4.0f, -2.0f, 0.0f, 2.0f, 4.0f}; + + for (auto method : + {faiss::ClusteringInitMethod::KMEANS_PLUS_PLUS, + faiss::ClusteringInitMethod::AFK_MC2}) { + faiss::ClusteringInitialization initializer(d, k); + initializer.method = method; + initializer.seed = 4321; + initializer.afkmc2_chain_length = 7; + std::vector full(k * d); + std::vector half(k * d); + + initializer.init_centroids( + n, rounded.data(), full.data(), 1, existing.data()); + faiss::detail::init_centroids_fp16( + initializer, + n, + encoded.data(), + half.data(), + 1, + existing.data()); + EXPECT_EQ(half, full) << "existing method=" << static_cast(method); + + faiss::ClusteringInitialization single(d, 1); + single.method = method; + single.seed = 4321; + std::vector full_single(d); + std::vector half_single(d); + single.init_centroids(n, rounded.data(), full_single.data()); + faiss::detail::init_centroids_fp16( + single, n, encoded.data(), half_single.data()); + EXPECT_EQ(half_single, full_single) + << "early return method=" << static_cast(method); + } +} + +TEST(Clustering, train_ex_float16_assigns_in_bounded_batches) { + constexpr size_t n = 50; + constexpr size_t d = 8; + constexpr size_t k = 3; + auto encoded = encode_fp16(make_training_data(n, d)); + auto cp = small_clustering_params(3); + cp.decode_block_size = 7; + + faiss::Clustering clus(d, k, cp); + TrackingFlatL2 index(d); + clus.train_ex(n, encoded.data(), faiss::NumericType::Float16, index); + + EXPECT_GT(index.max_search_rows, 0); + EXPECT_LE(index.max_search_rows, cp.decode_block_size); + // fp16 blocks reach the index through search_ex, not widened beforehand + EXPECT_GT(index.fp16_search_calls, 0); +} + +TEST(Clustering, train_ex_invalid_assignment_throws) { + constexpr int n = 8; + constexpr int d = 3; + constexpr int k = 2; + auto encoded = encode_fp16(make_training_data(n, d)); + faiss::Clustering clustering(d, k, small_clustering_params(1)); + InvalidAssignmentIndex index(d); + + EXPECT_THROW( + clustering.train_ex( + n, encoded.data(), faiss::NumericType::Float16, index), + faiss::FaissException); +} + +TEST(IVF, train_float16_clustering_index_sees_bounded_batches) { + constexpr int d = 8; + constexpr int n = 60; + constexpr int nlist = 3; + auto encoded = encode_fp16(make_training_data(n, d)); + + faiss::IndexFlatL2 quantizer(d); + TrackingFlatL2 clustering_index(d); + faiss::IndexIVFScalarQuantizer index( + &quantizer, d, nlist, faiss::ScalarQuantizer::QT_8bit); + index.clustering_index = &clustering_index; + index.cp = small_clustering_params(3); + index.cp.decode_block_size = 5; + index.train_ex(n, encoded.data(), faiss::NumericType::Float16); + + EXPECT_EQ(quantizer.ntotal, nlist); + EXPECT_GT(clustering_index.max_search_rows, 0); + EXPECT_LE(clustering_index.max_search_rows, index.cp.decode_block_size); +} diff --git a/thirdparty/faiss/tests/test_ivf_index.py b/thirdparty/faiss/tests/test_ivf_index.py new file mode 100644 index 000000000..b3f13c738 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivf_index.py @@ -0,0 +1,461 @@ +# 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. + +"""Tests for IVF index behavior.""" + +import contextlib +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +def encode_fp16(x): + return np.asarray(x, dtype=np.float32).astype(np.float16) + + +def decode_fp16(x): + return x.astype(np.float32) + + +def make_training_data(n, d): + i = np.arange(n * d, dtype=np.int64) + x = ((i * 29) % 131).astype(np.float32) / np.float32(17) - np.float32(3) + return x.reshape(n, d) + + +def make_queries(n, d): + i = np.arange(n * d, dtype=np.int64) + x = ((i * 37) % 113).astype(np.float32) / np.float32(19) - np.float32(3) + return x.reshape(n, d) + + +def small_clustering_params(niter): + cp = faiss.ClusteringParameters() + cp.niter = niter + cp.seed = 1234 + cp.min_points_per_centroid = 1 + return cp + + +@contextlib.contextmanager +def scoped_blas_tiles(query_bs): + threshold = faiss.cvar.distance_compute_blas_threshold + saved_query_bs = faiss.cvar.distance_compute_blas_query_bs + faiss.cvar.distance_compute_blas_threshold = 0 + faiss.cvar.distance_compute_blas_query_bs = query_bs + try: + yield + finally: + faiss.cvar.distance_compute_blas_threshold = threshold + faiss.cvar.distance_compute_blas_query_bs = saved_query_bs + + +def iteration_objs(clus): + stats = clus.iteration_stats + return [stats.at(i).obj for i in range(stats.size())] + + +class TestIVFIndex(unittest.TestCase): + def test_sorted_range_selector_rejects_store_pairs(self): + d = 4 + nb = 100 + k = 50 + + quantizer = faiss.IndexFlatL2(d) + centroid = np.zeros((1, d), dtype=np.float32) + quantizer.add(centroid) + index = faiss.IndexIVFFlat(quantizer, d, 1) + index.is_trained = True + + database = np.zeros((nb, d), dtype=np.float32) + ids = np.zeros(nb, dtype=np.int64) + for i in range(nb): + ids[i] = 1000 + i + for j in range(d): + database[i, j] = float(i + j) + index.add_with_ids(database, ids) + + selector = faiss.IDSelectorRange(1020, 1040, True) + params = faiss.SearchParametersIVF() + params.nprobe = 1 + params.sel = selector + keys = np.zeros((1, 1), dtype=np.int64) + coarse_distance = np.zeros((1, 1), dtype=np.float32) + D = np.empty((1, k), dtype=np.float32) + I = np.empty((1, k), dtype=np.int64) + with self.assertRaises(RuntimeError): + index.search_preassigned_c( + 1, + faiss.swig_ptr(centroid), + k, + faiss.swig_ptr(keys), + faiss.swig_ptr(coarse_distance), + faiss.swig_ptr(D), + faiss.swig_ptr(I), + True, + params, + ) + + def test_jaccard_search_returns_most_similar_vector(self): + d = 3 + xb = np.array( + [ + [1.0, 0.0, 1.0], + [1.0, 1.0, 0.0], + [0.0, 1.0, 1.0], + ], + dtype=np.float32, + ) + + quantizer = faiss.IndexFlatL2(d) + quantizer.add(xb[:1]) + index = faiss.IndexIVFFlat(quantizer, d, 1, faiss.METRIC_Jaccard) + index.add(xb) + + for parallel_mode in range(4): + index.parallel_mode = parallel_mode + D, I = index.search(xb[:1], 1) + self.assertEqual(I[0][0], 0, f"parallel mode {parallel_mode}") + self.assertAlmostEqual( + D[0][0], 1.0, msg=f"parallel mode {parallel_mode}") + + def test_preassigned_out_of_range_key(self): + d = 4 + nlist = 2 + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFFlat(quantizer, d, nlist) + + train_data = np.arange(nlist * d, dtype=np.float32).reshape( + nlist, d) + index.train(train_data) + index.add(train_data) + + xq = np.ones((1, d), dtype=np.float32) + bad_keys = np.array([[nlist]], dtype=np.int64) + coarse_dis = np.zeros((1, 1), dtype=np.float32) + with self.assertRaises(RuntimeError): + index.search_preassigned(xq, 1, bad_keys, coarse_dis) + with self.assertRaises(RuntimeError): + index.range_search_preassigned( + xq, np.finfo(np.float32).max, bad_keys, coarse_dis + ) + + def test_train_float16_matches_float32_on_rounded_input(self): + d = 4 + n = 64 + nlist = 4 + + i = np.arange(n * d, dtype=np.int64) + x = ((i * 17) % 101).astype(np.float32) / np.float32(13) + encoded = encode_fp16(x.reshape(n, d)) + rounded = decode_fp16(encoded) + + float_quantizer = faiss.IndexFlatL2(d) + float_index = faiss.IndexIVFFlat(float_quantizer, d, nlist) + float_index.cp.seed = 1234 + float_index.cp.niter = 4 + float_index.cp.min_points_per_centroid = 1 + float_index.train(rounded) + + half_quantizer = faiss.IndexFlatL2(d) + half_index = faiss.IndexIVFFlat(half_quantizer, d, nlist) + half_index.cp.seed = 1234 + half_index.cp.niter = 4 + half_index.cp.min_points_per_centroid = 1 + half_index.train(encoded, numeric_type=faiss.Float16) + + self.assertTrue(half_index.is_trained) + np.testing.assert_array_equal( + half_quantizer.reconstruct_n(0, nlist), + float_quantizer.reconstruct_n(0, nlist), + ) + + def test_train_float16_trains_scalar_quantizer_encoder(self): + d = 4 + n = 128 + nlist = 4 + + i = np.arange(n * d, dtype=np.int64) + x = ((i * 19) % 113).astype(np.float32) / np.float32(23) + encoded = encode_fp16(x.reshape(n, d)) + + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFScalarQuantizer( + quantizer, d, nlist, faiss.ScalarQuantizer.QT_8bit) + index.cp.seed = 1234 + index.cp.niter = 4 + index.cp.min_points_per_centroid = 1 + index.train(encoded, numeric_type=faiss.Float16) + + self.assertTrue(index.is_trained) + self.assertEqual(quantizer.ntotal, nlist) + self.assertGreater(index.sq.trained.size(), 0) + + def test_train_float16_with_flat_assigner_matches_float32(self): + d = 10 + n = 120 + nlist = 4 + encoded = encode_fp16(make_training_data(n, d)) + rounded = decode_fp16(encoded) + + float_quantizer = faiss.IndexFlatL2(d) + float_index = faiss.IndexIVFFlat(float_quantizer, d, nlist) + float_index.quantizer_trains_alone = 2 + float_index.cp = small_clustering_params(4) + float_index.train(rounded) + + half_quantizer = faiss.IndexFlatL2(d) + half_index = faiss.IndexIVFFlat(half_quantizer, d, nlist) + half_index.quantizer_trains_alone = 2 + half_index.cp = small_clustering_params(4) + half_index.train(encoded, numeric_type=faiss.Float16) + + np.testing.assert_array_equal( + half_quantizer.reconstruct_n(0, nlist), + float_quantizer.reconstruct_n(0, nlist), + ) + + def test_train_float16_rejected_by_dedup(self): + d = 4 + n = 16 + encoded = encode_fp16(make_training_data(n, d)) + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFFlatDedup(quantizer, d, 2) + with self.assertRaises(RuntimeError): + index.train(encoded, numeric_type=faiss.Float16) + + def test_train_ex_float32_preserves_deduplication(self): + d = 1 + n = 4 + nlist = 1 + x = np.array([[0.0], [0.0], [0.0], [10.0]], dtype=np.float32) + + train_ex_quantizer = faiss.IndexFlatL2(d) + train_ex = faiss.IndexIVFFlatDedup(train_ex_quantizer, d, nlist) + train_ex.cp = small_clustering_params(1) + train_ex.train_ex(n, faiss.swig_ptr(x), faiss.Float32) + + train_ex_centroid = train_ex_quantizer.reconstruct(0) + np.testing.assert_array_max_ulp( + train_ex_centroid, np.float32([5.0]), maxulp=4) + + +class TestClustering(unittest.TestCase): + def test_train_ex_float16_matches_float32_on_rounded_input(self): + n = 200 + k = 5 + # 16 exercises only the SIMD kernels, 13 and 37 also the scalar tails + for d in (13, 16, 37): + encoded = encode_fp16(make_training_data(n, d)) + rounded = decode_fp16(encoded) + cp = small_clustering_params(6) + + full = faiss.Clustering(d, k, cp) + full_index = faiss.IndexFlatL2(d) + full.train(rounded, full_index) + + half = faiss.Clustering(d, k, cp) + half_index = faiss.IndexFlatL2(d) + half.train_ex( + n, faiss.swig_ptr(encoded), faiss.Float16, half_index) + + np.testing.assert_array_equal( + faiss.vector_to_array(half.centroids), + faiss.vector_to_array(full.centroids), + err_msg=f"d={d}", + ) + full_objs = iteration_objs(full) + half_objs = iteration_objs(half) + self.assertEqual(half_objs, full_objs, f"d={d}") + + def test_train_ex_float16_weighted_matches_float32(self): + n = 150 + d = 20 + k = 4 + encoded = encode_fp16(make_training_data(n, d)) + rounded = decode_fp16(encoded) + weights = np.float32(0.25) + (np.arange(n) % 7).astype(np.float32) + cp = small_clustering_params(1) + + full = faiss.Clustering(d, k, cp) + full_index = faiss.IndexFlatL2(d) + full.train(rounded, full_index, weights) + + half = faiss.Clustering(d, k, cp) + half_index = faiss.IndexFlatL2(d) + half.train_ex( + n, + faiss.swig_ptr(encoded), + faiss.Float16, + half_index, + faiss.swig_ptr(weights), + ) + + full_centroids = faiss.vector_to_array(full.centroids) + half_centroids = faiss.vector_to_array(half.centroids) + np.testing.assert_allclose( + half_centroids, full_centroids, rtol=0, atol=1e-4) + + def test_train_ex_float16_subsampling_initializers_match_float32(self): + n = 100 + d = 12 + k = 4 + encoded = encode_fp16(make_training_data(n, d)) + rounded = decode_fp16(encoded) + + for method in ( + faiss.ClusteringInitMethod_KMEANS_PLUS_PLUS, + faiss.ClusteringInitMethod_AFK_MC2, + ): + cp = small_clustering_params(4) + cp.max_points_per_centroid = 8 + cp.init_method = method + cp.afkmc2_chain_length = 7 + + full = faiss.Clustering(d, k, cp) + full_index = faiss.IndexFlatL2(d) + full.train(rounded, full_index) + + half = faiss.Clustering(d, k, cp) + half_index = faiss.IndexFlatL2(d) + half.train_ex( + n, faiss.swig_ptr(encoded), faiss.Float16, half_index) + + np.testing.assert_array_equal( + faiss.vector_to_array(half.centroids), + faiss.vector_to_array(full.centroids), + err_msg=f"method={method}", + ) + + def test_train_ex_float16_rejects_non_finite_values(self): + n = 8 + d = 3 + k = 2 + max_finite = 0x7BFF # 65504 + for bad in (0x7E00, 0x7C00, 0xFC00): + encoded = encode_fp16(make_training_data(n, d)).view(np.uint16) + encoded.flat[0] = max_finite + encoded.flat[n * d - 1] = bad + clus = faiss.Clustering(d, k, small_clustering_params(2)) + index = faiss.IndexFlatL2(d) + with self.assertRaises(RuntimeError, msg=f"bits={bad}"): + clus.train_ex( + n, faiss.swig_ptr(encoded), faiss.Float16, index) + + encoded = encode_fp16(make_training_data(n, d)).view(np.uint16) + encoded.flat[0] = max_finite + clus = faiss.Clustering(d, k, small_clustering_params(2)) + index = faiss.IndexFlatL2(d) + clus.train_ex(n, faiss.swig_ptr(encoded), faiss.Float16, index) + + def test_train_ex_rejects_unsupported_numeric_type(self): + n = 8 + d = 4 + x = np.ones(n * d, dtype=np.uint8) + clus = faiss.Clustering(d, 2, small_clustering_params(2)) + index = faiss.IndexFlatL2(d) + with self.assertRaises(RuntimeError): + clus.train_ex(n, faiss.swig_ptr(x), faiss.UInt8, index) + + +class TestIndex(unittest.TestCase): + def test_search_ex_float16_default_matches_float32(self): + d = 12 + nb = 300 + nq = 40 + k = 5 + base = decode_fp16(encode_fp16(make_training_data(nb, d))) + queries = encode_fp16(make_queries(nq, d)) + rounded = decode_fp16(queries) + + # IndexIVFFlat does not override search_ex: exercises the default + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFFlat(quantizer, d, 4) + index.cp = small_clustering_params(3) + index.train(base) + index.add(base) + index.nprobe = 2 + + float_distances, float_labels = index.search(rounded, k) + half_distances, half_labels = index.search( + queries, k, numeric_type=faiss.Float16) + + np.testing.assert_array_equal(half_labels, float_labels) + np.testing.assert_array_equal(half_distances, float_distances) + with self.assertRaises(RuntimeError): + index.search_ex( + nq, + faiss.swig_ptr(queries), + faiss.UInt8, + k, + faiss.swig_ptr(half_distances), + faiss.swig_ptr(half_labels), + ) + + +class TestIndexFlat(unittest.TestCase): + def test_search_ex_float16_native_matches_float32(self): + nb = 500 + nq = 300 + with scoped_blas_tiles(64): # several query tiles per search + for metric in (faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT): + for d in (37, 64): + for k in (1, 5): + msg = f"metric={metric} d={d} k={k}" + base = make_training_data(nb, d) + queries = encode_fp16(make_queries(nq, d)) + rounded = decode_fp16(queries) + index = faiss.IndexFlat(d, metric) + index.add(base) + + fd, fi = index.search(rounded, k) + hd, hi = index.search( + queries, k, numeric_type=faiss.Float16) + np.testing.assert_array_equal(hi, fi, err_msg=msg) + tol = np.float32(1e-5) * np.maximum( + np.float32(1), np.abs(fd)) + err = np.abs( + hd.astype(np.float64) - fd.astype(np.float64)) + self.assertTrue(np.all(err <= tol), msg) + + def test_search_ex_float16_with_selector_matches_float32(self): + d = 48 + nb = 400 + nq = 50 + k = 3 + with scoped_blas_tiles(16): + base = make_training_data(nb, d) + queries = encode_fp16(make_queries(nq, d)) + rounded = decode_fp16(queries) + index = faiss.IndexFlatL2(d) + index.add(base) + + sel = faiss.IDSelectorRange(100, 250) + params = faiss.SearchParameters() + params.sel = sel + fd, fi = index.search(rounded, k, params=params) + hd, hi = index.search( + queries, k, params=params, numeric_type=faiss.Float16) + np.testing.assert_array_equal(hi, fi) + np.testing.assert_array_equal(hd, fd) + + def test_search_ex_float16_keeps_flat1d_search(self): + nb = 100 + nq = 20 + k = 4 + base = make_training_data(nb, 1) + queries = encode_fp16(make_queries(nq, 1)) + rounded = decode_fp16(queries) + index = faiss.IndexFlat1D() + index.add(base) + + fd, fi = index.search(rounded, k) + hd, hi = index.search(queries, k, numeric_type=faiss.Float16) + np.testing.assert_array_equal(hi, fi) + np.testing.assert_array_equal(hd, fd) # L1 distances from IndexFlat1D diff --git a/thirdparty/faiss/tests/test_ivf_rabitq_ssd.cpp b/thirdparty/faiss/tests/test_ivf_rabitq_ssd.cpp new file mode 100644 index 000000000..ad0ee6786 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivf_rabitq_ssd.cpp @@ -0,0 +1,252 @@ +/* + * 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. + */ + +// The tests that the Python bindings cannot run: fork() and DiskIOBackend. +// The other IndexIVFRaBitQSSD tests are in test_ivf_rabitq_ssd.py. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +using faiss::idx_t; +using faiss::IndexIVFRaBitQSSD; +using faiss::MetricType; + +namespace { + +/// a temporary file name, removed at destruction +struct TempFile { + std::string name; + + explicit TempFile(const char* suffix = "") { + char tmpl[] = "/tmp/faiss_rabitq_ssd_XXXXXX"; + int fd = mkstemp(tmpl); + EXPECT_GE(fd, 0); + close(fd); + unlink(tmpl); + name = std::string(tmpl) + suffix; + } + + ~TempFile() { + unlink(name.c_str()); + } + + const char* c_str() const { + return name.c_str(); + } +}; + +/// n vectors around ncenters Gaussian centers +std::vector make_data(size_t n, size_t d, size_t ncenters, int seed) { + std::mt19937 rng(seed); + std::normal_distribution normal; + std::vector centers(ncenters * d); + for (auto& v : centers) { + v = 2 * normal(rng); + } + std::vector x(n * d); + for (size_t i = 0; i < n; i++) { + const float* c = centers.data() + (i % ncenters) * d; + for (size_t j = 0; j < d; j++) { + x[i * d + j] = c[j] + normal(rng); + } + } + return x; +} + +struct Config { + size_t d = 128; + size_t mem_dim = 64; + int nb_bits = 5; + MetricType metric = faiss::METRIC_L2; + MetricType quantizer_metric = faiss::METRIC_L2; + bool use_hacc = true; + size_t nlist = 8; + size_t nb = 1000; +}; + +struct TestIndex { + TempFile file; + std::unique_ptr quantizer; + std::unique_ptr index; + std::vector xb; + + explicit TestIndex(const Config& cfg, int seed = 123) { + xb = make_data(cfg.nb, cfg.d, 3 * cfg.nlist, seed); + quantizer = + std::make_unique(cfg.d, cfg.quantizer_metric); + index = std::make_unique( + quantizer.get(), + cfg.d, + cfg.nlist, + cfg.mem_dim, + cfg.nb_bits, + cfg.metric); + index->attach_file(file.c_str()); + index->use_hacc = cfg.use_hacc; + index->train(cfg.nb, xb.data()); + index->add(cfg.nb, xb.data()); + } +}; + +/// Number of results of the second search that differ from the first: an id +/// missing from the same query of the first search, or a distance more than +/// tol away. The order of equal distances can differ between searches. +size_t n_different_results( + const std::vector& D1, + const std::vector& I1, + const std::vector& D2, + const std::vector& I2, + size_t nq, + size_t k, + float tol = 0) { + size_t n_diff = 0; + for (size_t q = 0; q < nq; q++) { + std::map dis; + for (size_t j = 0; j < k; j++) { + dis[I1[q * k + j]] = D1[q * k + j]; + } + for (size_t j = 0; j < k; j++) { + auto it = dis.find(I2[q * k + j]); + n_diff += it == dis.end() || + std::abs(it->second - D2[q * k + j]) > + tol * std::max(1.0f, std::abs(it->second)); + } + } + return n_diff; +} + +/// Exit status of a child process, -2 if it did not exit normally, or -1 if +/// it is still running after timeout_s seconds (it is then killed). +int wait_child(pid_t pid, int timeout_s) { + for (int i = 0; i < timeout_s * 10; i++) { + int wstatus = 0; + if (waitpid(pid, &wstatus, WNOHANG) == pid) { + return WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : -2; + } + usleep(100000); + } + kill(pid, SIGKILL); + waitpid(pid, nullptr, 0); + return -1; +} + +} // namespace + +/// The tests write their files to /tmp, which must support O_DIRECT. +class IVFRaBitQSSD : public ::testing::Test { + protected: + void SetUp() override { + TempFile file; + const int fd = open( + file.c_str(), O_CREAT | O_RDWR | O_DIRECT, S_IRUSR | S_IWUSR); + if (fd < 0) { + GTEST_SKIP() << "O_DIRECT not supported in /tmp"; + } + close(fd); + } +}; + +// A process forked after a search cannot use the libaio contexts that its +// parent keeps: it creates its own. +TEST_F(IVFRaBitQSSD, search_after_fork) { + Config cfg; + TestIndex ti(cfg); + const size_t nq = 5; + // with k = nb nothing is pruned + const idx_t k = cfg.nb; + std::vector xq = make_data(nq, cfg.d, 5, 789); + ti.index->nprobe = 4; + std::vector D_ref(nq * k), D(nq * k); + std::vector I_ref(nq * k), I(nq * k); + ti.index->search(nq, xq.data(), k, D_ref.data(), I_ref.data()); + + pid_t pid = fork(); + ASSERT_GE(pid, 0); + if (pid == 0) { + // single-threaded: OpenMP parallel regions can hang after fork() + omp_set_num_threads(1); + int status = 2; + try { + ti.index->search(nq, xq.data(), k, D.data(), I.data()); + if (n_different_results(D_ref, I_ref, D, I, nq, k) == 0) { + status = 0; + } + } catch (...) { + status = 3; + } + _exit(status); + } + // 2: different results, 3: the search threw + EXPECT_EQ(wait_child(pid, 30), 0); + + // a child that destroys the index drops the contexts of the parent + pid = fork(); + ASSERT_GE(pid, 0); + if (pid == 0) { + ti.index.reset(); + _exit(0); + } + // -1: the child hangs + EXPECT_EQ(wait_child(pid, 30), 0); + + ti.index->search(nq, xq.data(), k, D.data(), I.data()); + EXPECT_EQ(n_different_results(D_ref, I_ref, D, I, nq, k), 0); +} + +// reap with min_nr waits for a request in flight instead of returning +// nothing. The request is a poll of an empty pipe rather than a read, as a +// read can complete inside io_submit: the poll completes only when another +// thread writes to the pipe, 100 ms after reap is called. +TEST(DiskIOBackend, reap_waits) { + int fds[2]; + ASSERT_EQ(pipe(fds), 0); + faiss::DiskIOBackend io(4); + void* user_data = nullptr; + long res = 0; + // nothing in flight: min_nr is capped and reap does not wait + EXPECT_EQ(io.reap(&user_data, &res, 4, 1), 0); + + iocb cb; + io_prep_poll(&cb, fds[0], POLLIN); + int tag = 0; + cb.data = &tag; + iocb* cbs[] = {&cb}; + ASSERT_EQ(io_submit(io.ctx, 1, cbs), 1); + io.n_in_flight++; + std::thread writer([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + EXPECT_EQ(write(fds[1], "x", 1), 1); + }); + EXPECT_EQ(io.reap(&user_data, &res, 4, 1), 1); + EXPECT_EQ(user_data, &tag); + EXPECT_TRUE(res & POLLIN); + writer.join(); + close(fds[0]); + close(fds[1]); +} diff --git a/thirdparty/faiss/tests/test_ivf_rabitq_ssd.py b/thirdparty/faiss/tests/test_ivf_rabitq_ssd.py new file mode 100644 index 000000000..3c849ba64 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivf_rabitq_ssd.py @@ -0,0 +1,1049 @@ +# 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 gc +import os +import shutil +import tempfile +import threading +import unittest + +import numpy as np +import faiss +from faiss.contrib import datasets + +from common_faiss_tests import for_all_simd_levels, NoneSIMDLevel + + +def make_index(d, nlist, mem_dim, nb_bits, filename, + metric=faiss.METRIC_L2): + """Rotation to a multiple of 64 dimensions, then IndexIVFRaBitQSSD.""" + rot = faiss.HadamardRotation(d, 12345, False) + if metric == faiss.METRIC_L2: + quantizer = faiss.IndexFlatL2(rot.d_out) + else: + quantizer = faiss.IndexFlatIP(rot.d_out) + index_ivf = faiss.IndexIVFRaBitQSSD( + quantizer, rot.d_out, nlist, mem_dim, nb_bits, metric) + index_ivf.attach_file(filename) + return faiss.IndexPreTransform(rot, index_ivf) + + +def recall_at_1(I, gt): + return (I[:, 0] == gt[:, 0]).mean() + + +def make_data(n, d, ncenters, seed): + """n vectors around ncenters Gaussian centers""" + rs = np.random.RandomState(seed) + centers = 2 * rs.randn(ncenters, d) + return (centers[np.arange(n) % ncenters] + rs.randn(n, d)).astype( + "float32") + + +def make_queries(xb, nq, seed): + """queries near some of the vectors of xb""" + rs = np.random.RandomState(seed) + xq = xb[np.arange(nq) * 37 % len(xb)] + return (xq + 0.3 * rs.randn(*xq.shape)).astype("float32") + + +def same_results(D1, I1, D2, I2, rtol=0): + """The second search finds the ids of the first, with the same distances + up to rtol. The order of equal distances can differ between searches.""" + for q in range(len(I1)): + dis = dict(zip(I1[q], D1[q])) + for i, v in zip(I2[q], D2[q]): + if i not in dis or abs(dis[i] - v) > rtol * max(1, abs(dis[i])): + return False + return True + + +def list_ids(il, list_no): + """the ids of a list, read from the file""" + n = il.list_size(list_no) + if n == 0: + return np.zeros(0, dtype="int64") + ptr = il.get_ids(list_no) + ids = faiss.rev_swig_ptr(ptr, n).copy() + il.release_ids(list_no, ptr) + return ids + + +def count_aio_contexts(): + """libaio contexts of the process: each maps its ring as "[aio]" """ + with open("/proc/self/maps") as f: + return sum("[aio]" in line for line in f) + + +def lut_step(q, mem_dim, use_hacc): + """Step of the look-up table of the in-memory scan: all the entries, the + sums of q over subsets of 4 consecutive dimensions, are quantized with one + offset and one step.""" + subsets = (np.arange(16)[:, None] >> np.arange(4)) & 1 + v = q[:mem_dim].reshape(-1, 4) @ subsets.T + return (v.max() - v.min()) / (65535 if use_hacc else 255) + + +def reference_estimates(index, xq, xb, assign, use_hacc): + """Reference estimates of the distances (similarities for IP) between the + queries and the database vectors, computed in double from the + RaBitQuantizer codes: + ~ |r|^2 / + Also returns bounds on their difference with the index's float + computation, which quantizes over [0, mem_dim) with the look-up + table. Both have shape (nq, nb).""" + d, mem_dim = index.d, index.mem_dim + nb_bits = index.rabitq.nb_bits + ex_bits = nb_bits - 1 + centroids = index.quantizer.reconstruct_n(0, index.nlist) + scales = faiss.vector_to_array(index.centroid_scales) + if scales.size > 0: + centroids *= scales[:, None] + rq = faiss.RaBitQuantizer(d, index.metric_type, nb_bits) + # the sign bits, SignBitFactorsWithError, then the extra bits + ex_offset = d // 8 + 12 + assert rq.code_size == ex_offset + d * ex_bits // 8 + 8 + codes = np.empty((len(xb), rq.code_size), dtype="uint8") + for l in np.unique(assign): + rows = np.where(assign == l)[0] + x = np.ascontiguousarray(xb[rows]) + out = np.empty((len(rows), rq.code_size), dtype="uint8") + rq.compute_codes_core( + faiss.swig_ptr(x), faiss.swig_ptr(out), len(rows), + faiss.swig_ptr(centroids[l])) + codes[rows] = out + signs = np.unpackbits(codes[:, :d // 8], axis=1, bitorder="little") + ex = np.unpackbits( + codes[:, ex_offset:ex_offset + d * ex_bits // 8], axis=1, + bitorder="little") + ex = ex.reshape(len(xb), d, ex_bits) @ (1 << np.arange(ex_bits)) + xbq = signs * float(1 << ex_bits) + ex - ((1 << ex_bits) - 0.5) + c = centroids[assign].astype(float) + r = xb.astype(float) - c + ip_xb_r = (xbq * r).sum(1) + r2 = (r * r).sum(1) + ip_r_c = (r * c).sum(1) + xb_abs_max = np.abs(xbq).max(1) + nonzero = ip_xb_r != 0 + ip_xb_r_safe = np.where(nonzero, ip_xb_r, 1) + scale = np.where(nonzero, r2 / np.abs(ip_xb_r_safe), 0) + is_l2 = index.metric_type == faiss.METRIC_L2 + k = 2 if is_l2 else 1 + est = np.empty((len(xq), len(xb))) + tol = np.empty((len(xq), len(xb))) + for i, q in enumerate(xq.astype(float)): + qc = q - c + ip_xb_qc = (xbq * qc).sum(1) + ip_q_c = c @ q + qc2 = (qc * qc).sum(1) + ip_qc_r = np.where(nonzero, r2 * ip_xb_qc / ip_xb_r_safe, 0) + # each look-up table entry is rounded to the nearest step + lut_error = mem_dim // 4 * lut_step(q, mem_dim, use_hacc) / 2 + # float rounding: relative to the magnitude of the terms + magnitude = ( + qc2 + r2 + np.abs(ip_qc_r) + np.abs(ip_q_c) + np.abs(ip_r_c) + + scale * xb_abs_max * np.sqrt(d) + * np.sqrt(qc2 + ip_q_c ** 2 / (qc2 + 1e-30) + 1)) + tol[i] = k * scale * (1 << ex_bits) * lut_error + 2e-4 * magnitude + est[i] = qc2 + r2 - 2 * ip_qc_r if is_l2 else ip_q_c + ip_r_c + ip_qc_r + return est, tol + + +@unittest.skipUnless( + hasattr(faiss, "IndexIVFRaBitQSSD"), "IndexIVFRaBitQSSD not built") +class SSDTestCase(unittest.TestCase): + + def setUp(self): + super().setUp() + self.tmpdir = tempfile.TemporaryDirectory() + try: + fd = os.open(self.path("probe"), + os.O_CREAT | os.O_RDWR | os.O_DIRECT) + except OSError: + self.tmpdir.cleanup() + self.skipTest("O_DIRECT not supported in " + self.tmpdir.name) + os.close(fd) + + def tearDown(self): + self.tmpdir.cleanup() + super().tearDown() + + def path(self, name): + return os.path.join(self.tmpdir.name, name) + + def build(self, ds, nlist, mem_dim, nb_bits, metric=faiss.METRIC_L2): + index = make_index(ds.d, nlist, mem_dim, nb_bits, + self.path("index.ssd"), metric) + index.train(ds.get_train()) + index.add(ds.get_database()) + return index + + def build_flat(self, d=128, mem_dim=64, nb_bits=5, metric=faiss.METRIC_L2, + quantizer_metric=faiss.METRIC_L2, use_hacc=True, nlist=8, + nb=1000, seed=123, name="flat.ssd"): + """An index without rotation on clustered data, and its vectors.""" + xb = make_data(nb, d, 3 * nlist, seed) + index = faiss.IndexIVFRaBitQSSD( + faiss.IndexFlat(d, quantizer_metric), d, nlist, mem_dim, nb_bits, + metric) + index.attach_file(self.path(name)) + index.use_hacc = use_hacc + index.train(xb) + index.add(xb) + return index, xb + + +@for_all_simd_levels +class TestIVFRaBitQSSDKernels(SSDTestCase): + """The tests whose results depend on the SIMD kernels.""" + + def test_recall(self): + # same accuracy as IndexIVFRaBitQ with unquantized queries + ds = datasets.SyntheticDataset(100, 2000, 5000, 50) + Dref, Iref = faiss.knn(ds.get_queries(), ds.get_database(), 10) + for nb_bits in 2, 4, 9: + with self.subTest(nb_bits=nb_bits): + index = self.build(ds, 32, 64, nb_bits) + index_ivf = faiss.downcast_index( + faiss.extract_index_ivf(index)) + self.assertIsInstance(index_ivf, faiss.IndexIVFRaBitQSSD) + index_ivf.nprobe = 16 + D, I = index.search(ds.get_queries(), 10) + + rot = faiss.HadamardRotation(ds.d, 12345, False) + index_rq = faiss.IndexIVFRaBitQ( + faiss.IndexFlatL2(rot.d_out), rot.d_out, 32, + faiss.METRIC_L2, True, nb_bits) + index_rq.qb = 0 + index_rq.nprobe = 16 + index_ref = faiss.IndexPreTransform(rot, index_rq) + index_ref.train(ds.get_train()) + index_ref.add(ds.get_database()) + _, I_rq = index_ref.search(ds.get_queries(), 10) + + self.assertGreaterEqual( + recall_at_1(I, Iref), recall_at_1(I_rq, Iref) - 0.02) + if nb_bits == 9: + self.assertGreaterEqual(recall_at_1(I, Iref), 0.97) + np.testing.assert_allclose(D[:, 0], Dref[:, 0], rtol=0.01) + + def test_inner_product(self): + ds = datasets.SyntheticDataset(64, 2000, 5000, 50, metric="IP") + Dref, Iref = faiss.knn( + ds.get_queries(), ds.get_database(), 10, + faiss.METRIC_INNER_PRODUCT) + index = self.build(ds, 32, 64, 9, faiss.METRIC_INNER_PRODUCT) + faiss.extract_index_ivf(index).nprobe = 32 + D, I = index.search(ds.get_queries(), 10) + self.assertGreaterEqual(recall_at_1(I, Iref), 0.95) + # similarities, in decreasing order + self.assertTrue(np.all(D[:, :-1] >= D[:, 1:])) + np.testing.assert_allclose(D[:, 0], Dref[:, 0], rtol=0.01) + + def check_estimates(self, use_hacc=True, **kwargs): + """Search with k = nb: no vector is pruned, all are re-ranked, and + their distances must match the reference estimates.""" + index, xb = self.build_flat(use_hacc=use_hacc, **kwargs) + nb, nlist = index.ntotal, index.nlist + is_ip = index.metric_type == faiss.METRIC_INNER_PRODUCT + # only inner-product indexes have scales + self.assertEqual(index.centroid_scales.size(), nlist if is_ip else 0) + assign = index.quantizer.assign(xb, 1).ravel() + xq = make_data(4, index.d, 5, 456) + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=nlist, use_hacc=use_hacc) + D, I = index.search(xq, nb, params=params) + est, tol = reference_estimates(index, xq, xb, assign, use_hacc) + for q in range(len(xq)): + self.assertEqual(sorted(I[q]), list(range(nb))) + order = D[q, :-1] >= D[q, 1:] if is_ip else D[q, :-1] <= D[q, 1:] + self.assertTrue(np.all(order)) + bad = np.abs(D[q] - est[q, I[q]]) > tol[q, I[q]] + if bad.any(): + j = np.argmax(bad) + self.fail( + f"{bad.sum()} bad estimates, query {q} id {I[q, j]}: " + f"{D[q, j]} != {est[q, I[q, j]]} " + f"(tolerance {tol[q, I[q, j]]})") + + def test_estimates(self): + L2, IP = faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT + configs = [{"nb_bits": nb_bits, "mem_dim": mem_dim} + for nb_bits in (2, 5, 9) for mem_dim in (64, 128)] + configs += [{"metric": IP, "quantizer_metric": IP, "nb_bits": nb_bits, + "mem_dim": mem_dim} + for nb_bits in (2, 4, 9) for mem_dim in (64, 128)] + configs += [ + # the coarse distances come from a quantizer with the other + # metric + {"quantizer_metric": IP}, + {"metric": IP, "quantizer_metric": L2}, + # 8-bit look-up tables + {"use_hacc": False}, + {"metric": IP, "quantizer_metric": IP, "use_hacc": False}, + ] + # several 8-bit scan segments, records larger than a page + shapes = {"nb": 300, "nlist": 4} + configs += [ + {"d": 1536, "mem_dim": 1280, "nb_bits": 3, **shapes}, + {"d": 1536, "mem_dim": 1280, "nb_bits": 3, "use_hacc": False, + **shapes}, + # 512 sub-quantizers: their 8-bit sums exceed 2^16 unless split + {"d": 2048, "mem_dim": 2048, "nb_bits": 2, "use_hacc": False, + **shapes}, + {"d": 4096, "mem_dim": 256, "nb_bits": 9, **shapes}, + {"d": 192, "mem_dim": 192, "nb_bits": 2, **shapes}, + ] + for cfg in configs: + with self.subTest(**cfg): + self.check_estimates(**cfg) + + def test_same_results_as_none_level(self): + ds = datasets.SyntheticDataset(100, 2000, 3000, 30) + index = self.build(ds, 16, 64, 5) + faiss.extract_index_ivf(index).nprobe = 8 + # with k = nb nothing is pruned, so the order in which the reads + # complete does not matter: compare the distances of each vector + k = ds.nb + D, I = index.search(ds.get_queries(), k) + with NoneSIMDLevel(): + D2, I2 = index.search(ds.get_queries(), k) + for q in range(ds.nq): + n = (I[q] >= 0).sum() + self.assertEqual(n, (I2[q] >= 0).sum()) + dis = dict(zip(I[q, :n], D[q, :n])) + dis2 = dict(zip(I2[q, :n], D2[q, :n])) + self.assertEqual(dis.keys(), dis2.keys()) + ids = list(dis) + np.testing.assert_allclose( + [dis[i] for i in ids], [dis2[i] for i in ids], + rtol=1e-5, atol=1e-4) + + +class TestIVFRaBitQSSD(SSDTestCase): + + def test_layout(self): + il = faiss.RaBitQSSDInvertedLists(4, 192, 64, 3, self.path("a.ssd")) + self.assertEqual(il.batch_bytes, 32 * 64 // 8 + 32 * 3 * 4) + # 16 sign bytes, 72 bytes of extra bits, 2 factors, id + self.assertEqual(il.record_size, 16 + 72 + 8 + 8) + self.assertEqual(il.page_size, 4096) + self.assertEqual(il.records_per_page, 4096 // 104) + + # a record larger than a page + il = faiss.RaBitQSSDInvertedLists(4, 4096, 2048, 8, self.path("b.ssd")) + self.assertEqual(il.record_size, 256 + 4096 + 8 + 8) + self.assertEqual(il.page_size, 8192) + self.assertEqual(il.records_per_page, 1) + + # d must be a multiple of 64, mem_dim a multiple of 64 in [64, d], + # and ex_bits in [1, 8] + for d, mem_dim, ex_bits in [ + (100, 64, 1), (120, 64, 1), (128, 0, 1), (128, 32, 1), + (128, 96, 1), (128, 192, 1), (128, 64, 0), (128, 64, 9)]: + self.assertRaises( + RuntimeError, faiss.RaBitQSSDInvertedLists, 4, d, mem_dim, + ex_bits, self.path("c.ssd")) + + def test_bound_decides_reads(self): + # The in-memory lower bound decides whether a page is read. A list + # holds one full page, then its farthest vector from the centroid + # alone on a second page. With one read in flight and k = 1, the + # second page is considered after the first is re-ranked, and is + # read iff the lower bound of that vector does not exceed the best + # distance on the first page. With inner product, the center of the + # list is 7 times the centroid of the quantizer. + d, mem_dim, nb_bits = 128, 64, 5 + stats = faiss.cvar.indexIVFRaBitQSSD_stats + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + is_l2 = metric == faiss.METRIC_L2 + scale = np.float32(1 if is_l2 else 7) + centroid = np.full(d, np.float32(0.5) / scale, dtype="float32") + quantizer = faiss.IndexFlat(d, metric) + quantizer.add(centroid[None]) + index = faiss.IndexIVFRaBitQSSD( + quantizer, d, 1, mem_dim, nb_bits, metric) + index.attach_file(self.path(f"bound{metric}.ssd")) + if not is_l2: + faiss.copy_array_to_vector( + np.array([scale], dtype="float32"), index.centroid_scales) + index.is_trained = True + center = centroid * scale + il = index.get_ssd_invlists() + nb = il.records_per_page + 1 + xb = make_data(nb, d, 1, 321) + index.add(xb) + self.assertEqual(il.list_pages(0), 2) + + # the vector alone on page 1 is the farthest from the centroid + dis = ((xb - center) ** 2).sum(1) if is_l2 else -(xb @ center) + last = int(np.argmax(dis)) + self.assertEqual(il.get_single_id(0, nb - 1), last) + others = np.delete(np.arange(nb), last) + + # the in-memory lower bound of the last vector uses its sign bits + rq = faiss.RaBitQuantizer(d, metric, nb_bits) + code = np.empty(rq.code_size, dtype="uint8") + o = xb[last].copy() + rq.compute_codes_core( + faiss.swig_ptr(o), faiss.swig_ptr(code), 1, + faiss.swig_ptr(center)) + x1 = np.unpackbits(code[:d // 8], bitorder="little") - 0.5 + c = center.astype(float) + r = o.astype(float) - c + k = 2 if is_l2 else 1 + # the search minimizes - for IP + sign = 1 if is_l2 else -1 + + rs = np.random.RandomState(5) + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=1, qd_per_thread=1) + n_read = n_pruned = 0 + for _ in range(200): + q = (0.5 + 0.8 * rs.randn(1, d)).astype("float32") + # best distance on page 0 + est, tol = reference_estimates( + index, q, xb, np.zeros(nb, dtype="int64"), True) + j = others[np.argmin(sign * est[0, others])] + distk = sign * est[0, j] + qd = q[0].astype(float) + qc = qd - c + ip_x1_qc = x1[:mem_dim] @ qc[:mem_dim] + ip_qc_r = (r @ r) * (d / mem_dim) * ip_x1_qc / (x1 @ r) + if is_l2: + est_last = qc @ qc + r @ r - k * ip_qc_r + else: + est_last = -(qd @ c + r @ c + ip_qc_r) + low = est_last - k * 1.9 * np.sqrt( + (r @ r) * (qc @ qc) / mem_dim) + # margin for the look-up table and float rounding + if abs(low - distk) < 2 * tol[0, j] + 1e-3 * abs(distk): + continue + expect_read = low <= distk + stats.reset() + index.search(q, 1, params=params) + self.assertEqual( + stats.n_pages_read, 2 if expect_read else 1, + f"metric {metric} low {low} distk {distk}") + if expect_read: + n_read += 1 + else: + n_pruned += 1 + # both cases occur + self.assertGreater(n_read, 5) + self.assertGreater(n_pruned, 5) + + def test_pruning(self): + # pruning keeps the results of an exhaustive re-ranking and reads + # few pages + stats = faiss.cvar.indexIVFRaBitQSSD_stats + nq, k = 50, 10 + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + for use_hacc in False, True: + with self.subTest(metric=metric, use_hacc=use_hacc): + index, xb = self.build_flat( + nb_bits=9, metric=metric, quantizer_metric=metric, + nb=5000, nlist=16, use_hacc=use_hacc) + xq = make_queries(xb, nq, 789) + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=16, use_hacc=use_hacc) + # exhaustive: with k = nb nothing is pruned + _, I_all = index.search(xq, index.ntotal, params=params) + il = index.get_ssd_invlists() + total_pages = sum(il.list_pages(l) for l in range(16)) + stats.reset() + _, I = index.search(xq, k, params=params) + # the bound holds with high probability: the same + # results, from a fraction of the pages + recall = np.mean([ + len(set(I[q]) & set(I_all[q, :k])) / k + for q in range(nq)]) + self.assertGreaterEqual(recall, 0.99) + self.assertLess(stats.n_pages_read, nq * total_pages / 4) + self.assertGreater(stats.n_pages_read, 0) + + def test_retrain_centroid_norms(self): + index, _ = self.build_flat( + quantizer_metric=faiss.METRIC_INNER_PRODUCT, name="a.ssd") + fresh, xb = self.build_flat( + quantizer_metric=faiss.METRIC_INNER_PRODUCT, seed=456, + name="b.ssd") + index.reset() + self.assertEqual(index.centroid_norms.size(), 0) + index.quantizer.reset() + index.train(xb) + np.testing.assert_array_equal( + faiss.vector_to_array(index.centroid_norms), + faiss.vector_to_array(fresh.centroid_norms)) + index.add(xb) + xq = make_queries(xb, 3, 789) + index.nprobe = fresh.nprobe = 8 + D, I = index.search(xq, len(xb)) + Dref, Iref = fresh.search(xq, len(xb)) + np.testing.assert_array_equal(D, Dref) + self.assertTrue(same_results(Dref, Iref, D, I)) + + def test_ip_list_scales(self): + # train() of an inner-product index: needed even with a filled + # quantizer, sets centroid_scales and keeps the centroids + d, nlist, nb = 128, 4, 2000 + xb = make_data(nb, d, 3, 77) + # centroids of norm 2: a vector of each of the 3 clusters, and the + # opposite of the first one, which no vector is assigned to + centroids = xb[:nlist].copy() + centroids[3] = -centroids[0] + faiss.normalize_L2(centroids) + centroids *= 2 + quantizer = faiss.IndexFlatIP(d) + quantizer.add(centroids) + index = faiss.IndexIVFRaBitQSSD( + quantizer, d, nlist, 64, 5, faiss.METRIC_INNER_PRODUCT) + index.attach_file(self.path("index.ssd")) + self.assertFalse(index.is_trained) + self.assertRaises(RuntimeError, index.add, xb) + + assign = quantizer.assign(xb, 1).ravel() + index.train(xb) + self.assertTrue(index.is_trained) + np.testing.assert_array_equal( + quantizer.reconstruct_n(0, nlist), centroids) + # scale = / |centroid|^2 + counts = np.bincount(assign, minlength=nlist) + self.assertTrue(np.all(counts[:3] > 0)) + self.assertEqual(counts[3], 0) + ref = np.array([ + (xb[assign == l].astype(float) @ centroids[l]).mean() / 4 + for l in range(3)]) + scales = faiss.vector_to_array(index.centroid_scales) + np.testing.assert_allclose(scales[:3], ref, rtol=1e-4) + # a list without training vectors gets the mean scale of the others + np.testing.assert_allclose(scales[3], ref.mean(), rtol=1e-4) + + # the scales are saved with the index, and kept by train() on a + # non-empty index and by reset() + index.add(xb) + fname = self.path("index.faiss") + faiss.write_index(index, fname) + index2 = faiss.read_index(fname) + self.assertTrue(index2.is_trained) + np.testing.assert_array_equal( + faiss.vector_to_array(index2.centroid_scales), scales) + index.train(xb[:nb // 2]) + np.testing.assert_array_equal( + faiss.vector_to_array(index.centroid_scales), scales) + index.reset() + np.testing.assert_array_equal( + faiss.vector_to_array(index.centroid_scales), scales) + + def test_inner_product_unnormalized(self): + # Vectors of norm ~500. The centroids of spherical k-means have + # norm 1: with the scales of train(), the codes are relative to the + # centroids scaled to the means of the lists. + d, nlist, nb, nq = 256, 4, 12000, 20 + rs = np.random.RandomState(123) + center = 32 * rs.randn(d).astype("float32") + xb = center + rs.randn(nb, d).astype("float32") + xq = xb[np.arange(nq) * 37 % nb] + xq = xq + 0.3 * rs.randn(nq, d).astype("float32") + _, Iref = faiss.knn(xq, xb, 10, faiss.METRIC_INNER_PRODUCT) + + index = make_index(d, nlist, d, 9, self.path("index.ssd"), + faiss.METRIC_INNER_PRODUCT) + index.train(xb) + index.add(xb) + index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index)) + index_ivf.nprobe = nlist + scales = faiss.vector_to_array(index_ivf.centroid_scales) + self.assertEqual(scales.size, nlist) + stats = faiss.cvar.indexIVFRaBitQSSD_stats + stats.reset() + _, I = index.search(xq, 10) + self.assertGreaterEqual(recall_at_1(I, Iref), 0.95) + pages = stats.n_pages_read + + # the same index centered on the norm-1 centroids reads more pages + unit = make_index(d, nlist, d, 9, self.path("unit.ssd"), + faiss.METRIC_INNER_PRODUCT) + unit.train(xb) + unit_ivf = faiss.downcast_index(faiss.extract_index_ivf(unit)) + faiss.copy_array_to_vector( + np.ones(nlist, dtype="float32"), unit_ivf.centroid_scales) + unit.add(xb) + unit_ivf.nprobe = nlist + stats.reset() + unit.search(xq, 10) + self.assertLess(pages * 3, stats.n_pages_read) + + # A quantizer filled by the caller: the index is not trained before + # train(), which keeps the centroids and sets the same scales. + rot = faiss.downcast_VectorTransform(index.chain.at(0)) + xr = rot.apply(xb) + centroids = index_ivf.quantizer.reconstruct_n(0, nlist) + quantizer = faiss.IndexFlatIP(d) + quantizer.add(centroids) + index2 = faiss.IndexIVFRaBitQSSD( + quantizer, d, nlist, d, 9, faiss.METRIC_INNER_PRODUCT) + index2.attach_file(self.path("index2.ssd")) + self.assertFalse(index2.is_trained) + self.assertRaises(RuntimeError, index2.add, xr[:10]) + index2.train(xr) + self.assertTrue(index2.is_trained) + np.testing.assert_array_equal( + quantizer.reconstruct_n(0, nlist), centroids) + np.testing.assert_allclose( + faiss.vector_to_array(index2.centroid_scales), scales, rtol=1e-5) + + # With an L2 quantizer on the same centroids, is not derived + # from the coarse distance: the same distances. With k = nb nothing + # is pruned. + quantizer_l2 = faiss.IndexFlatL2(d) + quantizer_l2.add(centroids) + index_l2 = faiss.IndexIVFRaBitQSSD( + quantizer_l2, d, nlist, d, 9, faiss.METRIC_INNER_PRODUCT) + index_l2.attach_file(self.path("index_l2.ssd")) + faiss.copy_array_to_vector(scales, index_l2.centroid_scales) + index_l2.is_trained = True + assign = index_ivf.quantizer.assign(xr, 1).ravel() + index_l2.add_core( + nb, faiss.swig_ptr(xr), None, faiss.swig_ptr(assign)) + index_l2.nprobe = nlist + xqr = rot.apply(xq[:3]) + D1, I1 = index_ivf.search(xqr, nb) + D2, I2 = index_l2.search(xqr, nb) + self.assertTrue(same_results(D1, I1, D2, I2, 1e-5)) + + def test_recall_large_d(self): + # d = 768 with the sign bits of 256 dimensions in memory + rs = np.random.RandomState(7) + d, nb, nq = 768, 4000, 20 + xb = rs.randn(nb, d).astype("float32") + 2 * rs.randn(d).astype( + "float32") + xq = xb[:nq] + 0.1 * rs.randn(nq, d).astype("float32") + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + with self.subTest(metric=metric): + _, Iref = faiss.knn(xq, xb, 1, metric) + index = make_index(d, 8, 256, 9, + self.path("large_d.ssd"), metric) + index.train(xb) + index.add(xb) + faiss.extract_index_ivf(index).nprobe = 8 + _, I = index.search(xq, 10) + self.assertGreaterEqual(recall_at_1(I, Iref), 0.95) + + def test_hnsw_quantizer(self): + xb = make_data(3000, 128, 60, 123) + index = faiss.IndexIVFRaBitQSSD( + faiss.IndexHNSWFlat(128, 16), 128, 32, 64, 5) + index.attach_file(self.path("index.ssd")) + index.train(xb) + index.add(xb) + index.nprobe = 8 + _, I = index.search(xb[:20], 1) + self.assertGreaterEqual((I[:, 0] == np.arange(20)).sum(), 18) + + def test_fewer_results_than_k(self): + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + with self.subTest(metric=metric): + index, _ = self.build_flat( + metric=metric, quantizer_metric=metric, nb=50, nlist=4) + index.nprobe = 4 + D, I = index.search(make_data(1, 128, 1, 456), 80) + self.assertTrue(np.all(I[0, :50] >= 0)) + np.testing.assert_array_equal(I[0, 50:], -1) + finfo = np.finfo("float32") + empty = finfo.max if metric == faiss.METRIC_L2 else finfo.min + np.testing.assert_array_equal(D[0, 50:], empty) + + def test_incremental_add(self): + # adding in several batches gives the same distances as a single add + index, xb = self.build_flat(name="a.ssd") + index2 = faiss.IndexIVFRaBitQSSD(faiss.IndexFlatL2(128), 128, 8, 64, 5) + index2.attach_file(self.path("b.ssd")) + index2.train(xb) + for i0 in range(0, len(xb), 70): + index2.add(xb[i0:i0 + 70]) + self.assertEqual(index2.ntotal, len(xb)) + # several extents: consecutive pages of a list not adjacent in the + # file + il = index2.get_ssd_invlists() + self.assertTrue(any( + il.page_offset(l, p + 1) != il.page_offset(l, p) + il.page_size + for l in range(il.nlist) for p in range(il.list_pages(l) - 1))) + xq = make_data(1, 128, 1, 456) + index.nprobe = index2.nprobe = 8 + D1, I1 = index.search(xq, len(xb)) + D2, I2 = index2.search(xq, len(xb)) + self.assertTrue(same_results(D1, I1, D2, I2)) + + index.reset() + self.assertEqual(index.ntotal, 0) + self.assertEqual(index.get_ssd_invlists().total_pages, 0) + index.add_with_ids(xb, np.arange(1000, 1000 + len(xb))) + _, I = index.search(xb[7:8], 1) + self.assertEqual(I[0, 0], 1007) + + def test_search_matches_preassigned(self): + # search() runs the coarse quantizer in the search threads: the same + # results as the coarse quantizer on all the queries, then + # search_preassigned + for metric in faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT: + with self.subTest(metric=metric): + index, xb = self.build_flat( + metric=metric, quantizer_metric=metric) + # the coarse distances of a batch of queries can come from + # BLAS, those of one query do not: they can differ in the + # last bits + nq = 30 + xq = make_queries(xb, nq, 789) + index.nprobe = 8 + ivf_stats = faiss.cvar.indexIVF_stats + ivf_stats.reset() + # with k = nb nothing is pruned + D, I = index.search(xq, len(xb)) + self.assertEqual(ivf_stats.nq, nq) + self.assertEqual(ivf_stats.nlist, nq * 8) + Dq, Iq = index.quantizer.search(xq, 8) + D2, I2 = index.search_preassigned(xq, len(xb), Iq, Dq) + self.assertTrue(same_results(D, I, D2, I2, 1e-5)) + + def test_io(self): + ds = datasets.SyntheticDataset(100, 2000, 3000, 30) + index = self.build(ds, 16, 64, 5) + index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index)) + index_ivf.nprobe = 8 + index_ivf.drain_alpha = 0.8 + index_ivf.qd_per_thread = 8 + # the reads complete in an order that varies between runs, which + # can change what is pruned: with k = nb nothing is pruned + k = ds.nb + D, I = index.search(ds.get_queries(), k) + + fname = self.path("index.faiss") + faiss.write_index(index, fname) + for io_flags in faiss.IO_FLAG_SKIP_IVF_DATA, faiss.IO_FLAG_MMAP: + self.assertRaises(RuntimeError, faiss.read_index, fname, io_flags) + for io_flags in 0, faiss.IO_FLAG_READ_ONLY: + index2 = faiss.read_index(fname, io_flags) + index_ivf2 = faiss.downcast_index(faiss.extract_index_ivf(index2)) + self.assertIsInstance(index_ivf2, faiss.IndexIVFRaBitQSSD) + self.assertIsInstance( + faiss.downcast_InvertedLists(index_ivf2.invlists), + faiss.RaBitQSSDInvertedLists) + self.assertEqual(index_ivf2.nprobe, 8) + self.assertAlmostEqual(index_ivf2.drain_alpha, 0.8, places=6) + self.assertEqual(index_ivf2.qd_per_thread, 8) + D2, I2 = index2.search(ds.get_queries(), k) + np.testing.assert_array_equal(D, D2) + # equal distances can come out in either order + self.assertTrue(same_results(D, I, D2, I2)) + if io_flags == faiss.IO_FLAG_READ_ONLY: + # rejected before changing the lists, not by the descriptor + for method, args in [(index2.add, (ds.get_database()[:10],)), + (index2.reset, ())]: + self.assertRaisesRegex( + RuntimeError, "opened read-only", method, *args) + self.assertEqual(index2.ntotal, ds.nb) + D2, _ = index2.search(ds.get_queries(), k) + np.testing.assert_array_equal(D, D2) + del index2, index_ivf2 + + # IO_FLAG_ONDISK_SAME_DIR: the data file is the one next to the + # index file. It is moved, so that no file is left at the stored + # path; the open descriptor of index follows it. + copy_dir = self.path("copy") + os.mkdir(copy_dir) + shutil.copyfile(self.path("index.faiss"), + os.path.join(copy_dir, "index.faiss")) + os.rename(self.path("index.ssd"), os.path.join(copy_dir, "index.ssd")) + index3 = faiss.read_index( + os.path.join(copy_dir, "index.faiss"), + faiss.IO_FLAG_ONDISK_SAME_DIR) + il3 = faiss.downcast_index(faiss.extract_index_ivf(index3)).invlists + self.assertEqual( + faiss.downcast_InvertedLists(il3).filename, + os.path.join(copy_dir, "index.ssd")) + D3, _ = index3.search(ds.get_queries(), k) + np.testing.assert_array_equal(D, D3) + del index3, il3 + os.rename(os.path.join(copy_dir, "index.ssd"), self.path("index.ssd")) + + # the ids are read back from the file + il = index_ivf.get_ssd_invlists() + n = 0 + for l in range(il.nlist): + ids = list_ids(il, l) + for j, i in enumerate(ids): + self.assertEqual(il.get_single_id(l, j), i) + n += len(ids) + self.assertEqual(n, ds.nb) + + # resetting and refilling the file invalidates the saved index + index.reset() + index.add(ds.get_database()) + self.assertRaises(RuntimeError, faiss.read_index, fname) + faiss.write_index(index, fname) + # a new index on the same file invalidates the saved index + other = faiss.IndexIVFRaBitQSSD( + faiss.IndexFlatL2(index_ivf.d), index_ivf.d, 16, 64, 5) + other.attach_file(self.path("index.ssd")) + self.assertRaises(RuntimeError, faiss.read_index, fname) + + def test_search_parameters(self): + ds = datasets.SyntheticDataset(100, 2000, 3000, 30) + index = self.build(ds, 16, 64, 5) + index_ivf = faiss.downcast_index(faiss.extract_index_ivf(index)) + xq = ds.get_queries() + + # a selector, applied after reading the ids from disk + sel = faiss.IDSelectorRange(1000, 2000) + params = faiss.SearchParametersPreTransform( + index_params=faiss.IVFRaBitQSSDSearchParameters( + nprobe=16, sel=sel)) + D, I = index.search(xq, 10, params=params) + self.assertTrue(np.all((I >= 1000) & (I < 2000))) + + # the 8-bit look-up tables give nearly the same results + params16 = faiss.IVFRaBitQSSDSearchParameters( + nprobe=16, use_hacc=True) + params8 = faiss.IVFRaBitQSSDSearchParameters( + nprobe=16, use_hacc=False) + rot = faiss.downcast_VectorTransform(index.chain.at(0)) + xr = rot.apply(xq) + D16, I16 = index_ivf.search(xr, 10, params=params16) + D8, I8 = index_ivf.search(xr, 10, params=params8) + overlap = np.mean([ + len(set(I8[q]) & set(I16[q])) / 10 for q in range(len(xq))]) + self.assertGreaterEqual(overlap, 0.9) + + # with one read in flight, pages are still waiting after the last + # list, and a smaller drain_alpha reads fewer of them + stats = faiss.cvar.indexIVFRaBitQSSD_stats + pages = [] + for drain_alpha in 1.0, 0.3: + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=16, drain_alpha=drain_alpha, qd_per_thread=1) + stats.reset() + index_ivf.search(xr, 10, params=params) + pages.append(stats.n_pages_read) + self.assertGreater(pages[0], 0) + self.assertLess(pages[1], pages[0]) + + # store_pairs: the labels are (list, offset) pairs. With k = nb + # nothing is pruned. + k = ds.nb + Dq, Iq = index_ivf.quantizer.search(xr, 16) + + def search_preassigned(store_pairs, params): + D = np.empty((len(xr), k), dtype="float32") + I = np.empty((len(xr), k), dtype="int64") + index_ivf.search_preassigned_c( + len(xr), faiss.swig_ptr(xr), k, faiss.swig_ptr(Iq), + faiss.swig_ptr(Dq), faiss.swig_ptr(D), faiss.swig_ptr(I), + store_pairs, params) + return D, I + + params = faiss.IVFRaBitQSSDSearchParameters(nprobe=16) + Dref, Iref = search_preassigned(False, params) + D2, I2 = search_preassigned(True, params) + np.testing.assert_array_equal(D2, Dref) + il = index_ivf.get_ssd_invlists() + ids2 = np.full(I2.shape, -1) + for l in range(il.nlist): + mask = (I2 >= 0) & (I2 >> 32 == l) + ids2[mask] = list_ids(il, l)[I2[mask] & 0xffffffff] + self.assertTrue(same_results(Dref, Iref, D2, ids2)) + # a selector does not apply to (list, offset) pairs + params = faiss.IVFRaBitQSSDSearchParameters(nprobe=16, sel=sel) + self.assertRaisesRegex( + RuntimeError, "cannot be combined", search_preassigned, True, + params) + + # invalid parameters + for kwargs in ({"qd_per_thread": 0}, {"drain_alpha": 1.5}, + {"max_codes": 100}, {"max_lists_num": 2}, + {"ensure_topk_full": True}, + {"max_empty_result_buckets": 1}): + params = faiss.IVFRaBitQSSDSearchParameters(nprobe=16, **kwargs) + self.assertRaises( + RuntimeError, index_ivf.search, xr, 10, params=params) + index_ivf.parallel_mode = index_ivf.PARALLEL_MODE_NO_HEAP_INIT + self.assertRaisesRegex( + RuntimeError, "NO_HEAP_INIT", index_ivf.search, xr, 10) + index_ivf.parallel_mode = 0 + + def test_io_contexts_kept(self): + # the libaio contexts of the searches are kept between searches and + # destroyed with the index + gc.collect() + n0 = count_aio_contexts() + index, xb = self.build_flat() + self.assertEqual(count_aio_contexts(), n0) + xq = make_queries(xb, 50, 789) + index.search(xq, 10) + n1 = count_aio_contexts() + self.assertGreater(n1, n0) + self.assertLessEqual(n1, n0 + faiss.omp_get_max_threads()) + for _ in range(3): + index.search(xq, 10) + self.assertEqual(count_aio_contexts(), n1) + # contexts too small for a larger queue depth are replaced + for qd in 32, 64, 128, 200: + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=index.nprobe, qd_per_thread=qd) + index.search(xq, 10, params=params) + self.assertEqual(count_aio_contexts(), n1) + del index + self.assertEqual(count_aio_contexts(), n0) + + def test_concurrent_searches(self): + # searches from several threads at once, on two indexes, give the + # same results as one search at a time + indexes = [self.build_flat(seed=123, name="a.ssd")[0], + self.build_flat(seed=456, name="b.ssd")[0]] + xq = make_data(10, 128, 5, 789) + refs = [] + for index in indexes: + index.nprobe = 4 + # with k = nb nothing is pruned + refs.append(index.search(xq, index.ntotal)) + errors = [] + compared = [] + + def run(t): + faiss.omp_set_num_threads(2) + for rep in range(4): + j = (t + rep) % 2 + try: + D, I = indexes[j].search(xq, indexes[j].ntotal) + except Exception as e: + errors.append((t, rep, repr(e))) + continue + if not same_results(*refs[j], D, I): + errors.append((t, rep, "different results")) + compared.append((t, rep)) + + threads = [threading.Thread(target=run, args=(t,)) for t in range(4)] + for th in threads: + th.start() + for th in threads: + th.join() + self.assertEqual(errors, []) + self.assertEqual(len(compared), 16) + + def test_exception_during_search(self): + # a search that fails with reads in flight leaves its libaio + # contexts ready for the next searches + index, xb = self.build_flat(nb=3000) + xq = make_data(20, 128, 5, 789) + index.nprobe = 8 + # with k = nb nothing is pruned + Dref, Iref = index.search(xq, len(xb)) + n_calls = [0] + + def is_member(i): + n_calls[0] += 1 + if n_calls[0] > 50: + raise ValueError("too many calls") + return True + + # the selector is called when re-ranking, while other reads are in + # flight + sel = faiss.PyCallbackIDSelector(is_member) + params = faiss.IVFRaBitQSSDSearchParameters( + nprobe=8, sel=sel, qd_per_thread=64) + for _ in range(3): + n_calls[0] = 0 + # ValueError if the calling thread runs a failing callback, + # RuntimeError if only OpenMP worker threads do + self.assertRaises( + (ValueError, RuntimeError), index.search, xq, len(xb), + params=params) + # it failed in the callback + self.assertGreater(n_calls[0], 50) + D, I = index.search(xq, len(xb)) + self.assertTrue(same_results(Dref, Iref, D, I)) + + def test_index_factory(self): + ds = datasets.SyntheticDataset(64, 2000, 2000, 10) + index = faiss.index_factory(ds.d, "IVF16,RaBitQSSD5_64") + self.assertIsInstance(index, faiss.IndexIVFRaBitQSSD) + # created without inverted lists: attach a file before adding + self.assertIsNone(index.invlists) + index.reset() + index.train(ds.get_train()) + self.assertRaises(RuntimeError, index.add, ds.get_database()) + # it can be written and read back without inverted lists + fname = self.path("factory.faiss") + faiss.write_index(index, fname) + index = faiss.read_index(fname) + self.assertTrue(index.is_trained) + self.assertIsNone(index.invlists) + index.attach_file(self.path("factory.ssd")) + index.add(ds.get_database()) + # a new file would drop the vectors + self.assertRaisesRegex( + RuntimeError, "needs an empty index", index.attach_file, + self.path("other.ssd")) + + ref = faiss.IndexIVFRaBitQSSD(faiss.IndexFlatL2(ds.d), ds.d, 16, 64, 5) + ref.attach_file(self.path("ref.ssd")) + ref.train(ds.get_train()) + ref.add(ds.get_database()) + index.nprobe = ref.nprobe = 16 + # with k = nb nothing is pruned + k = ds.nb + D, I = index.search(ds.get_queries(), k) + Dref, Iref = ref.search(ds.get_queries(), k) + for q in range(ds.nq): + self.assertEqual( + dict(zip(I[q], D[q])), dict(zip(Iref[q], Dref[q]))) + + # nb_bits = 1, and mem_dim not a multiple of 64 + for bad in "IVF8,RaBitQSSD1_64", "IVF8,RaBitQSSD5_100": + self.assertRaises(RuntimeError, faiss.index_factory, 128, bad) + + def test_unsupported(self): + ds = datasets.SyntheticDataset(64, 1000, 1000, 10) + index = self.build(ds, 8, 64, 2) + index_ivf = faiss.extract_index_ivf(index) + self.assertRaises( + RuntimeError, index_ivf.remove_ids, + faiss.IDSelectorRange(0, 10)) + self.assertRaisesRegex( + RuntimeError, "reconstruct not supported", index_ivf.reconstruct, 0) + xr = faiss.downcast_VectorTransform(index.chain.at(0)).apply( + ds.get_queries()) + stats = faiss.cvar.indexIVFRaBitQSSD_stats + stats.reset() + for method, args in [ + (index.range_search, (ds.get_queries(), 1.0)), + (index_ivf.reconstruct_n, (0, 2)), + (index_ivf.search_and_reconstruct, (xr, 10)), + (index_ivf.search_and_return_codes, (xr, 10)), + (index_ivf.sa_encode, (xr,)), + (index_ivf.update_vectors, (np.arange(1), xr[:1]))]: + self.assertRaises(RuntimeError, method, *args) + # rejected before reading anything + self.assertEqual(stats.n_pages_read, 0) + self.assertEqual(stats.n_reranked, 0) + self.assertRaises(RuntimeError, index_ivf.merge_from, index_ivf, 0) + # moving codes between inverted lists + other = faiss.IndexIVFFlat(faiss.IndexFlatL2(64), 64, 8) + self.assertRaisesRegex( + RuntimeError, "copy_subset_to not supported", + index_ivf.copy_subset_to, other, 0, 0, 10) + # nb_bits = 1 is rejected + self.assertRaises( + RuntimeError, faiss.IndexIVFRaBitQSSD, faiss.IndexFlatL2(64), + 64, 8, 64, 1) + + +@unittest.skipUnless( + hasattr(faiss, "IndexIVFRaBitQSSD"), "IndexIVFRaBitQSSD not built") +class TestIVFRaBitQSSDCompileOptions(unittest.TestCase): + + def test_compile_options(self): + self.assertIn("DISK_IVF", faiss.get_compile_options()) diff --git a/thirdparty/faiss/tests/test_ivf_sharding.cpp b/thirdparty/faiss/tests/test_ivf_sharding.cpp index 68f6d7057..59bcd50ca 100644 --- a/thirdparty/faiss/tests/test_ivf_sharding.cpp +++ b/thirdparty/faiss/tests/test_ivf_sharding.cpp @@ -21,13 +21,10 @@ #include "test_util.h" -// Regression guard for two leaks in handle_ivf / handle_binary_ivf -// (faiss/IVFlib.cpp), both invisible to normal runs but caught under -// AddressSanitizer/LeakSanitizer (fbcode @mode/dev-asan, run in CI): -// 1. the input `clone` created once per call and never freed; -// 2. (generate_ids=true only) the cloned quantizer swapped out for an -// IndexIDMap2 wrapper that previously did not own/free it. -// Each test exercises both generate_ids paths so both leaks are covered. +// Leak regression for handle_ivf / handle_binary_ivf (faiss/IVFlib.cpp), only +// visible under AddressSanitizer (@mode/dev-asan): the per-call clone, and with +// generate_ids=true the quantizer wrapped in IndexIDMap2. Each test runs both +// generate_ids paths. namespace { @@ -76,7 +73,6 @@ TEST(TestIvfSharding, ShardIvfCentroidsNoLeak) { for (int64_t i = 0; i < shardCount; i++) { snprintf(fname, sizeof(fname), tmpl.c_str(), i); faiss::Index* shard = faiss::read_index(fname); - EXPECT_NE(shard, nullptr); delete shard; } removeShardFiles(tmpl, shardCount); @@ -112,7 +108,6 @@ TEST(TestIvfSharding, ShardBinaryIvfCentroidsNoLeak) { for (int64_t i = 0; i < shardCount; i++) { snprintf(fname, sizeof(fname), tmpl.c_str(), i); faiss::IndexBinary* shard = faiss::read_index_binary(fname); - EXPECT_NE(shard, nullptr); delete shard; } removeShardFiles(tmpl, shardCount); diff --git a/thirdparty/faiss/tests/test_ivf_sq_fastscan.py b/thirdparty/faiss/tests/test_ivf_sq_fastscan.py index 0a066b0ce..d866d7768 100644 --- a/thirdparty/faiss/tests/test_ivf_sq_fastscan.py +++ b/thirdparty/faiss/tests/test_ivf_sq_fastscan.py @@ -4,8 +4,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""Tests for IndexIVFSQFastScan.""" - import numpy as np import unittest @@ -13,83 +11,12 @@ from faiss.contrib.datasets import SyntheticDataset -class TestIndexIVFSQFastScanBasic(unittest.TestCase): - """Basic construction, train, add, search tests.""" - - def test_construct_native_4bit(self): - d, nlist = 32, 8 - quantizer = faiss.IndexFlatL2(d) - idx = faiss.IndexIVFSQFastScan( - quantizer, d, nlist, faiss.ScalarQuantizer.QT_4bit - ) - self.assertEqual(idx.d, d) - self.assertEqual(idx.nlist, nlist) - - def test_construct_rerank_8bit(self): - d, nlist = 32, 8 - quantizer = faiss.IndexFlatL2(d) - idx = faiss.IndexIVFSQFastScan( - quantizer, d, nlist, faiss.ScalarQuantizer.QT_8bit - ) - self.assertEqual(idx.d, d) - - def test_train_add_search_4bit(self): - ds = SyntheticDataset(d=32, nt=1000, nb=1000, nq=10, seed=42) - - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_4bit - ) - idx.train(ds.get_train()) - self.assertTrue(idx.is_trained) - idx.add(ds.get_database()) - self.assertEqual(idx.ntotal, ds.nb) - - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 10) - self.assertEqual(D.shape, (10, 10)) - self.assertEqual(I.shape, (10, 10)) - self.assertTrue(np.all(I >= 0)) - - def test_train_add_search_8bit(self): - ds = SyntheticDataset(d=32, nt=1000, nb=1000, nq=10, seed=42) - - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_8bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - self.assertEqual(idx.ntotal, ds.nb) - - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 10) - self.assertTrue(np.all(I >= 0)) - - def test_train_add_search_fp16_fallback(self): - ds = SyntheticDataset(d=32, nt=1000, nb=1000, nq=10, seed=42) - - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_fp16 - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - self.assertEqual(idx.ntotal, ds.nb) - - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 10) - self.assertTrue(np.all(I >= 0)) - - class TestIndexIVFSQFastScanRecall(unittest.TestCase): - """Recall parity tests against IndexIVFScalarQuantizer.""" def _compare_recall(self, qtype, nlist=16, nprobe=16): ds = SyntheticDataset(d=32, nt=2000, nb=2000, nq=50, seed=42) k = 10 - # Ground truth gt_idx = faiss.IndexFlatL2(ds.d) gt_idx.add(ds.get_database()) D_gt, I_gt = gt_idx.search(ds.get_queries(), k) @@ -97,84 +24,61 @@ def _compare_recall(self, qtype, nlist=16, nprobe=16): # Shared coarse quantizer ensures same IVF assignment quantizer = faiss.IndexFlatL2(ds.d) - # Reference: IndexIVFScalarQuantizer ref = faiss.IndexIVFScalarQuantizer( quantizer, ds.d, nlist, qtype ) ref.train(ds.get_train()) - ref.add(ds.get_database()) - ref.nprobe = nprobe - D_ref, I_ref = ref.search(ds.get_queries(), k) - # Test: IndexIVFSQFastScan with same quantizer and SQ test = faiss.IndexIVFSQFastScan( quantizer, ds.d, nlist, qtype ) test.sq = ref.sq test.is_trained = True test.add(ds.get_database()) + self.assertEqual(test.ntotal, ds.nb) test.nprobe = nprobe D_test, I_test = test.search(ds.get_queries(), k) - # Compute recalls - recall_ref = np.mean([ - len(set(I_ref[i]) & set(I_gt[i])) / k - for i in range(ds.nq) - ]) recall_test = np.mean([ len(set(I_test[i]) & set(I_gt[i])) / k for i in range(ds.nq) ]) - return recall_ref, recall_test + return recall_test def test_recall_4bit(self): - recall_ref, recall_test = self._compare_recall( + recall_test = self._compare_recall( faiss.ScalarQuantizer.QT_4bit ) self.assertGreater(recall_test, 0.5) def test_recall_8bit(self): - recall_ref, recall_test = self._compare_recall( + recall_test = self._compare_recall( faiss.ScalarQuantizer.QT_8bit ) self.assertGreater(recall_test, 0.7) def test_recall_6bit(self): - recall_ref, recall_test = self._compare_recall( + recall_test = self._compare_recall( faiss.ScalarQuantizer.QT_6bit ) self.assertGreater(recall_test, 0.6) def test_recall_fp16(self): - recall_ref, recall_test = self._compare_recall( + recall_test = self._compare_recall( faiss.ScalarQuantizer.QT_fp16 ) self.assertGreater(recall_test, 0.9) class TestIndexIVFSQFastScanFactory(unittest.TestCase): - """Factory string tests.""" - def test_factory_sq8fs(self): + def test_factory_strings(self): d = 32 - idx = faiss.index_factory(d, "IVF16,SQ8fs") - self.assertIsInstance(idx, faiss.IndexIVFSQFastScan) - - def test_factory_sq4fs(self): - d = 32 - idx = faiss.index_factory(d, "IVF16,SQ4fs") - self.assertIsInstance(idx, faiss.IndexIVFSQFastScan) - - def test_factory_sqfp16fs(self): - d = 32 - idx = faiss.index_factory(d, "IVF16,SQfp16fs") - self.assertIsInstance(idx, faiss.IndexIVFSQFastScan) - - def test_factory_sq6fs(self): - d = 32 - idx = faiss.index_factory(d, "IVF16,SQ6fs") - self.assertIsInstance(idx, faiss.IndexIVFSQFastScan) + for s in ("IVF16,SQ4fs", "IVF16,SQ6fs", "IVF16,SQfp16fs"): + with self.subTest(s=s): + idx = faiss.index_factory(d, s) + self.assertIsInstance(idx, faiss.IndexIVFSQFastScan) def test_factory_with_bbs(self): d = 32 @@ -194,81 +98,48 @@ def test_factory_train_search(self): class TestIndexIVFSQFastScanIP(unittest.TestCase): - """Inner product metric tests.""" - def test_inner_product_4bit(self): + def test_inner_product(self): ds = SyntheticDataset(d=32, nt=1000, nb=1000, nq=10, seed=42) - quantizer = faiss.IndexFlatIP(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_4bit, - faiss.METRIC_INNER_PRODUCT - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 10) - self.assertTrue(np.all(I >= 0)) - - def test_inner_product_8bit(self): - ds = SyntheticDataset(d=32, nt=1000, nb=1000, nq=10, seed=42) - - quantizer = faiss.IndexFlatIP(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_8bit, - faiss.METRIC_INNER_PRODUCT - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 10) - self.assertTrue(np.all(I >= 0)) + for qtype in (faiss.ScalarQuantizer.QT_4bit, + faiss.ScalarQuantizer.QT_8bit): + with self.subTest(qtype=qtype): + quantizer = faiss.IndexFlatIP(ds.d) + idx = faiss.IndexIVFSQFastScan( + quantizer, ds.d, 8, qtype, faiss.METRIC_INNER_PRODUCT + ) + idx.train(ds.get_train()) + idx.add(ds.get_database()) + idx.nprobe = 8 + D, I = idx.search(ds.get_queries(), 10) + self.assertTrue(np.all(I >= 0)) class TestIndexIVFSQFastScanIO(unittest.TestCase): - """Serialization round-trip tests.""" - def test_io_roundtrip_4bit(self): + def test_io_roundtrip(self): ds = SyntheticDataset(d=32, nt=500, nb=500, nq=5, seed=42) - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_4bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.nprobe = 8 - - D1, I1 = idx.search(ds.get_queries(), 5) + for qtype in (faiss.ScalarQuantizer.QT_4bit, + faiss.ScalarQuantizer.QT_8bit): + with self.subTest(qtype=qtype): + quantizer = faiss.IndexFlatL2(ds.d) + idx = faiss.IndexIVFSQFastScan(quantizer, ds.d, 8, qtype) + idx.train(ds.get_train()) + idx.add(ds.get_database()) + idx.nprobe = 8 - idx2 = faiss.deserialize_index(faiss.serialize_index(idx)) - idx2.nprobe = 8 - D2, I2 = idx2.search(ds.get_queries(), 5) - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, rtol=1e-5) + D1, I1 = idx.search(ds.get_queries(), 5) - def test_io_roundtrip_8bit(self): - ds = SyntheticDataset(d=32, nt=500, nb=500, nq=5, seed=42) - - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_8bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.nprobe = 8 - - D1, I1 = idx.search(ds.get_queries(), 5) - - idx2 = faiss.deserialize_index(faiss.serialize_index(idx)) - idx2.nprobe = 8 - D2, I2 = idx2.search(ds.get_queries(), 5) - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, rtol=1e-5) + idx2 = faiss.deserialize_index(faiss.serialize_index(idx)) + idx2.nprobe = 8 + D2, I2 = idx2.search(ds.get_queries(), 5) + np.testing.assert_array_equal(I1, I2) + np.testing.assert_allclose(D1, D2, rtol=1e-5) class TestIndexIVFSQFastScanReset(unittest.TestCase): - """Reset and re-add tests.""" def test_reset(self): ds = SyntheticDataset(d=32, nt=500, nb=500, nq=0, seed=42) @@ -279,7 +150,6 @@ def test_reset(self): ) idx.train(ds.get_train()) idx.add(ds.get_database()) - self.assertEqual(idx.ntotal, ds.nb) idx.reset() self.assertEqual(idx.ntotal, 0) @@ -289,43 +159,61 @@ def test_reset(self): class TestIndexIVFSQFastScanReconstruct(unittest.TestCase): - """Reconstruction tests.""" - def test_reconstruct_4bit(self): + def test_reconstruct(self): ds = SyntheticDataset(d=32, nt=200, nb=200, nq=0, seed=42) - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_4bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.make_direct_map() + for qtype, tol in ((faiss.ScalarQuantizer.QT_4bit, 5.0), + (faiss.ScalarQuantizer.QT_8bit, 1.0)): + with self.subTest(qtype=qtype): + quantizer = faiss.IndexFlatL2(ds.d) + idx = faiss.IndexIVFSQFastScan(quantizer, ds.d, 8, qtype) + idx.train(ds.get_train()) + idx.add(ds.get_database()) + idx.make_direct_map() - recon = idx.reconstruct(0) - self.assertEqual(recon.shape, (ds.d,)) - err = np.linalg.norm(recon - ds.get_database()[0]) - self.assertLess(err, 5.0) + recon = idx.reconstruct(0) + err = np.linalg.norm(recon - ds.get_database()[0]) + self.assertLess(err, tol) - def test_reconstruct_8bit(self): - ds = SyntheticDataset(d=32, nt=200, nb=200, nq=0, seed=42) - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_8bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.make_direct_map() +class TestIndexIVFSQFastScanSearchAndReconstruct(unittest.TestCase): + + def test_search_and_reconstruct(self): + ds = SyntheticDataset(d=32, nt=1000, nb=500, nq=10, seed=42) + # non-sequential ids so that an id is not a valid (list, offset) pair + ids = np.arange(ds.nb, dtype="int64") * 7 + 3 + k = 10 - recon = idx.reconstruct(0) - self.assertEqual(recon.shape, (ds.d,)) - err = np.linalg.norm(recon - ds.get_database()[0]) - self.assertLess(err, 1.0) + for qtype in (faiss.ScalarQuantizer.QT_8bit, + faiss.ScalarQuantizer.QT_6bit, + faiss.ScalarQuantizer.QT_fp16): + for metric in (faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT): + with self.subTest(qtype=qtype, metric=metric): + quantizer = faiss.IndexFlat(ds.d, metric) + idx = faiss.IndexIVFSQFastScan( + quantizer, ds.d, 8, qtype, metric + ) + idx.train(ds.get_train()) + idx.add_with_ids(ds.get_database(), ids) + idx.nprobe = 8 + if idx.direct_map.type == faiss.DirectMap.NoMap: + idx.set_direct_map_type(faiss.DirectMap.Hashtable) + + # reference: same coarse assignment, without store_pairs + xq = ds.get_queries() + Dq, Iq = quantizer.search(xq, idx.nprobe) + D_ref, I_ref = idx.search_preassigned(xq, k, Iq, Dq) + D, I, R = idx.search_and_reconstruct(xq, k) + np.testing.assert_array_equal(I, I_ref) + np.testing.assert_allclose(D, D_ref, rtol=1e-5) + R_ref = idx.reconstruct_batch(I_ref.ravel()) + np.testing.assert_allclose( + R.reshape(-1, ds.d), R_ref, rtol=1e-5, atol=1e-5 + ) class TestIndexIVFSQFastScanEdgeCases(unittest.TestCase): - """Edge cases and special scenarios.""" def test_single_vector(self): ds = SyntheticDataset(d=32, nt=100, nb=1, nq=1, seed=42) @@ -340,20 +228,6 @@ def test_single_vector(self): D, I = idx.search(ds.get_queries(), 1) self.assertEqual(I[0, 0], 0) - def test_k_equals_1(self): - ds = SyntheticDataset(d=32, nt=500, nb=500, nq=10, seed=42) - - quantizer = faiss.IndexFlatL2(ds.d) - idx = faiss.IndexIVFSQFastScan( - quantizer, ds.d, 8, faiss.ScalarQuantizer.QT_8bit - ) - idx.train(ds.get_train()) - idx.add(ds.get_database()) - idx.nprobe = 8 - D, I = idx.search(ds.get_queries(), 1) - self.assertEqual(D.shape, (10, 1)) - self.assertEqual(I.shape, (10, 1)) - def test_odd_dimension(self): ds = SyntheticDataset(d=33, nt=500, nb=500, nq=10, seed=42) diff --git a/thirdparty/faiss/tests/test_ivflib.py b/thirdparty/faiss/tests/test_ivflib.py index a4aa2f1e9..241deb6e2 100644 --- a/thirdparty/faiss/tests/test_ivflib.py +++ b/thirdparty/faiss/tests/test_ivflib.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import absolute_import, division, print_function - import unittest import faiss import numpy as np @@ -17,13 +15,6 @@ class TestIVFlib(unittest.TestCase): def test_methods_exported(self): methods = [ "check_compatible_for_merge", - "extract_index_ivf", - "merge_into", - "search_centroid", - "search_and_return_centroids", - "get_invlist_range", - "set_invlist_range", - "search_with_parameters", ] for method in methods: @@ -34,12 +25,6 @@ def search_single_scan(index, xq, k, bs=128): """performs a search so that the inverted lists are accessed sequentially by blocks of size bs""" - # handle pretransform - if isinstance(index, faiss.IndexPreTransform): - xq = index.apply_py(xq) - index = faiss.downcast_index(index.index) - - # coarse assignment nprobe = min(index.nprobe, index.nlist) coarse_dis, assign = index.quantizer.search(xq, nprobe) nlist = index.nlist @@ -154,6 +139,35 @@ def test_range_search_with_parameters(self): self.assertEqual(stats2["ndis"], ref_ndis) +class TestSearchWithDistanceToCode(unittest.TestCase): + + def do_test(self, factory, metric=faiss.METRIC_L2): + d = 32 + index = faiss.index_factory(d, factory, metric) + rs = np.random.RandomState(123) + index.train(rs.rand(5000, d).astype("float32")) + index.add(rs.rand(10000, d).astype("float32")) + xq = rs.rand(100, d).astype("float32") + faiss.extract_index_ivf(index).nprobe = 4 + + Dref, Iref = index.search(xq, 10) + D, I = faiss.search_with_distance_to_code(index, xq, 10) + + np.testing.assert_allclose(D, Dref, rtol=1e-5) + # distance_to_code and the batched scan may round differently, which + # can swap ties + self.assertGreater((I == Iref).mean(), 0.99) + + def test_ivfpq(self): + self.do_test("IVF32,PQ8") + + def test_ivfpq_ip(self): + self.do_test("IVF32,PQ8", faiss.METRIC_INNER_PRODUCT) + + def test_ivfsq_pretransform(self): + self.do_test("PCA16,IVF32,SQ8") + + class TestSmallData(unittest.TestCase): """Test in case of nprobe > nlist.""" @@ -173,13 +187,11 @@ def test_small_data(self): k = 5 xq = rs.rand(10, d).astype("float32") - # test kNN search D, I = index.search(xq, k) ref_D, ref_I = faiss.knn(xq, xb, k) assert np.all(D == ref_D) assert np.all(I == ref_I) - # test range search thresh = 0.1 # *squared* distance lims, D, I = index.range_search(xq, thresh) ref_index = faiss.IndexFlat(d) @@ -199,23 +211,34 @@ def custom_sharding_function(self, i, _): return 1 if i % 2 == 0 else 7 # Mimics the default in DefaultShardingFunction. - # This impl is just used for verification. def default_sharding_function(self, i, shard_count): return i % shard_count def verify_sharded_ivf_indexes( - self, template, xb, shard_count, sharding_function, generate_ids=True + self, template, xb, shard_count, sharding_function, + generate_ids=True, pre_transform=None ): sharded_indexes_counters = [0] * shard_count sharded_indexes = [] + wrappers = [] # Own the IVF sub-indexes until verification finishes. for i in range(shard_count): if xb[0].dtype.name == "uint8": index = faiss.read_index_binary(template % i) else: index = faiss.read_index(template % i) + if pre_transform is not None: + self.assertIsInstance(index, faiss.IndexPreTransform) + self.assertEqual(index.chain.size(), 1) + shard_transform = faiss.downcast_VectorTransform( + index.chain.at(0) + ) + np.testing.assert_array_equal( + shard_transform.apply(xb[:10]), pre_transform.apply(xb[:10]) + ) + wrappers.append(index) + index = faiss.downcast_index(index.index) sharded_indexes.append(index) - # Reconstruct and verify each centroid if generate_ids: for i in range(len(xb)): shard_id = sharding_function(i, shard_count) @@ -232,33 +255,17 @@ def verify_sharded_ivf_indexes( sharded_indexes_counters[shard_id] += 1 np.testing.assert_array_equal(reconstructed, xb[i]) - # Clean up for i in range(shard_count): os.remove(template % i) def test_save_index_shards_by_centroids_no_op(self): quantizer = faiss.IndexFlatL2(self.d) index = faiss.IndexIVFFlat(quantizer, self.d, self.nlist) - with self.assertRaises(RuntimeError): - faiss.shard_ivf_index_centroids(index, 10, "shard.%d.index", None) - - def test_save_index_shards_by_centroids_flat_quantizer_default_sharding( - self, - ): - xb = np.random.rand(self.nb, self.d).astype("float32") - quantizer = faiss.IndexFlatL2(self.d) - index = faiss.IndexIVFFlat(quantizer, self.d, self.nlist) - shard_count = 3 - - index.quantizer.add(xb) - - template = str(random.randint(0, 100000)) + "shard.%d.index" - faiss.shard_ivf_index_centroids( - index, shard_count, template, None, True - ) - self.verify_sharded_ivf_indexes( - template, xb, shard_count, self.default_sharding_function - ) + for invalid_index in (index, faiss.IndexPreTransform(quantizer)): + with self.assertRaises(RuntimeError): + faiss.shard_ivf_index_centroids( + invalid_index, 10, "shard.%d.index", None + ) def test_save_index_shards_by_centroids_flat_quantizer_custom_sharding( self, @@ -364,13 +371,11 @@ def test_save_index_shards_without_id_generation(self): ) def test_save_index_shards_by_centroids_rabitq(self): - """Test sharding for IndexIVFRaBitQ.""" xb = np.random.rand(self.nb, self.d).astype("float32") quantizer = faiss.IndexFlatL2(self.d) index = faiss.IndexIVFRaBitQ(quantizer, self.d, self.nlist) shard_count = 7 - # train and add centroids to quantizer index.train(xb) index.quantizer.reset() index.quantizer.add(xb) @@ -384,47 +389,36 @@ def test_save_index_shards_by_centroids_rabitq(self): ) def test_save_index_shards_by_centroids_rabitq_fastscan(self): - """Test sharding for IndexIVFRaBitQFastScan.""" xb = np.random.rand(self.nb, self.d).astype("float32") quantizer = faiss.IndexFlatL2(self.d) index = faiss.IndexIVFRaBitQFastScan(quantizer, self.d, self.nlist) shard_count = 5 - # train and add centroids to quantizer index.train(xb) index.quantizer.reset() index.quantizer.add(xb) - - template = str(random.randint(0, 100000)) + "shard.%d.rabitqfs.index" - faiss.shard_ivf_index_centroids( - index, shard_count, template, None, True - ) - self.verify_sharded_ivf_indexes( - template, xb, shard_count, self.default_sharding_function - ) - - def test_save_index_shards_by_centroids_rabitq_custom_sharding(self): - """Test sharding for IndexIVFRaBitQ with custom sharding function.""" - xb = np.random.rand(self.nb, self.d).astype("float32") - quantizer = faiss.IndexFlatL2(self.d) - index = faiss.IndexIVFRaBitQ(quantizer, self.d, self.nlist) - shard_count = 20 - - # train and add centroids to quantizer - index.train(xb) - index.quantizer.reset() - index.quantizer.add(xb) - - template = str(random.randint(0, 100000)) + "shard.%d.rabitq.index" - faiss.shard_ivf_index_centroids( - index, shard_count, template, self.custom_sharding_function, True - ) - self.verify_sharded_ivf_indexes( - template, xb, shard_count, self.custom_sharding_function - ) + rr = faiss.RandomRotationMatrix(self.d, self.d) + rr.init(1234) + + for transform in (None, rr): + with self.subTest(pretransform=transform is not None): + model = ( + faiss.IndexPreTransform(transform, index) + if transform else index + ) + generate_ids = transform is None + template = ( + str(random.randint(0, 100000)) + "shard.%d.rabitqfs.index" + ) + faiss.shard_ivf_index_centroids( + model, shard_count, template, None, generate_ids + ) + self.verify_sharded_ivf_indexes( + template, xb, shard_count, self.default_sharding_function, + generate_ids, transform + ) def test_save_index_shards_by_centroids_panorama(self): - """Test sharding for IndexIVFFlatPanorama.""" xb = np.random.rand(self.nb, self.d).astype("float32") quantizer = faiss.IndexFlatL2(self.d) n_levels = 4 @@ -440,7 +434,6 @@ def test_save_index_shards_by_centroids_panorama(self): index, shard_count, template, None, True ) - # Verify shards are IndexIVFFlatPanorama after read-back for i in range(shard_count): fname = template % i shard = faiss.read_index(fname) diff --git a/thirdparty/faiss/tests/test_ivfpq_codec.cpp b/thirdparty/faiss/tests/test_ivfpq_codec.cpp deleted file mode 100644 index c9e9a038c..000000000 --- a/thirdparty/faiss/tests/test_ivfpq_codec.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include - -#include - -#include - -#include -#include -#include - -namespace { - -// dimension of the vectors to index -int d = 64; - -// size of the database we plan to index -size_t nb = 8000; - -double eval_codec_error(long ncentroids, long m, const std::vector& v) { - faiss::IndexFlatL2 coarse_quantizer(d); - faiss::IndexIVFPQ index(&coarse_quantizer, d, ncentroids, m, 8); - index.pq.cp.niter = 10; // speed up train - index.train(nb, v.data()); - - // encode and decode to compute reconstruction error - - std::vector keys(nb); - std::vector codes(nb * m); - index.encode_multiple(nb, keys.data(), v.data(), codes.data(), true); - - std::vector v2(nb * d); - index.decode_multiple(nb, keys.data(), codes.data(), v2.data()); - - return faiss::fvec_L2sqr(v.data(), v2.data(), nb * d); -} - -} // namespace - -bool runs_on_sandcastle() { - // see discussion here https://fburl.com/qc5kpdo2 - const char* sandcastle = getenv("SANDCASTLE"); - if (sandcastle && !strcmp(sandcastle, "1")) { - return true; - } - const char* tw_job_user = getenv("TW_JOB_USER"); - if (tw_job_user && !strcmp(tw_job_user, "sandcastle")) { - return true; - } - - return false; -} - -TEST(IVFPQ, codec) { - std::vector database(nb * d); - std::mt19937 rng; - std::uniform_real_distribution<> distrib; - for (size_t i = 0; i < nb * d; i++) { - database[i] = distrib(rng); - } - - // limit number of threads when running on heavily parallelized test - // environment - if (runs_on_sandcastle()) { - omp_set_num_threads(2); - } - - double err0 = eval_codec_error(16, 8, database); - - // should be more accurate as there are more coarse centroids - double err1 = eval_codec_error(128, 8, database); - EXPECT_GT(err0, err1); - - // should be more accurate as there are more PQ codes - double err2 = eval_codec_error(16, 16, database); - EXPECT_GT(err0, err2); -} diff --git a/thirdparty/faiss/tests/test_ivfpq_codec.py b/thirdparty/faiss/tests/test_ivfpq_codec.py new file mode 100644 index 000000000..59cbea9f0 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivfpq_codec.py @@ -0,0 +1,68 @@ +# 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 os +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + +d = 64 +nb = 8000 + + +def eval_codec_error(ncentroids, m, database): + coarse_quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFPQ(coarse_quantizer, d, ncentroids, m, 8) + index.pq.cp.niter = 10 # speed up train + index.train(database) + + keys = np.empty(nb, dtype=np.int64) + codes = np.empty((nb, m), dtype=np.uint8) + index.encode_multiple( + nb, + faiss.swig_ptr(keys), + faiss.swig_ptr(database), + faiss.swig_ptr(codes), + True, + ) + + v2 = np.empty((nb, d), dtype=np.float32) + index.decode_multiple( + nb, faiss.swig_ptr(keys), faiss.swig_ptr(codes), faiss.swig_ptr(v2) + ) + + return float(np.sum((database - v2) ** 2)) + + +def runs_on_sandcastle(): + # see discussion here https://fburl.com/qc5kpdo2 + if os.environ.get("SANDCASTLE") == "1": + return True + return os.environ.get("TW_JOB_USER") == "sandcastle" + + +class TestIVFPQCodec(unittest.TestCase): + def test_codec(self): + rs = np.random.RandomState(0) + database = rs.rand(nb, d).astype(np.float32) + + # limit number of threads when running on heavily parallelized test + # environment + if runs_on_sandcastle(): + faiss.omp_set_num_threads(2) + + err0 = eval_codec_error(16, 8, database) + + # should be more accurate as there are more coarse centroids + err1 = eval_codec_error(128, 8, database) + self.assertGreater(err0, err1) + + # should be more accurate as there are more PQ codes + err2 = eval_codec_error(16, 16, database) + self.assertGreater(err0, err2) diff --git a/thirdparty/faiss/tests/test_ivfpq_indexing.cpp b/thirdparty/faiss/tests/test_ivfpq_indexing.cpp deleted file mode 100644 index 4f1b3d459..000000000 --- a/thirdparty/faiss/tests/test_ivfpq_indexing.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include - -#include - -#include -#include - -TEST(IVFPQ, onTheFlyDistanceToCodeMatchesPrecomputedTable) { - constexpr int d = 4; - constexpr size_t nt = 256; - faiss::IndexFlatL2 coarse_quantizer(d); - faiss::IndexIVFPQ index(&coarse_quantizer, d, 2, 2, 4); - - std::mt19937 rng(1234); - std::uniform_real_distribution distrib(-1.0f, 1.0f); - std::vector training(nt * d); - for (float& value : training) { - value = distrib(rng); - } - index.train(nt, training.data()); - - const std::vector query = {0.2f, -0.4f, 0.6f, -0.8f}; - const std::vector value = {-0.1f, 0.3f, 0.7f, -0.5f}; - faiss::idx_t list_no; - float coarse_distance; - index.quantizer->search(1, query.data(), 1, &coarse_distance, &list_no); - ASSERT_GE(list_no, 0); - - std::vector code(index.code_size); - index.encode(list_no, value.data(), code.data()); - std::unique_ptr table_scanner( - index.get_InvertedListScanner(false, nullptr, nullptr)); - std::unique_ptr on_the_fly_scanner( - index.get_InvertedListScanner( - false, nullptr, faiss::IndexIVFPQ::ScannerMode::OnTheFly)); - - for (auto* scanner : {table_scanner.get(), on_the_fly_scanner.get()}) { - scanner->set_query(query.data()); - scanner->set_list(list_no, coarse_distance); - } - - EXPECT_NEAR( - on_the_fly_scanner->distance_to_code(code.data()), - table_scanner->distance_to_code(code.data()), - 1e-4); -} - -TEST(IVFPQ, accuracy) { - // dimension of the vectors to index - int d = 64; - - // size of the database we plan to index - size_t nb = 1000; - - // make a set of nt training vectors in the unit cube - // (could be the database) - size_t nt = 1500; - - // make the index object and train it - faiss::IndexFlatL2 coarse_quantizer(d); - - // a reasonable number of centroids to index nb vectors - int ncentroids = 25; - - faiss::IndexIVFPQ index(&coarse_quantizer, d, ncentroids, 16, 8); - - // index that gives the ground-truth - faiss::IndexFlatL2 index_gt(d); - - std::mt19937 rng; - std::uniform_real_distribution<> distrib; - - { // training - - std::vector trainvecs(nt * d); - for (size_t i = 0; i < nt * d; i++) { - trainvecs[i] = distrib(rng); - } - index.verbose = true; - index.train(nt, trainvecs.data()); - } - - { // populating the database - - std::vector database(nb * d); - for (size_t i = 0; i < nb * d; i++) { - database[i] = distrib(rng); - } - - index.add(nb, database.data()); - index_gt.add(nb, database.data()); - } - - int nq = 200; - int n_ok; - - { // searching the database - - std::vector queries(nq * d); - for (int i = 0; i < nq * d; i++) { - queries[i] = distrib(rng); - } - - std::vector gt_nns(nq); - std::vector gt_dis(nq); - - index_gt.search(nq, queries.data(), 1, gt_dis.data(), gt_nns.data()); - - index.nprobe = 5; - int k = 5; - std::vector nns(k * nq); - std::vector dis(k * nq); - - index.search(nq, queries.data(), k, dis.data(), nns.data()); - - n_ok = 0; - for (int q = 0; q < nq; q++) { - for (int i = 0; i < k; i++) - if (nns[q * k + i] == gt_nns[q]) - n_ok++; - } - EXPECT_GT(n_ok, nq * 0.4); - } -} diff --git a/thirdparty/faiss/tests/test_ivfpq_indexing.py b/thirdparty/faiss/tests/test_ivfpq_indexing.py new file mode 100644 index 000000000..c021b5ad8 --- /dev/null +++ b/thirdparty/faiss/tests/test_ivfpq_indexing.py @@ -0,0 +1,47 @@ +# 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 unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +class TestIVFPQIndexing(unittest.TestCase): + def test_on_the_fly_distance_to_code_matches_precomputed_table(self): + d = 4 + nt = 256 + coarse_quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFPQ(coarse_quantizer, d, 2, 2, 4) + + rng = np.random.RandomState(1234) + training = rng.uniform(-1.0, 1.0, size=(nt, d)).astype(np.float32) + index.train(training) + + query = np.array([0.2, -0.4, 0.6, -0.8], dtype=np.float32) + value = np.array([-0.1, 0.3, 0.7, -0.5], dtype=np.float32) + coarse_D, coarse_I = index.quantizer.search(query.reshape(1, d), 1) + list_no = int(coarse_I[0, 0]) + coarse_distance = float(coarse_D[0, 0]) + + code = np.zeros(index.code_size, dtype=np.uint8) + index.encode(list_no, faiss.swig_ptr(value), faiss.swig_ptr(code)) + table_scanner = index.get_InvertedListScanner(False, None, None) + on_the_fly_scanner = index.get_InvertedListScanner( + False, None, faiss.IndexIVFPQ.ScannerMode_OnTheFly + ) + + for scanner in table_scanner, on_the_fly_scanner: + scanner.set_query(faiss.swig_ptr(query)) + scanner.set_list(list_no, coarse_distance) + + self.assertAlmostEqual( + on_the_fly_scanner.distance_to_code(faiss.swig_ptr(code)), + table_scanner.distance_to_code(faiss.swig_ptr(code)), + delta=1e-4, + ) diff --git a/thirdparty/faiss/tests/test_local_search_quantizer.py b/thirdparty/faiss/tests/test_local_search_quantizer.py index b24a511e5..0f042a1ce 100644 --- a/thirdparty/faiss/tests/test_local_search_quantizer.py +++ b/thirdparty/faiss/tests/test_local_search_quantizer.py @@ -3,10 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Tests for the implementation of Local Search Quantizer -""" - import numpy as np import platform @@ -73,7 +69,7 @@ def icm_encode_step_ref(unaries, binaries, codes): for m in range(M): objs = unaries[m].copy() # [n, K] - for m2 in range(M): # pair, m2 != m + for m2 in range(M): if m2 == m: continue @@ -109,7 +105,6 @@ def icm_encode_ref(x, codebooks, codes): new_codes = codes.copy() new_codes[:, m] = code - # decode x decoded_x = decode_ref(x, codebooks, new_codes) objs[:, code] = np.sum((x - decoded_x) ** 2, axis=1) @@ -122,7 +117,6 @@ def icm_encode_ref(x, codebooks, codes): class TestComponents(unittest.TestCase): def test_decode(self): - """Test LSQ decode""" d = 16 n = 500 M = 4 @@ -135,13 +129,11 @@ def test_decode(self): lsq = faiss.LocalSearchQuantizer(d, M, nbits) lsq.train(x) - # decode x pack_codes = np.zeros((n, lsq.code_size)).astype(np.uint8) decoded_x = np.zeros((n, d)).astype(np.float32) lsq.pack_codes(n, sp(codes), sp(pack_codes)) lsq.decode_c(sp(pack_codes), sp(decoded_x), n) - # decode in Python codebooks = faiss.vector_float_to_array(lsq.codebooks) codebooks = codebooks.reshape(M, K, d).copy() decoded_x_ref = decode_ref(x, codebooks, codes) @@ -153,7 +145,6 @@ def test_decode(self): "Does not work on Windows after numpy 2 upgrade.", ) def test_update_codebooks(self): - """Test codebooks updatation.""" d = 16 n = 500 M = 4 @@ -260,27 +251,18 @@ def test_icm_encode_step(self): rs = np.random.RandomState(123) - # randomly generate codes and unary terms codes = rs.randint(0, K, (n, M)).astype(np.int32) new_codes = codes.copy() unaries = rs.rand(M, n, K).astype(np.float32) - # binary terms should be symmetric, because binary terms - # represent cached dot products between the code C1 in codebook M1 - # and the code C2 in codebook M2. - # so, binaries[M1, M2, C1, C2] == binaries[M2, M1, C2, C1] - # - # generate binary terms in a standard way that provides - # the needed symmetry + # binaries must be symmetric: [M1, M2, C1, C2] == [M2, M1, C2, C1] codebooks = rs.rand(M, K, d).astype(np.float32) binaries = compute_binary_terms_ref(codebooks) binaries = np.ascontiguousarray(binaries) - # do icm encoding given binary and unary terms lsq = faiss.LocalSearchQuantizer(d, M, nbits) lsq.icm_encode_step(sp(new_codes), sp(unaries), sp(binaries), n, 1) - # do icm encoding given binary and unary terms in Python ref_codes = icm_encode_step_ref(unaries, binaries, codes) np.testing.assert_array_equal(new_codes, ref_codes) @@ -297,19 +279,15 @@ def test_icm_encode(self): lsq = faiss.LocalSearchQuantizer(d, M, nbits) lsq.train(x) # just for allocating memory for codebooks - # compute binary terms binaries = np.zeros((M, M, K, K)).astype(np.float32) lsq.compute_binary_terms(sp(binaries)) - # compute unary terms unaries = np.zeros((M, n, K)).astype(np.float32) lsq.compute_unary_terms(sp(x), sp(unaries), n) - # randomly generate codes codes = rs.randint(0, K, (n, M)).astype(np.int32) new_codes = codes.copy() - # do icm encoding given binary and unary terms lsq.icm_encode_step(sp(new_codes), sp(unaries), sp(binaries), n, 1) # do icm encoding without pre-computed unary and binary terms in Python @@ -378,18 +356,11 @@ def test_IndexLocalSearchQuantizer(self): np.testing.assert_array_almost_equal(Dref, D2, decimal=5) self.assertLess((Iref != I2).sum(), Iref.size * 0.01) - # test I/O - ir3 = faiss.deserialize_index(faiss.serialize_index(ir)) - D3, I3 = ir3.search(ds.get_queries(), 10) - np.testing.assert_array_equal(Iref, I3) - np.testing.assert_array_equal(Dref, D3) - def test_coarse_quantizer(self): ds = datasets.SyntheticDataset(32, 5000, 1000, 100) gt = ds.get_groundtruth(10) quantizer = faiss.LocalSearchCoarseQuantizer(ds.d, 2, 4) - quantizer.lsq.nperts quantizer.lsq.nperts = 2 index = faiss.IndexIVFFlat(quantizer, ds.d, 256) @@ -459,11 +430,8 @@ def eval_index_accuracy(self, factory_key): inters.append(inter) inters = np.array(inters) - # in fact the results should be the same for the decoding and the - # reconstructing versions self.assertTrue(np.all(inters[1:] >= inters[:-1])) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -543,7 +511,6 @@ def test_with_lsq(self): self.assertEqual(err_plsq, err_lsq) def test_lut(self): - """test compute_LUT function""" ds = datasets.SyntheticDataset(16, 1000, 0, 100) xt = ds.get_train() @@ -598,7 +565,6 @@ def eval_index_accuracy(self, index_key): D, I = index.search(ds.get_queries(), 10) inter = faiss.eval_intersection(I, ds.get_groundtruth(10)) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -610,7 +576,6 @@ def test_factory(self): AQ = faiss.AdditiveQuantizer ns, Msub, nbits = 2, 4, 8 index = faiss.index_factory(64, f"PLSQ{ns}x{Msub}x{nbits}_Nqint8") - assert isinstance(index, faiss.IndexProductLocalSearchQuantizer) self.assertEqual(index.plsq.nsplits, ns) self.assertEqual(index.plsq.subquantizer(0).M, Msub) self.assertEqual(index.plsq.subquantizer(0).nbits.at(0), nbits) @@ -639,7 +604,6 @@ def eval_index_accuracy(self, factory_key): inters = np.array(inters) self.assertTrue(np.all(inters[1:] >= inters[:-1])) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -648,14 +612,10 @@ def eval_index_accuracy(self, factory_key): return inter def test_index_accuracy(self): - self.eval_index_accuracy("IVF32,PLSQ2x2x5_Nqint8") - - @unittest.skipIf( - platform.system() == "Windows", "Does not work on Windows-2022+." - ) - def test_index_accuracy2(self): """check that the error is in the same ballpark as LSQ.""" inter1 = self.eval_index_accuracy("IVF32,PLSQ2x2x5_Nqint8") + if platform.system() == "Windows": + return # the LSQ comparison does not work on Windows-2022+ inter2 = self.eval_index_accuracy("IVF32,LSQ4x5_Nqint8") self.assertGreaterEqual(inter1 * 1.1, inter2) @@ -663,12 +623,8 @@ def test_factory(self): AQ = faiss.AdditiveQuantizer ns, Msub, nbits = 2, 4, 8 index = faiss.index_factory(64, f"IVF32,PLSQ{ns}x{Msub}x{nbits}_Nqint8") - assert isinstance(index, faiss.IndexIVFProductLocalSearchQuantizer) self.assertEqual(index.nlist, 32) self.assertEqual(index.plsq.nsplits, ns) self.assertEqual(index.plsq.subquantizer(0).M, Msub) self.assertEqual(index.plsq.subquantizer(0).nbits.at(0), nbits) self.assertEqual(index.plsq.search_type, AQ.ST_norm_qint8) - - code_size = (ns * Msub * nbits + 7) // 8 + 1 - self.assertEqual(index.plsq.code_size, code_size) diff --git a/thirdparty/faiss/tests/test_lowlevel_ivf.cpp b/thirdparty/faiss/tests/test_lowlevel_ivf.cpp index aec543af5..2e3e39b99 100644 --- a/thirdparty/faiss/tests/test_lowlevel_ivf.cpp +++ b/thirdparty/faiss/tests/test_lowlevel_ivf.cpp @@ -29,16 +29,9 @@ using namespace faiss; namespace { -// dimension of the vectors to index int d = 32; - -// nb of training vectors size_t nt = 5000; - -// size of the database points per window step size_t nb = 1000; - -// nb of queries size_t nq = 200; int k = 10; @@ -56,11 +49,12 @@ std::vector make_data(size_t n) { std::unique_ptr make_trained_index( const char* index_type, - MetricType metric_type) { + MetricType metric_type, + size_t train_nt = nt) { auto index = std::unique_ptr(index_factory(d, index_type, metric_type)); - auto xt = make_data(nt); - index->train(nt, xt.data()); + auto xt = make_data(train_nt); + index->train(train_nt, xt.data()); ParameterSpace().set_index_parameter(index.get(), "nprobe", 4); return index; } @@ -90,14 +84,16 @@ void test_get_InvertedListScanner( bool distance_to_code_supported = true, float accuracy_requirement = 1.0); -void test_lowlevel_access(const char* index_key, MetricType metric) { - std::unique_ptr index = make_trained_index(index_key, metric); +void test_lowlevel_access( + const char* index_key, + MetricType metric, + size_t train_nt = nt) { + std::unique_ptr index = + make_trained_index(index_key, metric, train_nt); auto xb = make_data(nb); index->add(nb, xb.data()); - /** handle the case if we have a preprocessor */ - const IndexPreTransform* index_pt = dynamic_cast(index.get()); @@ -159,13 +155,6 @@ void test_lowlevel_access(const char* index_key, MetricType metric) { } } - /** Test independent search - * - * Manually scans through inverted lists, computing distances and - * ordering results organized in a heap. - */ - - // sample some example queries and get reference search results. auto xq = make_data(nq); auto res = search_index(index.get(), xq.data()); @@ -191,7 +180,6 @@ void test_get_InvertedListScanner( MetricType metric, bool distance_to_code_supported, float accuracy_requirement) { - // handle preprocessing const float* xqt = xq.data(); std::unique_ptr del_xqt; @@ -202,7 +190,6 @@ void test_get_InvertedListScanner( } } - // quantize the queries to get the inverted list ids to visit. int nprobe = index_ivf->nprobe; const InvertedLists* il = index_ivf->invlists; @@ -212,7 +199,6 @@ void test_get_InvertedListScanner( index_ivf->quantizer->search(nq, xqt, nprobe, q_dis.data(), q_lists.data()); if (scanner == nullptr) { - // standard flow scanner = std::unique_ptr( index_ivf->get_InvertedListScanner()); } @@ -262,14 +248,12 @@ void test_get_InvertedListScanner( } } - // re-order heap if (metric == METRIC_L2) { maxheap_reorder(k, D.data(), I.data()); } else { minheap_reorder(k, D.data(), I.data()); } - // check that we have the same results as the reference search for (int j = 0; j < k; j++) { if (I[j] != ref_I[i * k + j]) { if (accuracy_requirement == 1.0) { @@ -298,7 +282,6 @@ void test_fastscan_scanner( IndexIVFFastScan* index_ivf = static_cast( ivflib::extract_index_ivf(index.get())); - // Set by_residual for PQ indexes if requested if (auto* pq_index = dynamic_cast(index_ivf)) { pq_index->by_residual = by_residual; } @@ -309,12 +292,9 @@ void test_fastscan_scanner( index->train(nt, xt.data()); auto xb = make_data(nb); index->add(nb, xb.data()); - // Initialize scanner with context in params so heap results can persist - // across multiple inverted list scans. auto scanner = std::unique_ptr( - index_ivf->get_InvertedListScanner(true, nullptr, nullptr)); + index_ivf->get_InvertedListScanner()); - // ref data auto xq = make_data(nq); auto res = search_index(index.get(), xq.data()); @@ -371,7 +351,12 @@ TEST(TestLowLevelIVF, IVFRaBitQ) { } TEST(TestLowLevelIVF, IVFRQ) { - test_lowlevel_access("IVF32,RQ16x8", METRIC_L2); + // ResidualQuantizer training runs one beam-search stage per + // sub-quantizer, so RQ16x8 over the full training set exceeds the + // test timeout when OpenMP is mocked out (serial) in an unoptimized + // ASan build. Eight stages over half the training points exercise + // the same encode, decode, and scanner paths. + test_lowlevel_access("IVF32,RQ8x8", METRIC_L2, 2500); } TEST(TestLowLevelIVF, IVFPQFS_L2) { @@ -422,8 +407,6 @@ namespace { int nbit = 256; -// here d is used the number of ints -> d=32 means 128 bits - std::vector make_data_binary(size_t n) { std::vector database(n * nbit / 8); std::uniform_int_distribution<> distrib; @@ -452,38 +435,25 @@ void test_lowlevel_access_binary(const char* index_key) { auto xb = make_data_binary(nb); index->add(nb, xb.data()); - std::vector list_nos(nb); - index_ivf->quantizer->assign(nb, xb.data(), list_nos.data()); - /* For binary there is no test for encoding because binary vectors * are copied verbatim to the inverted lists */ const InvertedLists* il = index_ivf->invlists; - /** Test independent search - * - * Manually scans through inverted lists, computing distances and - * ordering results organized in a heap. - */ - - // sample some example queries and get reference search results. auto xq = make_data_binary(nq); std::vector I_ref(k * nq); std::vector D_ref(k * nq); index->search(nq, xq.data(), k, D_ref.data(), I_ref.data()); - // quantize the queries to get the inverted list ids to visit. int nprobe = index_ivf->nprobe; std::vector q_lists(nq * nprobe); std::vector q_dis(nq * nprobe); - // quantize queries index_ivf->quantizer->search( nq, xq.data(), nprobe, q_dis.data(), q_lists.data()); - // object that does the scanning and distance computations. std::unique_ptr scanner( index_ivf->get_InvertedListScanner()); @@ -501,9 +471,6 @@ void test_lowlevel_access_binary(const char* index_key) { } scanner->set_list(list_no, q_dis[i * nprobe + j]); - // here we get the inverted lists from the InvertedLists - // object but they could come from anywhere - scanner->scan_codes( il->list_size(list_no), InvertedLists::ScopedCodes(il, list_no).get(), @@ -521,7 +488,6 @@ void test_lowlevel_access_binary(const char* index_key) { break; // heap is not full yet } - // we have the codes from the addition test float computed_D = scanner->distance_to_code( xb.data() + vno * il->code_size); @@ -530,14 +496,10 @@ void test_lowlevel_access_binary(const char* index_key) { } } - // re-order heap heap_reorder>(k, D.data(), I.data()); - // check that we have the same results as the reference search for (int j = 0; j < k; j++) { - // here the order is not guaranteed to be the same - // so we scan through ref results - // EXPECT_EQ (I[j], I_ref[i * k + j]); + // the order of ties is not guaranteed, so scan the ref results EXPECT_LE(D[j], D_ref[i * k + k - 1]); if (D[j] < D_ref[i * k + k - 1]) { int j2 = 0; @@ -564,53 +526,19 @@ TEST(TestLowLevelIVF, IVFBinary) { namespace { -void test_threaded_search(const char* index_key, MetricType metric) { - std::unique_ptr index = make_trained_index(index_key, metric); +void test_threaded_search(const char* index_key) { + std::unique_ptr index = make_trained_index(index_key, METRIC_L2); auto xb = make_data(nb); index->add(nb, xb.data()); - /** handle the case if we have a preprocessor */ - - const IndexPreTransform* index_pt = - dynamic_cast(index.get()); - - int dt = index->d; - const float* xbt = xb.data(); - std::unique_ptr del_xbt; - - if (index_pt) { - dt = index_pt->index->d; - xbt = index_pt->apply_chain(nb, xb.data()); - if (xbt != xb.data()) { - del_xbt.reset((float*)xbt); - } - } - IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get()); + int dt = index->d; - /** Test independent search - * - * Manually scans through inverted lists, computing distances and - * ordering results organized in a heap. - */ - - // sample some example queries and get reference search results. auto xq = make_data(nq); auto res = search_index(index.get(), xq.data()); - - // handle preprocessing const float* xqt = xq.data(); - std::unique_ptr del_xqt; - if (index_pt) { - xqt = index_pt->apply_chain(nq, xq.data()); - if (xqt != xq.data()) { - del_xqt.reset((float*)xqt); - } - } - - // quantize the queries to get the inverted list ids to visit. int nprobe = index_ivf->nprobe; std::vector q_lists(nq * nprobe); @@ -618,14 +546,11 @@ void test_threaded_search(const char* index_key, MetricType metric) { index_ivf->quantizer->search(nq, xqt, nprobe, q_dis.data(), q_lists.data()); - // now run search in this many threads int nproc = 3; for (size_t i = 0; i < nq; i++) { - // one result table per thread std::vector I(k * nproc, -1); - float default_dis = metric == METRIC_L2 ? HUGE_VAL : -HUGE_VAL; - std::vector D(k * nproc, default_dis); + std::vector D(k * nproc, HUGE_VAL); auto search_function = [index_ivf, &I, @@ -639,7 +564,6 @@ void test_threaded_search(const char* index_key, MetricType metric) { &q_lists](int rank) { const InvertedLists* il = index_ivf->invlists; - // object that does the scanning and distance computations. std::unique_ptr scanner( index_ivf->get_InvertedListScanner()); @@ -673,40 +597,22 @@ void test_threaded_search(const char* index_key, MetricType metric) { threads.emplace_back(search_function, rank); } - // join threads, merge heaps for (int rank = 0; rank < nproc; rank++) { threads[rank].join(); if (rank == 0) { - continue; // nothing to merge - } - // merge into first result - if (metric == METRIC_L2) { - maxheap_addn( - k, - D.data(), - I.data(), - D.data() + rank * k, - I.data() + rank * k, - k); - } else { - minheap_addn( - k, - D.data(), - I.data(), - D.data() + rank * k, - I.data() + rank * k, - k); + continue; } + maxheap_addn( + k, + D.data(), + I.data(), + D.data() + rank * k, + I.data() + rank * k, + k); } - // re-order heap - if (metric == METRIC_L2) { - maxheap_reorder(k, D.data(), I.data()); - } else { - minheap_reorder(k, D.data(), I.data()); - } + maxheap_reorder(k, D.data(), I.data()); - // check that we have the same results as the reference search for (int j = 0; j < k; j++) { EXPECT_EQ(I[j], res.first[i * k + j]); } @@ -716,5 +622,5 @@ void test_threaded_search(const char* index_key, MetricType metric) { } // namespace TEST(TestLowLevelIVF, ThreadedSearch) { - test_threaded_search("IVF32,Flat", METRIC_L2); + test_threaded_search("IVF32,Flat"); } diff --git a/thirdparty/faiss/tests/test_merge.cpp b/thirdparty/faiss/tests/test_merge.cpp deleted file mode 100644 index 759880edb..000000000 --- a/thirdparty/faiss/tests/test_merge.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* - * 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. - */ - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -#include "test_util.h" - -namespace { - -pthread_mutex_t temp_file_mutex = PTHREAD_MUTEX_INITIALIZER; - -using idx_t = faiss::idx_t; - -// parameters to use for the test -int d = 64; -size_t nb = 1000; -size_t nq = 100; -int nindex = 4; -int k = 10; -int nlist = 40; -int shard_size = nb / nindex; - -struct CommonData { - std::vector database; - std::vector queries; - std::vector ids; - faiss::IndexFlatL2 quantizer; - - CommonData() : database(nb * d), queries(nq * d), ids(nb), quantizer(d) { - std::mt19937 rng; - std::uniform_real_distribution<> distrib; - for (size_t i = 0; i < nb * d; i++) { - database[i] = distrib(rng); - } - for (size_t i = 0; i < nq * d; i++) { - queries[i] = distrib(rng); - } - for (size_t i = 0; i < nb; i++) { - ids[i] = 123 + 456 * i; - } - { // just to train the quantizer - faiss::IndexIVFFlat iflat(&quantizer, d, nlist); - iflat.train(nb, database.data()); - } - } -}; - -CommonData cd; -std::string temp_filename_template = "/tmp/faiss_tmp_XXXXXX"; -/// perform a search on shards, then merge and search again and -/// compare results. -int compare_merged( - faiss::IndexShards* index_shards, - bool shift_ids, - bool standard_merge = true) { - std::vector refI(k * nq); - std::vector refD(k * nq); - - index_shards->search(nq, cd.queries.data(), k, refD.data(), refI.data()); - Tempfilename filename(&temp_file_mutex, temp_filename_template); - - std::vector newI(k * nq); - std::vector newD(k * nq); - - if (standard_merge) { - for (int i = 1; i < nindex; i++) { - faiss::ivflib::merge_into( - index_shards->at(0), index_shards->at(i), shift_ids); - } - - index_shards->syncWithSubIndexes(); - } else { - std::vector lists; - faiss::IndexIVF* index0 = nullptr; - size_t ntotal = 0; - for (int i = 0; i < nindex; i++) { - auto index_ivf = - dynamic_cast(index_shards->at(i)); - assert(index_ivf); - if (i == 0) { - index0 = index_ivf; - } - lists.push_back(index_ivf->invlists); - ntotal += index_ivf->ntotal; - } - - auto il = new faiss::OnDiskInvertedLists( - index0->nlist, index0->code_size, filename.c_str()); - - il->merge_from_multiple(lists.data(), lists.size(), shift_ids); - - index0->replace_invlists(il, true); - index0->ntotal = ntotal; - } - // search only on first index - index_shards->at(0)->search( - nq, cd.queries.data(), k, newD.data(), newI.data()); - - size_t ndiff = 0; - bool adjust_ids = shift_ids && !standard_merge; - for (size_t i = 0; i < k * nq; i++) { - idx_t new_id = adjust_ids ? refI[i] % shard_size : refI[i]; - if (refI[i] != new_id) { - ndiff++; - } - } - - return ndiff; -} - -} // namespace - -// test on IVFFlat with implicit numbering -TEST(MERGE, merge_flat_no_ids) { - faiss::IndexShards index_shards(d); - index_shards.own_indices = true; - for (int i = 0; i < nindex; i++) { - index_shards.add_shard( - new faiss::IndexIVFFlat(&cd.quantizer, d, nlist)); - } - EXPECT_TRUE(index_shards.is_trained); - index_shards.add(nb, cd.database.data()); - size_t prev_ntotal = index_shards.ntotal; - int ndiff = compare_merged(&index_shards, true); - EXPECT_EQ(prev_ntotal, index_shards.ntotal); - EXPECT_EQ(0, ndiff); -} - -// test on IVFFlat, explicit ids -TEST(MERGE, merge_flat) { - faiss::IndexShards index_shards(d, false, false); - index_shards.own_indices = true; - - for (int i = 0; i < nindex; i++) { - index_shards.add_shard( - new faiss::IndexIVFFlat(&cd.quantizer, d, nlist)); - } - - EXPECT_TRUE(index_shards.is_trained); - index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data()); - int ndiff = compare_merged(&index_shards, false); - EXPECT_GE(0, ndiff); -} - -// test on IVFFlat and a VectorTransform -TEST(MERGE, merge_flat_vt) { - faiss::IndexShards index_shards(d, false, false); - index_shards.own_indices = true; - - // here we have to retrain because of the vectorTransform - faiss::RandomRotationMatrix rot(d, d); - rot.init(1234); - faiss::IndexFlatL2 quantizer(d); - - { // just to train the quantizer - faiss::IndexIVFFlat iflat(&quantizer, d, nlist); - faiss::IndexPreTransform ipt(&rot, &iflat); - ipt.train(nb, cd.database.data()); - } - - for (int i = 0; i < nindex; i++) { - faiss::IndexPreTransform* ipt = new faiss::IndexPreTransform( - new faiss::RandomRotationMatrix(rot), - new faiss::IndexIVFFlat(&quantizer, d, nlist)); - ipt->own_fields = true; - index_shards.add_shard(ipt); - } - EXPECT_TRUE(index_shards.is_trained); - index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data()); - size_t prev_ntotal = index_shards.ntotal; - int ndiff = compare_merged(&index_shards, false); - EXPECT_EQ(prev_ntotal, index_shards.ntotal); - EXPECT_GE(0, ndiff); -} - -// put the merged invfile on disk -TEST(MERGE, merge_flat_ondisk) { - faiss::IndexShards index_shards(d, false, false); - index_shards.own_indices = true; - Tempfilename filename(&temp_file_mutex, temp_filename_template); - - for (int i = 0; i < nindex; i++) { - auto ivf = new faiss::IndexIVFFlat(&cd.quantizer, d, nlist); - if (i == 0) { - auto il = new faiss::OnDiskInvertedLists( - ivf->nlist, ivf->code_size, filename.c_str()); - ivf->replace_invlists(il, true); - } - index_shards.add_shard(ivf); - } - - EXPECT_TRUE(index_shards.is_trained); - index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data()); - int ndiff = compare_merged(&index_shards, false); - - EXPECT_EQ(ndiff, 0); -} - -// now use ondisk specific merge -TEST(MERGE, merge_flat_ondisk_2) { - faiss::IndexShards index_shards(d, false, false); - index_shards.own_indices = true; - - for (int i = 0; i < nindex; i++) { - index_shards.add_shard( - new faiss::IndexIVFFlat(&cd.quantizer, d, nlist)); - } - EXPECT_TRUE(index_shards.is_trained); - index_shards.add_with_ids(nb, cd.database.data(), cd.ids.data()); - int ndiff = compare_merged(&index_shards, false, false); - EXPECT_GE(0, ndiff); -} - -// now use ondisk specific merge and use shift ids -TEST(MERGE, merge_flat_ondisk_3) { - faiss::IndexShards index_shards(d, false, false); - index_shards.own_indices = true; - - std::vector ids; - for (size_t i = 0; i < nb; ++i) { - int id = i % shard_size; - ids.push_back(id); - } - for (int i = 0; i < nindex; i++) { - index_shards.add_shard( - new faiss::IndexIVFFlat(&cd.quantizer, d, nlist)); - } - EXPECT_TRUE(index_shards.is_trained); - index_shards.add_with_ids(nb, cd.database.data(), ids.data()); - int ndiff = compare_merged(&index_shards, true, false); - EXPECT_GE(0, ndiff); -} diff --git a/thirdparty/faiss/tests/test_merge.py b/thirdparty/faiss/tests/test_merge.py new file mode 100644 index 000000000..a7a066f4d --- /dev/null +++ b/thirdparty/faiss/tests/test_merge.py @@ -0,0 +1,164 @@ +# 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. + +"""Tests for merging IVF shards.""" + +import os +import platform +import tempfile +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +d = 64 +nb = 1000 +nq = 100 +nindex = 4 +k = 10 +nlist = 40 +shard_size = nb // nindex + + +class CommonData: + def __init__(self): + rng = np.random.RandomState(123) + self.database = rng.rand(nb, d).astype(np.float32) + self.queries = rng.rand(nq, d).astype(np.float32) + self.ids = np.array( + [123 + 456 * i for i in range(nb)], dtype=np.int64) + self.quantizer = faiss.IndexFlatL2(d) + # just to train the quantizer + iflat = faiss.IndexIVFFlat(self.quantizer, d, nlist) + iflat.train(self.database) + + +def compare_merged_shards(index_shards, shift_ids, tmpdir, + standard_merge=True): + ref_D, ref_I = index_shards.search(cd.queries, k) + + if standard_merge: + for i in range(1, nindex): + faiss.merge_into( + index_shards.at(0), index_shards.at(i), shift_ids) + index_shards.syncWithSubIndexes() + else: + lists = faiss.InvertedListsPtrVector() + index0 = None + ntotal = 0 + for i in range(nindex): + index_ivf = faiss.downcast_index(index_shards.at(i)) + if i == 0: + index0 = index_ivf + lists.push_back(index_ivf.invlists) + ntotal += index_ivf.ntotal + + il = faiss.OnDiskInvertedLists( + index0.nlist, index0.code_size, + os.path.join(tmpdir, "merged.ivfdata")) + il.merge_from_multiple(lists.data(), lists.size(), shift_ids) + index0.replace_invlists(il, True) + il.this.disown() + index0.ntotal = ntotal + + new_D, new_I = index_shards.at(0).search(cd.queries, k) + + adjust_ids = shift_ids and not standard_merge + if adjust_ids: + new_I = np.fmod(new_I, shard_size) + return np.count_nonzero(ref_I != new_I) + + +cd = CommonData() + + +class TestMerge(unittest.TestCase): + def test_merge_flat_no_ids(self): + shards = [ + faiss.IndexIVFFlat(cd.quantizer, d, nlist) + for _ in range(nindex) + ] + index_shards = faiss.IndexShards(d) + index_shards.successive_ids = True + for shard in shards: + index_shards.add_shard(shard) + self.assertTrue(index_shards.is_trained) + index_shards.add(cd.database) + _, ref_I = index_shards.search(cd.queries, k) + for i in range(1, nindex): + faiss.merge_into(shards[0], shards[i], True) + _, new_I = shards[0].search(cd.queries, k) + np.testing.assert_array_equal(ref_I, new_I) + + def test_merge_flat_vt(self): + index_shards = faiss.IndexShards(d, False, False) + + rot = faiss.RandomRotationMatrix(d, d) + rot.init(1234) + quantizer = faiss.IndexFlatL2(d) + + # just to train the quantizer + iflat = faiss.IndexIVFFlat(quantizer, d, nlist) + ipt = faiss.IndexPreTransform(rot, iflat) + ipt.train(cd.database) + + for _ in range(nindex): + index_shards.add_shard(faiss.IndexPreTransform( + faiss.Cloner().clone_VectorTransform(rot), + faiss.IndexIVFFlat(quantizer, d, nlist))) + index_shards.add_with_ids(cd.database, cd.ids) + prev_ntotal = index_shards.ntotal + with tempfile.TemporaryDirectory() as tmpdir: + ndiff = compare_merged_shards(index_shards, False, tmpdir) + self.assertEqual(prev_ntotal, index_shards.ntotal) + self.assertEqual(0, ndiff) + + @unittest.skipIf( + platform.system() == "Windows", + "OnDiskInvertedLists is unsupported on Windows.", + ) + def test_merge_flat_ondisk(self): + with tempfile.TemporaryDirectory() as tmpdir: + index_shards = faiss.IndexShards(d, False, False) + for i in range(nindex): + ivf = faiss.IndexIVFFlat(cd.quantizer, d, nlist) + if i == 0: + il = faiss.OnDiskInvertedLists( + ivf.nlist, ivf.code_size, + os.path.join(tmpdir, "shard0.ivfdata")) + ivf.replace_invlists(il, True) + il.this.disown() + index_shards.add_shard(ivf) + + index_shards.add_with_ids(cd.database, cd.ids) + ndiff = compare_merged_shards(index_shards, False, tmpdir) + del index_shards, ivf, il + + self.assertEqual(0, ndiff) + + @unittest.skipIf( + platform.system() == "Windows", + "OnDiskInvertedLists is unsupported on Windows.", + ) + def test_merge_flat_ondisk_multiple(self): + for shift_ids, ids in ( + (False, cd.ids), + (True, np.arange(nb, dtype=np.int64) % shard_size), + ): + with tempfile.TemporaryDirectory() as tmpdir: + index_shards = faiss.IndexShards(d, False, False) + for _ in range(nindex): + index_shards.add_shard( + faiss.IndexIVFFlat(cd.quantizer, d, nlist)) + index_shards.add_with_ids(cd.database, ids) + ndiff = compare_merged_shards( + index_shards, shift_ids, tmpdir, standard_merge=False) + del index_shards + + self.assertEqual(0, ndiff) diff --git a/thirdparty/faiss/tests/test_merge_index.py b/thirdparty/faiss/tests/test_merge_index.py index b40ff53af..7ecaa3720 100644 --- a/thirdparty/faiss/tests/test_merge_index.py +++ b/thirdparty/faiss/tests/test_merge_index.py @@ -20,47 +20,28 @@ @for_all_simd_levels class TestMerge1(unittest.TestCase): - def make_index_for_merge(self, quant, index_type, master_index): - ncent = 40 - if index_type == 1: - index = faiss.IndexIVFFlat(quant, d, ncent, faiss.METRIC_L2) - if master_index: - index.is_trained = True - elif index_type == 2: - index = faiss.IndexIVFPQ(quant, d, ncent, 4, 8) - if master_index: - index.pq = master_index.pq - index.is_trained = True - elif index_type == 3: - index = faiss.IndexIVFPQR(quant, d, ncent, 4, 8, 8, 8) - if master_index: - index.pq = master_index.pq - index.refine_pq = master_index.refine_pq - index.is_trained = True - elif index_type == 4: - # quant used as the actual index - index = faiss.IndexIDMap(quant) + def make_index_for_merge(self, quant, master_index): + index = faiss.IndexIVFPQR(quant, d, 40, 4, 8, 8, 8) + if master_index: + index.pq = master_index.pq + index.refine_pq = master_index.refine_pq + index.is_trained = True return index - def do_test_merge(self, index_type): + def test_merge(self): k = 16 quant = faiss.IndexFlatL2(d) - ref_index = self.make_index_for_merge(quant, index_type, False) - - # trains the quantizer + ref_index = self.make_index_for_merge(quant, None) ref_index.train(xt) - - print("ref search") ref_index.add(xb) _Dref, Iref = ref_index.search(xq, k) - print(Iref[:5, :6]) indexes = [] ni = 3 for i in range(ni): i0 = int(i * nb / ni) i1 = int((i + 1) * nb / ni) - index = self.make_index_for_merge(quant, index_type, ref_index) + index = self.make_index_for_merge(quant, ref_index) index.is_trained = True index.add(xb[i0:i1]) indexes.append(index) @@ -68,93 +49,20 @@ def do_test_merge(self, index_type): index = indexes[0] for i in range(1, ni): - print( - "merge ntotal=%d other.ntotal=%d " - % (index.ntotal, indexes[i].ntotal) - ) index.merge_from(indexes[i], index.ntotal) _D, I = index.search(xq, k) ndiff = (I != Iref).sum() - print("%d / %d differences" % (ndiff, nq * k)) assert ndiff < nq * k / 1000.0 - def test_merge(self): - self.do_test_merge(1) - self.do_test_merge(2) - self.do_test_merge(3) - - ###################################### - # remove tests that piggyback on merge - - def do_test_remove(self, index_type): - k = 16 - quant = faiss.IndexFlatL2(d) - index = self.make_index_for_merge(quant, index_type, None) - - # trains the quantizer - index.train(xt) - - if index_type < 4: - index.add(xb) - else: - gen = np.random.RandomState(1234) - id_list = gen.permutation(nb * 7)[:nb].astype("int64") - index.add_with_ids(xb, id_list) - - print("ref search ntotal=%d" % index.ntotal) - Dref, Iref = index.search(xq, k) - - toremove = np.zeros(nq * k, dtype="int64") - nr = 0 - for i in range(nq): - for j in range(k): - # remove all even results (it's ok if there are duplicates - # in the list of ids) - if Iref[i, j] % 2 == 0: - nr = nr + 1 - toremove[nr] = Iref[i, j] - - print("nr=", nr) - - idsel = faiss.IDSelectorBatch(nr, faiss.swig_ptr(toremove)) - - for i in range(nr): - assert idsel.is_member(int(toremove[i])) - - nremoved = index.remove_ids(idsel) - - print("nremoved=%d ntotal=%d" % (nremoved, index.ntotal)) - D, I = index.search(xq, k) - - # make sure results are in the same order with even ones removed - ndiff = 0 - for i in range(nq): - j2 = 0 - for j in range(k): - if Iref[i, j] % 2 != 0: - if I[i, j2] != Iref[i, j]: - ndiff += 1 - assert abs(D[i, j2] - Dref[i, j]) < 1e-5 - j2 += 1 - # draws are ordered arbitrarily - assert ndiff < 5 - - def test_remove(self): - self.do_test_remove(1) - self.do_test_remove(2) - self.do_test_remove(4) - - -# Test merge_from method for all IndexFlatCodes Types @for_all_simd_levels class TestMerge2(unittest.TestCase): - def do_flat_codes_test(self, factory_key): + def test_merge_PreTransform(self): ds = SyntheticDataset(32, 300, 300, 100) - index1 = faiss.index_factory(ds.d, factory_key) + index1 = faiss.index_factory(ds.d, "PCA16,SQ4") index1.train(ds.get_train()) index1.add(ds.get_database()) _, Iref = index1.search(ds.get_queries(), 5) @@ -166,33 +74,11 @@ def do_flat_codes_test(self, factory_key): _, Inew = index1.search(ds.get_queries(), 5) np.testing.assert_array_equal(Inew, Iref) - def test_merge_IndexFlat(self): - self.do_flat_codes_test("Flat") - - def test_merge_IndexPQ(self): - self.do_flat_codes_test("PQ8np") - - def test_merge_IndexLSH(self): - self.do_flat_codes_test("LSHr") - - def test_merge_IndexScalarQuantizer(self): - self.do_flat_codes_test("SQ4") - - def test_merge_PreTransform(self): - self.do_flat_codes_test("PCA16,SQ4") - def do_fast_scan_test(self, factory_key, size1, with_add_id=False): ds = SyntheticDataset(110, 1000, 1000, 100) index_trained = faiss.index_factory(ds.d, factory_key) index_trained.train(ds.get_train()) - # test both clone and index_read/write - if True: - index1 = faiss.deserialize_index( - faiss.serialize_index(index_trained) - ) - else: - index1 = faiss.clone_index(index_trained) - # assert index1.aq.qnorm.ntotal == index_trained.aq.qnorm.ntotal + index1 = faiss.deserialize_index(faiss.serialize_index(index_trained)) index1.add(ds.get_database()) _, Iref = index1.search(ds.get_queries(), 5) @@ -216,9 +102,6 @@ def test_merge_IndexFastScan_not_complete_block(self): def test_merge_IndexFastScan_even_M(self): self.do_fast_scan_test("PQ10x4fs", 500) - def test_merge_IndexAdditiveQuantizerFastScan(self): - self.do_fast_scan_test("RQ10x4fs_32_Nrq2x4", 330) - def test_merge_IVFFastScan(self): self.do_fast_scan_test("IVF20,PQ5x4fs", 123, with_add_id=True) @@ -251,40 +134,29 @@ def test_merge_IDMap2(self): class TestRemoveFastScan(unittest.TestCase): def do_fast_scan_test( - self, factory_key, with_ids=False, direct_map_type=faiss.DirectMap.NoMap + self, factory_key, direct_map_type=faiss.DirectMap.NoMap ): ds = SyntheticDataset(110, 1000, 1000, 100) index = faiss.index_factory(ds.d, factory_key) index.train(ds.get_train()) - index.reset() tokeep = [i % 3 == 0 for i in range(ds.nb)] - if with_ids: - index.add_with_ids( - ds.get_database()[tokeep], np.arange(ds.nb)[tokeep] - ) - faiss.extract_index_ivf(index).nprobe = 5 - else: - index.add(ds.get_database()[tokeep]) + index.add_with_ids( + ds.get_database()[tokeep], np.arange(ds.nb)[tokeep] + ) + faiss.extract_index_ivf(index).nprobe = 5 _, Iref = index.search(ds.get_queries(), 5) index.reset() - if with_ids: - index.add_with_ids(ds.get_database(), np.arange(ds.nb)) - index.set_direct_map_type(direct_map_type) - faiss.extract_index_ivf(index).nprobe = 5 - else: - index.add(ds.get_database()) + index.add_with_ids(ds.get_database(), np.arange(ds.nb)) + index.set_direct_map_type(direct_map_type) + faiss.extract_index_ivf(index).nprobe = 5 index.remove_ids(np.where(np.logical_not(tokeep))[0]) _, Inew = index.search(ds.get_queries(), 5) np.testing.assert_array_equal(Inew, Iref) - def test_remove_PQFastScan(self): - # with_ids is not support for this type of index - self.do_fast_scan_test("PQ5x4fs", False) - def test_remove_IVFPQFastScan(self): - self.do_fast_scan_test("IVF20,PQ5x4fs", True) + self.do_fast_scan_test("IVF20,PQ5x4fs") def test_remove_IVFPQFastScan_2(self): self.assertRaisesRegex( @@ -292,6 +164,5 @@ def test_remove_IVFPQFastScan_2(self): ".*not supported.*", self.do_fast_scan_test, "IVF20,PQ5x4fs", - True, faiss.DirectMap.Hashtable, ) diff --git a/thirdparty/faiss/tests/test_meta_index.py b/thirdparty/faiss/tests/test_meta_index.py index 005a0640f..00b74a872 100644 --- a/thirdparty/faiss/tests/test_meta_index.py +++ b/thirdparty/faiss/tests/test_meta_index.py @@ -23,35 +23,10 @@ class IDRemap(unittest.TestCase): - def test_id_remap_idmap(self): - # reference: index without remapping - - index = faiss.IndexPQ(d, 8, 8) - k = 10 - index.train(xt) - index.add(xb) - _Dref, Iref = index.search(xq, k) - - # try a remapping - ids = np.arange(nb)[::-1].copy().astype("int64") - - sub_index = faiss.IndexPQ(d, 8, 8) - index2 = faiss.IndexIDMap(sub_index) - - index2.train(xt) - index2.add_with_ids(xb, ids) - - _D, I = index2.search(xq, k) - - assert np.all(I == nb - 1 - Iref) - def test_id_remap_ivf(self): - # coarse quantizer in common coarse_quantizer = faiss.IndexFlatIP(d) ncentroids = 25 - # reference: index without remapping - index = faiss.IndexIVFPQ(coarse_quantizer, d, ncentroids, 8, 8) index.nprobe = 5 k = 10 @@ -59,7 +34,6 @@ def test_id_remap_ivf(self): index.add(xb) _Dref, Iref = index.search(xq, k) - # try a remapping ids = np.arange(nb)[::-1].copy().astype("int64") index2 = faiss.IndexIVFPQ(coarse_quantizer, d, ncentroids, 8, 8) @@ -105,11 +79,8 @@ def test_shards(self): ref_index.add(xb) _Dref, Iref = ref_index.search(xq, k) - # Create both threaded and non-threaded shard indexes - shard_index_nonthreaded = faiss.IndexShards( - d, False - ) # explicitly non-threaded - shard_index_threaded = faiss.IndexShards(d, True) # explicitly threaded + shard_index_nonthreaded = faiss.IndexShards(d, False) + shard_index_threaded = faiss.IndexShards(d, True) shard_index_2 = faiss.IndexShards(d, True, False) self.add_flat_shards(shard_index_nonthreaded, xb) @@ -117,7 +88,6 @@ def test_shards(self): # populated below by the parallel add rather than shard by shard self.add_flat_shards(shard_index_2, None, wrap=faiss.IndexIDMap) - # test parallel add shard_index_2.verbose = True shard_index_2.add(xb) @@ -127,10 +97,8 @@ def test_shards(self): if with_threads: remember_nt = faiss.omp_get_max_threads() faiss.omp_set_num_threads(1) - # Use the threaded index test_index = shard_index_threaded else: - # Use the non-threaded index test_index = shard_index_nonthreaded if test_no != 2: @@ -210,7 +178,7 @@ def test_shards_ivf(self): ) for shard in range(3): index_i = faiss.clone_index(ref_index) - index_i.add(xb[shard * nb // 3 : (shard + 1) * nb // 3]) + index_i.add(xb[shard * ds.nb // 3 : (shard + 1) * ds.nb // 3]) sharded_index.add_shard(index_i) Dnew, Inew = sharded_index.search(ds.get_database(), 10) @@ -218,6 +186,27 @@ def test_shards_ivf(self): np.testing.assert_equal(Inew, Iref) np.testing.assert_allclose(Dnew, Dref) + def test_shards_negative_ids(self): + # Only -1 marks a missing result, so the merge keeps other negative + # ids. + ds = SyntheticDataset(32, 0, 900, 20) + xb = ds.get_database() + ids = -np.arange(1, ds.nb + 1, dtype="int64") * 1000 + ref_index = faiss.IndexIDMap(faiss.IndexFlatL2(ds.d)) + ref_index.add_with_ids(xb, ids) + Dref, Iref = ref_index.search(ds.get_queries(), 10) + + sharded_index = faiss.IndexShards(ds.d, False, False) + for shard in range(3): + index_i = faiss.IndexIDMap(faiss.IndexFlatL2(ds.d)) + sl = slice(shard * ds.nb // 3, (shard + 1) * ds.nb // 3) + index_i.add_with_ids(xb[sl], ids[sl]) + sharded_index.add_shard(index_i) + Dnew, Inew = sharded_index.search(ds.get_queries(), 10) + + np.testing.assert_equal(Inew, Iref) + np.testing.assert_allclose(Dnew, Dref, rtol=1e-5) + def test_shards_ivf_train_add(self): ds = SyntheticDataset(32, 1000, 600, 20) quantizer = faiss.IndexFlatL2(ds.d) diff --git a/thirdparty/faiss/tests/test_metal_ivfpq.py b/thirdparty/faiss/tests/test_metal_ivfpq.py new file mode 100644 index 000000000..45415fdf8 --- /dev/null +++ b/thirdparty/faiss/tests/test_metal_ivfpq.py @@ -0,0 +1,101 @@ +# 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. + +"""Regression tests for the Metal IVF-PQ search backend. + +The per-(query, probe) lookup-table path must add the coarse-quantizer score +for inner product: its tables hold only, while the CPU reference +adds dis0 = (see QueryTables::precompute_list_tables_IP). +These tests force the lookup-table path with configurations the +precomputed-table path declines, and compare GPU results against the CPU +index. +""" + +import functools +import unittest + +import numpy as np + +import faiss + + +_HAS_METAL = "MAC_METAL" in faiss.get_compile_options() +needs_metal_build = unittest.skipUnless( + _HAS_METAL, "needs a faiss Metal build" +) + + +def needs_metal_device(test_func): + @functools.wraps(test_func) + def wrapper(*args, **kwargs): + if faiss.get_num_gpus() == 0: + raise unittest.SkipTest("no Metal device available") + return test_func(*args, **kwargs) + + return wrapper + + +@needs_metal_build +class TestMetalIVFPQ(unittest.TestCase): + + def check_matches_cpu( + self, metric, d, M, nlist, nb, nq, nprobe, k + ): + rs = np.random.RandomState(1234) + xb = rs.rand(nb, d).astype(np.float32) + xq = rs.rand(nq, d).astype(np.float32) + + quantizer = ( + faiss.IndexFlatIP(d) + if metric == faiss.METRIC_INNER_PRODUCT + else faiss.IndexFlatL2(d) + ) + cpu_index = faiss.IndexIVFPQ(quantizer, d, nlist, M, 8, metric) + cpu_index.nprobe = nprobe + cpu_index.train(xb) + cpu_index.add(xb) + ref_D, ref_I = cpu_index.search(xq, k) + + res = faiss.StandardGpuResources() + gpu_index = faiss.index_cpu_to_gpu(res, 0, cpu_index) + got_D, got_I = gpu_index.search(xq, k) + + for q in range(nq): + valid = ref_I[q] != -1 + self.assertTrue(np.any(valid)) + self.assertEqual(set(got_I[q][valid]), set(ref_I[q][valid])) + np.testing.assert_allclose( + got_D[q][valid], ref_D[q][valid], atol=1e-2 + ) + + @needs_metal_device + def test_lookup_table_path_ip_large_k(self): + # k > 512 declines the precomputed-table path. With nprobe == 1 the + # missing coarse term keeps the ranking but shifts every score. + self.check_matches_cpu( + faiss.METRIC_INNER_PRODUCT, + d=64, + M=8, + nlist=8, + nb=500, + nq=5, + nprobe=1, + k=600, + ) + + @needs_metal_device + def test_lookup_table_path_l2_large_k(self): + # L2 tables hold the complete residual distance, so the coarse term + # must stay off: guard the flag plumbing in both directions. + self.check_matches_cpu( + faiss.METRIC_L2, + d=64, + M=8, + nlist=8, + nb=500, + nq=5, + nprobe=1, + k=600, + ) diff --git a/thirdparty/faiss/tests/test_mmap.cpp b/thirdparty/faiss/tests/test_mmap.cpp deleted file mode 100644 index ff16af9fb..000000000 --- a/thirdparty/faiss/tests/test_mmap.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* - * 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. - */ - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace { - -#if defined(_WIN32) || defined(__linux__) || defined(__FreeBSD__) || \ - defined(__APPLE__) -constexpr bool kMmapIFCSupported = true; -#else -constexpr bool kMmapIFCSupported = false; -#endif - -std::vector make_data(const size_t n, const size_t d, size_t seed) { - std::vector database(n * d); - std::mt19937 rng(seed); - std::uniform_real_distribution distrib; - - for (size_t i = 0; i < n * d; i++) { - database[i] = distrib(rng); - } - return database; -} - -std::vector make_binary_data( - const size_t n, - const size_t d, - size_t seed) { - std::vector database(n * d); - std::mt19937 rng(seed); - std::uniform_int_distribution distrib(0, 255); - - for (size_t i = 0; i < n * d; i++) { - database[i] = distrib(rng); - } - return database; -} - -} // namespace - -// the logic is the following: -// 1. generate two flatcodes-based indices, Index1 and Index2 -// 2. serialize both indices into std::vector<> buffers, Buf1 and Buf2 -// 3. save Buf1 into a temporary file, File1 -// 4. deserialize Index1 using mmap feature on File1 into Index1MM -// 5. ensure that Index1MM acts as Index2 if we write the data from Buf2 -// on top of the existing File1 -// 6. ensure that Index1MM acts as Index1 if we write the data from Buf1 -// on top of the existing File1 again - -TEST(TestMmap, mmap_flatcodes) { - if (!kMmapIFCSupported) { - GTEST_SKIP() << "Skipping test on unsupported platform."; - } - // generate data - const size_t nt = 1000; - const size_t nq = 10; - const size_t d = 32; - const size_t k = 25; - - std::vector xt1 = make_data(nt, d, 123); - std::vector xt2 = make_data(nt, d, 456); - std::vector xq = make_data(nq, d, 789); - - // ensure that the data is different - ASSERT_NE(xt1, xt2); - - // make index1 and create reference results - faiss::IndexFlatL2 index1(d); - index1.train(nt, xt1.data()); - index1.add(nt, xt1.data()); - - std::vector ref_dis_1(k * nq); - std::vector ref_ids_1(k * nq); - index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data()); - - // make index2 and create reference results - faiss::IndexFlatL2 index2(d); - index2.train(nt, xt2.data()); - index2.add(nt, xt2.data()); - - std::vector ref_dis_2(k * nq); - std::vector ref_ids_2(k * nq); - index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data()); - - // ensure that the results are different - ASSERT_NE(ref_dis_1, ref_dis_2); - ASSERT_NE(ref_ids_1, ref_ids_2); - - // serialize both in a form of vectors - faiss::VectorIOWriter wr1; - faiss::write_index(&index1, &wr1); - - faiss::VectorIOWriter wr2; - faiss::write_index(&index2, &wr2); - - // generate a temporary file and write index1 into it - std::string tmpname = std::tmpnam(nullptr); - - { - std::ofstream ofs(tmpname); - ofs.write((const char*)wr1.data.data(), wr1.data.size()); - } - - // create a mmap index - auto index1mm = - faiss::read_index_up(tmpname.c_str(), faiss::IO_FLAG_MMAP_IFC); - - ASSERT_NE(index1mm, nullptr); - - // perform a search - std::vector cand_dis_1(k * nq); - std::vector cand_ids_1(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_1); - ASSERT_EQ(ref_dis_1, cand_dis_1); - - // ok now, overwrite the internals of the file without recreating it - { - std::ofstream ofs(tmpname); - ofs.seekp(0, std::ios::beg); - - ofs.write((const char*)wr2.data.data(), wr2.data.size()); - } - - // perform a search - std::vector cand_dis_2(k * nq); - std::vector cand_ids_2(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_2, cand_ids_2); - ASSERT_EQ(ref_dis_2, cand_dis_2); - - // write back data1 - { - std::ofstream ofs(tmpname); - ofs.seekp(0, std::ios::beg); - - ofs.write((const char*)wr1.data.data(), wr1.data.size()); - } - - // perform a search - std::vector cand_dis_3(k * nq); - std::vector cand_ids_3(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_3); - ASSERT_EQ(ref_dis_1, cand_dis_3); -} - -TEST(TestMmap, mmap_binary_flatcodes) { - if (!kMmapIFCSupported) { - GTEST_SKIP() << "Skipping test on unsupported platform."; - } - // generate data - const size_t nt = 1000; - const size_t nq = 10; - // in bits - const size_t d = 64; - // in bytes - const size_t d8 = (d + 7) / 8; - const size_t k = 25; - - std::vector xt1 = make_binary_data(nt, d8, 123); - std::vector xt2 = make_binary_data(nt, d8, 456); - std::vector xq = make_binary_data(nq, d8, 789); - - // ensure that the data is different - ASSERT_NE(xt1, xt2); - - // make index1 and create reference results - faiss::IndexBinaryFlat index1(d); - index1.train(nt, xt1.data()); - index1.add(nt, xt1.data()); - - std::vector ref_dis_1(k * nq); - std::vector ref_ids_1(k * nq); - index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data()); - - // make index2 and create reference results - faiss::IndexBinaryFlat index2(d); - index2.train(nt, xt2.data()); - index2.add(nt, xt2.data()); - - std::vector ref_dis_2(k * nq); - std::vector ref_ids_2(k * nq); - index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data()); - - // ensure that the results are different - ASSERT_NE(ref_dis_1, ref_dis_2); - ASSERT_NE(ref_ids_1, ref_ids_2); - - // serialize both in a form of vectors - faiss::VectorIOWriter wr1; - faiss::write_index_binary(&index1, &wr1); - - faiss::VectorIOWriter wr2; - faiss::write_index_binary(&index2, &wr2); - - // generate a temporary file and write index1 into it - std::string tmpname = std::tmpnam(nullptr); - - { - std::ofstream ofs(tmpname); - ofs.write((const char*)wr1.data.data(), wr1.data.size()); - } - - // create a mmap index - auto index1mm = faiss::read_index_binary_up( - tmpname.c_str(), faiss::IO_FLAG_MMAP_IFC); - - ASSERT_NE(index1mm, nullptr); - - // perform a search - std::vector cand_dis_1(k * nq); - std::vector cand_ids_1(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_1); - ASSERT_EQ(ref_dis_1, cand_dis_1); - - // ok now, overwrite the internals of the file without recreating it - { - std::ofstream ofs(tmpname); - ofs.seekp(0, std::ios::beg); - - ofs.write((const char*)wr2.data.data(), wr2.data.size()); - } - - // perform a search - std::vector cand_dis_2(k * nq); - std::vector cand_ids_2(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_2, cand_ids_2); - ASSERT_EQ(ref_dis_2, cand_dis_2); - - // write back data1 - { - std::ofstream ofs(tmpname); - ofs.seekp(0, std::ios::beg); - - ofs.write((const char*)wr1.data.data(), wr1.data.size()); - } - - // perform a search - std::vector cand_dis_3(k * nq); - std::vector cand_ids_3(k * nq); - index1mm->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_3); - ASSERT_EQ(ref_dis_1, cand_dis_3); -} diff --git a/thirdparty/faiss/tests/test_mmap.py b/thirdparty/faiss/tests/test_mmap.py new file mode 100644 index 000000000..2eb38f3bc --- /dev/null +++ b/thirdparty/faiss/tests/test_mmap.py @@ -0,0 +1,128 @@ +# 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 os +import sys +import tempfile +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + +# The tests rewrite a file while it is memory-mapped. Windows does not permit +# that. +MMAP_IFC_SUPPORTED = sys.platform.startswith(("linux", "freebsd", "darwin")) + + +def make_data(n, d, seed): + rs = np.random.RandomState(seed) + return rs.rand(n, d).astype(np.float32) + + +def make_binary_data(n, d, seed): + rs = np.random.RandomState(seed) + return rs.randint(0, 256, size=(n, d)).astype(np.uint8) + + +class TestMmap(unittest.TestCase): + def test_mmap_flatcodes(self): + if not MMAP_IFC_SUPPORTED: + self.skipTest("Skipping test on unsupported platform.") + nt = 1000 + nq = 10 + d = 32 + k = 25 + + xt1 = make_data(nt, d, 123) + xt2 = make_data(nt, d, 456) + xq = make_data(nq, d, 789) + + index1 = faiss.IndexFlatL2(d) + index1.add(xt1) + ref_dis_1, ref_ids_1 = index1.search(xq, k) + + index2 = faiss.IndexFlatL2(d) + index2.add(xt2) + ref_dis_2, ref_ids_2 = index2.search(xq, k) + + self.assertFalse(np.array_equal(ref_dis_1, ref_dis_2)) + self.assertFalse(np.array_equal(ref_ids_1, ref_ids_2)) + + with tempfile.TemporaryDirectory() as tmpdir: + f1 = os.path.join(tmpdir, "index1.faiss") + f2 = os.path.join(tmpdir, "index2.faiss") + fmm = os.path.join(tmpdir, "indexmm.faiss") + faiss.write_index(index1, f1) + faiss.write_index(index2, f2) + with open(f1, "rb") as f: + buf1 = f.read() + with open(f2, "rb") as f: + buf2 = f.read() + with open(fmm, "wb") as f: + f.write(buf1) + + index1mm = faiss.read_index(fmm, faiss.IO_FLAG_MMAP_IFC) + + cand_dis_1, cand_ids_1 = index1mm.search(xq, k) + np.testing.assert_array_equal(ref_ids_1, cand_ids_1) + np.testing.assert_array_equal(ref_dis_1, cand_dis_1) + + with open(fmm, "wb") as f: + f.write(buf2) + cand_dis_2, cand_ids_2 = index1mm.search(xq, k) + np.testing.assert_array_equal(ref_ids_2, cand_ids_2) + np.testing.assert_array_equal(ref_dis_2, cand_dis_2) + + def test_mmap_binary_flatcodes(self): + if not MMAP_IFC_SUPPORTED: + self.skipTest("Skipping test on unsupported platform.") + nt = 1000 + nq = 10 + d = 64 + d8 = (d + 7) // 8 + k = 25 + + xt1 = make_binary_data(nt, d8, 123) + xt2 = make_binary_data(nt, d8, 456) + xq = make_binary_data(nq, d8, 789) + + index1 = faiss.IndexBinaryFlat(d) + index1.add(xt1) + ref_dis_1, ref_ids_1 = index1.search(xq, k) + + index2 = faiss.IndexBinaryFlat(d) + index2.add(xt2) + ref_dis_2, ref_ids_2 = index2.search(xq, k) + + self.assertFalse(np.array_equal(ref_dis_1, ref_dis_2)) + self.assertFalse(np.array_equal(ref_ids_1, ref_ids_2)) + + with tempfile.TemporaryDirectory() as tmpdir: + f1 = os.path.join(tmpdir, "index1.faiss") + f2 = os.path.join(tmpdir, "index2.faiss") + fmm = os.path.join(tmpdir, "indexmm.faiss") + faiss.write_index_binary(index1, f1) + faiss.write_index_binary(index2, f2) + with open(f1, "rb") as f: + buf1 = f.read() + with open(f2, "rb") as f: + buf2 = f.read() + with open(fmm, "wb") as f: + f.write(buf1) + + index1mm = faiss.read_index_binary(fmm, faiss.IO_FLAG_MMAP_IFC) + + cand_dis_1, cand_ids_1 = index1mm.search(xq, k) + np.testing.assert_array_equal(ref_ids_1, cand_ids_1) + np.testing.assert_array_equal(ref_dis_1, cand_dis_1) + + with open(fmm, "wb") as f: + f.write(buf2) + cand_dis_2, cand_ids_2 = index1mm.search(xq, k) + np.testing.assert_array_equal(ref_ids_2, cand_ids_2) + np.testing.assert_array_equal(ref_dis_2, cand_dis_2) diff --git a/thirdparty/faiss/tests/test_nndescent.cpp b/thirdparty/faiss/tests/test_nndescent.cpp index 4c78978ac..435bb0c4b 100644 --- a/thirdparty/faiss/tests/test_nndescent.cpp +++ b/thirdparty/faiss/tests/test_nndescent.cpp @@ -11,7 +11,6 @@ using namespace faiss::nndescent; -/// Helper: build a Nhood with known data in all fields. static Nhood make_populated_nhood() { std::mt19937 rng(42); int N = 200; diff --git a/thirdparty/faiss/tests/test_omp_exception_safety.cpp b/thirdparty/faiss/tests/test_omp_exception_safety.cpp index a34cd9ae1..ef45e781e 100644 --- a/thirdparty/faiss/tests/test_omp_exception_safety.cpp +++ b/thirdparty/faiss/tests/test_omp_exception_safety.cpp @@ -71,15 +71,13 @@ struct ThrowingInvertedLists : InvertedLists { } }; -// InterruptCallback that always signals an interrupt. struct AlwaysInterrupt : InterruptCallback { bool want_interrupt() override { return true; } }; -// Build a trained IndexIVFFlat with data added, using enough vectors and -// lists to exercise multi-threaded parallel modes. +// Enough vectors and lists to exercise multi-threaded parallel modes. struct IVFFixture { static constexpr int d = 8; static constexpr int nb = 2000; @@ -113,9 +111,6 @@ struct IVFFixture { } } - // Swap in a ThrowingInvertedLists that delegates to the real one. - // Returns the throwing wrapper. The real inverted lists is kept alive - // (disowned from the index) so the delegate pointer stays valid. std::unique_ptr install_throwing(int throw_after) { auto* real = index.invlists; auto throwing = @@ -126,7 +121,6 @@ struct IVFFixture { return throwing; } - // Restore the original inverted lists (the delegate from the wrapper). void restore(const ThrowingInvertedLists& throwing) { index.replace_invlists( const_cast(throwing.delegate), true); @@ -135,9 +129,6 @@ struct IVFFixture { } // namespace -// --------------------------------------------------------------------------- -// search_preassigned: exception in scan_one_list, pmode 0 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, search_preassigned_pmode0) { IVFFixture f; f.index.parallel_mode = 0; @@ -156,9 +147,6 @@ TEST(OMPExceptionSafety, search_preassigned_pmode0) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// search_preassigned: exception in scan_one_list, pmode 1 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, search_preassigned_pmode1) { IVFFixture f; f.index.parallel_mode = 1; @@ -177,9 +165,6 @@ TEST(OMPExceptionSafety, search_preassigned_pmode1) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// search_preassigned: exception in scan_one_list, pmode 2 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, search_preassigned_pmode2) { IVFFixture f; f.index.parallel_mode = 2; @@ -198,9 +183,6 @@ TEST(OMPExceptionSafety, search_preassigned_pmode2) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// search_preassigned: InterruptCallback::check() throws inside pmode 0 loop -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, search_interrupt_pmode0) { IVFFixture f; f.index.parallel_mode = 0; @@ -219,9 +201,6 @@ TEST(OMPExceptionSafety, search_interrupt_pmode0) { InterruptCallback::clear_instance(); } -// --------------------------------------------------------------------------- -// range_search_preassigned: exception in scan_list_func, pmode 0 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, range_search_pmode0) { IVFFixture f; f.index.parallel_mode = 0; @@ -241,9 +220,6 @@ TEST(OMPExceptionSafety, range_search_pmode0) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// range_search_preassigned: exception in scan_list_func, pmode 1 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, range_search_pmode1) { IVFFixture f; f.index.parallel_mode = 1; @@ -263,9 +239,6 @@ TEST(OMPExceptionSafety, range_search_pmode1) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// range_search_preassigned: exception in scan_list_func, pmode 2 -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, range_search_pmode2) { IVFFixture f; f.index.parallel_mode = 2; @@ -285,28 +258,6 @@ TEST(OMPExceptionSafety, range_search_pmode2) { f.restore(*throwing); } -// --------------------------------------------------------------------------- -// search (top-level OMP slicing): exception propagates from sub_search_func -// --------------------------------------------------------------------------- -TEST(OMPExceptionSafety, search_top_level_omp_slicing) { - IVFFixture f; - f.index.parallel_mode = 0; - f.index.nprobe = 4; - - // Allow a few successful calls so some slices start, then fail. - auto throwing = f.install_throwing(5); - - idx_t k = 4; - std::vector dis(f.nq * k); - std::vector labels(f.nq * k); - - EXPECT_THROW( - f.index.search(f.nq, f.xq.data(), k, dis.data(), labels.data()), - FaissException); - - f.restore(*throwing); -} - // Minimal IndexFlatCodes subclass whose sa_decode always throws, to // verify that exceptions thrown inside the OpenMP parallel region in // IndexFlatCodes::search are propagated to the caller. @@ -324,9 +275,6 @@ struct ThrowingIndex : IndexFlatCodes { } }; -// --------------------------------------------------------------------------- -// IndexFlatCodes::search: exception in OMP worker propagates to caller -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, flatcodes_search) { ThrowingIndex index(4); @@ -339,11 +287,6 @@ TEST(OMPExceptionSafety, flatcodes_search) { std::runtime_error); } -// --------------------------------------------------------------------------- -// IndexNNDescent::search: exception in OMP worker propagates to caller. -// Constructing with has_built=false triggers a FaissException inside the -// worksharing loop body. -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, nndescent_search) { int d = 4; auto storage = std::make_unique(d); @@ -363,9 +306,6 @@ TEST(OMPExceptionSafety, nndescent_search) { FaissException); } -// --------------------------------------------------------------------------- -// IndexNSG::search: exception in OMP worker propagates to caller -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, nsg_search) { int d = 4; auto storage = std::make_unique(d); @@ -463,9 +403,6 @@ struct HNSWFixture { } }; -// --------------------------------------------------------------------------- -// hnsw_search() init-phase throw: storage_distance_computer() throws -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, hnsw_search_init) { HNSWFixture f; auto throwing = std::make_unique(f.d); @@ -482,9 +419,6 @@ TEST(OMPExceptionSafety, hnsw_search_init) { f.restore_storage(old); } -// --------------------------------------------------------------------------- -// hnsw_search() loop-body throw: set_query() throws -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, hnsw_search_loop) { HNSWFixture f; auto throwing = std::make_unique(f.d); @@ -501,9 +435,6 @@ TEST(OMPExceptionSafety, hnsw_search_loop) { f.restore_storage(old); } -// --------------------------------------------------------------------------- -// search_level_0() init-phase throw: storage_distance_computer() throws -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, hnsw_search_level_0_init) { HNSWFixture f; auto throwing = std::make_unique(f.d); @@ -533,9 +464,6 @@ TEST(OMPExceptionSafety, hnsw_search_level_0_init) { f.restore_storage(old); } -// --------------------------------------------------------------------------- -// search_level_0() loop-body throw: set_query() throws -// --------------------------------------------------------------------------- TEST(OMPExceptionSafety, hnsw_search_level_0_loop) { HNSWFixture f; auto throwing = std::make_unique(f.d); @@ -630,11 +558,7 @@ struct HNSW2LevelFixture { } }; -// --------------------------------------------------------------------------- -// IndexHNSW2Level::search() mixed path init-phase throw: -// storage_distance_computer() throws during OMP init, after -// search_preassigned has already succeeded. -// --------------------------------------------------------------------------- +// Throws in the OMP init phase, after search_preassigned has succeeded. TEST(OMPExceptionSafety, hnsw_2level_mixed_init) { HNSW2LevelFixture f; @@ -676,11 +600,7 @@ TEST(OMPExceptionSafety, hnsw_2level_mixed_init) { f.index.own_fields = true; } -// --------------------------------------------------------------------------- -// IndexHNSW2Level::search() mixed path loop-body throw: -// set_query() throws inside OMP for loop, after search_preassigned -// and OMP init have succeeded. -// --------------------------------------------------------------------------- +// Throws in the OMP loop body, after search_preassigned and OMP init succeeded. TEST(OMPExceptionSafety, hnsw_2level_mixed_loop) { HNSW2LevelFixture f; diff --git a/thirdparty/faiss/tests/test_omp_threads.cpp b/thirdparty/faiss/tests/test_omp_threads.cpp deleted file mode 100644 index 1249b8835..000000000 --- a/thirdparty/faiss/tests/test_omp_threads.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* - * 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. - */ - -#include - -#include - -TEST(Threading, openmp) { - EXPECT_TRUE(faiss::check_openmp()); -} diff --git a/thirdparty/faiss/tests/test_omp_threads_py.py b/thirdparty/faiss/tests/test_omp_threads_py.py index e969dd39d..7086097e0 100644 --- a/thirdparty/faiss/tests/test_omp_threads_py.py +++ b/thirdparty/faiss/tests/test_omp_threads_py.py @@ -3,13 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import ( - absolute_import, - division, - print_function, - unicode_literals, -) - import faiss import unittest diff --git a/thirdparty/faiss/tests/test_ondisk_ivf.cpp b/thirdparty/faiss/tests/test_ondisk_ivf.cpp index 13f10dc5d..4f9fae15d 100644 --- a/thirdparty/faiss/tests/test_ondisk_ivf.cpp +++ b/thirdparty/faiss/tests/test_ondisk_ivf.cpp @@ -12,7 +12,6 @@ #include #include -#include #include @@ -37,7 +36,7 @@ struct Tempfilename { } ~Tempfilename() { - if (access(filename.c_str(), F_OK)) { + if (access(filename.c_str(), F_OK) == 0) { unlink(filename.c_str()); } } @@ -51,48 +50,6 @@ pthread_mutex_t Tempfilename::mutex = PTHREAD_MUTEX_INITIALIZER; } // namespace -TEST(ONDISK, make_invlists) { - int nlist = 100; - int code_size = 32; - int nadd = 1000000; - std::unordered_map listnos; - - Tempfilename filename; - - faiss::OnDiskInvertedLists ivf(nlist, code_size, filename.c_str()); - - { - std::vector code(32); - std::mt19937 rng; - std::uniform_real_distribution<> distrib; - for (int i = 0; i < nadd; i++) { - double d = distrib(rng); - int list_no = int(nlist * d * d); // skewed distribution - int* ar = (int*)code.data(); - ar[0] = i; - ar[1] = list_no; - ivf.add_entry(list_no, i, code.data()); - listnos[i] = list_no; - } - } - - int ntot = 0; - for (int i = 0; i < nlist; i++) { - int size = ivf.list_size(i); - const faiss::idx_t* ids = ivf.get_ids(i); - const uint8_t* codes = ivf.get_codes(i); - for (int j = 0; j < size; j++) { - faiss::idx_t id = ids[j]; - const int* ar = (const int*)&codes[code_size * j]; - EXPECT_EQ(ar[0], id); - EXPECT_EQ(ar[1], i); - EXPECT_EQ(listnos[id], i); - ntot++; - } - } - EXPECT_EQ(ntot, nadd); -} - TEST(ONDISK, test_add) { int d = 8; int nlist = 30, nq = 200, nb = 1500, k = 10; @@ -108,7 +65,7 @@ TEST(ONDISK, test_add) { faiss::IndexIVFFlat index(&quantizer, d, nlist); index.add(nb, xb.data()); - std::vector xq(d * nb); + std::vector xq(d * nq); faiss::float_rand(xq.data(), d * nq, 34567); std::vector ref_D(nq * k); @@ -118,7 +75,6 @@ TEST(ONDISK, test_add) { Tempfilename filename, filename2; - // test add + search { faiss::IndexIVFFlat index2(&quantizer, d, nlist); @@ -140,7 +96,6 @@ TEST(ONDISK, test_add) { write_index(&index2, filename2.c_str()); } - // test io { faiss::Index* index3 = faiss::read_index(filename2.c_str()); diff --git a/thirdparty/faiss/tests/test_pairs_decoding.cpp b/thirdparty/faiss/tests/test_pairs_decoding.cpp deleted file mode 100644 index 7a0696aa5..000000000 --- a/thirdparty/faiss/tests/test_pairs_decoding.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* - * 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. - */ - -#include -#include - -#include -#include -#include - -#include - -#include -#include -#include -#include - -namespace { - -using idx_t = faiss::idx_t; - -/************************************************************* - * Test utils - *************************************************************/ - -// dimension of the vectors to index -int d = 64; - -// size of the database we plan to index -size_t nb = 8000; - -// nb of queries -size_t nq = 200; - -std::mt19937 rng; - -std::vector make_data(size_t n) { - std::vector database(n * d); - std::uniform_real_distribution<> distrib; - for (size_t i = 0; i < n * d; i++) { - database[i] = distrib(rng); - } - return database; -} - -std::unique_ptr make_index( - const char* index_type, - const std::vector& x) { - auto index = - std::unique_ptr(faiss::index_factory(d, index_type)); - index->train(nb, x.data()); - index->add(nb, x.data()); - return index; -} - -/************************************************************* - * Test functions for a given index type - *************************************************************/ - -bool test_search_centroid(const char* index_key) { - std::vector xb = make_data(nb); // database vectors - auto index = make_index(index_key, xb); - - /* First test: find the centroids associated to the database - vectors and make sure that each vector does indeed appear in - the inverted list corresponding to its centroid */ - - std::vector centroid_ids(nb); - faiss::ivflib::search_centroid( - index.get(), xb.data(), nb, centroid_ids.data()); - - const faiss::IndexIVF* ivf = faiss::ivflib::extract_index_ivf(index.get()); - - for (size_t i = 0; i < nb; i++) { - bool found = false; - int list_no = centroid_ids[i]; - int list_size = ivf->invlists->list_size(list_no); - auto* list = ivf->invlists->get_ids(list_no); - - for (int j = 0; j < list_size; j++) { - if (list[j] == static_cast(i)) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - return true; -} - -int test_search_and_return_centroids(const char* index_key) { - std::vector xb = make_data(nb); // database vectors - auto index = make_index(index_key, xb); - - std::vector centroid_ids(nb); - faiss::ivflib::search_centroid( - index.get(), xb.data(), nb, centroid_ids.data()); - - faiss::IndexIVF* ivf = faiss::ivflib::extract_index_ivf(index.get()); - ivf->nprobe = 4; - - std::vector xq = make_data(nq); // database vectors - - int k = 5; - - // compute a reference search result - - std::vector refI(nq * k); - std::vector refD(nq * k); - index->search(nq, xq.data(), k, refD.data(), refI.data()); - - // compute search result - - std::vector newI(nq * k); - std::vector newD(nq * k); - - std::vector query_centroid_ids(nq); - std::vector result_centroid_ids(nq * k); - - faiss::ivflib::search_and_return_centroids( - index.get(), - nq, - xq.data(), - k, - newD.data(), - newI.data(), - query_centroid_ids.data(), - result_centroid_ids.data()); - - // first verify that we have the same result as the standard search - - if (newI != refI) { - return 1; - } - - // then check if the result ids are indeed in the inverted list - // they are supposed to be in - - for (size_t i = 0; i < nq * k; i++) { - int list_no = result_centroid_ids[i]; - int result_no = newI[i]; - - if (result_no < 0) { - continue; - } - - bool found = false; - - int list_size = ivf->invlists->list_size(list_no); - auto* list = ivf->invlists->get_ids(list_no); - - for (int j = 0; j < list_size; j++) { - if (list[j] == result_no) { - found = true; - break; - } - } - if (!found) { - return 2; - } - } - return 0; -} - -} // namespace - -/************************************************************* - * Test entry points - *************************************************************/ - -TEST(testSearchCentroid, IVFFlat) { - bool ok = test_search_centroid("IVF32,Flat"); - EXPECT_TRUE(ok); -} - -TEST(testSearchCentroid, PCAIVFFlat) { - bool ok = test_search_centroid("PCA16,IVF32,Flat"); - EXPECT_TRUE(ok); -} - -TEST(testSearchAndReturnCentroids, IVFFlat) { - int err = test_search_and_return_centroids("IVF32,Flat"); - EXPECT_NE(err, 1); - EXPECT_NE(err, 2); -} - -TEST(testSearchAndReturnCentroids, PCAIVFFlat) { - int err = test_search_and_return_centroids("PCA16,IVF32,Flat"); - EXPECT_NE(err, 1); - EXPECT_NE(err, 2); -} diff --git a/thirdparty/faiss/tests/test_pairs_decoding.py b/thirdparty/faiss/tests/test_pairs_decoding.py new file mode 100644 index 000000000..3c2cd8958 --- /dev/null +++ b/thirdparty/faiss/tests/test_pairs_decoding.py @@ -0,0 +1,91 @@ +# 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 unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + +d = 64 +nb = 8000 +nq = 200 + +rs = np.random.RandomState(0) + + +def make_data(n): + return rs.rand(n, d).astype(np.float32) + + +def make_index(index_key, x): + index = faiss.index_factory(d, index_key) + index.train(x) + index.add(x) + return index + + +class TestPairsDecoding(unittest.TestCase): + def check_pairs_decoding(self, index_key): + xb = make_data(nb) + index = make_index(index_key, xb) + + centroid_ids = np.empty(nb, dtype=np.int64) + faiss.search_centroid( + index, faiss.swig_ptr(xb), nb, faiss.swig_ptr(centroid_ids) + ) + + ivf = faiss.extract_index_ivf(index) + for i in range(nb): + list_no = int(centroid_ids[i]) + ids = faiss.rev_swig_ptr( + ivf.invlists.get_ids(list_no), + ivf.invlists.list_size(list_no), + ) + self.assertIn(i, set(ids.tolist())) + + ivf.nprobe = 4 + + xq = make_data(nq) + k = 5 + + _refD, refI = index.search(xq, k) + + newD = np.empty((nq, k), dtype=np.float32) + newI = np.empty((nq, k), dtype=np.int64) + query_centroid_ids = np.empty(nq, dtype=np.int64) + result_centroid_ids = np.empty(nq * k, dtype=np.int64) + faiss.search_and_return_centroids( + index, + nq, + faiss.swig_ptr(xq), + k, + faiss.swig_ptr(newD), + faiss.swig_ptr(newI), + faiss.swig_ptr(query_centroid_ids), + faiss.swig_ptr(result_centroid_ids), + ) + + np.testing.assert_array_equal(newI, refI) + + flatI = newI.reshape(-1) + for i in range(nq * k): + result_no = int(flatI[i]) + if result_no < 0: + continue + list_no = int(result_centroid_ids[i]) + ids = faiss.rev_swig_ptr( + ivf.invlists.get_ids(list_no), + ivf.invlists.list_size(list_no), + ) + self.assertIn(result_no, set(ids.tolist())) + + def test_ivf_flat(self): + self.check_pairs_decoding("IVF32,Flat") + + def test_pca_ivf_flat(self): + self.check_pairs_decoding("PCA16,IVF32,Flat") diff --git a/thirdparty/faiss/tests/test_params_override.cpp b/thirdparty/faiss/tests/test_params_override.cpp index b645442b1..5ec050c6e 100644 --- a/thirdparty/faiss/tests/test_params_override.cpp +++ b/thirdparty/faiss/tests/test_params_override.cpp @@ -14,14 +14,10 @@ #include -#include #include -#include #include #include #include -#include -#include #include #include @@ -29,13 +25,8 @@ using namespace faiss; namespace { -// dimension of the vectors to index int d = 32; - -// size of the database we plan to index size_t nb = 1000; - -// nb of queries size_t nq = 200; std::mt19937 rng; @@ -61,14 +52,6 @@ std::unique_ptr make_index( return index; } -std::vector search_index(Index* index, const float* xq) { - int k = 10; - std::vector I(k * nq); - std::vector D(k * nq); - index->search(nq, xq, k, D.data(), I.data()); - return I; -} - std::vector search_index_with_params( Index* index, const float* xq, @@ -81,121 +64,12 @@ std::vector search_index_with_params( return I; } -/************************************************************* - * Test functions for a given index type - *************************************************************/ - -int test_params_override(const char* index_key, MetricType metric) { - std::vector xb = make_data(nb); // database vectors - auto index = make_index(index_key, metric, xb); - // index->train(nb, xb.data()); - // index->add(nb, xb.data()); - std::vector xq = make_data(nq); - ParameterSpace ps; - ps.set_index_parameter(index.get(), "nprobe", 2); - auto res2ref = search_index(index.get(), xq.data()); - ps.set_index_parameter(index.get(), "nprobe", 9); - auto res9ref = search_index(index.get(), xq.data()); - ps.set_index_parameter(index.get(), "nprobe", 1); - - IVFSearchParameters params; - params.max_codes = 0; - params.nprobe = 2; - auto res2new = search_index_with_params(index.get(), xq.data(), ¶ms); - params.nprobe = 9; - auto res9new = search_index_with_params(index.get(), xq.data(), ¶ms); - - if (res2ref != res2new) { - return 2; - } - - if (res9ref != res9new) { - return 9; - } - - return 0; -} - -/************************************************************* - * Test subsets - *************************************************************/ - -/************************************************************* - * Test ensure_topk_full behavior - *************************************************************/ - -// With a tight max_codes budget the default search (ensure_topk_full=false) -// should truncate results, yielding -1 placeholders. With ensure_topk_full=true -// the same budget becomes soft: the probe loop keeps running until k raw -// candidates have been scanned, so placeholders disappear (data permitting). -int test_ensure_topk_full(const char* index_key, MetricType metric) { - std::vector xb = make_data(nb); - auto index = make_index(index_key, metric, xb); - std::vector xq = make_data(nq); - - constexpr int k = 10; - // Budget: smaller than k codes per query. Guaranteed truncation when - // ensure_topk_full is false. - const size_t tight_budget = k / 2; - - IVFSearchParameters p; - p.nprobe = 32; - p.max_codes = tight_budget; - p.ensure_topk_full = false; - auto res_tight = search_index_with_params(index.get(), xq.data(), &p); - - p.ensure_topk_full = true; - auto res_full = search_index_with_params(index.get(), xq.data(), &p); - - size_t miss_tight = - std::count(res_tight.begin(), res_tight.end(), (idx_t)-1); - size_t miss_full = std::count(res_full.begin(), res_full.end(), (idx_t)-1); - - // ensure_topk_full=true must produce at least as many valid slots as - // ensure_topk_full=false; in practice it must strictly reduce -1 count - // given our tight budget. - if (miss_full > miss_tight) { - return 1; - } - if (miss_tight == 0) { - // Test assumption violated: budget should have caused truncation. - return 2; - } - return 0; -} - -// Regression test: when all three new fields are left at defaults the -// search behaves identically to a search with no params at all. This is the -// backward-compatibility guarantee for pre-existing baseline callers. -int test_defaults_preserve_baseline(const char* index_key, MetricType metric) { - std::vector xb = make_data(nb); - auto index = make_index(index_key, metric, xb); - std::vector xq = make_data(nq); - - ParameterSpace ps; - ps.set_index_parameter(index.get(), "nprobe", 4); - auto res_no_params = search_index(index.get(), xq.data()); - - IVFSearchParameters p; // default-constructed: all new fields at 0/false - p.nprobe = 4; - auto res_default_params = - search_index_with_params(index.get(), xq.data(), &p); - - if (res_no_params != res_default_params) { - return 1; - } - return 0; -} - -// IDSelectorWithContext that delegates the verdict to an inner IDSelector while -// exercising the context parameters. Used to prove that a scanner (a) returns -// results identical to the plain is_member path and (b) actually routes through -// is_member_with_context — n_context_calls counts how often the context path -// fired, so a scanner that silently dropped the hook is detectable. +// Delegates to an inner IDSelector; n_context_calls detects a scanner that +// silently drops the is_member_with_context hook. struct ContextSelector : IDSelectorWithContext { const IDSelector& inner; mutable size_t n_context_calls = 0; - explicit ContextSelector(const IDSelector& inner) : inner(inner) {} + explicit ContextSelector(const IDSelector& inner_in) : inner(inner_in) {} bool is_member(idx_t id) const override { return inner.is_member(id); } @@ -207,53 +81,7 @@ struct ContextSelector : IDSelectorWithContext { } }; -int test_selector(const char* index_key) { - std::vector xb = make_data(nb); // database vectors - std::vector xq = make_data(nq); - ParameterSpace ps; - - std::vector sub_xb; - std::vector kept; - for (size_t i = 0; i < nb; i++) { - if (i % 10 == 2) { - kept.push_back(i); - sub_xb.insert( - sub_xb.end(), xb.begin() + i * d, xb.begin() + (i + 1) * d); - } - } - - // full index - auto index = make_index(index_key, METRIC_L2, xb); - ps.set_index_parameter(index.get(), "nprobe", 3); - - // restricted index - std::unique_ptr sub_index(clone_index(index.get())); - sub_index->reset(); - sub_index->add_with_ids(kept.size(), sub_xb.data(), kept.data()); - - auto ref_result = search_index(sub_index.get(), xq.data()); - - IVFSearchParameters params; - params.max_codes = 0; - params.nprobe = 3; - IDSelectorBatch sel(kept.size(), kept.data()); - params.sel = &sel; - auto new_result = search_index_with_params(index.get(), xq.data(), ¶ms); - - if (ref_result != new_result) { - return 1; - } - - return 0; -} - -// Runs the same membership set (every id where i % 10 == 2) through a plain -// IDSelectorBatch and through a ContextSelector wrapping it, on an -// already-trained index. Returns: -// 0 if the context path fired AND labels are byte-identical to the plain -// path, 1 if the results diverged (a correctness regression), 2 if the -// scanner never routed through is_member_with_context (the hook was -// silently dropped for this index type). +// Returns 0 if ok, 1 if results differ, 2 if the context hook never fired. int check_ctx_matches_plain(Index& index) { std::vector xq = make_data(nq); @@ -265,7 +93,6 @@ int check_ctx_matches_plain(Index& index) { } IDSelectorBatch batch(kept.size(), kept.data()); - // Plain IDSelector path. IVFSearchParameters plain_params; plain_params.max_codes = 0; plain_params.nprobe = 3; @@ -273,7 +100,6 @@ int check_ctx_matches_plain(Index& index) { auto plain_result = search_index_with_params(&index, xq.data(), &plain_params); - // IDSelectorWithContext path over the same membership set. ContextSelector ctx_sel(batch); IVFSearchParameters ctx_params; ctx_params.max_codes = 0; @@ -290,21 +116,15 @@ int check_ctx_matches_plain(Index& index) { return 0; } -// Same membership set as test_selector, but driven through an -// IDSelectorWithContext to prove the context scan path is functionally -// identical to — and actually exercised by — the given index type. int test_selector_with_context(const char* index_key) { std::vector xb = make_data(nb); auto index = make_index(index_key, METRIC_L2, xb); - // nprobe is set explicitly in the IVFSearchParameters inside - // check_ctx_matches_plain, so no need to set it on the index here. return check_ctx_matches_plain(*index); } // Multibit RaBitQ (nb_bits >= 2) scans through the two hand-written loops in // RaBitQuantizer.cpp rather than run_scan_codes1, so it needs the context hook -// wired separately. nb_bits=3 => ex_bits=2 => scan_codes_multibit; the default -// qb keeps a real quantized-query distance computer (no 1-bit fallback). +// wired separately. nb_bits=3 => ex_bits=2 => scan_codes_multibit. int test_selector_with_context_rabitq_multibit() { std::vector xb = make_data(nb); IndexFlatL2 quantizer(d); @@ -317,80 +137,6 @@ int test_selector_with_context_rabitq_multibit() { } // namespace -/************************************************************* - * Test entry points - *************************************************************/ - -TEST(TPO, IVFFlat) { - int err1 = test_params_override("IVF32,Flat", METRIC_L2); - EXPECT_EQ(err1, 0); - int err2 = test_params_override("IVF32,Flat", METRIC_INNER_PRODUCT); - EXPECT_EQ(err2, 0); -} - -TEST(TPO, IVFPQ) { - int err1 = test_params_override("IVF32,PQ8np", METRIC_L2); - EXPECT_EQ(err1, 0); - int err2 = test_params_override("IVF32,PQ8np", METRIC_INNER_PRODUCT); - EXPECT_EQ(err2, 0); -} - -TEST(TPO, IVFSQ) { - int err1 = test_params_override("IVF32,SQ8", METRIC_L2); - EXPECT_EQ(err1, 0); - int err2 = test_params_override("IVF32,SQ8", METRIC_INNER_PRODUCT); - EXPECT_EQ(err2, 0); -} - -TEST(TPO, IVFFlatPP) { - int err1 = test_params_override("PCA16,IVF32,SQ8", METRIC_L2); - EXPECT_EQ(err1, 0); - int err2 = test_params_override("PCA16,IVF32,SQ8", METRIC_INNER_PRODUCT); - EXPECT_EQ(err2, 0); -} - -TEST(TPOEnsureTopK, IVFFlat) { - EXPECT_EQ(test_ensure_topk_full("IVF32,Flat", METRIC_L2), 0); - EXPECT_EQ(test_ensure_topk_full("IVF32,Flat", METRIC_INNER_PRODUCT), 0); -} - -TEST(TPOEnsureTopK, IVFPQ) { - EXPECT_EQ(test_ensure_topk_full("IVF32,PQ8np", METRIC_L2), 0); - EXPECT_EQ(test_ensure_topk_full("IVF32,PQ8np", METRIC_INNER_PRODUCT), 0); -} - -TEST(TPOEnsureTopK, IVFSQ) { - EXPECT_EQ(test_ensure_topk_full("IVF32,SQ8", METRIC_L2), 0); - EXPECT_EQ(test_ensure_topk_full("IVF32,SQ8", METRIC_INNER_PRODUCT), 0); -} - -TEST(TPODefaults, IVFFlat) { - EXPECT_EQ(test_defaults_preserve_baseline("IVF32,Flat", METRIC_L2), 0); -} - -TEST(TPODefaults, IVFPQ) { - EXPECT_EQ(test_defaults_preserve_baseline("IVF32,PQ8np", METRIC_L2), 0); -} - -TEST(TPODefaults, IVFSQ) { - EXPECT_EQ(test_defaults_preserve_baseline("IVF32,SQ8", METRIC_L2), 0); -} - -TEST(TSEL, IVFFlat) { - int err = test_selector("PCA16,IVF32,Flat"); - EXPECT_EQ(err, 0); -} - -TEST(TSEL, IVFFPQ) { - int err = test_selector("PCA16,IVF32,PQ4x8np"); - EXPECT_EQ(err, 0); -} - -TEST(TSEL, IVFFSQ) { - int err = test_selector("PCA16,IVF32,SQ8"); - EXPECT_EQ(err, 0); -} - // An IDSelectorWithContext must be functionally identical to a plain // IDSelector AND actually exercised (results must not silently fall back to // is_member) on every applicable IVF scanner. IVFFlat/IVFSQ route through @@ -415,86 +161,3 @@ TEST(TSELCtx, RaBitQMultibit) { TEST(TSELCtx, Panorama) { EXPECT_EQ(test_selector_with_context("IVF32,FlatPanorama"), 0); } - -/************************************************************* - * Same for binary indexes - *************************************************************/ - -std::vector make_data_binary(size_t n) { - std::vector database(n * d / 8); - std::uniform_int_distribution<> distrib; - for (size_t i = 0; i < n * d / 8; i++) { - database[i] = distrib(rng); - } - return database; -} - -std::unique_ptr make_index( - const char* index_type, - const std::vector& x) { - auto index = std::unique_ptr( - dynamic_cast(index_binary_factory(d, index_type))); - index->train(nb, x.data()); - index->add(nb, x.data()); - return index; -} - -std::vector search_index(IndexBinaryIVF* index, const uint8_t* xq) { - int k = 10; - std::vector I(k * nq); - std::vector D(k * nq); - index->search(nq, xq, k, D.data(), I.data()); - return I; -} - -std::vector search_index_with_params( - IndexBinaryIVF* index, - const uint8_t* xq, - IVFSearchParameters* params) { - int k = 10; - std::vector I(k * nq); - std::vector D(k * nq); - - std::vector Iq(params->nprobe * nq); - std::vector Dq(params->nprobe * nq); - - index->quantizer->search(nq, xq, params->nprobe, Dq.data(), Iq.data()); - index->search_preassigned( - nq, xq, k, Iq.data(), Dq.data(), D.data(), I.data(), false, params); - return I; -} - -int test_params_override_binary(const char* index_key) { - std::vector xb = make_data_binary(nb); // database vectors - auto index = make_index(index_key, xb); - index->train(nb, xb.data()); - index->add(nb, xb.data()); - std::vector xq = make_data_binary(nq); - index->nprobe = 2; - auto res2ref = search_index(index.get(), xq.data()); - index->nprobe = 9; - auto res9ref = search_index(index.get(), xq.data()); - index->nprobe = 1; - - IVFSearchParameters params; - params.max_codes = 0; - params.nprobe = 2; - auto res2new = search_index_with_params(index.get(), xq.data(), ¶ms); - params.nprobe = 9; - auto res9new = search_index_with_params(index.get(), xq.data(), ¶ms); - - if (res2ref != res2new) { - return 2; - } - - if (res9ref != res9new) { - return 9; - } - - return 0; -} - -TEST(TPOB, IVF) { - int err1 = test_params_override_binary("BIVF32"); - EXPECT_EQ(err1, 0); -} diff --git a/thirdparty/faiss/tests/test_params_override.py b/thirdparty/faiss/tests/test_params_override.py new file mode 100644 index 000000000..a93f8225c --- /dev/null +++ b/thirdparty/faiss/tests/test_params_override.py @@ -0,0 +1,153 @@ +# 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 unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +d = 32 +nb = 1000 +nq = 200 +k = 10 + + +def make_data(n, seed=123): + rng = np.random.RandomState(seed) + return rng.rand(n, d).astype(np.float32) + + +def make_index(index_type, metric, xb): + index = faiss.index_factory(d, index_type, metric) + index.train(xb) + index.add(xb) + return index + + +def search_index(index, xq): + _, I = index.search(xq, k) + return I + + +def search_index_with_params(index, xq, params): + _, I = faiss.search_with_parameters(index, xq, k, params=params) + return I + + +def check_params_override(index_key, metric, seed): + xb = make_data(nb, seed) + index = make_index(index_key, metric, xb) + xq = make_data(nq, seed + 1) + ps = faiss.ParameterSpace() + ps.set_index_parameter(index, "nprobe", 2) + res2ref = search_index(index, xq) + ps.set_index_parameter(index, "nprobe", 1) + + params = faiss.IVFSearchParameters() + params.max_codes = 0 + params.nprobe = 2 + res2new = search_index_with_params(index, xq, params) + + return np.array_equal(res2ref, res2new) + + +def check_ensure_topk_full(index_key, metric, seed): + xb = make_data(nb, seed) + index = make_index(index_key, metric, xb) + xq = make_data(nq, seed + 1) + + # budget smaller than k codes per query: guaranteed truncation when + # ensure_topk_full is false + tight_budget = k // 2 + + params = faiss.IVFSearchParameters() + params.nprobe = 32 + params.max_codes = tight_budget + params.ensure_topk_full = False + res_tight = search_index_with_params(index, xq, params) + + params.ensure_topk_full = True + res_full = search_index_with_params(index, xq, params) + + miss_tight = np.count_nonzero(res_tight == -1) + miss_full = np.count_nonzero(res_full == -1) + + assert miss_tight > 0, "budget should have caused truncation" + return miss_full <= miss_tight + + +def check_defaults_preserve_baseline(index_key, metric, seed): + xb = make_data(nb, seed) + index = make_index(index_key, metric, xb) + xq = make_data(nq, seed + 1) + + ps = faiss.ParameterSpace() + ps.set_index_parameter(index, "nprobe", 4) + res_no_params = search_index(index, xq) + + params = faiss.IVFSearchParameters() + params.nprobe = 4 + res_default_params = search_index_with_params(index, xq, params) + + return np.array_equal(res_no_params, res_default_params) + + +def check_selector(index_key, seed): + rng = np.random.RandomState(seed) + xb = rng.rand(nb, d).astype(np.float32) + xq = rng.rand(nq, d).astype(np.float32) + ps = faiss.ParameterSpace() + + kept = np.array([i for i in range(nb) if i % 10 == 2], dtype=np.int64) + sub_xb = xb[kept] + + index = make_index(index_key, faiss.METRIC_L2, xb) + ps.set_index_parameter(index, "nprobe", 3) + + sub_index = faiss.clone_index(index) + sub_index.reset() + sub_index.add_with_ids(sub_xb, kept) + + ref_result = search_index(sub_index, xq) + + params = faiss.IVFSearchParameters() + params.max_codes = 0 + params.nprobe = 3 + params.sel = faiss.IDSelectorBatch(kept) + new_result = search_index_with_params(index, xq, params) + + return np.array_equal(ref_result, new_result) + + +class TestParamsOverride(unittest.TestCase): + def test_ivf_flat_pp(self): + self.assertTrue( + check_params_override("PCA16,IVF32,SQ8", faiss.METRIC_L2, 107)) + + +class TestEnsureTopkFull(unittest.TestCase): + def test_ivfpq(self): + self.assertTrue( + check_ensure_topk_full("IVF32,PQ8np", faiss.METRIC_L2, 203)) + + def test_ivfsq(self): + self.assertTrue( + check_ensure_topk_full("IVF32,SQ8", faiss.METRIC_L2, 205)) + + +class TestDefaultsPreserveBaseline(unittest.TestCase): + def test_ivf_flat(self): + self.assertTrue( + check_defaults_preserve_baseline( + "IVF32,Flat", faiss.METRIC_L2, 301)) + + +class TestSelector(unittest.TestCase): + def test_ivfpq(self): + self.assertTrue(check_selector("PCA16,IVF32,PQ4x8np", 402)) diff --git a/thirdparty/faiss/tests/test_partition.py b/thirdparty/faiss/tests/test_partition.py index 048cbaefc..faef55ce2 100644 --- a/thirdparty/faiss/tests/test_partition.py +++ b/thirdparty/faiss/tests/test_partition.py @@ -45,13 +45,13 @@ def pointer_to_minus1(): return np.array([-1], dtype="int64").view("uint64") -@for_all_simd_levels class TestPartitioningFloat(unittest.TestCase, PartitionTests): def do_partition(self, n, q, maxval=None, seed=None): if seed is None: for i in range(50): self.do_partition(n, q, maxval, i + 1234) + return rs = np.random.RandomState(seed) if maxval is None: vals = rs.rand(n).astype("float32") @@ -87,13 +87,13 @@ def do_partition(self, n, q, maxval=None, seed=None): self.assertEqual(n_eq, 0) -@for_all_simd_levels class TestPartitioningFloatMin(unittest.TestCase, PartitionTests): def do_partition(self, n, q, maxval=None, seed=None): if seed is None: for i in range(50): self.do_partition(n, q, maxval, i + 1234) + return rs = np.random.RandomState(seed) if maxval is None: vals = rs.rand(n).astype("float32") @@ -142,6 +142,7 @@ def do_partition(self, n, q, maxval=65536, seed=None): if seed is None: for i in range(50): self.do_partition(n, q, maxval, i + 1234) + return rs = np.random.RandomState(seed) vals = rs.randint(maxval, size=n).astype("uint16") @@ -185,10 +186,10 @@ def do_partition(self, n, q, maxval=65536, seed=None): class TestPartitioningUint16Min(unittest.TestCase, PartitionTests): def do_partition(self, n, q, maxval=65536, seed=None): - # seed = 1235 if seed is None: for i in range(50): self.do_partition(n, q, maxval, i + 1234) + return rs = np.random.RandomState(seed) vals = rs.randint(maxval, size=n).astype("uint16") ids = (rs.permutation(n) + 12345).astype("int64") diff --git a/thirdparty/faiss/tests/test_pipnn.cpp b/thirdparty/faiss/tests/test_pipnn.cpp new file mode 100644 index 000000000..80eacc8b7 --- /dev/null +++ b/thirdparty/faiss/tests/test_pipnn.cpp @@ -0,0 +1,1335 @@ +/* + * 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. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using faiss::pipnn::distance_key; +using faiss::pipnn::Hyperplanes; +using faiss::pipnn::kNoFarthest; +using faiss::pipnn::ReservoirRef; +using faiss::pipnn::residual_hash; +using faiss::pipnn::Slot; +using faiss::pipnn::slot_less; + +TEST(PiPNNDistanceKey, SpecialValues) { + const float inf = std::numeric_limits::infinity(); + EXPECT_EQ(distance_key(-0.0f), distance_key(0.0f)); + EXPECT_EQ( + distance_key(std::numeric_limits::quiet_NaN()), + distance_key(inf)); +} + +TEST(PiPNNDistanceKey, Monotone) { + // Strictly increasing over all non-NaN bf16 values. + std::vector grid; + for (uint32_t b = 0; b < 65536; b++) { + const uint32_t bits = b << 16; + float f; + std::memcpy(&f, &bits, sizeof(f)); + if (!std::isnan(f)) { + grid.push_back(f); + } + } + std::sort(grid.begin(), grid.end()); + for (size_t i = 1; i < grid.size(); i++) { + if (grid[i - 1] != grid[i]) { // skips the -0, +0 pair + ASSERT_LT(distance_key(grid[i - 1]), distance_key(grid[i])) + << grid[i - 1] << " vs " << grid[i]; + } + } + + // Non-decreasing over arbitrary floats, which bf16 rounding maps between + // grid points. + std::vector v; + faiss::SplitMix64RandomGenerator rng(42); + for (int i = 0; i < 100000; i++) { + const uint32_t bits = static_cast(rng.next()); + float f; + std::memcpy(&f, &bits, sizeof(f)); + if (!std::isnan(f)) { + v.push_back(f); + } + } + std::sort(v.begin(), v.end()); + for (size_t i = 1; i < v.size(); i++) { + ASSERT_LE(distance_key(v[i - 1]), distance_key(v[i])) + << v[i - 1] << " vs " << v[i]; + } +} + +namespace { + +struct TestReservoir { + std::vector slots; + uint8_t count = 0; + uint8_t farthest = kNoFarthest; + ReservoirRef ref; + + explicit TestReservoir(int capacity) + : slots(capacity), ref{slots.data(), &count, &farthest, capacity} {} + TestReservoir(const TestReservoir&) = delete; + TestReservoir& operator=(const TestReservoir&) = delete; + + bool offer(int32_t id, uint16_t hash, uint16_t key) { + return ref.offer(id, hash, key); + } +}; + +using SlotTuple = std::tuple; // (id, hash, key) + +std::vector contents(const TestReservoir& r) { + std::vector out; + out.reserve(r.count); + for (int i = 0; i < r.count; i++) { + out.emplace_back(r.slots[i].id, r.slots[i].hash, r.slots[i].key); + } + return out; +} + +/// Checks the ReservoirRef invariant documented in HashPrune.h. +void check_invariant(const TestReservoir& r) { + ASSERT_LE(int(r.count), r.ref.capacity); + std::set ids; + for (int i = 0; i < r.count; i++) { + if (i > 0) { + ASSERT_LT(r.slots[i - 1].hash, r.slots[i].hash); + } + ASSERT_TRUE(ids.insert(r.slots[i].id).second); + } + if (r.farthest != kNoFarthest) { + ASSERT_LT(int(r.farthest), int(r.count)); + const Slot& f = r.slots[r.farthest]; + for (int i = 0; i < r.count; i++) { + if (i != r.farthest) { + ASSERT_TRUE( + slot_less(r.slots[i].key, r.slots[i].id, f.key, f.id)); + } + } + } +} + +} // namespace + +TEST(PiPNNReservoir, FarthestCache) { + TestReservoir r(3); + ASSERT_TRUE(r.offer(1, 10, 0x9000)); + ASSERT_TRUE(r.offer(2, 20, 0x9300)); + ASSERT_TRUE(r.offer(3, 30, 0x9100)); + EXPECT_FALSE(r.offer(4, 40, 0x9400)); // the scan caches the max, id 2 + EXPECT_EQ(int(r.farthest), 1); + EXPECT_TRUE(r.offer(3, 30, 0x8F00)); // lowering another slot keeps it + EXPECT_EQ(int(r.farthest), 1); + EXPECT_TRUE(r.offer(2, 20, 0x8E00)); // lowering the max clears it + EXPECT_EQ(int(r.farthest), int(kNoFarthest)); +} + +namespace { + +struct Offer { + int32_t id; + uint16_t hash; + uint16_t key; +}; + +/// Reference model of the reservoir (Lemma A.2 of the PiPNN paper, with key +/// ties decided by id): the min(capacity, B) slot_less-smallest bucket +/// minima, listed in hash order. +std::vector model_reservoir( + const std::vector& offers, + int capacity) { + std::map> minima; // hash->(key,id) + for (const Offer& o : offers) { + auto it = minima.find(o.hash); + if (it == minima.end()) { + minima.emplace(o.hash, std::make_pair(o.key, o.id)); + } else if (slot_less( + o.key, o.id, it->second.first, it->second.second)) { + it->second = std::make_pair(o.key, o.id); + } + } + std::vector> ranked; // key,id,hash + ranked.reserve(minima.size()); + for (const auto& [hash, key_id] : minima) { + ranked.emplace_back(key_id.first, key_id.second, hash); + } + std::sort(ranked.begin(), ranked.end()); + if (ranked.size() > static_cast(capacity)) { + ranked.resize(capacity); + } + std::vector out; + out.reserve(ranked.size()); + for (const auto& [key, id, hash] : ranked) { + out.emplace_back(id, hash, key); + } + std::sort( + out.begin(), out.end(), [](const SlotTuple& a, const SlotTuple& b) { + return std::get<1>(a) < std::get<1>(b); + }); + return out; +} + +/// Ids are bucket * 4 + r (r < 4), so an id always lands in the same bucket, +/// as the residual hash guarantees in the build. Ids and keys repeat, so the +/// offers include re-offers and key ties. +std::vector random_offers( + size_t n, + int n_buckets, + int n_keys, + faiss::SplitMix64RandomGenerator& rng) { + std::vector offers(n); + for (Offer& o : offers) { + const int bucket = static_cast(rng.next() % n_buckets); + o.hash = static_cast(bucket * 37); + o.id = static_cast(bucket * 4 + rng.next() % 4); + o.key = static_cast(0x8000 + rng.next() % n_keys); + } + return offers; +} + +} // namespace + +TEST(PiPNNReservoir, MatchesModelInAnyOrder) { + faiss::SplitMix64RandomGenerator rng(77); + for (int capacity : {1, 3, 8, 255}) { + const int n_buckets = 2 * capacity + 8; + for (int n_keys : {3, 4096}) { + for (int trial = 0; trial < 3; trial++) { + std::vector offers = + random_offers(3 * n_buckets, n_buckets, n_keys, rng); + const std::vector expected = + model_reservoir(offers, capacity); + for (int shuffle = 0; shuffle < 10; shuffle++) { + SCOPED_TRACE( + testing::Message() + << "capacity " << capacity << " keys " << n_keys + << " trial " << trial << " shuffle " << shuffle); + for (size_t i = offers.size(); i > 1; i--) { + std::swap(offers[i - 1], offers[rng.next() % i]); + } + TestReservoir r(capacity); + for (const Offer& o : offers) { + const std::vector before = contents(r); + const bool changed = r.offer(o.id, o.hash, o.key); + ASSERT_EQ(changed, contents(r) != before); + ASSERT_NO_FATAL_FAILURE(check_invariant(r)); + } + ASSERT_EQ(contents(r), expected); + } + } + } + } +} + +TEST(PiPNNSketch, InvalidArgs) { + EXPECT_THROW(Hyperplanes(0, 4, 1), faiss::FaissException); + EXPECT_THROW(Hyperplanes(8, 0, 1), faiss::FaissException); + EXPECT_THROW(Hyperplanes(8, 17, 1), faiss::FaissException); +} + +TEST(PiPNNSketch, ProjectionIndependentOfBuffer) { + const int d = 37; + const int m = 12; + Hyperplanes hp(d, m, 7); + std::vector h(size_t(m) * d); + faiss::float_randn(h.data(), h.size(), 7); + std::vector x(d); + faiss::float_randn(x.data(), d, 99); + // The same vector at an odd offset of another buffer, with a misaligned + // output, must give a bitwise-identical sketch. + std::vector shifted(3 + d); + std::copy(x.begin(), x.end(), shifted.begin() + 3); + float a[16]; + std::vector b(17); + hp.sketch(x.data(), a); + hp.sketch(shifted.data() + 3, b.data() + 1); + EXPECT_EQ(0, std::memcmp(a, b.data() + 1, sizeof(a))); + for (int i = 0; i < m; i++) { + double s = 0; + for (int j = 0; j < d; j++) { + s += double(x[j]) * double(h[size_t(i) * d + j]); + } + EXPECT_NEAR(a[i], s, 1e-4 * (1 + std::abs(s))) << i; + } + for (int i = m; i < 16; i++) { + EXPECT_EQ(a[i], 0.0f) << i; // zero-padded hyperplanes + } +} + +TEST(PiPNNSketch, ResidualHash) { + float p[16]; + float c[16]; + for (int i = 0; i < 16; i++) { + p[i] = float(i); + c[i] = i % 3 == 0 ? float(i) - 1 : float(i) + 1; + } + // Bit i is set iff i % 3 != 0. + EXPECT_EQ(residual_hash(p, c, 6), uint16_t(0x36)); + EXPECT_EQ(residual_hash(p, c, 16), uint16_t(0x6DB6)); + // A zero residual sets all m bits and none above. + EXPECT_EQ(residual_hash(p, p, 12), uint16_t(0x0FFF)); +} + +/************************************************************* + * Numeric kernels + *************************************************************/ + +namespace pipnn_kernel_test { + +using faiss::pipnn::Ranking; + +const Ranking kRankings[] = {Ranking::L2, Ranking::IP, Ranking::Angle}; + +faiss::AlignedTable random_table(size_t n, int64_t seed) { + faiss::AlignedTable t(n); + faiss::float_randn(t.get(), n, seed); + return t; +} + +// Scratch buffers start as NaN, so a BLAS that reads C with beta == 0 fails. +faiss::AlignedTable nan_table(size_t n) { + faiss::AlignedTable t(n); + std::fill(t.get(), t.get() + n, std::numeric_limits::quiet_NaN()); + return t; +} + +std::vector norms_of(const float* X, size_t n, size_t d) { + std::vector norms(n); + for (size_t i = 0; i < n; i++) { + norms[i] = faiss::fvec_norm_L2sqr(X + i * d, d); + } + return norms; +} + +double ref_rank(const float* p, const float* l, size_t d, Ranking ranking) { + double dot = 0, ln = 0; + for (size_t t = 0; t < d; t++) { + dot += double(p[t]) * double(l[t]); + ln += double(l[t]) * double(l[t]); + } + if (ranking == Ranking::L2) { + return ln - 2 * dot; + } + return ranking == Ranking::IP ? -dot : -dot / std::sqrt(ln); +} + +std::vector run_stripe( + const float* points, + size_t S, + const float* leaders, + size_t L, + size_t d, + Ranking ranking, + int fanout) { + const std::vector norms = norms_of(leaders, L, d); + faiss::AlignedTable scratch = nan_table(S * L); + std::vector out(S * size_t(fanout), 0xFFFF); + faiss::pipnn::stripe_assign( + points, + S, + leaders, + ranking == Ranking::IP ? nullptr : norms.data(), + L, + d, + ranking, + fanout, + scratch.get(), + out.data()); + return out; +} + +// Full float64 distance matrix: L2 squared, or -dot for IP. +std::vector ref_distances( + const float* X, + size_t n, + size_t d, + faiss::MetricType metric) { + std::vector ref(n * n); + for (size_t i = 0; i < n; i++) { + for (size_t j = 0; j < n; j++) { + double acc = 0; + for (size_t c = 0; c < d; c++) { + const double a = X[i * d + c]; + const double b = X[j * d + c]; + acc += metric == faiss::METRIC_L2 ? (a - b) * (a - b) : a * b; + } + ref[i * n + j] = metric == faiss::METRIC_L2 ? acc : -acc; + } + } + return ref; +} + +void run_leaf( + const float* X, + size_t s, + size_t d, + faiss::MetricType metric, + int k, + std::vector& idx, + std::vector& dist) { + const std::vector norms = norms_of(X, s, d); + faiss::AlignedTable gram = nan_table(s * s); + idx.assign(s * size_t(k), 7); // garbage: every slot must be written + dist.assign(s * size_t(k), 7.0f); + faiss::pipnn::leaf_knn( + X, + norms.data(), + s, + d, + metric, + k, + gram.get(), + idx.data(), + dist.data()); +} + +} // namespace pipnn_kernel_test + +TEST(PiPNNKernels, StripeMatchesFloat64Reference) { + namespace pkt = pipnn_kernel_test; + struct Case { + size_t S, L, d; + std::vector fanouts; + }; + const Case cases[] = { + {9, 20, 16, {1, 10, 20}}, + {faiss::pipnn::kStripe, 100, 32, {33, 100}}}; + for (const Case& c : cases) { + const auto points = pkt::random_table(c.S * c.d, 123); + const auto leaders = pkt::random_table(c.L * c.d, 456); + for (pkt::Ranking ranking : pkt::kRankings) { + for (int fanout : c.fanouts) { + SCOPED_TRACE( + testing::Message() + << "L=" << c.L << " ranking=" << int(ranking) + << " fanout=" << fanout); + const std::vector out = pkt::run_stripe( + points.get(), + c.S, + leaders.get(), + c.L, + c.d, + ranking, + fanout); + for (size_t i = 0; i < c.S; i++) { + std::vector rank(c.L); + for (size_t j = 0; j < c.L; j++) { + rank[j] = pkt::ref_rank( + points.get() + i * c.d, + leaders.get() + j * c.d, + c.d, + ranking); + } + std::vector sorted = rank; + std::sort(sorted.begin(), sorted.end()); + const uint16_t* row = out.data() + i * fanout; + ASSERT_EQ( + std::set(row, row + fanout).size(), + size_t(fanout)); + for (int r = 0; r < fanout; r++) { + ASSERT_LT(row[r], c.L); + EXPECT_NEAR(rank[row[r]], sorted[r], 1e-3); + } + } + } + } + } +} + +// Leaders cycle through the 4 unit directions and the points are (0, 0) and +// (2, 0): small integers make every rank, and so every tie, exact. +TEST(PiPNNKernels, StripeTiesPreferLowerLeaderIndex) { + namespace pkt = pipnn_kernel_test; + const size_t L = 40; + const float dirs[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + faiss::AlignedTable leaders(L * 2); + for (size_t j = 0; j < L; j++) { + leaders[2 * j] = dirs[j % 4][0]; + leaders[2 * j + 1] = dirs[j % 4][1]; + } + faiss::AlignedTable points(4); + const float pts[4] = {0, 0, 2, 0}; + std::copy(pts, pts + 4, points.get()); + // (2, 0) ranks the +x leaders first, then the orthogonal ones, then -x. + std::vector order1; + for (size_t first : {0, 1, 2}) { + for (size_t j = first; j < L; j += first == 1 ? 2 : 4) { + order1.push_back(uint16_t(j)); + } + } + for (pkt::Ranking ranking : pkt::kRankings) { + for (int fanout : {10, 40}) { + SCOPED_TRACE( + testing::Message() + << "ranking=" << int(ranking) << " fanout=" << fanout); + std::vector expected(2 * fanout); + for (int r = 0; r < fanout; r++) { + expected[r] = uint16_t(r); + expected[fanout + r] = order1[r]; + } + EXPECT_EQ( + pkt::run_stripe( + points.get(), + 2, + leaders.get(), + L, + 2, + ranking, + fanout), + expected); + } + } +} + +// NaN ranks +inf: a NaN point still gets `fanout` leaders in index order, and +// a NaN leader is never chosen over a finite one. +TEST(PiPNNKernels, StripeNaNRanksLast) { + namespace pkt = pipnn_kernel_test; + const size_t S = 5, L = 40, d = 8; + auto points = pkt::random_table(S * d, 7); + auto leaders = pkt::random_table(L * d, 8); + points[2 * d] = std::numeric_limits::quiet_NaN(); + leaders[0] = std::numeric_limits::quiet_NaN(); + for (pkt::Ranking ranking : pkt::kRankings) { + for (int fanout : {4, 33}) { + SCOPED_TRACE( + testing::Message() + << "ranking=" << int(ranking) << " fanout=" << fanout); + const std::vector out = pkt::run_stripe( + points.get(), S, leaders.get(), L, d, ranking, fanout); + for (size_t i = 0; i < S; i++) { + for (int r = 0; r < fanout; r++) { + const uint16_t leader = out[i * fanout + r]; + if (i == 2) { + EXPECT_EQ(leader, r) << "NaN point, rank " << r; + } else { + EXPECT_NE(leader, 0) << "point " << i << " rank " << r; + } + } + } + } + } +} + +// Leader 3 underflows to a zero norm; with a positive dot product it would +// otherwise rank first at -inf under Angle. +TEST(PiPNNKernels, StripeAngleZeroLeaderRanksLast) { + namespace pkt = pipnn_kernel_test; + const size_t S = 5, L = 6, d = 4; + faiss::AlignedTable points(S * d); + faiss::float_rand(points.get(), S * d, 11); + for (size_t i = 0; i < S * d; i++) { + points[i] += 0.5f; + } + auto leaders = pkt::random_table(L * d, 12); + for (size_t c = 0; c < d; c++) { + leaders[3 * d + c] = 1e-30f; + } + const std::vector out = pkt::run_stripe( + points.get(), S, leaders.get(), L, d, pkt::Ranking::Angle, int(L)); + for (size_t i = 0; i < S; i++) { + EXPECT_EQ(out[i * L + 5], 3) << "point " << i; + } +} + +// Exact distances: ties go to the lower index, and a NaN point is at +inf +// from everyone. +TEST(PiPNNKernels, LeafKnnExactCases) { + namespace pkt = pipnn_kernel_test; + const float inf = std::numeric_limits::infinity(); + std::vector idx; + std::vector dist; + + const float line[5] = {0, 1, 2, 3, 4}; + pkt::run_leaf(line, 5, 1, faiss::METRIC_L2, 2, idx, dist); + EXPECT_EQ(idx, (std::vector{1, 2, 0, 2, 1, 3, 2, 4, 3, 2})); + EXPECT_EQ(dist, (std::vector{1, 4, 1, 1, 1, 1, 1, 1, 1, 4})); + + const float with_nan[8] = { + 0, 0, 1, 0, 0, 2, std::numeric_limits::quiet_NaN(), 0}; + pkt::run_leaf(with_nan, 4, 2, faiss::METRIC_L2, 3, idx, dist); + EXPECT_EQ(idx, (std::vector{1, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 2})); + EXPECT_EQ( + dist, + (std::vector{ + 1, 4, inf, 1, 5, inf, 4, 5, inf, inf, inf, inf})); +} + +// The Gram entries of a copied row may round differently, so its L2 distance +// is a small value that must be clamped at 0, never negative. +TEST(PiPNNKernels, LeafL2CopiedRowIsNearestAndNonNegative) { + namespace pkt = pipnn_kernel_test; + const size_t s = 33, d = 24; + const int k = 4; + auto Y = pkt::random_table(s * d, 13); + std::copy(Y.get() + 7 * d, Y.get() + 8 * d, Y.get() + 30 * d); + std::vector idx; + std::vector dist; + pkt::run_leaf(Y.get(), s, d, faiss::METRIC_L2, k, idx, dist); + EXPECT_GE(*std::min_element(dist.begin(), dist.end()), 0.0f); + EXPECT_EQ(idx[7 * k], 30); + EXPECT_EQ(idx[30 * k], 7); + EXPECT_LE(dist[7 * k], 1e-4f); +} + +// pairwise_distances matches the float64 reference, and leaf_knn equals the +// (distance, index)-smallest non-self entries of its rows, bitwise, then -1 / +// +inf padding. The final prune relies on this agreement. +TEST(PiPNNKernels, LeafKnnMatchesPairwise) { + namespace pkt = pipnn_kernel_test; + const size_t d = 24; + for (faiss::MetricType metric : + {faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}) { + for (size_t n : {1, 3, 65}) { + const auto X = pkt::random_table(n * d, int64_t(100 + n)); + const std::vector norms = pkt::norms_of(X.get(), n, d); + faiss::AlignedTable D = pkt::nan_table(n * n); + faiss::pipnn::pairwise_distances( + X.get(), norms.data(), n, d, metric, D.get()); + const std::vector ref = + pkt::ref_distances(X.get(), n, d, metric); + for (size_t i = 0; i < n * n; i++) { + EXPECT_EQ(D[i], D[(i % n) * n + i / n]); // symmetric + EXPECT_NEAR(D[i], ref[i], 1e-3); + } + for (int k : {2, 5}) { + SCOPED_TRACE( + testing::Message() << "metric=" << int(metric) + << " n=" << n << " k=" << k); + std::vector want_idx(n * k, -1); + std::vector want_dist( + n * k, std::numeric_limits::infinity()); + for (size_t i = 0; i < n; i++) { + std::vector> row; + for (size_t j = 0; j < n; j++) { + if (j != i) { + row.emplace_back(D[i * n + j], int32_t(j)); + } + } + std::sort(row.begin(), row.end()); + for (size_t r = 0; r < std::min(size_t(k), row.size()); + r++) { + want_dist[i * k + r] = row[r].first; + want_idx[i * k + r] = row[r].second; + } + } + std::vector idx; + std::vector dist; + pkt::run_leaf(X.get(), n, d, metric, k, idx, dist); + EXPECT_EQ(idx, want_idx); + EXPECT_EQ(dist, want_dist); + } + } + } +} + +TEST(PiPNNKernels, RejectBadArguments) { + using faiss::FaissException; + const auto X = pipnn_kernel_test::random_table(3 * 4, 1); + const std::vector norms(3, 1.0f); + faiss::AlignedTable scratch(3 * 3); + std::vector leaders_out(3 * 3); + std::vector idx(3 * 2); + std::vector dist(3 * 2); + + auto stripe = [&](const float* nrm, size_t L, int fanout) { + faiss::pipnn::stripe_assign( + X.get(), + 3, + X.get(), + nrm, + L, + 4, + faiss::pipnn::Ranking::L2, + fanout, + scratch.get(), + leaders_out.data()); + }; + EXPECT_THROW(stripe(norms.data(), 3, 0), FaissException); + EXPECT_THROW(stripe(norms.data(), 3, 4), FaissException); // > L + EXPECT_THROW(stripe(nullptr, 3, 1), FaissException); + EXPECT_THROW(stripe(norms.data(), 65536, 1), FaissException); // > uint16 + + auto leaf = [&](const float* nrm, faiss::MetricType m, int k) { + faiss::pipnn::leaf_knn( + X.get(), + nrm, + 3, + 4, + m, + k, + scratch.get(), + idx.data(), + dist.data()); + }; + EXPECT_THROW(leaf(norms.data(), faiss::METRIC_L1, 2), FaissException); + EXPECT_THROW(leaf(norms.data(), faiss::METRIC_L2, 0), FaissException); + EXPECT_THROW(leaf(nullptr, faiss::METRIC_L2, 2), FaissException); + EXPECT_THROW( + faiss::pipnn::pairwise_distances( + X.get(), + norms.data(), + 3, + 4, + faiss::METRIC_L1, + scratch.get()), + FaissException); +} + +/************************************************************* + * PiPNN storage access and Randomized Ball Carving + *************************************************************/ + +namespace pipnn_partition_test { + +std::vector gaussian_data(size_t n, size_t d, int64_t seed) { + std::vector x(n * d); + faiss::float_randn(x.data(), x.size(), seed); + return x; +} + +/// x_i = (1 + 10 i / n) * u for one direction u: under max-IP every point ranks +/// leaders by norm, so all points pick the same `fanout` leaders. +std::vector collinear_data(size_t n, size_t d, int64_t seed) { + std::vector u(d); + faiss::float_rand(u.data(), d, seed); + std::vector x(n * d); + for (size_t i = 0; i < n; i++) { + const float scale = 1.0f + 10.0f * float(i) / float(n); + for (size_t j = 0; j < d; j++) { + x[i * d + j] = scale * u[j]; + } + } + return x; +} + +struct FlatData { + faiss::IndexFlat index; + + FlatData(const std::vector& x, size_t d, faiss::MetricType metric) + : index(d, metric) { + index.add(x.size() / d, x.data()); + } +}; + +const uint64_t kSeed = faiss::pipnn::mix_seed(1234, 0); + +faiss::pipnn::PartitionParams small_params(faiss::MetricType metric) { + faiss::pipnn::PartitionParams p; + p.c_max = 64; + p.c_min = 16; + p.metric = metric; + return p; +} + +struct ScopedOmpThreads { + const int saved = omp_get_max_threads(); + explicit ScopedOmpThreads(int n) { + omp_set_num_threads(n); + } + ~ScopedOmpThreads() { + omp_set_num_threads(saved); + } +}; + +using Leaves = std::vector>; + +/// Leaves are non-empty, strictly increasing, at most c_max long, and cover +/// every point. +void expect_valid_cover(const Leaves& leaves, size_t n, int c_max); + +/// Runs partition_and_visit, checks that its leaves are a valid cover, and +/// returns them sorted. +Leaves visit_all( + const faiss::Index& storage, + const faiss::pipnn::PartitionParams& p, + uint64_t seed, + faiss::pipnn::PartitionStats* stats = nullptr) { + std::mutex mu; + Leaves leaves; + faiss::pipnn::partition_and_visit( + storage, + p, + seed, + [&](const int32_t* ids, size_t s) { + std::vector leaf(ids, ids + s); + std::lock_guard lock(mu); + leaves.push_back(std::move(leaf)); + }, + stats); + std::sort(leaves.begin(), leaves.end()); + expect_valid_cover(leaves, size_t(storage.ntotal), p.c_max); + return leaves; +} + +void expect_valid_cover(const Leaves& leaves, size_t n, int c_max) { + std::vector seen(n, 0); + for (const std::vector& leaf : leaves) { + ASSERT_FALSE(leaf.empty()); + ASSERT_LE(leaf.size(), size_t(c_max)); + for (size_t i = 0; i < leaf.size(); i++) { + ASSERT_GE(leaf[i], 0); + ASSERT_LT(size_t(leaf[i]), n); + if (i > 0) { + ASSERT_LT(leaf[i - 1], leaf[i]); + } + seen[leaf[i]] = 1; + } + } + for (size_t i = 0; i < n; i++) { + ASSERT_TRUE(seen[i]) << "point " << i << " is in no leaf"; + } +} + +/// Fraction of points that share a leaf with their nearest other point (L2), or +/// with the other point of largest inner product (IP). +double fraction_with_neighbour( + const Leaves& leaves, + const std::vector& x, + size_t d, + faiss::MetricType metric) { + const size_t n = x.size() / d; + faiss::IndexFlat index(d, metric); + index.add(n, x.data()); + std::vector D(2 * n); + std::vector I(2 * n); + index.search(n, x.data(), 2, D.data(), I.data()); + std::vector> leaves_of(n); + for (size_t l = 0; l < leaves.size(); l++) { + for (int32_t id : leaves[l]) { + leaves_of[id].push_back(l); + } + } + size_t hits = 0; + for (size_t i = 0; i < n; i++) { + const faiss::idx_t j = + I[2 * i] == faiss::idx_t(i) ? I[2 * i + 1] : I[2 * i]; + const std::vector& a = leaves_of[i]; + const std::vector& b = leaves_of[j]; + if (std::find_first_of(a.begin(), a.end(), b.begin(), b.end()) != + a.end()) { + hits++; + } + } + return double(hits) / double(n); +} + +} // namespace pipnn_partition_test + +TEST(PiPNNStorage, GatherSQRowsMatchesReconstruct) { + const int d = 12; + const size_t n = 200; + const std::vector x = pipnn_partition_test::gaussian_data(n, d, 7); + faiss::IndexScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit); + sq.train(n, x.data()); + sq.add(n, x.data()); + const int32_t ids[3] = {5, 0, 199}; + faiss::AlignedTable out(3 * d); + faiss::pipnn::gather_rows(sq, ids, 3, out.data()); + std::vector expected(d); + for (size_t i = 0; i < 3; i++) { + sq.reconstruct(ids[i], expected.data()); + EXPECT_EQ( + 0, + std::memcmp( + out.data() + i * d, expected.data(), sizeof(float) * d)) + << "row " << i; + } +} + +// Pinned values: changing any of them changes every graph. +TEST(PiPNNPartition, SeededHelpersGolden) { + using faiss::pipnn::mix_seed; + using faiss::pipnn::detail::sample_positions; + EXPECT_EQ(mix_seed(1234, 1), 0x626e95467131d717ULL); + + std::vector pos; + sample_positions(100, 5, 42, pos); + EXPECT_EQ(pos, (std::vector{6, 45, 50, 84, 85})); + sample_positions(10, 10, 7, pos); + EXPECT_EQ(pos, (std::vector{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); +} + +TEST(PiPNNPartition, ParameterHelpers) { + using faiss::pipnn::Ranking; + using faiss::pipnn::detail::leader_count; + using faiss::pipnn::detail::ranking_for; + faiss::pipnn::PartitionParams p; + EXPECT_EQ(p.fanout_at(1), 3); + EXPECT_EQ(p.fanout_at(2), 1); + EXPECT_EQ(leader_count(1025, p, 0), 40u); // 4 * fanout floor + EXPECT_EQ(leader_count(100000, p, 0), 500u); // ceil(P_samp * |P|) + EXPECT_EQ(leader_count(10000000, p, 0), 1000u); // leader_cap + EXPECT_EQ(leader_count(300, p, 1), 12u); + EXPECT_EQ(leader_count(3, p, 5), 3u); // never more than |P| + p.leader_cap = 7; + EXPECT_EQ(leader_count(1025, p, 0), 7u); + + p.ip_partition_by_angle = true; + EXPECT_EQ(ranking_for(p, false), Ranking::L2); + p.metric = faiss::METRIC_INNER_PRODUCT; + EXPECT_EQ(ranking_for(p, false), Ranking::Angle); + EXPECT_EQ(ranking_for(p, true), Ranking::L2); + p.ip_partition_by_angle = false; + EXPECT_EQ(ranking_for(p, false), Ranking::IP); +} + +TEST(PiPNNPartition, SizesAroundCMax) { + namespace ppt = pipnn_partition_test; + const size_t d = 8; + const faiss::pipnn::PartitionParams p = ppt::small_params(faiss::METRIC_L2); + + ppt::FlatData empty({}, d, faiss::METRIC_L2); + EXPECT_TRUE(ppt::visit_all(empty.index, p, 1).empty()); + + const size_t n = size_t(p.c_max); + ppt::FlatData one_leaf(ppt::gaussian_data(n, d, 5), d, faiss::METRIC_L2); + std::vector all(n); + for (size_t i = 0; i < n; i++) { + all[i] = int32_t(i); + } + EXPECT_EQ(ppt::visit_all(one_leaf.index, p, 1), ppt::Leaves{all}); + + ppt::FlatData above(ppt::gaussian_data(n + 1, d, 11), d, faiss::METRIC_L2); + // One split whose small children are merged: no leaf is below c_min + // (without merging, 25 of its 40 leaves are). + for (const std::vector& leaf : ppt::visit_all(above.index, p, 9)) { + EXPECT_GE(leaf.size(), size_t(p.c_min)); + } +} + +// The root's 70,000 points span two 65,536-point counting-sort blocks, so the +// per-block counts and cursors must combine into valid children. +TEST(PiPNNPartition, RootSpansCountingSortBlocks) { + namespace ppt = pipnn_partition_test; + const size_t n = 70000, d = 2; + ppt::FlatData data(ppt::gaussian_data(n, d, 31), d, faiss::METRIC_L2); + ppt::visit_all(data.index, ppt::small_params(faiss::METRIC_L2), ppt::kSeed); +} + +TEST(PiPNNPartition, LeavesGroupNeighbours) { + namespace ppt = pipnn_partition_test; + const size_t n = 5000, d = 16; + const std::vector x = ppt::gaussian_data(n, d, 2024); + ppt::FlatData l2(x, d, faiss::METRIC_L2); + ppt::FlatData ip(x, d, faiss::METRIC_INNER_PRODUCT); + struct Case { + const char* name; + const faiss::Index* storage; + faiss::MetricType metric; + bool by_angle; + double min_fraction; // measured: 0.986 for L2, 0.950 for IP + }; + const Case cases[] = { + {"L2", &l2.index, faiss::METRIC_L2, false, 0.95}, + {"IP", &ip.index, faiss::METRIC_INNER_PRODUCT, false, 0.9}, + {"IP by angle", &ip.index, faiss::METRIC_INNER_PRODUCT, true, 0.9}}; + for (const Case& c : cases) { + SCOPED_TRACE(c.name); + faiss::pipnn::PartitionParams p = ppt::small_params(c.metric); + p.ip_partition_by_angle = c.by_angle; + const ppt::Leaves leaves = ppt::visit_all(*c.storage, p, ppt::kSeed); + EXPECT_GE( + ppt::fraction_with_neighbour(leaves, x, d, c.metric), + c.min_fraction); + } +} + +TEST(PiPNNPartition, StatsDescribeLeaves) { + namespace ppt = pipnn_partition_test; + const size_t d = 16; + ppt::FlatData data(ppt::gaussian_data(5000, d, 2024), d, faiss::METRIC_L2); + const faiss::pipnn::PartitionParams p = ppt::small_params(faiss::METRIC_L2); + faiss::pipnn::PartitionStats stats; + const ppt::Leaves leaves = + ppt::visit_all(data.index, p, ppt::kSeed, &stats); + size_t instances = 0; + size_t max_leaf = 0; + for (const std::vector& leaf : leaves) { + instances += leaf.size(); + max_leaf = std::max(max_leaf, leaf.size()); + } + EXPECT_EQ(stats.n_leaves, leaves.size()); + EXPECT_EQ(stats.n_point_instances, instances); + EXPECT_EQ(stats.max_leaf, max_leaf); + EXPECT_GE(stats.max_depth_seen, 3); + size_t histogram_total = 0; + for (size_t h : stats.leaf_size_histogram) { + histogram_total += h; + } + EXPECT_EQ(histogram_total, stats.n_leaves); +} + +TEST(PiPNNPartition, AllZeroDataUsesSliceFallback) { + namespace ppt = pipnn_partition_test; + // All products are 0, so every point picks leaders 0..9, whose children + // equal the root and are cut into id slices. + const size_t n = 3000; + ppt::FlatData data(std::vector(n, 0.0f), 1, faiss::METRIC_L2); + faiss::pipnn::PartitionStats stats; + ppt::visit_all( + data.index, + ppt::small_params(faiss::METRIC_L2), + ppt::kSeed, + &stats); + EXPECT_EQ(stats.n_slice_fallbacks, 10u); + EXPECT_EQ(stats.n_leaves, 10u * ((n + 63) / 64)); +} + +TEST(PiPNNPartition, DuplicateGroupTerminatesAndCovers) { + namespace ppt = pipnn_partition_test; + const size_t n = 3000, d = 16; + std::vector x = ppt::gaussian_data(n, d, 77); + std::fill(x.begin() + 1000 * d, x.begin() + 1500 * d, 10.0f); + ppt::FlatData data(x, d, faiss::METRIC_L2); + const faiss::pipnn::PartitionParams p = ppt::small_params(faiss::METRIC_L2); + faiss::pipnn::PartitionStats stats; + ppt::visit_all(data.index, p, ppt::kSeed, &stats); + // The group is sliced once a child equals its parent (depth 7 here), well + // before the depth limit. + EXPECT_LT(stats.max_depth_seen, p.max_depth); +} + +TEST(PiPNNPartition, DepthLimitPrecedesL2Repartition) { + namespace ppt = pipnn_partition_test; + // 10 root children hold all points; with max_depth = 1 the depth limit + // applies before the L2 re-partition rule, so none is flagged. + const size_t n = 5000, d = 16; + ppt::FlatData data( + ppt::collinear_data(n, d, 31), d, faiss::METRIC_INNER_PRODUCT); + faiss::pipnn::PartitionParams p = + ppt::small_params(faiss::METRIC_INNER_PRODUCT); + p.max_depth = 1; + faiss::pipnn::PartitionStats stats; + ppt::visit_all(data.index, p, ppt::kSeed, &stats); + EXPECT_EQ(stats.n_l2_repartitions, 0u); + EXPECT_EQ(stats.n_slice_fallbacks, 10u); +} + +TEST(PiPNNPartition, WavesDoNotChangeLeaves) { + namespace ppt = pipnn_partition_test; + // Waves that carry L2 re-partition flags. + const size_t n = 5000, d = 16; + ppt::FlatData ip( + ppt::collinear_data(n, d, 31), d, faiss::METRIC_INNER_PRODUCT); + faiss::pipnn::PartitionParams p_ip = + ppt::small_params(faiss::METRIC_INNER_PRODUCT); + faiss::pipnn::PartitionStats one_wave_stats; + const ppt::Leaves one_wave = + ppt::visit_all(ip.index, p_ip, ppt::kSeed, &one_wave_stats); + // The children of the 10 largest-norm leaders hold all points and are + // flagged; their descendants rank by L2 and are not flagged again. + EXPECT_EQ(one_wave_stats.n_l2_repartitions, 10u); + p_ip.wave_budget = 3000; + faiss::pipnn::PartitionStats ip_stats; + EXPECT_TRUE( + one_wave == ppt::visit_all(ip.index, p_ip, ppt::kSeed, &ip_stats)); + EXPECT_GT(ip_stats.n_waves, 1u); +} + +namespace pipnn_partition_test { + +struct AlwaysInterrupt : faiss::InterruptCallback { + bool want_interrupt() override { + return true; + } +}; + +struct InterruptGuard { + ~InterruptGuard() { + faiss::InterruptCallback::clear_instance(); + } +}; + +} // namespace pipnn_partition_test + +TEST(PiPNNPartition, InterruptStopsWithin64Items) { + namespace ppt = pipnn_partition_test; + // All-zero data gives one region of 470 slice leaves. With one thread the + // master polls after items 0, 64, ...; the interrupt is set while visiting + // item 9, so items 10..64 still run. + ppt::FlatData data(std::vector(3000, 0.0f), 1, faiss::METRIC_L2); + const faiss::pipnn::PartitionParams p = ppt::small_params(faiss::METRIC_L2); + const size_t install_at = 10; + std::string what; + size_t visited = 0; + { + ppt::InterruptGuard guard; + ppt::ScopedOmpThreads one_thread(1); + try { + faiss::pipnn::partition_and_visit( + data.index, + p, + ppt::kSeed, + [&](const int32_t*, size_t) { + if (++visited == install_at) { + faiss::InterruptCallback::instance.reset( + new ppt::AlwaysInterrupt()); + } + }, + nullptr); + } catch (const faiss::FaissException& e) { + what = e.what(); + } + } + EXPECT_NE(what.find("interrupted"), std::string::npos) << what; + EXPECT_EQ(visited - install_at, 55u); +} + +/************************************************************* + * PiPNN build assembly + *************************************************************/ + +namespace pipnn_build_test { + +namespace pipnn = faiss::pipnn; +namespace ppt = pipnn_partition_test; + +// Many leaves, merges and depth >= 3 on 2000 points. +faiss::PiPNN small_params() { + faiss::PiPNN p(16); + p.c_max = 64; + p.c_min = 16; + p.leader_cap = 64; + p.reservoir_size = 32; + return p; +} + +std::vector graph_of(const faiss::PiPNN& p) { + return std::vector( + p.graph.data(), p.graph.data() + p.graph.size()); +} + +TEST(PiPNNMedoid, LowestIdArgmin) { + // Point 70000, in the second block, is at the mean of the others. + const size_t d = 8, n = pipnn::kMedoidBlock + 4465; + std::vector x = ppt::gaussian_data(n, d, 123); + for (size_t i = 0; i < n * d; i++) { + x[i] = i / d == 70000 ? 3.0f : x[i] + 3.0f; + } + ppt::FlatData data(x, d, faiss::METRIC_L2); + EXPECT_EQ(pipnn::medoid_and_validate(data.index), 70000); + + // All points tie, in two blocks. + ppt::FlatData zeros( + std::vector(pipnn::kMedoidBlock + 1, 0.0f), + 1, + faiss::METRIC_L2); + EXPECT_EQ(pipnn::medoid_and_validate(zeros.index), 0); +} + +TEST(PiPNNMedoid, NormCVIgnoresZeros) { + ppt::FlatData data({2.0f, 6.0f, 0.0f}, 1, faiss::METRIC_INNER_PRODUCT); + float cv = 0; + pipnn::medoid_and_validate(data.index, &cv); + EXPECT_FLOAT_EQ(cv, 0.5f); +} + +TEST(PiPNNMedoid, RejectsInvalidVectors) { + const size_t n = 100, d = 8; + // 1e19 squares to 1e38 > FLT_MAX / 8 + for (float v : {std::numeric_limits::quiet_NaN(), 1e19f}) { + SCOPED_TRACE(v); + std::vector x = ppt::gaussian_data(n, d, 5); + x[37 * d + 3] = v; + ppt::FlatData data(x, d, faiss::METRIC_L2); + EXPECT_THROW( + pipnn::medoid_and_validate(data.index), faiss::FaissException); + } +} + +TEST(PiPNNRobustPrune, HandExamples) { + std::vector out; + auto prune = [&](const float* D, + const std::vector& cand, + faiss::MetricType metric, + float alpha, + int R) { + std::vector order(cand.size()); + out.resize(R); + pipnn::robust_prune( + D, + cand.size() + 1, + cand.data(), + metric, + alpha, + R, + order.data(), + out.data()); + }; + + // L2: x = 0 on a line, candidates 5, 6, 7 at 1, 2 and -1.5. + // clang-format off + const float L2[16] = { + 0, 1, 4, 2.25f, + 1, 0, 1, 6.25f, + 4, 1, 0, 12.25f, + 2.25f, 6.25f, 12.25f, 0}; + // clang-format on + // alpha 1.2: 5 prunes 6 (1.2 * 1 < 4); 7 survives (1.2 * 6.25 > 2.25). + prune(L2, {5, 6, 7}, faiss::METRIC_L2, 1.2f, 3); + EXPECT_EQ(out, std::vector({5, 7, -1})); + prune(L2, {5, 6, 7}, faiss::METRIC_L2, 5.0f, 3); // 5 >= 4 + EXPECT_EQ(out, std::vector({5, 7, 6})); + + // IP, d = -dot: c is pruned by y if d(y, c) < alpha * d(x, c). + // clang-format off + const float IP[16] = { + -5, -4, -3, -2, + -4, -5, -4, -1, + -3, -4, -5, -2.5f, + -2, -1, -2.5f, -5}; + // clang-format on + // alpha 1: 5 prunes 6 (-4 < -3); 7 survives (-1 >= -2). + prune(IP, {5, 6, 7}, faiss::METRIC_INNER_PRODUCT, 1.0f, 3); + EXPECT_EQ(out, std::vector({5, 7, -1})); + prune(IP, {5, 6, 7}, faiss::METRIC_INNER_PRODUCT, 1.5f, 3); + EXPECT_EQ(out, std::vector({5, 6, 7})); // -4 >= -4.5 + + // Candidates 9 and 8 at +1 and -1: the tie goes to the lower id, and R + // caps the row. + const float tie[9] = {0, 1, 1, 1, 0, 4, 1, 4, 0}; + prune(tie, {9, 8}, faiss::METRIC_L2, 1.2f, 1); + EXPECT_EQ(out, std::vector({8})); +} + +// Counts reconstruct() calls, one per row read; call number throw_at throws. +struct InjectingIndex : faiss::IndexFlatL2 { + mutable std::atomic calls{0}; + int64_t throw_at = 0; // 0 = never + + InjectingIndex(const std::vector& x, size_t d_in) + : faiss::IndexFlatL2(d_in) { + add(x.size() / d_in, x.data()); + } + + void reconstruct(faiss::idx_t key, float* out) const override { + FAISS_THROW_IF_MSG(++calls == throw_at, "injected read failure"); + faiss::IndexFlatL2::reconstruct(key, out); + } + + void arm(int64_t k) { + throw_at = k; + calls = 0; + } +}; + +struct PredicateInterrupt : faiss::InterruptCallback { + std::function pred; + explicit PredicateInterrupt(std::function p) : pred(std::move(p)) {} + bool want_interrupt() override { + return pred(); + } +}; + +// Builds once and records the graph and its read count; the two medoid passes +// make reads 1..2n, and barriers keep counts independent of the thread count. +class PiPNNBuilt : public testing::Test { + protected: + static constexpr size_t n = 2000, d = 16; + InjectingIndex storage{ppt::gaussian_data(n, d, 82), d}; + faiss::PiPNN p = small_params(); + std::vector graph; + int32_t entry_point = -1; + int64_t total = 0; + + void SetUp() override { + p.build(storage); + graph = graph_of(p); + entry_point = p.entry_point; + total = storage.calls; + } + + void expect_unchanged() { + EXPECT_EQ(graph_of(p), graph); + EXPECT_EQ(p.entry_point, entry_point); + EXPECT_EQ(p.ntotal, faiss::idx_t(n)); + } +}; + +TEST_F(PiPNNBuilt, GraphIndependentOfChunkSize) { + faiss::PiPNN chunked = small_params(); + pipnn::detail::build_with_chunk(chunked, storage, 700, false); // 3 chunks + EXPECT_EQ(graph_of(chunked), graph); +} + +TEST_F(PiPNNBuilt, EmptyStorageResets) { + p.build(faiss::IndexFlatL2(d)); + EXPECT_EQ(p.graph.size(), 0u); + EXPECT_EQ(p.entry_point, -1); + EXPECT_EQ(p.ntotal, 0); +} + +TEST_F(PiPNNBuilt, ReadFailureKeepsPreviousGraph) { + const int64_t partition = 2 * n + 1; + for (int64_t k : {partition, total}) { + SCOPED_TRACE(k); + storage.arm(k); + EXPECT_THROW(p.build(storage), faiss::FaissException); + expect_unchanged(); + } +} + +// The interrupt is raised from a given read on; the build must stop by +// last_allowed. +TEST_F(PiPNNBuilt, InterruptStopsTheBuild) { + // With one thread, the medoid pass polls after its only block, and the + // last final-prune items run after the last poll of the region, so only + // the check after it sees an interrupt raised there. + ppt::ScopedOmpThreads one_thread(1); + struct Window { + const char* phase; + int64_t raise_from, last_allowed; + }; + const Window windows[] = { + {"before any read", 0, 0}, + {"first medoid pass", 1, n}, + {"last read", total, total}}; + for (const Window& w : windows) { + SCOPED_TRACE(w.phase); + storage.arm(0); + { + ppt::InterruptGuard guard; + faiss::InterruptCallback::instance.reset(new PredicateInterrupt( + [&] { return storage.calls >= w.raise_from; })); + EXPECT_THROW(p.build(storage), faiss::FaissException); + } + EXPECT_LE(storage.calls.load(), w.last_allowed); + expect_unchanged(); + } +} + +} // namespace pipnn_build_test diff --git a/thirdparty/faiss/tests/test_pipnn.py b/thirdparty/faiss/tests/test_pipnn.py new file mode 100644 index 000000000..2da5a94de --- /dev/null +++ b/thirdparty/faiss/tests/test_pipnn.py @@ -0,0 +1,439 @@ +# 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 os +import platform +import tempfile +import unittest + +import faiss +import numpy as np + +from common_faiss_tests import get_dataset_2 + +DIM = 32 +NB = 20000 +NQ = 500 +K = 10 + + +def recall(index, xb, xq): + _, gt = faiss.knn(xq, xb, K, index.metric_type) + _, labels = index.search(xq, K) + return faiss.eval_intersection(labels, gt) / labels.size + + +def graph_of(index): + return faiss.vector_to_array(index.pipnn.graph), index.pipnn.entry_point + + +class TestPiPNNBuild(unittest.TestCase): + + def build(self, xb, metric, **params): + index = faiss.IndexPiPNNFlat(DIM, 16, metric) + # many leaves, merges and depth >= 3 + index.pipnn.c_max = 64 + index.pipnn.c_min = 16 + for name, value in params.items(): + setattr(index.pipnn, name, value) + index.add(xb) + return index + + def test_deterministic_build(self): + self.addCleanup(faiss.omp_set_num_threads, faiss.omp_get_max_threads()) + _, xb_l2, _ = get_dataset_2(DIM, 0, 3000, 0) + # unnormalized, mixed-sign inner products + scale = np.random.RandomState(123).uniform(0.5, 2.0, size=(3000, 1)) + xb_ip = (xb_l2 * scale).astype("float32") + for metric, xb in ( + (faiss.METRIC_L2, xb_l2), + (faiss.METRIC_INNER_PRODUCT, xb_ip), + ): + with self.subTest(metric=metric): + faiss.omp_set_num_threads(1) + i1 = self.build(xb, metric) + faiss.omp_set_num_threads(8) + i8 = self.build(xb, metric, partition_wave_budget=1) + np.testing.assert_equal(graph_of(i8), graph_of(i1)) + # the entry point is the L2 medoid + d2 = ((xb - xb.mean(axis=0, dtype=np.float64)) ** 2).sum(1) + self.assertEqual(i1.pipnn.entry_point, np.argmin(d2)) + + def test_larger_fanout_adds_neighbours(self): + _, xb, _ = get_dataset_2(DIM, 0, 3000, 0) + _, nn = faiss.knn(xb, xb, 2) + + def nn_in_row(fanout): + index = faiss.IndexPiPNNFlat(DIM, 16) + index.pipnn.c_max = 64 + index.pipnn.c_min = 16 + faiss.copy_array_to_vector( + np.array(fanout, dtype="int32"), index.pipnn.fanout + ) + index.add(xb) + g, _ = graph_of(index) + return (g.reshape(len(xb), -1) == nn[:, 1:]).any(axis=1).mean() + + self.assertGreater(nn_in_row([20, 3]), nn_in_row([2, 1])) + + def test_effective_alpha(self): + p = faiss.PiPNN() + self.assertAlmostEqual(p.effective_alpha(faiss.METRIC_L2), 1.2, 6) + self.assertAlmostEqual( + p.effective_alpha(faiss.METRIC_INNER_PRODUCT), 1.2, 6 + ) + p.alpha = 1.25 + self.assertEqual(p.effective_alpha(faiss.METRIC_L2), 1.25) + self.assertRaises(RuntimeError, p.effective_alpha, faiss.METRIC_L1) + + def test_sq8_train_add_search(self): + _, xb, xq = get_dataset_2(DIM, 0, 10000, 200) + index = faiss.IndexPiPNNSQ(DIM, faiss.ScalarQuantizer.QT_8bit, 32) + self.assertFalse(index.is_trained) + with self.assertRaisesRegex(RuntimeError, "is_trained"): + index.add(xb) + self.assertRaises(RuntimeError, index.search, xq, K) + index.train(xb) + index.add(xb) + self.assertGreaterEqual(recall(index, xb, xq), 0.96) + + +class TestPiPNNRecall(unittest.TestCase): + + def test_recall_L2(self): + _, xb, xq = get_dataset_2(DIM, 0, NB, NQ) + index = faiss.IndexPiPNNFlat(DIM, 64) + index.add(xb) + self.assertGreaterEqual(recall(index, xb, xq), 0.97) + + def test_recall_IP(self): + _, xb, xq = get_dataset_2(DIM, 0, NB, NQ) + faiss.normalize_L2(xb) + index = faiss.IndexPiPNNFlat(DIM, 64, faiss.METRIC_INNER_PRODUCT) + index.add(xb) + self.assertGreaterEqual(recall(index, xb, xq), 0.96) + D, I = index.search(xq, K) + # inner products are returned positive, not negated + np.testing.assert_allclose( + D[:, 0], (xq * xb[I[:, 0]]).sum(axis=1), rtol=1e-4, atol=1e-4 + ) + + def test_recall_IP_varying_norms(self): + _, xb, xq = get_dataset_2(DIM, 0, NB, NQ) + xb *= np.random.RandomState(123).lognormal(sigma=2.0, size=(NB, 1)) + index = faiss.IndexPiPNNFlat(DIM, 64, faiss.METRIC_INNER_PRODUCT) + index.add(xb) + self.assertGreaterEqual(recall(index, xb, xq), 0.98) + + def test_recall_one_leaf(self): + # nb <= c_max: each point offers its reservoir_size nearest, not leaf_k + _, xb, xq = get_dataset_2(DIM, 0, 500, NQ) + index = faiss.IndexPiPNNFlat(DIM, 32) + index.add(xb) + index.pipnn.search_L = 16 + self.assertGreaterEqual(recall(index, xb, xq), 0.95) + + def test_recall_duplicates(self): + # the K nearest neighbours are all copies of the nearest one + _, xb, xq = get_dataset_2(DIM, 0, 2000, NQ) + xb = np.tile(xb, (K, 1)) + index = faiss.IndexPiPNNFlat(DIM, 32) + index.add(xb) + index = faiss.deserialize_index(faiss.serialize_index(index)) + self.assertGreaterEqual(recall(index, xb, xq), 0.95) + + +class TestPiPNNSearch(unittest.TestCase): + + @classmethod + def setUpClass(cls): + _, cls.xb, cls.xq = get_dataset_2(DIM, 0, 10000, 200) + cls.index = faiss.IndexPiPNNFlat(DIM, 32) + cls.index.add(cls.xb) + + def test_id_selector(self): + subset = np.sort( + np.random.RandomState(5).choice(10000, 3000, replace=False) + ) + params = faiss.SearchParametersPiPNN( + sel=faiss.IDSelectorBatch(subset), search_L=128 + ) + _, labels = self.index.search(self.xq, K, params=params) + self.assertTrue(np.all(np.isin(labels[labels >= 0], subset))) + _, gt = faiss.knn(self.xq, self.xb[subset], K) + r = faiss.eval_intersection(labels, subset[gt]) / labels.size + self.assertGreaterEqual(r, 0.90) + + def test_search_L(self): + index, P = self.index, faiss.SearchParametersPiPNN + self.addCleanup(setattr, index.pipnn, "search_L", index.pipnn.search_L) + index.pipnn.search_L = 16 + _, ref = index.search(self.xq, K) + # params with search_L = 0 inherit the index value + _, inherited = index.search(self.xq, K, params=P()) + np.testing.assert_array_equal(inherited, ref) + _, wide = index.search(self.xq, K, params=P(search_L=128)) + self.assertFalse(np.array_equal(wide, ref)) + # search_L < k searches with a beam of k + _, at_k = index.search(self.xq, K, params=P(search_L=K)) + _, below_k = index.search(self.xq, K, params=P(search_L=-1)) + np.testing.assert_array_equal(below_k, at_k) + + def test_k_above_ntotal(self): + for nb in (1, 20): + with self.subTest(nb=nb): + _, xb, xq = get_dataset_2(DIM, 0, nb, 5) + index = faiss.IndexPiPNNFlat(DIM, 32) + index.add(xb) + D, I = index.search(xq, nb + 5) + Dref, Iref = faiss.knn(xq, xb, nb) + np.testing.assert_array_equal(I[:, :nb], Iref) + np.testing.assert_allclose(D[:, :nb], Dref, rtol=1e-5) + np.testing.assert_array_equal(I[:, nb:], -1) + np.testing.assert_array_equal( + D[:, nb:], np.finfo(np.float32).max + ) + + +class TestPiPNNErrors(unittest.TestCase): + + def setUp(self): + _, self.xb, self.xq = get_dataset_2(DIM, 0, 3000, 10) + + def test_build_lifecycle(self): + prefilled = faiss.IndexFlatL2(DIM) + prefilled.add(self.xb) + from_storage = faiss.IndexPiPNN(prefilled, 32) + self.assertEqual(from_storage.ntotal, len(self.xb)) + deferred = faiss.IndexPiPNNFlat(DIM, 32) + deferred.defer_build = True + deferred.add(self.xb) + for index in (deferred, from_storage): + with self.assertRaisesRegex(RuntimeError, r"call build\(\)"): + index.search(self.xq, K) + index.build() + with self.assertRaisesRegex(RuntimeError, "incremental addition"): + index.add(self.xq) + _, labels = index.search(self.xq, K) + self.assertTrue(np.all(labels >= 0)) + index.storage.add(self.xq) + with self.assertRaisesRegex(RuntimeError, r"call build\(\)"): + index.search(self.xq, K) + + def test_unsupported_storage_ctor(self): + SQ = faiss.ScalarQuantizer + for storage in ( + faiss.IndexFlatL2Panorama(DIM, 4), + faiss.IndexScalarQuantizer(DIM, SQ.QT_0bit), + faiss.IndexScalarQuantizer(DIM, SQ.QT_4bit_tq), + faiss.IndexFlat(DIM, faiss.METRIC_L1), + ): + with self.assertRaisesRegex(RuntimeError, "unsupported storage"): + faiss.IndexPiPNN(storage, 32) + + def test_reset_and_rebuild(self): + index = faiss.IndexPiPNNFlat(DIM, 32, faiss.METRIC_INNER_PRODUCT) + index.add(self.xb) + _, Iref = index.search(self.xq, K) + index.reset() + Dempty, Iempty = index.search(self.xq, K) + np.testing.assert_array_equal(Iempty, -1) + np.testing.assert_array_equal(Dempty, -np.finfo(np.float32).max) + index.add(self.xb) + np.testing.assert_array_equal(index.search(self.xq, K)[1], Iref) + + def test_invalid_params(self): + with self.assertRaisesRegex(RuntimeError, "has no storage"): + faiss.IndexPiPNN(None, 32) + index = faiss.IndexPiPNNFlat(DIM, 32) + index.pipnn.hash_bits = 17 + with self.assertRaisesRegex(RuntimeError, "hash_bits"): + index.add(self.xb) + + bad = [ + ("R", 0), + ("R", 65), # > reservoir_size + ("leaf_k", 0), + ("leaf_k", 1025), # > c_max + ("hash_bits", 0), + ("reservoir_size", 0), + ("reservoir_size", 256), + ("c_min", 0), + ("c_min", 2000), # > c_max + ("c_max", 4097), + ("leader_cap", 0), + ("leader_cap", 65536), + ("leader_fraction", -0.1), + ("leader_fraction", 1.5), + ("alpha", 0.5), + ("alpha", float("inf")), + ] + for name, value in bad: + with self.subTest(name=name, value=value): + p = faiss.PiPNN() + setattr(p, name, value) + self.assertRaises(RuntimeError, p.check_params) + p = faiss.PiPNN() + p.fanout.push_back(0) + self.assertRaises(RuntimeError, p.check_params) + limits = { + "leaf_k": 4096, + "hash_bits": 16, + "reservoir_size": 255, + "c_min": 4096, + "c_max": 4096, + "leader_cap": 65535, + "leader_fraction": 0, + "alpha": 1, + } + p = faiss.PiPNN() + for name, value in limits.items(): + setattr(p, name, value) + p.check_params() + + def test_interrupts(self): + index = faiss.IndexPiPNNFlat(DIM, 32) + index.add(self.xb) + with faiss.TimeoutGuard(1e-6): + with self.assertRaises(RuntimeError): + index.search(self.xq, K) + + +class TestPiPNNSerialization(unittest.TestCase): + + def setUp(self): + _, self.xb, self.xq = get_dataset_2(DIM, 0, 2000, 50) + + def assert_same_index(self, a, b): + np.testing.assert_equal(graph_of(b), graph_of(a)) + np.testing.assert_equal(b.search(self.xq, K), a.search(self.xq, K)) + + def test_fourcc_follows_storage(self): + # a plain IndexPiPNN reads back as the subclass of its storage type + index = faiss.IndexPiPNN(faiss.IndexFlatIP(DIM), 16) + index.add(self.xb) + index2 = faiss.deserialize_index(faiss.serialize_index(index)) + self.assertIsInstance(index2, faiss.IndexPiPNNFlat) + self.assert_same_index(index, index2) + + sq = faiss.IndexScalarQuantizer(DIM, faiss.ScalarQuantizer.QT_8bit) + sq.train(self.xb) + index = faiss.IndexPiPNN(sq, 16) + index.add(self.xb) + index2 = faiss.deserialize_index(faiss.serialize_index(index)) + self.assertIsInstance(index2, faiss.IndexPiPNNSQ) + self.assert_same_index(index, index2) + + def test_round_trip_unbuilt_params(self): + index = faiss.IndexPiPNNFlat(DIM, 24, faiss.METRIC_INNER_PRODUCT) + values = { + "leaf_k": 3, + "hash_bits": 10, + "reservoir_size": 48, + "c_max": 512, + "c_min": 64, + "leader_cap": 500, + "leader_fraction": 0.01, + "alpha": 1.1, + "seed": 4321, + "ip_partition_by_angle": True, + "search_L": 40, + } + for name, value in values.items(): + setattr(index.pipnn, name, value) + faiss.copy_array_to_vector( + np.array([8, 2], dtype="int32"), index.pipnn.fanout + ) + index.defer_build = True + index.add(self.xb) + + index2 = faiss.deserialize_index(faiss.serialize_index(index)) + self.assertTrue(index2.defer_build) + for name in ["R", *values]: + self.assertEqual( + getattr(index2.pipnn, name), getattr(index.pipnn, name), name + ) + np.testing.assert_array_equal( + faiss.vector_to_array(index2.pipnn.fanout), [8, 2] + ) + + def test_state_the_reader_rejects_is_not_written(self): + index = faiss.IndexPiPNNFlat(DIM, 16) + index.add(self.xq) + index.pipnn.R = 8 + with self.assertRaisesRegex(RuntimeError, "graph size"): + faiss.serialize_index(index) + index = faiss.IndexPiPNNFlat(DIM, 16) + index.storage.add(self.xq) + with self.assertRaisesRegex(RuntimeError, "cannot serialize"): + faiss.serialize_index(index) + + @unittest.skipIf( + platform.system() not in ["Windows", "Linux", "Darwin"], + "supported OSes only", + ) + def test_mmap_load(self): + index = faiss.IndexPiPNNFlat(DIM, 16) + index.add(self.xb) + + fd, fname = tempfile.mkstemp() + os.close(fd) + + index2 = None + try: + faiss.write_index(index, fname) + index2 = faiss.read_index(fname, faiss.IO_FLAG_MMAP_IFC) + self.assertFalse(index2.pipnn.graph.is_owned) + self.assert_same_index(index, index2) + finally: + del index2 + if os.path.exists(fname): + try: + os.unlink(fname) + except Exception: + pass + + +class TestPiPNNClone(unittest.TestCase): + def test_clone_survives_original(self): + _, xb, xq = get_dataset_2(DIM, 0, 2000, 50) + index = faiss.IndexPiPNNFlat(DIM, 16) + index.add(xb) + ref = graph_of(index), index.search(xq, K) + clone = faiss.clone_index(index) + self.assertIsInstance(clone, faiss.IndexPiPNNFlat) + self.assertTrue(clone.own_fields) + index.reset() + del index + np.testing.assert_equal((graph_of(clone), clone.search(xq, K)), ref) + + +class TestPiPNNFactory(unittest.TestCase): + def test_strings(self): + SQ, IP = faiss.ScalarQuantizer, faiss.METRIC_INNER_PRODUCT + for desc, cls, R, qtype in [ + ("PiPNN32,Flat", faiss.IndexPiPNNFlat, 32, None), + ("PiPNN16", faiss.IndexPiPNNFlat, 16, None), # as for HNSW/NSG + ("PiPNN_SQ8", faiss.IndexPiPNNSQ, 64, SQ.QT_8bit), + ]: + with self.subTest(desc=desc): + index = faiss.index_factory(DIM, desc, IP) + self.assertIsInstance(index, cls) + self.assertEqual(index.pipnn.R, R) + self.assertEqual(index.storage.metric_type, IP) + if qtype is not None: + storage = faiss.downcast_index(index.storage) + self.assertEqual(storage.sq.qtype, qtype) + + +class TestPiPNNCoarseQuantizer(unittest.TestCase): + def test_ivf_pipnn(self): + xt, _, xq = get_dataset_2(DIM, 10000, 0, NQ) + index = faiss.index_factory(DIM, "IVF256_PiPNN,Flat") + quantizer = faiss.downcast_index(index.quantizer) + self.assertEqual(quantizer.pipnn.R, 64) + index.train(xt) + centroids = quantizer.reconstruct_n(0, quantizer.ntotal) + self.assertGreaterEqual(recall(quantizer, centroids, xq), 0.95) diff --git a/thirdparty/faiss/tests/test_pq_code_distance.cpp b/thirdparty/faiss/tests/test_pq_code_distance.cpp index 45d4e8132..3959e5acf 100644 --- a/thirdparty/faiss/tests/test_pq_code_distance.cpp +++ b/thirdparty/faiss/tests/test_pq_code_distance.cpp @@ -7,17 +7,10 @@ #include -#include - -#include -#include #include -#include #include -#include #include -#include #include #include @@ -40,31 +33,18 @@ size_t nMismatches( } void test( - // dimensionality of the data - const size_t dim, // number of subquantizers const size_t subq, - // bits per subquantizer - const size_t nbits, // number of codes to process const size_t n) { - FAISS_THROW_IF_NOT(nbits == 8); - - // remove if benchmarking is needed - omp_set_num_threads(1); - - // rng std::minstd_rand rng(123); - std::uniform_int_distribution u(0, 255); std::uniform_real_distribution uf(0, 1); - // initialize lookup std::vector lookup(256 * subq, 0); for (size_t i = 0; i < lookup.size(); i++) { lookup[i] = uf(rng); } - // initialize codes std::vector codes(n * subq); #pragma omp parallel { @@ -77,194 +57,71 @@ void test( } } - // warmup. compute reference results using explicit scalar + // reference results using explicit scalar std::vector resultsRef(n, 0); - for (size_t k = 0; k < 10; k++) { #pragma omp parallel for schedule(guided) - for (int64_t i = 0; i < (int64_t)n; i++) { - resultsRef[i] = faiss::PQCodeDistance< - faiss::PQDecoder8, - faiss::SIMDLevel::NONE>:: - distance_single_code( - subq, 8, lookup.data(), codes.data() + subq * i); - } - } - - // scalar, 1 code per step - std::vector resultsScalar1x(n, 0); - double scalar1xMsec = 0; - { - const auto startingTimepoint = std::chrono::steady_clock::now(); - for (size_t k = 0; k < 1000; k++) { -#pragma omp parallel for schedule(guided) - for (int64_t i = 0; i < (int64_t)n; i++) { - resultsScalar1x[i] = faiss::PQCodeDistance< - faiss::PQDecoder8, - faiss::SIMDLevel::NONE>:: - distance_single_code( - subq, - 8, - lookup.data(), - codes.data() + subq * i); - } - } - const auto endingTimepoint = std::chrono::steady_clock::now(); - - std::chrono::duration duration = - endingTimepoint - startingTimepoint; - scalar1xMsec = (duration.count() * 1000.0); + for (int64_t i = 0; i < (int64_t)n; i++) { + resultsRef[i] = faiss::PQCodeDistance< + faiss::PQDecoder8, + faiss::SIMDLevel::NONE>:: + distance_single_code( + subq, 8, lookup.data(), codes.data() + subq * i); } // scalar, 4 codes per step std::vector resultsScalar4x(n, 0); - double scalar4xMsec = 0; - { - const auto startingTimepoint = std::chrono::steady_clock::now(); - for (size_t k = 0; k < 1000; k++) { #pragma omp parallel for schedule(guided) - for (int64_t i = 0; i < (int64_t)n; i += 4) { - faiss::PQCodeDistance< - faiss::PQDecoder8, - faiss::SIMDLevel::NONE>:: - distance_four_codes( - subq, - 8, - lookup.data(), - codes.data() + subq * (i + 0), - codes.data() + subq * (i + 1), - codes.data() + subq * (i + 2), - codes.data() + subq * (i + 3), - resultsScalar4x[i + 0], - resultsScalar4x[i + 1], - resultsScalar4x[i + 2], - resultsScalar4x[i + 3]); - } - } - - const auto endingTimepoint = std::chrono::steady_clock::now(); - - std::chrono::duration duration = - endingTimepoint - startingTimepoint; - scalar4xMsec = (duration.count() * 1000.0); + for (int64_t i = 0; i < (int64_t)n; i += 4) { + faiss::PQCodeDistance:: + distance_four_codes( + subq, + 8, + lookup.data(), + codes.data() + subq * (i + 0), + codes.data() + subq * (i + 1), + codes.data() + subq * (i + 2), + codes.data() + subq * (i + 3), + resultsScalar4x[i + 0], + resultsScalar4x[i + 1], + resultsScalar4x[i + 2], + resultsScalar4x[i + 3]); } // dispatched, 1 code per step (best available SIMD level) std::vector resultsDispatched1x(n, 0); - double dispatched1xMsec = 0; - { - const auto startingTimepoint = std::chrono::steady_clock::now(); - for (size_t k = 0; k < 1000; k++) { #pragma omp parallel for schedule(guided) - for (int64_t i = 0; i < (int64_t)n; i++) { - resultsDispatched1x[i] = faiss::pq_code_distance_8bit_single( - subq, lookup.data(), codes.data() + subq * i); - } - } - const auto endingTimepoint = std::chrono::steady_clock::now(); - - std::chrono::duration duration = - endingTimepoint - startingTimepoint; - dispatched1xMsec = (duration.count() * 1000.0); + for (int64_t i = 0; i < (int64_t)n; i++) { + resultsDispatched1x[i] = faiss::pq_code_distance_8bit_single( + subq, lookup.data(), codes.data() + subq * i); } // dispatched, 4 codes per step (best available SIMD level) std::vector resultsDispatched4x(n, 0); - double dispatched4xMsec = 0; - { - const auto startingTimepoint = std::chrono::steady_clock::now(); - for (size_t k = 0; k < 1000; k++) { #pragma omp parallel for schedule(guided) - for (int64_t i = 0; i < (int64_t)n; i += 4) { - faiss::pq_code_distance_8bit_four( - subq, - lookup.data(), - codes.data() + subq * (i + 0), - codes.data() + subq * (i + 1), - codes.data() + subq * (i + 2), - codes.data() + subq * (i + 3), - resultsDispatched4x[i + 0], - resultsDispatched4x[i + 1], - resultsDispatched4x[i + 2], - resultsDispatched4x[i + 3]); - } - } - - const auto endingTimepoint = std::chrono::steady_clock::now(); - - std::chrono::duration duration = - endingTimepoint - startingTimepoint; - dispatched4xMsec = (duration.count() * 1000.0); + for (int64_t i = 0; i < (int64_t)n; i += 4) { + faiss::pq_code_distance_8bit_four( + subq, + lookup.data(), + codes.data() + subq * (i + 0), + codes.data() + subq * (i + 1), + codes.data() + subq * (i + 2), + codes.data() + subq * (i + 3), + resultsDispatched4x[i + 0], + resultsDispatched4x[i + 1], + resultsDispatched4x[i + 2], + resultsDispatched4x[i + 3]); } - const size_t nMismatchesS1 = nMismatches(resultsRef, resultsScalar1x); - const size_t nMismatchesS4 = nMismatches(resultsRef, resultsScalar4x); - const size_t nMismatchesD1 = nMismatches(resultsRef, resultsDispatched1x); - const size_t nMismatchesD4 = nMismatches(resultsRef, resultsDispatched4x); - - std::cout << "Dim = " << dim << ", subq = " << subq << ", nbits = " << nbits - << ", n = " << n << std::endl; - std::cout << "Scalar 1x code: " << scalar1xMsec << " msec, " - << nMismatchesS1 << " mismatches" << std::endl; - std::cout << "Scalar 4x code: " << scalar4xMsec << " msec, " - << nMismatchesS4 << " mismatches" << std::endl; - std::cout << "Dispatched 1x code: " << dispatched1xMsec << " msec, " - << nMismatchesD1 << " mismatches" << std::endl; - std::cout << "Dispatched 4x code: " << dispatched4xMsec << " msec, " - << nMismatchesD4 << " mismatches" << std::endl; - std::cout << std::endl; - - ASSERT_EQ(nMismatchesS1, 0); - ASSERT_EQ(nMismatchesS4, 0); - ASSERT_EQ(nMismatchesD1, 0); - ASSERT_EQ(nMismatchesD4, 0); -} - -// this test can be used as a benchmark. -// 1. Increase the value of NELEMENTS -// 2. Remove omp_set_num_threads() - -constexpr size_t NELEMENTS = 10000; - -TEST(TestCodeDistance, SUBQ4_NBITS8) { - test(256, 4, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ8_NBITS8) { - test(256, 8, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ16_NBITS8) { - test(256, 16, 8, NELEMENTS); + ASSERT_EQ(nMismatches(resultsRef, resultsScalar4x), 0); + ASSERT_EQ(nMismatches(resultsRef, resultsDispatched1x), 0); + ASSERT_EQ(nMismatches(resultsRef, resultsDispatched4x), 0); } -TEST(TestCodeDistance, SUBQ32_NBITS8) { - test(256, 32, 8, NELEMENTS); -} - -// Odd M values exercise the scalar tail within SIMD implementations. -// AVX2/AVX512 process M in fixed-size chunks; these values ensure the -// remainder path is correct. - -TEST(TestCodeDistance, SUBQ1_NBITS8) { - test(256, 1, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ3_NBITS8) { - test(256, 3, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ5_NBITS8) { - test(256, 5, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ7_NBITS8) { - test(256, 7, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ9_NBITS8) { - test(256, 9, 8, NELEMENTS); -} - -TEST(TestCodeDistance, SUBQ15_NBITS8) { - test(256, 15, 8, NELEMENTS); +// M = 4 and 8 have dedicated AVX2 kernels, 16 and 32 fill the 16-wide blocks, +// and the other values exercise the leftover loops of the SIMD kernels. +TEST(TestCodeDistance, NBITS8) { + for (size_t subq : {1, 4, 5, 8, 9, 15, 16, 32}) { + SCOPED_TRACE(subq); + test(subq, 10000); + } } diff --git a/thirdparty/faiss/tests/test_pq_encoding.cpp b/thirdparty/faiss/tests/test_pq_encoding.cpp index 7b8ad2c1d..ec0d16db7 100644 --- a/thirdparty/faiss/tests/test_pq_encoding.cpp +++ b/thirdparty/faiss/tests/test_pq_encoding.cpp @@ -5,7 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -#include #include #include @@ -44,14 +43,13 @@ TEST(PQEncoderGeneric, encode) { const std::vector values = random_vector(nsubcodes); for (int nbits = minbits; nbits <= maxbits; ++nbits) { - std::cerr << "nbits = " << nbits << std::endl; + SCOPED_TRACE(nbits); const uint64_t mask = (1ull << nbits) - 1; std::unique_ptr codes( new uint8_t[(nsubcodes * maxbits + 7) / 8]); - // NOTE(hoss): Necessary scope to ensure trailing bits are flushed to - // mem. + // Scope so the encoder destructor flushes the trailing bits. { faiss::PQEncoderGeneric encoder(codes.get(), nbits); for (const auto& v : values) { @@ -67,42 +65,6 @@ TEST(PQEncoderGeneric, encode) { } } -TEST(PQEncoder8, encode) { - const int nsubcodes = 100; - const std::vector values = random_vector(nsubcodes); - const uint64_t mask = 0xFF; - std::unique_ptr codes(new uint8_t[nsubcodes]); - - faiss::PQEncoder8 encoder(codes.get(), 8); - for (const auto& v : values) { - encoder.encode(v & mask); - } - - faiss::PQDecoder8 decoder(codes.get(), 8); - for (int i = 0; i < nsubcodes; ++i) { - uint64_t v = decoder.decode(); - EXPECT_EQ(values[i] & mask, v); - } -} - -TEST(PQEncoder16, encode) { - const int nsubcodes = 100; - const std::vector values = random_vector(nsubcodes); - const uint64_t mask = 0xFFFF; - std::unique_ptr codes(new uint8_t[2 * nsubcodes]); - - faiss::PQEncoder16 encoder(codes.get(), 16); - for (const auto& v : values) { - encoder.encode(v & mask); - } - - faiss::PQDecoder16 decoder(codes.get(), 16); - for (int i = 0; i < nsubcodes; ++i) { - uint64_t v = decoder.decode(); - EXPECT_EQ(values[i] & mask, v); - } -} - TEST(PQFastScan, set_packed_element) { int d = 20, ntotal = 1000, M = 5, nbits = 4; const std::vector ds = random_vector_float(ntotal * d); diff --git a/thirdparty/faiss/tests/test_pqfs_unaligned.cpp b/thirdparty/faiss/tests/test_pqfs_unaligned.cpp index 1ff6698fb..a61478de1 100644 --- a/thirdparty/faiss/tests/test_pqfs_unaligned.cpp +++ b/thirdparty/faiss/tests/test_pqfs_unaligned.cpp @@ -16,16 +16,11 @@ #include #include -/** - * This validates we can run fast scan with unaligned codes and get the same - * results as aligned codes. On modern CPUs, unaligned codes appear to have - * similar performance characteristics to aligned codes. - */ +// Fast-scan accumulation must give the same result for unaligned codes. namespace { std::vector create_aligned_buffer(size_t size, size_t alignment) { - // Allocate extra space for alignment adjustment std::vector buffer(size + alignment); return buffer; } @@ -42,7 +37,6 @@ uint8_t* get_aligned_ptr(std::vector& buffer, size_t alignment) { uint8_t* get_unaligned_ptr(std::vector& buffer, size_t alignment) { uint8_t* aligned = get_aligned_ptr(buffer, alignment); - // Return pointer that is off by 1 byte from alignment return aligned + 1; } @@ -63,8 +57,6 @@ TEST(FastScanUnaligned, TestUnalignedCodesAccess) { std::vector aligned_buffer = create_aligned_buffer(code_size, alignment); - // unaligned_buffer itself is aligned but it's the buffer for the unaligned - // pointer. std::vector unaligned_buffer = create_aligned_buffer(code_size, alignment); @@ -100,8 +92,6 @@ TEST(FastScanUnaligned, TestUnalignedCodesAccess) { faiss::accumulate_to_mem( nq, result_size, nsq, codes_unaligned, LUT, accu_unaligned.data()); - // They should be the same, because codes_unaligned gets set to the same - // values as aligned, it's just not aligned. ASSERT_EQ(accu_aligned, accu_unaligned) << "Aligned and unaligned code paths should produce identical results"; diff --git a/thirdparty/faiss/tests/test_product_quantizer.py b/thirdparty/faiss/tests/test_product_quantizer.py index 623765edb..5ce271cc6 100644 --- a/thirdparty/faiss/tests/test_product_quantizer.py +++ b/thirdparty/faiss/tests/test_product_quantizer.py @@ -54,12 +54,10 @@ def do_test_codec(self, nbit): # can be encoded exactly x = np.hstack((centroids[0, idx[:, 0]], centroids[1, idx[:, 1]])) - # encode / decode codes = pq.compute_codes(x) xr = pq.decode(codes) assert np.all(xr == x) - # encode w/ external index assign_index = faiss.IndexFlatL2(8) pq.assign_index = assign_index codes2 = np.empty((100, pq.code_size), dtype="uint8") @@ -73,8 +71,8 @@ def test_codec(self): self.do_test_codec(i + 1) def test_codes_match_none(self): - """PQ codes are integer; encode dispatch must produce bit-identical - output at every SIMD level.""" + """dsub = 16 takes the BLAS encode path, whose codes must be + bit-identical at every SIMD level.""" if not faiss.SIMDConfig.is_simd_level_available(faiss.SIMDLevel_NONE): self.skipTest("SIMDLevel.NONE not available") d, cs = 64, 4 @@ -90,6 +88,30 @@ def test_codes_match_none(self): np.testing.assert_array_equal(codes, codes_none) +class TestPQTrainParallel(unittest.TestCase): + + def setUp(self): + faiss.omp_set_num_threads(4) + self.x = np.random.RandomState(123).rand(256, 32) + self.pq = faiss.ProductQuantizer(32, 8, 2) + + def test_parallel_training_gives_sequential_centroids(self): + centroids = [] + for assign_index in (None, faiss.IndexFlatL2(4)): + self.pq.assign_index = assign_index + self.pq.train(self.x) + centroids.append(faiss.vector_to_array(self.pq.centroids)) + np.testing.assert_array_equal(centroids[0], centroids[1]) + + def test_parallel_training_error(self): + with self.assertRaises(RuntimeError): + self.pq.train(self.x[:3]) + + def test_parallel_training_timeout(self): + with faiss.TimeoutGuard(1e-6), self.assertRaises(RuntimeError): + self.pq.train(self.x) + + @for_all_simd_levels class TestPQTransposedCentroids(unittest.TestCase): @@ -102,11 +124,9 @@ def do_test(self, d, dsub): codes = pq.compute_codes(xt) - # enable transposed centroids table to speedup compute_codes() pq.sync_transposed_centroids() codes_transposed = pq.compute_codes(xt) - # disable transposed centroids table pq.clear_transposed_centroids() codes_cleared = pq.compute_codes(xt) @@ -119,15 +139,9 @@ def test_dsub2(self): def test_dsub5(self): self.do_test(20, 5) - def test_dsub2_odd(self): - self.do_test(18, 2) - def test_dsub4(self): self.do_test(32, 4) - def test_dsub4_odd(self): - self.do_test(36, 4) - @for_all_simd_levels class TestPQTables(unittest.TestCase): @@ -137,7 +151,6 @@ def do_test(self, d, dsub, nbit=8, metric=None): self.do_test(d, dsub, nbit, faiss.METRIC_INNER_PRODUCT) self.do_test(d, dsub, nbit, faiss.METRIC_L2) return - # faiss.cvar.distance_compute_blas_threshold = 1000000 M = d // dsub pq = faiss.ProductQuantizer(d, M, nbit) @@ -153,7 +166,6 @@ def do_test(self, d, dsub, nbit=8, metric=None): ref_tab = np.zeros((nx, M, pq.ksub), "float32") - # computation of tables in numpy for sq in range(M): i0, i1 = sq * dsub, (sq + 1) * dsub xsub = x[:, i0:i1] @@ -177,7 +189,6 @@ def do_test(self, d, dsub, nbit=8, metric=None): else: raise AssertionError() - # compute sdc tables in numpy cent1 = np.expand_dims(centroids, axis=2) # [M, ksub, 1, dsub] cent2 = np.expand_dims(centroids, axis=1) # [M, 1, ksub, dsub] ref_sdc_tab = ((cent1 - cent2) ** 2).sum(3) @@ -197,18 +208,63 @@ def test_dsub2(self): def test_dsub5(self): self.do_test(20, 5) - def test_dsub2_odd(self): - self.do_test(18, 2) - def test_dsub4(self): self.do_test(32, 4) - def test_dsub4_odd(self): - self.do_test(36, 4) + def test_dsub2_4bit(self): + # ksub = 16, so the SIMD dsub2 kernels run. + self.do_test(16, 2, nbit=4) + + def test_dsub2_4bit_odd(self): + # M = 9 leaves a partial group of subquantizers in the dsub2 kernels. + self.do_test(18, 2, nbit=4) + + def test_dsub2_2bit(self): + # ksub = 4 is not a multiple of 8, so the dsub2 kernels must be + # skipped in favour of the generic path + self.do_test(16, 2, nbit=2) + - # too slow - # def test_12bit(self): - # self.do_test(32, 4, nbit=12) +@for_all_simd_levels +class TestPQDistancesToCodes(unittest.TestCase): + def check(self, index, xt, n=203): + codes = index.pq.compute_codes(xt[:n]) + scanner = index.get_InvertedListScanner(False, None, None) + scanner.set_query(faiss.swig_ptr(xt[0])) + scanner.set_list(0, 0) + distances = np.empty(n, dtype="float32") + scanner.distances_to_codes( + n, faiss.swig_ptr(codes), faiss.swig_ptr(distances) + ) + np.testing.assert_allclose( + distances, + [scanner.distance_to_code(faiss.swig_ptr(c)) for c in codes], + rtol=1e-5, + ) - def test_4bit(self): - self.do_test(32, 4, nbit=4) + def test_8bit(self): + # With scalar_gather clear, M = 30 takes the block kernel (M % 4 != 0 + # reaches its tail) and M = 128 the per-code fallback. n is not a + # multiple of the block size; inner product makes dis0 nonzero. + rs = np.random.RandomState(456) + original = faiss.cvar.SIMDConfig_scalar_gather + faiss.cvar.SIMDConfig_scalar_gather = False + try: + for M in [30, 128]: + with self.subTest(M=M): + xt = rs.rand(10000, 4 * M).astype("float32") + index = faiss.index_factory( + 4 * M, f"IVF1,PQ{M}np", faiss.METRIC_INNER_PRODUCT + ) + index.train(xt) + self.check(index, xt) + finally: + faiss.cvar.SIMDConfig_scalar_gather = original + + def test_fastscan(self): + # the default distances_to_codes steps by code_size + rs = np.random.RandomState(456) + xt = rs.rand(2000, 32).astype("float32") + index = faiss.index_factory(32, "IVF1,PQ16x4fs") + index.train(xt) + self.check(index, xt, n=50) diff --git a/thirdparty/faiss/tests/test_rabitq.py b/thirdparty/faiss/tests/test_rabitq.py index 2c2c03e99..a806149b9 100644 --- a/thirdparty/faiss/tests/test_rabitq.py +++ b/thirdparty/faiss/tests/test_rabitq.py @@ -13,12 +13,6 @@ from common_faiss_tests import for_all_simd_levels, NoneSIMDLevel -def random_rotation(d, seed=123): - rs = np.random.RandomState(seed) - Q, _ = np.linalg.qr(rs.randn(d, d)) - return Q - - # Exercise SIMD codepaths, maintain multiple of 16. TEST_DIM = 512 * 2 + 256 + 128 + 64 + 16 # 1488 TEST_N = 4096 @@ -46,16 +40,14 @@ def inv_rotation(self, x): return x @ self.P.T def add(self, Or): - # centering & normalization Orc = Or - self.centroid - self.O_norms = np.sqrt((Orc**2).sum(1)) # need to store the norms + self.O_norms = np.sqrt((Orc**2).sum(1)) O = Orc / self.O_norms[:, None] # 3.1.3 self.Xbarb = (self.inv_rotation(Orc) > 0).astype("int8") # 0, 1 # here the encoded vectors are stored as an int array for simplicity # but in the real code it would be as a packed uint8 array - # self.Xbarb = np.packbits(self.inv_rotation(Orc) > 0, axis=1) # reconstruct to compute Obar = self.rotation((2 * self.Xbarb - 1) / np.sqrt(self.d)) self.o_Obar = (O * Obar).sum(1) # store dot products @@ -75,9 +67,6 @@ def distances(self, Qr): mins, maxes = Qprime.min(axis=1)[:, None], Qprime.max(axis=1)[:, None] Delta = (maxes - mins) / (2**Bq - 1) - # article mentioned a randomized variant - # qbar = np.floor((Qprime - mins) / Delta + rs.rand(nq, d)) - # we'll use a non-randomized for the comparison purposes qbar = np.round((Qprime - mins) / Delta) # in the real implementation, this would be re-ordered @@ -85,10 +74,7 @@ def distances(self, Qr): # dot product matrix, integers -- this is the expensive operation dp = (qbar[:, None, :] * self.Xbarb[None, :, :]).sum(2) - # the operations below roll back the normalizations to get the distance - # estimates. it is likely that they could be merged - # or some of them could be left out because we are interested only - # in top-k compute (eq 19-20) + # roll back the normalizations to get (eq 19-20) sum_X = self.Xbarb.sum(1) sum_Q = qbar.sum(1)[:, None] sD = np.sqrt(d) @@ -116,15 +102,12 @@ def do_comparison_vs_pq_test(self, metric_type=faiss.METRIC_L2): k = 10 index_flat = faiss.IndexFlat(ds.d, metric_type) - index_flat.train(ds.get_train()) index_flat.add(ds.get_database()) _, I_f = index_flat.search(ds.get_queries(), k) def eval_I(I): return faiss.eval_intersection(I, I_f) / I_f.ravel().shape[0] - print() - for random_rotate in [False, True]: # PQ{D/4}x4fs, also 1 bit per query dimension @@ -132,7 +115,6 @@ def eval_I(I): # Share a single quantizer (much faster, minimal recall change) index_pq.pq.train_type = faiss.ProductQuantizer.Train_shared if random_rotate: - # wrap with random rotations rrot = faiss.RandomRotationMatrix(ds.d, ds.d) rrot.init(123) @@ -142,12 +124,10 @@ def eval_I(I): _, I_pq = index_pq.search(ds.get_queries(), k) loss_pq = 1 - eval_I(I_pq) - print(f"{random_rotate=:1}, {loss_pq=:5.3f}") np.testing.assert_(loss_pq < 0.4, f"{loss_pq}") index_rbq = faiss.IndexRaBitQ(ds.d, metric_type) if random_rotate: - # wrap with random rotations rrot = faiss.RandomRotationMatrix(ds.d, ds.d) rrot.init(123) @@ -158,19 +138,10 @@ def eval_I(I): def test(params, ratio_threshold, index, rotate, loss_pq_val): _, I_rbq = index.search(ds.get_queries(), k, params=params) - # ensure that RaBitQ and PQ are relatively close loss_rbq = 1 - eval_I(I_rbq) - print( - f"{rotate=:1}, {params.qb=}, {params.centered=:1}: " - f"{loss_rbq=:5.3f} = loss_pq * " - f"{loss_rbq / loss_pq_val:5.3f}" - f" < {ratio_threshold=:.2f}" - ) - np.testing.assert_(loss_rbq < loss_pq_val * ratio_threshold) for qb in [1, 2, 3, 4, 8]: - print() for centered in [False, True]: params = faiss.RaBitQSearchParameters( qb=qb, centered=centered @@ -190,40 +161,6 @@ def test_comparison_vs_pq_L2(self): def test_comparison_vs_pq_IP(self): self.do_comparison_vs_pq_test(faiss.METRIC_INNER_PRODUCT) - def test_comparison_vs_ref_L2_rrot(self, rrot_seed=123): - ds = datasets.SyntheticDataset(TEST_DIM, TEST_N, TEST_N, 1) - - ref_rbq = ReferenceRabitQ(ds.d, Bq=8) - ref_rbq.train(ds.get_train(), random_rotation(ds.d, rrot_seed)) - ref_rbq.add(ds.get_database()) - - index_rbq = faiss.IndexRaBitQ(ds.d, faiss.METRIC_L2) - index_rbq.qb = 8 - - # wrap with random rotations - rrot = faiss.RandomRotationMatrix(ds.d, ds.d) - rrot.init(rrot_seed) - - index_cand = faiss.IndexPreTransform(rrot, index_rbq) - index_cand.train(ds.get_train()) - index_cand.add(ds.get_database()) - - ref_dis = ref_rbq.distances(ds.get_queries()) - - dc = index_cand.get_distance_computer() - xq = ds.get_queries() - - # ensure that the correlation coefficient is very high - dc_dist = [0] * ds.nb - - dc.set_query(faiss.swig_ptr(xq[0])) - for j in range(ds.nb): - dc_dist[j] = dc(j) - - corr = np.corrcoef(dc_dist, ref_dis[0])[0, 1] - print(corr) - np.testing.assert_(corr > 0.9) - def test_comparison_vs_ref_L2(self): ds = datasets.SyntheticDataset(TEST_DIM, TEST_N, TEST_N, 1) @@ -268,6 +205,80 @@ def test_serde_rabitq(self): do_test_serde("RaBitQ") +@for_all_simd_levels +class TestRaBitQBatchedScan(unittest.TestCase): + def do_test(self, metric, nb_bits, qb, centered): + # The scans that estimate four codes at a time (no selector, or the + # selector after the distance) match the per-code scan bit for bit. + rs = np.random.RandomState(1234) + # 300 dims is 38 bytes per code, which leaves tails in every kernel, + # and 1003 codes leave a tail batch. + d, nb, nq = 300, 1003, 5 + xb = rs.randn(nb, d).astype("float32") + xq = rs.randn(nq, d).astype("float32") + index = faiss.IndexRaBitQ(d, metric, nb_bits) + index.qb = qb + index.centered = centered + index.train(xb) + index.add(xb) + + dc = index.get_distance_computer() + for k in [1, 10, 100, nb]: + D, I = index.search(xq, k) + for sel_after_distance in [False, True]: + params = faiss.RaBitQSearchParameters( + qb=qb, + centered=centered, + sel=faiss.IDSelectorAll(), + sel_after_distance=sel_after_distance, + ) + D1, I1 = index.search(xq, k, params=params) + np.testing.assert_array_equal(I, I1) + np.testing.assert_array_equal(D, D1) + # Every distance is the per-code one. + for q in range(nq): + dc.set_query(faiss.swig_ptr(xq[q])) + ref = np.array([dc(int(j)) for j in I[q]], dtype="float32") + np.testing.assert_array_equal(D[q], ref) + + def test_1bit_L2(self): + self.do_test(faiss.METRIC_L2, 1, 4, False) + + def test_1bit_IP(self): + self.do_test(faiss.METRIC_INNER_PRODUCT, 1, 4, False) + + def test_4bit_L2(self): + self.do_test(faiss.METRIC_L2, 4, 4, False) + + def test_4bit_IP(self): + self.do_test(faiss.METRIC_INNER_PRODUCT, 4, 4, False) + + def test_unbatched_kernels(self): + # These query encodings estimate four codes one by one. + self.do_test(faiss.METRIC_L2, 1, 8, False) + self.do_test(faiss.METRIC_L2, 1, 4, True) + self.do_test(faiss.METRIC_L2, 1, 0, False) + + def test_range_search(self): + # range_search scans single-stage, so it keeps the per-code distance: + # the full distance for multi-bit codes, not the 1-bit estimate. + rs = np.random.RandomState(123) + d, nb = 32, 1003 + xb = rs.randn(nb, d).astype("float32") + xq = rs.randn(1, d).astype("float32") + for nb_bits in [1, 4]: + index = faiss.IndexRaBitQ(d, faiss.METRIC_L2, nb_bits) + index.train(xb) + index.add(xb) + dc = index.get_distance_computer() + dc.set_query(faiss.swig_ptr(xq[0])) + ref = np.array([dc(j) for j in range(nb)], dtype="float32") + radius = float(np.median(ref)) + _, D, I = index.range_search(xq, radius) + np.testing.assert_array_equal(I, np.flatnonzero(ref < radius)) + np.testing.assert_array_equal(D, ref[ref < radius]) + + @for_all_simd_levels class TestIVFRaBitQ(unittest.TestCase): def do_comparison_vs_pq_test(self, metric_type=faiss.METRIC_L2): @@ -293,13 +304,10 @@ def do_comparison_vs_pq_test(self, metric_type=faiss.METRIC_L2): def eval_I(I): return faiss.eval_intersection(I, I_f) / I_f.ravel().shape[0] - print() - for random_rotate in [False, True]: quantizer = faiss.IndexFlat(d, metric_type) index_rbq = faiss.IndexIVFRaBitQ(quantizer, d, nlist, metric_type) if random_rotate: - # wrap with random rotations rrot = faiss.RandomRotationMatrix(d, d) rrot.init(123) @@ -315,7 +323,6 @@ def eval_I(I): # Share a single quantizer (much faster, minimal recall change) index_pq.pq.train_type = faiss.ProductQuantizer.Train_shared if random_rotate: - # wrap with random rotations rrot = faiss.RandomRotationMatrix(d, d) rrot.init(123) @@ -327,26 +334,15 @@ def eval_I(I): xq, k, params=faiss.IVFPQSearchParameters(nprobe=nprobe) ) loss_pq = 1 - eval_I(I_pq) - - print(f"{random_rotate=:1}, {loss_pq=:5.3f}") np.testing.assert_(loss_pq < 0.25, f"{loss_pq}") def test(params, ratio_threshold, index, rotate, loss_pq_val): _, I_rbq = index.search(xq, k, params=params) - # ensure that RaBitQ and PQ are relatively close loss_rbq = 1 - eval_I(I_rbq) - print( - f"{rotate=:1}, {params.qb=}, {params.centered=:1}: " - f"{loss_rbq=:5.3f} = loss_pq * " - f"{loss_rbq / loss_pq_val:5.3f}" - f" < {ratio_threshold=:.2f}" - ) - np.testing.assert_(loss_rbq < loss_pq_val * ratio_threshold) for qb in [1, 2, 3, 4, 8]: - print() for centered in [False, True]: params = faiss.IVFRaBitQSearchParameters( nprobe=nprobe, qb=qb, centered=centered @@ -396,53 +392,16 @@ def test_comparison_vs_ref_L2(self): np.testing.assert_array_equal(I_simd, I_none) - def test_comparison_vs_ref_L2_rrot(self): - # SIMD path must return identical results to NONE on the same - # index with a pre-applied random rotation (IndexPreTransform). - ds = datasets.SyntheticDataset(128, 4096, 4096, 100) - - k = 10 - nlist = 200 - rrot_seed = 123 - - index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2) - index_rbq = faiss.IndexIVFRaBitQ( - index_flat, ds.d, nlist, faiss.METRIC_L2 - ) - index_rbq.qb = 4 - - rrot = faiss.RandomRotationMatrix(ds.d, ds.d) - rrot.init(rrot_seed) - - index_cand = faiss.IndexPreTransform(rrot, index_rbq) - index_cand.train(ds.get_train()) - index_cand.add(ds.get_database()) - - for nprobe in 1, 4, 16: - params = faiss.IVFRaBitQSearchParameters() - params.qb = index_rbq.qb - params.nprobe = nprobe - _, I_simd, _ = faiss.search_with_parameters( - index_cand, ds.get_queries(), k, params, output_stats=True - ) - - with NoneSIMDLevel(): - _, I_none, _ = faiss.search_with_parameters( - index_cand, ds.get_queries(), k, params, output_stats=True - ) - - np.testing.assert_array_equal(I_simd, I_none) - def test_serde_ivfrabitq(self): do_test_serde("IVF16,RaBitQ") @for_all_simd_levels class TestRaBitQuantizerEncodeDecode(unittest.TestCase): - def do_test_encode_decode(self, d, metric): + def test_encode_decode_L2(self): # rabitq must precisely reconstruct a vector, # which consists of +A and -A values - + d = 16 seed = 123 rs = np.random.RandomState(seed) @@ -451,67 +410,31 @@ def do_test_encode_decode(self, d, metric): vec = (2 * rs.randint(0, 2, d * n) - 1).astype(np.float32) * ampl vec = np.reshape(vec, (n, d)) - quantizer = faiss.RaBitQuantizer(d, metric) - - # encode and decode + quantizer = faiss.RaBitQuantizer(d, faiss.METRIC_L2) vec_q = quantizer.compute_codes(vec) vec_rec = quantizer.decode(vec_q) - - # verify np.testing.assert_equal(vec, vec_rec) - def test_encode_decode_L2(self): - self.do_test_encode_decode(16, faiss.METRIC_L2) - - def test_encode_decode_IP(self): - self.do_test_encode_decode(16, faiss.METRIC_INNER_PRODUCT) - def test_codes_match_none(self): - """RaBitQ codes are integer; encode must be bit-identical across - SIMD levels.""" - if not faiss.SIMDConfig.is_simd_level_available(faiss.SIMDLevel_NONE): - self.skipTest("SIMDLevel.NONE not available") - d = 64 - rs = np.random.RandomState(123) - vec = rs.standard_normal((100, d)).astype(np.float32) - for metric in (faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT): - with self.subTest(metric=metric): - quantizer = faiss.RaBitQuantizer(d, metric) - codes = quantizer.compute_codes(vec) - with NoneSIMDLevel(): - codes_none = quantizer.compute_codes(vec) - np.testing.assert_array_equal(codes, codes_none) - - -# ============================================================================== -# Multi-bit RaBitQ Test Suite -# ============================================================================== - - -def create_index_rabitq_with_rotation(d, metric, nb_bits, qb=0, rrot_seed=123): - """Helper: Create IndexRaBitQ with random rotation.""" +def create_index_rabitq_with_rotation(d, metric, nb_bits, qb=0): index_rbq = faiss.IndexRaBitQ(d, metric, nb_bits) index_rbq.qb = qb rrot = faiss.RandomRotationMatrix(d, d) - rrot.init(rrot_seed) + rrot.init(123) return faiss.IndexPreTransform(rrot, index_rbq) -def create_index_ivf_rabitq_with_rotation( - d, metric, nb_bits, nlist=16, qb=0, nprobe=4, rrot_seed=123 -): - """Helper: Create IndexIVFRaBitQ with random rotation.""" +def create_index_ivf_rabitq_with_rotation(d, metric, nb_bits, qb=0): quantizer = faiss.IndexFlat(d, metric) - index_rbq = faiss.IndexIVFRaBitQ(quantizer, d, nlist, metric, True, nb_bits) + index_rbq = faiss.IndexIVFRaBitQ(quantizer, d, 16, metric, True, nb_bits) index_rbq.qb = qb - index_rbq.nprobe = nprobe + index_rbq.nprobe = 4 rrot = faiss.RandomRotationMatrix(d, d) - rrot.init(rrot_seed) + rrot.init(123) return faiss.IndexPreTransform(rrot, index_rbq) def compute_expected_code_size(d, nb_bits): - """Helper: Compute expected code size based on formula.""" ex_bits = nb_bits - 1 # For 1-bit: use SignBitFactors (8 bytes) for non-IVF # For multi-bit: use SignBitFactorsWithError (12 bytes) @@ -524,7 +447,6 @@ def compute_expected_code_size(d, nb_bits): def do_test_serde(description): - """Shared helper: Test serialize/deserialize preserves search results.""" ds = datasets.SyntheticDataset(32, 1000, 100, 20) index = faiss.index_factory(ds.d, description) @@ -541,7 +463,6 @@ def do_test_serde(description): np.testing.assert_equal(Dref, Dnew) np.testing.assert_equal(Iref, Inew) - # Verify deserialized index is serializable again b2 = faiss.serialize_index(index2) index3 = faiss.deserialize_index(b2) Dnew3, Inew3 = index3.search(ds.get_queries(), 10) @@ -551,110 +472,20 @@ def do_test_serde(description): @for_all_simd_levels class TestMultiBitRaBitQ(unittest.TestCase): - """Consolidated tests for multi-bit RaBitQ. - - Tests IndexRaBitQ and IndexIVFRaBitQ for construction, basic operations, - recall, serialization, IVF operations, query quantization, and factory. - """ - - # ==================== Construction Tests ==================== - - def test_valid_nb_bits_range(self): - """Test that nb_bits 1-9 are valid for IndexRaBitQ.""" - d = 128 - for nb_bits in range(1, 10): - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - index = faiss.IndexRaBitQ(d, metric, nb_bits) - self.assertEqual(index.d, d) - self.assertEqual(index.metric_type, metric) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - def test_invalid_nb_bits(self): - """Test that invalid nb_bits values raise errors.""" with self.assertRaises(RuntimeError): faiss.IndexRaBitQ(128, faiss.METRIC_L2, 0) with self.assertRaises(RuntimeError): faiss.IndexRaBitQ(128, faiss.METRIC_L2, 10) def test_code_size_formula(self): - """Test that code sizes match expected formula for all nb_bits.""" d = 128 for nb_bits in range(1, 10): index = faiss.IndexRaBitQ(d, faiss.METRIC_L2, nb_bits) expected_size = compute_expected_code_size(d, nb_bits) self.assertEqual(index.code_size, expected_size) - def test_ivf_construction(self): - """Test IndexIVFRaBitQ construction with valid/invalid nb_bits.""" - d, nlist = 64, 16 - # Valid nb_bits - for nb_bits in range(1, 10): - quantizer = faiss.IndexFlat(d, faiss.METRIC_L2) - index = faiss.IndexIVFRaBitQ( - quantizer, d, nlist, faiss.METRIC_L2, True, nb_bits - ) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - expected = compute_expected_code_size(d, nb_bits) - self.assertEqual(index.code_size, expected) - - # Invalid nb_bits - quantizer = faiss.IndexFlat(d, faiss.METRIC_L2) - with self.assertRaises(RuntimeError): - faiss.IndexIVFRaBitQ(quantizer, d, nlist, faiss.METRIC_L2, True, 0) - with self.assertRaises(RuntimeError): - faiss.IndexIVFRaBitQ(quantizer, d, nlist, faiss.METRIC_L2, True, 10) - - # ==================== Basic Operations Tests ==================== - - def test_basic_operations(self): - """Test train/add/search pipeline for various configurations.""" - ds = datasets.SyntheticDataset(128, 300, 500, 20) - k = 10 - - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - for nb_bits in [1, 2, 4, 8]: - for qb in [0, 4, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index = create_index_rabitq_with_rotation( - ds.d, metric, nb_bits, qb=qb - ) - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), k) - - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, ds.nb) - self.assertEqual(D.shape, (ds.nq, k)) - self.assertEqual(I.shape, (ds.nq, k)) - self.assertTrue(np.all(I >= 0)) - self.assertTrue(np.all(I < ds.nb)) - self.assertTrue(np.all(np.isfinite(D))) - - # ==================== Recall Tests ==================== - - def test_recall_quality(self): - """Test that recall is reasonable for various configurations.""" - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - metric_str = "L2" if metric == faiss.METRIC_L2 else "IP" - ds = datasets.SyntheticDataset( - 128, 500, 1000, 50, metric=metric_str - ) - I_gt = ds.get_groundtruth(10) - - for nb_bits in [1, 2, 4, 8]: - for qb in [0, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index = create_index_rabitq_with_rotation( - ds.d, metric, nb_bits, qb=qb - ) - index.train(ds.get_train()) - index.add(ds.get_database()) - _, I = index.search(ds.get_queries(), 10) - recall = faiss.eval_intersection(I, I_gt) / (ds.nq * 10) - self.assertGreater(recall, 0.10) - def test_recall_monotonic_improvement(self): - """Test that recall improves with more bits.""" for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: metric_str = "L2" if metric == faiss.METRIC_L2 else "IP" ds = datasets.SyntheticDataset( @@ -675,61 +506,46 @@ def test_recall_monotonic_improvement(self): recalls[nb_bits] = faiss.eval_intersection(I, I_gt) / ( ds.nq * 10 ) + self.assertGreater(recalls[nb_bits], 0.10) - # Monotonic improvement with tolerance tolerance = 0.03 self.assertGreaterEqual(recalls[2], recalls[1] - tolerance) self.assertGreaterEqual(recalls[4], recalls[2] - tolerance) self.assertGreaterEqual(recalls[8], recalls[4] - tolerance) self.assertGreater(recalls[8], 0.75) - # ==================== Serialization Tests ==================== - def test_serialization(self): - """Test serialize/deserialize preserves search results.""" ds = datasets.SyntheticDataset(64, 150, 200, 10) + qb = 4 for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - for nb_bits in [1, 2, 4, 8, 9]: - for qb in [0, 4, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index1 = create_index_rabitq_with_rotation( - ds.d, metric, nb_bits, qb=qb - ) - index1.train(ds.get_train()) - index1.add(ds.get_database()) - D1, I1 = index1.search(ds.get_queries(), 5) - - index_bytes = faiss.serialize_index(index1) - index2 = faiss.deserialize_index(index_bytes) - - self.assertEqual(index2.d, ds.d) - self.assertEqual(index2.ntotal, ds.nb) - self.assertTrue(index2.is_trained) + for nb_bits in [1, 9]: + with self.subTest(metric=metric, nb_bits=nb_bits): + index1 = create_index_rabitq_with_rotation( + ds.d, metric, nb_bits, qb=qb + ) + index1.train(ds.get_train()) + index1.add(ds.get_database()) + D1, I1 = index1.search(ds.get_queries(), 5) - params = faiss.RaBitQSearchParameters() - params.qb = qb - params.centered = False - D2, I2 = index2.search( - ds.get_queries(), 5, params=params - ) + index_bytes = faiss.serialize_index(index1) + index2 = faiss.deserialize_index(index_bytes) - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, rtol=1e-5) + params = faiss.RaBitQSearchParameters() + params.qb = qb + params.centered = False + D2, I2 = index2.search(ds.get_queries(), 5, params=params) - # Verify deserialized index is serializable again - index_bytes2 = faiss.serialize_index(index2) - index3 = faiss.deserialize_index(index_bytes2) - D3, I3 = index3.search( - ds.get_queries(), 5, params=params - ) - np.testing.assert_array_equal(I1, I3) - np.testing.assert_allclose(D1, D3, rtol=1e-5) + np.testing.assert_array_equal(I1, I2) + np.testing.assert_allclose(D1, D2, rtol=1e-5) - # ==================== IVF Tests ==================== + index_bytes2 = faiss.serialize_index(index2) + index3 = faiss.deserialize_index(index_bytes2) + D3, I3 = index3.search(ds.get_queries(), 5, params=params) + np.testing.assert_array_equal(I1, I3) + np.testing.assert_allclose(D1, D3, rtol=1e-5) def test_ivf_basic_operations(self): - """Test IVF train/add/search pipeline.""" ds = datasets.SyntheticDataset(128, 300, 500, 20) for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: @@ -737,20 +553,16 @@ def test_ivf_basic_operations(self): for qb in [0, 4, 8]: with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): index = create_index_ivf_rabitq_with_rotation( - ds.d, metric, nb_bits, nlist=16, qb=qb, nprobe=4 + ds.d, metric, nb_bits, qb=qb ) index.train(ds.get_train()) index.add(ds.get_database()) D, I = index.search(ds.get_queries(), 10) - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, ds.nb) - self.assertEqual(D.shape, (ds.nq, 10)) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(np.isfinite(D))) def test_ivf_nprobe_improves_recall(self): - """Test that higher nprobe improves recall.""" for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: metric_str = "L2" if metric == faiss.METRIC_L2 else "IP" ds = datasets.SyntheticDataset( @@ -783,50 +595,38 @@ def test_ivf_nprobe_improves_recall(self): self.assertGreaterEqual(recalls[8], recalls[4]) def test_ivf_serialization(self): - """Test IVF serialization preserves results.""" ds = datasets.SyntheticDataset(64, 150, 200, 10) + qb = 4 for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - for nb_bits in [1, 2, 4, 8, 9]: - for qb in [0, 4, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index1 = create_index_ivf_rabitq_with_rotation( - ds.d, metric, nb_bits, nlist=16, qb=qb, nprobe=4 - ) - index1.train(ds.get_train()) - index1.add(ds.get_database()) - D1, I1 = index1.search(ds.get_queries(), 5) - - index_bytes = faiss.serialize_index(index1) - index2 = faiss.deserialize_index(index_bytes) - - self.assertEqual(index2.d, ds.d) - self.assertEqual(index2.ntotal, ds.nb) + for nb_bits in [1, 9]: + with self.subTest(metric=metric, nb_bits=nb_bits): + index1 = create_index_ivf_rabitq_with_rotation( + ds.d, metric, nb_bits, qb=qb + ) + index1.train(ds.get_train()) + index1.add(ds.get_database()) + D1, I1 = index1.search(ds.get_queries(), 5) - params = faiss.IVFRaBitQSearchParameters() - params.qb = qb - params.centered = False - params.nprobe = 4 - D2, I2 = index2.search( - ds.get_queries(), 5, params=params - ) + index_bytes = faiss.serialize_index(index1) + index2 = faiss.deserialize_index(index_bytes) - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, rtol=1e-5) + params = faiss.IVFRaBitQSearchParameters() + params.qb = qb + params.centered = False + params.nprobe = 4 + D2, I2 = index2.search(ds.get_queries(), 5, params=params) - # Verify deserialized index is serializable again - index_bytes2 = faiss.serialize_index(index2) - index3 = faiss.deserialize_index(index_bytes2) - D3, I3 = index3.search( - ds.get_queries(), 5, params=params - ) - np.testing.assert_array_equal(I1, I3) - np.testing.assert_allclose(D1, D3, rtol=1e-5) + np.testing.assert_array_equal(I1, I2) + np.testing.assert_allclose(D1, D2, rtol=1e-5) - # ==================== Query Quantization Tests ==================== + index_bytes2 = faiss.serialize_index(index2) + index3 = faiss.deserialize_index(index_bytes2) + D3, I3 = index3.search(ds.get_queries(), 5, params=params) + np.testing.assert_array_equal(I1, I3) + np.testing.assert_allclose(D1, D3, rtol=1e-5) def test_query_quantization_levels(self): - """Test that all qb values produce valid results.""" ds = datasets.SyntheticDataset(128, 300, 500, 20) for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: @@ -844,73 +644,23 @@ def test_query_quantization_levels(self): params.centered = False D, I = index.search(ds.get_queries(), 10, params=params) - self.assertEqual(D.shape, (ds.nq, 10)) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(np.isfinite(D))) - # ==================== Index Factory Tests ==================== - - def test_factory_default_nb_bits(self): - """Test that 'RaBitQ' creates 1-bit index by default.""" - index = faiss.index_factory(128, "RaBitQ") - self.assertIsInstance(index, faiss.IndexRaBitQ) - self.assertEqual(index.rabitq.nb_bits, 1) - - def test_factory_multibit(self): - """Test 'RaBitQ{nb_bits}' creates correct multi-bit indexes.""" - for nb_bits in [2, 4, 8]: - index = faiss.index_factory(128, f"RaBitQ{nb_bits}") - self.assertIsInstance(index, faiss.IndexRaBitQ) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - self.assertEqual( - index.code_size, compute_expected_code_size(128, nb_bits) - ) - - def test_factory_ivf(self): - """Test IVF factory with default and multi-bit.""" - # Default 1-bit - index = faiss.index_factory(128, "IVF16,RaBitQ") - self.assertIsInstance(index, faiss.IndexIVFRaBitQ) - self.assertEqual(index.rabitq.nb_bits, 1) - - # Multi-bit - for nb_bits in [2, 4, 8]: - index = faiss.index_factory(128, f"IVF16,RaBitQ{nb_bits}") - self.assertIsInstance(index, faiss.IndexIVFRaBitQ) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - - def test_factory_end_to_end(self): - """Test complete workflow: factory creation, train, add, search.""" - ds = datasets.SyntheticDataset(64, 150, 200, 10) - - for nb_bits in [1, 4]: - # Non-IVF - factory_str = f"RaBitQ{nb_bits}" if nb_bits > 1 else "RaBitQ" - index = faiss.index_factory(ds.d, factory_str) - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 5) - self.assertEqual(D.shape, (ds.nq, 5)) - self.assertTrue(np.all(I >= 0)) - - # IVF - ivf_str = ( - f"IVF16,RaBitQ{nb_bits}" if nb_bits > 1 else "IVF16,RaBitQ" - ) - ivf_index = faiss.index_factory(ds.d, ivf_str) - ivf_index.train(ds.get_train()) - ivf_index.add(ds.get_database()) - D_ivf, I_ivf = ivf_index.search(ds.get_queries(), 5) - self.assertEqual(D_ivf.shape, (ds.nq, 5)) - self.assertTrue(np.all(I_ivf >= 0)) + def test_factory(self): + for prefix, cls in [ + ("", faiss.IndexRaBitQ), + ("IVF16,", faiss.IndexIVFRaBitQ), + ]: + for nb_bits in [1, 2, 4, 8]: + suffix = str(nb_bits) if nb_bits > 1 else "" + index = faiss.index_factory(128, f"{prefix}RaBitQ{suffix}") + self.assertIsInstance(index, cls) + self.assertEqual(index.rabitq.nb_bits, nb_bits) def test_degenerate_centroid_distance(self): - """Test that a doc identical to its centroid gets correct distances. - - When a vector's residual (x - centroid) has near-zero norm, - quantize_ex_bits hits a degenerate early-return path. A previous - bug set f_rescale_ex=1 (should be 0) and f_add_ex=0 (should be - metric-dependent), causing wildly wrong multi-bit distances. + """A doc equal to its centroid hits the zero-residual early return of + quantize_ex_bits (f_rescale_ex must be 0, f_add_ex metric-dependent). """ d = 128 nlist = 16 @@ -929,9 +679,7 @@ def test_degenerate_centroid_distance(self): quantizer, d, nlist, metric, True, nb_bits ) index.train(xt) - index.nprobe = nlist # exhaustive - - # Add the centroid itself as the only document + index.nprobe = nlist centroid = index.quantizer.reconstruct(0).reshape(1, d) index.add(centroid) diff --git a/thirdparty/faiss/tests/test_rabitq_batch_estimates.cpp b/thirdparty/faiss/tests/test_rabitq_batch_estimates.cpp index 106942983..426ca88dc 100644 --- a/thirdparty/faiss/tests/test_rabitq_batch_estimates.cpp +++ b/thirdparty/faiss/tests/test_rabitq_batch_estimates.cpp @@ -58,7 +58,7 @@ TEST(RaBitQBatchEstimates, MatchesSingleAcrossPrecisionsMetricsAndSIMD) { v = normal(rng); } for (auto metric : {faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}) { - for (int bits = 1; bits <= 9; ++bits) { + for (int bits : {1, 2}) { faiss::IndexRaBitQ index(d, metric, bits); index.train(16, data.data()); index.add(16, data.data()); @@ -147,12 +147,15 @@ TEST(RaBitQBatchEstimates, RBQ9ByteCodesMatchIndependentReference) { // Exactly d extra bytes after an intentionally unaligned start. std::vector signs(1 + (d + 7) / 8), extra(1 + d); std::vector query(d); - for (auto& v : signs) + for (auto& v : signs) { v = rng(); - for (auto& v : extra) + } + for (auto& v : extra) { v = rng(); - for (auto& v : query) + } + for (auto& v : query) { v = (int(rng() % 2001) - 1000) / 1000.f; + } double expected = 0, magnitude = 0; for (size_t i = 0; i < d; ++i) { const int sign = (signs[1 + i / 8] >> (i % 8)) & 1; @@ -184,14 +187,17 @@ TEST(RaBitQBatchEstimates, Q4KernelUnalignedTailsMatchByteReference) { std::mt19937 rng(42); for (size_t size : {0, 1, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 96, 97, 193}) { - std::vector query(1 + 4 * size), storage[4]; - for (auto& v : query) + std::vector query(1 + 4 * size); + std::vector storage[4]; + for (auto& v : query) { v = rng(); + } const uint8_t* codes[4]; for (int i = 0; i < 4; ++i) { storage[i].resize(i + 1 + size); - for (auto& v : storage[i]) + for (auto& v : storage[i]) { v = rng(); + } codes[i] = storage[i].data() + i + 1; } for (auto level : available_levels()) { @@ -232,8 +238,9 @@ TEST(RaBitQBatchEstimates, MultiBitKernelsMatchIndependentReference) { std::vector signs(1 + (d + 7) / 8); std::vector extra(1 + (d * ex_bits + 7) / 8 + 8); std::vector query(d); - for (auto& v : signs) + for (auto& v : signs) { v = rng(); + } double expected = 0, magnitude = 0; const float cb = -(float(1u << ex_bits) - 0.5f); for (size_t i = 0; i < d; ++i) { diff --git a/thirdparty/faiss/tests/test_rabitq_fastscan.py b/thirdparty/faiss/tests/test_rabitq_fastscan.py index b06045aee..a21e2c839 100644 --- a/thirdparty/faiss/tests/test_rabitq_fastscan.py +++ b/thirdparty/faiss/tests/test_rabitq_fastscan.py @@ -13,7 +13,6 @@ def compute_expected_code_size(d, nb_bits): - """Helper: Compute expected code size based on formula.""" ex_bits = nb_bits - 1 # For 1-bit: use SignBitFactors (8 bytes) for non-IVF # For multi-bit: use SignBitFactorsWithError (12 bytes) @@ -31,49 +30,35 @@ def _create_fastscan_index( use_ivf=False, nlist=16, nprobe=4, - bbs=32, nb_bits=1, ): - """Create FastScan index (IVF or non-IVF).""" if use_ivf: quantizer = faiss.IndexFlat(d, metric) index = faiss.IndexIVFRaBitQFastScan( - quantizer, d, nlist, metric, bbs, True, nb_bits + quantizer, d, nlist, metric, 32, True, nb_bits ) index.nprobe = nprobe else: - index = faiss.IndexRaBitQFastScan(d, metric, bbs, nb_bits) + index = faiss.IndexRaBitQFastScan(d, metric, 32, nb_bits) return index @for_all_simd_levels class TestRaBitQFastScan(unittest.TestCase): - """Unified tests for IndexRaBitQFastScan and IndexIVFRaBitQFastScan.""" - NLIST = 16 NPROBE = 4 - def _create_index( - self, - d, - metric, - use_ivf=False, - nlist=None, - bbs=32, - nb_bits=1, - ): + def _create_index(self, d, metric, use_ivf=False, nlist=None, nb_bits=1): return _create_fastscan_index( d, metric, use_ivf=use_ivf, nlist=nlist or self.NLIST, nprobe=self.NPROBE, - bbs=bbs, nb_bits=nb_bits, ) def _create_baseline(self, d, metric, use_ivf=False, nlist=None): - """Create baseline RaBitQ index (IVF or non-IVF).""" if use_ivf: nlist = nlist or self.NLIST quantizer = faiss.IndexFlat(d, metric) @@ -83,10 +68,7 @@ def _create_baseline(self, d, metric, use_ivf=False, nlist=None): index = faiss.IndexRaBitQ(d, metric) return index - # ==================== Comparison Tests ==================== - def test_comparison_vs_baseline(self): - """Test FastScan produces similar results to baseline RaBitQ.""" ds = datasets.SyntheticDataset(128, 4096, 4096, 100) k = 10 @@ -97,13 +79,11 @@ def test_comparison_vs_baseline(self): index_flat.add(ds.get_database()) _, I_gt = index_flat.search(ds.get_queries(), k) - # Baseline index_base = self._create_baseline(ds.d, metric, use_ivf) index_base.train(ds.get_train()) index_base.add(ds.get_database()) _, I_base = index_base.search(ds.get_queries(), k) - # FastScan index_fs = self._create_index(ds.d, metric, use_ivf) index_fs.train(ds.get_train()) index_fs.add(ds.get_database()) @@ -117,11 +97,10 @@ def test_comparison_vs_baseline(self): ) / (ds.nq * k) np.testing.assert_(abs(eval_base - eval_fs) < 0.05) - - # ==================== Encode/Decode Tests ==================== + if not use_ivf and metric == faiss.METRIC_L2: + np.testing.assert_(eval_fs > 0.55) def test_encode_decode_consistency(self): - """Test encoding/decoding operations are consistent.""" for use_ivf in [False, True]: with self.subTest(use_ivf=use_ivf): nlist = 32 @@ -129,7 +108,6 @@ def test_encode_decode_consistency(self): test_vectors = ds.get_database()[:100] if use_ivf: - # IVF: use add + reconstruct_n index_fs = self._create_index( ds.d, faiss.METRIC_L2, True, nlist ) @@ -146,7 +124,6 @@ def test_encode_decode_consistency(self): 0, len(test_vectors) ) else: - # Non-IVF: use sa_encode + sa_decode index_fs = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2) index_fs.train(ds.get_train()) @@ -165,7 +142,6 @@ def test_encode_decode_consistency(self): codes_base = index_base.sa_encode(test_vectors) decoded_base = index_base.sa_decode(codes_base) - # Compare reconstruction errors err_fs = np.mean( np.sum((test_vectors - decoded_fs) ** 2, axis=1) ) @@ -175,10 +151,7 @@ def test_encode_decode_consistency(self): np.testing.assert_(abs(err_fs - err_base) < 0.01) - # ==================== Serialization Tests ==================== - def test_serialization(self): - """Test serialize/deserialize preserves search results.""" for use_ivf in [False, True]: for nb_bits in [1, 2, 4]: with self.subTest(use_ivf=use_ivf, nb_bits=nb_bits): @@ -205,7 +178,6 @@ def test_serialization(self): np.testing.assert_array_equal(Dref, Dnew) np.testing.assert_array_equal(Iref, Inew) - # Verify deserialized index is serializable again b2 = faiss.serialize_index(index2) index3 = faiss.deserialize_index(b2) if use_ivf: @@ -214,10 +186,8 @@ def test_serialization(self): np.testing.assert_array_equal(Dref, Dnew3) np.testing.assert_array_equal(Iref, Inew3) - # ==================== Memory Management Tests ==================== - def test_memory_management(self): - """Test memory is managed correctly during chunked add.""" + """Adds in chunks that end mid-block.""" for use_ivf in [False, True]: with self.subTest(use_ivf=use_ivf): ds = datasets.SyntheticDataset(128, 2000, 2000, 50) @@ -233,17 +203,14 @@ def test_memory_management(self): np.testing.assert_equal(index.ntotal, ds.nb) _, I = index.search(ds.get_queries(), 5) - np.testing.assert_equal(I.shape, (ds.nq, 5)) I_gt = ds.get_groundtruth(5) recall = faiss.eval_intersection(I[:, :5], I_gt[:, :5]) recall /= ds.nq * 5 np.testing.assert_(recall > 0.1) - # ==================== Thread Safety Tests ==================== - def test_thread_safety(self): - """Test parallel operations work correctly via OpenMP.""" + """L2 distances must be clamped to >= 0.""" for use_ivf in [False, True]: with self.subTest(use_ivf=use_ivf): nq = 300 if use_ivf else 500 @@ -256,51 +223,11 @@ def test_thread_safety(self): k = 10 distances, labels = index.search(ds.get_queries(), k) - np.testing.assert_equal(distances.shape, (ds.nq, k)) - np.testing.assert_equal(labels.shape, (ds.nq, k)) np.testing.assert_(np.all(distances >= 0)) np.testing.assert_(np.all(labels >= 0)) np.testing.assert_(np.all(labels < ds.nb)) - # ==================== Factory Tests ==================== - - def test_factory_construction(self): - """Test factory construction for both IVF and non-IVF.""" - ds = datasets.SyntheticDataset(64, 500, 500, 20) - nlist = 16 - - for use_ivf in [False, True]: - with self.subTest(use_ivf=use_ivf): - factory_str = f"IVF{nlist},RaBitQfs" if use_ivf else "RaBitQfs" - expected_type = ( - faiss.IndexIVFRaBitQFastScan - if use_ivf - else faiss.IndexRaBitQFastScan - ) - - index = faiss.index_factory(ds.d, factory_str) - self.assertIsInstance(index, expected_type) - - if use_ivf: - index.nprobe = 4 - index.train(ds.get_train()) - index.add(ds.get_database()) - _, I = index.search(ds.get_queries(), 5) - - np.testing.assert_equal(I.shape, (ds.nq, 5)) - - # Test with custom batch size - for use_ivf in [False, True]: - factory_str = ( - f"IVF{nlist},RaBitQfs_64" if use_ivf else "RaBitQfs_64" - ) - index = faiss.index_factory(ds.d, factory_str) - np.testing.assert_equal(index.bbs, 64) - - # ==================== Non-IVF Specific Tests ==================== - def test_query_quantization_bits(self): - """Test different query quantization bit settings (non-IVF only).""" ds = datasets.SyntheticDataset(64, 2000, 2000, 50) k = 10 @@ -317,50 +244,7 @@ def test_query_quantization_bits(self): recall /= ds.nq * k np.testing.assert_(recall > 0.4) - def test_small_dataset(self): - """Test on small dataset for basic functionality (non-IVF only).""" - d, n, nq = 32, 100, 10 - - rs = np.random.RandomState(123) - xb = rs.rand(n, d).astype(np.float32) - xq = rs.rand(nq, d).astype(np.float32) - - index = faiss.IndexRaBitQFastScan(d, faiss.METRIC_L2) - index.train(xb) - index.add(xb) - - k = 5 - D, I = index.search(xq, k) - - np.testing.assert_equal(D.shape, (nq, k)) - np.testing.assert_equal(I.shape, (nq, k)) - np.testing.assert_(np.all(I >= 0)) - np.testing.assert_(np.all(I < n)) - np.testing.assert_(np.all(D >= 0)) - - def test_comparison_vs_pq_fastscan(self): - """Compare RaBitQFastScan to PQFastScan (non-IVF only).""" - ds = datasets.SyntheticDataset(128, 4096, 4096, 100) - k = 10 - - index_pq = faiss.IndexPQFastScan(ds.d, 16, 4, faiss.METRIC_L2) - index_pq.train(ds.get_train()) - index_pq.add(ds.get_database()) - _, I_pq = index_pq.search(ds.get_queries(), k) - - index_rbq = faiss.IndexRaBitQFastScan(ds.d, faiss.METRIC_L2) - index_rbq.train(ds.get_train()) - index_rbq.add(ds.get_database()) - _, I_rbq = index_rbq.search(ds.get_queries(), k) - - I_gt = ds.get_groundtruth(k) - eval_rbq = faiss.eval_intersection(I_rbq[:, :k], I_gt[:, :k]) - eval_rbq /= ds.nq * k - - np.testing.assert_(eval_rbq > 0.55) - def test_invalid_parameters(self): - """Test error handling for invalid parameters (non-IVF only).""" with np.testing.assert_raises(Exception): faiss.IndexRaBitQFastScan(0, faiss.METRIC_L2) @@ -370,10 +254,7 @@ def test_invalid_parameters(self): except RuntimeError: pass - # ==================== IVF Specific Tests ==================== - def test_nprobe_variations(self): - """Test different nprobe values (IVF only).""" nlist = 32 ds = datasets.SyntheticDataset(64, 1000, 1000, 50) k = 10 @@ -381,12 +262,10 @@ def test_nprobe_variations(self): for nprobe in [1, 4, 8, 16]: with self.subTest(nprobe=nprobe): - # Baseline quantizer1 = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_base = faiss.IndexIVFRaBitQ( quantizer1, ds.d, nlist, faiss.METRIC_L2 ) - index_base.nprobe = nprobe index_base.train(ds.get_train()) index_base.add(ds.get_database()) @@ -398,14 +277,12 @@ def test_nprobe_variations(self): ds.get_queries(), k, params=params_base ) - # FastScan quantizer2 = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_fs = faiss.IndexIVFRaBitQFastScan( quantizer2, ds.d, nlist, faiss.METRIC_L2, 32 ) index_fs.qb = 8 index_fs.centered = False - index_fs.nprobe = nprobe index_fs.train(ds.get_train()) index_fs.add(ds.get_database()) @@ -423,14 +300,12 @@ def test_nprobe_variations(self): np.testing.assert_(abs(eval_base - eval_fs) < 0.01) def _do_test_search_implementation(self, impl): - """Helper to test a specific search implementation (IVF only).""" nlist, nprobe = 32, 8 ds = datasets.SyntheticDataset(128, 2048, 2048, 100) k = 10 I_gt = ds.get_groundtruth(k) - # Baseline quantizer1 = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_base = faiss.IndexIVFRaBitQ( quantizer1, ds.d, nlist, faiss.METRIC_L2 @@ -450,7 +325,6 @@ def _do_test_search_implementation(self, impl): ds.nq * k ) - # FastScan with specific implementation quantizer2 = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_fs = faiss.IndexIVFRaBitQFastScan( quantizer2, ds.d, nlist, faiss.METRIC_L2, 32 @@ -475,14 +349,10 @@ def _do_test_search_implementation(self, impl): def test_search_implem_10(self): self._do_test_search_implementation(impl=10) - def test_search_implem_12(self): - self._do_test_search_implementation(impl=12) - def test_search_implem_14(self): self._do_test_search_implementation(impl=14) def test_search_with_parameters(self): - """Test search_with_parameters code path (IVF only).""" nlist, nprobe, nq = 64, 8, 500 ds = datasets.SyntheticDataset(128, 2048, 2048, nq) k = 10 @@ -500,26 +370,16 @@ def test_search_with_parameters(self): params = faiss.IVFSearchParameters() params.nprobe = nprobe - D, I = faiss.search_with_parameters(index, ds.get_queries(), k, params) - - self.assertEqual(D.shape, (nq, k)) - self.assertEqual(I.shape, (nq, k)) - self.assertGreater(np.sum(I >= 0), 0) + _, I = faiss.search_with_parameters(index, ds.get_queries(), k, params) I_gt = ds.get_groundtruth(k) recall = faiss.eval_intersection(I, I_gt) / (nq * k) self.assertGreater(recall, 0.4) def test_ivf_large_bbs_aux_offsets(self): - """Regression for aux-factor offsets when bbs > 32 (IVF path). - - A bbs block holds bbs/32 SIMD sub-blocks. With nlist=1 every vector - lands in a single list that spans many bbs=64 blocks, so the b>=1 - sub-blocks exercise ``idx_base % bbs != 0`` in IVFRaBitQHeapHandler. - If the per-element aux offset drops the ``idx_base % bbs`` term, roughly - half the vectors read another sub-block's factors and recall collapses, - so bbs=64 must match the bbs=32 baseline, which is always block-aligned. - """ + """nlist=1 puts all vectors in one list spanning many bbs=64 blocks, so + sub-blocks b>=1 need the idx_base % bbs aux offset; bbs=64 recall must + match bbs=32.""" d, nlist, nprobe, k = 64, 1, 1, 10 ds = datasets.SyntheticDataset(d, 2000, 2000, 100) I_gt = ds.get_groundtruth(k) @@ -559,14 +419,9 @@ def _create_index(self, d, metric, nb_bits=1): return index def _do_test_filter( - self, - selector_type="batch", - metric=faiss.METRIC_L2, - nb_bits=1, - k=10, - nb=1000, + self, selector_type="batch", metric=faiss.METRIC_L2, nb_bits=1 ): - d = 32 + d, k, nb = 32, 10, 1000 ds = datasets.SyntheticDataset(d, 2000, nb, 20, metric=metric) index = self._create_index(d, metric, nb_bits=nb_bits) index.train(ds.get_train()) @@ -574,28 +429,9 @@ def _do_test_filter( rs = np.random.RandomState(123) if selector_type == "batch": - subset = rs.choice(nb, max(nb // 3, 1), replace=False).astype( - "int64" - ) + subset = rs.choice(nb, nb // 3, replace=False).astype("int64") sel = faiss.IDSelectorBatch(subset) allowed = set(subset.tolist()) - elif selector_type == "whole_block_not": - excluded = np.concatenate( - [ - np.arange(0, min(32, nb), dtype="int64"), - np.arange(64, min(96, nb), dtype="int64"), - ] - ) - inner_sel = faiss.IDSelectorBatch(excluded) - sel = faiss.IDSelectorNot(inner_sel) - allowed = {i for i in range(nb) if i not in excluded} - elif selector_type == "partial_block_not": - excluded = np.array( - [i for i in [5, 10, 20, 31] if i < nb], dtype="int64" - ) - inner_sel = faiss.IDSelectorBatch(excluded) - sel = faiss.IDSelectorNot(inner_sel) - allowed = {i for i in range(nb) if i not in excluded} elif selector_type == "empty": sel = faiss.IDSelectorBatch(np.array([], dtype="int64")) allowed = set() @@ -617,61 +453,25 @@ def _do_test_filter( if selector_type == "empty": np.testing.assert_array_equal(labels, -1) - elif len(allowed) > k: + else: self.assertGreater(np.sum(labels >= 0), 0) def test_batch_filter_l2_1bit(self): - self._do_test_filter("batch", faiss.METRIC_L2, nb_bits=1) + self._do_test_filter("batch", nb_bits=1) def test_batch_filter_ip_1bit(self): self._do_test_filter("batch", faiss.METRIC_INNER_PRODUCT, nb_bits=1) - def test_whole_block_exclusion_l2_1bit(self): - self._do_test_filter("whole_block_not", faiss.METRIC_L2, nb_bits=1) - - def test_partial_block_exclusion_l2_1bit(self): - self._do_test_filter("partial_block_not", faiss.METRIC_L2, nb_bits=1) - def test_empty_selector_l2_1bit(self): - self._do_test_filter("empty", faiss.METRIC_L2, nb_bits=1) + self._do_test_filter("empty", nb_bits=1) def test_batch_filter_l2_multibit(self): - self._do_test_filter("batch", faiss.METRIC_L2, nb_bits=2) + self._do_test_filter("batch", nb_bits=2) @for_all_simd_levels class TestMultiBitRaBitQFastScan(unittest.TestCase): - """Consolidated tests for multi-bit RaBitQ FastScan. - - Tests IndexRaBitQFastScan and IndexIVFRaBitQFastScan for construction, - basic operations, recall, serialization, and factory construction. - """ - - NLIST = 16 - NPROBE = 4 - - # ==================== Construction Tests ==================== - - def test_valid_nb_bits_range(self): - """Test that nb_bits 1-9 are valid for IndexRaBitQFastScan.""" - d = 128 - for nb_bits in range(1, 10): - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - index = faiss.IndexRaBitQFastScan(d, metric, 32, nb_bits) - self.assertEqual(index.d, d) - self.assertEqual(index.metric_type, metric) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - - def test_invalid_nb_bits(self): - """Test that invalid nb_bits values raise errors.""" - d = 128 - with self.assertRaises(RuntimeError): - faiss.IndexRaBitQFastScan(d, faiss.METRIC_L2, 32, 0) - with self.assertRaises(RuntimeError): - faiss.IndexRaBitQFastScan(d, faiss.METRIC_L2, 10, 32) - def test_code_size_formula(self): - """Test that code sizes match expected formula for all nb_bits.""" d = 128 for nb_bits in range(1, 10): index = faiss.IndexRaBitQFastScan(d, faiss.METRIC_L2, 32, nb_bits) @@ -679,58 +479,17 @@ def test_code_size_formula(self): self.assertEqual(index.code_size, expected_size) def test_ivf_construction(self): - """Test IndexIVFRaBitQFastScan construction with valid/invalid - nb_bits.""" d, nlist = 128, 16 - # Valid nb_bits for nb_bits in [1, 2, 4, 8]: - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - quantizer = faiss.IndexFlat(d, metric) - index = faiss.IndexIVFRaBitQFastScan( - quantizer, d, nlist, metric, 32, True, nb_bits - ) - self.assertEqual(index.d, d) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - expected = compute_expected_code_size(d, nb_bits) - self.assertEqual(index.code_size, expected) - - # Invalid nb_bits - quantizer = faiss.IndexFlat(d, faiss.METRIC_L2) - with self.assertRaises(RuntimeError): - faiss.IndexIVFRaBitQFastScan( - quantizer, d, nlist, faiss.METRIC_L2, 32, True, 0 - ) - with self.assertRaises(RuntimeError): - faiss.IndexIVFRaBitQFastScan( - quantizer, d, nlist, faiss.METRIC_L2, 32, True, 10 + quantizer = faiss.IndexFlat(d, faiss.METRIC_L2) + index = faiss.IndexIVFRaBitQFastScan( + quantizer, d, nlist, faiss.METRIC_L2, 32, True, nb_bits ) - - # ==================== Basic Operations Tests ==================== - - def test_basic_operations(self): - """Test train/add/search pipeline for various configurations.""" - ds = datasets.SyntheticDataset(128, 300, 500, 20) - - for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - for nb_bits in [2, 4, 8]: - for qb in [1, 4, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index = faiss.IndexRaBitQFastScan( - ds.d, metric, 32, nb_bits - ) - index.qb = max(1, qb) - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 10) - - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, ds.nb) - self.assertEqual(D.shape, (ds.nq, 10)) - self.assertTrue(np.all(I >= 0)) - self.assertTrue(np.all(np.isfinite(D))) + self.assertEqual(index.rabitq.nb_bits, nb_bits) + expected = compute_expected_code_size(d, nb_bits) + self.assertEqual(index.code_size, expected) def test_ivf_basic_operations(self): - """Test IVF train/add/search pipeline.""" for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: metric_str = "L2" if metric == faiss.METRIC_L2 else "IP" ds = datasets.SyntheticDataset( @@ -745,17 +504,11 @@ def test_ivf_basic_operations(self): index.nprobe = 4 index.train(ds.get_train()) index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 10) + _, I = index.search(ds.get_queries(), 10) - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, ds.nb) - self.assertEqual(D.shape, (ds.nq, 10)) self.assertTrue(np.all(I >= 0)) - # ==================== Recall Tests ==================== - def test_recall_monotonic_improvement(self): - """Test that recall improves with more bits.""" for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: metric_str = "L2" if metric == faiss.METRIC_L2 else "IP" ds = datasets.SyntheticDataset( @@ -785,7 +538,6 @@ def test_recall_monotonic_improvement(self): self.assertGreater(recalls[8], 0.75) def test_ivf_recall_improves_with_bits(self): - """Test that recall improves monotonically with more bits for IVF.""" d, nlist, nprobe = 128, 16, 8 ds = datasets.SyntheticDataset(d, 1000, 1000, 50) I_gt = ds.get_groundtruth(10) @@ -807,7 +559,6 @@ def test_ivf_recall_improves_with_bits(self): self.assertGreater(recalls[8], recalls[4]) def test_comparison_vs_rabitq(self): - """Test multi-bit FastScan produces similar results to RaBitQ.""" ds = datasets.SyntheticDataset(128, 500, 1000, 50) k = 10 @@ -884,7 +635,6 @@ def test_ivf_vs_ivfrabitq_equivalence(self): np.testing.assert_array_equal(I_fs_simd, I_fs_none) def test_ivf_conversion_constructor_matches_direct_fastscan(self): - """Converting IndexIVFRaBitQ must build a usable FastScan index.""" d, nlist, nprobe, k = 64, 16, 4, 10 ds = datasets.SyntheticDataset(d, 700, 300, 20) @@ -921,55 +671,47 @@ def test_ivf_conversion_constructor_matches_direct_fastscan(self): ) self.assertEqual(index_converted.ntotal, index_rbq.ntotal) - self.assertEqual(index_converted.bbs, 32) - self.assertEqual(index_converted.nprobe, index_rbq.nprobe) - self.assertTrue(index_converted.by_residual) np.testing.assert_array_equal(I_converted, I_direct) np.testing.assert_allclose( D_converted, D_direct, rtol=0, atol=1e-5 ) - # ==================== Serialization Tests ==================== - def test_serialization(self): - """Test serialize/deserialize preserves search results.""" ds = datasets.SyntheticDataset(64, 150, 200, 10) + qb = 4 for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: - for nb_bits in [2, 4, 8, 9]: - for qb in [1, 4, 8]: - with self.subTest(metric=metric, nb_bits=nb_bits, qb=qb): - index1 = faiss.IndexRaBitQFastScan( - ds.d, metric, 32, nb_bits - ) - index1.qb = qb - index1.train(ds.get_train()) - index1.add(ds.get_database()) - D1, I1 = index1.search(ds.get_queries(), 5) - - index_bytes = faiss.serialize_index(index1) - index2 = faiss.deserialize_index(index_bytes) - index2.qb = qb - D2, I2 = index2.search(ds.get_queries(), 5) - - self.assertEqual(index2.rabitq.nb_bits, nb_bits) - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, rtol=1e-5) - - # Verify deserialized index is serializable again - index_bytes2 = faiss.serialize_index(index2) - index3 = faiss.deserialize_index(index_bytes2) - index3.qb = qb - D3, I3 = index3.search(ds.get_queries(), 5) - np.testing.assert_array_equal(I1, I3) - np.testing.assert_allclose(D1, D3, rtol=1e-5) + for nb_bits in [1, 2, 4, 8, 9]: + with self.subTest(metric=metric, nb_bits=nb_bits): + index1 = faiss.IndexRaBitQFastScan( + ds.d, metric, 32, nb_bits + ) + index1.qb = qb + index1.train(ds.get_train()) + index1.add(ds.get_database()) + D1, I1 = index1.search(ds.get_queries(), 5) + + index_bytes = faiss.serialize_index(index1) + index2 = faiss.deserialize_index(index_bytes) + index2.qb = qb + D2, I2 = index2.search(ds.get_queries(), 5) + + self.assertEqual(index2.rabitq.nb_bits, nb_bits) + np.testing.assert_array_equal(I1, I2) + np.testing.assert_allclose(D1, D2, rtol=1e-5) + + index_bytes2 = faiss.serialize_index(index2) + index3 = faiss.deserialize_index(index_bytes2) + index3.qb = qb + D3, I3 = index3.search(ds.get_queries(), 5) + np.testing.assert_array_equal(I1, I3) + np.testing.assert_allclose(D1, D3, rtol=1e-5) def test_ivf_serialization(self): - """Test IVF serialization preserves results.""" ds = datasets.SyntheticDataset(64, 1000, 500, 20) nlist = 16 - for nb_bits in [2, 4, 8]: + for nb_bits in [1, 2, 4, 8]: for metric in [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT]: with self.subTest(nb_bits=nb_bits, metric=metric): quantizer = faiss.IndexFlat(ds.d, metric) @@ -989,17 +731,13 @@ def test_ivf_serialization(self): np.testing.assert_array_equal(I1, I2) np.testing.assert_allclose(D1, D2, rtol=1e-5) - # Verify deserialized index is serializable again index_bytes2 = faiss.serialize_index(index2) index3 = faiss.deserialize_index(index_bytes2) D3, I3 = index3.search(ds.get_queries(), 10) np.testing.assert_array_equal(I1, I3) np.testing.assert_allclose(D1, D3, rtol=1e-5) - # ==================== Reconstruction Tests ==================== - def test_ivf_reconstruction(self): - """Test that reconstruct_n works for multi-bit IVF indices.""" d, nlist = 64, 8 ds = datasets.SyntheticDataset(d, 500, 100, 0) @@ -1018,11 +756,9 @@ def test_ivf_reconstruction(self): errors = np.sum((test_vectors - reconstructed) ** 2, axis=1) avg_error = np.mean(errors) - self.assertTrue(np.all(np.isfinite(reconstructed))) self.assertLess(avg_error, 15.0) def test_encode_decode_roundtrip(self): - """Test encode/decode round-trip produces consistent results.""" d, nlist = 64, 8 for use_ivf in [False, True]: @@ -1057,117 +793,40 @@ def test_encode_decode_roundtrip(self): self_retrieval_rate = self_retrieval_count / len(xb) self.assertGreater(self_retrieval_rate, 0.5) - def test_ivf_encoding_format_consistency(self): - """Verify IVF FastScan encoding matches non-IVF FastScan pattern.""" - d, nb, nlist = 64, 50, 4 - - np.random.seed(123) - xb = np.random.randn(nb, d).astype(np.float32) - xt = np.random.randn(500, d).astype(np.float32) - - for nb_bits in [1, 2, 4]: - with self.subTest(nb_bits=nb_bits): - index_flat = faiss.IndexRaBitQFastScan( - d, faiss.METRIC_L2, 32, nb_bits - ) - index_flat.train(xt) - index_flat.add(xb) - - quantizer = faiss.IndexFlat(d, faiss.METRIC_L2) - index_ivf = faiss.IndexIVFRaBitQFastScan( - quantizer, d, nlist, faiss.METRIC_L2, 32, True, nb_bits - ) - index_ivf.nprobe = nlist - index_ivf.train(xt) - index_ivf.add(xb) - - xq = xb[:10] - _, I_ivf = index_ivf.search(xq, 5) - - for i in range(len(xq)): - self.assertIn(i, I_ivf[i]) - - # ==================== Factory Tests ==================== - def test_factory_construction(self): - """Test multi-bit RaBitQFastScan can be constructed via factory.""" - ds = datasets.SyntheticDataset(64, 150, 200, 10) - - for nb_bits in [2, 4, 8]: - factory_str = f"RaBitQfs{nb_bits}" - index = faiss.index_factory(ds.d, factory_str) - self.assertIsInstance(index, faiss.IndexRaBitQFastScan) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 5) - self.assertEqual(D.shape, (ds.nq, 5)) - self.assertTrue(np.all(I >= 0)) - - def test_factory_with_batch_size(self): - """Test factory construction with both nb_bits and batch size.""" - ds = datasets.SyntheticDataset(64, 150, 200, 10) - - for bbs in [32, 64]: - factory_str = f"RaBitQfs4_{bbs}" - index = faiss.index_factory(ds.d, factory_str) - self.assertIsInstance(index, faiss.IndexRaBitQFastScan) - self.assertEqual(index.rabitq.nb_bits, 4) - self.assertEqual(index.bbs, bbs) - - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 5) - self.assertEqual(D.shape, (ds.nq, 5)) - - def test_ivf_factory_construction(self): - """Test that multi-bit IVF index can be constructed via factory.""" - nlist = 16 - ds = datasets.SyntheticDataset(64, 1000, 500, 20) - - for nb_bits in [2, 4, 8]: - factory_str = f"IVF{nlist},RaBitQfs{nb_bits}" - index = faiss.index_factory(ds.d, factory_str) - self.assertIsInstance(index, faiss.IndexIVFRaBitQFastScan) - self.assertEqual(index.rabitq.nb_bits, nb_bits) - - index.nprobe = 4 - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 10) - self.assertEqual(D.shape, (ds.nq, 10)) - - def test_ivf_factory_with_batch_size(self): - """Test IVF factory construction with both nb_bits and batch size.""" - nlist = 16 ds = datasets.SyntheticDataset(64, 1000, 200, 10) - factory_str = f"IVF{nlist},RaBitQfs4_64" - index = faiss.index_factory(ds.d, factory_str) - self.assertIsInstance(index, faiss.IndexIVFRaBitQFastScan) - self.assertEqual(index.rabitq.nb_bits, 4) - self.assertEqual(index.bbs, 64) + for prefix, cls in [ + ("", faiss.IndexRaBitQFastScan), + ("IVF16,", faiss.IndexIVFRaBitQFastScan), + ]: + for suffix, nb_bits, bbs in [ + ("", 1, 32), + ("4", 4, 32), + ("_64", 1, 64), + ("4_64", 4, 64), + ]: + factory_str = f"{prefix}RaBitQfs{suffix}" + with self.subTest(factory_str=factory_str): + index = faiss.index_factory(ds.d, factory_str) + self.assertIsInstance(index, cls) + self.assertEqual(index.rabitq.nb_bits, nb_bits) + self.assertEqual(index.bbs, bbs) - index.nprobe = 4 - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 5) - self.assertEqual(D.shape, (ds.nq, 5)) + index.train(ds.get_train()) + index.add(ds.get_database()) + _, I = index.search(ds.get_queries(), 5) + self.assertTrue(np.all(I >= 0)) class TestRaBitQFastScanSearchParams(unittest.TestCase): - """Test that IVFRaBitQSearchParameters qb/centered are respected.""" - def test_higher_qb_improves_recall(self): - """Search with qb=4 should give better recall than qb=1.""" d = 64 nlist = 16 nprobe = 4 k = 10 ds = datasets.SyntheticDataset(d, 5000, 5000, 50) - # Ground truth with flat index index_flat = faiss.IndexFlatL2(d) index_flat.add(ds.get_database()) _, I_gt = index_flat.search(ds.get_queries(), k) @@ -1181,19 +840,16 @@ def test_higher_qb_improves_recall(self): index.train(ds.get_train()) index.add(ds.get_database()) - # Search with qb=1 (coarse quantization) params_qb1 = faiss.IVFRaBitQSearchParameters() params_qb1.nprobe = nprobe params_qb1.qb = 1 _, I_qb1 = index.search(ds.get_queries(), k, params=params_qb1) - # Search with qb=4 (finer quantization) params_qb4 = faiss.IVFRaBitQSearchParameters() params_qb4.nprobe = nprobe params_qb4.qb = 4 _, I_qb4 = index.search(ds.get_queries(), k, params=params_qb4) - # Compute recall@k recall_qb1 = np.mean( [len(np.intersect1d(I_qb1[i], I_gt[i])) / k for i in range(ds.nq)] ) diff --git a/thirdparty/faiss/tests/test_rabitq_simd.cpp b/thirdparty/faiss/tests/test_rabitq_simd.cpp index b7552a209..1d87e7e78 100644 --- a/thirdparty/faiss/tests/test_rabitq_simd.cpp +++ b/thirdparty/faiss/tests/test_rabitq_simd.cpp @@ -31,33 +31,8 @@ static std::vector random_codes(size_t d, size_t qb, uint32_t seed) { return q; } -static std::vector random_bytes(size_t n, uint32_t seed) { - std::mt19937 rng(seed); - std::vector v(n); - for (size_t i = 0; i < n; i++) { - v[i] = static_cast(rng()); - } - return v; -} - -// 32-d chunks and chunk boundaries. -static const std::vector kDims = { - 1, - 8, - 16, - 31, - 32, - 33, - 100, - 128, - 255, - 256, - 257, - 384, - 512, - 768, - 1024, - 2048}; +using faiss_test::kDims; +using faiss_test::random_bytes; // Note: scalar kernel's own correctness is covered end-to-end by // tests/test_rabitq.py. This target is x86-only (see BUCK). diff --git a/thirdparty/faiss/tests/test_rabitq_simd_dd.cpp b/thirdparty/faiss/tests/test_rabitq_simd_dd.cpp index 35e0272a8..b3c82145a 100644 --- a/thirdparty/faiss/tests/test_rabitq_simd_dd.cpp +++ b/thirdparty/faiss/tests/test_rabitq_simd_dd.cpp @@ -5,15 +5,8 @@ * LICENSE file in the root directory of this source tree. */ -/* - * RaBitQ kernels that a static build does not compile, against the scalar - * reference. - * - * A static x86 build holds AVX2 kernels only, so the AVX512 and - * AVX512_VPOPCNT specializations exist in a dynamic dispatch build alone. - * test_rabitq_simd.cpp builds in both modes and cannot reference them, so - * they are tested here instead. The target is dynamic dispatch only. - */ +// AVX512 and AVX512_VPOPCNT RaBitQ kernels against the scalar reference. +// Only a dynamic dispatch build compiles these specializations. #include @@ -29,37 +22,8 @@ using faiss::SIMDLevel; -namespace { - -std::vector random_bytes(size_t n, uint32_t seed) { - std::mt19937 rng(seed); - std::vector v(n); - for (size_t i = 0; i < n; i++) { - v[i] = static_cast(rng()); - } - return v; -} - -// Widths on either side of every register boundary the kernels step over. -const std::vector kDims = { - 1, - 8, - 16, - 31, - 32, - 33, - 100, - 128, - 255, - 256, - 257, - 384, - 512, - 768, - 1024, - 2048}; - -} // namespace +using faiss_test::kDims; +using faiss_test::random_bytes; TEST(RaBitQVpopcnt, BitwiseKernelsMatchScalarAcrossTails) { if (!faiss::SIMDConfig::is_simd_level_available( diff --git a/thirdparty/faiss/tests/test_rabitq_simd_neon.cpp b/thirdparty/faiss/tests/test_rabitq_simd_neon.cpp new file mode 100644 index 000000000..b46eff4b5 --- /dev/null +++ b/thirdparty/faiss/tests/test_rabitq_simd_neon.cpp @@ -0,0 +1,118 @@ +/* + * 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. + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "test_rabitq_simd_util.h" + +using faiss::SIMDLevel; +using faiss_test::kDims; +using faiss_test::random_bytes; + +// This target is aarch64-only (see BUCK): it calls the ARM_NEON +// specializations directly, and no other architecture compiles them. +TEST(RaBitQNeon, BitwiseKernelsMatchScalar) { + if (!faiss::SIMDConfig::is_simd_level_available(SIMDLevel::ARM_NEON)) { + GTEST_SKIP() << "ARM_NEON is not available on this CPU"; + } + + for (size_t d : kDims) { + const size_t size = (d + 7) / 8; + const auto data = random_bytes(size, 19717 + d); + for (size_t qb = 1; qb <= 8; qb++) { + const auto query = random_bytes(size * qb, 51691 + d + qb); + + const uint64_t expected_and = + faiss::rabitq::bitwise_and_dot_product( + query.data(), data.data(), size, qb); + const uint64_t expected_xor = + faiss::rabitq::bitwise_xor_dot_product( + query.data(), data.data(), size, qb); + const uint64_t expected_popcount = + faiss::rabitq::popcount(data.data(), size); + + const uint64_t actual_and = + faiss::rabitq::bitwise_and_dot_product( + query.data(), data.data(), size, qb); + const uint64_t actual_xor = + faiss::rabitq::bitwise_xor_dot_product( + query.data(), data.data(), size, qb); + const uint64_t actual_popcount = + faiss::rabitq::popcount( + data.data(), size); + const auto actual_fused = + faiss::rabitq::bitwise_and_dot_product_with_popcount< + SIMDLevel::ARM_NEON>( + query.data(), data.data(), size, qb); + + EXPECT_EQ(actual_and, expected_and) << "d=" << d << " qb=" << qb; + EXPECT_EQ(actual_xor, expected_xor) << "d=" << d << " qb=" << qb; + EXPECT_EQ(actual_popcount, expected_popcount) + << "d=" << d << " qb=" << qb; + EXPECT_EQ(actual_fused.dot_product, expected_and) + << "d=" << d << " qb=" << qb; + EXPECT_EQ(actual_fused.popcount, expected_popcount) + << "d=" << d << " qb=" << qb; + } + } +} + +TEST(RaBitQNeon, MultiBitInnerProductMatchesScalar) { + if (!faiss::SIMDConfig::is_simd_level_available(SIMDLevel::ARM_NEON)) { + GTEST_SKIP() << "ARM_NEON is not available on this CPU"; + } + + std::mt19937 rng(918273); + std::uniform_real_distribution values(-2.0f, 2.0f); + + for (size_t d : kDims) { + const auto sign_bits = random_bytes((d + 7) / 8, 13579 + d); + std::vector query(d); + for (float& value : query) { + value = values(rng); + } + for (size_t ex_bits = 1; ex_bits <= 7; ex_bits++) { + // ip_scalar reads an 8-byte extraction window, so pad the code to + // match the production layout. + const auto extra_bits = random_bytes( + (d * ex_bits + 7) / 8 + 7, 24680 + d + ex_bits); + const float cb = -static_cast((1u << ex_bits) - 0.5f); + const float expected = + faiss::rabitq::multibit::compute_inner_product< + SIMDLevel::NONE>( + sign_bits.data(), + extra_bits.data(), + query.data(), + d, + ex_bits, + cb); + const float actual = faiss::rabitq::multibit::compute_inner_product< + SIMDLevel::ARM_NEON>( + sign_bits.data(), + extra_bits.data(), + query.data(), + d, + ex_bits, + cb); + + // The NEON kernel accumulates in eight lanes, so it does not + // reproduce the scalar sum bit for bit. + const float tolerance = 2e-5f * std::max(1.0f, std::abs(expected)); + EXPECT_NEAR(actual, expected, tolerance) + << "d=" << d << " ex_bits=" << ex_bits; + } + } +} diff --git a/thirdparty/faiss/tests/test_rabitq_simd_util.h b/thirdparty/faiss/tests/test_rabitq_simd_util.h index 02203f9eb..78407e51d 100644 --- a/thirdparty/faiss/tests/test_rabitq_simd_util.h +++ b/thirdparty/faiss/tests/test_rabitq_simd_util.h @@ -5,9 +5,11 @@ * LICENSE file in the root directory of this source tree. */ -// Shared by test_rabitq_simd.cpp and test_rabitq_simd_dd.cpp. The AVX512 -// kernels live in a dynamic dispatch build only, so the tests that call them -// sit in the second file, but both compare against the same scalar reference. +// Shared by test_rabitq_simd.cpp, test_rabitq_simd_dd.cpp and +// test_rabitq_simd_neon.cpp. The AVX512 kernels live in a dynamic dispatch +// build only, and the NEON kernels live in an aarch64 build only, so each set +// of tests sits in its own file. They all compare against the same scalar +// reference. #pragma once @@ -15,6 +17,7 @@ #include #include +#include #include #include @@ -24,6 +27,34 @@ namespace faiss_test { using faiss::SIMDLevel; +// Widths on either side of every register boundary the kernels step over. +inline const std::vector kDims = { + 1, + 8, + 16, + 31, + 32, + 33, + 100, + 128, + 255, + 256, + 257, + 384, + 512, + 768, + 1024, + 2048}; + +inline std::vector random_bytes(size_t n, uint32_t seed) { + std::mt19937 rng(seed); + std::vector v(n); + for (size_t i = 0; i < n; i++) { + v[i] = static_cast(rng()); + } + return v; +} + template inline void check_quantization_matches_scalar() { constexpr size_t d = 257; diff --git a/thirdparty/faiss/tests/test_rabitq_split_inner_product.cpp b/thirdparty/faiss/tests/test_rabitq_split_inner_product.cpp new file mode 100644 index 000000000..11e8a9893 --- /dev/null +++ b/thirdparty/faiss/tests/test_rabitq_split_inner_product.cpp @@ -0,0 +1,262 @@ +/* + * 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. + */ + +// fvec_masked_sum and multibit::compute_inner_product_with_sign_ip +// score a multi-bit RaBitQ code whose sign bits are stored in pieces, e.g. +// partly in memory and partly on disk. They are checked against a double +// reference and against the fused multibit::compute_inner_product, at every +// SIMD level available on this machine. + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { + +using faiss::SIMDLevel; + +struct RestoreSIMD { + SIMDLevel saved = faiss::SIMDConfig::get_level(); + ~RestoreSIMD() { + faiss::SIMDConfig::set_level(saved); + } +}; + +std::vector available_levels() { + std::vector levels; + for (auto level : + {faiss::SIMDConfig::get_level(), + SIMDLevel::NONE, + SIMDLevel::AVX2, + SIMDLevel::AVX512, + SIMDLevel::AVX512_VPOPCNT, + SIMDLevel::ARM_NEON, + SIMDLevel::RISCV_RVV}) { + if (faiss::SIMDConfig::is_simd_level_available(level) && + std::find(levels.begin(), levels.end(), level) == levels.end()) { + levels.push_back(level); + } + } + return levels; +} + +// Dispatched the way multibit::compute_inner_product is. +template +float dispatch(Action&& action) { + return faiss::with_selected_simd_levels< + faiss::AVAILABLE_SIMD_LEVELS_BASE_WITH_VPOPCNT>( + std::forward(action)); +} + +float sign_ip(const uint8_t* sign_bits, const float* rotated_q, size_t d) { + return faiss::with_simd_level([&]() { + return faiss::fvec_masked_sum::value>( + rotated_q, sign_bits, d); + }); +} + +float split_ip( + const uint8_t* ex_code, + const float* rotated_q, + size_t d, + size_t ex_bits, + float cb, + float sign_ip_value, + float q_sum) { + return faiss::with_selected_simd_levels< + faiss::rabitq::multibit:: + RABITQ_SPLIT_IP_SIMD_LEVELS>([&]() { + return faiss::rabitq::multibit::compute_inner_product_with_sign_ip( + ex_code, rotated_q, d, ex_bits, cb, sign_ip_value, q_sum); + }); +} + +float fused_ip( + const uint8_t* sign_bits, + const uint8_t* ex_code, + const float* rotated_q, + size_t d, + size_t ex_bits, + float cb) { + return dispatch([&]() { + return faiss::rabitq::multibit::compute_inner_product( + sign_bits, ex_code, rotated_q, d, ex_bits, cb); + }); +} + +// Dimensions on either side of the 8-, 16- and 32-dim steps of the kernels. +const std::vector kDims = {1, 7, 8, 9, 15, 16, 17, + 24, 31, 32, 33, 63, 64, 65, + 100, 129, 768, 1000, 1280, 1536}; + +std::vector random_query(size_t d, std::mt19937& rng) { + std::normal_distribution normal; + std::vector q(d); + for (auto& v : q) { + v = normal(rng); + } + return q; +} + +// One extra byte in front, so that the codes start at an odd address. +std::vector random_codes(size_t n_bytes, std::mt19937& rng) { + std::vector codes(1 + n_bytes); + for (auto& v : codes) { + v = static_cast(rng()); + } + return codes; +} + +int get_bit(const uint8_t* bits, size_t i) { + return (bits[i / 8] >> (i % 8)) & 1; +} + +unsigned get_ex(const uint8_t* ex_code, size_t i, size_t ex_bits) { + unsigned value = 0; + for (size_t b = 0; b < ex_bits; b++) { + value |= unsigned(get_bit(ex_code, i * ex_bits + b)) << b; + } + return value; +} + +} // namespace + +TEST(RaBitQSplitInnerProduct, WithSignIpMatchesFusedKernel) { + RestoreSIMD restore; + std::mt19937 rng(789); + for (size_t d : kDims) { + for (size_t ex_bits = 1; ex_bits <= 8; ex_bits++) { + const float cb = -(float(1u << ex_bits) - 0.5f); + const auto q = random_query(d, rng); + const auto signs = random_codes((d + 7) / 8, rng); + const size_t ex_bytes = (d * ex_bits + 7) / 8; + // The fused kernel may read 8 bytes past the codes, so it gets a + // padded copy. The split kernel gets codes of the exact size. + const auto ex = random_codes(ex_bytes, rng); + std::vector ex_padded(ex.begin(), ex.end()); + ex_padded.resize(ex.size() + 8); + const uint8_t* sign_bits = signs.data() + 1; + const uint8_t* ex_code = ex.data() + 1; + + double expected = 0, magnitude = 0, q_sum = 0; + for (size_t i = 0; i < d; i++) { + const double recon = (get_bit(sign_bits, i) << ex_bits) + + double(get_ex(ex_code, i, ex_bits)) + cb; + expected += q[i] * recon; + magnitude += std::abs(q[i] * recon); + q_sum += q[i]; + } + const double tolerance = 1e-5 * magnitude + 1e-5; + + for (auto level : available_levels()) { + faiss::SIMDConfig::set_level(level); + const float s = sign_ip(sign_bits, q.data(), d); + const float split = + split_ip(ex_code, q.data(), d, ex_bits, cb, s, q_sum); + const float fused = fused_ip( + sign_bits, + ex_padded.data() + 1, + q.data(), + d, + ex_bits, + cb); + EXPECT_NEAR(split, expected, tolerance) + << "d=" << d << " ex_bits=" << ex_bits + << " level=" << faiss::to_string(level); + EXPECT_NEAR(split, fused, tolerance) + << "d=" << d << " ex_bits=" << ex_bits + << " level=" << faiss::to_string(level); + } + } + } +} + +// The use the kernels are for: sign bits split between a resident prefix and +// a stored suffix, the extra bits in the stored part only. +TEST(RaBitQSplitInnerProduct, SignTermAccumulatedInPieces) { + RestoreSIMD restore; + std::mt19937 rng(1011); + const size_t d = 1536; + for (size_t mem_dim : {0, 64, 384, 768, 1472, 1536}) { + for (size_t ex_bits : {1, 4, 8}) { + const float cb = -(float(1u << ex_bits) - 0.5f); + const auto q = random_query(d, rng); + const auto signs = random_codes(d / 8, rng); + auto ex = random_codes((d * ex_bits + 7) / 8, rng); + ex.resize(ex.size() + 8); // for the fused kernel + const uint8_t* sign_bits = signs.data() + 1; + const uint8_t* ex_code = ex.data() + 1; + + // Each piece in its own buffer, as if read from a different place. + const std::vector prefix( + sign_bits, sign_bits + mem_dim / 8); + const std::vector suffix( + sign_bits + mem_dim / 8, sign_bits + d / 8); + + double expected = 0, magnitude = 0, q_sum = 0; + for (size_t i = 0; i < d; i++) { + const double recon = (get_bit(sign_bits, i) << ex_bits) + + double(get_ex(ex_code, i, ex_bits)) + cb; + expected += q[i] * recon; + magnitude += std::abs(q[i] * recon); + q_sum += q[i]; + } + const double tolerance = 1e-5 * magnitude + 1e-5; + + for (auto level : available_levels()) { + faiss::SIMDConfig::set_level(level); + const float sign_term = + sign_ip(prefix.data(), q.data(), mem_dim) + + sign_ip(suffix.data(), q.data() + mem_dim, d - mem_dim); + const float split = split_ip( + ex_code, q.data(), d, ex_bits, cb, sign_term, q_sum); + const float fused = + fused_ip(sign_bits, ex_code, q.data(), d, ex_bits, cb); + EXPECT_NEAR(split, expected, tolerance) + << "mem_dim=" << mem_dim << " ex_bits=" << ex_bits + << " level=" << faiss::to_string(level); + EXPECT_NEAR(split, fused, tolerance) + << "mem_dim=" << mem_dim << " ex_bits=" << ex_bits + << " level=" << faiss::to_string(level); + } + } + } +} + +TEST(RaBitQSplitInnerProduct, WithSignIpWithoutExtraBits) { + RestoreSIMD restore; + std::mt19937 rng(1213); + const size_t d = 100; + const auto q = random_query(d, rng); + const auto signs = random_codes((d + 7) / 8, rng); + const uint8_t* sign_bits = signs.data() + 1; + const float cb = -0.5f; + + double expected = 0, q_sum = 0; + for (size_t i = 0; i < d; i++) { + expected += q[i] * (get_bit(sign_bits, i) + cb); + q_sum += q[i]; + } + for (auto level : available_levels()) { + faiss::SIMDConfig::set_level(level); + const float s = sign_ip(sign_bits, q.data(), d); + EXPECT_NEAR( + split_ip(nullptr, q.data(), d, 0, cb, s, q_sum), expected, 1e-4) + << "level=" << faiss::to_string(level); + } +} diff --git a/thirdparty/faiss/tests/test_rabitq_utils.py b/thirdparty/faiss/tests/test_rabitq_utils.py index 40bdab81b..a528727cc 100644 --- a/thirdparty/faiss/tests/test_rabitq_utils.py +++ b/thirdparty/faiss/tests/test_rabitq_utils.py @@ -62,15 +62,6 @@ def test_round_nonnegative_to_uint8(self): self.assertEqual(faiss.round_nonnegative_to_uint8(254.5), 255) self.assertEqual(faiss.round_nonnegative_to_uint8(255.0), 255) - below_half = float(np.nextafter(np.float32(0.5), np.float32(0.0))) - self.assertLessEqual( - abs( - int(faiss.round_nonnegative_to_uint8(below_half)) - - round_half_away(below_half) - ), - 1, - ) - rng = np.random.RandomState(123) for x in rng.uniform(0.0, 255.49, size=10000).astype(np.float32): x = float(x) diff --git a/thirdparty/faiss/tests/test_rcq_cropping.py b/thirdparty/faiss/tests/test_rcq_cropping.py new file mode 100644 index 000000000..2c00eedb1 --- /dev/null +++ b/thirdparty/faiss/tests/test_rcq_cropping.py @@ -0,0 +1,114 @@ +# 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. + +"""RCQ cropping tests.""" + +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + + +class TestRCQCropping(unittest.TestCase): + def test_search_params(self): + nq = 10 + nt = 2000 + nb = 1000 + d = 32 + + buf = faiss.rand_smooth_vectors(nq + nb + nt, d) + xt = buf[:nt] + xb = buf[nt : nt + nb] + xq = buf[nt + nb :] + + nbits = faiss.UInt64Vector() + nbits.push_back(3) + nbits.push_back(6) + nbits.push_back(3) + quantizer = faiss.ResidualCoarseQuantizer(d, nbits) + ntotal = 1 << quantizer.rq.tot_bits + index = faiss.IndexIVFScalarQuantizer( + quantizer, d, ntotal, faiss.ScalarQuantizer.QT_8bit + ) + index.quantizer_trains_alone = True + + index.train(xt) + index.add(xb) + + index.nprobe = 10 + + k = 4 + beam_factor_1 = 8.0 + quantizer.set_beam_factor(beam_factor_1) + D1, I1 = index.search(xq, k) + + quantizer.set_beam_factor(1.0) + D2, I2 = index.search(xq, k) + + self.assertFalse(np.array_equal(I1, I2)) + + # override the class level beam factor + params1 = faiss.SearchParametersResidualCoarseQuantizer() + params1.beam_factor = beam_factor_1 + params = faiss.SearchParametersIVF() + params.nprobe = index.nprobe + params.quantizer_params = params1 + + D3, I3 = index.search(xq, k, params=params) + + np.testing.assert_array_equal(I1, I3) + np.testing.assert_array_equal(D1, D3) + + def test_cropping(self): + nq = 10 + nt = 2000 + nb = 1000 + d = 32 + + buf = faiss.rand_smooth_vectors(nq + nb + nt, d, 1234) + xt = buf[:nt] + xq = buf[nt + nb :] + + nbits = [5, 4, 4] + nbits_vec = faiss.UInt64Vector() + for nb_i in nbits: + nbits_vec.push_back(nb_i) + rcq = faiss.ResidualCoarseQuantizer(d, nbits_vec) + + rcq.train(xt) + + # the test below works only for beam size == nprobe + rcq.set_beam_factor(1.0) + + nprobe = 15 + Dref, Iref = rcq.search(xq, nprobe) + + # crop to the first 2 quantization levels + last_nbits = nbits.pop() + nbits_vec = faiss.UInt64Vector() + for nb_i in nbits: + nbits_vec.push_back(nb_i) + rcq_cropped = faiss.ResidualCoarseQuantizer(d, nbits_vec) + rcq_cropped.initialize_from(rcq) + + self.assertEqual(rcq_cropped.ntotal, rcq.ntotal >> last_nbits) + + Dnew, Inew = rcq_cropped.search(xq, nprobe) + + # these bits are in common between the two RCQs + mask = (1 << rcq_cropped.rq.tot_bits) - 1 + for q in range(nq): + for i in range(nprobe): + fine = int(Iref[q, i]) + self.assertGreaterEqual(fine, 0) + # fine should be generated from a path that passes + # through coarse + found = any( + (fine & mask) == Inew[q, j] for j in range(nprobe) + ) + self.assertTrue(found) diff --git a/thirdparty/faiss/tests/test_read_index_deserialize.cpp b/thirdparty/faiss/tests/test_read_index_deserialize.cpp index 8dc6ee3bb..8ba30a38d 100644 --- a/thirdparty/faiss/tests/test_read_index_deserialize.cpp +++ b/thirdparty/faiss/tests/test_read_index_deserialize.cpp @@ -8,40 +8,22 @@ #include #include -#include #include -#include -#include +#include #include #include #include -#include #include -#include -#include #include -#include -#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include -#include #include #include #include #include -#include -#include using namespace faiss; @@ -85,447 +67,111 @@ static void push_index_header( push_val(buf, metric_type); } -/// Helper: append write_ProductQuantizer fields (d, M, nbits, centroids vec). -static void push_pq( - std::vector& buf, - size_t d, - size_t M, - size_t nbits, - const std::vector& centroids = {}) { - push_val(buf, d); - push_val(buf, M); - push_val(buf, nbits); - push_vector(buf, centroids); -} - -/// Try to read a VectorTransform from the given buffer and expect a -/// FaissException whose message contains the given substring. -static void expect_vt_read_throws_with( - const std::vector& data, - const std::string& expected_substr) { - VectorIOReader reader; - reader.data = data; - try { - read_VectorTransform_up(&reader); - FAIL() << "expected FaissException"; - } catch (const FaissException& e) { - EXPECT_NE( - std::string(e.what()).find(expected_substr), std::string::npos) - << "expected '" << expected_substr << "' in: " << e.what(); - } -} - -/// Try to read a float index from the given buffer and expect a FaissException. -static void expect_read_throws(const std::vector& data) { - VectorIOReader reader; - reader.data = data; - EXPECT_THROW(read_index_up(&reader), FaissException); -} - -/// Try to read a float index and expect a FaissException whose message -/// contains the given substring. -static void expect_read_throws_with( - const std::vector& data, - const std::string& expected_substr) { - VectorIOReader reader; - reader.data = data; - try { - read_index_up(&reader); - FAIL() << "expected FaissException"; - } catch (const FaissException& e) { - EXPECT_NE( - std::string(e.what()).find(expected_substr), std::string::npos) - << "expected '" << expected_substr << "' in: " << e.what(); - } -} - -// ----------------------------------------------------------------------- -// Test: ProductQuantizer with M=0 causes divide-by-zero in -// set_derived_values(). The fix validates M > 0 in read_ProductQuantizer -// before calling set_derived_values(). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, PQWithMZeroDivideByZero) { - // Build a minimal MultiIndexQuantizer ("Imiq") payload with M=0. - // Format: fourcc("Imiq") + index_header + PQ(d=4, M=0, nbits=8, []) - std::vector buf; - push_fourcc(buf, "Imiq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_pq(buf, /*d=*/4, /*M=*/0, /*nbits=*/8); - - expect_read_throws(buf); -} - -// ----------------------------------------------------------------------- -// Test: a non-{0,1} byte at a bool field position must be rejected as -// FaissException rather than silently producing an invalid bool value. -// Reading a non-canonical byte directly into a bool is UB and trips -// UBSan's invalid-bool-load check; the READ1_BOOL helper routes every -// bool READ1 through a value check and throws on anything outside {0,1}. -// is_trained, read inside read_index_header, exercises the helper from -// the most common deserialization path. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexHeaderInvalidBoolEncodingIsTrained) { - // Minimal IndexFlatL2 ("IxF2") with ntotal=0 - read_index_header is - // the first thing the deserializer consumes for this fourcc. - std::vector buf; - push_fourcc(buf, "IxF2"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - - // is_trained sits at offset 4 (fourcc) + 4 (d) + 8 (ntotal) + - // 8 (dummy) + 8 (dummy) = 32. push_index_header writes 0x01 there; - // overwrite with a non-canonical bool byte. - constexpr size_t is_trained_offset = 32; - ASSERT_EQ(buf[is_trained_offset], uint8_t{1}); - buf[is_trained_offset] = 0x02; - - expect_read_throws_with(buf, "invalid bool encoding"); -} - -// ----------------------------------------------------------------------- -// Test: AdditiveQuantizer with nbits.size() != M causes out-of-bounds -// access on the nbits vector in set_derived_values(). The fix validates -// nbits.size() == M in read_AdditiveQuantizer. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AdditiveQuantizerNbitsSizeMismatch) { - // Build a minimal IndexProductResidualQuantizerFastScan ("IPRf") payload - // whose AdditiveQuantizer has M=10 but nbits vector has only 1 element. - // - // "IPRf" format: - // fourcc + index_header + read_AdditiveQuantizer(d, M, nbits, - // is_trained, codebooks, search_type, norm_min, norm_max) - // + set_derived_values() - // - // We must provide enough data to reach set_derived_values() so the - // OOB access on nbits[i] actually triggers (rather than an earlier - // read-error throwing first). - std::vector buf; - push_fourcc(buf, "IPRf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // read_AdditiveQuantizer fields: - push_val(buf, 4); // d - push_val(buf, 10); // M = 10 - // nbits vector with only 1 element (should be 10 to match M) - push_vector(buf, {8}); - // is_trained - push_val(buf, true); - // codebooks (empty vector is fine) - push_vector(buf, {}); - // search_type (ST_decompress = 0) - push_val(buf, 0); - // norm_min, norm_max - push_val(buf, 0.0f); - push_val(buf, 1.0f); - // After these reads, set_derived_values() will access nbits[1..9] - // which are out of bounds. - - expect_read_throws_with(buf, "nbits size"); -} - -// ----------------------------------------------------------------------- -// Test: ResidualQuantizer (old format) with nbits.size() != M also causes -// out-of-bounds access. Uses the "IxRQ" fourcc path. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualQuantizerOldNbitsSizeMismatch) { - // "IxRQ" format: fourcc + index_header + read_ResidualQuantizer_old(...) - // read_ResidualQuantizer_old reads: d, M, nbits_vec, is_trained, ... - std::vector buf; - push_fourcc(buf, "IxRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // ResidualQuantizer_old fields: - push_val(buf, 4); // d - push_val(buf, 5); // M = 5 - // nbits vector with only 2 elements (should be 5 to match M) - push_vector(buf, {8, 8}); - - expect_read_throws_with(buf, "nbits size"); -} - -// ----------------------------------------------------------------------- -// Test: ProductQuantizer with d * ksub overflow in centroids allocation. -// The fix uses mul_no_overflow to detect the overflow. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, PQCentroidsOverflow) { - // Build a minimal "Imiq" with d very large and nbits=24 so that - // d * (1 << 24) overflows size_t. - std::vector buf; - push_fourcc(buf, "Imiq"); - // Use a huge d that, when multiplied by ksub=2^24, overflows - size_t huge_d = (size_t)1 << 48; - push_index_header(buf, /*d=*/(int)huge_d, /*ntotal=*/0); - // M must divide d; set M=1 so d % M == 0 - push_pq(buf, /*d=*/huge_d, /*M=*/1, /*nbits=*/24); - - expect_read_throws(buf); -} - // ----------------------------------------------------------------------- -// Test: READVECTOR rejects a vector whose total byte size exceeds the -// configurable deserialization byte limit. Uses a LinearTransform -// ("LTra") whose A vector is read via READVECTOR. +// Test: Index2Layer deserialization sets own_fields=true so the +// sub-quantizer is freed when the deserialized index is destroyed. +// C++ only: Python cannot subclass Index to observe the destructor. // ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, READVECTORByteLimit) { - // Build a "LTra" (LinearTransform) payload. - // Format: fourcc + have_bias + READVECTOR(A) + READVECTOR(b) - // + d_in + d_out + is_trained - // A contains 1024 floats = 4096 bytes. - // READVECTOR check: size < limit / sizeof(float) - const size_t old_limit = get_deserialization_vector_byte_limit(); - - const int d_in = 32; - const int d_out = 32; - const size_t n_elements = d_in * d_out; // 1024 - - std::vector buf; - push_fourcc(buf, "LTra"); - push_val(buf, false); // have_bias - std::vector A(n_elements, 0.0f); - push_vector(buf, A); - // b vector: empty (no bias) - push_vector(buf, {}); - // Common VectorTransform fields - push_val(buf, d_in); - push_val(buf, d_out); - push_val(buf, true); // is_trained - // Exactly at the boundary: limit = n_elements * sizeof(float). - // Check is strict less-than, so this should be rejected. - set_deserialization_vector_byte_limit(n_elements * sizeof(float)); - { - VectorIOReader reader; - reader.data = buf; - EXPECT_THROW(read_VectorTransform_up(&reader), FaissException); +struct CountedDestructorIndex : IndexFlatL2 { + static int destructor_count; + using IndexFlatL2::IndexFlatL2; + ~CountedDestructorIndex() override { + destructor_count++; } +}; +int CountedDestructorIndex::destructor_count = 0; + +TEST(ReadIndexDeserialize, Index2LayerQuantizerOwnership) { + int d = 4, nb = 512, nlist = 2; - // One element above the boundary: limit = (n_elements + 1) * sizeof(float). - // Now n_elements < limit / sizeof(float) = n_elements + 1, so it passes. - set_deserialization_vector_byte_limit((n_elements + 1) * sizeof(float)); + auto original_q = std::make_unique(d); + Index2Layer original(original_q.release(), nlist, 2); + original.q1.own_fields = true; + std::vector xb(d * nb); { - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_VectorTransform_up(&reader)); + std::mt19937 rng(42); + std::uniform_real_distribution dist; + for (auto& v : xb) { + v = dist(rng); + } } + original.train(nb, xb.data()); + original.add(nb, xb.data()); - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: ProductQuantizer centroids allocation is rejected when it would -// exceed the configurable deserialization byte limit. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, PQCentroidsByteLimit) { - // d=8, M=1, nbits=8 → ksub=256, centroids = 8*256 = 2048 floats. - // PQ check: n < limit / sizeof(float), where n = d * ksub = 2048. - const size_t old_limit = get_deserialization_vector_byte_limit(); - - const size_t d = 8; - const size_t M = 1; - const size_t nbits = 8; - const size_t ksub = size_t{1} << nbits; - const size_t n_elements = d * ksub; // 2048 - std::vector centroids(n_elements, 0.0f); - - std::vector buf; - push_fourcc(buf, "Imiq"); - push_index_header(buf, /*d=*/d, /*ntotal=*/0); - push_pq(buf, d, M, nbits, centroids); + VectorIOWriter writer; + write_index(&original, &writer); - // Exactly at the boundary: limit = n_elements * sizeof(float). - // Check is strict less-than, so this should be rejected. - set_deserialization_vector_byte_limit(n_elements * sizeof(float)); + // Swap in a CountedDestructorIndex to observe whether own_fields frees it. + CountedDestructorIndex::destructor_count = 0; { VectorIOReader reader; - reader.data = buf; - EXPECT_THROW(read_index_up(&reader), FaissException); - } + reader.data = writer.data; + auto idx = std::unique_ptr(read_index(&reader)); + auto* idx2l = dynamic_cast(idx.get()); + ASSERT_NE(idx2l, nullptr); - // One element above the boundary: limit = (n_elements + 1) * sizeof(float). - // Now n_elements < limit / sizeof(float) = n_elements + 1, so it passes. - set_deserialization_vector_byte_limit((n_elements + 1) * sizeof(float)); - { - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); + delete idx2l->q1.quantizer; + idx2l->q1.quantizer = new CountedDestructorIndex(d); + // idx goes out of scope here. If own_fields is true, + // ~Level1Quantizer deletes the CountedDestructorIndex. } - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: IndexLattice with nsq=0 causes divide-by-zero in the -// constructor's member initializer list (dsq = d / nsq). The fix -// validates nsq > 0 in the deserialization path. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeNsqZeroDivideByZero) { - // "IxLa" format: fourcc + d(int) + nsq(int) + scale_nbit(int) - // + r2(int) + index_header + READVECTOR(trained) - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 16); // d - push_val(buf, 0); // nsq = 0 -> divide by zero - push_val(buf, 4); // scale_nbit - push_val(buf, 14); // r2 - - expect_read_throws(buf); -} - -// ----------------------------------------------------------------------- -// Test: IndexLattice with d not divisible by nsq causes undefined -// behavior in the constructor. The fix validates d % nsq == 0 before -// construction. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeDNotDivisibleByNsq) { - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 17); // d = 17 (not divisible by nsq=4) - push_val(buf, 4); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, 14); // r2 - - expect_read_throws_with(buf, "divisible by nsq"); -} - -// ----------------------------------------------------------------------- -// Test: IndexLattice with r2=0 causes heap-buffer-overflow in -// ZnSphereCodecRec constructor. The fix validates r2 > 0. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeR2Zero) { - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 4); // d - push_val(buf, 1); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, 0); // r2 = 0 -> heap-buffer-overflow - - expect_read_throws_with(buf, "r2"); + EXPECT_EQ(CountedDestructorIndex::destructor_count, 1); } -// ----------------------------------------------------------------------- -// Test: IndexLattice with d/nsq not a power of 2 >= 2 causes -// heap-buffer-overflow in ZnSphereCodecRec constructor. The fix -// validates that d/nsq is a power of 2 and >= 2. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeDsqNotPowerOf2) { - // d=3, nsq=1 -> dsq=3 (not a power of 2) - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 3); // d - push_val(buf, 1); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, 1); // r2 - - expect_read_throws_with(buf, "power of 2"); -} +namespace { -TEST(ReadIndexDeserialize, IndexLatticeDsqOne) { - // d=1, nsq=1 -> dsq=1 (too small, causes cache_level=-1) - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 1); // d - push_val(buf, 1); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, 1); // r2 +constexpr size_t kTurboQFullDimension = 16; +constexpr uint64_t kTurboQFullSeed = 0x0123456789abcdefULL; +constexpr auto kTurboQFullQtype = ScalarQuantizer::QT_3bit_tq; +// QT_3bit_tq: (3 - 1) MSE bits + 1 QJL bit, so 1 << (3 - 1) centroids. +constexpr size_t kTurboQFullCentroids = 4; - expect_read_throws_with(buf, "power of 2"); -} +std::vector make_turboq_full_sq_payload(uint8_t qjl_type) { + float seed[2]; + ScalarQuantizer::TurboQuantRefine::pack_seed(kTurboQFullSeed, seed); + std::vector trained( + kTurboQFullCentroids + (kTurboQFullCentroids - 1) + 3, 0.0f); + trained[trained.size() - 3] = seed[0]; + trained[trained.size() - 2] = seed[1]; + trained[trained.size() - 1] = static_cast(qjl_type); -// ----------------------------------------------------------------------- -// Test: IndexLattice with r2 too large causes timeout in -// ZnSphereCodecRec constructor (exponential codeword count in the -// decode cache). ZnSphereCodecRec caps the decode cache size to -// prevent this. Use dsq=16 (log2_dim=4, cache_level=3) with r2=73 -// which would take well over a minute of CPU time if not rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeR2TooLarge) { std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 16); // d - push_val(buf, 1); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, 73); // r2 = 73 (decode cache too large for dsq=16) - - expect_read_throws_with(buf, "decode cache"); + push_fourcc(buf, "IxSQ"); + push_index_header( + buf, static_cast(kTurboQFullDimension), /*ntotal=*/0); + push_val(buf, kTurboQFullQtype); + push_val(buf, 0); // rangestat + push_val(buf, 0.0f); // rangestat_arg + push_val(buf, kTurboQFullDimension); + push_val(buf, 0); // code_size is recomputed on read + push_vector(buf, trained); + push_vector(buf, {}); // codes + return buf; } -// ----------------------------------------------------------------------- -// Test: the configurable deserialization_lattice_r2_limit rejects -// IndexLattice payloads whose r2 exceeds the limit, separately from -// the in-codec decode-cache memory cap. The limit's purpose is to -// let callers that operate on untrusted index payloads cap the -// ZnSphereCodecRec decode-cache build cost (which grows polynomially -// in r2) before it dominates load time, even for parameter -// combinations that the memory cap permits. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLatticeR2ConfigurableLimit) { - const size_t old_limit = get_deserialization_lattice_r2_limit(); - - // d=4, nsq=1, scale_nbit=4 produces dsq=4 -- a configuration that - // passes the existing structural checks. r2 at the limit must - // deserialize cleanly (the cap is "r2 > limit", not "r2 >= limit"); - // r2 above the limit must be rejected with a FaissException whose - // message names the limit, before the IndexLattice constructor - // (and the underlying ZnSphereCodecRec) is invoked. - constexpr int d = 4; - auto build = [](int r2) { - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, d); // d - push_val(buf, 1); // nsq - push_val(buf, 4); // scale_nbit - push_val(buf, r2); // r2 - push_index_header(buf, d, /*ntotal=*/0); - // Untrained: empty trained vector. - push_vector(buf, {}); - return buf; - }; +} // namespace - set_deserialization_lattice_r2_limit(2); - { - // r2 == limit: the limit check passes (since it is r2 > limit, - // not r2 >= limit) and the underlying ZnSphereCodecRec - // constructor runs to completion. - auto buf = build(2); - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); - } - { - // r2 == limit + 1: rejected at the limit check with the - // configured limit value in the error message. - auto buf = build(3); - expect_read_throws_with(buf, "deserialization_lattice_r2_limit"); - } +// C++ only: swig does not wrap ScalarQuantizer::TurboQuantRefine. +TEST(ReadIndexDeserialize, SQTurboQuantFullRecoversConfigFromTrained) { + // qjl_type 2, not the default 0, so a missing extraction is caught. + const uint8_t qjl_type = 2; + VectorIOReader reader; + reader.data = make_turboq_full_sq_payload(qjl_type); + std::unique_ptr index; + ASSERT_NO_THROW(index = read_index_up(&reader)); - set_deserialization_lattice_r2_limit(old_limit); + const auto* sq_index = dynamic_cast(index.get()); + ASSERT_NE(sq_index, nullptr); + EXPECT_EQ(sq_index->sq.turboq_refine.qjl_type, qjl_type); + EXPECT_EQ(sq_index->sq.turboq_refine.seed, kTurboQFullSeed); } // ----------------------------------------------------------------------- -// Binary index helpers +// Malformed streams must throw FaissException instead of reading out of +// bounds. Regression tests for crashes found by the Lionhead fuzzers. // ----------------------------------------------------------------------- -/// Helper: append read_index_binary_header fields. -/// Fields: int d, int code_size, idx_t ntotal, bool is_trained, int metric_type -static void push_binary_index_header( - std::vector& buf, - int d, - int64_t ntotal, - bool is_trained = true, - int metric_type = 1 /* L2 */) { - int code_size = d / 8; - push_val(buf, d); - push_val(buf, code_size); - push_val(buf, ntotal); - push_val(buf, is_trained); - push_val(buf, metric_type); -} - -/// Try to read a binary index from the given buffer and expect a -/// FaissException. -static void expect_binary_read_throws(const std::vector& data) { - VectorIOReader reader; - reader.data = data; - EXPECT_THROW(read_index_binary_up(&reader), FaissException); -} - /// Try to read a binary index and expect a FaissException whose message /// contains the given substring. static void expect_binary_read_throws_with( @@ -543,3867 +189,162 @@ static void expect_binary_read_throws_with( } } -/// Helper: append empty direct_map bytes (NoMap type + empty array). -static void push_empty_direct_map(std::vector& buf) { - push_val(buf, 0); // DirectMap::NoMap - push_val(buf, 0); // empty array -} - -/// Helper: append null inverted lists ("il00" fourcc). -static void push_null_invlists(std::vector& buf) { - push_fourcc(buf, "il00"); -} - -/// Helper: append a minimal IndexBinaryFlat ("IBxF") with the given -/// dimensions and ntotal=0. -static void push_minimal_binary_flat(std::vector& buf, int d) { - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, d, /*ntotal=*/0); - push_vector(buf, {}); // empty xb -} - -// ----------------------------------------------------------------------- -// Test: Unrecognized binary fourcc throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryUnrecognizedFourcc) { - std::vector buf; - push_fourcc(buf, "ZZZZ"); - - expect_binary_read_throws(buf); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryFlat with truncated input (fourcc only, no header). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryFlatTruncatedInput) { - std::vector buf; - push_fourcc(buf, "IBxF"); - - expect_binary_read_throws(buf); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryFlat xb size mismatch (ntotal=1 but empty xb). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryFlatXbSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/1); - push_vector(buf, {}); // empty xb, but ntotal=1 expects 2 bytes - - expect_binary_read_throws_with(buf, "xb.size()"); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryFlat with negative dimension. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryFlatNegativeDimension) { - std::vector buf; - push_fourcc(buf, "IBxF"); - // Manually push header with d=-1 - push_val(buf, -1); // d - push_val(buf, 0); // code_size - push_val(buf, 0); // ntotal +/// Append read_index_binary_header fields. +static void push_binary_header( + std::vector& buf, + int d, + int code_size, + int64_t ntotal) { + push_val(buf, d); + push_val(buf, code_size); + push_val(buf, ntotal); push_val(buf, true); // is_trained - push_val(buf, 1); // metric_type - - expect_binary_read_throws_with(buf, "dimension"); + push_val(buf, 1); // metric_type (L2) } -// ----------------------------------------------------------------------- -// Test: IndexBinaryMultiHash with storage ntotal mismatch exercises the -// Leak 5 fix (dynamic_cast + assertion with unique_ptr guard). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryMultiHashStorageCastFailure) { +TEST(ReadIndexDeserialize, BinaryMultiHashMapNegativeIdBitsRejected) { + // id_bits == -b with ntotal == 0 makes the multi hash map's bit + // budget zero, so its buffer is empty while entries remain to read. std::vector buf; push_fourcc(buf, "IBHm"); - // Outer index header: ntotal=99 - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/99); - // Nested IBxF storage with ntotal=0 (mismatch with outer ntotal=99) - push_minimal_binary_flat(buf, /*d=*/16); - - expect_binary_read_throws(buf); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryIVF with inverted list nlist mismatch exercises the -// Leak 2 fix. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryIVFInvListNlistMismatch) { - std::vector buf; - push_fourcc(buf, "IBwF"); - // Binary IVF header: binary_header + nlist + nprobe + quantizer + - // direct_map - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 10); // nlist = 10 - push_val(buf, 1); // nprobe - // Nested quantizer (IBxF) - push_minimal_binary_flat(buf, /*d=*/16); - // Empty direct map - push_empty_direct_map(buf); - // ArrayInvertedLists with nlist=5 (mismatch with IVF nlist=10). - // "ilar" fourcc + nlist + code_size + sizes - push_fourcc(buf, "ilar"); - push_val(buf, 5); // nlist = 5 (mismatches IVF nlist=10) - push_val(buf, 2); // code_size = d/8 = 2 - // 5 list sizes, all zero - for (int i = 0; i < 5; i++) { - push_val(buf, 0); - } + push_binary_header(buf, 8, 1, 0); + push_fourcc(buf, "IBxF"); + push_binary_header(buf, 8, 1, 0); + push_vector(buf, {}); // storage xb + push_val(buf, 1); // b + push_val(buf, 1); // nhash + push_val(buf, 0); // nflip + push_val(buf, -1); // id_bits + push_val(buf, 1); // sz + push_vector(buf, {}); // buf - expect_binary_read_throws(buf); + expect_binary_read_throws_with(buf, "id_bits"); } -// ----------------------------------------------------------------------- -// Test: IndexBinaryHash with empty hash invlist buffer but non-zero entry -// count. Exercises the null-deref fix in read_binary_hash_invlists. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryHashEmptyInvlistBuffer) { +TEST(ReadIndexDeserialize, BinaryMultiHashMapZeroIdBitsParses) { + // id_bits == 0 is what the writer emits for ntotal == 0. The last + // entry's zero-bit size read must not touch the buffer past its end. std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 4); // b - push_val(buf, 0); // nflip - push_val(buf, size_t(1)); // sz = 1 (non-zero) - push_val(buf, 8); // il_nbit - push_vector(buf, {}); // empty buffer (should fail) - - expect_binary_read_throws_with(buf, "binary hash invlists"); -} + push_fourcc(buf, "IBHm"); + push_binary_header(buf, 8, 1, 0); + push_fourcc(buf, "IBxF"); + push_binary_header(buf, 8, 1, 0); + push_vector(buf, {}); // storage xb + push_val(buf, 2); // b + push_val(buf, 1); // nhash + push_val(buf, 0); // nflip + push_val(buf, 0); // id_bits + push_val(buf, 12); // sz + push_vector(buf, {0x01, 0x49, 0x6d}); // buf -// ----------------------------------------------------------------------- -// Test: NSG with R=0 triggers the R > 0 validation. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, NSGNegativeR) { - // "INSf" format: fourcc + index_header + GK + build_type + - // nndescent_S/R/L/iter + read_NSG(ntotal, R, ...) + VectorIOReader reader; + reader.data = buf; + std::unique_ptr index; + ASSERT_NO_THROW(index = read_index_binary_up(&reader)); + const auto* idxmh = dynamic_cast(index.get()); + ASSERT_NE(idxmh, nullptr); + ASSERT_EQ(idxmh->maps.size(), 1); + // The 12 two-bit hashes collide into at most 4 distinct keys, each + // holding no ids because ntotal == 0. + EXPECT_LE(idxmh->maps[0].size(), 12); + size_t total_ids = 0; + for (const auto& entry : idxmh->maps[0]) { + total_ids += entry.second.size(); + } + EXPECT_EQ(total_ids, 0); +} + +/// Build an "Ixrr" (IndexRaBitQ, multi-bit) stream. +static std::vector make_rabitq_payload( + size_t code_size, + const std::vector& codes, + const std::vector& center) { std::vector buf; - push_fourcc(buf, "INSf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 0); // GK - push_val(buf, 0); // build_type - push_val(buf, 10); // nndescent_S - push_val(buf, 10); // nndescent_R - push_val(buf, 10); // nndescent_L - push_val(buf, 1); // nndescent_iter - // read_NSG fields: - push_val(buf, 0); // ntotal - push_val(buf, -1); // R = -1 (invalid) - - expect_read_throws_with(buf, "invalid NSG R"); + push_fourcc(buf, "Ixrr"); + push_index_header(buf, 4, 1); + push_val(buf, size_t(4)); // rabitq.d + push_val(buf, code_size); // rabitq.code_size + push_val(buf, 1); // metric_type (L2) + push_val(buf, size_t(1)); // nb_bits + push_vector(buf, codes); + push_vector(buf, center); + push_val(buf, 0); // qb + return buf; } -// ----------------------------------------------------------------------- -// Test: ScalarQuantizer with out-of-range qtype throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ScalarQuantizerInvalidQtype) { - // "IxSQ" format: fourcc + index_header + read_ScalarQuantizer(qtype, ...) - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // ScalarQuantizer fields: - push_val(buf, 99); // qtype = 99 (out of range) - - expect_read_throws_with(buf, "qtype"); -} - -// ----------------------------------------------------------------------- -// Test: ProductAdditiveQuantizer with nsplits=0 throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductAdditiveQuantizerZeroNsplits) { - // "IxPR" format: fourcc + index_header + - // read_ProductResidualQuantizer(read_ProductAdditiveQuantizer( - // read_AdditiveQuantizer(...) + nsplits)) - std::vector buf; - push_fourcc(buf, "IxPR"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // AdditiveQuantizer fields: - push_val(buf, 4); // d - push_val(buf, 1); // M - push_vector(buf, {8}); // nbits (1 element matching M=1) - push_val(buf, true); // is_trained - // codebooks: d * total_codebook_size = 4 * 256 = 1024 floats - push_vector(buf, std::vector(4 * 256, 0.0f)); - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - // ProductAdditiveQuantizer field: - push_val(buf, 0); // nsplits = 0 (invalid) - - expect_read_throws_with(buf, "nsplits"); -} - -// ----------------------------------------------------------------------- -// Test: PreTransform with negative chain length throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, PreTransformNegativeChainLength) { - // "IxPT" format: fourcc + index_header + nt + VT chain + nested index - std::vector buf; - push_fourcc(buf, "IxPT"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, -1); // nt = -1 (invalid) - - expect_read_throws_with(buf, "chain length"); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryMultiHash with nhash=0 throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryMultiHashZeroNhash) { - std::vector buf; - push_fourcc(buf, "IBHm"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - // Nested IBxF storage (ntotal=0 matches outer) - push_minimal_binary_flat(buf, /*d=*/16); - push_val(buf, 4); // b - push_val(buf, 0); // nhash = 0 (invalid) - - expect_binary_read_throws_with(buf, "nhash"); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryHash with b=0 triggers the b > 0 validation. -// Without this check, BitstringReader::read(0) would silently produce -// garbage hash values on every inverted-list entry. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryHashBZero) { - std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 0); // b = 0 (invalid) - - expect_binary_read_throws_with(buf, "IndexBinaryHash b="); -} - -// ----------------------------------------------------------------------- -// Test: read_binary_hash_invlists with negative il_nbit triggers the -// il_nbit >= 0 validation. Without this check, the negative value would -// wrap to a huge size_t in the bits-per-entry calculation, causing an -// out-of-bounds read in BitstringReader. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryHashNegativeIlNbit) { - std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 4); // b - push_val(buf, 0); // nflip - // read_binary_hash_invlists fields: - push_val(buf, size_t(0)); // sz = 0 - push_val(buf, -1); // il_nbit = -1 (invalid) - - expect_binary_read_throws_with(buf, "il_nbit="); -} - -// ----------------------------------------------------------------------- -// Test: read_binary_hash_invlists with il_nbit=0 but sz > 0 triggers -// the il_nbit > 0 validation. Without this check, every inverted-list -// size would silently read as 0, corrupting the deserialized index. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryHashIlNbitZeroWithEntries) { - std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 4); // b - push_val(buf, 0); // nflip - // read_binary_hash_invlists fields: - push_val(buf, size_t(1)); // sz = 1 (non-zero) - push_val(buf, 0); // il_nbit = 0 (invalid when sz > 0) - - expect_binary_read_throws_with(buf, "il_nbit="); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryHash with b exceeding code_size*8 triggers validation. -// Without this check, BitstringReader::read() would access past the -// allocated code buffer, causing a heap-buffer-overflow. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryHashBExceedsCodeSize) { - std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - // d=16 → code_size=2 → 16 bits available - push_val(buf, 17); // b = 17 (exceeds 16 bits) - - expect_binary_read_throws_with(buf, "IndexBinaryHash b="); -} - -// ----------------------------------------------------------------------- -// Test: read_binary_multi_hash_map with crafted ilsz values that sum to -// more than ntotal. Without the check, the inner loop would read past -// the end of the BitstringReader buffer. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryMultiHashMapIlszExceedsNtotal) { - // ntotal=4 → id_bits=2 (writer: while (4 > (1< bitbuf(bitbuf_size, 0); - BitstringWriter wr(bitbuf.data(), bitbuf.size()); - // Entry 0: hash=0, ilsz=3, ids={0,0,0} - wr.write(0, b); - wr.write(3, id_bits); - wr.write(0, id_bits); - wr.write(0, id_bits); - wr.write(0, id_bits); - // Entry 1: hash=1, ilsz=3 - // (reader should throw before reading ids for this entry) - wr.write(1, b); - wr.write(3, id_bits); - - // Build the full IBHm serialized buffer. - std::vector buf; - push_fourcc(buf, "IBHm"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal); - - // Nested IBxF storage with matching ntotal. - // xb needs ntotal * code_size bytes (code_size = d/8 = 2). - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal); - std::vector xb(ntotal * 2, 0); - push_vector(buf, xb); - - push_val(buf, b); // b - push_val(buf, 1); // nhash = 1 - push_val(buf, 0); // nflip - - // Multi hash map fields (1 map): - push_val(buf, id_bits); // id_bits - push_val(buf, sz); // sz = 2 entries - push_vector(buf, bitbuf); // packed bitstring - - expect_binary_read_throws_with(buf, "would exceed ntotal"); -} - -// ----------------------------------------------------------------------- -// Test: IndexBinaryIDMap ("IBMp") with id_map size != ntotal. Without -// the check, construct_rev_map (IBM2) or subsequent search operations -// would use an inconsistent ID mapping. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BinaryIDMapIdMapSizeMismatch) { - // Outer IBMp header has ntotal=2, but the id_map vector has 5 - // entries. The check on id_map.size() == ntotal must reject this. - std::vector buf; - push_fourcc(buf, "IBMp"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/2); - - // Nested IBxF storage with ntotal=2 (matches outer header). - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/2); - std::vector xb(2 * 2, 0); // ntotal * code_size - push_vector(buf, xb); - - // id_map with 5 entries (mismatches ntotal=2). - std::vector id_map = {10, 20, 30, 40, 50}; - push_vector(buf, id_map); - - expect_binary_read_throws_with(buf, "id_map"); -} - -// ----------------------------------------------------------------------- -// Test: IndexIDMap2 ("IxM2") with id_map size != ntotal. Without the -// check, construct_rev_map() reads past id_map bounds causing a crash. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexIDMap2IdMapSizeMismatch) { - // Outer IxM2 header has ntotal=2, but the id_map vector has 5 - // entries. The check on id_map.size() == ntotal must reject this. - std::vector buf; - push_fourcc(buf, "IxM2"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - - // Nested IndexFlatL2 ("IxF2") with ntotal=2. - push_fourcc(buf, "IxF2"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // WRITEXBVECTOR: ntotal * d floats - size_t num_floats = 2 * 4; - push_val(buf, num_floats); - for (size_t i = 0; i < num_floats; ++i) { - push_val(buf, 0.0f); - } - - // id_map with 5 entries (mismatches ntotal=2). - std::vector id_map = {10, 20, 30, 40, 50}; - push_vector(buf, id_map); - - expect_read_throws_with(buf, "id_map"); -} - -// ----------------------------------------------------------------------- -// InvertedLists helpers -// ----------------------------------------------------------------------- - -/// Try to read an InvertedLists from the given buffer and expect a -/// FaissException whose message contains the given substring. -static void expect_invlists_read_throws_with( +/// Try to read a float index and expect a FaissException whose message +/// contains the given substring. +static void expect_float_read_throws_with( const std::vector& data, const std::string& expected_substr) { VectorIOReader reader; - reader.data = data; - try { - read_InvertedLists_up(&reader); - FAIL() << "expected FaissException"; - } catch (const FaissException& e) { - EXPECT_NE( - std::string(e.what()).find(expected_substr), std::string::npos) - << "expected '" << expected_substr << "' in: " << e.what(); - } -} - -// ----------------------------------------------------------------------- -// Test: BlockInvertedLists with n_per_block=0 causes divide-by-zero -// in resize() and add_entries(). The fix validates n_per_block > 0 -// during deserialization. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BlockInvertedListsNPerBlockZero) { - std::vector buf; - push_fourcc(buf, "ilbl"); - push_val(buf, 1); // nlist - push_val(buf, 32); // code_size - push_val(buf, 0); // n_per_block = 0 (invalid) - push_val(buf, 128); // block_size - - expect_invlists_read_throws_with(buf, "n_per_block"); -} - -// ----------------------------------------------------------------------- -// Test: BlockInvertedLists with block_size=0 causes divide-by-zero -// in add_entries(). The fix validates block_size > 0 during -// deserialization. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BlockInvertedListsBlockSizeZero) { - std::vector buf; - push_fourcc(buf, "ilbl"); - push_val(buf, 1); // nlist - push_val(buf, 32); // code_size - push_val(buf, 32); // n_per_block - push_val(buf, 0); // block_size = 0 (invalid) - - expect_invlists_read_throws_with(buf, "block_size"); -} - -// ----------------------------------------------------------------------- -// Test: BlockInvertedLists with codes vector size inconsistent with ids -// size, n_per_block, and block_size. Without the check, a search or -// add operation would read/write past the end of the codes buffer. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BlockInvertedListsCodesSizeMismatch) { - const size_t n_per_block = 32; - const size_t block_size = 128; - - std::vector buf; - push_fourcc(buf, "ilbl"); - push_val(buf, 1); // nlist = 1 - push_val(buf, 32); // code_size - push_val(buf, n_per_block); // n_per_block - push_val(buf, block_size); // block_size - - // ids: 10 entries → ceil(10/32) = 1 block → expected codes = 128 bytes - std::vector ids(10, 0); - push_vector(buf, ids); - // codes: 64 bytes (wrong, should be 128) - std::vector codes(64, 0); - push_vector(buf, codes); - - expect_invlists_read_throws_with(buf, "codes size"); -} - -// ----------------------------------------------------------------------- -// Test: BlockInvertedLists with n_block * block_size overflow. Without -// the mul_no_overflow check, the multiplication wraps around and the -// size comparison passes spuriously. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BlockInvertedListsCodesOverflow) { - // Choose n_per_block=1 and block_size near SIZE_MAX so that - // n_block * block_size overflows. - const size_t n_per_block = 1; - const size_t block_size = (size_t)-1; // SIZE_MAX - - std::vector buf; - push_fourcc(buf, "ilbl"); - push_val(buf, 1); // nlist = 1 - push_val(buf, 32); // code_size - push_val(buf, n_per_block); // n_per_block - push_val(buf, block_size); // block_size - - // ids: 2 entries → n_block = 2 → 2 * SIZE_MAX overflows - std::vector ids(2, 0); - push_vector(buf, ids); - // codes: any size, doesn't matter — overflow should be caught first - std::vector codes(0); - push_vector(buf, codes); - - expect_invlists_read_throws_with(buf, "overflow"); -} - -// ----------------------------------------------------------------------- -// Test: BlockInvertedLists with valid ids and codes passes validation. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, BlockInvertedListsValidCodesSize) { - const size_t n_per_block = 32; - const size_t block_size = 128; - const size_t nlist = 2; - - std::vector buf; - push_fourcc(buf, "ilbl"); - push_val(buf, nlist); // nlist - push_val(buf, 32); // code_size - push_val(buf, n_per_block); // n_per_block - push_val(buf, block_size); // block_size - - // List 0: 10 ids → ceil(10/32)=1 block → 128 bytes - std::vector ids0(10, 0); - push_vector(buf, ids0); - std::vector codes0(128, 0); - push_vector(buf, codes0); - - // List 1: 0 ids → 0 blocks → 0 bytes - std::vector ids1; - push_vector(buf, ids1); - std::vector codes1; - push_vector(buf, codes1); - - VectorIOReader reader; - reader.data = buf; - auto il = read_InvertedLists_up(&reader); - EXPECT_NE(il, nullptr); -} - -// ----------------------------------------------------------------------- -// Test: ProductQuantizer centroids size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, PQCentroidsSizeMismatch) { - // "Imiq" (MultiIndexQuantizer): fourcc + index_header + PQ - // PQ: d=4, M=2, nbits=8 -> ksub=256, expected centroids = 4*256 = 1024 - std::vector buf; - push_fourcc(buf, "Imiq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - std::vector bad_centroids(100, 0.0f); - push_pq(buf, /*d=*/4, /*M=*/2, /*nbits=*/8, bad_centroids); - - expect_read_throws_with(buf, "centroids size"); -} - -// ----------------------------------------------------------------------- -// Test: ScalarQuantizer trained vector size mismatch. -// For QT_4bit (qtype=1), expected trained.size() = 2 * d. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, SQTrainedSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // ScalarQuantizer fields: - push_val( - buf, ScalarQuantizer::QT_4bit); // expects trained.size()=2*d=8 - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 1); // code_size - // trained: 3 floats instead of expected 8 - push_vector(buf, {1.0f, 2.0f, 3.0f}); - - expect_read_throws_with(buf, "ScalarQuantizer trained size"); -} - -// ----------------------------------------------------------------------- -// Test: IndexPQ codes vector size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQCodesSizeMismatch) { - // "IxPq": fourcc + index_header + PQ + codes + search_type + - // encode_signs + polysemous_ht - std::vector buf; - push_fourcc(buf, "IxPq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // PQ: d=4, M=2, nbits=8 -> code_size=2, ksub=256 - std::vector centroids(4 * 256, 0.0f); - push_pq(buf, /*d=*/4, /*M=*/2, /*nbits=*/8, centroids); - // codes: should be ntotal * code_size = 2 * 2 = 4 bytes - // Provide wrong size (10 bytes) - push_vector(buf, std::vector(10, 0)); - // IxPq format extras: - push_val(buf, 0); // search_type - push_val(buf, 0); // encode_signs - push_val(buf, 0); // polysemous_ht - - expect_read_throws_with(buf, "codes.size()"); -} - -/// Helper: append a minimal AdditiveQuantizer (d, M, nbits, is_trained, -/// codebooks, search_type=ST_decompress, norm_min, norm_max). -/// Writes zero-filled codebooks of size codebook_d * total_codebook_size so -/// that the deserialization codebooks-size validation passes. -/// For standalone quantizers codebook_d == d. For ProductAdditiveQuantizer -/// codebook_d == d / nsplits. Pass codebook_d = 0 (default) to use d. -static void push_additive_quantizer( - std::vector& buf, - size_t d, - size_t M, - const std::vector& nbits, - size_t codebook_d = 0) { - if (codebook_d == 0) { - codebook_d = d; - } - - // Compute total_codebook_size = sum(2^nbits[i]). - size_t total_codebook_size = 0; - for (auto nb : nbits) { - total_codebook_size += size_t{1} << nb; - } - - push_val(buf, d); - push_val(buf, M); - push_vector(buf, nbits); - push_val(buf, true); // is_trained - push_vector( - buf, - std::vector( - codebook_d * total_codebook_size, 0.0f)); // codebooks - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max -} - -/// Helper: append a minimal ResidualQuantizer (AdditiveQuantizer + -/// train_type + max_beam_size). Uses Skip_codebook_tables to avoid -/// compute_codebook_tables on empty codebooks. -static void push_residual_quantizer( - std::vector& buf, - size_t d, - size_t M, - const std::vector& nbits) { - push_additive_quantizer(buf, d, M, nbits); - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 1); // max_beam_size -} - -/// Helper: append a minimal LocalSearchQuantizer (AdditiveQuantizer + -/// K + train_iters + encode_ils_iters + train_ils_iters + icm_iters + -/// p + lambd + chunk_size + random_seed + nperts + -/// update_codebooks_with_double). -static void push_local_search_quantizer( - std::vector& buf, - size_t d, - size_t M, - const std::vector& nbits) { - push_additive_quantizer(buf, d, M, nbits); - push_val(buf, 256); // K - push_val(buf, 25); // train_iters - push_val(buf, 8); // encode_ils_iters - push_val(buf, 8); // train_ils_iters - push_val(buf, 4); // icm_iters - push_val(buf, 0.5f); // p - push_val(buf, 0.0f); // lambd - push_val(buf, 0); // chunk_size - push_val(buf, 123); // random_seed - push_val(buf, 4); // nperts - push_val(buf, false); // update_codebooks_with_double -} - -// ----------------------------------------------------------------------- -// Test: IndexResidualQuantizer codes vector size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexResidualQuantizerCodesSizeMismatch) { - // "IxRq": fourcc + index_header + ResidualQuantizer + code_size + codes - std::vector buf; - push_fourcc(buf, "IxRq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - push_residual_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - // code_size = 1 (M=1, nbits=8 → 1 byte per code) - push_val(buf, 1); // code_size - // codes: should be ntotal * code_size = 2 * 1 = 2 bytes - // Provide wrong size (10 bytes) - push_vector(buf, std::vector(10, 0)); - - expect_read_throws_with(buf, "codes.size()"); -} - -// ----------------------------------------------------------------------- -// Test: IndexLocalSearchQuantizer codes vector size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexLocalSearchQuantizerCodesSizeMismatch) { - // "IxLS": fourcc + index_header + LocalSearchQuantizer + code_size + codes - std::vector buf; - push_fourcc(buf, "IxLS"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - push_local_search_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - // code_size = 1 (M=1, nbits=8 → 1 byte per code) - push_val(buf, 1); // code_size - // codes: should be ntotal * code_size = 2 * 1 = 2 bytes - // Provide wrong size (10 bytes) - push_vector(buf, std::vector(10, 0)); - - expect_read_throws_with(buf, "codes.size()"); -} - -// ----------------------------------------------------------------------- -// Test: IndexProductResidualQuantizer codes vector size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexProductResidualQuantizerCodesSizeMismatch) { - // "IxPR": fourcc + index_header + ProductResidualQuantizer + code_size - // + codes - // ProductResidualQuantizer = ProductAdditiveQuantizer(AdditiveQuantizer - // + nsplits) + nsplits * ResidualQuantizer - std::vector buf; - push_fourcc(buf, "IxPR"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // ProductAdditiveQuantizer: AdditiveQuantizer + nsplits - push_additive_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - push_val(buf, 1); // nsplits = 1 - // 1 nested ResidualQuantizer (sub-dimension = d / nsplits = 4) - push_residual_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - // code_size = 1 - push_val(buf, 1); // code_size - // codes: should be ntotal * code_size = 2 * 1 = 2 bytes - // Provide wrong size (10 bytes) - push_vector(buf, std::vector(10, 0)); - - expect_read_throws_with(buf, "codes.size()"); -} - -// ----------------------------------------------------------------------- -// Test: IndexProductLocalSearchQuantizer codes vector size mismatch. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexProductLocalSearchQuantizerCodesSizeMismatch) { - // "IxPL": fourcc + index_header + ProductLocalSearchQuantizer + code_size - // + codes - // ProductLocalSearchQuantizer = ProductAdditiveQuantizer(AdditiveQuantizer - // + nsplits) + nsplits * LocalSearchQuantizer - std::vector buf; - push_fourcc(buf, "IxPL"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // ProductAdditiveQuantizer: AdditiveQuantizer + nsplits - push_additive_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - push_val(buf, 1); // nsplits = 1 - // 1 nested LocalSearchQuantizer (sub-dimension = d / nsplits = 4) - push_local_search_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{8}); - // code_size = 1 - push_val(buf, 1); // code_size - // codes: should be ntotal * code_size = 2 * 1 = 2 bytes - // Provide wrong size (10 bytes) - push_vector(buf, std::vector(10, 0)); - - expect_read_throws_with(buf, "codes.size()"); -} - -// ----------------------------------------------------------------------- -// Graph index helpers -// ----------------------------------------------------------------------- - -/// Helper: append a minimal IndexFlatL2 ("IxF2") with the given d and ntotal. -/// Uses the WRITEXBVECTOR format (size_t num_floats prefix, then raw data). -static void push_minimal_flat( - std::vector& buf, - int d, - int64_t ntotal = 0) { - push_fourcc(buf, "IxF2"); - push_index_header(buf, d, ntotal); - size_t num_floats = (size_t)ntotal * (size_t)d; - push_val(buf, num_floats); - buf.resize(buf.size() + num_floats * sizeof(float), 0); -} - -/// Helper: append a minimal valid HNSW structure with the given number of -/// nodes. All nodes are at level 1 with zero neighbors, which passes -/// validate_HNSW. -static void push_minimal_hnsw(std::vector& buf, int ntotal) { - // assign_probas (empty) - push_vector(buf, {}); - // cum_nneighbor_per_level: {0, 0} — 0 cumulative neighbors at each level - push_vector(buf, {0, 0}); - // levels: one entry per node, all at level 1 (1-indexed in HNSW) - std::vector levels(ntotal, 1); - push_vector(buf, levels); - // offsets: ntotal + 1 entries, all 0 - std::vector offsets(ntotal + 1, 0); - push_vector(buf, offsets); - // neighbors (empty) - push_vector(buf, {}); - // entry_point - push_val(buf, ntotal > 0 ? 0 : -1); - // max_level - push_val(buf, 0); - // efConstruction - push_val(buf, 40); - // efSearch - push_val(buf, 16); - // upper_beam (deprecated, always 1) - push_val(buf, 1); -} - -/// Helper: append NNDescent fields. -static void push_nndescent( - std::vector& buf, - int ntotal, - int d, - int K, - bool has_built, - const std::vector& final_graph) { - push_val(buf, ntotal); - push_val(buf, d); - push_val(buf, K); - push_val(buf, 10); // S - push_val(buf, 10); // R - push_val(buf, 10); // L - push_val(buf, 1); // iter - push_val(buf, 10); // search_L - push_val(buf, 42); // random_seed - push_val(buf, has_built); - push_vector(buf, final_graph); -} - -// ----------------------------------------------------------------------- -// Test: NNDescent final_graph size mismatch (should be ntotal * K). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, NNDescentGraphSizeMismatch) { - std::vector buf; - push_fourcc(buf, "INNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // NNDescent: ntotal=2, K=3, has_built=true - // Expected graph size = 2*3 = 6, but provide 10 - push_nndescent( - buf, - /*ntotal=*/2, - /*d=*/4, - /*K=*/3, - /*has_built=*/true, - std::vector(10, 0)); - - expect_read_throws_with(buf, "NNDescent final_graph size"); -} - -// ----------------------------------------------------------------------- -// Test: NNDescent final_graph contains out-of-range neighbor ID. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, NNDescentGraphInvalidId) { - std::vector buf; - push_fourcc(buf, "INNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/2); - // NNDescent: ntotal=2, K=2, graph size = 4 - // ID 99 is out of range [-1, 2) - push_nndescent( - buf, - /*ntotal=*/2, - /*d=*/4, - /*K=*/2, - /*has_built=*/true, - {0, 1, 99, 0}); - - expect_read_throws_with(buf, "out of range"); -} - -// ----------------------------------------------------------------------- -// Test: HNSW levels.size() != index ntotal. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWLevelsSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/5); - // HNSW with 3 entries (mismatch with ntotal=5) - push_minimal_hnsw(buf, /*ntotal=*/3); - - expect_read_throws_with(buf, "HNSW levels size"); -} - -// ----------------------------------------------------------------------- -// Test: HNSW storage ntotal != index ntotal. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWStorageNtotalMismatch) { - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/3); - // Valid HNSW with 3 entries (matches header) - push_minimal_hnsw(buf, /*ntotal=*/3); - // Storage with ntotal=99 (mismatch) - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/99); - - expect_read_throws_with(buf, "HNSW storage ntotal"); -} - -// ----------------------------------------------------------------------- -// Helper: append an HNSW structure with explicit neighbor data. -// All nodes at level 1. cum_nneighbor_per_level = {0, neighbors_per_node}. -// Callers supply the full neighbors vector (ntotal * neighbors_per_node -// entries, using -1 for empty slots). -// ----------------------------------------------------------------------- -static void push_hnsw_with_neighbors( - std::vector& buf, - int ntotal, - int neighbors_per_node, - const std::vector& neighbors, - int32_t entry_point = 0) { - // assign_probas (empty) - push_vector(buf, {}); - // cum_nneighbor_per_level: {0, neighbors_per_node} - push_vector(buf, {0, neighbors_per_node}); - // levels: one entry per node, all at level 1 - std::vector levels(ntotal, 1); - push_vector(buf, levels); - // offsets: ntotal + 1 entries, each node occupies neighbors_per_node slots - std::vector offsets(ntotal + 1); - for (int i = 0; i <= ntotal; i++) { - offsets[i] = (size_t)i * neighbors_per_node; - } - push_vector(buf, offsets); - // neighbors - push_vector(buf, neighbors); - // entry_point - push_val(buf, entry_point); - // max_level - push_val(buf, 0); - // efConstruction - push_val(buf, 40); - // efSearch - push_val(buf, 16); - // upper_beam (deprecated) - push_val(buf, 1); -} - -// ----------------------------------------------------------------------- -// Test: HNSW neighbors contain a negative ID (not -1). -// validate_HNSW must reject this at deserialization time. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWNeighborNegativeId) { - int ntotal = 3, npn = 2; - // Node 0 neighbors: {1, -5} — -5 is invalid (only -1 is allowed) - // Node 1 neighbors: {0, -1} - // Node 2 neighbors: {0, -1} - std::vector neighbors = {1, -5, 0, -1, 0, -1}; - - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/ntotal); - push_hnsw_with_neighbors(buf, ntotal, npn, neighbors); - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/ntotal); - - expect_read_throws_with(buf, "HNSW neighbors"); -} - -// ----------------------------------------------------------------------- -// Test: HNSW neighbors contain an ID >= ntotal (out of range). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWNeighborIdTooLarge) { - int ntotal = 3, npn = 2; - // Node 0 neighbors: {1, 99} — 99 >= ntotal - std::vector neighbors = {1, 99, 0, -1, 0, -1}; - - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/ntotal); - push_hnsw_with_neighbors(buf, ntotal, npn, neighbors); - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/ntotal); - - expect_read_throws_with(buf, "HNSW neighbors"); -} - -// ----------------------------------------------------------------------- -// Test: HNSW entry_point is out of range (>= ntotal). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWEntryPointOutOfRange) { - int ntotal = 3, npn = 2; - std::vector neighbors = {1, -1, 0, -1, 0, -1}; - - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/ntotal); - push_hnsw_with_neighbors(buf, ntotal, npn, neighbors, /*entry_point=*/99); - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/ntotal); - - expect_read_throws_with(buf, "HNSW entry_point"); -} - -// ----------------------------------------------------------------------- -// Test: HNSW with valid neighbor data deserializes and searches correctly. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWValidNeighborsSearchWorks) { - int ntotal = 4, npn = 2; - // Simple valid graph: each node links to 2 others - std::vector neighbors = {1, 2, 0, 3, 0, 3, 1, 2}; - - std::vector buf; - push_fourcc(buf, "IHNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/ntotal); - push_hnsw_with_neighbors(buf, ntotal, npn, neighbors); - - // Flat storage with 4 zero vectors (valid, just not useful for recall) - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/ntotal); - - VectorIOReader reader; - reader.data = buf; - std::unique_ptr idx; - ASSERT_NO_THROW(idx = read_index_up(&reader)); - ASSERT_NE(idx, nullptr); - - // Search should succeed without crashing - std::vector xq(4, 0.0f); - std::vector distances(1); - std::vector labels(1); - EXPECT_NO_THROW( - idx->search(1, xq.data(), 1, distances.data(), labels.data())); - EXPECT_GE(labels[0], 0); - EXPECT_LT(labels[0], ntotal); -} - -// ----------------------------------------------------------------------- -// Test: IndexHNSW2Level with wrong storage type is rejected. -// Protects against corrupt serialized data where storage is not -// Index2Layer or IndexIVFPQ, causing null-deref from failed dynamic_cast. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSW2LevelWrongStorageType) { - // Build an IHN2 with IndexFlat storage (wrong type — must be - // Index2Layer or IndexIVFPQ). - std::vector buf; - push_fourcc(buf, "IHN2"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_minimal_hnsw(buf, /*ntotal=*/0); - // IndexFlat storage — wrong type for HNSW2Level - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/0); - - expect_read_throws_with(buf, "Index2Layer or IndexIVFPQ"); -} - -// ----------------------------------------------------------------------- -// Test: Index2Layer deserialization sets own_fields=true so the -// sub-quantizer is freed when the deserialized index is destroyed. -// ----------------------------------------------------------------------- - -struct CountedDestructorIndex : IndexFlatL2 { - static int destructor_count; - using IndexFlatL2::IndexFlatL2; - ~CountedDestructorIndex() override { - destructor_count++; - } -}; -int CountedDestructorIndex::destructor_count = 0; - -TEST(ReadIndexDeserialize, Index2LayerQuantizerOwnership) { - int d = 4, nb = 512, nlist = 2; - - // Build and serialize a valid Index2Layer. - auto original_q = std::make_unique(d); - Index2Layer original(original_q.release(), nlist, 2); - original.q1.own_fields = true; - std::vector xb(d * nb); - { - std::mt19937 rng(42); - std::uniform_real_distribution dist; - for (auto& v : xb) { - v = dist(rng); - } - } - original.train(nb, xb.data()); - original.add(nb, xb.data()); - - VectorIOWriter writer; - write_index(&original, &writer); - - // Deserialize and swap in a CountedDestructorIndex as the quantizer. - // When the deserialized index is destroyed, own_fields controls - // whether the quantizer is freed. The destructor counter verifies - // this independently of any flag check. - CountedDestructorIndex::destructor_count = 0; - { - VectorIOReader reader; - reader.data = writer.data; - auto idx = std::unique_ptr(read_index(&reader)); - auto* idx2l = dynamic_cast(idx.get()); - ASSERT_NE(idx2l, nullptr); - ASSERT_NE(idx2l->q1.quantizer, nullptr); - - // Replace the deserialized quantizer with a CountedDestructorIndex. - delete idx2l->q1.quantizer; - idx2l->q1.quantizer = new CountedDestructorIndex(d); - EXPECT_EQ(CountedDestructorIndex::destructor_count, 0); - // idx goes out of scope here. If own_fields is true, - // ~Level1Quantizer deletes the CountedDestructorIndex. - } - EXPECT_EQ(CountedDestructorIndex::destructor_count, 1); -} - -// ----------------------------------------------------------------------- -// Test: Index2Layer with a null quantizer (serialized as "null" fourcc) -// still sets own_fields=true. Deleting a nullptr is safe, so this -// verifies the fix doesn't assume the quantizer is non-null. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, Index2LayerNullQuantizerOwnership) { - std::vector buf; - push_fourcc(buf, "Ix2L"); - push_index_header(buf, 4, 0); - // Null sub-quantizer. - push_fourcc(buf, "null"); - push_val(buf, size_t(1)); // nlist - // Truncate here — the next READ1 will fail and trigger cleanup. - // With own_fields=true and quantizer=nullptr, the destructor - // must not crash (delete nullptr is well-defined). - EXPECT_THROW( - { - VectorIOReader reader; - reader.data = buf; - read_index(&reader); - }, - FaissException); -} - -// ----------------------------------------------------------------------- -// Test: IndexHNSW2Level with null storage is rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSW2LevelNullStorage) { - std::vector buf; - push_fourcc(buf, "IHN2"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_minimal_hnsw(buf, /*ntotal=*/0); - // Null storage - push_fourcc(buf, "null"); - - expect_read_throws_with(buf, "non-null storage"); -} - -// ----------------------------------------------------------------------- -// Test: NSG ntotal != index ntotal. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, NSGNtotalMismatch) { - std::vector buf; - push_fourcc(buf, "INSf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/5); - push_val(buf, 0); // GK - push_val(buf, 0); // build_type (char, not int) - push_val(buf, 10); // nndescent_S - push_val(buf, 10); // nndescent_R - push_val(buf, 10); // nndescent_L - push_val(buf, 1); // nndescent_iter - // NSG: ntotal=3 (mismatch with index ntotal=5) - push_val(buf, 3); // ntotal - push_val(buf, 2); // R - push_val(buf, 10); // L - push_val(buf, 10); // C - push_val(buf, 10); // search_L - push_val(buf, 0); // enterpoint - push_val(buf, true); // is_built - // Graph: 3 nodes, R=2, all empty (EMPTY_ID terminates each) - for (int i = 0; i < 3; i++) { - push_val(buf, -1); // EMPTY_ID - } - - expect_read_throws_with(buf, "NSG ntotal"); -} - -// ----------------------------------------------------------------------- -// Test: NNDescent ntotal != index ntotal. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, NNDescentNtotalMismatch) { - std::vector buf; - push_fourcc(buf, "INNf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/5); - // NNDescent: ntotal=3, has_built=true (mismatch with index ntotal=5) - // Graph is internally valid: ntotal=3, K=2, 6 entries all in range - push_nndescent( - buf, - /*ntotal=*/3, - /*d=*/4, - /*K=*/2, - /*has_built=*/true, - {0, 1, 0, 2, 1, 2}); - - expect_read_throws_with(buf, "NNDescent ntotal"); -} - -// ----------------------------------------------------------------------- -// Test: IndexHNSWCagra search with base_level_only on empty index. -// Without the fix, this would access uninitialized graph nodes. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, HNSWCagraEmptyIndexSearch) { - IndexHNSWCagra idx(4, 16); - idx.base_level_only = true; - - std::vector xq(4, 1.0f); - std::vector distances(1); - std::vector labels(1); - - EXPECT_NO_THROW( - idx.search(1, xq.data(), 1, distances.data(), labels.data())); - EXPECT_EQ(labels[0], -1); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVF search with null invlists (e.g. loaded with -// IO_FLAG_SKIP_IVF_DATA) throws instead of crashing. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexIVFNullInvlistsSearch) { - IndexFlatL2 quantizer(4); - IndexIVFFlat idx(&quantizer, 4, 10); - idx.own_fields = false; - // Simulate IO_FLAG_SKIP_IVF_DATA by deleting invlists - delete idx.invlists; - idx.invlists = nullptr; - - std::vector xq(4, 1.0f); - std::vector distances(1); - std::vector labels(1); - - EXPECT_THROW( - idx.search(1, xq.data(), 1, distances.data(), labels.data()), - FaissException); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVF add_with_ids with null invlists throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexIVFNullInvlistsAdd) { - IndexFlatL2 quantizer(4); - IndexIVFFlat idx(&quantizer, 4, 10); - idx.own_fields = false; - idx.is_trained = true; - delete idx.invlists; - idx.invlists = nullptr; - - std::vector xb(4, 1.0f); - - EXPECT_THROW(idx.add(1, xb.data()), FaissException); -} - -// ----------------------------------------------------------------------- -// IVF quantizer ntotal / nlist deserialization acceptance tests. -// The quantizer may legitimately have ntotal != nlist (e.g., sharded -// indexes, custom inverted list management, untrained quantizers). -// ----------------------------------------------------------------------- - -// Surplus quantizer centroids: ntotal > nlist. Produced by -// shard_ivf_index_centroids(), which distributes all of the original -// quantizer's centroids across shards without adjusting nlist. -// The search-time key < nlist bounds check prevents OOB access if -// the quantizer returns out-of-range keys. -TEST(ReadIndexDeserialize, IVFQuantizerSurplus) { - std::vector buf; - push_fourcc(buf, "IwFl"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 2); // nlist = 2 - push_val(buf, 1); // nprobe - // Quantizer with ntotal=5 (more centroids than nlist) - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/5); - push_empty_direct_map(buf); - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// Trained quantizer: ntotal == nlist (normal trained IVF). -TEST(ReadIndexDeserialize, IVFQuantizerTrained) { - std::vector buf; - push_fourcc(buf, "IwFl"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 2); // nlist = 2 - push_val(buf, 1); // nprobe - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/2); - push_empty_direct_map(buf); - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// Sharded quantizer: 0 < ntotal < nlist. Produced by -// shard_ivf_index_centroids(), where each shard's quantizer holds a -// subset of the full index's centroids. -TEST(ReadIndexDeserialize, IVFQuantizerSubset) { - std::vector buf; - push_fourcc(buf, "IwFl"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 10); // nlist = 10 - push_val(buf, 1); // nprobe - // Quantizer with ntotal=3 (subset of centroids, as in sharding) - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/3); - push_empty_direct_map(buf); - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// Untrained quantizer: ntotal == 0 (custom inverted list management). -TEST(ReadIndexDeserialize, IVFQuantizerUntrained) { - std::vector buf; - push_fourcc(buf, "IwFl"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 10); // nlist = 10 - push_val(buf, 1); // nprobe - push_minimal_flat(buf, /*d=*/4, /*ntotal=*/0); - push_empty_direct_map(buf); - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVFScalarQuantizer with empty trained vector and -// is_trained=false deserializes successfully (legitimate untrained index), -// but searching it throws because IndexIVF::search checks is_trained. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFScalarQuantizerUntrainedSearchRejected) { - std::vector buf; - push_fourcc(buf, "IwSq"); - // IVF header: index_header + nlist + nprobe + quantizer + direct_map - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/false); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_minimal_flat(buf, /*d=*/4); - push_empty_direct_map(buf); - // ScalarQuantizer fields: - push_val(buf, 0); // qtype = QT_8bit - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 4); // code_size - push_vector(buf, {}); // trained (empty — untrained) - // IwSq additional fields: - push_val(buf, 4); // code_size - push_val(buf, false); // by_residual - push_null_invlists(buf); - - // Deserialization should succeed — untrained indexes are legitimate - VectorIOReader reader; - reader.data = buf; - auto idx = read_index_up(&reader); - ASSERT_NE(idx, nullptr); - EXPECT_FALSE(idx->is_trained); - - // search should throw — is_trained check in IndexIVF::search - std::vector xq(4, 0.0f); - std::vector distances(1); - std::vector labels(1); - EXPECT_THROW( - idx->search(1, xq.data(), 1, distances.data(), labels.data()), - FaissException); - - // range_search should throw — is_trained check in IndexIVF::range_search - RangeSearchResult rsr(1); - EXPECT_THROW(idx->range_search(1, xq.data(), 1.0f, &rsr), FaissException); - - // search_preassigned should throw directly - auto* ivf = dynamic_cast(idx.get()); - ASSERT_NE(ivf, nullptr); - idx_t key = 0; - float coarse_dis = 0.0f; - EXPECT_THROW( - ivf->search_preassigned( - 1, - xq.data(), - 1, - &key, - &coarse_dis, - distances.data(), - labels.data(), - false, - nullptr, - nullptr), - FaissException); - - // range_search_preassigned should throw directly - RangeSearchResult rsr2(1); - EXPECT_THROW( - ivf->range_search_preassigned( - 1, - xq.data(), - 1.0f, - &key, - &coarse_dis, - &rsr2, - false, - nullptr, - nullptr), - FaissException); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVFScalarQuantizer with is_trained=true but empty trained -// is rejected at deserialization time — corrupt data. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFScalarQuantizerTrainedEmptyTrained) { - std::vector buf; - push_fourcc(buf, "IwSq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/true); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_minimal_flat(buf, /*d=*/4); - push_empty_direct_map(buf); - // ScalarQuantizer fields: - push_val(buf, 0); // qtype = QT_8bit - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 4); // code_size - push_vector(buf, {}); // trained (empty — but is_trained=true!) - - expect_read_throws_with(buf, "ScalarQuantizer trained size"); -} - -// ----------------------------------------------------------------------- -// Test: initialize_IVFPQ_precomputed_table rejects a null quantizer. -// Protects against null-deref from corrupt serialized data where the -// quantizer sub-index is absent (fourcc "null"). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFPQNullQuantizerPrecomputeTableRejected) { - ProductQuantizer pq(4, 1, 8); - AlignedTable precomputed_table; - int use_precomputed_table = 0; - EXPECT_THROW( - initialize_IVFPQ_precomputed_table( - use_precomputed_table, - /*quantizer=*/nullptr, - pq, - precomputed_table, - /*by_residual=*/true, - /*verbose=*/false), - faiss::FaissException); -} - -TEST(ReadIndexDeserialize, IVFNullQuantizerSearchRejected) { - IndexIVFFlat ivf; - ivf.quantizer = nullptr; - ivf.is_trained = true; - std::vector x(4); - std::vector distances(1); - std::vector labels(1); - EXPECT_THROW( - ivf.search(1, x.data(), 1, distances.data(), labels.data()), - faiss::FaissException); -} - -TEST(ReadIndexDeserialize, IVFNullQuantizerRangeSearchRejected) { - IndexIVFFlat ivf; - ivf.quantizer = nullptr; - ivf.is_trained = true; - std::vector x(4); - RangeSearchResult result(1); - EXPECT_THROW( - ivf.range_search(1, x.data(), 1.0, &result), faiss::FaissException); -} - -TEST(ReadIndexDeserialize, IVFNullQuantizerAddRejected) { - IndexIVFFlat ivf; - ivf.quantizer = nullptr; - std::vector x(4); - EXPECT_THROW(ivf.add(1, x.data()), faiss::FaissException); -} - -TEST(ReadIndexDeserialize, IVFNullQuantizerTrainRejected) { - IndexIVFFlat ivf; - ivf.quantizer = nullptr; - std::vector x(4); - EXPECT_THROW(ivf.train(1, x.data()), faiss::FaissException); -} - -// ----------------------------------------------------------------------- -// VectorTransform deserialization validation tests -// ----------------------------------------------------------------------- - -// Test: NormalizationTransform with d_in != d_out is rejected. -// Protects against corrupt serialized data where dimension mismatch -// causes memcpy to overflow the output buffer in apply_noalloc. -TEST(ReadIndexDeserialize, NormalizationTransformDinDoutMismatch) { - // VNrm format: fourcc("VNrm") + norm(float) + d_in(int) + d_out(int) + - // is_trained(bool) - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); // norm (L2) - push_val(buf, 16); // d_in - push_val(buf, 8); // d_out (mismatch!) - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "d_in == d_out"); -} - -// Test: NormalizationTransform with d_in == d_out is accepted. -TEST(ReadIndexDeserialize, NormalizationTransformDinDoutMatch) { - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); // norm (L2) - push_val(buf, 16); // d_in - push_val(buf, 16); // d_out (match) - push_val(buf, true); // is_trained - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_VectorTransform_up(&reader)); -} - -// Test: CenteringTransform with d_in != d_out is rejected. -TEST(ReadIndexDeserialize, CenteringTransformDinDoutMismatch) { - // VCnt format: fourcc("VCnt") + mean(vector) + d_in(int) + - // d_out(int) + is_trained(bool) - std::vector buf; - push_fourcc(buf, "VCnt"); - push_vector(buf, std::vector(16, 0.0f)); // mean - push_val(buf, 16); // d_in - push_val(buf, 8); // d_out (mismatch!) - push_val(buf, true); - - expect_vt_read_throws_with(buf, "d_in == d_out"); -} - -// Test: IndexPreTransform with mismatched chain dimensions is rejected. -TEST(ReadIndexDeserialize, PreTransformChainDimensionMismatch) { - // Build an IxPT with a NormalizationTransform (d_in=d_out=4) followed - // by a sub-index with d=8. The chain's d_out (4) != sub-index d (8). - std::vector buf; - push_fourcc(buf, "IxPT"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 1); // nt = 1 transform - // NormalizationTransform with d_in=d_out=4 - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); - push_val(buf, 4); // d_in - push_val(buf, 4); // d_out - push_val(buf, true); - // Sub-index: IndexFlat with d=8 (mismatch with chain d_out=4) - push_minimal_flat(buf, /*d=*/8); - - expect_read_throws_with(buf, "d_out=4"); -} - -// Test: IndexPreTransform with an *empty* chain must still agree with its -// sub-index on d. With no transform, reconstruct() hands the caller's -// buffer -- sized from the outer d -- straight to the sub-index, so a -// larger sub-index d is a heap overflow (T287094917). -TEST(ReadIndexDeserialize, PreTransformEmptyChainDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "IxPT"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 0); // nt = 0, empty chain - push_minimal_flat(buf, /*d=*/8); - - expect_read_throws_with(buf, "IndexPreTransform empty chain"); -} - -// A well-formed empty-chain IxPT still deserializes. -TEST(ReadIndexDeserialize, PreTransformEmptyChainMatchingDimensionAccepted) { - std::vector buf; - push_fourcc(buf, "IxPT"); - push_index_header(buf, /*d=*/8, /*ntotal=*/0); - push_val(buf, 0); // nt = 0, empty chain - push_minimal_flat(buf, /*d=*/8); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW({ - auto idx = read_index_up(&reader); - EXPECT_NE(idx, nullptr); - }); -} - -TEST(ReadIndexDeserialize, HadamardRotationInvalidDout) { - // HRot format: fourcc("HRot") + seed(int) + d_in(int) + d_out(int) + - // is_trained(bool) - std::vector buf; - push_fourcc(buf, "HRot"); - push_val(buf, 42); // seed - push_val(buf, 16); // d_in - push_val(buf, 1 << 21); // d_out (not power-of-2 match for d_in) - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "d_out must be the smallest power of 2"); -} - -TEST(ReadIndexDeserialize, HadamardRotationDinZero) { - std::vector buf; - push_fourcc(buf, "HRot"); - push_val(buf, 42); // seed - push_val(buf, 0); // d_in = 0 (invalid) - push_val(buf, 1); // d_out - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "HadamardRotation d_in="); -} - -TEST(ReadIndexDeserialize, HadamardRotationDoutZero) { - std::vector buf; - push_fourcc(buf, "HRot"); - push_val(buf, 42); // seed - push_val(buf, 16); // d_in - push_val(buf, 0); // d_out = 0 (invalid) - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "HadamardRotation d_out="); -} - -TEST(ReadIndexDeserialize, RemapDimensionsTransformMapTooSmall) { - // RmDT format: fourcc("RmDT") + WRITEVECTOR(map) + d_in(int) + - // d_out(int) + is_trained(bool) - std::vector buf; - push_fourcc(buf, "RmDT"); - push_vector(buf, {0, 1}); // map with 2 entries - push_val(buf, 4); // d_in - push_val(buf, 10); // d_out = 10 > map.size()=2 - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "RemapDimensionsTransform map size"); -} - -TEST(ReadIndexDeserialize, CenteringTransformMeanTooSmall) { - // VCnt format: fourcc("VCnt") + WRITEVECTOR(mean) + d_in(int) + - // d_out(int) + is_trained(bool) - std::vector buf; - push_fourcc(buf, "VCnt"); - push_vector(buf, {1.0f, 2.0f}); // mean with 2 entries - push_val(buf, 8); // d_in = 8 > mean.size()=2 - push_val(buf, 8); // d_out - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "CenteringTransform mean size"); -} - -TEST(ReadIndexDeserialize, ITQTransformMeanTooSmall) { - // Viqt format: fourcc("Viqt") + WRITEVECTOR(mean) + do_pca(int) + - // sub_vt(ITQMatrix) + sub_vt(LinearTransform) + - // d_in(int) + d_out(int) + is_trained(bool) - std::vector buf; - push_fourcc(buf, "Viqt"); - push_vector(buf, {1.0f}); // mean with 1 entry - push_val(buf, false); // do_pca - - // Sub-VT 1: ITQMatrix ("Viqm") - push_fourcc(buf, "Viqm"); - push_val(buf, 10); // max_iter - push_val(buf, 42); // seed - push_val(buf, false); // have_bias - push_vector(buf, {}); // A - push_vector(buf, {}); // b - push_val(buf, 0); // d_in - push_val(buf, 0); // d_out - push_val(buf, true); // is_trained - - // Sub-VT 2: LinearTransform ("LTra") - push_fourcc(buf, "LTra"); - push_val(buf, false); // have_bias - push_vector(buf, {}); // A - push_vector(buf, {}); // b - push_val(buf, 0); // d_in - push_val(buf, 0); // d_out - push_val(buf, true); // is_trained - - // Outer Viqt footer - push_val(buf, 4); // d_in = 4 > mean.size()=1 - push_val(buf, 4); // d_out - push_val(buf, true); // is_trained - - expect_vt_read_throws_with(buf, "ITQTransform mean size"); -} - -// ----------------------------------------------------------------------- -// RaBitQ qb deserialization validation tests -// ----------------------------------------------------------------------- - -/// Helper: push a minimal RaBitQuantizer (single-bit format, multi_bit=false). -static void push_rabitq(std::vector& buf, size_t d) { - push_val(buf, d); // d - push_val(buf, 1); // code_size - push_val(buf, 1); // metric_type (L2) -} - -/// Helper: push a minimal RaBitQuantizer (multi-bit format, multi_bit=true). -static void push_rabitq_multibit(std::vector& buf, size_t d) { - push_val(buf, d); // d - push_val(buf, 1); // code_size - push_val(buf, 1); // metric_type (L2) - push_val(buf, 1); // nb_bits -} - -/// Helper: push an IVF header (index_header + nlist + nprobe + flat quantizer -/// + empty direct_map). -static void push_ivf_header(std::vector& buf, int d) { - push_index_header(buf, d, /*ntotal=*/0); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_minimal_flat(buf, d); - push_empty_direct_map(buf); -} - -// ----------------------------------------------------------------------- -// Test: Inverted list with oversized entry exceeding deserialization byte -// limit is rejected. Protects against corrupt data causing OOM via -// unchecked vector::resize in read_InvertedLists_up. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, InvertedListOversizedEntry) { - const size_t old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1024); // 1 KB limit - - std::vector buf; - push_fourcc(buf, "IwFl"); - push_ivf_header(buf, /*d=*/4); - // "ilar" inverted lists with 1 list, code_size=16 - push_fourcc(buf, "ilar"); - push_val(buf, 1); // nlist = 1 - push_val(buf, 16); // code_size = 16 - // "full" list type with 1 size entry - push_fourcc(buf, "full"); - // sizes vector: 1 entry with absurdly large value - push_val(buf, 1); // vector length - push_val(buf, (size_t)1 << 40); // sizes[0] = 1 TB - - expect_read_throws_with(buf, "deserialization byte limit"); - - set_deserialization_vector_byte_limit(old_limit); -} - -TEST(ReadIndexDeserialize, OnDiskInvertedListsShortListsVectorRejected) { - std::vector buf; - push_fourcc(buf, "IwFl"); - push_ivf_header(buf, /*d=*/4); - push_fourcc(buf, "ilod"); - push_val(buf, 1); // nlist = 1 - push_val(buf, 16); // code_size = 16 - push_val(buf, 0); // lists: empty, inconsistent with nlist = 1 - - expect_read_throws_with(buf, "read 0 lists for nlist 1"); -} - -// -- Ixrq (IndexRaBitQ, single-bit) -- -// qb=0 is valid for Ixrq: disables query quantization, uses raw fp32 values. -// See IndexRaBitQ.h comment on qb and RaBitQDistanceComputerNotQ. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Ixrq) { - std::vector buf; - push_fourcc(buf, "Ixrq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq(buf, 4); - push_vector(buf, {}); // codes - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroAccepted_Ixrq) { - std::vector buf; - push_fourcc(buf, "Ixrq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq(buf, 4); - push_vector(buf, {}); // codes - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 0); // qb = 0 (valid for Ixrq) - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// -- Ixrr (IndexRaBitQ, multi-bit) -- -// qb=0 is valid for Ixrr: disables query quantization, uses raw fp32 values. -// See IndexRaBitQ.h comment on qb and RaBitQDistanceComputerNotQ. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Ixrr) { - std::vector buf; - push_fourcc(buf, "Ixrr"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq_multibit(buf, 4); - push_vector(buf, {}); // codes - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroAccepted_Ixrr) { - std::vector buf; - push_fourcc(buf, "Ixrr"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq_multibit(buf, 4); - push_vector(buf, {}); // codes - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 0); // qb = 0 (valid for Ixrr) - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// -- Irfn (IndexRaBitQFastScan, new format) -- -// qb=0 is not supported: FastScan requires quantized queries for SIMD. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Irfn) { - std::vector buf; - push_fourcc(buf, "Irfn"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq_multibit(buf, 4); - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroRejected_Irfn) { - std::vector buf; - push_fourcc(buf, "Irfn"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_rabitq_multibit(buf, 4); - push_vector(buf, {0, 0, 0, 0}); // center - push_val(buf, 0); // qb = 0 (invalid for FastScan) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -// -- Iwrq (IndexIVFRaBitQ, single-bit) -- -// qb=0 is valid for Iwrq: disables query quantization, uses raw fp32 values. -// See IndexIVFRaBitQ.h comment on qb and RaBitQDistanceComputerNotQ. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Iwrq) { - std::vector buf; - push_fourcc(buf, "Iwrq"); - push_ivf_header(buf, /*d=*/4); - push_rabitq(buf, 4); - push_val(buf, 1); // code_size - push_val(buf, false); // by_residual - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroAccepted_Iwrq) { - std::vector buf; - push_fourcc(buf, "Iwrq"); - push_ivf_header(buf, /*d=*/4); - push_rabitq(buf, 4); - push_val(buf, 1); // code_size - push_val(buf, false); // by_residual - push_val(buf, 0); // qb = 0 (valid for Iwrq) - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// -- Iwrr (IndexIVFRaBitQ, multi-bit) -- -// qb=0 is valid for Iwrr: disables query quantization, uses raw fp32 values. -// See IndexIVFRaBitQ.h comment on qb and RaBitQDistanceComputerNotQ. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Iwrr) { - std::vector buf; - push_fourcc(buf, "Iwrr"); - push_ivf_header(buf, /*d=*/4); - push_rabitq_multibit(buf, 4); - push_val(buf, 1); // code_size - push_val(buf, false); // by_residual - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroAccepted_Iwrr) { - std::vector buf; - push_fourcc(buf, "Iwrr"); - push_ivf_header(buf, /*d=*/4); - push_rabitq_multibit(buf, 4); - push_val(buf, 1); // code_size - push_val(buf, false); // by_residual - push_val(buf, 0); // qb = 0 (valid for Iwrr) - push_null_invlists(buf); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// -- Iwrn (IndexIVFRaBitQFastScan, new format) -- -// qb=0 is not supported: IVF FastScan requires quantized queries. - -TEST(ReadIndexDeserialize, RaBitQQbTooLarge_Iwrn) { - std::vector buf; - push_fourcc(buf, "Iwrn"); - push_ivf_header(buf, /*d=*/4); - push_rabitq_multibit(buf, 4); - push_val(buf, false); // by_residual - push_val(buf, 1); // code_size - push_val(buf, 32); // bbs - push_val(buf, 0); // qbs2 - push_val(buf, 1); // M2 - push_val(buf, 0); // implem - push_val(buf, 9); // qb = 9 (> 8, invalid) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -TEST(ReadIndexDeserialize, RaBitQQbZeroRejected_Iwrn) { - std::vector buf; - push_fourcc(buf, "Iwrn"); - push_ivf_header(buf, /*d=*/4); - push_rabitq_multibit(buf, 4); - push_val(buf, false); // by_residual - push_val(buf, 1); // code_size - push_val(buf, 32); // bbs - push_val(buf, 0); // qbs2 - push_val(buf, 1); // M2 - push_val(buf, 0); // implem - push_val(buf, 0); // qb = 0 (invalid for IVF FastScan) - - expect_read_throws_with(buf, "RaBitQ qb="); -} - -// ----------------------------------------------------------------------- -// Binary index deserialization validation tests -// ----------------------------------------------------------------------- - -TEST(ReadIndexDeserialize, BinaryHeaderDimensionNotMultipleOf8) { - std::vector buf; - push_fourcc(buf, "IBxF"); - push_val(buf, 17); // d = 17 (not multiple of 8) - push_val(buf, 2); // code_size - push_val(buf, 0); // ntotal - push_val(buf, true); // is_trained - push_val(buf, 1); // metric_type - - expect_binary_read_throws_with(buf, "multiple of 8"); -} - -TEST(ReadIndexDeserialize, BinaryHeaderCodeSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IBxF"); - push_val(buf, 16); // d = 16 - push_val(buf, 5); // code_size = 5 (should be 2) - push_val(buf, 0); // ntotal - push_val(buf, true); // is_trained - push_val(buf, 1); // metric_type - - expect_binary_read_throws_with(buf, "code_size"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWLevelsSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IBHf"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/5); - push_minimal_hnsw(buf, /*ntotal=*/3); // 3 != 5 - - expect_binary_read_throws_with(buf, "HNSW levels size"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWNeighborNegativeId) { - int ntotal = 3, npn = 2; - std::vector neighbors = {1, -5, 0, -1, 0, -1}; - - std::vector buf; - push_fourcc(buf, "IBHf"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal); - push_hnsw_with_neighbors(buf, ntotal, npn, neighbors); - - expect_binary_read_throws_with(buf, "HNSW neighbors"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWStorageNtotalMismatch) { - std::vector buf; - push_fourcc(buf, "IBHf"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/3); - push_minimal_hnsw(buf, /*ntotal=*/3); - push_minimal_binary_flat(buf, /*d=*/16); // ntotal=0 != 3 - - expect_binary_read_throws_with(buf, "storage ntotal"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWStorageNotFlat) { - std::vector buf; - push_fourcc(buf, "IBHf"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_minimal_hnsw(buf, /*ntotal=*/0); - // Nest an IBwF (IVF) instead of IBxF (flat) - push_fourcc(buf, "IBwF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_minimal_binary_flat(buf, /*d=*/16); // quantizer - push_empty_direct_map(buf); - push_null_invlists(buf); - - expect_binary_read_throws_with(buf, "IndexBinaryFlat storage"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWCagraLevelsSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IBHc"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/5); - push_val(buf, true); // keep_max_size_level0 - push_val(buf, false); // base_level_only - push_val(buf, 10); // num_base_level_search_entrypoints - push_minimal_hnsw(buf, /*ntotal=*/3); // 3 != 5 - - expect_binary_read_throws_with(buf, "HNSW levels size"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWCagraStorageNotFlat) { - std::vector buf; - push_fourcc(buf, "IBHc"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, true); // keep_max_size_level0 - push_val(buf, false); // base_level_only - push_val(buf, 10); // num_base_level_search_entrypoints - push_minimal_hnsw(buf, /*ntotal=*/0); - // Nest an IBwF (IVF) instead of IBxF (flat) - push_fourcc(buf, "IBwF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_minimal_binary_flat(buf, /*d=*/16); // quantizer - push_empty_direct_map(buf); - push_null_invlists(buf); - - expect_binary_read_throws_with(buf, "IndexBinaryFlat storage"); -} - -TEST(ReadIndexDeserialize, BinaryHNSWCagraStorageNtotalMismatch) { - std::vector buf; - push_fourcc(buf, "IBHc"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/3); - push_val(buf, true); // keep_max_size_level0 - push_val(buf, false); // base_level_only - push_val(buf, 10); // num_base_level_search_entrypoints - push_minimal_hnsw(buf, /*ntotal=*/3); - push_minimal_binary_flat(buf, /*d=*/16); // ntotal=0 != 3 - - expect_binary_read_throws_with(buf, "storage ntotal"); -} - -TEST(ReadIndexDeserialize, BinaryHashInvlistsVecsSizeMismatch) { - // IBHh: fourcc + binary_header + b + nflip + hash_invlists - std::vector buf; - push_fourcc(buf, "IBHh"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_val(buf, 4); // b - push_val(buf, 0); // nflip - - // hash invlists with 1 entry - push_val(buf, size_t(1)); // sz = 1 - push_val(buf, 8); // il_nbit = 8 - - // Bitstring: 1 entry needs (b + il_nbit) = 12 bits -> 2 bytes - std::vector bitbuf(2, 0); - BitstringWriter wr(bitbuf.data(), bitbuf.size()); - wr.write(0, 4); // hash = 0 - wr.write(1, 8); // ilsz = 1 - push_vector(buf, bitbuf); - - // ids: 1 entry - push_vector(buf, {0}); - // vecs: wrong size (3 bytes instead of code_size=2) - push_vector(buf, {0, 0, 0}); - - expect_binary_read_throws_with(buf, "binary hash invlists: vecs size"); -} - -TEST(ReadIndexDeserialize, BinaryMultiHashMapIdOutOfRange) { - // IBHm with ntotal=1, one map containing id=1 (>= ntotal). - const int b = 4; - const int id_bits = 1; - const size_t ntotal = 1; - const size_t sz = 1; - // bits: (b + id_bits) * sz + 1 * id_bits = 6 bits -> 1 byte - const size_t nbit = (b + id_bits) * sz + 1 * id_bits; - const size_t bitbuf_size = (nbit + 7) / 8; - - std::vector bitbuf(bitbuf_size, 0); - BitstringWriter wr2(bitbuf.data(), bitbuf.size()); - wr2.write(0, b); // hash = 0 - wr2.write(1, id_bits); // ilsz = 1 - wr2.write(1, id_bits); // id = 1 (>= ntotal=1, invalid) - - std::vector buf; - push_fourcc(buf, "IBHm"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal); - - // Nested IBxF storage - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/ntotal); - std::vector xb(ntotal * 2, 0); // code_size=2 - push_vector(buf, xb); - - push_val(buf, b); // b - push_val(buf, 1); // nhash = 1 - push_val(buf, 0); // nflip - - // Multi hash map fields (1 map): - push_val(buf, id_bits); // id_bits - push_val(buf, sz); // sz = 1 entry - push_vector(buf, bitbuf); // packed bitstring - - expect_binary_read_throws_with(buf, "multi hash map: id="); -} - -TEST(ReadIndexDeserialize, BinaryMultiHashBZero) { - // b must be positive; BitstringReader::read(0) produces garbage hash - // values and b is used as a bit-width for hash extraction. - std::vector buf; - push_fourcc(buf, "IBHm"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - - // Nested IBxF storage with ntotal=0 - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_vector(buf, {}); // empty xb - - push_val(buf, 0); // b = 0 (invalid) - - expect_binary_read_throws_with(buf, "IndexBinaryMultiHash b="); -} - -TEST(ReadIndexDeserialize, BinaryMultiHashNhashTimesBExceedsCodeSize) { - // nhash * b must not exceed code_size * 8, otherwise BitstringReader - // overflows the query buffer during search. - std::vector buf; - push_fourcc(buf, "IBHm"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - - // Nested IBxF storage with ntotal=0 - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, /*d=*/16, /*ntotal=*/0); - push_vector(buf, {}); // empty xb - - push_val(buf, 12); // b = 12 - push_val(buf, 2); // nhash = 2 => nhash*b = 24 > code_size*8 = 16 - // (code_size = d/8 = 2, so 2*8 = 16 bits available) - - expect_binary_read_throws_with(buf, "exceeds code_size"); -} - -// ---- IndexBinaryHNSW runtime safety checks ---- - -TEST(ReadIndexDeserialize, BinaryHNSWGetDistanceComputerNonFlatThrows) { - // Construct an IndexBinaryHNSW with non-flat storage and verify - // get_distance_computer throws instead of asserting. - IndexBinaryHNSW idx; - idx.storage = nullptr; - idx.own_fields = false; - // storage is nullptr so dynamic_cast will fail - EXPECT_THROW( - { - try { - idx.get_distance_computer(); - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find("IndexBinaryFlat"), - std::string::npos); - throw; - } - }, - faiss::FaissException); -} - -TEST(ReadIndexDeserialize, BinaryHNSWCagraEmptyIndexSearch) { - IndexBinaryHNSWCagra idx(16, 4); - idx.base_level_only = true; - // ntotal is 0, searching should throw - std::vector distances(1); - std::vector labels(1); - std::vector query(2); // d=16 -> code_size=2 - EXPECT_THROW( - { - try { - idx.search( - 1, - query.data(), - 1, - distances.data(), - labels.data()); - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find("empty index"), - std::string::npos); - throw; - } - }, - faiss::FaissException); -} - -TEST(ReadIndexDeserialize, BinaryHNSWCagraZeroEntrypoints) { - IndexBinaryHNSWCagra idx(16, 4); - // Add a vector first (add requires base_level_only == false) - std::vector vec(2, 0xFF); - idx.add(1, vec.data()); - idx.base_level_only = true; - idx.num_base_level_search_entrypoints = 0; - std::vector distances(1); - std::vector labels(1); - std::vector query(2); - EXPECT_THROW( - { - try { - idx.search( - 1, - query.data(), - 1, - distances.data(), - labels.data()); - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find( - "num_base_level_search_entrypoints"), - std::string::npos); - throw; - } - }, - faiss::FaissException); -} - -// ----------------------------------------------------------------------- -// Test: ResidualCoarseQuantizer with huge ntotal triggers centroid_norms -// byte limit check (pre-existing guard on ntotal vs byte_limit/sizeof(float)). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerHugeNtotal) { - // "ImRQ": fourcc + index_header + ResidualQuantizer + beam_factor - std::vector buf; - push_fourcc(buf, "ImRQ"); - // ntotal = 2^60: huge value that would cause OOM in search() - push_index_header(buf, /*d=*/4, /*ntotal=*/int64_t{1} << 60); - push_residual_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, -1.0f); // beam_factor = -1 (skip tables) - - expect_read_throws_with(buf, "centroid norms allocation"); -} - -// ----------------------------------------------------------------------- -// Test: ResidualCoarseQuantizer ntotal * M exceeds byte limit even when -// ntotal alone passes the centroid_norms check. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerNtotalTimesM) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - // ntotal=200000 passes centroid_norms check (200000 < 1MB/4 = 262144) - // but ntotal*M*sizeof(int32_t) = 200000*2*4 = 1600000 > 1MB - push_index_header(buf, /*d=*/4, /*ntotal=*/200000); - push_residual_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, -1.0f); // beam_factor = -1 (skip tables) - - auto old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1 << 20); // 1 MB - expect_read_throws_with(buf, "deserialization vector byte limit"); - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: ResidualCoarseQuantizer with huge beam_factor throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerHugeBeamFactor) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/16); - push_residual_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, 1e10f); // beam_factor = 1e10 (way too large) - - expect_read_throws_with(buf, "beam_factor"); -} - -// ----------------------------------------------------------------------- -// Test: ResidualQuantizer with max_beam_size=0 throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualQuantizerMaxBeamSizeZero) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/16); - // Build AdditiveQuantizer manually + bad max_beam_size - push_additive_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 0); // max_beam_size = 0 (invalid) - - expect_read_throws_with(buf, "max_beam_size"); -} - -// ----------------------------------------------------------------------- -// Test: ResidualQuantizer with huge max_beam_size exceeds byte limit. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualQuantizerHugeMaxBeamSize) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/16); - push_additive_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 1 << 30); // max_beam_size = 2^30 (huge) - - // With a tight byte limit, this should fail - auto old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1 << 20); // 1 MB - expect_read_throws_with(buf, "deserialization vector byte limit"); - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: Negative ntotal is rejected by read_index_header. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerNegativeNtotal) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/-1); - push_residual_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, -1.0f); // beam_factor - - expect_read_throws_with(buf, "invalid ntotal"); -} - -// ----------------------------------------------------------------------- -// Test: AdditiveQuantizer with M=0 is rejected during deserialization. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AdditiveQuantizerMZero) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/16); - // Build AdditiveQuantizer manually with M=0 - push_additive_quantizer(buf, /*d=*/4, /*M=*/0, /*nbits=*/{}); - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 1); // max_beam_size - - expect_read_throws_with(buf, "invalid AdditiveQuantizer M"); -} - -// ----------------------------------------------------------------------- -// Test: ResidualCoarseQuantizer with ntotal inconsistent with its codebooks -// is rejected before centroid norms are computed. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerNtotalZero) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_residual_quantizer(buf, /*d=*/4, /*M=*/2, /*nbits=*/{4, 4}); - push_val(buf, -1.0f); // beam_factor = -1 (skip tables) - - expect_read_throws_with(buf, "inconsistent with 2^tot_bits"); -} - -// ---- IndexBinaryIVF runtime safety checks ---- - -TEST(ReadIndexDeserialize, BinaryIVFNullInvlistsSearch) { - IndexBinaryIVF idx; - idx.d = 16; - idx.code_size = 2; - idx.invlists = nullptr; - idx.own_invlists = false; - std::vector distances(1); - std::vector labels(1); - std::vector query(2); - EXPECT_THROW( - { - try { - idx.search( - 1, - query.data(), - 1, - distances.data(), - labels.data()); - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find("inverted lists"), - std::string::npos); - throw; - } - }, - faiss::FaissException); -} - -// ----------------------------------------------------------------------- -// Test: VectorTransform deserialization rejects d_in * d_out that would -// exceed the deserialization vector byte limit. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, VectorTransformDimExceedsByteLimit) { - // VNrm format: fourcc + float(norm) + d_in + d_out + is_trained - // d_in=1024, d_out=1024 => d_in*d_out = 1M floats = 4 MB. - // Set byte limit to 1 MB so the check fails. - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); - push_val(buf, 1024); - push_val(buf, 1024); - push_val(buf, true); - - auto old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1 << 20); // 1 MB < 4 MB - - VectorIOReader reader; - reader.data = buf; - EXPECT_THROW(read_VectorTransform_up(&reader), FaissException); - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: VectorTransform deserialization accepts d_in * d_out within -// the deserialization vector byte limit. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, VectorTransformDimWithinByteLimit) { - // d_in=16, d_out=16 => d_in*d_out = 256 floats = 1 KB. - // Set byte limit to 1 MB so the check passes. - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); - push_val(buf, 16); - push_val(buf, 16); - push_val(buf, true); - - auto old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1 << 20); // 1 MB >> 1 KB - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_VectorTransform_up(&reader)); - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: VectorTransform deserialization rejects negative d_out. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, VectorTransformDOutNegative) { - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); - push_val(buf, 16); - push_val(buf, -1); - push_val(buf, true); - - VectorIOReader reader; - reader.data = buf; - EXPECT_THROW(read_VectorTransform_up(&reader), FaissException); -} - -// ----------------------------------------------------------------------- -// Test: VectorTransform deserialization rejects negative d_in. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, VectorTransformDInNegative) { - std::vector buf; - push_fourcc(buf, "VNrm"); - push_val(buf, 2.0f); - push_val(buf, -1); - push_val(buf, 16); - push_val(buf, true); - - VectorIOReader reader; - reader.data = buf; - EXPECT_THROW(read_VectorTransform_up(&reader), FaissException); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVFIndependentQuantizer deserialization rejects a VT whose -// d_in does not match the outer index dimension. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IwIQVtDinMismatch) { - // Create a valid IndexIVFIndependentQuantizer and serialize it. - const int d = 16; - const int nlist = 4; - auto quantizer = std::make_unique(d); - auto ivf = std::make_unique(quantizer.get(), d, nlist); - ivf->own_fields = false; - auto vt = std::make_unique(d); - - IndexIVFIndependentQuantizer indep(quantizer.get(), ivf.get(), vt.get()); - indep.own_fields = false; - - VectorIOWriter writer; - write_index(&indep, &writer); - - // Locate the VNrm fourcc to find where VT dimensions are stored. - // VNrm layout: fourcc(4) + norm(4) + d_in(4) + d_out(4) + is_trained(1) - auto& data = writer.data; - uint32_t vnrm_h; - { - const unsigned char s[4] = {'V', 'N', 'r', 'm'}; - vnrm_h = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24); - } - size_t vnrm_pos = 0; - bool found = false; - for (size_t i = 0; i + 4 <= data.size(); ++i) { - uint32_t val; - memcpy(&val, &data[i], sizeof(val)); - if (val == vnrm_h) { - vnrm_pos = i; - found = true; - break; - } - } - ASSERT_TRUE(found); - - // Corrupt d_in to create mismatch with indep->d. - size_t d_in_offset = vnrm_pos + 4 + 4; // after fourcc + norm - auto corrupted = data; - int bad_d_in = d + 1; - memcpy(&corrupted[d_in_offset], &bad_d_in, sizeof(int)); - - VectorIOReader reader; - reader.data = corrupted; - EXPECT_THROW(read_index(&reader), FaissException); -} - -// ----------------------------------------------------------------------- -// Test: IndexIVFIndependentQuantizer deserialization rejects a VT whose -// d_out does not match the inner IVF index dimension. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IwIQVtDoutMismatch) { - const int d = 16; - const int nlist = 4; - auto quantizer = std::make_unique(d); - auto ivf = std::make_unique(quantizer.get(), d, nlist); - ivf->own_fields = false; - auto vt = std::make_unique(d); - - IndexIVFIndependentQuantizer indep(quantizer.get(), ivf.get(), vt.get()); - indep.own_fields = false; - - VectorIOWriter writer; - write_index(&indep, &writer); - - auto& data = writer.data; - uint32_t vnrm_h; - { - const unsigned char s[4] = {'V', 'N', 'r', 'm'}; - vnrm_h = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24); - } - size_t vnrm_pos = 0; - bool found = false; - for (size_t i = 0; i + 4 <= data.size(); ++i) { - uint32_t val; - memcpy(&val, &data[i], sizeof(val)); - if (val == vnrm_h) { - vnrm_pos = i; - found = true; - break; - } - } - ASSERT_TRUE(found); - - // Corrupt d_out to create mismatch with index_ivf->d. - size_t d_out_offset = vnrm_pos + 4 + 4 + 4; // after fourcc + norm + d_in - auto corrupted = data; - int bad_d_out = d + 1; - memcpy(&corrupted[d_out_offset], &bad_d_out, sizeof(int)); - - VectorIOReader reader; - reader.data = corrupted; - EXPECT_THROW(read_index(&reader), FaissException); -} - -/// Helper: append a minimal valid serialized IndexPQFastScan ("IPfs"). -/// Caller can override bbs and M2 to inject invalid values. -static std::vector build_IndexPQFastScan_buf( - int bbs = 32, - size_t M2 = 2, - int qbs = 0) { - // PQ: d=4, M=2, nbits=4 → ksub=16, centroids size = d*ksub = 64 floats - std::vector buf; - push_fourcc(buf, "IPfs"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_pq(buf, /*d=*/4, /*M=*/2, /*nbits=*/4, std::vector(64, 0.0f)); - push_val(buf, 0); // implem - push_val(buf, bbs); // bbs - push_val(buf, qbs); // qbs - push_val(buf, 0); // ntotal2 - push_val(buf, M2); // M2 - push_vector(buf, {}); // codes - return buf; -} - -/// Helper: append a minimal valid serialized -/// IndexResidualQuantizerFastScan ("IRfs"). -/// Writes AdditiveQuantizer + ResidualQuantizer fields, then FastScan fields. -/// Caller can override FastScan M, ksub, bbs to inject invalid values. -static std::vector build_AQFastScan_buf( - size_t fastscan_M = 3, - size_t fastscan_ksub = 16, - int bbs = 32, - int qbs = 0, - size_t fastscan_M2 = 0) { - std::vector buf; - push_fourcc(buf, "IRfs"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - - // AdditiveQuantizer fields: - push_val(buf, 4); // d - push_val(buf, 1); // M (AQ M, not FastScan M) - push_vector(buf, {4}); // nbits = [4] - push_val(buf, false); // is_trained - push_vector(buf, std::vector(64, 0.0f)); // codebooks (d*16) - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - - // ResidualQuantizer extras: - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 1); // max_beam_size - - // FastScan fields (IndexAdditiveQuantizerFastScan): - push_val(buf, 0); // implem - push_val(buf, bbs); // bbs - push_val(buf, qbs); // qbs - push_val(buf, fastscan_M); // M - push_val(buf, 4); // nbits - push_val(buf, fastscan_ksub); // ksub - push_val(buf, 2); // code_size - push_val(buf, 0); // ntotal2 - // M2: use override if provided, otherwise roundup(M, 2) - size_t M2 = fastscan_M2 ? fastscan_M2 : (fastscan_M + 1) & ~size_t{1}; - push_val(buf, M2); - push_val(buf, true); // rescale_norm - push_val(buf, 1); // norm_scale - push_val(buf, 48); // max_train_points - push_vector(buf, {}); // codes - - return buf; -} - -/// Helper: serialize a valid IndexRaBitQFastScan and return the raw bytes. -/// Then locate the bbs field and patch it to the given value. -static std::vector build_RaBitQFastScan_buf(int bbs) { - IndexRaBitQFastScan idx(4, METRIC_L2, 32, 1); - - // Serialize the valid index - VectorIOWriter writer; - write_index(&idx, &writer); - - auto buf = std::move(writer.data); - - // Locate bbs (int, value 32) in the serialized data. - // Format: ... qb (uint8_t=8) then bbs (int=32). - // Search for qb=8 (1 byte) followed by bbs=32 (4 bytes). - uint8_t target_qb = 8; - int target_bbs = 32; - bool patched = false; - for (size_t i = 0; i + sizeof(uint8_t) + sizeof(int) <= buf.size(); i++) { - uint8_t val_qb; - int val_bbs; - memcpy(&val_qb, &buf[i], sizeof(uint8_t)); - memcpy(&val_bbs, &buf[i + sizeof(uint8_t)], sizeof(int)); - if (val_qb == target_qb && val_bbs == target_bbs) { - memcpy(&buf[i + sizeof(uint8_t)], &bbs, sizeof(int)); - patched = true; - break; - } - } - EXPECT_TRUE(patched) << "Could not find bbs field in serialized data"; - return buf; -} - -// ----------------------------------------------------------------------- -// IndexPQFastScan deserialization: bbs=0 must be rejected. -// Without this check, search() would divide by zero in ntotal2/bbs. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanBbsZero) { - auto buf = build_IndexPQFastScan_buf(/*bbs=*/0); - expect_read_throws_with(buf, "invalid bbs"); -} - -// ----------------------------------------------------------------------- -// IndexPQFastScan deserialization: bbs not a multiple of 32. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanBbsNotAligned) { - auto buf = build_IndexPQFastScan_buf(/*bbs=*/33); - expect_read_throws_with(buf, "invalid bbs"); -} - -// ----------------------------------------------------------------------- -// IndexPQFastScan deserialization: M2 must equal roundup(M, 2). -// A corrupted file with M2=0 while M>0 causes compute_quantized_LUT -// to write M*ksub bytes into a buffer sized for M2*ksub=0 bytes. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanM2Zero) { - auto buf = build_IndexPQFastScan_buf(/*bbs=*/32, /*M2=*/0); - expect_read_throws_with(buf, "invalid M2"); -} - -// ----------------------------------------------------------------------- -// IndexPQFastScan deserialization: M2 too small (1 < roundup(2, 2) = 2). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanM2TooSmall) { - auto buf = build_IndexPQFastScan_buf(/*bbs=*/32, /*M2=*/1); - expect_read_throws_with(buf, "invalid M2"); -} - -// ----------------------------------------------------------------------- -// IndexPQFastScan deserialization: ksub * M2 overflow. -// M2 is read directly from the file and could be corrupted to a huge -// value that causes ksub * M2 to overflow size_t. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanKsubM2Overflow) { - // M2=SIZE_MAX is now caught by M2 != roundup(M, 2) before overflow. - auto buf = build_IndexPQFastScan_buf( - /*bbs=*/32, /*M2=*/std::numeric_limits::max()); - expect_read_throws_with(buf, "invalid M2"); -} - -// ----------------------------------------------------------------------- -// IndexAdditiveQuantizerFastScan deserialization: M=0 must be rejected. -// Without this check, search() would crash in compute_float_LUT. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AQFastScanMZero) { - auto buf = build_AQFastScan_buf(/*fastscan_M=*/0); - expect_read_throws_with(buf, "invalid quantizer state"); -} - -// ----------------------------------------------------------------------- -// IndexAdditiveQuantizerFastScan deserialization: ksub=0 must be rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AQFastScanKsubZero) { - auto buf = build_AQFastScan_buf( - /*fastscan_M=*/3, /*fastscan_ksub=*/0); - expect_read_throws_with(buf, "invalid quantizer state"); -} - -// ----------------------------------------------------------------------- -// IndexAdditiveQuantizerFastScan deserialization: bbs=0 must be rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AQFastScanBbsZero) { - auto buf = build_AQFastScan_buf( - /*fastscan_M=*/3, /*fastscan_ksub=*/16, /*bbs=*/0); - expect_read_throws_with(buf, "invalid bbs"); -} - -// ----------------------------------------------------------------------- -// IndexAdditiveQuantizerFastScan deserialization: M2 mismatch. -// M2=0 while M=3 causes compute_quantized_LUT to write out of bounds. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AQFastScanM2Mismatch) { - auto buf = build_AQFastScan_buf( - /*fastscan_M=*/3, - /*fastscan_ksub=*/16, - /*bbs=*/32, - /*qbs=*/0, - /*fastscan_M2=*/1); - expect_read_throws_with(buf, "invalid M2"); -} - -// ----------------------------------------------------------------------- -// IndexAdditiveQuantizerFastScan deserialization: ksub * M overflow. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AQFastScanKsubMOverflow) { - auto buf = build_AQFastScan_buf( - /*fastscan_M=*/std::numeric_limits::max(), - /*fastscan_ksub=*/16, - /*bbs=*/32); - expect_read_throws_with(buf, "overflow"); -} - -// ----------------------------------------------------------------------- -// IndexRaBitQFastScan deserialization: bbs=0 must be rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, RaBitQFastScanBbsZero) { - auto buf = build_RaBitQFastScan_buf(/*bbs=*/0); - expect_read_throws_with(buf, "invalid bbs"); -} - -// ----------------------------------------------------------------------- -// IndexRaBitQFastScan deserialization: bbs not a multiple of 32. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, RaBitQFastScanBbsNotAligned) { - auto buf = build_RaBitQFastScan_buf(/*bbs=*/17); - expect_read_throws_with(buf, "invalid bbs"); -} - -// ----------------------------------------------------------------------- -// Test: read_AdditiveQuantizer rejects codebooks that are too small for -// d * total_codebook_size. Previously this was only caught at -// compute_LUT() time; now deserialization itself must throw. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AdditiveQuantizerCodebooksTooSmall) { - // Build an IndexResidualQuantizer ("IxRq") with d=4, M=1, nbits={8}. - // Write AdditiveQuantizer fields manually with empty codebooks so that - // the deserialization check fires (codebooks.size()=0 < d*256=1024). - std::vector buf; - push_fourcc(buf, "IxRq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // AdditiveQuantizer fields (inline, not via push_additive_quantizer - // which now writes correctly-sized codebooks): - push_val(buf, 4); // d - push_val(buf, 1); // M - push_vector(buf, {8}); // nbits - push_val(buf, true); // is_trained - push_vector(buf, {}); // codebooks (empty — triggers check) - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - // ResidualQuantizer fields: - push_val(buf, 2048); // train_type = Skip_codebook_tables - push_val(buf, 1); // max_beam_size - // IndexResidualQuantizer fields: - push_val(buf, 1); // code_size - push_vector(buf, {}); // codes (empty, matches ntotal=0) - - expect_read_throws_with(buf, "not a positive multiple"); -} - -// ----------------------------------------------------------------------- -// Test: AdditiveQuantizer with d=0 is rejected during deserialization. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AdditiveQuantizerDZero) { - std::vector buf; - push_fourcc(buf, "IxRq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - // AdditiveQuantizer fields with d=0: - push_val(buf, 0); // d = 0 (invalid) - push_val(buf, 1); // M - push_vector(buf, {8}); // nbits - push_val(buf, true); // is_trained - push_vector(buf, {}); // codebooks - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - - expect_read_throws_with(buf, "invalid AdditiveQuantizer d"); -} - -// ----------------------------------------------------------------------- -// Test: AdditiveQuantizer with codebooks size not a multiple of -// total_codebook_size is rejected. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, AdditiveQuantizerCodebooksNotMultiple) { - // d=4, M=1, nbits={8} → total_codebook_size=256. - // codebooks should be a multiple of 256 floats. Provide 257 floats. - std::vector buf; - push_fourcc(buf, "IxRq"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, 4); // d - push_val(buf, 1); // M - push_vector(buf, {8}); // nbits - push_val(buf, true); // is_trained - push_vector(buf, std::vector(257, 0.0f)); // not a multiple - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - - expect_read_throws_with(buf, "not a positive multiple"); -} - -// ----------------------------------------------------------------------- -// Test: ProductAdditiveQuantizer with d not divisible by nsplits throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductAdditiveQuantizerDNotDivisible) { - // d=5, nsplits=2 → d % nsplits != 0 - std::vector buf; - push_fourcc(buf, "IxPR"); - push_index_header(buf, /*d=*/5, /*ntotal=*/0); - // AdditiveQuantizer fields: d=5, M=2, nbits={4,4} - // For a PAQ with nsplits=2, codebook_d should be d/nsplits, but since - // d is not divisible we can just write codebooks sized for d - // (the divisibility check fires before the codebooks size check). - push_val(buf, 5); // d - push_val(buf, 2); // M - push_vector(buf, {4, 4}); // nbits - push_val(buf, true); // is_trained - push_vector(buf, std::vector(5 * 32, 0.0f)); // codebooks - push_val(buf, 0); // search_type = ST_decompress - push_val(buf, 0.0f); // norm_min - push_val(buf, 1.0f); // norm_max - // ProductAdditiveQuantizer: - push_val(buf, 2); // nsplits = 2 - - expect_read_throws_with(buf, "not divisible by nsplits"); -} - -// ----------------------------------------------------------------------- -// Test: ProductResidualQuantizer sub-quantizer d mismatch throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductResidualQuantizerSubDMismatch) { - // d=8, nsplits=2 → d_sub should be 4, but sub-quantizer has d=6 - std::vector buf; - push_fourcc(buf, "IxPR"); - push_index_header(buf, /*d=*/8, /*ntotal=*/0); - // ProductAdditiveQuantizer: AQ(d=8) + nsplits=2 → codebook_d = 4 - push_additive_quantizer( - buf, /*d=*/8, /*M=*/2, /*nbits=*/{4, 4}, /*codebook_d=*/4); - push_val(buf, 2); // nsplits = 2 - // First sub-quantizer: d=6 instead of expected d_sub=4 - push_residual_quantizer(buf, /*d=*/6, /*M=*/1, /*nbits=*/{4}); - // (second sub-quantizer not needed — should throw on first) - - expect_read_throws_with(buf, "sub-quantizer"); -} - -// ----------------------------------------------------------------------- -// Test: ProductLocalSearchQuantizer sub-quantizer d mismatch throws. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductLocalSearchQuantizerSubDMismatch) { - // d=8, nsplits=2 → d_sub should be 4, but sub-quantizer has d=6 - std::vector buf; - push_fourcc(buf, "IxPL"); - push_index_header(buf, /*d=*/8, /*ntotal=*/0); - // ProductAdditiveQuantizer: AQ(d=8) + nsplits=2 → codebook_d = 4 - push_additive_quantizer( - buf, /*d=*/8, /*M=*/2, /*nbits=*/{4, 4}, /*codebook_d=*/4); - push_val(buf, 2); // nsplits = 2 - // First sub-quantizer: d=6 instead of expected d_sub=4 - push_local_search_quantizer(buf, /*d=*/6, /*M=*/1, /*nbits=*/{4}); - // (second sub-quantizer not needed — should throw on first) - - expect_read_throws_with(buf, "sub-quantizer"); -} - -// ----------------------------------------------------------------------- -// Test: ProductResidualQuantizer with nsplits > 1 round-trips correctly -// (codebooks sized for d_sub, not d). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductResidualQuantizerMultiSplitValid) { - // d=8, nsplits=2, each sub-RQ has d_sub=4, M=1, nbits={4} - std::vector buf; - push_fourcc(buf, "IxPR"); - push_index_header(buf, /*d=*/8, /*ntotal=*/0); - // ProductAdditiveQuantizer: codebook_d = d/nsplits = 4 - push_additive_quantizer( - buf, /*d=*/8, /*M=*/2, /*nbits=*/{4, 4}, /*codebook_d=*/4); - push_val(buf, 2); // nsplits = 2 - // Two sub-RQs with d_sub=4 - push_residual_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{4}); - push_residual_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{4}); - // code_size = 1 (M=2, nbits={4,4} → 8 bits → 1 byte) - push_val(buf, 1); // code_size - push_vector(buf, {}); // codes (empty, ntotal=0) - - VectorIOReader reader; - reader.data = buf; - auto idx = read_index_up(&reader); - EXPECT_EQ(idx->ntotal, 0); - EXPECT_EQ(idx->d, 8); -} - -// ----------------------------------------------------------------------- -// Test: ProductLocalSearchQuantizer with nsplits > 1 round-trips correctly -// (codebooks sized for d_sub, not d). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductLocalSearchQuantizerMultiSplitValid) { - // d=8, nsplits=2, each sub-LSQ has d_sub=4, M=1, nbits={4} - std::vector buf; - push_fourcc(buf, "IxPL"); - push_index_header(buf, /*d=*/8, /*ntotal=*/0); - // ProductAdditiveQuantizer: codebook_d = d/nsplits = 4 - push_additive_quantizer( - buf, /*d=*/8, /*M=*/2, /*nbits=*/{4, 4}, /*codebook_d=*/4); - push_val(buf, 2); // nsplits = 2 - // Two sub-LSQs with d_sub=4 - push_local_search_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{4}); - push_local_search_quantizer(buf, /*d=*/4, /*M=*/1, /*nbits=*/{4}); - // code_size = 1 - push_val(buf, 1); // code_size - push_vector(buf, {}); // codes (empty, ntotal=0) - - VectorIOReader reader; - reader.data = buf; - auto idx = read_index_up(&reader); - EXPECT_EQ(idx->ntotal, 0); - EXPECT_EQ(idx->d, 8); -} - -// ----------------------------------------------------------------------- -// Negative qbs must be rejected at deserialization time to prevent -// infinite loops in pq4_qbs_to_nq (arithmetic right shift preserves -// the sign bit, so the loop never terminates for negative values). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexPQFastScanNegativeQbs) { - auto buf = build_IndexPQFastScan_buf(/*bbs=*/32, /*M2=*/2, /*qbs=*/-1); - expect_read_throws_with(buf, "qbs must be non-negative"); -} - -TEST(ReadIndexDeserialize, AQFastScanNegativeQbs) { - auto buf = build_AQFastScan_buf( - /*fastscan_M=*/3, - /*fastscan_ksub=*/16, - /*bbs=*/32, - /*qbs=*/-1); - expect_read_throws_with(buf, "qbs must be non-negative"); -} - -/// Helper: serialize a valid IndexIVFResidualQuantizerFastScan, then patch -/// the qbs field to a given value. The qbs field (int, default 0) immediately -/// follows bbs (int, value 32) in the serialized IVRf format. -static std::vector build_IVFAQFastScan_buf(int qbs) { - IndexFlat coarse_quantizer(4, METRIC_L2); - IndexIVFResidualQuantizerFastScan idx( - &coarse_quantizer, /*d=*/4, /*nlist=*/1, /*M=*/1, /*nbits=*/4); - - // Train the index so serialization produces valid codebooks. - std::vector train_data(4 * 64); - for (size_t i = 0; i < train_data.size(); i++) { - train_data[i] = static_cast(i); - } - idx.train(64, train_data.data()); - - // Set a distinctive qbs value so the byte pattern is unique. - int sentinel_qbs = 0x1234; - idx.qbs = sentinel_qbs; - - VectorIOWriter writer; - write_index(&idx, &writer); - - auto buf = std::move(writer.data); - - // Locate qbs (int, value sentinel_qbs) which follows bbs (int, value 32). - int target_bbs = 32; - int target_qbs = sentinel_qbs; - bool patched = false; - for (size_t i = 0; i + 2 * sizeof(int) <= buf.size(); i++) { - int val_bbs, val_qbs; - memcpy(&val_bbs, &buf[i], sizeof(int)); - memcpy(&val_qbs, &buf[i + sizeof(int)], sizeof(int)); - if (val_bbs == target_bbs && val_qbs == target_qbs) { - memcpy(&buf[i + sizeof(int)], &qbs, sizeof(int)); - patched = true; - break; - } - } - EXPECT_TRUE(patched) << "Could not find qbs field in serialized data"; - return buf; -} - -TEST(ReadIndexDeserialize, IVFAQFastScanNegativeQbs) { - auto buf = build_IVFAQFastScan_buf(/*qbs=*/-1); - expect_read_throws_with(buf, "qbs must be non-negative"); -} - -// ----------------------------------------------------------------------- -// Test: ScalarQuantizer with empty trained vector for qtypes that require -// training data must be rejected at deserialization time. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, SQEmptyTrainedNonUniform) { - // QT_8bit (NON_UNIFORM) expects trained.size() == 2*d == 8. - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, ScalarQuantizer::QT_8bit); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 1); // code_size - push_vector(buf, {}); // empty trained - push_vector(buf, {}); // codes (ntotal=0) - - expect_read_throws_with(buf, "ScalarQuantizer trained size"); -} - -TEST(ReadIndexDeserialize, SQEmptyTrainedUniform) { - // QT_8bit_uniform (UNIFORM) expects trained.size() == 2. - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, ScalarQuantizer::QT_8bit_uniform); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 1); // code_size - push_vector(buf, {}); // empty trained - push_vector(buf, {}); // codes (ntotal=0) - - expect_read_throws_with(buf, "ScalarQuantizer trained size"); -} - -// ----------------------------------------------------------------------- -// Test: ScalarQuantizer d must match the index header d. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, SQDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, ScalarQuantizer::QT_8bit); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 8); // d = 8, mismatches header d = 4 - push_val(buf, 1); // code_size - push_vector(buf, std::vector(16, 0.0f)); // trained - push_vector(buf, {}); // codes (ntotal=0) - - expect_read_throws_with(buf, "ScalarQuantizer d"); -} - -// ----------------------------------------------------------------------- -// Test: ScalarQuantizer with training data but is_trained=false in header. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, SQIsTrainedMismatch) { - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/false); - push_val(buf, ScalarQuantizer::QT_8bit); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 1); // code_size - // Provide correctly-sized trained data (2*d=8 floats) - push_vector(buf, std::vector(8, 0.0f)); - push_vector(buf, {}); // codes (ntotal=0) - - expect_read_throws_with(buf, "is_trained"); -} - -// ----------------------------------------------------------------------- -// Test: Untrained ScalarQuantizer (is_trained=false, empty trained) must -// deserialize successfully — this is a legitimate untrained index. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, SQUntrainedEmptyTrainedAccepted) { - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/false); - push_val(buf, ScalarQuantizer::QT_8bit); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, 4); // d - push_val(buf, 1); // code_size - push_vector(buf, {}); // empty trained (untrained) - push_vector(buf, {}); // codes (ntotal=0) - - VectorIOReader reader; - reader.data = buf; - auto idx = read_index_up(&reader); - EXPECT_FALSE(idx->is_trained); -} - -// Test: IndexResidualQuantizer rejects AQ dimension != index dimension. -TEST(ReadIndexDeserialize, IndexResidualQuantizerAQDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "IxRq"); - // Index header says d=4, but AQ will have d=8 → mismatch. - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_residual_quantizer(buf, /*d=*/8, /*M=*/1, /*nbits=*/{4}); - push_val(buf, 1); // code_size - push_vector(buf, {}); // codes - - expect_read_throws_with(buf, "does not match index d"); -} - -// Test: IndexLocalSearchQuantizer rejects AQ dimension != index dimension. -TEST(ReadIndexDeserialize, IndexLocalSearchQuantizerAQDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "IxLS"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_local_search_quantizer(buf, /*d=*/8, /*M=*/1, /*nbits=*/{4}); - push_val(buf, 1); // code_size - push_vector(buf, {}); // codes - - expect_read_throws_with(buf, "does not match index d"); -} - -// Test: ResidualCoarseQuantizer rejects AQ dimension != index dimension. -TEST(ReadIndexDeserialize, ResidualCoarseQuantizerAQDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "ImRQ"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_residual_quantizer(buf, /*d=*/8, /*M=*/1, /*nbits=*/{4}); - push_val(buf, -1.0f); // beam_factor - - expect_read_throws_with(buf, "does not match index d"); -} - -// Test: IndexResidualQuantizerFastScan rejects AQ dimension != index dimension. -TEST(ReadIndexDeserialize, IndexRQFastScanAQDimensionMismatch) { - std::vector buf; - push_fourcc(buf, "IRfs"); - // Index header says d=4, but AQ will have d=8 → mismatch. - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_residual_quantizer(buf, /*d=*/8, /*M=*/1, /*nbits=*/{4}); - // FastScan fields won't be reached due to early validation. - // But include a few just in case: - push_val(buf, 0); // implem - push_val(buf, 32); // bbs - push_val(buf, 0); // qbs - - expect_read_throws_with(buf, "does not match index d"); -} - -// ============================================================ -// code_size cross-validation against quantizer-derived values. -// -// Several index types read code_size from the serialized stream -// independently of the quantizer parameters. A corrupt code_size -// that passes the codes.size() == ntotal * code_size check (e.g. -// when ntotal == 0) can cause excessive allocations in -// GenericFlatCodesDistanceComputer during search. -// ============================================================ - -// Locate the byte offset of code_size in a serialized index by -// diffing two serializations: one with the real code_size and one -// with a probe value. This avoids false matches from other fields -// that happen to share the same numeric value. -static ssize_t find_code_size_offset( - Index* index, - size_t* code_size_ptr, - size_t real_cs) { - VectorIOWriter w1; - write_index(index, &w1); - - size_t probe_cs = real_cs ^ 0xDEAD; - *code_size_ptr = probe_cs; - VectorIOWriter w2; - write_index(index, &w2); - *code_size_ptr = real_cs; - - EXPECT_EQ(w1.data.size(), w2.data.size()); - if (w1.data.size() != w2.data.size()) { - return -1; - } - - ssize_t offset = -1; - for (size_t i = 0; i + sizeof(size_t) <= w1.data.size(); i++) { - if (w1.data[i] != w2.data[i]) { - size_t v1, v2; - memcpy(&v1, w1.data.data() + i, sizeof(size_t)); - memcpy(&v2, w2.data.data() + i, sizeof(size_t)); - if (v1 == real_cs && v2 == probe_cs) { - offset = i; - } - i += sizeof(size_t) - 1; - } - } - return offset; -} - -// Serialize a valid index, locate the exact byte offset of its -// code_size field via double-serialization diffing, corrupt it, -// and verify deserialization rejects it. -static void corrupt_code_size_and_expect_throw( - Index* index, - size_t* code_size_ptr, - const std::string& expected_substr) { - size_t real_cs = *code_size_ptr; - ssize_t offset = find_code_size_offset(index, code_size_ptr, real_cs); - ASSERT_GE(offset, 0) << "could not locate code_size field in " - << "serialized data via double-serialization diff"; - - VectorIOWriter writer; - write_index(index, &writer); - - size_t corrupt_cs = real_cs + 999; - memcpy(writer.data.data() + offset, &corrupt_cs, sizeof(size_t)); - - VectorIOReader reader; - reader.data = writer.data; - try { - auto idx = std::unique_ptr(read_index(&reader)); - FAIL() << "expected FaissException containing '" << expected_substr - << "'"; - } catch (const FaissException& e) { - EXPECT_NE( - std::string(e.what()).find(expected_substr), std::string::npos) - << "expected '" << expected_substr << "' in: " << e.what(); - } -} - -static std::vector make_random_data(int d, int n, int seed = 42) { - std::vector data(d * n); - std::mt19937 rng(seed); - std::uniform_real_distribution dist; - for (auto& v : data) { - v = dist(rng); - } - return data; -} - -TEST(ReadIndexDeserialize, ResidualQuantizerCodeSizeMismatch) { - int d = 8, nb = 256; - IndexResidualQuantizer idx(d, 2, 4); - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size, "code_size mismatch"); -} - -TEST(ReadIndexDeserialize, LocalSearchQuantizerCodeSizeMismatch) { - int d = 8, nb = 256; - IndexLocalSearchQuantizer idx(d, 2, 4); - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size, "code_size mismatch"); -} - -TEST(ReadIndexDeserialize, ProductResidualQuantizerCodeSizeMismatch) { - int d = 16, nb = 512; - IndexProductResidualQuantizer idx(d, 2, 4, 8); - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size, "code_size mismatch"); -} - -TEST(ReadIndexDeserialize, ProductLocalSearchQuantizerCodeSizeMismatch) { - int d = 8, nb = 256; - IndexProductLocalSearchQuantizer idx(d, 2, 2, 4); - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size, "code_size mismatch"); -} - -// IndexLSH code_size is validated against (nbits + 7) / 8. Use a -// crafted payload with a mismatched code_size to exercise the check. -TEST(ReadIndexDeserialize, LSHCodeSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IxHe"); // new format IndexLSH - push_index_header(buf, 8, 0); - push_val(buf, 64); // nbits - push_val(buf, false); // rotate_data - push_val(buf, false); // train_thresholds - push_vector(buf, {}); // thresholds - push_val(buf, 99); // code_size = 99 (should be 8) - // rrot: RandomRotationMatrix - push_fourcc(buf, "rrot"); - push_val(buf, 8); // d_in - push_val(buf, 64); // d_out - push_val(buf, false); // is_trained - push_val(buf, false); // have_bias - push_vector(buf, {}); // A - push_vector(buf, {}); // b - push_vector(buf, {}); // codes - - expect_read_throws_with(buf, "code_size mismatch"); -} - -TEST(ReadIndexDeserialize, IVFScalarQuantizerCodeSizeMismatch) { - // QT_fp16 gives code_size = d * 2 = 16, distinctive enough. - int d = 8, nb = 256, nlist = 4; - IndexFlatL2 quantizer(d); - IndexIVFScalarQuantizer idx(&quantizer, d, nlist, ScalarQuantizer::QT_fp16); - idx.own_fields = false; - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - // The corrupted code_size is caught either by our - // validate_code_size_match or by the InvertedLists code_size - // consistency check — both reject corrupt data. - corrupt_code_size_and_expect_throw(&idx, &idx.code_size, "code_size"); -} - -TEST(ReadIndexDeserialize, IVFAdditiveQuantizerCodeSizeMismatch) { - int d = 16, nb = 512, nlist = 4; - IndexFlatL2 quantizer(d); - IndexIVFResidualQuantizer idx(&quantizer, d, nlist, 2, 8); - idx.own_fields = false; - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - corrupt_code_size_and_expect_throw(&idx, &idx.code_size, "code_size"); -} - -TEST(ReadIndexDeserialize, Index2LayerCodeSize2Mismatch) { - int d = 8, nb = 256, nlist = 4; - auto quantizer = std::make_unique(d); - Index2Layer idx(quantizer.release(), nlist, 4); - idx.q1.own_fields = true; - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - idx.add(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size_2, "code_size mismatch"); -} - -TEST(ReadIndexDeserialize, Index2LayerCodeSizeSumMismatch) { - int d = 8, nb = 256, nlist = 4; - auto quantizer = std::make_unique(d); - Index2Layer idx(quantizer.release(), nlist, 4); - idx.q1.own_fields = true; - auto xb = make_random_data(d, nb); - idx.train(nb, xb.data()); - idx.add(nb, xb.data()); - corrupt_code_size_and_expect_throw( - &idx, &idx.code_size, "code_size mismatch"); -} - -// IndexLattice code_size is derived from scale_nbit, lattice_nbit, -// and nsq. A corrupt scale_nbit (e.g. negative) causes integer -// overflow in the total_nbit → code_size computation, producing -// a huge code_size that is rejected at deserialization. -TEST(ReadIndexDeserialize, IndexLatticeCodeSizeTooLarge) { - std::vector buf; - push_fourcc(buf, "IxLa"); - push_val(buf, 4); // d - push_val(buf, 2); // nsq (dsq = 4/2 = 2, power of 2 >= 2) - push_val(buf, -100); // scale_nbit (corrupt → overflows code_size) - push_val(buf, 1); // r2 - - expect_read_throws_with(buf, "code_size"); -} - -// ----------------------------------------------------------------------- -// Test: ProductQuantizer with M*ksub exceeding the deserialization byte -// limit is rejected. ProductQuantizer::set_derived_values only validates -// d % M == 0, which is satisfied by any M when d == 0, so a crafted PQ -// header could carry an enormous M alongside an empty centroids vector. -// Without the read-side bound, downstream allocations sized M*ksub (e.g. -// IVFPQ residual norms in initialize_IVFPQ_precomputed_table) reach -// std::vector::max_size() and abort the process via std::length_error. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, ProductQuantizerMKsubExceedsByteLimit) { - const size_t old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(1 << 20); // 1 MB - - std::vector buf; - push_fourcc(buf, "IxPq"); - push_index_header(buf, /*d=*/0, /*ntotal=*/0); - // PQ: d=0 (so 0 % M == 0 holds), M=1<<20, nbits=8 -> ksub=256 - // M * ksub = 2^28 floats = 1 GB, well above the 1 MB byte limit. - push_pq(buf, - /*d=*/0, - /*M=*/(size_t{1} << 20), - /*nbits=*/8, - /*centroids=*/{}); - - expect_read_throws_with(buf, "M*ksub"); - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: initialize_IVFPQ_precomputed_table rejects parameter combinations -// whose nlist * pq.M * pq.ksub * sizeof(float) computation overflows -// size_t. Without overflow-checked multiplication, the wrapped value -// silently bypasses the precomputed_table_max_bytes guard and the -// subsequent r_norms allocation aborts the process. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, InitializeIVFPQPrecomputedTableOverflowRejected) { - // Construct a PQ with M*ksub already saturating most of size_t. The - // nlist factor (taken from the quantizer's ntotal) then forces overflow - // when multiplied in. - ProductQuantizer pq; - pq.d = 0; - pq.M = size_t{1} << 40; - pq.nbits = 24; - pq.ksub = size_t{1} << pq.nbits; - pq.dsub = 0; - pq.code_size = 0; - // Skip set_derived_values (which would resize centroids); we are - // exercising initialize_IVFPQ_precomputed_table's arithmetic guard, not - // PQ training. - - IndexFlatL2 quantizer(/*d_in=*/0); - quantizer.ntotal = size_t{1} << 20; // nlist - AlignedTable precomputed_table; - int use_precomputed_table = 0; - - EXPECT_THROW( - initialize_IVFPQ_precomputed_table( - use_precomputed_table, - &quantizer, - pq, - precomputed_table, - /*by_residual=*/true, - /*verbose=*/false), - faiss::FaissException); -} - -// ----------------------------------------------------------------------- -// Test: initialize_IVFPQ_precomputed_table rejects an overflowing M*ksub -// even when the caller has pre-set use_precomputed_table to 1, which -// bypasses the in-function size-class branch. Protects in-memory IVFPQ -// callers (training, IndexHNSW, IndexIVFPQFastScan) and the -// IndexIVFIndependentQuantizer deserialization path that reads -// use_precomputed_table directly from the stream. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, - InitializeIVFPQPrecomputedTableUserSetFlagOverflowRejected) { - ProductQuantizer pq; - pq.d = 0; - pq.M = size_t{1} << 40; - pq.nbits = 24; - pq.ksub = size_t{1} << pq.nbits; - pq.dsub = 0; - pq.code_size = 0; - - IndexFlatL2 quantizer(/*d_in=*/0); - quantizer.ntotal = 1; // nlist - AlignedTable precomputed_table; - int use_precomputed_table = 1; // caller pre-selects table type 1 - - EXPECT_THROW( - initialize_IVFPQ_precomputed_table( - use_precomputed_table, - &quantizer, - pq, - precomputed_table, - /*by_residual=*/true, - /*verbose=*/false), - faiss::FaissException); -} - -// ----------------------------------------------------------------------- -// Test: read_ivfpq bounds the derived (not-stored) IVFPQ precomputed table -// by the deserialization vector byte limit before recomputing it. The table -// is quantizer->ntotal * pq.M * pq.ksub floats and is taken from -// attacker-controlled header fields, so a small crafted index can drive a -// large allocation (memory-amplification DoS reachable from read_index and -// the binary index fuzzer). With a low limit the read must throw rather than -// allocate. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFPQPrecomputedTableExceedsByteLimit) { - const int d = 16; - const int nlist = 256; - const int M = 8; - const int nbits = 8; // ksub = 256 - - IndexFlatL2 quantizer(d); - IndexIVFPQ index(&quantizer, d, nlist, M, nbits); - ASSERT_TRUE(index.by_residual); // precompute_table() runs on read - - const int nt = 10000; - std::vector xt(size_t(nt) * d); - std::mt19937 rng(12345); - std::uniform_real_distribution u(-1.0f, 1.0f); - for (auto& v : xt) { - v = u(rng); - } - index.train(nt, xt.data()); - index.add(nt, xt.data()); - - VectorIOWriter writer; - write_index(&index, &writer); - - // Recomputed table = ntotal(256) * M(8) * ksub(256) = 524288 floats (2 MB). - const size_t table_elems = size_t(nlist) * M * (size_t{1} << nbits); - const size_t old_limit = get_deserialization_vector_byte_limit(); - - // Cap the limit at 256 KB (65536 floats) so the precompute table is over - // the limit while the smaller derived reads (PQ centroids ~16 KB, inverted - // lists) stay under it. Pin the message so the throw can only come from the - // precompute-table guard, not some other byte-limit check. - set_deserialization_vector_byte_limit(size_t{1} << 18); // 256 KB - { - VectorIOReader reader; - reader.data = writer.data; - try { - read_index(&reader); - FAIL() << "expected FaissException"; - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find("precomputed_table"), - std::string::npos) - << "expected precompute-table guard, got: " << e.what(); - } - } - - // Just above the table size the index still loads (positive control). - set_deserialization_vector_byte_limit((table_elems + 1) * sizeof(float)); - { - VectorIOReader reader; - reader.data = writer.data; - EXPECT_NO_THROW(read_index_up(&reader)); - } - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: the same precompute-table bound guards the IVFPQFastScan (IwPf) read -// path, whose precompute_table() call is unconditional. nbits=4 -> ksub=16, so -// the recomputed table = ntotal(256) * M(8) * ksub(16) = 32768 floats (128 KB). -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFPQFastScanPrecomputedTableExceedsByteLimit) { - const int d = 16; - const int nlist = 256; - const int M = 8; - const int nbits = 4; // ksub = 16 - - IndexFlatL2 quantizer(d); - IndexIVFPQFastScan index(&quantizer, d, nlist, M, nbits); - - const int nt = 10000; - std::vector xt(size_t(nt) * d); - std::mt19937 rng(12345); - std::uniform_real_distribution u(-1.0f, 1.0f); - for (auto& v : xt) { - v = u(rng); - } - index.train(nt, xt.data()); - index.add(nt, xt.data()); - - VectorIOWriter writer; - write_index(&index, &writer); - - const size_t table_elems = size_t(nlist) * M * (size_t{1} << nbits); - const size_t old_limit = get_deserialization_vector_byte_limit(); - - // 64 KB (16384 floats) is below the 32768-float table but above the smaller - // derived reads. Pin the message so only the precompute-table guard - // matches. - set_deserialization_vector_byte_limit(size_t{1} << 16); // 64 KB - { - VectorIOReader reader; - reader.data = writer.data; - try { - read_index(&reader); - FAIL() << "expected FaissException"; - } catch (const faiss::FaissException& e) { - EXPECT_NE( - std::string(e.what()).find("precomputed_table"), - std::string::npos) - << "expected precompute-table guard, got: " << e.what(); - } - } - - // Just above the table size the index still loads (positive control). - set_deserialization_vector_byte_limit((table_elems + 1) * sizeof(float)); - { - VectorIOReader reader; - reader.data = writer.data; - EXPECT_NO_THROW(read_index_up(&reader)); - } - - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: read_ivfpq rejects a null coarse quantizer rather than dereferencing -// it. read_ivf_header deserializes the coarse quantizer via read_index, which -// returns nullptr for a crafted "null" fourcc. The explicit null check right -// after read_ivf_header must throw cleanly, before the precompute-table guard -// (or precompute_table itself) dereferences quantizer->ntotal. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFPQNullQuantizerReadRejected) { - std::vector buf; - push_fourcc(buf, "IwPQ"); - // read_ivf_header: index_header (is_trained=true), nlist, nprobe, - // coarse quantizer, direct_map. - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/true); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_fourcc(buf, "null"); // coarse quantizer -> read_index returns nullptr - push_empty_direct_map(buf); - // IVFPQ body: by_residual, code_size, ProductQuantizer, inverted lists. - push_val(buf, true); // by_residual - push_val(buf, 1); // code_size - // Valid PQ: d=4, M=1, nbits=8 -> ksub=256, centroids = d*ksub = 1024. - push_pq(buf, - /*d=*/4, - /*M=*/1, - /*nbits=*/8, - std::vector(4 * 256, 0.0f)); - push_null_invlists(buf); - - expect_read_throws_with(buf, "IVFPQ coarse quantizer is null"); -} - -// ----------------------------------------------------------------------- -// Test: the precompute-table bound also covers the type-2 table used when the -// coarse quantizer is a MultiIndexQuantizer. That table is -// cpq.ksub * pq.M * pq.ksub floats, driven by the coarse PQ's ksub, which is -// decoupled from quantizer->ntotal. A crafted MultiIndexQuantizer with a tiny -// ntotal but a large ksub passes an ntotal-only bound yet forces a huge -// allocation, so the guard must reject it. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, - IVFPQMultiIndexQuantizerPrecomputedTableExceedsByteLimit) { - const int d = 8; - std::vector buf; - push_fourcc(buf, "IwPQ"); - push_index_header(buf, d, /*ntotal=*/0, /*is_trained=*/true); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - // Coarse quantizer = MultiIndexQuantizer ("Imiq") with a crafted tiny - // ntotal(1) but cpq.nbits=10 -> cpq.ksub=1024, decoupling the type-2 table - // size from ntotal. - push_fourcc(buf, "Imiq"); - push_index_header(buf, d, /*ntotal=*/1, /*is_trained=*/true); - push_pq(buf, d, /*M=*/1, /*nbits=*/10, std::vector(d * 1024, 0.0f)); - push_empty_direct_map(buf); - push_val(buf, true); // by_residual - push_val(buf, 1); // code_size - // Outer PQ: M=2, nbits=8 -> ksub=256, m_ksub=512, and pq.M % cpq.M == 0. - push_pq(buf, d, /*M=*/2, /*nbits=*/8, std::vector(d * 256, 0.0f)); - push_null_invlists(buf); - - const size_t old_limit = get_deserialization_vector_byte_limit(); - set_deserialization_vector_byte_limit(size_t{1} << 16); // 64 KB - // type-1 bound: ntotal(1) * 2 * 256 = 512 floats -- an ntotal-only guard - // would pass. type-2 table: cpq.ksub(1024) * 2 * 256 = 524288 floats -- - // must be rejected. - expect_read_throws_with(buf, "precomputed_table"); - set_deserialization_vector_byte_limit(old_limit); -} - -// ----------------------------------------------------------------------- -// Test: the IVFPQFastScan (IwPf) read path also rejects a null coarse quantizer -// at the explicit check right after read_ivf_header, before any -// quantizer->ntotal dereference. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IVFPQFastScanNullQuantizerReadRejected) { - std::vector buf; - push_fourcc(buf, "IwPf"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0, /*is_trained=*/true); - push_val(buf, 1); // nlist - push_val(buf, 1); // nprobe - push_fourcc(buf, "null"); // coarse quantizer -> read_index returns nullptr - push_empty_direct_map(buf); - - expect_read_throws_with(buf, "IVFPQFastScan coarse quantizer is null"); -} - -// ============================================================ -// SVS fourcc rejection / deserialization safety (Group F: T262015608) -// ============================================================ - -#ifdef FAISS_ENABLE_SVS - -#include - -namespace { - -/// Append the IndexSVSVamana on-disk fields up to and including storage_kind. -/// Caller may then push initialized=true (to trigger the SVS deserialize_impl -/// path) or any other trailing fields needed to reach the validation site. -void push_svs_vamana_prefix(std::vector& buf, int storage_kind) { - push_index_header(buf, 8, 0); - push_val(buf, 32); // graph_max_degree - push_val(buf, 1.2f); // alpha - push_val(buf, 10); // search_window_size - push_val(buf, 10); // search_buffer_capacity - push_val(buf, 64); // construction_window_size - push_val(buf, 750); // max_candidate_pool_size - push_val(buf, 28); // prune_to - push_val(buf, false); // use_full_search_history - push_val(buf, storage_kind); -} - -/// Append the IndexSVSIVF on-disk fields up to and including storage_kind. -/// Used to exercise the validation guard at the ISIQ/ISIL/ISID read sites. -void push_svs_ivf_prefix(std::vector& buf, int storage_kind) { - push_index_header(buf, 8, 0); - push_val(buf, 8); // num_centroids - push_val(buf, 64); // minibatch_size - push_val(buf, 1); // num_iterations - push_val(buf, false); // is_hierarchical - push_val(buf, 0.1f); // training_fraction - push_val(buf, 0); // hierarchical_level1_clusters - push_val(buf, 0); // seed - push_val(buf, 1); // n_probes - push_val(buf, 1.0f); // k_reorder (float, not size_t) - push_val(buf, 1); // num_threads - push_val(buf, 1); // intra_query_threads - push_val(buf, storage_kind); -} - -} // namespace - -// An invalid storage_kind value should be rejected at deserialization time -// with a FaissException, not abort via FAISS_ASSERT in to_svs_storage_kind(). -TEST(ReadIndexDeserialize, SVSVamanaInvalidStorageKind) { - std::vector buf; - push_fourcc(buf, "ISVD"); - push_svs_vamana_prefix(buf, /*storage_kind=*/static_cast(SVS_count)); - push_val(buf, true); // initialized - - expect_read_throws_with(buf, "storage_kind"); -} - -// The Vamana validator must reject negative storage_kind values too — the -// shared helper takes a signed int because READ1 reads four bytes that could -// be either sign. -TEST(ReadIndexDeserialize, SVSVamanaNegativeStorageKind) { - std::vector buf; - push_fourcc(buf, "ISVD"); - push_svs_vamana_prefix(buf, /*storage_kind=*/-1); - push_val(buf, true); - - expect_read_throws_with(buf, "storage_kind"); + reader.data = data; + try { + read_index_up(&reader); + FAIL() << "expected FaissException"; + } catch (const FaissException& e) { + EXPECT_NE( + std::string(e.what()).find(expected_substr), std::string::npos) + << "expected '" << expected_substr << "' in: " << e.what(); + } } -// IVF Vamana flavours (ISIQ = IndexSVSIVFLVQ, ISIL = IndexSVSIVFLeanVec, -// ISID = IndexSVSIVF) all share the same storage_kind read site and must -// reject out-of-range values at the deserialization boundary, mirroring the -// Vamana branch above. Without the shared validator the bad value would -// propagate into IndexSVSIVF::deserialize_impl and only get rejected from -// to_svs_storage_kind() after several allocations and an SVS-runtime call. -TEST(ReadIndexDeserialize, SVSIVFInvalidStorageKind) { - std::vector buf; - push_fourcc(buf, "ISID"); - push_svs_ivf_prefix(buf, /*storage_kind=*/static_cast(SVS_count)); - push_val(buf, true); // is_static - push_val(buf, true); // initialized - - expect_read_throws_with(buf, "storage_kind"); +TEST(ReadIndexDeserialize, RaBitQCodesUndersizedRejected) { + // d == 4, nb_bits == 1 needs (4 + 7) / 8 + 8 == 9 bytes per code. + // One byte sized to the stored code_size cannot hold one code. + expect_float_read_throws_with( + make_rabitq_payload(1, {0}, {0.0f, 0.0f, 0.0f, 0.0f}), + "codes size"); } -TEST(ReadIndexDeserialize, SVSIVFLVQInvalidStorageKind) { - std::vector buf; - push_fourcc(buf, "ISIQ"); - push_svs_ivf_prefix(buf, /*storage_kind=*/-1); - push_val(buf, true); - push_val(buf, true); - - expect_read_throws_with(buf, "storage_kind"); +TEST(ReadIndexDeserialize, RaBitQCodeSizeDerivedFromLayout) { + // The stored code_size is a placeholder. The buffers match the + // derived stride, so the read succeeds with the derived code_size. + VectorIOReader reader; + reader.data = make_rabitq_payload( + 1, std::vector(9, 0), {0.0f, 0.0f, 0.0f, 0.0f}); + std::unique_ptr index; + ASSERT_NO_THROW(index = read_index_up(&reader)); + const auto* idxq = dynamic_cast(index.get()); + ASSERT_NE(idxq, nullptr); + EXPECT_EQ(idxq->rabitq.code_size, 9); + std::vector recons(4); + ASSERT_NO_THROW(index->reconstruct(0, recons.data())); } -TEST(ReadIndexDeserialize, SVSIVFLeanVecInvalidStorageKind) { - std::vector buf; - push_fourcc(buf, "ISIL"); - push_svs_ivf_prefix(buf, /*storage_kind=*/static_cast(SVS_count) + 7); - push_val(buf, true); // is_static - push_val(buf, 8); // leanvec_d (only on ISIL path) - push_val(buf, true); // initialized - - expect_read_throws_with(buf, "storage_kind"); +TEST(ReadIndexDeserialize, RaBitQShortCenterRejected) { + // decode_core reads center[j] for every j < d. + expect_float_read_throws_with( + make_rabitq_payload(9, std::vector(9, 0), {0.0f}), + "center"); } -// When SVS is enabled, deserializing an SVS Vamana index with invalid SVS -// stream data should throw a FaissException (from the SVS runtime load -// failure) rather than crashing with a null-pointer dereference. -// Previously, deserialize_impl called impl->load() on a null impl pointer. -TEST(ReadIndexDeserialize, SVSVamanaInvalidStreamThrows) { - std::vector buf; - push_fourcc(buf, "ISVD"); - push_index_header(buf, 8, 0); - // SVS Vamana deserialization fields: - push_val(buf, 32); // graph_max_degree - push_val(buf, 1.2f); // alpha - push_val(buf, 10); // search_window_size - push_val(buf, 10); // search_buffer_capacity - push_val(buf, 64); // construction_window_size - push_val(buf, 750); // max_candidate_pool_size - push_val(buf, 28); // prune_to - push_val(buf, false); // use_full_search_history - push_val(buf, 0); // storage_kind (SVS_Float16) - push_val(buf, false); // is_static - push_val(buf, true); // initialized = true → triggers deserialize_impl - // Provide garbage SVS stream data — load should fail gracefully. - for (int i = 0; i < 256; i++) { - push_val(buf, 0); - } +#ifdef FAISS_ENABLE_SVS - // Should throw from SVS runtime load failure, NOT crash with SIGSEGV. - EXPECT_THROW( - { - auto reader = faiss::VectorIOReader(); - reader.data = buf; - faiss::read_index(&reader); - }, - faiss::FaissException); -} +// ----------------------------------------------------------------------- +// Tests: SVS DirectoryArchiver entries stay inside the extraction root. +// C++ only: they check the path check in the fbsource copy of SVS +// (third-party/svs/v0.4.0/src/include/svs/lib/file.h). The SVS runtime that +// CMake builds use does not have this check. +// ----------------------------------------------------------------------- -// Same test for SVS Flat index. -TEST(ReadIndexDeserialize, SVSFlatInvalidStreamThrows) { - std::vector buf; - push_fourcc(buf, "ISVF"); - push_index_header(buf, 8, 0); - push_val(buf, true); // initialized = true → triggers deserialize_impl - // Provide garbage SVS stream data. - for (int i = 0; i < 256; i++) { - push_val(buf, 0); +/// Try to read a float index and expect a FaissException whose message +/// contains the given substring. +static void expect_read_throws_with( + const std::vector& data, + const std::string& expected_substr) { + VectorIOReader reader; + reader.data = data; + try { + read_index_up(&reader); + FAIL() << "expected FaissException"; + } catch (const FaissException& e) { + EXPECT_NE( + std::string(e.what()).find(expected_substr), std::string::npos) + << "expected '" << expected_substr << "' in: " << e.what(); } - - EXPECT_THROW( - { - auto reader = faiss::VectorIOReader(); - reader.data = buf; - faiss::read_index(&reader); - }, - faiss::FaissException); } -// ----------------------------------------------------------------------- -// Tests: SVS DirectoryArchiver entry validation. -// -// An "ISVF" payload carrying DirectoryArchiver::magic_number is unpacked by -// the vendored SVS archiver, which reads the entry name length, the entry -// name, and the entry size straight off the stream. All three are -// attacker-controlled and are consumed before any FAISS-side validation runs -// — the ReaderStreambuf byte limit only bounds individual reads, so it -// cannot police either the name length or the resulting path. -// ----------------------------------------------------------------------- - /// DirectoryArchiver::magic_number, from /// third-party/svs/v0.4.0/src/include/svs/lib/file.h. static constexpr uint64_t kSvsDirectoryArchiverMagic = 0x5e2d58d9f3b4a6c1ULL; @@ -4460,616 +401,4 @@ TEST(ReadIndexDeserialize, SVSArchiveParentTraversalEntryRejected) { EXPECT_FALSE(std::filesystem::exists(probe)); } -// ----------------------------------------------------------------------- -// Tests: IndexRefine / IndexRefinePanorama k_factor validation. -// -// Format "IxRF" (IndexRefineFlat) and "IxRP" (IndexRefinePanorama): -// fourcc + index_header + base_index + refine_index + k_factor -// -// k_factor must be finite and in [1, 1000]. -// ----------------------------------------------------------------------- - -// Helper: build a minimal IxRF or IxRP payload with the given k_factor. -static void push_index_refine( - std::vector& buf, - const char fourcc_str[4], - float k_factor) { - int d = 4; - push_fourcc(buf, fourcc_str); - push_index_header(buf, d, /*ntotal=*/0); - push_minimal_flat(buf, d); // base_index - push_minimal_flat(buf, d); // refine_index - push_val(buf, k_factor); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorValid) { - std::vector buf; - push_index_refine(buf, "IxRF", 1.0f); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorMax) { - std::vector buf; - push_index_refine(buf, "IxRF", 1000.0f); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorTooLarge) { - std::vector buf; - push_index_refine(buf, "IxRF", 1001.0f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorNegative) { - std::vector buf; - push_index_refine(buf, "IxRF", -1.0f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorZero) { - std::vector buf; - push_index_refine(buf, "IxRF", 0.0f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorInfinity) { - std::vector buf; - push_index_refine(buf, "IxRF", INFINITY); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefineKFactorNaN) { - std::vector buf; - push_index_refine(buf, "IxRF", NAN); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefinePanoramaKFactorTooLarge) { - std::vector buf; - push_index_refine(buf, "IxRP", 1e10f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexRefinePanoramaKFactorValid) { - std::vector buf; - push_index_refine(buf, "IxRP", 4.0f); - - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW(read_index_up(&reader)); -} - -// ----------------------------------------------------------------------- -// Tests: IndexIVFPQR k_factor validation via round-trip. -// -// Create a real IndexIVFPQR, serialize it, patch the k_factor bytes in -// the serialized blob, and verify deserialization rejects invalid values. -// ----------------------------------------------------------------------- - -// Helper: serialize an index to a byte vector. -static std::vector serialize_index(const Index* idx) { - VectorIOWriter writer; - write_index(idx, &writer); - return writer.data; -} - -// Helper: find and patch a float value in a byte buffer. -// Searches backwards from the end (k_factor is the last field written -// for IVFPQR). -static void patch_last_float(std::vector& buf, float new_val) { - size_t offset = buf.size() - sizeof(float); - std::memcpy(buf.data() + offset, &new_val, sizeof(float)); -} - -// Helper: create a trained IndexIVFPQR, serialize it, return the bytes. -// Uses nbits=4 (16 centroids) so training succeeds with few vectors. -static std::vector make_ivfpqr_bytes(float k_factor) { - int d = 8; - IndexFlatL2 quantizer(d); - IndexIVFPQR ivfpqr( - &quantizer, - d, - /*nlist=*/1, - /*M=*/2, - /*nbits_per_idx=*/4, - /*M_refine=*/2, - /*nbits_per_idx_refine=*/4); - - int ntrain = 64; - std::vector train_data(d * ntrain, 0.0f); - for (size_t i = 0; i < train_data.size(); i++) { - train_data[i] = float(i) / float(train_data.size()); - } - ivfpqr.train(ntrain, train_data.data()); - ivfpqr.k_factor = k_factor; - return serialize_index(&ivfpqr); -} - -TEST(ReadIndexDeserialize, IndexIVFPQRKFactorTooLarge) { - auto buf = make_ivfpqr_bytes(4.0f); - patch_last_float(buf, 1e10f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexIVFPQRKFactorNegative) { - auto buf = make_ivfpqr_bytes(4.0f); - patch_last_float(buf, -1.0f); - expect_read_throws_with(buf, "k_factor"); -} - -TEST(ReadIndexDeserialize, IndexIVFPQRKFactorValid) { - auto buf = make_ivfpqr_bytes(64.0f); // AutoTune max - - VectorIOReader reader; - reader.data = buf; - auto idx = read_index_up(&reader); - auto* result = dynamic_cast(idx.get()); - ASSERT_NE(result, nullptr); - EXPECT_FLOAT_EQ(result->k_factor, 64.0f); -} - -#else // !FAISS_ENABLE_SVS - -// When SVS is not enabled, attempting to read an index with an SVS fourcc -// should fail with an "unknown fourcc" error rather than crashing. -TEST(ReadIndexDeserialize, SVSVamanaFourccRejected) { - std::vector buf; - push_fourcc(buf, "ISVD"); - push_index_header(buf, 8, 0); - for (int i = 0; i < 128; i++) { - push_val(buf, 0); - } - - expect_read_throws_with(buf, "fourcc"); -} - #endif // FAISS_ENABLE_SVS - -// ----------------------------------------------------------------------- -// IndexIDMap deserialization invariant: id_map.size(), idxmap.ntotal, -// and the inner index's ntotal must all agree. The outer IDMap header -// and the inner index header carry independent ntotal fields on disk, -// so deserialization must reject payloads where they disagree. -// ----------------------------------------------------------------------- - -namespace { - -/// Build a serialized IxMp/IxM2 payload. The inner IxF2 (IndexFlat) carries -/// codes sized to match its own ntotal, so it passes the inner deserializer's -/// codes-vs-ntotal check and the IDMap-vs-inner-ntotal check is exercised -/// in isolation. -std::vector make_idmap_payload( - const char fourcc[4], - int64_t outer_ntotal, - int64_t inner_ntotal, - size_t id_map_size) { - constexpr int d = 4; - std::vector buf; - push_fourcc(buf, fourcc); - push_index_header(buf, d, outer_ntotal); - push_fourcc(buf, "IxF2"); - push_index_header(buf, d, inner_ntotal); - // IndexFlat codes are written via WRITEXBVECTOR: a size_t prefix of - // (byte_count / 4) followed by byte_count bytes. For inner_ntotal - // float vectors of dimension d, byte_count = inner_ntotal * d * 4. - const size_t byte_count = - static_cast(inner_ntotal) * d * sizeof(float); - push_val(buf, byte_count / 4); - buf.insert(buf.end(), byte_count, uint8_t{0}); - std::vector id_map(id_map_size, 0); - push_vector(buf, id_map); - return buf; -} - -std::vector make_binary_idmap_payload( - const char fourcc[4], - int64_t outer_ntotal, - int64_t inner_ntotal, - size_t id_map_size) { - constexpr int d = 8; - constexpr int code_size = d / 8; - std::vector buf; - push_fourcc(buf, fourcc); - push_binary_index_header(buf, d, outer_ntotal); - push_fourcc(buf, "IBxF"); - push_binary_index_header(buf, d, inner_ntotal); - std::vector codes(inner_ntotal * code_size, 0); - push_vector(buf, codes); - std::vector id_map(id_map_size, 0); - push_vector(buf, id_map); - return buf; -} - -} // namespace - -TEST(ReadIndexDeserialize, IndexIDMapInnerNtotalMismatchRejected) { - // Outer IDMap ntotal=0 agrees with id_map.size()=0, but the inner - // IndexFlat reports ntotal=3. - auto buf = make_idmap_payload( - "IxMp", /*outer_ntotal=*/0, /*inner_ntotal=*/3, /*id_map_size=*/0); - expect_read_throws_with(buf, "inner index ntotal"); -} - -TEST(ReadIndexDeserialize, IndexIDMap2InnerNtotalMismatchRejected) { - auto buf = make_idmap_payload( - "IxM2", /*outer_ntotal=*/0, /*inner_ntotal=*/3, /*id_map_size=*/0); - expect_read_throws_with(buf, "inner index ntotal"); -} - -TEST(ReadIndexDeserialize, IndexBinaryIDMapInnerNtotalMismatchRejected) { - auto buf = make_binary_idmap_payload( - "IBMp", /*outer_ntotal=*/0, /*inner_ntotal=*/3, /*id_map_size=*/0); - expect_binary_read_throws_with(buf, "inner index ntotal"); -} - -TEST(ReadIndexDeserialize, IndexBinaryIDMap2InnerNtotalMismatchRejected) { - auto buf = make_binary_idmap_payload( - "IBM2", /*outer_ntotal=*/0, /*inner_ntotal=*/3, /*id_map_size=*/0); - expect_binary_read_throws_with(buf, "inner index ntotal"); -} - -// ----------------------------------------------------------------------- -// IndexIDMap with a "null" sub-index fourcc. read_index returns -// nullptr for that fourcc, so the inner-ntotal cross-check on the -// IxMp/IxM2 path would dereference idxmap->index without protection. -// Verify both float variants reject the payload at the new "inner -// index is null" guard rather than crashing inside the validator. -// The binary IBMp/IBM2 path is reached indirectly (an embedded float -// IxMp/IxM2 inside a binary wrapper such as IndexBinaryFromFloat); it -// is covered by the same float-side guard exercised here. -// ----------------------------------------------------------------------- - -namespace { - -std::vector make_idmap_null_inner_payload(const char fourcc[4]) { - constexpr int d = 4; - std::vector buf; - push_fourcc(buf, fourcc); - push_index_header(buf, d, /*ntotal=*/0); - push_fourcc(buf, "null"); - push_vector(buf, std::vector{}); - return buf; -} - -} // namespace - -TEST(ReadIndexDeserialize, IndexIDMapNullInnerRejected) { - auto buf = make_idmap_null_inner_payload("IxMp"); - expect_read_throws_with(buf, "inner index is null"); -} - -TEST(ReadIndexDeserialize, IndexIDMap2NullInnerRejected) { - auto buf = make_idmap_null_inner_payload("IxM2"); - expect_read_throws_with(buf, "inner index is null"); -} - -// ----------------------------------------------------------------------- -// IndexBinaryFromFloat ("IBFf") wraps an inner float index. read_index -// returns nullptr for the "null" sub-index fourcc, and the IBFf -// deserialize site previously accepted it without validation -- the -// resulting IndexBinaryFromFloat would null-deref on the first -// search/add operation rather than at the deserialization boundary. -// Verify the new guard rejects the payload up front. -// ----------------------------------------------------------------------- -TEST(ReadIndexDeserialize, IndexBinaryFromFloatNullInnerRejected) { - constexpr int d = 8; - std::vector buf; - push_fourcc(buf, "IBFf"); - push_binary_index_header(buf, d, /*ntotal=*/0); - push_fourcc(buf, "null"); - expect_binary_read_throws_with(buf, "inner index is null"); -} - -// A well-formed IxMp payload with matching ntotals deserializes cleanly. -TEST(ReadIndexDeserialize, IndexIDMapMatchingNtotalsAccepted) { - auto buf = make_idmap_payload( - "IxMp", /*outer_ntotal=*/0, /*inner_ntotal=*/0, /*id_map_size=*/0); - VectorIOReader reader; - reader.data = buf; - EXPECT_NO_THROW({ - auto idx = read_index_up(&reader); - EXPECT_NE(idx, nullptr); - }); -} - -// ----------------------------------------------------------------------- -// IndexIDMap::search_ex maps each inner-index label through id_map. When -// inner.ntotal exceeds id_map.size() (e.g. mid-construction, or after a -// recoverable failure in add_with_ids_ex / add_sa_codes / merge_from -// leaves the IDMap layer behind the inner index), inner labels can land -// outside id_map. Such labels must be remapped to the -1 "no result" -// sentinel. -// ----------------------------------------------------------------------- -TEST(IndexIDMapSafety, SearchRemapsOutOfRangeLabelsToSentinel) { - constexpr int d = 4; - constexpr int nb = 3; - std::vector xb(nb * d, 0.0f); - for (int i = 0; i < nb; i++) { - xb[i * d] = static_cast(i); - } - - IndexFlat inner(d, METRIC_L2); - IndexIDMap idmap(&inner); - // inner.ntotal == nb, idmap.id_map is empty. - inner.add(nb, xb.data()); - - std::vector xq(d, 0.0f); - std::vector distances(1); - std::vector labels(1, 0); - EXPECT_NO_THROW( - idmap.search(1, xq.data(), 1, distances.data(), labels.data())); - EXPECT_EQ(labels[0], -1); -} - -// ----------------------------------------------------------------------- -// Panorama deserialization and reconstruct bounds (T287094917). -// -// "IxFP"/"IxFp" format: fourcc + d(int) + n_levels + batch_size + -// ntotal(int64) + is_trained(bool) + codes vec + cum_sums vec. -// Unlike every other index type this branch does not go through -// read_index_header, so its own range checks are all that guard d and -// ntotal. -// ----------------------------------------------------------------------- -static void push_flat_panorama( - std::vector& buf, - int d, - size_t n_levels, - size_t batch_size, - int64_t ntotal, - size_t codes_bytes, - size_t cum_sums_count) { - push_fourcc(buf, "IxFP"); - push_val(buf, d); - push_val(buf, n_levels); - push_val(buf, batch_size); - push_val(buf, ntotal); - push_val(buf, true); - push_val(buf, codes_bytes); - buf.resize(buf.size() + codes_bytes, 0); - push_val(buf, cum_sums_count); - buf.resize(buf.size() + cum_sums_count * sizeof(float), 0); -} - -// A d large enough to make code_size = d * 4 overflow into gigabytes must -// be rejected at read time, as it is for every other index type. -TEST(ReadIndexDeserialize, FlatPanoramaDimensionOutOfRange) { - std::vector buf; - push_flat_panorama( - buf, - /*d=*/1280725833, - /*n_levels=*/1, - /*batch_size=*/1024, - /*ntotal=*/0, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - expect_read_throws_with(buf, "out of range"); -} - -TEST(ReadIndexDeserialize, FlatPanoramaNegativeNtotal) { - std::vector buf; - push_flat_panorama( - buf, - /*d=*/8, - /*n_levels=*/1, - /*batch_size=*/4, - /*ntotal=*/-1, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - expect_read_throws_with(buf, "invalid ntotal"); -} - -TEST(ReadIndexDeserialize, FlatPanoramaZeroBatchSizeRejected) { - std::vector buf; - push_flat_panorama( - buf, - /*d=*/8, - /*n_levels=*/1, - /*batch_size=*/0, - /*ntotal=*/2, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - expect_read_throws_with(buf, "invalid IxFP batch_size"); -} - -TEST(ReadIndexDeserialize, FlatPanoramaCodesSizeOverflowRejected) { - std::vector buf; - push_flat_panorama( - buf, - /*d=*/8, - /*n_levels=*/1, - /*batch_size=*/(std::numeric_limits::max)(), - /*ntotal=*/2, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - // With batch_size=SIZE_MAX and ntotal=2, num_batches computes to 1 and - // num_slots=1*SIZE_MAX does not overflow. The throw actually originates - // from the later num_slots * code_size multiplication in mul_no_overflow, - // which emits "integer overflow in IndexFlatPanorama codes: ...". Match - // on that full prefix so this test cannot be silently satisfied by the - // sibling "IndexFlatPanorama codes size mismatch" throw. - expect_read_throws_with(buf, "integer overflow in IndexFlatPanorama codes"); -} - -TEST(ReadIndexDeserialize, FlatPanoramaCodesSizeMismatch) { - std::vector buf; - push_flat_panorama( - buf, - /*d=*/8, - /*n_levels=*/1, - /*batch_size=*/4, - /*ntotal=*/2, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - // Match on the explicit FAISS_THROW_IF_NOT_FMT message so the test is - // pinned to the intended error rather than a stringified condition - // expression that would break on trivial refactors. - expect_read_throws_with(buf, "IndexFlatPanorama codes size mismatch"); -} - -// End-to-end shape of the fuzzer crash: an IndexPreTransform with an empty -// chain wrapping an empty IndexFlatPanorama. Everything deserializes, and -// reconstruct() must then reject the out-of-range key instead of memcpy'ing -// code_size bytes out of a zero-length codes buffer. -TEST(ReadIndexDeserialize, PreTransformOverEmptyFlatPanoramaReconstruct) { - constexpr int d = 8; - std::vector buf; - push_fourcc(buf, "IxPT"); - push_index_header(buf, d, /*ntotal=*/0); - push_val(buf, 0); // nt = 0, empty chain - push_flat_panorama( - buf, - d, - /*n_levels=*/1, - /*batch_size=*/4, - /*ntotal=*/0, - /*codes_bytes=*/0, - /*cum_sums_count=*/0); - - VectorIOReader reader; - reader.data = buf; - std::unique_ptr idx; - ASSERT_NO_THROW({ idx = read_index_up(&reader); }); - ASSERT_NE(idx, nullptr); - - std::vector recons(d, 0.0f); - EXPECT_THROW(idx->reconstruct(0, recons.data()), FaissException); -} - -// "IHfP" format: fourcc + index_header + n_levels(size_t) + cum_sums vec + -// HNSW graph + storage index. cum_sums must hold ntotal * (n_levels + 1) -// floats; a short vector is an out-of-bounds read on the search path. -TEST(ReadIndexDeserialize, HNSWFlatPanoramaCumSumsSizeMismatch) { - std::vector buf; - push_fourcc(buf, "IHfP"); - push_index_header(buf, /*d=*/4, /*ntotal=*/1); - push_val(buf, size_t(1)); // n_levels - push_vector(buf, {0.0f}); // cum_sums: 1 float, needs 2 - - expect_read_throws_with(buf, "IndexHNSWFlatPanorama cum_sums"); -} - -TEST(ReadIndexDeserialize, HNSWFlatPanoramaZeroLevels) { - std::vector buf; - push_fourcc(buf, "IHfP"); - push_index_header(buf, /*d=*/4, /*ntotal=*/0); - push_val(buf, size_t(0)); // n_levels = 0 - - expect_read_throws_with(buf, "invalid IHfP n_levels"); -} - -// IndexFlatPanorama overrides reconstruct()/reconstruct_n() and so does not -// inherit the range guards in IndexFlat / IndexFlatCodes. Panorama's -// level-major layout means an out-of-range key reads whole batch strides -// past the end of `codes`. -TEST(IndexFlatPanoramaSafety, ReconstructRejectsOutOfRangeKey) { - constexpr int d = 8; - IndexFlatL2Panorama index(d, /*n_levels_in=*/2, /*batch_size_in=*/4); - std::vector recons(2 * d, 0.0f); - - EXPECT_THROW(index.reconstruct(0, recons.data()), FaissException); - - std::vector xb(2 * d, 1.0f); - index.add(2, xb.data()); - - EXPECT_NO_THROW(index.reconstruct(1, recons.data())); - EXPECT_THROW(index.reconstruct(2, recons.data()), FaissException); - EXPECT_THROW(index.reconstruct(-1, recons.data()), FaissException); - EXPECT_NO_THROW(index.reconstruct_n(0, 2, recons.data())); - EXPECT_THROW(index.reconstruct_n(-1, 1, recons.data()), FaissException); - EXPECT_THROW(index.reconstruct_n(0, -1, recons.data()), FaissException); - EXPECT_THROW( - index.reconstruct_n( - 1, (std::numeric_limits::max)(), recons.data()), - FaissException); - EXPECT_THROW(index.reconstruct_n(1, 2, recons.data()), FaissException); - EXPECT_THROW(index.reconstruct_n(-1, 0, recons.data()), FaissException); - EXPECT_THROW(index.reconstruct_n(3, 0, recons.data()), FaissException); -} - -namespace { - -constexpr size_t kTurboQFullDimension = 16; -constexpr uint64_t kTurboQFullSeed = 0x0123456789abcdefULL; -constexpr auto kTurboQFullQtype = ScalarQuantizer::QT_3bit_tq; - -// Total TurboQ bits/component for a QT_*_tq qtype (matches the mapping in -// ScalarQuantizer::set_derived_sizes). Full TurboQ splits these into -// (bits - 1) MSE bits + 1 QJL bit, so the reader-side trained-vector -// centroid count is k = 1 << (bits - 1). -constexpr size_t turboq_full_nb_bits(ScalarQuantizer::QuantizerType qt) { - return qt == ScalarQuantizer::QT_2bit_tq ? 2 - : qt == ScalarQuantizer::QT_3bit_tq ? 3 - : qt == ScalarQuantizer::QT_4bit_tq ? 4 - : qt == ScalarQuantizer::QT_5bit_tq ? 5 - : 0; -} - -// Derived rather than hardcoded so that changing kTurboQFullQtype (e.g. to -// QT_4bit_tq) automatically resizes the payload; hardcoding kept the two -// constants coupled and a mismatch would fail the read for an unrelated -// reason (trained.size() != k + (k-1) + 3). -// -// `turboq_full_nb_bits` returns 0 for qtypes it does not recognise; guard -// against that sentinel here so a future change to `kTurboQFullQtype` that -// forgets to extend the mapping fails loudly at compile time instead of -// tripping UB via `size_t{1} << (0 - 1)`. -static_assert( - turboq_full_nb_bits(kTurboQFullQtype) != 0, - "kTurboQFullQtype must be a QT_*_tq qtype recognised by " - "turboq_full_nb_bits; extend the mapping when adding new tq qtypes."); -constexpr size_t kTurboQFullCentroids = size_t{1} - << (turboq_full_nb_bits(kTurboQFullQtype) - 1); - -std::vector make_turboq_full_sq_payload( - uint8_t qjl_type, - size_t d = kTurboQFullDimension) { - float seed[2]; - ScalarQuantizer::TurboQuantRefine::pack_seed(kTurboQFullSeed, seed); - std::vector trained( - kTurboQFullCentroids + (kTurboQFullCentroids - 1) + 3, 0.0f); - trained[trained.size() - 3] = seed[0]; - trained[trained.size() - 2] = seed[1]; - trained[trained.size() - 1] = static_cast(qjl_type); - - std::vector buf; - push_fourcc(buf, "IxSQ"); - push_index_header(buf, static_cast(d), /*ntotal=*/0); - push_val(buf, kTurboQFullQtype); - push_val(buf, 0); // rangestat - push_val(buf, 0.0f); // rangestat_arg - push_val(buf, d); - push_val(buf, 0); // code_size is recomputed on read - push_vector(buf, trained); - push_vector(buf, {}); // codes - return buf; -} - -} // namespace - -TEST(ReadIndexDeserialize, SQTurboQuantFullRecoversConfigFromTrained) { - for (const uint8_t qjl_type : {uint8_t{0}, uint8_t{2}}) { - SCOPED_TRACE(testing::Message() << "qjl_type = " << int(qjl_type)); - - VectorIOReader reader; - reader.data = make_turboq_full_sq_payload(qjl_type); - std::unique_ptr index; - ASSERT_NO_THROW(index = read_index_up(&reader)); - - const auto* sq_index = dynamic_cast(index.get()); - ASSERT_NE(sq_index, nullptr); - EXPECT_EQ(sq_index->sq.d, kTurboQFullDimension); - EXPECT_EQ(sq_index->sq.turboq_refine.qjl_type, qjl_type); - EXPECT_EQ(sq_index->sq.turboq_refine.seed, kTurboQFullSeed); - } -} diff --git a/thirdparty/faiss/tests/test_read_index_deserialize.py b/thirdparty/faiss/tests/test_read_index_deserialize.py new file mode 100644 index 000000000..8be7ddf45 --- /dev/null +++ b/thirdparty/faiss/tests/test_read_index_deserialize.py @@ -0,0 +1,2799 @@ +# 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. + +"""Deserialization validation tests for crafted and corrupted index +payloads.""" + +import contextlib +import struct +import sys +import unittest + +import numpy as np + +import faiss + +# struct format codes for the C++ types that the faiss writer emits. +INT = "i" +INT64 = "q" +SIZE_T = "Q" +BOOL = "?" +FLOAT = "f" +DOUBLE = "d" +CHAR = "b" +UINT8 = "B" + +SIZE_MAX = 2**64 - 1 +INT64_MAX = 2**63 - 1 + +SVS_ENABLED = hasattr(faiss, "IndexSVSVamana") + + +# ----------------------------------------------------------------------- +# Byte-buffer helpers that mirror the faiss writer layout. +# ----------------------------------------------------------------------- + + +def push_val(buf, fmt, val): + """Append a scalar value in little-endian format, matching WRITE1.""" + buf += struct.pack("<" + fmt, val) + + +def push_vector(buf, fmt, vec): + """Append a WRITEVECTOR-formatted vector (size_t length prefix followed + by raw element data).""" + vec = list(vec) + push_val(buf, SIZE_T, len(vec)) + buf += struct.pack("<%d%s" % (len(vec), fmt), *vec) + + +def push_fourcc(buf, s): + """Append a fourcc string. The writer stores it as the uint32 + x[0] | x[1] << 8 | x[2] << 16 | x[3] << 24, which is the same bytes in + little-endian order.""" + assert len(s) == 4 + buf += s.encode("ascii") + + +def push_index_header(buf, d, ntotal, is_trained=True, metric_type=1): + """Append write_index_header fields (metric_type 1 is L2).""" + push_val(buf, INT, d) + push_val(buf, INT64, ntotal) + dummy = 1 << 20 + push_val(buf, INT64, dummy) + push_val(buf, INT64, dummy) + push_val(buf, BOOL, is_trained) + push_val(buf, INT, metric_type) + + +def push_pq(buf, d, M, nbits, centroids=()): + """Append write_ProductQuantizer fields (d, M, nbits, centroids vec).""" + push_val(buf, SIZE_T, d) + push_val(buf, SIZE_T, M) + push_val(buf, SIZE_T, nbits) + push_vector(buf, FLOAT, centroids) + + +def push_binary_index_header(buf, d, ntotal, is_trained=True, metric_type=1): + """Append read_index_binary_header fields: + int d, int code_size, idx_t ntotal, bool is_trained, int metric_type.""" + code_size = d // 8 + push_val(buf, INT, d) + push_val(buf, INT, code_size) + push_val(buf, INT64, ntotal) + push_val(buf, BOOL, is_trained) + push_val(buf, INT, metric_type) + + +def push_empty_direct_map(buf): + """Append empty direct_map bytes (NoMap type + empty array).""" + push_val(buf, CHAR, 0) # DirectMap::NoMap + push_val(buf, SIZE_T, 0) # empty array + + +def push_null_invlists(buf): + """Append null inverted lists ("il00" fourcc).""" + push_fourcc(buf, "il00") + + +def push_minimal_binary_flat(buf, d): + """Append a minimal IndexBinaryFlat ("IBxF") with ntotal=0.""" + push_fourcc(buf, "IBxF") + push_binary_index_header(buf, d, 0) + push_vector(buf, UINT8, []) # empty xb + + +def push_additive_quantizer(buf, d, M, nbits, codebook_d=0): + """Append a minimal AdditiveQuantizer (d, M, nbits, is_trained, + codebooks, search_type=ST_decompress, norm_min, norm_max). + Writes zero-filled codebooks of size codebook_d * total_codebook_size so + that the deserialization codebooks-size validation passes. + For standalone quantizers codebook_d == d. For ProductAdditiveQuantizer + codebook_d == d / nsplits. Pass codebook_d = 0 (default) to use d.""" + if codebook_d == 0: + codebook_d = d + total_codebook_size = sum(1 << nb for nb in nbits) + push_val(buf, SIZE_T, d) + push_val(buf, SIZE_T, M) + push_vector(buf, SIZE_T, nbits) + push_val(buf, BOOL, True) # is_trained + push_vector(buf, FLOAT, [0.0] * (codebook_d * total_codebook_size)) + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + + +def push_residual_quantizer(buf, d, M, nbits): + """Append a minimal ResidualQuantizer (AdditiveQuantizer + train_type + + max_beam_size). Uses Skip_codebook_tables to avoid + compute_codebook_tables on empty codebooks.""" + push_additive_quantizer(buf, d, M, nbits) + push_val(buf, INT, 2048) # train_type = Skip_codebook_tables + push_val(buf, INT, 1) # max_beam_size + + +def push_local_search_quantizer(buf, d, M, nbits): + """Append a minimal LocalSearchQuantizer (AdditiveQuantizer + K + + train_iters + encode_ils_iters + train_ils_iters + icm_iters + p + lambd + + chunk_size + random_seed + nperts + update_codebooks_with_double).""" + push_additive_quantizer(buf, d, M, nbits) + push_val(buf, SIZE_T, 256) # K + push_val(buf, SIZE_T, 25) # train_iters + push_val(buf, SIZE_T, 8) # encode_ils_iters + push_val(buf, SIZE_T, 8) # train_ils_iters + push_val(buf, SIZE_T, 4) # icm_iters + push_val(buf, FLOAT, 0.5) # p + push_val(buf, FLOAT, 0.0) # lambd + push_val(buf, SIZE_T, 0) # chunk_size + push_val(buf, INT, 123) # random_seed + push_val(buf, SIZE_T, 4) # nperts + push_val(buf, BOOL, False) # update_codebooks_with_double + + +def push_minimal_flat(buf, d, ntotal=0): + """Append a minimal IndexFlatL2 ("IxF2"). Uses the WRITEXBVECTOR format + (size_t num_floats prefix, then raw data).""" + push_fourcc(buf, "IxF2") + push_index_header(buf, d, ntotal) + num_floats = ntotal * d + push_val(buf, SIZE_T, num_floats) + buf += bytes(num_floats * 4) + + +def push_minimal_hnsw(buf, ntotal): + """Append a minimal valid HNSW structure. All nodes are at level 1 with + zero neighbors, which passes validate_HNSW.""" + push_vector(buf, DOUBLE, []) # assign_probas + # cum_nneighbor_per_level: 0 cumulative neighbors at each level + push_vector(buf, INT, [0, 0]) + # levels: one entry per node, all at level 1 (1-indexed in HNSW) + push_vector(buf, INT, [1] * ntotal) + push_vector(buf, SIZE_T, [0] * (ntotal + 1)) # offsets + push_vector(buf, INT, []) # neighbors + push_val(buf, INT, 0 if ntotal > 0 else -1) # entry_point + push_val(buf, INT, 0) # max_level + push_val(buf, INT, 40) # efConstruction + push_val(buf, INT, 16) # efSearch + push_val(buf, INT, 1) # upper_beam (deprecated, always 1) + + +def push_hnsw_with_neighbors( + buf, ntotal, neighbors_per_node, neighbors, entry_point=0 +): + """Append an HNSW structure with explicit neighbor data. All nodes are + at level 1, cum_nneighbor_per_level = {0, neighbors_per_node}. Callers + supply the full neighbors vector (ntotal * neighbors_per_node entries, + using -1 for empty slots).""" + push_vector(buf, DOUBLE, []) # assign_probas + push_vector(buf, INT, [0, neighbors_per_node]) + push_vector(buf, INT, [1] * ntotal) # levels + # offsets: each node occupies neighbors_per_node slots + offsets = [i * neighbors_per_node for i in range(ntotal + 1)] + push_vector(buf, SIZE_T, offsets) + push_vector(buf, INT, neighbors) + push_val(buf, INT, entry_point) + push_val(buf, INT, 0) # max_level + push_val(buf, INT, 40) # efConstruction + push_val(buf, INT, 16) # efSearch + push_val(buf, INT, 1) # upper_beam (deprecated) + + +def push_nndescent(buf, ntotal, d, K, has_built, final_graph): + """Append NNDescent fields.""" + push_val(buf, INT, ntotal) + push_val(buf, INT, d) + push_val(buf, INT, K) + push_val(buf, INT, 10) # S + push_val(buf, INT, 10) # R + push_val(buf, INT, 10) # L + push_val(buf, INT, 1) # iter + push_val(buf, INT, 10) # search_L + push_val(buf, INT, 42) # random_seed + push_val(buf, BOOL, has_built) + push_vector(buf, INT, final_graph) + + +def push_rabitq(buf, d): + """Append a minimal RaBitQuantizer (single-bit format).""" + push_val(buf, SIZE_T, d) + push_val(buf, SIZE_T, 1) # code_size + push_val(buf, INT, 1) # metric_type (L2) + + +def push_rabitq_multibit(buf, d): + """Append a minimal RaBitQuantizer (multi-bit format).""" + push_rabitq(buf, d) + push_val(buf, SIZE_T, 1) # nb_bits + + +def push_ivf_header(buf, d): + """Append an IVF header (index_header + nlist + nprobe + flat quantizer + + empty direct_map).""" + push_index_header(buf, d, 0) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_flat(buf, d) + push_empty_direct_map(buf) + + +def pack_bits(nbytes, fields): + """Pack (value, nbit) fields with faiss.BitstringWriter.""" + bitbuf = np.zeros(nbytes, dtype="uint8") + wr = faiss.BitstringWriter(faiss.swig_ptr(bitbuf), bitbuf.size) + for value, nbit in fields: + wr.write(value, nbit) + return bitbuf.tolist() + + +def make_idmap_payload(fourcc, outer_ntotal, inner_ntotal, id_map_size): + """Serialized IxMp/IxM2 payload. The inner IxF2 carries codes sized to + its own ntotal, so it passes the inner codes-vs-ntotal check and the + IDMap-vs-inner-ntotal check is exercised in isolation.""" + d = 4 + buf = bytearray() + push_fourcc(buf, fourcc) + push_index_header(buf, d, outer_ntotal) + push_fourcc(buf, "IxF2") + push_index_header(buf, d, inner_ntotal) + # IndexFlat codes use WRITEXBVECTOR: a size_t prefix of + # (byte_count / 4) followed by byte_count bytes. + byte_count = inner_ntotal * d * 4 + push_val(buf, SIZE_T, byte_count // 4) + buf += bytes(byte_count) + push_vector(buf, INT64, [0] * id_map_size) + return buf + + +def push_flat_panorama(buf, d, n_levels, batch_size, ntotal): + """"IxFP" format: fourcc + d(int) + n_levels + batch_size + + ntotal(int64) + is_trained(bool) + empty codes vec + empty cum_sums + vec.""" + push_fourcc(buf, "IxFP") + push_val(buf, INT, d) + push_val(buf, SIZE_T, n_levels) + push_val(buf, SIZE_T, batch_size) + push_val(buf, INT64, ntotal) + push_val(buf, BOOL, True) + push_vector(buf, UINT8, []) # codes + push_vector(buf, FLOAT, []) # cum_sums + + +# ----------------------------------------------------------------------- +# Readers +# ----------------------------------------------------------------------- + + +def make_reader(buf): + reader = faiss.VectorIOReader() + faiss.copy_array_to_vector( + np.frombuffer(bytes(buf), dtype="uint8"), reader.data + ) + return reader + + +def read_index(buf): + return faiss.deserialize_index(np.frombuffer(bytes(buf), dtype="uint8")) + + +def read_index_binary(buf): + return faiss.deserialize_index_binary( + np.frombuffer(bytes(buf), dtype="uint8") + ) + + +def read_vector_transform(buf): + return faiss.read_VectorTransform(make_reader(buf)) + + +def read_invlists(buf): + return faiss.read_InvertedLists(make_reader(buf)) + + +def serialize_index(index): + return bytearray(faiss.serialize_index(index).tobytes()) + + +@contextlib.contextmanager +def vector_byte_limit(value): + old_limit = faiss.get_deserialization_vector_byte_limit() + faiss.set_deserialization_vector_byte_limit(value) + try: + yield + finally: + faiss.set_deserialization_vector_byte_limit(old_limit) + + +@contextlib.contextmanager +def lattice_r2_limit(value): + old_limit = faiss.get_deserialization_lattice_r2_limit() + faiss.set_deserialization_lattice_r2_limit(value) + try: + yield + finally: + faiss.set_deserialization_lattice_r2_limit(old_limit) + + +def swig_default_construct(cls): + """Call the swig default constructor of cls. + + For IndexIVFFlat and IndexBinaryIVF, cls() raises IndexError in the + Python wrapper: add_ref_in_constructor(cls, 0) reads args[0], which the + default constructor does not have. + + The low-level module of swigfaiss, swigfaiss_avx2, swigfaiss_sve, ... is + _swigfaiss, _swigfaiss_avx2, _swigfaiss_sve, ...""" + module = sys.modules[cls.__module__] + swig_module = getattr(module, "_" + module.__name__.rpartition(".")[2]) + obj = cls.__new__(cls) + name = cls.__name__ + getattr(swig_module, name + "_swiginit")( + obj, getattr(swig_module, "new_" + name)() + ) + return obj + + +def make_random_data(d, n, seed=42): + return np.random.RandomState(seed).rand(n, d).astype("float32") + + +class FaissTestCase(unittest.TestCase): + @contextlib.contextmanager + def assertRaisesFaiss(self, expected_substr=None): + """Python form of EXPECT_THROW(..., faiss::FaissException). + + swig maps faiss::FaissException to RuntimeError with e.what() as the + message, std::bad_alloc to MemoryError, and any other std::exception + to RuntimeError with a "C++ exception " prefix. The prefix check + rejects a std::exception that is not a FaissException.""" + with self.assertRaises(RuntimeError) as cm: + yield + msg = str(cm.exception) + self.assertFalse(msg.startswith("C++ exception "), msg) + if expected_substr is not None: + self.assertIn(expected_substr, msg) + + def expect_read_throws(self, buf, expected_substr=None): + with self.assertRaisesFaiss(expected_substr): + read_index(buf) + + def expect_binary_read_throws(self, buf, expected_substr=None): + with self.assertRaisesFaiss(expected_substr): + read_index_binary(buf) + + def expect_vt_read_throws(self, buf, expected_substr=None): + with self.assertRaisesFaiss(expected_substr): + read_vector_transform(buf) + + def expect_invlists_read_throws(self, buf, expected_substr=None): + with self.assertRaisesFaiss(expected_substr): + read_invlists(buf) + + +class TestReadIndexDeserialize(FaissTestCase): + def test_pq_with_m_zero_divide_by_zero(self): + # ProductQuantizer with M=0 causes divide-by-zero in + # set_derived_values(). read_ProductQuantizer validates M > 0. + buf = bytearray() + push_fourcc(buf, "Imiq") + push_index_header(buf, 4, 0) + push_pq(buf, 4, 0, 8) + self.expect_read_throws(buf) + + def test_index_header_invalid_bool_encoding_is_trained(self): + # A non-{0,1} byte read into a bool is UB; READ1_BOOL must reject it. + buf = bytearray() + push_fourcc(buf, "IxF2") + push_index_header(buf, 4, 0) + # is_trained sits at offset 4 (fourcc) + 4 (d) + 8 (ntotal) + + # 8 (dummy) + 8 (dummy) = 32. + is_trained_offset = 32 + buf[is_trained_offset] = 0x02 + self.expect_read_throws(buf, "invalid bool encoding") + + def test_additive_quantizer_nbits_size_mismatch(self): + # AdditiveQuantizer with nbits.size() != M causes out-of-bounds + # access on nbits in set_derived_values(). + buf = bytearray() + push_fourcc(buf, "IPRf") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 10) # M = 10 + push_vector(buf, SIZE_T, [8]) # nbits: 1 element, should be 10 + push_val(buf, BOOL, True) # is_trained + push_vector(buf, FLOAT, []) # codebooks + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + self.expect_read_throws(buf, "nbits size") + + def test_residual_quantizer_old_nbits_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxRQ") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 5) # M = 5 + push_vector(buf, SIZE_T, [8, 8]) # nbits: 2 elements, should be 5 + self.expect_read_throws(buf, "nbits size") + + def test_pq_centroids_overflow(self): + # d * (1 << 24) overflows size_t; mul_no_overflow detects it. + buf = bytearray() + push_fourcc(buf, "Imiq") + huge_d = 1 << 48 + # The header d is (int)huge_d: the low 32 bits, which are 0. + push_index_header(buf, huge_d & 0xFFFFFFFF, 0) + push_pq(buf, huge_d, 1, 24) # M=1 so d % M == 0 + self.expect_read_throws(buf) + + def test_readvector_byte_limit(self): + # READVECTOR rejects a vector whose byte size reaches the + # deserialization byte limit. "LTra" (LinearTransform) format: + # fourcc + have_bias + READVECTOR(A) + READVECTOR(b) + d_in + d_out + # + is_trained. A contains 1024 floats = 4096 bytes. + # READVECTOR check: size < limit / sizeof(float) + d_in = 32 + d_out = 32 + n_elements = d_in * d_out + buf = bytearray() + push_fourcc(buf, "LTra") + push_val(buf, BOOL, False) # have_bias + push_vector(buf, FLOAT, [0.0] * n_elements) # A + push_vector(buf, FLOAT, []) # b + push_val(buf, INT, d_in) + push_val(buf, INT, d_out) + push_val(buf, BOOL, True) # is_trained + + # Exactly at the boundary: the check is strict less-than. + with vector_byte_limit(n_elements * 4): + with self.assertRaisesFaiss(): + read_vector_transform(buf) + # One element above the boundary passes. + with vector_byte_limit((n_elements + 1) * 4): + read_vector_transform(buf) + + def test_pq_centroids_byte_limit(self): + # d=8, M=1, nbits=8 -> ksub=256, centroids = 8*256 = 2048 floats. + # PQ check: n < limit / sizeof(float), where n = d * ksub = 2048. + d = 8 + M = 1 + nbits = 8 + n_elements = d * (1 << nbits) + buf = bytearray() + push_fourcc(buf, "Imiq") + push_index_header(buf, d, 0) + push_pq(buf, d, M, nbits, [0.0] * n_elements) + + with vector_byte_limit(n_elements * 4): + with self.assertRaisesFaiss(): + read_index(buf) + with vector_byte_limit((n_elements + 1) * 4): + read_index(buf) + + def test_index_lattice_nsq_zero_divide_by_zero(self): + # nsq=0 causes divide-by-zero in the constructor (dsq = d / nsq). + # "IxLa": fourcc + d + nsq + scale_nbit + r2 + index_header + # + READVECTOR(trained) + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 16) # d + push_val(buf, INT, 0) # nsq = 0 + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 14) # r2 + self.expect_read_throws(buf) + + def test_index_lattice_d_not_divisible_by_nsq(self): + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 17) # d = 17 (not divisible by nsq=4) + push_val(buf, INT, 4) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 14) # r2 + self.expect_read_throws(buf, "divisible by nsq") + + def test_index_lattice_r2_zero(self): + # r2=0 causes heap-buffer-overflow in the ZnSphereCodecRec ctor. + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 4) # d + push_val(buf, INT, 1) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 0) # r2 = 0 + self.expect_read_throws(buf, "r2") + + def test_index_lattice_dsq_not_power_of_2(self): + # d/nsq that is not a power of 2 >= 2 causes heap-buffer-overflow + # in the ZnSphereCodecRec ctor. d=3, nsq=1 -> dsq=3. + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 3) # d + push_val(buf, INT, 1) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 1) # r2 + self.expect_read_throws(buf, "power of 2") + + def test_index_lattice_dsq_one(self): + # d=1, nsq=1 -> dsq=1 (too small, causes cache_level=-1) + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 1) # d + push_val(buf, INT, 1) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 1) # r2 + self.expect_read_throws(buf, "power of 2") + + def test_index_lattice_r2_too_large(self): + # r2 too large causes a timeout in the ZnSphereCodecRec ctor + # (exponential codeword count in the decode cache). dsq=16 + # (log2_dim=4, cache_level=3) with r2=73 would take well over a + # minute of CPU time if not rejected. + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 16) # d + push_val(buf, INT, 1) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, 73) # r2 + self.expect_read_throws(buf, "decode cache") + + def test_index_lattice_r2_configurable_limit(self): + # deserialization_lattice_r2_limit caps the ZnSphereCodecRec + # decode-cache build cost for untrusted payloads, separately from + # the in-codec memory cap. d=4, nsq=1, scale_nbit=4 (dsq=4) passes + # the structural checks. The cap is "r2 > limit". + d = 4 + + def build(r2): + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, d) + push_val(buf, INT, 1) # nsq + push_val(buf, INT, 4) # scale_nbit + push_val(buf, INT, r2) + push_index_header(buf, d, 0) + push_vector(buf, FLOAT, []) # untrained: empty trained vector + return buf + + with lattice_r2_limit(2): + # r2 == limit: the ZnSphereCodecRec ctor runs to completion. + read_index(build(2)) + # r2 == limit + 1: rejected with the limit in the message. + self.expect_read_throws( + build(3), "deserialization_lattice_r2_limit" + ) + + def test_binary_unrecognized_fourcc(self): + buf = bytearray() + push_fourcc(buf, "ZZZZ") + self.expect_binary_read_throws(buf) + + def test_binary_flat_xb_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBxF") + push_binary_index_header(buf, 16, 1) + push_vector(buf, UINT8, []) # empty xb, ntotal=1 expects 2 bytes + self.expect_binary_read_throws(buf, "xb.size()") + + def test_binary_multi_hash_storage_cast_failure(self): + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, 99) + push_minimal_binary_flat(buf, 16) # ntotal=0, mismatches 99 + self.expect_binary_read_throws(buf) + + def test_binary_ivf_inv_list_nlist_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBwF") + push_binary_index_header(buf, 16, 0) + push_val(buf, SIZE_T, 10) # nlist = 10 + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_binary_flat(buf, 16) + push_empty_direct_map(buf) + # ArrayInvertedLists: "ilar" + nlist + code_size + sizes + push_fourcc(buf, "ilar") + push_val(buf, SIZE_T, 5) # nlist = 5 (mismatches IVF nlist=10) + push_val(buf, SIZE_T, 2) # code_size = d/8 + for _ in range(5): + push_val(buf, SIZE_T, 0) + self.expect_binary_read_throws(buf) + + def test_binary_hash_empty_invlist_buffer(self): + # An empty hash invlist buffer with a non-zero entry count would be + # dereferenced as null in read_binary_hash_invlists. + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + push_val(buf, INT, 4) # b + push_val(buf, INT, 0) # nflip + push_val(buf, SIZE_T, 1) # sz = 1 (non-zero) + push_val(buf, INT, 8) # il_nbit + push_vector(buf, UINT8, []) # empty buffer + self.expect_binary_read_throws(buf, "binary hash invlists") + + def test_nsg_negative_r(self): + buf = bytearray() + push_fourcc(buf, "INSf") + push_index_header(buf, 4, 0) + push_val(buf, INT, 0) # GK + push_val(buf, CHAR, 0) # build_type + push_val(buf, INT, 10) # nndescent_S + push_val(buf, INT, 10) # nndescent_R + push_val(buf, INT, 10) # nndescent_L + push_val(buf, INT, 1) # nndescent_iter + push_val(buf, INT, 0) # ntotal + push_val(buf, INT, -1) # R = -1 (invalid) + self.expect_read_throws(buf, "invalid NSG R") + + def test_scalar_quantizer_invalid_qtype(self): + buf = bytearray() + push_fourcc(buf, "IxSQ") + push_index_header(buf, 4, 0) + push_val(buf, INT, 99) # qtype = 99 (out of range) + self.expect_read_throws(buf, "qtype") + + def test_product_additive_quantizer_zero_nsplits(self): + buf = bytearray() + push_fourcc(buf, "IxPR") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 1) # M + push_vector(buf, SIZE_T, [8]) # nbits + push_val(buf, BOOL, True) # is_trained + # codebooks: d * total_codebook_size = 4 * 256 floats + push_vector(buf, FLOAT, [0.0] * (4 * 256)) + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + push_val(buf, SIZE_T, 0) # nsplits = 0 (invalid) + self.expect_read_throws(buf, "nsplits") + + def test_pre_transform_negative_chain_length(self): + buf = bytearray() + push_fourcc(buf, "IxPT") + push_index_header(buf, 4, 0) + push_val(buf, INT, -1) # nt = -1 (invalid) + self.expect_read_throws(buf, "chain length") + + def test_binary_multi_hash_zero_nhash(self): + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, 0) + push_minimal_binary_flat(buf, 16) + push_val(buf, INT, 4) # b + push_val(buf, INT, 0) # nhash = 0 (invalid) + self.expect_binary_read_throws(buf, "nhash") + + def test_binary_hash_b_zero(self): + # Without the b > 0 check, BitstringReader::read(0) would silently + # produce garbage hash values on every inverted-list entry. + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + push_val(buf, INT, 0) # b = 0 (invalid) + self.expect_binary_read_throws(buf, "IndexBinaryHash b=") + + def test_binary_hash_negative_il_nbit(self): + # A negative il_nbit would wrap to a huge size_t in the + # bits-per-entry calculation and read out of bounds in + # BitstringReader. + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + push_val(buf, INT, 4) # b + push_val(buf, INT, 0) # nflip + push_val(buf, SIZE_T, 0) # sz = 0 + push_val(buf, INT, -1) # il_nbit = -1 (invalid) + self.expect_binary_read_throws(buf, "il_nbit=") + + def test_binary_hash_il_nbit_zero_with_entries(self): + # With il_nbit=0 and sz > 0, every inverted-list size would read as + # 0 and corrupt the deserialized index. + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + push_val(buf, INT, 4) # b + push_val(buf, INT, 0) # nflip + push_val(buf, SIZE_T, 1) # sz = 1 (non-zero) + push_val(buf, INT, 0) # il_nbit = 0 (invalid when sz > 0) + self.expect_binary_read_throws(buf, "il_nbit=") + + def test_binary_hash_b_exceeds_code_size(self): + # A b larger than code_size*8 makes BitstringReader::read() access + # past the code buffer (heap-buffer-overflow). + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + # d=16 -> code_size=2 -> 16 bits available + push_val(buf, INT, 17) # b = 17 + self.expect_binary_read_throws(buf, "IndexBinaryHash b=") + + def test_binary_multi_hash_map_ilsz_exceeds_ntotal(self): + # ilsz values that sum to more than ntotal would make the inner + # loop read past the end of the BitstringReader buffer. + # ntotal=4 -> id_bits=2, b=4, sz=2 entries. + # Total bits = (b + id_bits) * sz + ntotal * id_bits = 20 -> 3 bytes + # Entry 0: hash=0, ilsz=3 (3 ids follow) + # Entry 1: hash=1, ilsz=3 -> total ilsz 6 > ntotal 4, throws here. + b = 4 + id_bits = 2 + ntotal = 4 + sz = 2 + nbit = (b + id_bits) * sz + ntotal * id_bits + bitbuf = pack_bits( + (nbit + 7) // 8, + [ + (0, b), + (3, id_bits), + (0, id_bits), + (0, id_bits), + (0, id_bits), + (1, b), + (3, id_bits), + ], + ) + + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, ntotal) + # Nested IBxF storage with matching ntotal (code_size = 2). + push_fourcc(buf, "IBxF") + push_binary_index_header(buf, 16, ntotal) + push_vector(buf, UINT8, [0] * (ntotal * 2)) + push_val(buf, INT, b) + push_val(buf, INT, 1) # nhash = 1 + push_val(buf, INT, 0) # nflip + # Multi hash map fields (1 map): + push_val(buf, INT, id_bits) + push_val(buf, SIZE_T, sz) + push_vector(buf, UINT8, bitbuf) + self.expect_binary_read_throws(buf, "would exceed ntotal") + + def test_binary_id_map_id_map_size_mismatch(self): + # IBMp with id_map size != ntotal. Without the check, + # construct_rev_map (IBM2) or search would use an inconsistent ID + # mapping. Outer ntotal=2, id_map has 5 entries. + buf = bytearray() + push_fourcc(buf, "IBMp") + push_binary_index_header(buf, 16, 2) + push_fourcc(buf, "IBxF") + push_binary_index_header(buf, 16, 2) + push_vector(buf, UINT8, [0] * (2 * 2)) # ntotal * code_size + push_vector(buf, INT64, [10, 20, 30, 40, 50]) + self.expect_binary_read_throws(buf, "id_map") + + def test_index_id_map2_id_map_size_mismatch(self): + # IxM2 with id_map size != ntotal. Without the check, + # construct_rev_map() reads past id_map bounds. + buf = bytearray() + push_fourcc(buf, "IxM2") + push_index_header(buf, 4, 2) + push_fourcc(buf, "IxF2") + push_index_header(buf, 4, 2) + # WRITEXBVECTOR: ntotal * d floats + num_floats = 2 * 4 + push_val(buf, SIZE_T, num_floats) + for _ in range(num_floats): + push_val(buf, FLOAT, 0.0) + push_vector(buf, INT64, [10, 20, 30, 40, 50]) + self.expect_read_throws(buf, "id_map") + + def test_block_inverted_lists_n_per_block_zero(self): + # n_per_block=0 causes divide-by-zero in resize() and add_entries(). + buf = bytearray() + push_fourcc(buf, "ilbl") + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 32) # code_size + push_val(buf, SIZE_T, 0) # n_per_block = 0 (invalid) + push_val(buf, SIZE_T, 128) # block_size + self.expect_invlists_read_throws(buf, "n_per_block") + + def test_block_inverted_lists_block_size_zero(self): + # block_size=0 causes divide-by-zero in add_entries(). + buf = bytearray() + push_fourcc(buf, "ilbl") + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 32) # code_size + push_val(buf, SIZE_T, 32) # n_per_block + push_val(buf, SIZE_T, 0) # block_size = 0 (invalid) + self.expect_invlists_read_throws(buf, "block_size") + + def test_block_inverted_lists_codes_size_mismatch(self): + # A codes size inconsistent with ids size, n_per_block and + # block_size would make search or add access past the codes buffer. + buf = bytearray() + push_fourcc(buf, "ilbl") + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 32) # code_size + push_val(buf, SIZE_T, 32) # n_per_block + push_val(buf, SIZE_T, 128) # block_size + # ids: 10 entries -> ceil(10/32) = 1 block -> codes = 128 bytes + push_vector(buf, INT64, [0] * 10) + push_vector(buf, UINT8, [0] * 64) # wrong, should be 128 + self.expect_invlists_read_throws(buf, "codes size") + + def test_block_inverted_lists_codes_overflow(self): + # n_block * block_size overflow. Without mul_no_overflow the product + # wraps and the size comparison passes spuriously. + buf = bytearray() + push_fourcc(buf, "ilbl") + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 32) # code_size + push_val(buf, SIZE_T, 1) # n_per_block + push_val(buf, SIZE_T, SIZE_MAX) # block_size + # ids: 2 entries -> n_block = 2 -> 2 * SIZE_MAX overflows + push_vector(buf, INT64, [0] * 2) + push_vector(buf, UINT8, []) # overflow is caught first + self.expect_invlists_read_throws(buf, "overflow") + + def test_pq_centroids_size_mismatch(self): + # PQ: d=4, M=2, nbits=8 -> ksub=256, expected centroids = 1024 + buf = bytearray() + push_fourcc(buf, "Imiq") + push_index_header(buf, 4, 0) + push_pq(buf, 4, 2, 8, [0.0] * 100) + self.expect_read_throws(buf, "centroids size") + + def test_sq_trained_size_mismatch(self): + # For QT_4bit, expected trained.size() = 2 * d. + buf = bytearray() + push_fourcc(buf, "IxSQ") + push_index_header(buf, 4, 0) + push_val(buf, INT, faiss.ScalarQuantizer.QT_4bit) + push_val(buf, INT, 0) # rangestat + push_val(buf, FLOAT, 0.0) # rangestat_arg + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 1) # code_size + push_vector(buf, FLOAT, [1.0, 2.0, 3.0]) # 3 floats, expected 8 + self.expect_read_throws(buf, "ScalarQuantizer trained size") + + def test_index_pq_codes_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxPq") + push_index_header(buf, 4, 2) + # PQ: d=4, M=2, nbits=8 -> code_size=2, ksub=256 + push_pq(buf, 4, 2, 8, [0.0] * (4 * 256)) + # codes should be ntotal * code_size = 4 bytes; provide 10 + push_vector(buf, UINT8, [0] * 10) + push_val(buf, INT, 0) # search_type + push_val(buf, INT, 0) # encode_signs + push_val(buf, INT, 0) # polysemous_ht + self.expect_read_throws(buf, "codes.size()") + + def test_index_residual_quantizer_codes_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxRq") + push_index_header(buf, 4, 2) + push_residual_quantizer(buf, 4, 1, [8]) + push_val(buf, SIZE_T, 1) # code_size (M=1, nbits=8) + push_vector(buf, UINT8, [0] * 10) # should be 2 bytes + self.expect_read_throws(buf, "codes.size()") + + def test_index_local_search_quantizer_codes_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxLS") + push_index_header(buf, 4, 2) + push_local_search_quantizer(buf, 4, 1, [8]) + push_val(buf, SIZE_T, 1) # code_size + push_vector(buf, UINT8, [0] * 10) # should be 2 bytes + self.expect_read_throws(buf, "codes.size()") + + def test_index_product_residual_quantizer_codes_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxPR") + push_index_header(buf, 4, 2) + push_additive_quantizer(buf, 4, 1, [8]) + push_val(buf, SIZE_T, 1) # nsplits = 1 + push_residual_quantizer(buf, 4, 1, [8]) # d_sub = d / nsplits + push_val(buf, SIZE_T, 1) # code_size + push_vector(buf, UINT8, [0] * 10) # should be 2 bytes + self.expect_read_throws(buf, "codes.size()") + + def test_index_product_local_search_quantizer_codes_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxPL") + push_index_header(buf, 4, 2) + push_additive_quantizer(buf, 4, 1, [8]) + push_val(buf, SIZE_T, 1) # nsplits = 1 + push_local_search_quantizer(buf, 4, 1, [8]) + push_val(buf, SIZE_T, 1) # code_size + push_vector(buf, UINT8, [0] * 10) # should be 2 bytes + self.expect_read_throws(buf, "codes.size()") + + def test_nn_descent_graph_size_mismatch(self): + # NNDescent: ntotal=2, K=3 -> expected graph size 6, provide 10. + buf = bytearray() + push_fourcc(buf, "INNf") + push_index_header(buf, 4, 2) + push_nndescent(buf, 2, 4, 3, True, [0] * 10) + self.expect_read_throws(buf, "NNDescent final_graph size") + + def test_nn_descent_graph_invalid_id(self): + # NNDescent: ntotal=2, K=2, graph size 4. ID 99 is out of [-1, 2). + buf = bytearray() + push_fourcc(buf, "INNf") + push_index_header(buf, 4, 2) + push_nndescent(buf, 2, 4, 2, True, [0, 1, 99, 0]) + self.expect_read_throws(buf, "out of range") + + def test_hnsw_levels_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IHNf") + push_index_header(buf, 4, 5) + push_minimal_hnsw(buf, 3) # 3 entries, mismatches ntotal=5 + self.expect_read_throws(buf, "HNSW levels size") + + def test_hnsw_storage_ntotal_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IHNf") + push_index_header(buf, 4, 3) + push_minimal_hnsw(buf, 3) + push_minimal_flat(buf, 4, 99) # storage ntotal=99 (mismatch) + self.expect_read_throws(buf, "HNSW storage ntotal") + + def test_hnsw_neighbor_negative_id(self): + # validate_HNSW must reject a negative neighbor ID other than -1. + ntotal, npn = 3, 2 + # Node 0: {1, -5} (-5 is invalid), node 1: {0, -1}, node 2: {0, -1} + neighbors = [1, -5, 0, -1, 0, -1] + buf = bytearray() + push_fourcc(buf, "IHNf") + push_index_header(buf, 4, ntotal) + push_hnsw_with_neighbors(buf, ntotal, npn, neighbors) + push_minimal_flat(buf, 4, ntotal) + self.expect_read_throws(buf, "HNSW neighbors") + + def test_hnsw_neighbor_id_too_large(self): + ntotal, npn = 3, 2 + neighbors = [1, 99, 0, -1, 0, -1] # 99 >= ntotal + buf = bytearray() + push_fourcc(buf, "IHNf") + push_index_header(buf, 4, ntotal) + push_hnsw_with_neighbors(buf, ntotal, npn, neighbors) + push_minimal_flat(buf, 4, ntotal) + self.expect_read_throws(buf, "HNSW neighbors") + + def test_hnsw_entry_point_out_of_range(self): + ntotal, npn = 3, 2 + neighbors = [1, -1, 0, -1, 0, -1] + buf = bytearray() + push_fourcc(buf, "IHNf") + push_index_header(buf, 4, ntotal) + push_hnsw_with_neighbors(buf, ntotal, npn, neighbors, entry_point=99) + push_minimal_flat(buf, 4, ntotal) + self.expect_read_throws(buf, "HNSW entry_point") + + def test_hnsw2_level_wrong_storage_type(self): + # IndexHNSW2Level storage must be Index2Layer or IndexIVFPQ, else a + # failed dynamic_cast leads to a null deref. + buf = bytearray() + push_fourcc(buf, "IHN2") + push_index_header(buf, 4, 0) + push_minimal_hnsw(buf, 0) + push_minimal_flat(buf, 4, 0) # IndexFlat storage: wrong type + self.expect_read_throws(buf, "Index2Layer or IndexIVFPQ") + + def test_index2_layer_null_quantizer_ownership(self): + # Index2Layer with a null quantizer ("null" fourcc) still sets + # own_fields=true. The read is truncated after nlist, so the next + # READ1 fails and triggers cleanup; with quantizer=nullptr the + # destructor must not crash. + buf = bytearray() + push_fourcc(buf, "Ix2L") + push_index_header(buf, 4, 0) + push_fourcc(buf, "null") # null sub-quantizer + push_val(buf, SIZE_T, 1) # nlist + self.expect_read_throws(buf) + + def test_hnsw2_level_null_storage(self): + buf = bytearray() + push_fourcc(buf, "IHN2") + push_index_header(buf, 4, 0) + push_minimal_hnsw(buf, 0) + push_fourcc(buf, "null") # null storage + self.expect_read_throws(buf, "non-null storage") + + def test_nsg_ntotal_mismatch(self): + buf = bytearray() + push_fourcc(buf, "INSf") + push_index_header(buf, 4, 5) + push_val(buf, INT, 0) # GK + push_val(buf, CHAR, 0) # build_type (char, not int) + push_val(buf, INT, 10) # nndescent_S + push_val(buf, INT, 10) # nndescent_R + push_val(buf, INT, 10) # nndescent_L + push_val(buf, INT, 1) # nndescent_iter + push_val(buf, INT, 3) # NSG ntotal=3 (mismatch with 5) + push_val(buf, INT, 2) # R + push_val(buf, INT, 10) # L + push_val(buf, INT, 10) # C + push_val(buf, INT, 10) # search_L + push_val(buf, INT, 0) # enterpoint + push_val(buf, BOOL, True) # is_built + # Graph: 3 nodes, R=2, all empty (EMPTY_ID terminates each) + for _ in range(3): + push_val(buf, INT, -1) + self.expect_read_throws(buf, "NSG ntotal") + + def test_nn_descent_ntotal_mismatch(self): + # NNDescent ntotal=3 (mismatch with index ntotal=5). The graph is + # internally valid: K=2, 6 entries all in range. + buf = bytearray() + push_fourcc(buf, "INNf") + push_index_header(buf, 4, 5) + push_nndescent(buf, 3, 4, 2, True, [0, 1, 0, 2, 1, 2]) + self.expect_read_throws(buf, "NNDescent ntotal") + + def test_hnsw_cagra_empty_index_search(self): + # base_level_only search on an empty index must not access + # uninitialized graph nodes. + idx = faiss.IndexHNSWCagra(4, 16) + idx.base_level_only = True + _, labels = idx.search(np.ones((1, 4), dtype="float32"), 1) + self.assertEqual(labels[0, 0], -1) + + def test_index_ivf_null_invlists_search(self): + # Search with null invlists (e.g. loaded with IO_FLAG_SKIP_IVF_DATA) + # throws instead of crashing. + quantizer = faiss.IndexFlatL2(4) + idx = faiss.IndexIVFFlat(quantizer, 4, 10) + idx.own_fields = False + idx.is_trained = True + idx.replace_invlists(None, False) + with self.assertRaisesFaiss("inverted lists"): + idx.search(np.ones((1, 4), dtype="float32"), 1) + + def test_index_ivf_null_invlists_add(self): + quantizer = faiss.IndexFlatL2(4) + idx = faiss.IndexIVFFlat(quantizer, 4, 10) + idx.own_fields = False + idx.is_trained = True + idx.replace_invlists(None, False) + with self.assertRaisesFaiss("inverted lists"): + idx.add(np.ones((1, 4), dtype="float32")) + + # IVF quantizer ntotal / nlist acceptance tests. The quantizer may + # legitimately have ntotal != nlist (sharded indexes, custom inverted + # list management, untrained quantizers). + + def _ivf_flat_with_quantizer_ntotal(self, nlist, quantizer_ntotal): + buf = bytearray() + push_fourcc(buf, "IwFl") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, nlist) + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_flat(buf, 4, quantizer_ntotal) + push_empty_direct_map(buf) + push_null_invlists(buf) + return buf + + def test_ivf_quantizer_ntotal_not_nlist_accepted(self): + # shard_ivf_index_centroids() produces ntotal > nlist (all centroids + # spread across shards) and 0 < ntotal < nlist (one shard's subset). + # The search-time key < nlist check prevents OOB access. + for nlist, ntotal in [(2, 5), (10, 3), (10, 0)]: + with self.subTest(nlist=nlist, ntotal=ntotal): + read_index(self._ivf_flat_with_quantizer_ntotal(nlist, ntotal)) + + def test_ivf_scalar_quantizer_untrained_search_rejected(self): + # Empty trained vector with is_trained=false deserializes (a + # legitimate untrained index), but searching it throws because + # IndexIVF checks is_trained. + buf = bytearray() + push_fourcc(buf, "IwSq") + push_index_header(buf, 4, 0, is_trained=False) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_flat(buf, 4) + push_empty_direct_map(buf) + push_val(buf, INT, 0) # qtype = QT_8bit + push_val(buf, INT, 0) # rangestat + push_val(buf, FLOAT, 0.0) # rangestat_arg + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 4) # code_size + push_vector(buf, FLOAT, []) # trained (empty: untrained) + push_val(buf, SIZE_T, 4) # IwSq code_size + push_val(buf, BOOL, False) # by_residual + push_null_invlists(buf) + + idx = read_index(buf) + self.assertFalse(idx.is_trained) + + xq = np.zeros((1, 4), dtype="float32") + with self.assertRaisesFaiss(): + idx.search(xq, 1) + with self.assertRaisesFaiss(): + idx.range_search(xq, 1.0) + + key = np.zeros((1, 1), dtype="int64") + coarse_dis = np.zeros((1, 1), dtype="float32") + with self.assertRaisesFaiss(): + idx.search_preassigned(xq, 1, key, coarse_dis) + with self.assertRaisesFaiss(): + idx.range_search_preassigned(xq, 1.0, key, coarse_dis) + + def test_ivfpq_null_quantizer_precompute_table_rejected(self): + # initialize_IVFPQ_precomputed_table rejects a null quantizer, which + # corrupt data produces with a "null" quantizer fourcc. + pq = faiss.ProductQuantizer(4, 1, 8) + use_precomputed_table = np.zeros(1, dtype="int32") + with self.assertRaisesFaiss(): + faiss.initialize_IVFPQ_precomputed_table( + faiss.swig_ptr(use_precomputed_table), + None, + pq, + faiss.AlignedTableFloat32(), + True, # by_residual + False, # verbose + ) + + def _ivf_flat_with_null_quantizer(self): + ivf = swig_default_construct(faiss.IndexIVFFlat) + ivf.quantizer = None + return ivf + + def test_ivf_null_quantizer_search_rejected(self): + ivf = self._ivf_flat_with_null_quantizer() + ivf.is_trained = True + with self.assertRaisesFaiss(): + ivf.search(np.zeros((1, ivf.d), dtype="float32"), 1) + + def test_ivf_null_quantizer_range_search_rejected(self): + ivf = self._ivf_flat_with_null_quantizer() + ivf.is_trained = True + with self.assertRaisesFaiss(): + ivf.range_search(np.zeros((1, ivf.d), dtype="float32"), 1.0) + + def test_ivf_null_quantizer_add_rejected(self): + ivf = self._ivf_flat_with_null_quantizer() + with self.assertRaisesFaiss(): + ivf.add(np.zeros((1, ivf.d), dtype="float32")) + + def test_ivf_null_quantizer_train_rejected(self): + ivf = self._ivf_flat_with_null_quantizer() + with self.assertRaisesFaiss(): + ivf.train(np.zeros((1, ivf.d), dtype="float32")) + + def test_normalization_transform_din_dout_mismatch(self): + # d_in != d_out makes memcpy overflow the output buffer in + # apply_noalloc. + buf = bytearray() + push_fourcc(buf, "VNrm") + push_val(buf, FLOAT, 2.0) # norm (L2) + push_val(buf, INT, 16) # d_in + push_val(buf, INT, 8) # d_out (mismatch) + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "d_in == d_out") + + def test_centering_transform_din_dout_mismatch(self): + buf = bytearray() + push_fourcc(buf, "VCnt") + push_vector(buf, FLOAT, [0.0] * 16) # mean + push_val(buf, INT, 16) # d_in + push_val(buf, INT, 8) # d_out (mismatch) + push_val(buf, BOOL, True) + self.expect_vt_read_throws(buf, "d_in == d_out") + + def test_pre_transform_chain_dimension_mismatch(self): + # A NormalizationTransform (d_in=d_out=4) followed by a sub-index + # with d=8: the chain's d_out (4) != sub-index d (8). + buf = bytearray() + push_fourcc(buf, "IxPT") + push_index_header(buf, 4, 0) + push_val(buf, INT, 1) # nt = 1 transform + push_fourcc(buf, "VNrm") + push_val(buf, FLOAT, 2.0) + push_val(buf, INT, 4) # d_in + push_val(buf, INT, 4) # d_out + push_val(buf, BOOL, True) + push_minimal_flat(buf, 8) + self.expect_read_throws(buf, "d_out=4") + + def test_pre_transform_empty_chain_dimension_mismatch(self): + # With no transform, reconstruct() hands the caller's buffer, sized + # from the outer d, straight to the sub-index, so a larger sub-index + # d is a heap overflow (T287094917). + buf = bytearray() + push_fourcc(buf, "IxPT") + push_index_header(buf, 4, 0) + push_val(buf, INT, 0) # nt = 0, empty chain + push_minimal_flat(buf, 8) + self.expect_read_throws(buf, "IndexPreTransform empty chain") + + def test_hadamard_rotation_invalid_dout(self): + buf = bytearray() + push_fourcc(buf, "HRot") + push_val(buf, INT, 42) # seed + push_val(buf, INT, 16) # d_in + push_val(buf, INT, 1 << 21) # d_out (not the power of 2 for d_in) + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "d_out must be the smallest power of 2") + + def test_hadamard_rotation_din_zero(self): + buf = bytearray() + push_fourcc(buf, "HRot") + push_val(buf, INT, 42) # seed + push_val(buf, INT, 0) # d_in = 0 (invalid) + push_val(buf, INT, 1) # d_out + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "HadamardRotation d_in=") + + def test_hadamard_rotation_hr64_invalid_dout(self): + # HR64: as HRot, with d_out the smallest multiple of 64 >= d_in + buf = bytearray() + push_fourcc(buf, "HR64") + push_val(buf, INT, 42) # seed + push_val(buf, INT, 100) # d_in + push_val(buf, INT, 256) # d_out (should be 128) + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws( + buf, "d_out must be the smallest multiple of 64 >= d_in") + + def test_hadamard_rotation_hr64_din_zero(self): + buf = bytearray() + push_fourcc(buf, "HR64") + push_val(buf, INT, 42) # seed + push_val(buf, INT, 0) # d_in = 0 (invalid) + push_val(buf, INT, 64) # d_out + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "HadamardRotation d_in=") + + def test_remap_dimensions_transform_map_too_small(self): + buf = bytearray() + push_fourcc(buf, "RmDT") + push_vector(buf, INT, [0, 1]) # map with 2 entries + push_val(buf, INT, 4) # d_in + push_val(buf, INT, 10) # d_out = 10 > map.size()=2 + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "RemapDimensionsTransform map size") + + def test_centering_transform_mean_too_small(self): + buf = bytearray() + push_fourcc(buf, "VCnt") + push_vector(buf, FLOAT, [1.0, 2.0]) # mean with 2 entries + push_val(buf, INT, 8) # d_in = 8 > mean.size()=2 + push_val(buf, INT, 8) # d_out + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "CenteringTransform mean size") + + def test_itq_transform_mean_too_small(self): + buf = bytearray() + push_fourcc(buf, "Viqt") + push_vector(buf, FLOAT, [1.0]) # mean with 1 entry + push_val(buf, BOOL, False) # do_pca + # Sub-VT 1: ITQMatrix ("Viqm") + push_fourcc(buf, "Viqm") + push_val(buf, INT, 10) # max_iter + push_val(buf, INT, 42) # seed + push_val(buf, BOOL, False) # have_bias + push_vector(buf, FLOAT, []) # A + push_vector(buf, FLOAT, []) # b + push_val(buf, INT, 0) # d_in + push_val(buf, INT, 0) # d_out + push_val(buf, BOOL, True) # is_trained + # Sub-VT 2: LinearTransform ("LTra") + push_fourcc(buf, "LTra") + push_val(buf, BOOL, False) # have_bias + push_vector(buf, FLOAT, []) # A + push_vector(buf, FLOAT, []) # b + push_val(buf, INT, 0) # d_in + push_val(buf, INT, 0) # d_out + push_val(buf, BOOL, True) # is_trained + # Outer Viqt footer + push_val(buf, INT, 4) # d_in = 4 > mean.size()=1 + push_val(buf, INT, 4) # d_out + push_val(buf, BOOL, True) # is_trained + self.expect_vt_read_throws(buf, "ITQTransform mean size") + + def test_inverted_list_oversized_entry(self): + # An inverted list entry over the byte limit is rejected. Corrupt + # data would otherwise cause OOM through an unchecked + # vector::resize in read_InvertedLists_up. + with vector_byte_limit(1024): # 1 KB limit + buf = bytearray() + push_fourcc(buf, "IwFl") + push_ivf_header(buf, 4) + # "ilar" inverted lists with 1 list, code_size=16 + push_fourcc(buf, "ilar") + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 16) # code_size + push_fourcc(buf, "full") # "full" list type + push_val(buf, SIZE_T, 1) # sizes vector length + push_val(buf, SIZE_T, 1 << 40) # sizes[0] = 1 TB + self.expect_read_throws(buf, "deserialization byte limit") + + @unittest.skipIf( + sys.platform == "win32", + "OnDiskInvertedLists is unsupported on Windows.", + ) + def test_on_disk_inverted_lists_short_lists_vector_rejected(self): + buf = bytearray() + push_fourcc(buf, "IwFl") + push_ivf_header(buf, 4) + push_fourcc(buf, "ilod") + push_val(buf, SIZE_T, 1) # nlist = 1 + push_val(buf, SIZE_T, 16) # code_size + push_val(buf, SIZE_T, 0) # lists: empty, inconsistent with nlist + self.expect_read_throws(buf, "read 0 lists for nlist 1") + + # RaBitQ qb validation. qb=0 is valid for Ixrq / Ixrr / Iwrq / Iwrr: it + # disables query quantization and uses raw fp32 values (see the qb + # comment in IndexRaBitQ.h / IndexIVFRaBitQ.h and + # RaBitQDistanceComputerNotQ). qb=0 is not supported for the FastScan + # variants Irfn / Iwrn, which need quantized queries for SIMD. + + def _rabitq_flat_buf(self, fourcc, multibit, qb): + buf = bytearray() + push_fourcc(buf, fourcc) + push_index_header(buf, 4, 0) + if multibit: + push_rabitq_multibit(buf, 4) + else: + push_rabitq(buf, 4) + push_vector(buf, UINT8, []) # codes + push_vector(buf, FLOAT, [0, 0, 0, 0]) # center + push_val(buf, UINT8, qb) + return buf + + def test_rabitq_qb_too_large_ixrq(self): + buf = self._rabitq_flat_buf("Ixrq", False, 9) # qb = 9 > 8 + self.expect_read_throws(buf, "RaBitQ qb=") + + def test_rabitq_qb_zero_accepted_ixrq(self): + read_index(self._rabitq_flat_buf("Ixrq", False, 0)) + + def test_rabitq_qb_too_large_ixrr(self): + buf = self._rabitq_flat_buf("Ixrr", True, 9) + self.expect_read_throws(buf, "RaBitQ qb=") + + def test_rabitq_qb_zero_accepted_ixrr(self): + read_index(self._rabitq_flat_buf("Ixrr", True, 0)) + + def _rabitq_fastscan_buf(self, qb): + buf = bytearray() + push_fourcc(buf, "Irfn") + push_index_header(buf, 4, 0) + push_rabitq_multibit(buf, 4) + push_vector(buf, FLOAT, [0, 0, 0, 0]) # center + push_val(buf, UINT8, qb) + return buf + + def test_rabitq_qb_too_large_irfn(self): + self.expect_read_throws(self._rabitq_fastscan_buf(9), "RaBitQ qb=") + + def test_rabitq_qb_zero_rejected_irfn(self): + self.expect_read_throws(self._rabitq_fastscan_buf(0), "RaBitQ qb=") + + def _ivf_rabitq_buf(self, fourcc, multibit, qb, with_invlists): + buf = bytearray() + push_fourcc(buf, fourcc) + push_ivf_header(buf, 4) + if multibit: + push_rabitq_multibit(buf, 4) + else: + push_rabitq(buf, 4) + push_val(buf, SIZE_T, 1) # code_size + push_val(buf, BOOL, False) # by_residual + push_val(buf, UINT8, qb) + if with_invlists: + push_null_invlists(buf) + return buf + + def test_rabitq_qb_too_large_iwrq(self): + buf = self._ivf_rabitq_buf("Iwrq", False, 9, False) + self.expect_read_throws(buf, "RaBitQ qb=") + + def test_rabitq_qb_zero_accepted_iwrq(self): + read_index(self._ivf_rabitq_buf("Iwrq", False, 0, True)) + + def test_rabitq_qb_too_large_iwrr(self): + buf = self._ivf_rabitq_buf("Iwrr", True, 9, False) + self.expect_read_throws(buf, "RaBitQ qb=") + + def test_rabitq_qb_zero_accepted_iwrr(self): + read_index(self._ivf_rabitq_buf("Iwrr", True, 0, True)) + + @unittest.skipUnless( + hasattr(faiss, "IndexIVFRaBitQSSD"), "requires disk IVF") + def test_ivf_rabitq_ssd_unsupported_metric(self): + buf = bytearray() + push_fourcc(buf, "IwDr") + push_index_header(buf, 64, 0, metric_type=faiss.METRIC_L1) + push_val(buf, FLOAT, 0.0) # metric_arg for metric_type > 1 + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_flat(buf, 64) + push_empty_direct_map(buf) + push_val(buf, SIZE_T, 64) # rabitq.d + push_val(buf, SIZE_T, 1) # rabitq.code_size + push_val(buf, INT, faiss.METRIC_L1) # rabitq.metric_type + push_val(buf, SIZE_T, 2) # rabitq.nb_bits + self.expect_read_throws(buf, "IndexIVFRaBitQSSD: unsupported metric") + + def _ivf_rabitq_fastscan_buf(self, qb): + buf = bytearray() + push_fourcc(buf, "Iwrn") + push_ivf_header(buf, 4) + push_rabitq_multibit(buf, 4) + push_val(buf, BOOL, False) # by_residual + push_val(buf, SIZE_T, 1) # code_size + push_val(buf, INT, 32) # bbs + push_val(buf, SIZE_T, 0) # qbs2 + push_val(buf, SIZE_T, 1) # M2 + push_val(buf, INT, 0) # implem + push_val(buf, UINT8, qb) + return buf + + def test_rabitq_qb_too_large_iwrn(self): + self.expect_read_throws(self._ivf_rabitq_fastscan_buf(9), "RaBitQ qb=") + + def test_rabitq_qb_zero_rejected_iwrn(self): + self.expect_read_throws(self._ivf_rabitq_fastscan_buf(0), "RaBitQ qb=") + + def test_binary_header_dimension_not_multiple_of8(self): + buf = bytearray() + push_fourcc(buf, "IBxF") + push_val(buf, INT, 17) # d = 17 (not multiple of 8) + push_val(buf, INT, 2) # code_size + push_val(buf, INT64, 0) # ntotal + push_val(buf, BOOL, True) # is_trained + push_val(buf, INT, 1) # metric_type + self.expect_binary_read_throws(buf, "multiple of 8") + + def test_binary_header_code_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBxF") + push_val(buf, INT, 16) # d = 16 + push_val(buf, INT, 5) # code_size = 5 (should be 2) + push_val(buf, INT64, 0) # ntotal + push_val(buf, BOOL, True) # is_trained + push_val(buf, INT, 1) # metric_type + self.expect_binary_read_throws(buf, "code_size") + + def test_binary_hnsw_levels_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBHf") + push_binary_index_header(buf, 16, 5) + push_minimal_hnsw(buf, 3) # 3 != 5 + self.expect_binary_read_throws(buf, "HNSW levels size") + + def test_binary_hnsw_storage_ntotal_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBHf") + push_binary_index_header(buf, 16, 3) + push_minimal_hnsw(buf, 3) + push_minimal_binary_flat(buf, 16) # ntotal=0 != 3 + self.expect_binary_read_throws(buf, "storage ntotal") + + def _push_binary_ivf_storage(self, buf): + # Nest an IBwF (IVF) instead of IBxF (flat) + push_fourcc(buf, "IBwF") + push_binary_index_header(buf, 16, 0) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_minimal_binary_flat(buf, 16) # quantizer + push_empty_direct_map(buf) + push_null_invlists(buf) + + def test_binary_hnsw_storage_not_flat(self): + buf = bytearray() + push_fourcc(buf, "IBHf") + push_binary_index_header(buf, 16, 0) + push_minimal_hnsw(buf, 0) + self._push_binary_ivf_storage(buf) + self.expect_binary_read_throws(buf, "IndexBinaryFlat storage") + + def _push_binary_hnsw_cagra_prefix(self, buf, ntotal): + push_fourcc(buf, "IBHc") + push_binary_index_header(buf, 16, ntotal) + push_val(buf, BOOL, True) # keep_max_size_level0 + push_val(buf, BOOL, False) # base_level_only + push_val(buf, INT, 10) # num_base_level_search_entrypoints + + def test_binary_hnsw_cagra_levels_size_mismatch(self): + buf = bytearray() + self._push_binary_hnsw_cagra_prefix(buf, 5) + push_minimal_hnsw(buf, 3) # 3 != 5 + self.expect_binary_read_throws(buf, "HNSW levels size") + + def test_binary_hnsw_cagra_storage_not_flat(self): + buf = bytearray() + self._push_binary_hnsw_cagra_prefix(buf, 0) + push_minimal_hnsw(buf, 0) + self._push_binary_ivf_storage(buf) + self.expect_binary_read_throws(buf, "IndexBinaryFlat storage") + + def test_binary_hnsw_cagra_storage_ntotal_mismatch(self): + buf = bytearray() + self._push_binary_hnsw_cagra_prefix(buf, 3) + push_minimal_hnsw(buf, 3) + push_minimal_binary_flat(buf, 16) # ntotal=0 != 3 + self.expect_binary_read_throws(buf, "storage ntotal") + + def test_binary_hash_invlists_vecs_size_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IBHh") + push_binary_index_header(buf, 16, 0) + push_val(buf, INT, 4) # b + push_val(buf, INT, 0) # nflip + # hash invlists with 1 entry + push_val(buf, SIZE_T, 1) # sz = 1 + push_val(buf, INT, 8) # il_nbit = 8 + # Bitstring: 1 entry needs (b + il_nbit) = 12 bits -> 2 bytes + # hash = 0, ilsz = 1 + push_vector(buf, UINT8, pack_bits(2, [(0, 4), (1, 8)])) + push_vector(buf, INT64, [0]) # ids: 1 entry + push_vector(buf, UINT8, [0, 0, 0]) # vecs: 3 bytes, code_size=2 + self.expect_binary_read_throws(buf, "binary hash invlists: vecs size") + + def test_binary_multi_hash_map_id_out_of_range(self): + # IBHm with ntotal=1, one map containing id=1 (>= ntotal). + b = 4 + id_bits = 1 + ntotal = 1 + sz = 1 + # bits: (b + id_bits) * sz + 1 * id_bits = 6 bits -> 1 byte + nbit = (b + id_bits) * sz + 1 * id_bits + # hash = 0, ilsz = 1, id = 1 (>= ntotal=1, invalid) + bitbuf = pack_bits( + (nbit + 7) // 8, [(0, b), (1, id_bits), (1, id_bits)] + ) + + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, ntotal) + push_fourcc(buf, "IBxF") + push_binary_index_header(buf, 16, ntotal) + push_vector(buf, UINT8, [0] * (ntotal * 2)) # code_size=2 + push_val(buf, INT, b) + push_val(buf, INT, 1) # nhash = 1 + push_val(buf, INT, 0) # nflip + # Multi hash map fields (1 map): + push_val(buf, INT, id_bits) + push_val(buf, SIZE_T, sz) + push_vector(buf, UINT8, bitbuf) + self.expect_binary_read_throws(buf, "multi hash map: id=") + + def test_binary_multi_hash_b_zero(self): + # b must be positive: BitstringReader::read(0) produces garbage hash + # values and b is the bit width for hash extraction. + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, 0) + push_minimal_binary_flat(buf, 16) + push_val(buf, INT, 0) # b = 0 (invalid) + self.expect_binary_read_throws(buf, "IndexBinaryMultiHash b=") + + def test_binary_multi_hash_nhash_times_b_exceeds_code_size(self): + # nhash * b must not exceed code_size * 8, otherwise + # BitstringReader overflows the query buffer during search. + buf = bytearray() + push_fourcc(buf, "IBHm") + push_binary_index_header(buf, 16, 0) + push_minimal_binary_flat(buf, 16) + push_val(buf, INT, 12) # b = 12 + # nhash = 2 => nhash*b = 24 > code_size*8 = 16 (code_size = d/8) + push_val(buf, INT, 2) + self.expect_binary_read_throws(buf, "exceeds code_size") + + def test_binary_hnsw_get_distance_computer_non_flat_throws(self): + idx = faiss.IndexBinaryHNSW() + idx.storage = None + idx.own_fields = False + with self.assertRaisesFaiss("IndexBinaryFlat"): + idx.get_distance_computer() + + def test_binary_hnsw_cagra_empty_index_search(self): + idx = faiss.IndexBinaryHNSWCagra(16, 4) + idx.base_level_only = True + query = np.zeros((1, 2), dtype="uint8") # d=16 -> code_size=2 + with self.assertRaisesFaiss("empty index"): + idx.search(query, 1) + + def test_binary_hnsw_cagra_zero_entrypoints(self): + idx = faiss.IndexBinaryHNSWCagra(16, 4) + # add requires base_level_only == false + idx.add(np.full((1, 2), 0xFF, dtype="uint8")) + idx.base_level_only = True + idx.num_base_level_search_entrypoints = 0 + query = np.zeros((1, 2), dtype="uint8") + with self.assertRaisesFaiss("num_base_level_search_entrypoints"): + idx.search(query, 1) + + def test_residual_coarse_quantizer_huge_ntotal(self): + # Huge ntotal triggers the centroid_norms byte limit check (guard on + # ntotal vs byte_limit/sizeof(float)). + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 1 << 60) # would cause OOM in search() + push_residual_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, FLOAT, -1.0) # beam_factor = -1 (skip tables) + self.expect_read_throws(buf, "centroid norms allocation") + + def test_residual_coarse_quantizer_ntotal_times_m(self): + # ntotal * M exceeds the byte limit even when ntotal alone passes + # the centroid_norms check: 200000 < 1MB/4 = 262144, but + # ntotal*M*sizeof(int32_t) = 200000*2*4 = 1600000 > 1MB. + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 200000) + push_residual_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, FLOAT, -1.0) # beam_factor = -1 (skip tables) + with vector_byte_limit(1 << 20): # 1 MB + self.expect_read_throws(buf, "deserialization vector byte limit") + + def test_residual_coarse_quantizer_huge_beam_factor(self): + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 16) + push_residual_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, FLOAT, 1e10) # beam_factor = 1e10 (way too large) + self.expect_read_throws(buf, "beam_factor") + + def test_residual_quantizer_max_beam_size_zero(self): + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 16) + push_additive_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, INT, 2048) # train_type = Skip_codebook_tables + push_val(buf, INT, 0) # max_beam_size = 0 (invalid) + self.expect_read_throws(buf, "max_beam_size") + + def test_residual_quantizer_huge_max_beam_size(self): + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 16) + push_additive_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, INT, 2048) # train_type = Skip_codebook_tables + push_val(buf, INT, 1 << 30) # max_beam_size = 2^30 (huge) + with vector_byte_limit(1 << 20): # 1 MB + self.expect_read_throws(buf, "deserialization vector byte limit") + + def test_residual_coarse_quantizer_negative_ntotal(self): + # read_index_header rejects a negative ntotal. + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, -1) + push_residual_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, FLOAT, -1.0) # beam_factor + self.expect_read_throws(buf, "invalid ntotal") + + def test_additive_quantizer_m_zero(self): + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 16) + push_additive_quantizer(buf, 4, 0, []) # M=0 + push_val(buf, INT, 2048) # train_type = Skip_codebook_tables + push_val(buf, INT, 1) # max_beam_size + self.expect_read_throws(buf, "invalid AdditiveQuantizer M") + + def test_residual_coarse_quantizer_ntotal_zero(self): + # An ntotal inconsistent with the codebooks is rejected before the + # centroid norms are computed. + buf = bytearray() + push_fourcc(buf, "ImRQ") + push_index_header(buf, 4, 0) + push_residual_quantizer(buf, 4, 2, [4, 4]) + push_val(buf, FLOAT, -1.0) # beam_factor = -1 (skip tables) + self.expect_read_throws(buf, "inconsistent with 2^tot_bits") + + def test_binary_ivf_null_invlists_search(self): + idx = swig_default_construct(faiss.IndexBinaryIVF) + idx.d = 16 + idx.code_size = 2 + idx.invlists = None + idx.own_invlists = False + query = np.zeros((1, 2), dtype="uint8") + with self.assertRaisesFaiss("inverted lists"): + idx.search(query, 1) + + def _vnrm_buf(self, d_in, d_out): + buf = bytearray() + push_fourcc(buf, "VNrm") + push_val(buf, FLOAT, 2.0) + push_val(buf, INT, d_in) + push_val(buf, INT, d_out) + push_val(buf, BOOL, True) + return buf + + def test_vector_transform_dim_exceeds_byte_limit(self): + # d_in=1024, d_out=1024 => d_in*d_out = 1M floats = 4 MB > 1 MB. + buf = self._vnrm_buf(1024, 1024) + with vector_byte_limit(1 << 20): + self.expect_vt_read_throws(buf) + + def test_vector_transform_dim_within_byte_limit(self): + # d_in=16, d_out=16 => 256 floats = 1 KB < 1 MB. + buf = self._vnrm_buf(16, 16) + with vector_byte_limit(1 << 20): + read_vector_transform(buf) + + def _corrupt_iwiq_vt_dimension(self, field_offset): + # Serialize a valid IndexIVFIndependentQuantizer, locate the VNrm + # fourcc and overwrite one VT dimension with d + 1. + # VNrm layout: fourcc(4) + norm(4) + d_in(4) + d_out(4) + + # is_trained(1) + d = 16 + nlist = 4 + quantizer = faiss.IndexFlat(d) + ivf = faiss.IndexIVFFlat(quantizer, d, nlist) + ivf.own_fields = False + vt = faiss.NormalizationTransform(d) + indep = faiss.IndexIVFIndependentQuantizer(quantizer, ivf, vt) + indep.own_fields = False + + data = serialize_index(indep) + vnrm_pos = data.find(b"VNrm") + self.assertGreaterEqual(vnrm_pos, 0) + corrupted = bytearray(data) + struct.pack_into(" + # ksub=16, centroids size = d*ksub = 64 floats. + buf = bytearray() + push_fourcc(buf, "IPfs") + push_index_header(buf, 4, 0) + push_pq(buf, 4, 2, 4, [0.0] * 64) + push_val(buf, INT, 0) # implem + push_val(buf, INT, bbs) + push_val(buf, INT, qbs) + push_val(buf, SIZE_T, 0) # ntotal2 + push_val(buf, SIZE_T, M2) + push_vector(buf, UINT8, []) # codes + return buf + + def _build_aq_fast_scan_buf(self, fastscan_M=3, fastscan_ksub=16, qbs=0): + # Minimal valid IndexResidualQuantizerFastScan ("IRfs"): + # AdditiveQuantizer + ResidualQuantizer fields, then FastScan fields. + buf = bytearray() + push_fourcc(buf, "IRfs") + push_index_header(buf, 4, 0) + # AdditiveQuantizer fields: + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 1) # M (AQ M, not FastScan M) + push_vector(buf, SIZE_T, [4]) # nbits + push_val(buf, BOOL, False) # is_trained + push_vector(buf, FLOAT, [0.0] * 64) # codebooks (d*16) + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + # ResidualQuantizer extras: + push_val(buf, INT, 2048) # train_type = Skip_codebook_tables + push_val(buf, INT, 1) # max_beam_size + # FastScan fields (IndexAdditiveQuantizerFastScan): + push_val(buf, INT, 0) # implem + push_val(buf, INT, 32) # bbs + push_val(buf, INT, qbs) + push_val(buf, SIZE_T, fastscan_M) # M + push_val(buf, SIZE_T, 4) # nbits + push_val(buf, SIZE_T, fastscan_ksub) # ksub + push_val(buf, SIZE_T, 2) # code_size + push_val(buf, SIZE_T, 0) # ntotal2 + # M2 = roundup(M, 2) in size_t arithmetic (wraps to 0 for + # M = SIZE_MAX). + push_val(buf, SIZE_T, ((fastscan_M + 1) & ~1) & SIZE_MAX) + push_val(buf, BOOL, True) # rescale_norm + push_val(buf, INT, 1) # norm_scale + push_val(buf, SIZE_T, 48) # max_train_points + push_vector(buf, UINT8, []) # codes + return buf + + def test_index_pq_fast_scan_bbs_zero(self): + # Without this check, search() would divide by zero in ntotal2/bbs. + buf = self._build_index_pq_fast_scan_buf(bbs=0) + self.expect_read_throws(buf, "invalid bbs") + + def test_index_pq_fast_scan_bbs_not_aligned(self): + # bbs not a multiple of 32. + buf = self._build_index_pq_fast_scan_buf(bbs=33) + self.expect_read_throws(buf, "invalid bbs") + + def test_index_pq_fast_scan_m2_zero(self): + # M2 must equal roundup(M, 2). M2=0 while M>0 makes + # compute_quantized_LUT write M*ksub bytes into a buffer sized for + # M2*ksub=0 bytes. + buf = self._build_index_pq_fast_scan_buf(bbs=32, M2=0) + self.expect_read_throws(buf, "invalid M2") + + def test_aq_fast_scan_m_zero(self): + # Without this check, search() would crash in compute_float_LUT. + buf = self._build_aq_fast_scan_buf(fastscan_M=0) + self.expect_read_throws(buf, "invalid quantizer state") + + def test_aq_fast_scan_ksub_zero(self): + buf = self._build_aq_fast_scan_buf(fastscan_M=3, fastscan_ksub=0) + self.expect_read_throws(buf, "invalid quantizer state") + + def test_aq_fast_scan_ksub_m_overflow(self): + buf = self._build_aq_fast_scan_buf( + fastscan_M=SIZE_MAX, fastscan_ksub=16 + ) + self.expect_read_throws(buf, "overflow") + + def test_rabitq_fast_scan_bbs_zero(self): + # Serialize a valid IndexRaBitQFastScan and patch its bbs field. The + # format has qb (uint8_t = 8) immediately followed by bbs (int = 32). + idx = faiss.IndexRaBitQFastScan(4, faiss.METRIC_L2, 32, 1) + buf = serialize_index(idx) + pos = buf.find(struct.pack(" total_codebook_size=256; provide 257 floats. + buf = bytearray() + push_fourcc(buf, "IxRq") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, 4) # d + push_val(buf, SIZE_T, 1) # M + push_vector(buf, SIZE_T, [8]) # nbits + push_val(buf, BOOL, True) # is_trained + push_vector(buf, FLOAT, [0.0] * 257) # not a multiple + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + self.expect_read_throws(buf, "not a positive multiple") + + def test_product_additive_quantizer_d_not_divisible(self): + # d=5, nsplits=2 -> d % nsplits != 0. The codebooks are sized for d + # because the divisibility check fires before the codebooks size + # check. + buf = bytearray() + push_fourcc(buf, "IxPR") + push_index_header(buf, 5, 0) + push_val(buf, SIZE_T, 5) # d + push_val(buf, SIZE_T, 2) # M + push_vector(buf, SIZE_T, [4, 4]) # nbits + push_val(buf, BOOL, True) # is_trained + push_vector(buf, FLOAT, [0.0] * (5 * 32)) # codebooks + push_val(buf, INT, 0) # search_type = ST_decompress + push_val(buf, FLOAT, 0.0) # norm_min + push_val(buf, FLOAT, 1.0) # norm_max + push_val(buf, SIZE_T, 2) # nsplits = 2 + self.expect_read_throws(buf, "not divisible by nsplits") + + def test_product_residual_quantizer_sub_d_mismatch(self): + # d=8, nsplits=2 -> d_sub should be 4, the sub-quantizer has d=6. + buf = bytearray() + push_fourcc(buf, "IxPR") + push_index_header(buf, 8, 0) + push_additive_quantizer(buf, 8, 2, [4, 4], codebook_d=4) + push_val(buf, SIZE_T, 2) # nsplits = 2 + # First sub-quantizer: d=6. The read throws before the second. + push_residual_quantizer(buf, 6, 1, [4]) + self.expect_read_throws(buf, "sub-quantizer") + + def test_product_local_search_quantizer_sub_d_mismatch(self): + buf = bytearray() + push_fourcc(buf, "IxPL") + push_index_header(buf, 8, 0) + push_additive_quantizer(buf, 8, 2, [4, 4], codebook_d=4) + push_val(buf, SIZE_T, 2) # nsplits = 2 + push_local_search_quantizer(buf, 6, 1, [4]) + self.expect_read_throws(buf, "sub-quantizer") + + def test_product_residual_quantizer_multi_split_valid(self): + # nsplits > 1 round-trips (codebooks sized for d_sub, not d). + # d=8, nsplits=2, each sub-RQ has d_sub=4, M=1, nbits={4} + buf = bytearray() + push_fourcc(buf, "IxPR") + push_index_header(buf, 8, 0) + push_additive_quantizer(buf, 8, 2, [4, 4], codebook_d=4) + push_val(buf, SIZE_T, 2) # nsplits = 2 + push_residual_quantizer(buf, 4, 1, [4]) + push_residual_quantizer(buf, 4, 1, [4]) + push_val(buf, SIZE_T, 1) # code_size (8 bits -> 1 byte) + push_vector(buf, UINT8, []) # codes (ntotal=0) + idx = read_index(buf) + self.assertEqual(idx.ntotal, 0) + self.assertEqual(idx.d, 8) + + def test_product_local_search_quantizer_multi_split_valid(self): + buf = bytearray() + push_fourcc(buf, "IxPL") + push_index_header(buf, 8, 0) + push_additive_quantizer(buf, 8, 2, [4, 4], codebook_d=4) + push_val(buf, SIZE_T, 2) # nsplits = 2 + push_local_search_quantizer(buf, 4, 1, [4]) + push_local_search_quantizer(buf, 4, 1, [4]) + push_val(buf, SIZE_T, 1) # code_size + push_vector(buf, UINT8, []) # codes (ntotal=0) + idx = read_index(buf) + self.assertEqual(idx.ntotal, 0) + self.assertEqual(idx.d, 8) + + # A negative qbs must be rejected at deserialization time to prevent + # infinite loops in pq4_qbs_to_nq (arithmetic right shift preserves the + # sign bit, so the loop never terminates for negative values). + + def test_index_pq_fast_scan_negative_qbs(self): + buf = self._build_index_pq_fast_scan_buf(bbs=32, M2=2, qbs=-1) + self.expect_read_throws(buf, "qbs must be non-negative") + + def test_aq_fast_scan_negative_qbs(self): + buf = self._build_aq_fast_scan_buf( + fastscan_M=3, fastscan_ksub=16, qbs=-1 + ) + self.expect_read_throws(buf, "qbs must be non-negative") + + def test_ivf_aq_fast_scan_negative_qbs(self): + # Serialize a valid IndexIVFResidualQuantizerFastScan, then patch + # the qbs field. qbs (int) immediately follows bbs (int = 32) in the + # IVRf format; a distinctive sentinel qbs makes the pattern unique. + coarse_quantizer = faiss.IndexFlat(4, faiss.METRIC_L2) + idx = faiss.IndexIVFResidualQuantizerFastScan( + coarse_quantizer, 4, 1, 1, 4 + ) + train_data = np.arange(4 * 64, dtype="float32").reshape(64, 4) + idx.train(train_data) + sentinel_qbs = 0x1234 + idx.qbs = sentinel_qbs + + buf = serialize_index(idx) + pos = buf.find(struct.pack(" code_size computation and gives a huge code_size. + buf = bytearray() + push_fourcc(buf, "IxLa") + push_val(buf, INT, 4) # d + push_val(buf, INT, 2) # nsq (dsq = 2, power of 2 >= 2) + push_val(buf, INT, -100) # scale_nbit (corrupt) + push_val(buf, INT, 1) # r2 + self.expect_read_throws(buf, "code_size") + + def test_product_quantizer_m_ksub_exceeds_byte_limit(self): + # ProductQuantizer::set_derived_values only validates d % M == 0, + # which any M satisfies when d == 0, so a crafted PQ header could + # carry an enormous M with an empty centroids vector. Without the + # read-side bound, allocations sized M*ksub (e.g. IVFPQ residual + # norms in initialize_IVFPQ_precomputed_table) reach + # std::vector::max_size() and abort via std::length_error. + with vector_byte_limit(1 << 20): # 1 MB + buf = bytearray() + push_fourcc(buf, "IxPq") + push_index_header(buf, 0, 0) + # PQ: d=0, M=1<<20, nbits=8 -> ksub=256. + # M * ksub = 2^28 floats = 1 GB, far above the 1 MB limit. + push_pq(buf, 0, 1 << 20, 8, []) + self.expect_read_throws(buf, "M*ksub") + + def _saturating_pq(self): + # M*ksub saturates most of size_t. set_derived_values (which would + # resize centroids) is skipped: the tests exercise the arithmetic + # guard in initialize_IVFPQ_precomputed_table, not PQ training. + pq = faiss.ProductQuantizer() + pq.d = 0 + pq.M = 1 << 40 + pq.nbits = 24 + pq.ksub = 1 << pq.nbits + pq.dsub = 0 + pq.code_size = 0 + return pq + + def test_initialize_ivfpq_precomputed_table_user_set_flag_overflow_rejected( + self, + ): + # The overflowing M*ksub is rejected even when the caller pre-sets + # use_precomputed_table to 1, which bypasses the size-class branch. + # Protects in-memory IVFPQ callers (training, IndexHNSW, + # IndexIVFPQFastScan) and the IndexIVFIndependentQuantizer read path + # that reads use_precomputed_table directly from the stream. + quantizer = faiss.IndexFlatL2(0) + quantizer.ntotal = 1 + use_table = np.array([1], dtype="int32") + with self.assertRaisesFaiss(): + faiss.initialize_IVFPQ_precomputed_table( + faiss.swig_ptr(use_table), + quantizer, + self._saturating_pq(), + faiss.AlignedTableFloat32(), + True, # by_residual + False, # verbose + ) + + def _expect_precomputed_table_limit(self, index, nlist, M, nbits, limit): + # Read with a limit below the recomputed table size must throw from + # the precompute-table guard (the message pins it, so no other + # byte-limit check can satisfy the test). Just above the table size + # the index still loads (positive control). + xt = ( + np.random.RandomState(12345) + .uniform(-1.0, 1.0, size=(10000, index.d)) + .astype("float32") + ) + index.train(xt) + index.add(xt) + data = serialize_index(index) + table_elems = nlist * M * (1 << nbits) + with vector_byte_limit(limit): + self.expect_read_throws(data, "precomputed_table") + with vector_byte_limit((table_elems + 1) * 4): + read_index(data) + + def test_ivfpq_precomputed_table_exceeds_byte_limit(self): + # read_ivfpq bounds the derived (not stored) IVFPQ precomputed table + # by the byte limit before it recomputes it. The table is + # quantizer->ntotal * pq.M * pq.ksub floats from attacker-controlled + # header fields, so a small crafted index can drive a large + # allocation (memory-amplification DoS reachable from read_index + # and the binary index fuzzer). + d, nlist, M, nbits = 16, 256, 8, 8 # ksub = 256 + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFPQ(quantizer, d, nlist, M, nbits) + # Recomputed table = 256 * 8 * 256 = 524288 floats (2 MB). A 256 KB + # limit (65536 floats) is below the table but above the smaller + # derived reads (PQ centroids ~16 KB, inverted lists). + self._expect_precomputed_table_limit(index, nlist, M, nbits, 1 << 18) + + def test_ivfpq_fast_scan_precomputed_table_exceeds_byte_limit(self): + # The same bound guards the IVFPQFastScan (IwPf) read path, whose + # precompute_table() call is unconditional. nbits=4 -> ksub=16, so + # the table = 256 * 8 * 16 = 32768 floats (128 KB). 64 KB (16384 + # floats) is below the table but above the smaller derived reads. + d, nlist, M, nbits = 16, 256, 8, 4 + quantizer = faiss.IndexFlatL2(d) + index = faiss.IndexIVFPQFastScan(quantizer, d, nlist, M, nbits) + self._expect_precomputed_table_limit(index, nlist, M, nbits, 1 << 16) + + def test_ivfpq_null_quantizer_read_rejected(self): + # read_ivf_header reads the coarse quantizer via read_index, which + # returns nullptr for a crafted "null" fourcc. The null check right + # after read_ivf_header must throw before the precompute-table guard + # (or precompute_table) dereferences quantizer->ntotal. + buf = bytearray() + push_fourcc(buf, "IwPQ") + push_index_header(buf, 4, 0, is_trained=True) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_fourcc(buf, "null") # coarse quantizer -> nullptr + push_empty_direct_map(buf) + push_val(buf, BOOL, True) # by_residual + push_val(buf, SIZE_T, 1) # code_size + # Valid PQ: d=4, M=1, nbits=8 -> centroids = d*ksub = 1024. + push_pq(buf, 4, 1, 8, [0.0] * (4 * 256)) + push_null_invlists(buf) + self.expect_read_throws(buf, "IVFPQ coarse quantizer is null") + + def test_ivfpq_multi_index_quantizer_precomputed_table_exceeds_byte_limit( + self, + ): + # The type-2 table (MultiIndexQuantizer coarse quantizer) is + # cpq.ksub * pq.M * pq.ksub floats, decoupled from quantizer->ntotal. + d = 8 + buf = bytearray() + push_fourcc(buf, "IwPQ") + push_index_header(buf, d, 0, is_trained=True) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + # Coarse quantizer: MultiIndexQuantizer ("Imiq") with ntotal=1 but + # cpq.nbits=10 -> cpq.ksub=1024. + push_fourcc(buf, "Imiq") + push_index_header(buf, d, 1, is_trained=True) + push_pq(buf, d, 1, 10, [0.0] * (d * 1024)) + push_empty_direct_map(buf) + push_val(buf, BOOL, True) # by_residual + push_val(buf, SIZE_T, 1) # code_size + # Outer PQ: M=2, nbits=8 -> ksub=256, m_ksub=512, pq.M % cpq.M == 0. + push_pq(buf, d, 2, 8, [0.0] * (d * 256)) + push_null_invlists(buf) + # type-1 bound: 1 * 2 * 256 = 512 floats (an ntotal-only guard would + # pass). type-2 table: 1024 * 2 * 256 = 524288 floats. + with vector_byte_limit(1 << 16): # 64 KB + self.expect_read_throws(buf, "precomputed_table") + + def test_ivfpq_fast_scan_null_quantizer_read_rejected(self): + # The IVFPQFastScan (IwPf) read path also rejects a null coarse + # quantizer right after read_ivf_header. + buf = bytearray() + push_fourcc(buf, "IwPf") + push_index_header(buf, 4, 0, is_trained=True) + push_val(buf, SIZE_T, 1) # nlist + push_val(buf, SIZE_T, 1) # nprobe + push_fourcc(buf, "null") # coarse quantizer -> nullptr + push_empty_direct_map(buf) + self.expect_read_throws(buf, "IVFPQFastScan coarse quantizer is null") + + # SVS fourcc rejection and deserialization safety (T262015608). + + def _push_svs_vamana_prefix(self, buf, storage_kind): + # IndexSVSVamana on-disk fields up to and including storage_kind. + push_index_header(buf, 8, 0) + push_val(buf, SIZE_T, 32) # graph_max_degree + push_val(buf, FLOAT, 1.2) # alpha + push_val(buf, SIZE_T, 10) # search_window_size + push_val(buf, SIZE_T, 10) # search_buffer_capacity + push_val(buf, SIZE_T, 64) # construction_window_size + push_val(buf, SIZE_T, 750) # max_candidate_pool_size + push_val(buf, SIZE_T, 28) # prune_to + push_val(buf, BOOL, False) # use_full_search_history + push_val(buf, INT, storage_kind) + + def _push_svs_ivf_prefix(self, buf, storage_kind): + # IndexSVSIVF on-disk fields up to and including storage_kind, for + # the validation guard at the ISIQ/ISIL/ISID read sites. + push_index_header(buf, 8, 0) + push_val(buf, SIZE_T, 8) # num_centroids + push_val(buf, SIZE_T, 64) # minibatch_size + push_val(buf, SIZE_T, 1) # num_iterations + push_val(buf, BOOL, False) # is_hierarchical + push_val(buf, FLOAT, 0.1) # training_fraction + push_val(buf, SIZE_T, 0) # hierarchical_level1_clusters + push_val(buf, SIZE_T, 0) # seed + push_val(buf, SIZE_T, 1) # n_probes + push_val(buf, FLOAT, 1.0) # k_reorder (float, not size_t) + push_val(buf, SIZE_T, 1) # num_threads + push_val(buf, SIZE_T, 1) # intra_query_threads + push_val(buf, INT, storage_kind) + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svs_vamana_invalid_storage_kind(self): + # An invalid storage_kind is rejected at deserialization time, not + # aborted via FAISS_ASSERT in to_svs_storage_kind(). + buf = bytearray() + push_fourcc(buf, "ISVD") + self._push_svs_vamana_prefix(buf, faiss.SVS_count) + push_val(buf, BOOL, True) # initialized + self.expect_read_throws(buf, "storage_kind") + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svs_vamana_negative_storage_kind(self): + # The shared validator takes a signed int because READ1 reads four + # bytes that could be either sign. + buf = bytearray() + push_fourcc(buf, "ISVD") + self._push_svs_vamana_prefix(buf, -1) + push_val(buf, BOOL, True) + self.expect_read_throws(buf, "storage_kind") + + # ISIQ/ISIL/ISID share one storage_kind read site. + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svsivf_invalid_storage_kind(self): + buf = bytearray() + push_fourcc(buf, "ISID") + self._push_svs_ivf_prefix(buf, faiss.SVS_count) + push_val(buf, BOOL, True) # is_static + push_val(buf, BOOL, True) # initialized + self.expect_read_throws(buf, "storage_kind") + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svsivflvq_invalid_storage_kind(self): + buf = bytearray() + push_fourcc(buf, "ISIQ") + self._push_svs_ivf_prefix(buf, -1) + push_val(buf, BOOL, True) + push_val(buf, BOOL, True) + self.expect_read_throws(buf, "storage_kind") + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svsivf_lean_vec_invalid_storage_kind(self): + buf = bytearray() + push_fourcc(buf, "ISIL") + self._push_svs_ivf_prefix(buf, faiss.SVS_count + 7) + push_val(buf, BOOL, True) # is_static + push_val(buf, SIZE_T, 8) # leanvec_d (only on the ISIL path) + push_val(buf, BOOL, True) # initialized + self.expect_read_throws(buf, "storage_kind") + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svs_vamana_invalid_stream_throws(self): + # Invalid SVS stream data throws from the SVS runtime load failure + # rather than a null-pointer dereference (deserialize_impl called + # impl->load() on a null impl pointer). + buf = bytearray() + push_fourcc(buf, "ISVD") + self._push_svs_vamana_prefix(buf, 0) # storage_kind = SVS_Float16 + push_val(buf, BOOL, False) # is_static + push_val(buf, BOOL, True) # initialized -> deserialize_impl + buf += bytes(256) # garbage SVS stream data + self.expect_read_throws(buf) + + @unittest.skipUnless(SVS_ENABLED, "requires SVS") + def test_svs_flat_invalid_stream_throws(self): + buf = bytearray() + push_fourcc(buf, "ISVF") + push_index_header(buf, 8, 0) + push_val(buf, BOOL, True) # initialized -> deserialize_impl + buf += bytes(256) # garbage SVS stream data + self.expect_read_throws(buf) + + # k_factor must be finite and in [1, 1000]. + + def _index_refine_buf(self, fourcc, k_factor): + d = 4 + buf = bytearray() + push_fourcc(buf, fourcc) + push_index_header(buf, d, 0) + push_minimal_flat(buf, d) # base_index + push_minimal_flat(buf, d) # refine_index + push_val(buf, FLOAT, k_factor) + return buf + + def test_index_refine_k_factor_valid(self): + read_index(self._index_refine_buf("IxRF", 1.0)) + + def test_index_refine_k_factor_max(self): + read_index(self._index_refine_buf("IxRF", 1000.0)) + + def test_index_refine_k_factor_too_large(self): + buf = self._index_refine_buf("IxRF", 1001.0) + self.expect_read_throws(buf, "k_factor") + + def test_index_refine_k_factor_zero(self): + self.expect_read_throws(self._index_refine_buf("IxRF", 0.0), "k_factor") + + def test_index_refine_k_factor_nan(self): + buf = self._index_refine_buf("IxRF", float("nan")) + self.expect_read_throws(buf, "k_factor") + + def _make_ivfpqr_bytes(self, k_factor): + # nbits=4 (16 centroids) so that training succeeds with few vectors. + d = 8 + quantizer = faiss.IndexFlatL2(d) + ivfpqr = faiss.IndexIVFPQR(quantizer, d, 1, 2, 4, 2, 4) + ntrain = 64 + train_data = ( + np.arange(d * ntrain, dtype="float32") / np.float32(d * ntrain) + ).reshape(ntrain, d) + ivfpqr.train(train_data) + ivfpqr.k_factor = k_factor + return serialize_index(ivfpqr) + + def _patch_last_float(self, buf, new_val): + # k_factor is the last field written for IVFPQR. + struct.pack_into("index without the "inner index is null" guard. + # The binary IBMp/IBM2 path is reached indirectly (an embedded float + # IxMp/IxM2 inside a binary wrapper such as IndexBinaryFromFloat) and is + # covered by the same float-side guard. + + def test_index_id_map_null_inner_rejected(self): + buf = bytearray() + push_fourcc(buf, "IxMp") + push_index_header(buf, 4, 0) + push_fourcc(buf, "null") + push_vector(buf, INT64, []) # id_map + self.expect_read_throws(buf, "inner index is null") + + def test_index_binary_from_float_null_inner_rejected(self): + # A null inner index would null-deref on the first search or add. + d = 8 + buf = bytearray() + push_fourcc(buf, "IBFf") + push_binary_index_header(buf, d, 0) + push_fourcc(buf, "null") + self.expect_binary_read_throws(buf, "inner index is null") + + def test_index_id_map_matching_ntotals_accepted(self): + read_index(make_idmap_payload("IxMp", 0, 0, 0)) + + # Panorama deserialization and reconstruct bounds (T287094917). + # The IxFP branch does not go through read_index_header, so its own + # range checks are all that guard d and ntotal. + + def test_flat_panorama_dimension_out_of_range(self): + # A d large enough to make code_size = d * 4 overflow into + # gigabytes is rejected, as it is for every other index type. + buf = bytearray() + push_flat_panorama(buf, 1280725833, 1, 1024, 0) + self.expect_read_throws(buf, "out of range") + + def test_flat_panorama_negative_ntotal(self): + buf = bytearray() + push_flat_panorama(buf, 8, 1, 4, -1) + self.expect_read_throws(buf, "invalid ntotal") + + def test_flat_panorama_zero_batch_size_rejected(self): + buf = bytearray() + push_flat_panorama(buf, 8, 1, 0, 2) + self.expect_read_throws(buf, "invalid IxFP batch_size") + + def test_flat_panorama_codes_size_overflow_rejected(self): + # batch_size=SIZE_MAX, ntotal=2: num_slots = 1 * SIZE_MAX does not + # overflow, the later num_slots * code_size multiplication does. + buf = bytearray() + push_flat_panorama(buf, 8, 1, SIZE_MAX, 2) + self.expect_read_throws( + buf, "integer overflow in IndexFlatPanorama codes" + ) + + def test_flat_panorama_codes_size_mismatch(self): + buf = bytearray() + push_flat_panorama(buf, 8, 1, 4, 2) + self.expect_read_throws(buf, "IndexFlatPanorama codes size mismatch") + + def test_pre_transform_over_empty_flat_panorama_reconstruct(self): + # The fuzzer crash shape: an IndexPreTransform with an empty chain + # around an empty IndexFlatPanorama. Everything deserializes, and + # reconstruct() must reject the out-of-range key instead of copying + # code_size bytes out of a zero-length codes buffer. + d = 8 + buf = bytearray() + push_fourcc(buf, "IxPT") + push_index_header(buf, d, 0) + push_val(buf, INT, 0) # nt = 0, empty chain + push_flat_panorama(buf, d, 1, 4, 0) + idx = read_index(buf) + with self.assertRaisesFaiss(): + idx.reconstruct(0) + + def test_hnsw_flat_panorama_cum_sums_size_mismatch(self): + # "IHfP": fourcc + index_header + n_levels + cum_sums vec + HNSW + # graph + storage index. cum_sums must hold ntotal * (n_levels + 1) + # floats; a short vector is an out-of-bounds read on search. + buf = bytearray() + push_fourcc(buf, "IHfP") + push_index_header(buf, 4, 1) + push_val(buf, SIZE_T, 1) # n_levels + push_vector(buf, FLOAT, [0.0]) # cum_sums: 1 float, needs 2 + self.expect_read_throws(buf, "IndexHNSWFlatPanorama cum_sums") + + def test_hnsw_flat_panorama_zero_levels(self): + buf = bytearray() + push_fourcc(buf, "IHfP") + push_index_header(buf, 4, 0) + push_val(buf, SIZE_T, 0) # n_levels = 0 + self.expect_read_throws(buf, "invalid IHfP n_levels") + + +class TestIndexIDMapSafety(FaissTestCase): + def test_search_remaps_out_of_range_labels_to_sentinel(self): + # IndexIDMap::search_ex maps each inner label through id_map. When + # inner.ntotal exceeds id_map.size() (mid-construction, or after a + # recoverable failure in add_with_ids_ex / add_sa_codes / + # merge_from), inner labels can land outside id_map and must map to + # the -1 "no result" sentinel. + d = 4 + nb = 3 + xb = np.zeros((nb, d), dtype="float32") + xb[:, 0] = np.arange(nb) + + inner = faiss.IndexFlat(d, faiss.METRIC_L2) + idmap = faiss.IndexIDMap(inner) + inner.add(xb) # inner.ntotal == nb, idmap.id_map is empty + + _, labels = idmap.search(np.zeros((1, d), dtype="float32"), 1) + self.assertEqual(labels[0, 0], -1) + + +class TestIndexFlatPanoramaSafety(FaissTestCase): + def test_reconstruct_rejects_out_of_range_key(self): + # IndexFlatPanorama overrides reconstruct()/reconstruct_n() and does + # not inherit the range guards of IndexFlat / IndexFlatCodes. The + # level-major layout means an out-of-range key reads whole batch + # strides past the end of codes. + # reconstruct_n_c is the swig method: the Python reconstruct_n + # wrapper maps ni=-1 to ntotal - n0 and allocates (ni, d), so it + # cannot pass the raw arguments. + d = 8 + index = faiss.IndexFlatL2Panorama(d, 2, 4) + recons = np.zeros(2 * d, dtype="float32") + recons_ptr = faiss.swig_ptr(recons) + + index.add(np.ones((2, d), dtype="float32")) + + index.reconstruct(1) + with self.assertRaisesFaiss(): + index.reconstruct(2) + with self.assertRaisesFaiss(): + index.reconstruct(-1) + index.reconstruct_n_c(0, 2, recons_ptr) + bad_ranges = [(-1, 1), (0, -1), (1, INT64_MAX), (1, 2), (3, 0)] + for n0, ni in bad_ranges: + with self.assertRaisesFaiss(): + index.reconstruct_n_c(n0, ni, recons_ptr) + + +# ----------------------------------------------------------------------- +# IndexPiPNN +# ----------------------------------------------------------------------- + +PIPNN_DIM = 4 + +# A valid unbuilt, empty index. +EMPTY_PIPNN = { + "ntotal": 0, + "entry_point": -1, + "graph": (), + "storage_ntotal": 0, +} + + +def pipnn_payload( + metric_type=1, + R=2, + pipnn_ntotal=None, + ntotal=2, + entry_point=0, + graph=(1, -1, 0, -1), + next_copy=(), + storage_ntotal=2, + storage_d=PIPNN_DIM, + panorama_storage=False, +): + buf = bytearray() + push_fourcc(buf, "IPNf") + push_index_header(buf, PIPNN_DIM, ntotal, True, metric_type) + push_val(buf, BOOL, False) # defer_build + push_val(buf, INT, R) + # leaf_k, hash_bits, reservoir_size, c_max, c_min, leader_cap, replicas + for value in (2, 12, 64, 1024, 128, 1000, 1): + push_val(buf, INT, value) + push_val(buf, FLOAT, 0.005) # leader_fraction + push_val(buf, FLOAT, 0.0) # alpha + push_vector(buf, INT, (10, 3)) # fanout + push_val(buf, INT64, 1234) # seed + push_val(buf, BOOL, False) # ip_partition_by_angle + push_val(buf, INT, 64) # search_L + push_val(buf, INT64, ntotal if pipnn_ntotal is None else pipnn_ntotal) + push_val(buf, INT, entry_point) + for neighbor in graph: + push_val(buf, INT, neighbor) + push_vector(buf, INT, next_copy) + if panorama_storage: + push_flat_panorama(buf, PIPNN_DIM, 1, 1024, storage_ntotal) + else: + push_minimal_flat(buf, storage_d, storage_ntotal) + return buf + + +class TestPiPNNDeserialize(FaissTestCase): + + def test_valid_payloads(self): + for fields in ({}, EMPTY_PIPNN): + self.assertTrue(read_index(pipnn_payload(**fields)).own_fields) + + def test_rejects_malformed_payloads(self): + cases = [ + ({"R": 0}, "R must be >= 1"), + ({"ntotal": 2**31}, "exceeds INT32_MAX"), + ({"pipnn_ntotal": 1}, "PiPNN ntotal 1 != index ntotal"), + ({"graph": (1, 2, 0, -1)}, "out of range"), + ({"entry_point": 2}, "entry_point"), + ({"entry_point": -1}, "entry_point"), + ({"next_copy": (1,)}, "next_copy.size()"), + ({**EMPTY_PIPNN, "panorama_storage": True}, "unsupported storage"), + ({"storage_ntotal": 3}, "PiPNN storage ntotal"), + ({"storage_d": 2 * PIPNN_DIM}, "PiPNN storage d"), + ({"metric_type": 0}, "PiPNN storage metric"), + ] + for fields, msg in cases: + with self.subTest(**fields): + self.expect_read_throws(pipnn_payload(**fields), msg) + + def test_corrupt_graph_view_search_stays_in_bounds(self): + # views skip the neighbour scan on read; search must still stay in + # bounds on corrupt neighbour and copy ids, above ntotal and negative + data = np.array( + pipnn_payload(graph=(1, 99, -5, -1), next_copy=(99, -1)), + dtype="uint8", + ) + index = faiss.read_index( + faiss.ZeroCopyIOReader(faiss.swig_ptr(data), data.size) + ) + _, labels = index.search(np.zeros((1, PIPNN_DIM), dtype="float32"), 3) + self.assertTrue(np.all((labels >= -1) & (labels <= 1)), labels) diff --git a/thirdparty/faiss/tests/test_referenced_objects.py b/thirdparty/faiss/tests/test_referenced_objects.py index b2609e58b..cedf11373 100644 --- a/thirdparty/faiss/tests/test_referenced_objects.py +++ b/thirdparty/faiss/tests/test_referenced_objects.py @@ -4,12 +4,6 @@ # LICENSE file in the root directory of this source tree. """make sure that the referenced objects are kept""" -from __future__ import ( - absolute_import, - division, - print_function, - unicode_literals, -) import numpy as np import unittest @@ -42,11 +36,6 @@ def test_count_refs(self): refc2 = sys.getrefcount(quantizer) assert refc2 == refc1 - 1 - def test_IndexIVF_2(self): - index = faiss.IndexIVFFlat(faiss.IndexFlatL2(d), d, 10) - index.train(xt) - index.add(xb) - def test_IndexPreTransform(self): ltrans = faiss.NormalizationTransform(d) sub_index = faiss.IndexFlatL2(d) @@ -114,36 +103,18 @@ def body(): # noise but is well below the leak signal. self.assertLess(growth_mb, 200) - def test_SearchParameters_subclass_no_double_wrap(self): - # Regression: SWIG does not generate per-class __setattr__, so - # the ownership-protecting override must be installed only on - # the base SearchParameters; otherwise subclasses inherit and - # re-wrap, doubling the refcount on the assigned selector. - params = faiss.SearchParametersIVF() - sel = faiss.IDSelectorBatch(np.arange(10)) - before = sys.getrefcount(sel) - params.sel = sel - delta = sys.getrefcount(sel) - before - self.assertEqual(delta, 1) - def test_SearchParameters_reassignment_no_accumulation(self): - # Reassigning the same field on a long-lived SearchParameters - # must release the prior ref. Without per-field tracking the - # protection list grows unbounded - reproducing the original - # leak shape under a different access pattern. + # reassigning a field must release the previous selector params = faiss.SearchParameters() sel1 = faiss.IDSelectorBatch(np.arange(10)) sel2 = faiss.IDSelectorBatch(np.arange(10)) before1 = sys.getrefcount(sel1) params.sel = sel1 params.sel = sel2 - # sel1 ref dropped when sel2 took its slot self.assertEqual(sys.getrefcount(sel1), before1) def test_SearchParameters_setattr_else_branch(self): - # Else branch coverage: setting a field to None drops the prior - # SWIG ref; assigning two different fields keeps both alive - # independently so dropping one does not affect the other. + # None drops the ref of that field only params = faiss.SearchParametersIVF() sel = faiss.IDSelectorBatch(np.arange(10)) quant = faiss.SearchParameters() @@ -155,7 +126,6 @@ def test_SearchParameters_setattr_else_branch(self): self.assertEqual(sys.getrefcount(sel) - sel_before, 1) self.assertEqual(sys.getrefcount(quant) - quant_before, 1) - # Drop sel via None; quantizer_params untouched. params.sel = None self.assertEqual(sys.getrefcount(sel), sel_before) self.assertEqual(sys.getrefcount(quant) - quant_before, 1) diff --git a/thirdparty/faiss/tests/test_refine.py b/thirdparty/faiss/tests/test_refine.py index 6bb1ed159..447765930 100644 --- a/thirdparty/faiss/tests/test_refine.py +++ b/thirdparty/faiss/tests/test_refine.py @@ -77,30 +77,21 @@ def do_test(self, factory_string): index.train(ds.get_train()) index.add(ds.get_database()) - # Set nprobe on the base index (for IndexRefine, nprobe belongs to - # the IVF base index) - if hasattr(index, "base_index") and hasattr(index.base_index, "nprobe"): - index.base_index.nprobe = 4 - elif hasattr(index, "nprobe"): - index.nprobe = 4 + faiss.extract_index_ivf(index).nprobe = 4 xq = ds.get_queries() - # do a search with k_factor = 1 D1, I1 = index.search(xq, 10) inter1 = faiss.eval_intersection(I1, ds.get_groundtruth(10)) - # do a search with k_factor = 1.5 params = faiss.IndexRefineSearchParameters(k_factor=1.1) D2, I2 = index.search(xq, 10, params=params) inter2 = faiss.eval_intersection(I2, ds.get_groundtruth(10)) - # do a search with k_factor = 2 params = faiss.IndexRefineSearchParameters(k_factor=2) D3, I3 = index.search(xq, 10, params=params) inter3 = faiss.eval_intersection(I3, ds.get_groundtruth(10)) - # make sure that the recall rate increases with k_factor self.assertGreater(inter2, inter1) self.assertGreater(inter3, inter2) @@ -122,7 +113,6 @@ def do_test(self, factory_string): D5, I5 = index.search(xq, 10, params=params) inter5 = faiss.eval_intersection(I5, ds.get_groundtruth(10)) - # make sure that the recall rate changes self.assertNotEqual(inter4, inter5) def test_rflat(self): @@ -149,17 +139,13 @@ def do_test(self, factory_string): xq = ds.get_queries() xb = ds.get_database() - # perform a range_search lims_1, D1, I1 = index.range_search(xq, radius) - # create a baseline (FlatL2) index_flat = faiss.IndexFlatL2(d) - index_flat.train(ds.get_train()) index_flat.add(ds.get_database()) lims_ref, Dref, Iref = index_flat.range_search(xq, radius) - # add a refine index on top of the index index_r = faiss.IndexRefine(index, index_flat) lims_2, D2, I2 = index_r.range_search(xq, radius) @@ -191,11 +177,6 @@ def do_test(self, factory_string): def test_refine_1(self): self.do_test("SQ4") - def test_refine_sq6(self): - # coarser quantization makes approximate/exact distance mismatches - # near the radius boundary more likely, exercising the filtering - self.do_test("SQ6") - def do_test_k_factor( self, factory_string, @@ -226,13 +207,8 @@ def do_test_k_factor( index_r = faiss.IndexRefine(index, index_flat) - # k_factor scales the radius used to query the base index (base_radius = - # radius * k_factor); the results are still filtered at the requested - # radius, so every returned distance must stay on the correct side of it - # regardless of k_factor (issue #5367). For an L2 base a larger k_factor - # widens the base search and can only add candidates, so recall must not - # decrease; for a similarity base radius * k_factor does not necessarily - # widen the search, so no recall guarantee is asserted there. + # results are filtered at the requested radius for any k_factor (issue + # #5367); only an L2 base guarantees that a larger k_factor keeps recall recalls = [] for k_factor in (1, 4): index_r.k_factor = k_factor diff --git a/thirdparty/faiss/tests/test_refine_panorama.py b/thirdparty/faiss/tests/test_refine_panorama.py index 889b511ac..13695d226 100644 --- a/thirdparty/faiss/tests/test_refine_panorama.py +++ b/thirdparty/faiss/tests/test_refine_panorama.py @@ -3,20 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Test comparing IndexRefineFlat to IndexRefinePanorama -with full-corpus refinement. - -This test constructs two refine indexes over the same IVF-PQ base: -- IndexRefineFlat -- IndexRefinePanorama (with n_levels=8) - -We set k=10 and k_factor such that k_base = k * k_factor = nb = 500,000, and -set nprobe = nlist on the base indexes so the base stage covers all vectors. -Then we check that both refined results return identical ids and (nearly) -identical distances. -""" - import unittest import faiss @@ -28,12 +14,8 @@ @for_all_simd_levels class TestIndexRefinePanorama(unittest.TestCase): - - # Metrics to test METRICS = [faiss.METRIC_L2, faiss.METRIC_INNER_PRODUCT] - # Helper methods for index creation and data generation - def generate_data(self, d, nt, nb, nq, seed=42): ds = SyntheticDataset(d, nt, nb, nq, seed=seed) return ds.get_train(), ds.get_database(), ds.get_queries() @@ -41,7 +23,6 @@ def generate_data(self, d, nt, nb, nq, seed=42): def create_flat( self, d, base_factory, xt=None, xb=None, metric=faiss.METRIC_L2 ): - """Create and initialize IndexRefineFlat.""" base_index = faiss.index_factory(d, base_factory, metric) index = faiss.IndexRefineFlat(base_index) if xt is not None: @@ -59,7 +40,6 @@ def create_panorama( xb=None, metric=faiss.METRIC_L2, ): - """Create and initialize IndexRefinePanorama.""" base_index = faiss.index_factory(d, base_factory, metric) refine_index = faiss.index_factory( d, @@ -80,18 +60,9 @@ def assert_search_results_equal( I_regular, D_panorama, I_panorama, - rtol=1e-5, - atol=1e-4, ): - np.testing.assert_allclose( - D_regular, - D_panorama, - rtol=rtol, - atol=atol, - err_msg="Distances mismatch", - ) check_ref_knn_with_draws( - D_regular, I_regular, D_panorama, I_panorama, rtol=rtol, atol=atol + D_regular, I_regular, D_panorama, I_panorama, rtol=1e-5, atol=1e-4 ) def test_refine_panorama_correctness(self): @@ -106,7 +77,6 @@ def test_refine_panorama_correctness(self): for metric in self.METRICS: with self.subTest(metric=metric): - # Build two identical refine indexes base_cfg = "Flat" index_flat = self.create_flat( d, base_cfg, xt=xt, xb=xb, metric=metric @@ -115,7 +85,7 @@ def test_refine_panorama_correctness(self): d, base_cfg, n_levels, xt=xt, xb=xb, metric=metric ) - for k_factor in [1, 8, 64, 256, 1024, 50000]: + for k_factor in [1, 64, 1024]: params = faiss.IndexRefineSearchParameters( k_factor=float(k_factor) ) @@ -123,12 +93,10 @@ def test_refine_panorama_correctness(self): D_flat, I_flat = index_flat.search(xq, k, params=params) D_pano, I_pano = index_pan.search(xq, k, params=params) - # Ids must match exactly; distances can be allclose np.testing.assert_array_equal(I_flat, I_pano) np.testing.assert_allclose(D_flat, D_pano, rtol=1e-5) def test_different_n_levels(self): - """Test correctness with various n_levels parameter values""" d, nb, nt, nq, k = 128, 25000, 40000, 10, 15 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=456) @@ -163,7 +131,6 @@ def test_different_n_levels(self): faiss.omp_set_num_threads(nt_threads) def test_uneven_dimension_division(self): - """Test when n_levels doesn't evenly divide dimension""" test_cases = [(65, 4), (63, 8), (100, 7), (960, 128), (964, 128)] for metric in self.METRICS: @@ -187,54 +154,7 @@ def test_uneven_dimension_division(self): D_regular, I_regular, D_panorama, I_panorama ) - def test_single_level(self): - """Test edge case with n_levels=1""" - d, nb, nt, nq, nlevels, k = 32, 500, 700, 10, 1, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=333) - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat( - d, base_cfg, xt=xt, xb=xb, metric=metric - ) - index_panorama = self.create_panorama( - d, base_cfg, nlevels, xt=xt, xb=xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - - def test_multiple_levels_small_dimension(self): - """Test edge case: more levels than dimension naturally supports""" - d, nb, nt, nq, nlevels, k = 16, 200, 300, 10, 8, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=1212) - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat( - d, base_cfg, xt=xt, xb=xb, metric=metric - ) - index_panorama = self.create_panorama( - d, base_cfg, nlevels, xt=xt, xb=xb, metric=metric - ) - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama - ) - def test_id_selector_range(self): - """Test ID filtering with range selector""" d, nb, nt, nq, nlevels, k = 128, 80000, 120000, 500, 8, 20 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=321) @@ -262,145 +182,10 @@ def test_id_selector_range(self): xq, k, params=params ) - self.assertTrue(np.all(I_panorama >= 10000)) - self.assertTrue(np.all(I_panorama < 50000)) - np.testing.assert_array_equal(I_regular, I_panorama) np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) - def test_id_selector_batch(self): - """Test ID filtering with batch selector""" - d, nb, nt, nq, nlevels, k = 128, 60000, 90000, 400, 8, 20 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=522) - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat( - d, base_cfg, xt=xt, xb=xb, metric=metric - ) - index_panorama = self.create_panorama( - d, base_cfg, nlevels, xt=xt, xb=xb, metric=metric - ) - - allowed_ids = np.array( - [i * 100 for i in range(500)], dtype=np.int64 - ) - base_params = faiss.SearchParameters() - base_params.sel = faiss.IDSelectorBatch(allowed_ids) - params = faiss.IndexRefineSearchParameters( - k_factor=1, base_index_params=base_params - ) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - allowed_set = set(allowed_ids) - for id_val in I_panorama.flatten(): - self.assertIn(int(id_val), allowed_set) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) - - def test_selector_with_small_dataset(self): - """Test ID selectors with dataset smaller than batch size""" - d, nb, nt, nq, nlevels, k = 32, 100, 200, 10, 4, 5 - xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=888) - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat( - d, base_cfg, xt=xt, xb=xb, metric=metric - ) - index_panorama = self.create_panorama( - d, base_cfg, nlevels, xt=xt, xb=xb, metric=metric - ) - - base_params = faiss.SearchParameters() - base_params.sel = faiss.IDSelectorRange(20, 60) - params = faiss.IndexRefineSearchParameters( - k_factor=1, base_index_params=base_params - ) - - D_regular, I_regular = index_regular.search( - xq, k, params=params - ) - D_panorama, I_panorama = index_panorama.search( - xq, k, params=params - ) - - self.assertTrue(np.all(I_panorama >= 20)) - self.assertTrue(np.all(I_panorama < 60)) - - np.testing.assert_array_equal(I_regular, I_panorama) - np.testing.assert_allclose(D_regular, D_panorama, rtol=1e-5) - - def test_empty_result_handling(self): - """Test handling of empty search results (shapes only)""" - d, nb, nt, nq, nlevels, k = 32, 100, 200, 10, 4, 10 - xt, xb, _ = self.generate_data(d, nt, nb, nq, seed=111) - xq = ( - np.random.rand(nq, d).astype("float32") + 10.0 - ) # Queries far from database - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index = self.create_panorama( - d, base_cfg, nlevels, xt=xt, xb=xb, metric=metric - ) - D, I = index.search(xq, k) - - self.assertEqual(D.shape, (nq, k)) - self.assertEqual(I.shape, (nq, k)) - - def test_incremental_add(self): - """Test adding vectors incrementally in multiple batches""" - # Seed the (otherwise unseeded) incremental batch + query draws so - # near-tied neighbors don't reorder run-to-run (matches the sibling - # test_add_search_add_search). - np.random.seed(1234) - d, nlevels, k = 128, 8, 15 - - base_cfg = "Flat" - - for metric in self.METRICS: - with self.subTest(metric=metric): - index_regular = self.create_flat(d, base_cfg, metric=metric) - index_panorama = self.create_panorama( - d, base_cfg, nlevels, metric=metric - ) - - # Keep total nb under 100k - batch_sizes = [5000, 10000, 15000, 20000] - for batch_size in batch_sizes: - xb_batch = np.random.rand(batch_size, d).astype("float32") - index_regular.add(xb_batch) - index_panorama.add(xb_batch) - - nq = 10 - xq = np.random.rand(nq, d).astype("float32") - - D_regular, I_regular = index_regular.search(xq, k) - D_panorama, I_panorama = index_panorama.search(xq, k) - - # Panorama distance reformulation (a*a+b*b-2ab vs (a-b)^2) - # differs at float32 ULP; atol absorbs it while the strong - # ID-overlap floor still trips on a real regression. - self.assert_search_results_equal( - D_regular, I_regular, D_panorama, I_panorama, atol=1e-4 - ) - def test_add_search_add_search(self): - """Test interleaved add and search operations""" d, nlevels, k = 32, 4, 5 np.random.seed(555) @@ -413,7 +198,6 @@ def test_add_search_add_search(self): d, base_cfg, nlevels, metric=metric ) - # First add and search xb1 = np.random.rand(200, d).astype("float32") index_regular.add(xb1) index_panorama.add(xb1) @@ -426,7 +210,6 @@ def test_add_search_add_search(self): D_reg_1, I_reg_1, D_pan_1, I_pan_1 ) - # Second add and search xb2 = np.random.rand(300, d).astype("float32") index_regular.add(xb2) index_panorama.add(xb2) @@ -439,7 +222,6 @@ def test_add_search_add_search(self): ) def test_serialization(self): - """Test write/read Panorama indexes preserves search results""" d, nb, nt, nq, nlevels, k = 128, 10000, 15000, 100, 8, 20 xt, xb, xq = self.generate_data(d, nt, nb, nq, seed=2024) @@ -461,7 +243,6 @@ def test_serialization(self): np.testing.assert_array_equal(D_before, D_after) def test_ratio_dims_scanned(self): - """Test the correctness of the ratio of dimensions scanned""" d, nb, nq, k = 128, 500000, 10, 1 # Setup: All vectors in the dataset are [-1, -1, ..., -1], except for @@ -474,7 +255,6 @@ def test_ratio_dims_scanned(self): for metric in self.METRICS: with self.subTest(metric=metric): - # Create base flat index for comparison index_base = faiss.IndexFlat(d, metric) index_base.add(xb) D_base, I_base = index_base.search(xq, k) @@ -483,7 +263,7 @@ def test_ratio_dims_scanned(self): faiss.omp_set_num_threads(1) # Force k_base = nb - k_factor = nb // k # 500000 // 10 = 50000 + k_factor = nb // k params = faiss.IndexRefineSearchParameters( k_factor=float(k_factor) ) @@ -504,9 +284,7 @@ def test_ratio_dims_scanned(self): faiss.cvar.indexPanorama_stats.reset() D, I = index.search(xq, k, params=params) - self.assert_search_results_equal( - D_base, I_base, D, I, atol=1e-4 - ) + self.assert_search_results_equal(D_base, I_base, D, I) ratios.append( faiss.cvar.indexPanorama_stats.ratio_dims_scanned diff --git a/thirdparty/faiss/tests/test_residual_quantizer.py b/thirdparty/faiss/tests/test_residual_quantizer.py index a718c8ab7..83b15ca08 100644 --- a/thirdparty/faiss/tests/test_residual_quantizer.py +++ b/thirdparty/faiss/tests/test_residual_quantizer.py @@ -13,8 +13,6 @@ from faiss.contrib.inspect_tools import get_additive_quantizer_codebooks ########################################################### - - # Reference implementation of encoding with beam search ########################################################### @@ -43,35 +41,19 @@ def beam_search_encode_step_ref(cent, residuals, codes, L): ) cent_distances = cent_distances.reshape(n, beam_size, K) - # TODO write in vector form - - if beam_size * K <= L: - # then keep all the results - new_beam_size = beam_size * K - new_codes = np.zeros((n, beam_size, K, m + 1), dtype=int) - new_residuals = np.zeros((n, beam_size, K, d), dtype="float32") - for i in range(n): - new_codes[i, :, :, :-1] = codes[i] - new_codes[i, :, :, -1] = np.arange(K) - new_residuals[i] = residuals[i].reshape(1, d) - cent.reshape(K, d) - new_codes = new_codes.reshape(n, new_beam_size, m + 1) - new_residuals = new_residuals.reshape(n, new_beam_size, d) - new_distances = cent_distances.reshape(n, new_beam_size) - else: - # keep top-L results - new_beam_size = L - new_codes = np.zeros((n, L, m + 1), dtype=int) - new_residuals = np.zeros((n, L, d), dtype="float32") - new_distances = np.zeros((n, L), dtype="float32") - for i in range(n): - cd = cent_distances[i].ravel() - jl = np.argsort(cd)[:L] # TODO argpartition - js = jl // K # input beam index - ls = jl % K # centroid index - new_codes[i, :, :-1] = codes[i, js, :] - new_codes[i, :, -1] = ls - new_residuals[i, :, :] = residuals[i, js, :] - cent[ls, :] - new_distances[i, :] = cd[jl] + # keep top-L results + new_codes = np.zeros((n, L, m + 1), dtype=int) + new_residuals = np.zeros((n, L, d), dtype="float32") + new_distances = np.zeros((n, L), dtype="float32") + for i in range(n): + cd = cent_distances[i].ravel() + jl = np.argsort(cd)[:L] + js = jl // K # input beam index + ls = jl % K # centroid index + new_codes[i, :, :-1] = codes[i, js, :] + new_codes[i, :, -1] = ls + new_residuals[i, :, :] = residuals[i, js, :] - cent[ls, :] + new_distances[i, :] = cd[jl] return new_codes, new_residuals, new_distances @@ -136,10 +118,11 @@ def beam_search_encoding_ref(centroids, x, L): class TestBeamSearch(unittest.TestCase): - def do_test(self, K=70, L=10, use_assign_index=False): + def do_test(self, use_assign_index=False): """compare C++ beam search with reference python implementation""" d = 32 n = 500 + K = 70 L = 10 # beam size rs = np.random.RandomState(123) @@ -147,7 +130,6 @@ def do_test(self, K=70, L=10, use_assign_index=False): cent = rs.rand(K, d).astype("float32") - # first quant step --> input beam size is 1 codes = np.zeros((n, 1, 0), dtype=int) residuals = x.reshape(n, 1, d) @@ -165,7 +147,6 @@ def do_test(self, K=70, L=10, use_assign_index=False): np.testing.assert_array_equal(new_residuals, ref_residuals) np.testing.assert_allclose(new_distances, ref_distances, rtol=1e-5) - # second quant step: K = 50 cent = rs.rand(K, d).astype("float32") @@ -189,12 +170,6 @@ def test_beam_search(self): def test_beam_search_assign_index(self): self.do_test(use_assign_index=True) - def test_small_beam(self): - self.do_test(L=1) - - def test_small_beam_2(self): - self.do_test(L=2) - def eval_codec(q, xb): codes = q.compute_codes(xb) @@ -213,12 +188,8 @@ def test_training(self): xb = ds.get_database() rq = faiss.ResidualQuantizer(ds.d, 4, 6) - rq.verbose rq.verbose = True - # rq.train_type = faiss.ResidualQuantizer.Train_default - rq.cp.verbose - # rq.cp.verbose = True rq.train(xt) err_rq = eval_codec(rq, xb) @@ -260,16 +231,13 @@ def test_training_with_limited_mem(self): rq0 = faiss.ResidualQuantizer(ds.d, 4, 6) rq0.train_type = faiss.ResidualQuantizer.Train_default rq0.max_beam_size = 5 - # rq0.verbose = True rq0.train(xt) cb0 = get_additive_quantizer_codebooks(rq0) rq1 = faiss.ResidualQuantizer(ds.d, 4, 6) rq1.train_type = faiss.ResidualQuantizer.Train_default rq1.max_beam_size = 5 - rq1.max_mem_distances rq1.max_mem_distances = 3000 * ds.d * 4 * 3 - # rq1.verbose = True rq1.train(xt) cb1 = get_additive_quantizer_codebooks(rq1) @@ -278,9 +246,7 @@ def test_training_with_limited_mem(self): def test_compute_codes_matches_none(self): """RQ encode is integer-valued, so codes must be bit-exact across - SIMD levels. Catches dispatch drift in - residual_quantizer_encode_steps.cpp:96,369 (with_simd_level_256bit). - """ + SIMD levels.""" ds = datasets.SyntheticDataset(32, 1000, 200, 0) rq = faiss.ResidualQuantizer(ds.d, 4, 6) rq.train_type = faiss.ResidualQuantizer.Train_default @@ -303,13 +269,12 @@ def test_clipping(self): rq.max_beam_size = 5 rq.train(ds.get_train()) - rq.max_beam_size = 1 # is not he same for a large beam size + rq.max_beam_size = 1 # is not the same for a large beam size codes = rq.compute_codes(ds.get_database()) rq2 = faiss.ResidualQuantizer(ds.d, 2, 4) rq2.initialize_from(rq) self.assertEqual(rq2.M, 2) - # verify that the beginning of the codes are the same codes2 = rq2.compute_codes(ds.get_database()) rq3 = faiss.ResidualQuantizer(ds.d, 3, 4) @@ -317,7 +282,6 @@ def test_clipping(self): self.assertEqual(rq3.M, 3) codes3 = rq3.compute_codes(ds.get_database() - rq2.decode(codes2)) - # verify that prefixes are the same for i in range(ds.nb): br = faiss.BitstringReader(faiss.swig_ptr(codes[i]), rq.code_size) br2 = faiss.BitstringReader( @@ -335,61 +299,6 @@ def test_clipping(self): ########################################################### -def unpack_codes(rq, packed_codes): - nbits = faiss.vector_to_array(rq.nbits) - if np.all(nbits == 8): - return packed_codes.astype("uint32") - nbits = [int(x) for x in nbits] - nb = len(nbits) - n, code_size = packed_codes.shape - codes = np.zeros((n, nb), dtype="uint32") - for i in range(n): - br = faiss.BitstringReader(faiss.swig_ptr(packed_codes[i]), code_size) - for j, nbi in enumerate(nbits): - codes[i, j] = br.read(nbi) - return codes - - -def retrain_AQ_codebook(index, xt): - """reference implementation of codebook retraining""" - rq = index.rq - - codes_packed = index.sa_encode(xt) - n, code_size = codes_packed.shape - - index.sa_decode(codes_packed) - - codes = unpack_codes(index.rq, codes_packed) - codebook_offsets = faiss.vector_to_array(rq.codebook_offsets) - - # build sparse code matrix (represented as a dense matrix) - C = np.zeros((n, rq.total_codebook_size)) - - for i in range(n): - C[i][codes[i] + codebook_offsets[:-1]] = 1 - - # import pdb; pdb.set_trace() - # import scipy - # B, residuals, rank, singvals = np.linalg.lstsq(C, xt, rcond=None) - if True: - B, residuals, rank, singvals = np.linalg.lstsq(C, xt, rcond=None) - else: - import scipy.linalg - - B, residuals, rank, singvals = scipy.linalg.lstsq( - C, - xt, - ) - - # replace codebook - # faiss.copy_array_to_vector( - # B.astype('float32').ravel(), index.rq.codebooks) - # update codebook tables - # index.rq.compute_codebook_tables() - - return C, B - - class TestIndexResidualQuantizer(unittest.TestCase): def test_io(self): @@ -416,23 +325,19 @@ def test_equiv_rq(self): """ ds = datasets.SyntheticDataset(32, 3000, 1000, 50) - # make a flat RQ iflat = faiss.IndexResidualQuantizer(ds.d, 5, 4) iflat.rq.train_type = faiss.ResidualQuantizer.Train_default iflat.train(ds.get_train()) iflat.add(ds.get_database()) - # ref search result Dref, Iref = iflat.search(ds.get_queries(), 10) - # get its codebooks + encoded version of the dataset codebooks = get_additive_quantizer_codebooks(iflat.rq) codes = faiss.vector_to_array(iflat.codes).reshape(-1, iflat.code_size) # make an IVF with 2x4 + 3x4 = 5x4 bits ivf = faiss.index_factory(ds.d, "IVF256(RCQ2x4),RQ3x4") - # initialize the codebooks rcq = faiss.downcast_index(ivf.quantizer) faiss.copy_array_to_vector( np.vstack(codebooks[: rcq.rq.M]).ravel(), rcq.rq.codebooks @@ -461,20 +366,6 @@ def test_equiv_rq(self): np.testing.assert_array_equal(Iref, Inew) np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5) - def test_factory(self): - index = faiss.index_factory(5, "RQ2x16_3x8_6x4") - - np.testing.assert_array_equal( - faiss.vector_to_array(index.rq.nbits), - np.array([16, 16, 8, 8, 8, 4, 4, 4, 4, 4, 4]), - ) - - def test_factory_norm(self): - index = faiss.index_factory(5, "RQ8x8_Nqint8") - self.assertEqual( - index.rq.search_type, faiss.AdditiveQuantizer.ST_norm_qint8 - ) - def test_search_decompress(self): ds = datasets.SyntheticDataset(32, 1000, 1000, 100) @@ -489,12 +380,9 @@ def test_search_decompress(self): D, I = ir.search(ds.get_queries(), 10) gt = ds.get_groundtruth() - recalls = { - rank: (I[:, :rank] == gt[:, :1]).sum() / len(gt) - for rank in [1, 10, 100] - } - # recalls are {1: 0.05, 10: 0.37, 100: 0.37} - self.assertGreater(recalls[10], 0.35) + recall = (I == gt[:, :1]).sum() / len(gt) + # ref run: 0.37 + self.assertGreater(recall, 0.35) def do_exact_search_equiv(self, norm_type): """searching with this normalization should yield @@ -528,30 +416,6 @@ def test_exact_equiv_norm_float(self): def test_exact_equiv_norm_from_LUT(self): self.do_exact_search_equiv(faiss.AdditiveQuantizer.ST_norm_from_LUT) - def test_reestimate_codebook(self): - ds = datasets.SyntheticDataset(32, 1000, 1000, 100) - - xt = ds.get_train() - xb = ds.get_database() - - ir = faiss.IndexResidualQuantizer(ds.d, 3, 4) - ir.train(xt) - - # ir.rq.verbose = True - xb_decoded = ir.sa_decode(ir.sa_encode(xb)) - err_before = ((xb - xb_decoded) ** 2).sum() - - # test manual call of retrain_AQ_codebook - - ref_C, ref_codebook = retrain_AQ_codebook(ir, xb) - ir.rq.retrain_AQ_codebook(len(xb), faiss.swig_ptr(xb)) - - xb_decoded = ir.sa_decode(ir.sa_encode(xb)) - err_after = ((xb - xb_decoded) ** 2).sum() - - # ref run: 8347.857 vs. 7710.014 - self.assertGreater(err_before, err_after * 1.05) - def test_reestimate_codebook_2(self): ds = datasets.SyntheticDataset(32, 1000, 0, 0) xt = ds.get_train() @@ -594,14 +458,11 @@ def test_IVF_resiudal(self): rq = quantizer.rq rq.train_type = faiss.ResidualQuantizer.Train_default index = faiss.IndexIVFFlat(quantizer, ds.d, 1 << rq.tot_bits) - index.quantizer_trains_alone index.quantizer_trains_alone = True index.train(xt) index.add(xb) - # make sure that increasing the nprobe increases accuracy - index.nprobe = 10 D, I = index.search(ds.get_queries(), 10) r10 = (I == gt[None, :]).sum() / ds.nq @@ -612,8 +473,6 @@ def test_IVF_resiudal(self): self.assertGreater(r40, r10) - # make sure that decreasing beam factor decreases accuracy - quantizer.beam_factor quantizer.beam_factor = 1.0 index.nprobe = 10 D, I = index.search(ds.get_queries(), 10) @@ -638,35 +497,6 @@ def test_factory(self): np.testing.assert_equal(Dref, Dnew) np.testing.assert_equal(Iref, Inew) - def test_ivfsq(self): - ds = datasets.SyntheticDataset(32, 3000, 1000, 100) - - xt = ds.get_train() - xb = ds.get_database() - - gt = ds.get_groundtruth(1) - - # RQ 2x5 = 10 bits = 1024 centroids - index = faiss.index_factory(ds.d, "IVF1024(RCQ2x5),SQ8") - quantizer = faiss.downcast_index(index.quantizer) - rq = quantizer.rq - rq.train_type = faiss.ResidualQuantizer.Train_default - - index.train(xt) - index.add(xb) - - # make sure that increasing the nprobe increases accuracy - - index.nprobe = 10 - D, I = index.search(ds.get_queries(), 10) - r10 = (I == gt[None, :]).sum() / ds.nq - - index.nprobe = 40 - D, I = index.search(ds.get_queries(), 10) - r40 = (I == gt[None, :]).sum() / ds.nq - - self.assertGreater(r40, r10) - def test_rcq_LUT(self): ds = datasets.SyntheticDataset(32, 3000, 1000, 100) @@ -699,10 +529,8 @@ def test_rcq_LUT(self): np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5) np.testing.assert_array_equal(Iref, Inew) - # check i/o CDref, CIref = quantizer.search(ds.get_queries(), 10) quantizer2 = faiss.deserialize_index(faiss.serialize_index(quantizer)) - quantizer2.search(ds.get_queries(), 10) CDnew, CInew = quantizer2.search(ds.get_queries(), 10) np.testing.assert_array_almost_equal(CDref, CDnew, decimal=5) np.testing.assert_array_equal(CIref, CInew) @@ -740,16 +568,12 @@ def test_RCQ_knn(self): sp = faiss.swig_ptr - # test norms computation - norms_ref = (cents**2).sum(1) norms = np.zeros(1 << aq.tot_bits, dtype="float32") aq.compute_centroid_norms(sp(norms)) np.testing.assert_array_almost_equal(norms, norms_ref, decimal=5) - # test IP search - Dref, Iref = faiss.knn(xq, cents, 10, metric=faiss.METRIC_INNER_PRODUCT) Dnew = np.zeros_like(Dref) @@ -760,8 +584,6 @@ def test_RCQ_knn(self): np.testing.assert_array_almost_equal(Dref, Dnew, decimal=5) np.testing.assert_array_equal(Iref, Inew) - # test L2 search - Dref, Iref = faiss.knn(xq, cents, 10, metric=faiss.METRIC_L2) Dnew = np.zeros_like(Dref) @@ -824,7 +646,6 @@ def test_search_L2(self): ir.add(xb) Dref, Iref = ir.search(xq, 10) - # 388 inter_ref = faiss.eval_intersection(Iref, gt) AQ = faiss.AdditiveQuantizer @@ -870,7 +691,6 @@ def do_test_accuracy(self, by_residual, st): ) index.by_residual = by_residual - index.rq.train_type index.rq.train_type = faiss.ResidualQuantizer.Train_default index.rq.max_beam_size = 30 @@ -884,7 +704,6 @@ def do_test_accuracy(self, by_residual, st): inter = faiss.eval_intersection(I, ds.get_groundtruth(10)) inters.append(inter) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -893,8 +712,6 @@ def do_test_accuracy(self, by_residual, st): inters = np.array(inters) if by_residual: - # check that we have increasing intersection measures with - # nprobe self.assertTrue(np.all(inters[1:] >= inters[:-1])) else: self.assertTrue(np.all(inters[1:3] >= inters[:2])) @@ -902,7 +719,6 @@ def do_test_accuracy(self, by_residual, st): iflat = faiss.IndexResidualQuantizer( ds.d, 3, 4, faiss.METRIC_L2, st ) - iflat.rq.train_type iflat.rq.train_type = faiss.ResidualQuantizer.Train_default iflat.rq.max_beam_size = 30 iflat.train(ds.get_train()) @@ -969,7 +785,6 @@ def do_test_accuracy_IP(self, by_residual): index.cp.spherical = True index.by_residual = by_residual - index.rq.train_type index.rq.train_type = faiss.ResidualQuantizer.Train_default index.train(ds.get_train()) @@ -986,8 +801,6 @@ def do_test_accuracy_IP(self, by_residual): # there are many ties because the codes are so short self.assertLess((I != I2).sum(), I.size * 0.1) - # D2, I2 = index2.search(ds.get_queries(), 10) - inter = faiss.eval_intersection(I, ds.get_groundtruth(10)) inters.append(inter) self.assertTrue(np.all(inters[1:4] >= inters[:3])) @@ -1021,9 +834,6 @@ def precomp_codebooks(codebooks): def beam_search_encode_step_tab( codes, L, distances, codebook_cross_prods_i, query_cp_i, cent_norms_i ): - """Reference beam search implementation - encodes a residual table. - """ n, beam_size, m = codes.shape n2, beam_size_2 = distances.shape @@ -1049,30 +859,17 @@ def beam_search_encode_step_tab( new_distances += 2 * dotprods cent_distances = new_distances - # TODO write in vector form - - if beam_size * K <= L: - # then keep all the results - new_beam_size = beam_size * K - new_codes = np.zeros((n, beam_size, K, m + 1), dtype=int) - for i in range(n): - new_codes[i, :, :, :-1] = codes[i] - new_codes[i, :, :, -1] = np.arange(K) - new_codes = new_codes.reshape(n, new_beam_size, m + 1) - new_distances = cent_distances.reshape(n, new_beam_size) - else: - # keep top-L results - new_beam_size = L - new_codes = np.zeros((n, L, m + 1), dtype=int) - new_distances = np.zeros((n, L), dtype="float32") - for i in range(n): - cd = cent_distances[i].ravel() - jl = np.argsort(cd)[:L] # TODO argpartition - js = jl // K # input beam index - ls = jl % K # centroid index - new_codes[i, :, :-1] = codes[i, js, :] - new_codes[i, :, -1] = ls - new_distances[i, :] = cd[jl] + # keep top-L results + new_codes = np.zeros((n, L, m + 1), dtype=int) + new_distances = np.zeros((n, L), dtype="float32") + for i in range(n): + cd = cent_distances[i].ravel() + jl = np.argsort(cd)[:L] + js = jl // K # input beam index + ls = jl % K # centroid index + new_codes[i, :, :-1] = codes[i, js, :] + new_codes[i, :, -1] = ls + new_distances[i, :] = cd[jl] return new_codes, new_distances @@ -1172,13 +969,9 @@ def test_precomp(self): precomp = precomp_codebooks(codebooks) codebook_cross_prods_ref, cent_norms_ref = precomp - # validate that the python tab-based encoding works xb = ds.get_database() ref_codes, _, _ = beam_search_encoding_ref(codebooks, xb, 7) - new_codes, _ = beam_search_encoding_tab(codebooks, xb, 7, precomp) - np.testing.assert_array_equal(ref_codes, new_codes) - # check C++ precomp tables rq.compute_codebook_tables() codebook_cross_prods = faiss.vector_to_array(rq.codebook_cross_products) ofs = 0 @@ -1286,7 +1079,6 @@ def eval_index_accuracy(self, index_key): D, I = index.search(ds.get_queries(), 10) inter = faiss.eval_intersection(I, ds.get_groundtruth(10)) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -1298,7 +1090,6 @@ def test_factory(self): AQ = faiss.AdditiveQuantizer ns, Msub, nbits = 2, 4, 8 index = faiss.index_factory(64, f"PRQ{ns}x{Msub}x{nbits}_Nqint8") - assert isinstance(index, faiss.IndexProductResidualQuantizer) self.assertEqual(index.prq.nsplits, ns) self.assertEqual(index.prq.subquantizer(0).M, Msub) self.assertEqual(index.prq.subquantizer(0).nbits.at(0), nbits) @@ -1308,12 +1099,8 @@ def test_factory(self): self.assertEqual(index.prq.code_size, code_size) def test_symmetric_dis(self): - """AQDistanceComputerLUT::symmetric_dis must decode into its reserved - scratch region, not into LUT.data(). Decoding into LUT.data() silently - clobbers the lookup table computed by set_query(), so an interleaved - symmetric_dis() corrupts subsequent asymmetric distances -- which is - exactly what HNSW construction does. No crash, so only a value check - catches it.""" + """AQDistanceComputerLUT::symmetric_dis must not decode into + LUT.data(): HNSW construction interleaves it with set_query().""" ds = datasets.SyntheticDataset(64, 1000, 10000, 1) for search_type in ( faiss.AdditiveQuantizer.ST_LUT_nonorm, @@ -1355,7 +1142,6 @@ def eval_index_accuracy(self, factory_key): # 1.05: test relaxed for OSX on ARM self.assertTrue(np.all(inters[1:] * 1.05 >= inters[:-1])) - # do a little I/O test index2 = faiss.deserialize_index(faiss.serialize_index(index)) D2, I2 = index2.search(ds.get_queries(), 10) np.testing.assert_array_equal(I2, I) @@ -1363,9 +1149,6 @@ def eval_index_accuracy(self, factory_key): return inter - def test_index_accuracy(self): - self.eval_index_accuracy("IVF100,PRQ2x2x5_Nqint8") - def test_index_accuracy2(self): """check that the error is in the same ballpark as RQ.""" inter1 = self.eval_index_accuracy("IVF100,PRQ2x2x5_Nqint8") @@ -1376,12 +1159,8 @@ def test_factory(self): AQ = faiss.AdditiveQuantizer ns, Msub, nbits = 2, 4, 8 index = faiss.index_factory(64, f"IVF100,PRQ{ns}x{Msub}x{nbits}_Nqint8") - assert isinstance(index, faiss.IndexIVFProductResidualQuantizer) self.assertEqual(index.nlist, 100) self.assertEqual(index.prq.nsplits, ns) self.assertEqual(index.prq.subquantizer(0).M, Msub) self.assertEqual(index.prq.subquantizer(0).nbits.at(0), nbits) self.assertEqual(index.prq.search_type, AQ.ST_norm_qint8) - - code_size = (ns * Msub * nbits + 7) // 8 + 1 - self.assertEqual(index.prq.code_size, code_size) diff --git a/thirdparty/faiss/tests/test_rowwise_minmax.py b/thirdparty/faiss/tests/test_rowwise_minmax.py index 32b79ec61..a62db9823 100644 --- a/thirdparty/faiss/tests/test_rowwise_minmax.py +++ b/thirdparty/faiss/tests/test_rowwise_minmax.py @@ -20,30 +20,23 @@ def compare_train_vs_train_inplace(self, factory_key): xt, x, _ = get_dataset_2(d, nt, nb, nq) - assert x.size > 0 - codec = faiss.index_factory(d, factory_key) - # use the regular .train() codec.train(xt) codes_train = codec.sa_encode(x) decoded = codec.sa_decode(codes_train) - # use .train_inplace() xt_cloned = np.copy(xt) codec.train_inplace(xt_cloned) codes_train_inplace = codec.sa_encode(x) - # compare .train and .train_inplace codes n_diff = (codes_train != codes_train_inplace).sum() self.assertEqual(n_diff, 0) - # make sure that the array used for .train_inplace got affected n_diff_xt = (xt_cloned != xt).sum() self.assertNotEqual(n_diff_xt, 0) - # make sure that the reconstruction error is not crazy reconstruction_err = ((x - decoded) ** 2).sum() self.assertLess(reconstruction_err, 0.6) diff --git a/thirdparty/faiss/tests/test_scalar_quantizer.cpp b/thirdparty/faiss/tests/test_scalar_quantizer.cpp index fc6d38ad4..a619650c2 100644 --- a/thirdparty/faiss/tests/test_scalar_quantizer.cpp +++ b/thirdparty/faiss/tests/test_scalar_quantizer.cpp @@ -7,6 +7,7 @@ #include +#include #include #include #include @@ -22,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -36,13 +36,6 @@ std::vector make_normalized_vectors(size_t n, size_t d) { return x; } -float mean_squared_error( - const std::vector& x, - const std::vector& y) { - EXPECT_EQ(x.size(), y.size()); - return faiss::fvec_L2sqr(x.data(), y.data(), x.size()) / x.size(); -} - template using ScalarLloydMaxQuantizer = faiss::scalar_quantizer:: QuantizerLloydMax; @@ -93,6 +86,24 @@ std::vector available_lloyd_max_simd_levels() { return levels; } +// SIMD levels with scalar-quantizer kernels that can be checked for parity +// against the scalar (NONE) path. Unlike dispatch tests, parity tests do not +// require dimension restrictions, so RISCV_RVV (no alignment constraints) +// is included here. +std::vector available_sq_parity_simd_levels() { + std::vector levels; + for (faiss::SIMDLevel level : + {faiss::SIMDLevel::AVX512, + faiss::SIMDLevel::AVX2, + faiss::SIMDLevel::ARM_NEON, + faiss::SIMDLevel::RISCV_RVV}) { + if (faiss::SIMDConfig::is_simd_level_available(level)) { + levels.push_back(level); + } + } + return levels; +} + template void expect_lloyd_max_simd_dispatch_for_compatible_dim( faiss::SIMDLevel level, @@ -153,13 +164,49 @@ void expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim( EXPECT_EQ(typeid(*scanner_raw), typeid(ScalarLloydMaxL2Scanner)); } -template -void check_lloyd_max_distance_path_parity( +// Random data never lands exactly on a boundary, so the distance-path parity +// checks cannot catch a SIMD encoder whose tie-break differs from the scalar +// upper_bound (x == b encodes to the upper bin). Encode the boundaries +// themselves and require byte-identical codes. +void check_lloyd_max_boundary_encode_parity( faiss::SIMDLevel level, faiss::ScalarQuantizer::QuantizerType qtype) { ScopedSIMDLevel scoped(level); const size_t d = 32; - const size_t n = 128; + faiss::ScalarQuantizer sq = make_trained_lloyd_max_sq(d, qtype); + + const size_t k = (sq.trained.size() + 1) / 2; + const float* boundaries = sq.trained.data() + k; + std::vector x(d); + for (size_t i = 0; i < d; i++) { + x[i] = boundaries[i % (k - 1)]; + } + x[d - 2] = 0.0f; + x[d - 1] = -0.0f; + + std::unique_ptr scalar_quant( + faiss::scalar_quantizer::sq_select_quantizer< + faiss::SIMDLevel::NONE>(qtype, d, sq.trained)); + std::unique_ptr simd_quant( + sq.select_quantizer()); + ASSERT_NE(scalar_quant, nullptr); + ASSERT_NE(simd_quant, nullptr); + + std::vector ref(sq.code_size, 0), out(sq.code_size, 0); + scalar_quant->encode_vector(x.data(), ref.data()); + simd_quant->encode_vector(x.data(), out.data()); + EXPECT_EQ(ref, out); +} + +// Parity between a SIMD level and the scalar (NONE) path for one quantizer +// type, metric and dimension. +void check_sq_distance_path_parity( + faiss::SIMDLevel level, + faiss::ScalarQuantizer::QuantizerType qtype, + faiss::MetricType metric, + size_t d) { + ScopedSIMDLevel scoped(level); + const size_t n = 64; std::vector xb = make_normalized_vectors(n, d); std::vector xq = make_normalized_vectors(1, d); @@ -169,44 +216,90 @@ void check_lloyd_max_distance_path_parity( std::vector codes(sq.code_size * n, 0); sq.compute_codes(xb.data(), codes.data(), n); + // fp16/bf16 codes are raw IEEE bit patterns: arbitrary bytes can decode + // to NaN, so only codes produced by compute_codes are checked for those. + const bool arbitrary_bytes_ok = qtype != faiss::ScalarQuantizer::QT_fp16 && + qtype != faiss::ScalarQuantizer::QT_bf16; + + std::vector zero_code(sq.code_size, 0); + std::vector max_code(sq.code_size, 0xff); + std::vector query_codes = { + codes.data(), + codes.data() + sq.code_size, + codes.data() + 2 * sq.code_size, + codes.data() + 3 * sq.code_size}; + if (arbitrary_bytes_ok) { + query_codes.push_back(zero_code.data()); + query_codes.push_back(max_code.data()); + } + + std::unique_ptr scalar_quant( + faiss::scalar_quantizer::sq_select_quantizer< + faiss::SIMDLevel::NONE>(qtype, d, sq.trained)); + std::unique_ptr simd_quant( + sq.select_quantizer()); + ASSERT_NE(scalar_quant, nullptr); + ASSERT_NE(simd_quant, nullptr); + + for (const uint8_t* code : query_codes) { + std::vector ref(d), out(d); + scalar_quant->decode_vector(code, ref.data()); + simd_quant->decode_vector(code, out.data()); + for (size_t j = 0; j < d; j++) { + EXPECT_NEAR( + ref[j], out[j], 1e-5 * std::max(1.0f, std::fabs(ref[j]))); + } + } + + auto expect_distance_near = [](float ref, float out) { + EXPECT_NEAR(ref, out, 5e-3 * std::max(1.0f, std::fabs(ref))); + }; + std::unique_ptr scalar_dc( faiss::scalar_quantizer::sq_select_distance_computer< - faiss::SIMDLevel::NONE>( - faiss::METRIC_L2, qtype, d, sq.trained)); + faiss::SIMDLevel::NONE>(metric, qtype, d, sq.trained)); std::unique_ptr simd_dc( - sq.get_distance_computer(faiss::METRIC_L2)); + sq.get_distance_computer(metric)); ASSERT_NE(scalar_dc, nullptr); ASSERT_NE(simd_dc, nullptr); scalar_dc->set_query(xq.data()); simd_dc->set_query(xq.data()); - std::vector zero_code(sq.code_size, 0); - std::vector max_code(sq.code_size, 0xff); - const std::array query_codes = { - codes.data(), - codes.data() + sq.code_size, - codes.data() + 2 * sq.code_size, - codes.data() + 3 * sq.code_size, - zero_code.data(), - max_code.data()}; - for (const uint8_t* code : query_codes) { - EXPECT_NEAR( - scalar_dc->query_to_code(code), - simd_dc->query_to_code(code), - 1e-3); + expect_distance_near( + scalar_dc->query_to_code(code), simd_dc->query_to_code(code)); } - std::vector bundle(4 * sq.code_size, 0); - std::memcpy(bundle.data(), zero_code.data(), sq.code_size); - std::memcpy(bundle.data() + sq.code_size, max_code.data(), sq.code_size); - std::memcpy(bundle.data() + 2 * sq.code_size, codes.data(), sq.code_size); - std::memcpy( - bundle.data() + 3 * sq.code_size, - codes.data() + sq.code_size, - sq.code_size); + float scalar_dis[4], simd_dis[4]; + scalar_dc->query_to_codes_batch_4( + query_codes[0], + query_codes[1], + query_codes[2], + query_codes[3], + scalar_dis[0], + scalar_dis[1], + scalar_dis[2], + scalar_dis[3]); + simd_dc->query_to_codes_batch_4( + query_codes[0], + query_codes[1], + query_codes[2], + query_codes[3], + simd_dis[0], + simd_dis[1], + simd_dis[2], + simd_dis[3]); + for (int k = 0; k < 4; k++) { + expect_distance_near(scalar_dis[k], simd_dis[k]); + EXPECT_EQ(simd_dis[k], simd_dc->query_to_code(query_codes[k])); + } + std::vector bundle(4 * sq.code_size, 0); + for (int k = 0; k < 4; k++) { + std::memcpy( + bundle.data() + k * sq.code_size, query_codes[k], sq.code_size); + } scalar_dc->codes = bundle.data(); scalar_dc->code_size = sq.code_size; simd_dc->codes = bundle.data(); @@ -219,17 +312,16 @@ void check_lloyd_max_distance_path_parity( {2, 3}, }}; for (const auto& [lhs, rhs] : pairs) { - EXPECT_NEAR( + expect_distance_near( scalar_dc->symmetric_dis(lhs, rhs), - simd_dc->symmetric_dis(lhs, rhs), - 1e-3); + simd_dc->symmetric_dis(lhs, rhs)); } std::unique_ptr scalar_scanner( faiss::scalar_quantizer::sq_select_InvertedListScanner< faiss::SIMDLevel::NONE>( qtype, - faiss::METRIC_L2, + metric, d, sq.code_size, sq.trained, @@ -239,7 +331,7 @@ void check_lloyd_max_distance_path_parity( false)); std::unique_ptr simd_scanner( sq.select_InvertedListScanner( - faiss::METRIC_L2, nullptr, false, nullptr, false)); + metric, nullptr, false, nullptr, false)); ASSERT_NE(scalar_scanner, nullptr); ASSERT_NE(simd_scanner, nullptr); @@ -249,10 +341,58 @@ void check_lloyd_max_distance_path_parity( simd_scanner->set_list(0, 0.0f); for (const uint8_t* code : query_codes) { - EXPECT_NEAR( + expect_distance_near( scalar_scanner->distance_to_code(code), - simd_scanner->distance_to_code(code), - 1e-3); + simd_scanner->distance_to_code(code)); + } +} + +// The IVF scanner scores most codes of an inverted list four at a time and +// the rest one at a time, so the batch must return exactly the single-code +// distances. Both are also checked against the inner product with the +// decoded vectors, which bounds the rounding of the precomputed QT_8bit form +// much tighter than the parity check against the scalar path. +void check_sq8_ip_batch_matches_single(faiss::SIMDLevel level, size_t d) { + ScopedSIMDLevel scoped(level); + const size_t n = 64; + std::vector xb = make_normalized_vectors(n, d); + std::vector xq(d); + faiss::float_randn(xq.data(), d, 4321); + faiss::fvec_renorm_L2(d, 1, xq.data()); + + faiss::ScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit); + sq.train(n, xb.data()); + std::vector codes(sq.code_size * n); + sq.compute_codes(xb.data(), codes.data(), n); + std::vector decoded(n * d); + sq.decode(codes.data(), decoded.data(), n); + + std::unique_ptr dc( + sq.get_distance_computer(faiss::METRIC_INNER_PRODUCT)); + ASSERT_NE(dc, nullptr); + dc->set_query(xq.data()); + + const size_t cs = sq.code_size; + for (size_t i = 0; i < n; i += 4) { + const uint8_t* c = codes.data() + i * cs; + float dis[4]; + dc->query_to_codes_batch_4( + c, + c + cs, + c + 2 * cs, + c + 3 * cs, + dis[0], + dis[1], + dis[2], + dis[3]); + for (size_t k = 0; k < 4; k++) { + EXPECT_EQ(dis[k], dc->query_to_code(c + k * cs)); + double ref = 0; + for (size_t j = 0; j < d; j++) { + ref += double(xq[j]) * decoded[(i + k) * d + j]; + } + EXPECT_NEAR(dis[k], ref, 1e-5); + } } } @@ -280,7 +420,6 @@ void check_tqmse_roundtrip( void check_eden_roundtrip( size_t d, - size_t nb_bits, faiss::ScalarQuantizer::QuantizerType qtype) { const size_t n = 128; std::vector x = make_normalized_vectors(n, d); @@ -288,10 +427,6 @@ void check_eden_roundtrip( sq.train(0, nullptr); - const size_t k = size_t(1) << nb_bits; - EXPECT_EQ(sq.bits, nb_bits); - EXPECT_EQ(sq.trained.size(), 2 * k - 1); - std::vector codes(sq.code_size * n, 0); sq.compute_codes(x.data(), codes.data(), n); @@ -333,63 +468,6 @@ TEST(ScalarQuantizer, RSQuantilesClamping) { ASSERT_NO_THROW(sq.train(n, x.data())); } -TEST(ScalarQuantizer, RSQuantilesOddSize) { - int d = 4; - int n = 5; - - std::vector x(d * n); - for (size_t i = 0; i < x.size(); i++) { - x[i] = static_cast(i); - } - - faiss::ScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit); - sq.rangestat = faiss::ScalarQuantizer::RS_quantiles; - - sq.rangestat_arg = 0.4f; - ASSERT_NO_THROW(sq.train(n, x.data())); - - sq.rangestat_arg = 0.5f; - ASSERT_NO_THROW(sq.train(n, x.data())); - - sq.rangestat_arg = 0.6f; - ASSERT_NO_THROW(sq.train(n, x.data())); -} - -TEST(ScalarQuantizer, RSQuantilesValidRange) { - int d = 8; - int n = 100; - - std::vector x(d * n); - for (size_t i = 0; i < x.size(); i++) { - x[i] = static_cast(i); - } - - faiss::ScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit); - sq.rangestat = faiss::ScalarQuantizer::RS_quantiles; - sq.rangestat_arg = 0.1f; - - sq.train(n, x.data()); - - std::vector codes(sq.code_size * n); - ASSERT_NO_THROW(sq.compute_codes(x.data(), codes.data(), n)); - - std::vector decoded(d * n); - ASSERT_NO_THROW(sq.decode(codes.data(), decoded.data(), n)); -} - -TEST(ScalarQuantizer, RSQuantilesSmallDataset) { - int d = 2; - int n = 2; - - std::vector x = {1.0f, 2.0f, 3.0f, 4.0f}; - - faiss::ScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit); - sq.rangestat = faiss::ScalarQuantizer::RS_quantiles; - sq.rangestat_arg = 0.1f; - - ASSERT_NO_THROW(sq.train(n, x.data())); -} - TEST(ScalarQuantizer, MinimalTraining) { std::vector x = {1.0f, 2.0f, 3.0f, 4.0f}; using SQ = faiss::ScalarQuantizer; @@ -404,18 +482,53 @@ TEST(ScalarQuantizer, MinimalTraining) { for (size_t d : {1, 2}) { faiss::IndexScalarQuantizer index(d, qt); index.sq.rangestat = SQ::RS_minmax; - // n=0 is insufficient. EXPECT_THROW(index.train(0, x.data()), faiss::FaissException); - // nullptr throws, not crashes. EXPECT_THROW(index.train(1, nullptr), faiss::FaissException); - // 1x1 values is allowed. EXPECT_NO_THROW(index.train(1, x.data())); } } } +TEST(ScalarQuantizer, RVVDirect8bitEncodingMatchesTruncation) { + if (!faiss::SIMDConfig::is_simd_level_available( + faiss::SIMDLevel::RISCV_RVV)) { + GTEST_SKIP() << "RVV is not available"; + } + ScopedSIMDLevel scoped(faiss::SIMDLevel::RISCV_RVV); + // Negative fractions greater than -1 truncate to the valid code zero. + // Inputs outside (-1, 256) have no portable scalar conversion contract. + const std::vector values = { + std::nextafter(-1.0f, 0.0f), + -0.75f, + -0.0f, + std::nextafter(0.0f, -1.0f), + 0.0f, + std::nextafter(0.0f, 1.0f), + std::nextafter(1.0f, 0.0f), + 1.0f, + std::nextafter(1.0f, 2.0f), + 127.75f, + 128.5f, + 254.999f, + 255.0f, + std::nextafter(256.0f, 0.0f)}; + for (size_t d : {0, 1, 15, 16, 17, 31, 32, 33, 65, 769}) { + SCOPED_TRACE(d); + const size_t n = 3; + std::vector input(d * n + 1); + std::vector expected(d * n + 32, 0xa5); + for (size_t i = 0; i < d * n; ++i) { + input[i] = values[i % values.size()]; + expected[16 + i] = static_cast(input[i]); + } + std::vector actual(d * n + 32, 0xa5); + faiss::ScalarQuantizer sq(d, faiss::ScalarQuantizer::QT_8bit_direct); + sq.compute_codes(input.data(), actual.data() + 16, n); + EXPECT_EQ(actual, expected); + } +} + TEST(TestSQ0bit, CoarseOnlySearch) { - // Test QT_0bit: centroid-only distance int d = 64; int nlist = 8; int nb = 1000; @@ -441,23 +554,15 @@ TEST(TestSQ0bit, CoarseOnlySearch) { faiss::METRIC_L2, false); EXPECT_EQ(index.code_size, 0); - EXPECT_FALSE(index.by_residual); index.train(nb, xb.data()); index.add(nb, xb.data()); - EXPECT_EQ(index.ntotal, nb); index.nprobe = nlist; std::vector distances(nq * k); std::vector labels(nq * k); index.search(nq, xq.data(), k, distances.data(), labels.data()); - // Verify we got results - for (int q = 0; q < nq; q++) { - EXPECT_GE(labels[q * k], 0); - } - - // Compare with direct quantizer search - distances should match std::vector coarse_dis(nq * nlist); std::vector coarse_ids(nq * nlist); quantizer.search( @@ -477,16 +582,6 @@ TEST(TestSQ0bit, CoarseOnlySearch) { } } -TEST(TestSQ0bit, IndexFactory) { - int d = 32; - std::unique_ptr index(faiss::index_factory(d, "IVF8,SQ0")); - EXPECT_NE(index, nullptr); - auto* ivfsq = dynamic_cast(index.get()); - EXPECT_NE(ivfsq, nullptr); - EXPECT_EQ(ivfsq->sq.qtype, faiss::ScalarQuantizer::QT_0bit); - EXPECT_EQ(ivfsq->code_size, 0); -} - TEST(TestSQ0bit, InnerProduct) { int d = 64; int nlist = 4; @@ -526,54 +621,15 @@ TEST(TestSQ0bit, InnerProduct) { } } -TEST(ScalarQuantizer, TQMSEEncodeDecode) { - check_tqmse_roundtrip(32, faiss::ScalarQuantizer::QT_1bit_tqmse); - check_tqmse_roundtrip(32, faiss::ScalarQuantizer::QT_2bit_tqmse); - check_tqmse_roundtrip(32, faiss::ScalarQuantizer::QT_3bit_tqmse); - check_tqmse_roundtrip(32, faiss::ScalarQuantizer::QT_4bit_tqmse); - check_tqmse_roundtrip(32, faiss::ScalarQuantizer::QT_8bit_tqmse); -} - TEST(ScalarQuantizer, EDENEncodeDecode) { - check_eden_roundtrip(32, 1, faiss::ScalarQuantizer::QT_1bit_eden); - check_eden_roundtrip(32, 2, faiss::ScalarQuantizer::QT_2bit_eden); - check_eden_roundtrip(32, 3, faiss::ScalarQuantizer::QT_3bit_eden); - check_eden_roundtrip(32, 4, faiss::ScalarQuantizer::QT_4bit_eden); - check_eden_roundtrip(32, 5, faiss::ScalarQuantizer::QT_5bit_eden); - check_eden_roundtrip(32, 6, faiss::ScalarQuantizer::QT_6bit_eden); - check_eden_roundtrip(32, 7, faiss::ScalarQuantizer::QT_7bit_eden); - check_eden_roundtrip(32, 8, faiss::ScalarQuantizer::QT_8bit_eden); -} - -TEST(ScalarQuantizer, TQMSEAccuracyOrdering) { - const size_t d = 32; - const size_t n = 256; - std::vector x = make_normalized_vectors(n, d); - const std::array qtypes = { - faiss::ScalarQuantizer::QT_1bit_tqmse, - faiss::ScalarQuantizer::QT_2bit_tqmse, - faiss::ScalarQuantizer::QT_3bit_tqmse, - faiss::ScalarQuantizer::QT_4bit_tqmse, - faiss::ScalarQuantizer::QT_8bit_tqmse}; - - std::vector mses; - mses.reserve(qtypes.size()); - - for (auto qtype : qtypes) { - faiss::ScalarQuantizer sq(d, qtype); - sq.train(n, x.data()); - - std::vector codes(sq.code_size * n, 0); - sq.compute_codes(x.data(), codes.data(), n); - - std::vector decoded(n * d); - sq.decode(codes.data(), decoded.data(), n); - mses.push_back(mean_squared_error(x, decoded)); - } - - for (size_t i = 0; i + 1 < mses.size(); ++i) { - EXPECT_GE(mses[i], mses[i + 1]); - } + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_1bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_2bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_3bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_4bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_5bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_6bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_7bit_eden); + check_eden_roundtrip(32, faiss::ScalarQuantizer::QT_8bit_eden); } TEST(ScalarQuantizer, TQMSENonSimdDims) { @@ -584,112 +640,379 @@ TEST(ScalarQuantizer, TQMSENonSimdDims) { check_tqmse_roundtrip(33, faiss::ScalarQuantizer::QT_8bit_tqmse); } -TEST(ScalarQuantizer, TQMSESimdDispatchSelection) { +TEST(ScalarQuantizer, LloydMaxSimdDispatchSelection) { const std::vector levels = available_lloyd_max_simd_levels(); if (levels.empty()) { - GTEST_SKIP() << "No SIMD level available for TurboQuant dispatch tests"; + GTEST_SKIP() << "No SIMD level available for Lloyd-Max dispatch tests"; } + using SQ = faiss::ScalarQuantizer; for (faiss::SIMDLevel level : levels) { SCOPED_TRACE(faiss::to_string(level)); expect_lloyd_max_simd_dispatch_for_compatible_dim<1>( - level, faiss::ScalarQuantizer::QT_1bit_tqmse); + level, SQ::QT_1bit_tqmse); + expect_lloyd_max_simd_dispatch_for_compatible_dim<1>( + level, SQ::QT_1bit_eden); expect_lloyd_max_simd_dispatch_for_compatible_dim<2>( - level, faiss::ScalarQuantizer::QT_2bit_tqmse); + level, SQ::QT_2bit_tqmse); + expect_lloyd_max_simd_dispatch_for_compatible_dim<2>( + level, SQ::QT_2bit_eden); + expect_lloyd_max_simd_dispatch_for_compatible_dim<3>( + level, SQ::QT_3bit_tqmse); expect_lloyd_max_simd_dispatch_for_compatible_dim<3>( - level, faiss::ScalarQuantizer::QT_3bit_tqmse); + level, SQ::QT_3bit_eden); expect_lloyd_max_simd_dispatch_for_compatible_dim<4>( - level, faiss::ScalarQuantizer::QT_4bit_tqmse); + level, SQ::QT_4bit_tqmse); + expect_lloyd_max_simd_dispatch_for_compatible_dim<4>( + level, SQ::QT_4bit_eden); + expect_lloyd_max_simd_dispatch_for_compatible_dim<8>( + level, SQ::QT_8bit_tqmse); expect_lloyd_max_simd_dispatch_for_compatible_dim<8>( - level, faiss::ScalarQuantizer::QT_8bit_tqmse); + level, SQ::QT_8bit_eden); expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<1>( - level, 7, faiss::ScalarQuantizer::QT_1bit_tqmse); + level, 7, SQ::QT_1bit_tqmse); + expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<1>( + level, 7, SQ::QT_1bit_eden); expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<2>( - level, 9, faiss::ScalarQuantizer::QT_2bit_tqmse); + level, 9, SQ::QT_2bit_tqmse); + expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<2>( + level, 9, SQ::QT_2bit_eden); + expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<3>( + level, 11, SQ::QT_3bit_tqmse); expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<3>( - level, 11, faiss::ScalarQuantizer::QT_3bit_tqmse); + level, 11, SQ::QT_3bit_eden); + expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<4>( + level, 13, SQ::QT_4bit_tqmse); expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<4>( - level, 13, faiss::ScalarQuantizer::QT_4bit_tqmse); + level, 13, SQ::QT_4bit_eden); expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<8>( - level, 33, faiss::ScalarQuantizer::QT_8bit_tqmse); + level, 33, SQ::QT_8bit_tqmse); + expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<8>( + level, 33, SQ::QT_8bit_eden); } } -TEST(ScalarQuantizer, EDENSimdDispatchSelection) { +TEST(ScalarQuantizer, LloydMaxSimdDistancePathParity) { const std::vector levels = - available_lloyd_max_simd_levels(); + available_sq_parity_simd_levels(); if (levels.empty()) { - GTEST_SKIP() << "No SIMD level available for EDEN dispatch tests"; + GTEST_SKIP() << "No SIMD level available for Lloyd-Max parity tests"; } for (faiss::SIMDLevel level : levels) { SCOPED_TRACE(faiss::to_string(level)); - expect_lloyd_max_simd_dispatch_for_compatible_dim<1>( - level, faiss::ScalarQuantizer::QT_1bit_eden); - expect_lloyd_max_simd_dispatch_for_compatible_dim<2>( - level, faiss::ScalarQuantizer::QT_2bit_eden); - expect_lloyd_max_simd_dispatch_for_compatible_dim<3>( - level, faiss::ScalarQuantizer::QT_3bit_eden); - expect_lloyd_max_simd_dispatch_for_compatible_dim<4>( - level, faiss::ScalarQuantizer::QT_4bit_eden); - expect_lloyd_max_simd_dispatch_for_compatible_dim<8>( - level, faiss::ScalarQuantizer::QT_8bit_eden); - - expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<1>( - level, 7, faiss::ScalarQuantizer::QT_1bit_eden); - expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<2>( - level, 9, faiss::ScalarQuantizer::QT_2bit_eden); - expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<3>( - level, 11, faiss::ScalarQuantizer::QT_3bit_eden); - expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<4>( - level, 13, faiss::ScalarQuantizer::QT_4bit_eden); - expect_lloyd_max_simd_dispatch_fallback_for_incompatible_dim<8>( - level, 33, faiss::ScalarQuantizer::QT_8bit_eden); + for (auto qtype : + {faiss::ScalarQuantizer::QT_1bit_tqmse, + faiss::ScalarQuantizer::QT_2bit_tqmse, + faiss::ScalarQuantizer::QT_3bit_tqmse, + faiss::ScalarQuantizer::QT_4bit_tqmse, + faiss::ScalarQuantizer::QT_8bit_tqmse, + faiss::ScalarQuantizer::QT_1bit_eden, + faiss::ScalarQuantizer::QT_2bit_eden, + faiss::ScalarQuantizer::QT_3bit_eden, + faiss::ScalarQuantizer::QT_4bit_eden, + faiss::ScalarQuantizer::QT_8bit_eden}) { + SCOPED_TRACE(static_cast(qtype)); + check_sq_distance_path_parity(level, qtype, faiss::METRIC_L2, 32); + } } } -TEST(ScalarQuantizer, TQMSESimdDistancePathParity) { +TEST(ScalarQuantizer, LloydMaxSimdBoundaryEncodeParity) { const std::vector levels = - available_lloyd_max_simd_levels(); + available_sq_parity_simd_levels(); if (levels.empty()) { - GTEST_SKIP() << "No SIMD level available for TurboQuant parity tests"; + GTEST_SKIP() << "No SIMD level available for Lloyd-Max parity tests"; } for (faiss::SIMDLevel level : levels) { SCOPED_TRACE(faiss::to_string(level)); - check_lloyd_max_distance_path_parity<1>( - level, faiss::ScalarQuantizer::QT_1bit_tqmse); - check_lloyd_max_distance_path_parity<2>( - level, faiss::ScalarQuantizer::QT_2bit_tqmse); - check_lloyd_max_distance_path_parity<3>( - level, faiss::ScalarQuantizer::QT_3bit_tqmse); - check_lloyd_max_distance_path_parity<4>( - level, faiss::ScalarQuantizer::QT_4bit_tqmse); - check_lloyd_max_distance_path_parity<8>( - level, faiss::ScalarQuantizer::QT_8bit_tqmse); + for (auto qtype : + {faiss::ScalarQuantizer::QT_1bit_tqmse, + faiss::ScalarQuantizer::QT_2bit_tqmse, + faiss::ScalarQuantizer::QT_1bit_eden, + faiss::ScalarQuantizer::QT_2bit_eden}) { + SCOPED_TRACE(static_cast(qtype)); + check_lloyd_max_boundary_encode_parity(level, qtype); + } } } -TEST(ScalarQuantizer, EDENSimdDistancePathParity) { +// d = 24 and 72 are multiples of 8 but not 16: AVX512 falls back to AVX2. +// From d = 384 the loops have four accumulators per code. d = 400 adds one +// remainder block at AVX512 and two at AVX2. d = 456 falls back to AVX2 and +// adds one there. +TEST(ScalarQuantizer, SQ8InnerProductSimdDistancePathParity) { + struct RestoreFlag { + bool original = faiss::SIMDConfig::sq_avx512_4_accumulators; + ~RestoreFlag() { + faiss::SIMDConfig::sq_avx512_4_accumulators = original; + } + } restore_flag; + faiss::SIMDConfig::sq_avx512_4_accumulators = true; const std::vector levels = - available_lloyd_max_simd_levels(); + available_sq_parity_simd_levels(); if (levels.empty()) { - GTEST_SKIP() << "No SIMD level available for EDEN parity tests"; + GTEST_SKIP() << "No SIMD level available for SQ8 parity tests"; } for (faiss::SIMDLevel level : levels) { - SCOPED_TRACE(faiss::to_string(level)); - check_lloyd_max_distance_path_parity<1>( - level, faiss::ScalarQuantizer::QT_1bit_eden); - check_lloyd_max_distance_path_parity<2>( - level, faiss::ScalarQuantizer::QT_2bit_eden); - check_lloyd_max_distance_path_parity<3>( - level, faiss::ScalarQuantizer::QT_3bit_eden); - check_lloyd_max_distance_path_parity<4>( - level, faiss::ScalarQuantizer::QT_4bit_eden); - check_lloyd_max_distance_path_parity<8>( - level, faiss::ScalarQuantizer::QT_8bit_eden); + for (size_t d : {8, 16, 24, 64, 72, 128, 384, 400, 456}) { + SCOPED_TRACE( + testing::Message() + << faiss::to_string(level) << " d=" << d); + check_sq_distance_path_parity( + level, + faiss::ScalarQuantizer::QT_8bit, + faiss::METRIC_INNER_PRODUCT, + d); + check_sq8_ip_batch_matches_single(level, d); + } + } +} + +// Dimensions straddle VLMAX = VLEN / 4 (e32m8) for VLEN 128 to 2048. +// QT_fp16 is in RVVFP16DistancePathParity. +TEST(ScalarQuantizer, RVVDistancePathParity) { + if (!faiss::SIMDConfig::is_simd_level_available( + faiss::SIMDLevel::RISCV_RVV)) { + GTEST_SKIP() << "RISCV_RVV not available on this machine"; + } + + const std::vector qtypes = { + faiss::ScalarQuantizer::QT_8bit, + faiss::ScalarQuantizer::QT_4bit, + faiss::ScalarQuantizer::QT_6bit, + faiss::ScalarQuantizer::QT_8bit_uniform, + faiss::ScalarQuantizer::QT_4bit_uniform, + faiss::ScalarQuantizer::QT_bf16, + faiss::ScalarQuantizer::QT_8bit_direct, + faiss::ScalarQuantizer::QT_8bit_direct_signed, + faiss::ScalarQuantizer::QT_1bit_eden, + faiss::ScalarQuantizer::QT_2bit_eden, + faiss::ScalarQuantizer::QT_3bit_eden, + faiss::ScalarQuantizer::QT_4bit_eden, + faiss::ScalarQuantizer::QT_8bit_eden, + // The QT_*_tqmse types currently alias QuantizerLloydMax, so + // they share the EDEN RVV kernels; listing them makes that + // dispatch coverage explicit for every metric and distance API. + faiss::ScalarQuantizer::QT_1bit_tqmse, + faiss::ScalarQuantizer::QT_2bit_tqmse, + faiss::ScalarQuantizer::QT_3bit_tqmse, + faiss::ScalarQuantizer::QT_4bit_tqmse, + faiss::ScalarQuantizer::QT_8bit_tqmse, + }; + const std::vector dims = { + 1, + 7, + 31, + 32, + 33, + 63, + 64, + 65, + 127, + 128, + 129, + 255, + 256, + 257, + 511, + 512, + 513}; + const std::vector metrics = { + faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}; + + for (auto qtype : qtypes) { + for (size_t d : dims) { + for (auto metric : metrics) { + SCOPED_TRACE( + testing::Message() + << "qtype=" << static_cast(qtype) << " d=" << d + << " metric=" << metric); + check_sq_distance_path_parity( + faiss::SIMDLevel::RISCV_RVV, qtype, metric, d); + } + } + } +} + +// Separate test: the RVV FP16 kernel needs Zvfhmin (SIGILL without it). +TEST(ScalarQuantizer, RVVFP16DistancePathParity) { + if (!faiss::SIMDConfig::is_simd_level_available( + faiss::SIMDLevel::RISCV_RVV)) { + GTEST_SKIP() << "RISCV_RVV not available on this machine"; + } + + const std::vector dims = { + 1, + 7, + 31, + 32, + 33, + 63, + 64, + 65, + 127, + 128, + 129, + 255, + 256, + 257, + 511, + 512, + 513}; + const std::vector metrics = { + faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}; + + for (size_t d : dims) { + for (auto metric : metrics) { + SCOPED_TRACE( + testing::Message() << "d=" << d << " metric=" << metric); + check_sq_distance_path_parity( + faiss::SIMDLevel::RISCV_RVV, + faiss::ScalarQuantizer::QT_fp16, + metric, + d); + } + } +} + +// The 16-bit float quantizers at AVX2 and AVX512 select one accumulator or +// four per code from d and SIMDConfig::sq_avx512_4_accumulators. d = 111 has a +// 15-lane masked tail, d = 120 runs the AVX2 one-accumulator loop, and d = 568 +// runs the 64-wide loop, three remainder blocks and an 8-lane tail. +TEST(ScalarQuantizer, Float16AccumulatorLoopParity) { + struct RestoreFlag { + bool original = faiss::SIMDConfig::sq_avx512_4_accumulators; + ~RestoreFlag() { + faiss::SIMDConfig::sq_avx512_4_accumulators = original; + } + } restore_flag; + faiss::SIMDConfig::sq_avx512_4_accumulators = true; + for (faiss::SIMDLevel level : + {faiss::SIMDLevel::AVX512, faiss::SIMDLevel::AVX2}) { + if (!faiss::SIMDConfig::is_simd_level_available(level)) { + continue; + } + for (auto qtype : + {faiss::ScalarQuantizer::QT_fp16, + faiss::ScalarQuantizer::QT_bf16}) { + for (auto metric : + {faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}) { + for (size_t d : {111, 120, 568}) { + SCOPED_TRACE( + testing::Message() + << "level=" << static_cast(level) + << " qtype=" << static_cast(qtype) + << " metric=" << metric << " d=" << d); + check_sq_distance_path_parity(level, qtype, metric, d); + } + } + } + } +} + +// d == 0 early returns in the RVV DCTemplate loops must give exactly 0 +// without reading the query or the codes. +TEST(ScalarQuantizer, RVVZeroDimDistancePathParity) { + if (!faiss::SIMDConfig::is_simd_level_available( + faiss::SIMDLevel::RISCV_RVV)) { + GTEST_SKIP() << "RISCV_RVV not available on this machine"; + } + ScopedSIMDLevel scoped(faiss::SIMDLevel::RISCV_RVV); + + // trained layouts each quantizer expects at d == 0: non-uniform + // templates take 2 * d (empty) values, uniform templates take {vmin, + // vdiff}, LloydMax takes 2^k - 1 centroids/boundaries, and the raw + // codecs (fp16/bf16/direct) ignore trained entirely. + const std::vector>> + cases = { + {faiss::ScalarQuantizer::QT_8bit, {}}, + {faiss::ScalarQuantizer::QT_4bit, {}}, + {faiss::ScalarQuantizer::QT_6bit, {}}, + {faiss::ScalarQuantizer::QT_8bit_uniform, {0.0f, 1.0f}}, + {faiss::ScalarQuantizer::QT_4bit_uniform, {0.0f, 1.0f}}, + {faiss::ScalarQuantizer::QT_fp16, {}}, + {faiss::ScalarQuantizer::QT_bf16, {}}, + {faiss::ScalarQuantizer::QT_8bit_direct, {}}, + {faiss::ScalarQuantizer::QT_8bit_direct_signed, {}}, + {faiss::ScalarQuantizer::QT_1bit_eden, + std::vector(3, 0.0f)}, + {faiss::ScalarQuantizer::QT_2bit_eden, + std::vector(7, 0.0f)}, + {faiss::ScalarQuantizer::QT_3bit_eden, + std::vector(15, 0.0f)}, + {faiss::ScalarQuantizer::QT_4bit_eden, + std::vector(31, 0.0f)}, + {faiss::ScalarQuantizer::QT_8bit_eden, + std::vector(511, 0.0f)}, + }; + const std::vector metrics = { + faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}; + + uint8_t dummy_code[8] = {}; + + for (const auto& [qtype, trained] : cases) { + for (auto metric : metrics) { + SCOPED_TRACE( + testing::Message() << "qtype=" << static_cast(qtype) + << " metric=" << metric); + + faiss::ScalarQuantizer sq(0, qtype); + sq.trained = trained; + + std::unique_ptr + scalar_dc( + faiss::scalar_quantizer:: + sq_select_distance_computer< + faiss::SIMDLevel::NONE>( + metric, qtype, 0, sq.trained)); + std::unique_ptr simd_dc( + sq.get_distance_computer(metric)); + ASSERT_NE(scalar_dc, nullptr); + ASSERT_NE(simd_dc, nullptr); + + scalar_dc->set_query(nullptr); + simd_dc->set_query(nullptr); + + EXPECT_FLOAT_EQ(scalar_dc->query_to_code(dummy_code), 0.0f); + EXPECT_FLOAT_EQ(simd_dc->query_to_code(dummy_code), 0.0f); + + float scalar_dis[4], simd_dis[4]; + scalar_dc->query_to_codes_batch_4( + dummy_code, + dummy_code, + dummy_code, + dummy_code, + scalar_dis[0], + scalar_dis[1], + scalar_dis[2], + scalar_dis[3]); + simd_dc->query_to_codes_batch_4( + dummy_code, + dummy_code, + dummy_code, + dummy_code, + simd_dis[0], + simd_dis[1], + simd_dis[2], + simd_dis[3]); + for (int k = 0; k < 4; k++) { + EXPECT_FLOAT_EQ(scalar_dis[k], 0.0f); + EXPECT_FLOAT_EQ(simd_dis[k], 0.0f); + } + + scalar_dc->codes = dummy_code; + scalar_dc->code_size = 0; + simd_dc->codes = dummy_code; + simd_dc->code_size = 0; + EXPECT_FLOAT_EQ(scalar_dc->symmetric_dis(0, 1), 0.0f); + EXPECT_FLOAT_EQ(simd_dc->symmetric_dis(0, 1), 0.0f); + } } } diff --git a/thirdparty/faiss/tests/test_scalar_quantizer_correctness.py b/thirdparty/faiss/tests/test_scalar_quantizer_correctness.py index 078be2d3f..c1b90e2a2 100644 --- a/thirdparty/faiss/tests/test_scalar_quantizer_correctness.py +++ b/thirdparty/faiss/tests/test_scalar_quantizer_correctness.py @@ -3,8 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -from __future__ import absolute_import, division, print_function - import os import tempfile @@ -31,7 +29,6 @@ def do_encode_decode(self, qtype, max_err): sq.train(self.xb) codes = sq.compute_codes(self.xb) xb_decoded = sq.decode(codes) - self.assertEqual(xb_decoded.shape, self.xb.shape) err = np.abs(self.xb - xb_decoded).max() self.assertLess(err, max_err) @@ -47,33 +44,21 @@ def test_8bit_uniform(self): def test_4bit_uniform(self): self.do_encode_decode(faiss.ScalarQuantizer.QT_4bit_uniform, 0.1) - def test_tqmse_1bit(self): - faiss.normalize_L2(self.xb) - self.do_encode_decode(faiss.ScalarQuantizer.QT_1bit_tqmse, 1.0) - - def test_tqmse_2bit(self): - faiss.normalize_L2(self.xb) - self.do_encode_decode(faiss.ScalarQuantizer.QT_2bit_tqmse, 0.8) - - def test_tqmse_3bit(self): - faiss.normalize_L2(self.xb) - self.do_encode_decode(faiss.ScalarQuantizer.QT_3bit_tqmse, 0.6) - - def test_tqmse_4bit(self): - faiss.normalize_L2(self.xb) - self.do_encode_decode(faiss.ScalarQuantizer.QT_4bit_tqmse, 0.2) - - def test_tqmse_8bit(self): + def test_tqmse(self): faiss.normalize_L2(self.xb) - self.do_encode_decode(faiss.ScalarQuantizer.QT_8bit_tqmse, 0.1) + for qtype, max_err in ( + (faiss.ScalarQuantizer.QT_1bit_tqmse, 1.0), + (faiss.ScalarQuantizer.QT_2bit_tqmse, 0.8), + (faiss.ScalarQuantizer.QT_3bit_tqmse, 0.6), + (faiss.ScalarQuantizer.QT_4bit_tqmse, 0.2), + (faiss.ScalarQuantizer.QT_8bit_tqmse, 0.1), + ): + with self.subTest(qtype=qtype): + self.do_encode_decode(qtype, max_err) def test_tqmse_preserves_norm(self): - """tqmse encodes unit-norm vectors with no per-vector scale factor in - the code, so reconstructions must keep unit norm. The Lloyd-Max table - is optimal for unit *variance*, so it only lines up with unit-norm - input once scaled by 1/sqrt(d) -- without that, every component lands - in the innermost cells and the codebook collapses toward a sign - quantizer, inflating norms by 15% at d=64 and 258% at d=768.""" + """tqmse has no per-vector scale: the Lloyd-Max table must be scaled + by 1/sqrt(d) or the codebook collapses toward a sign quantizer.""" for qtype, nbits in ( (faiss.ScalarQuantizer.QT_1bit_tqmse, 1), (faiss.ScalarQuantizer.QT_2bit_tqmse, 2), @@ -104,10 +89,20 @@ def test_tqmse_preserves_norm(self): used = len(np.unique(decoded)) self.assertGreaterEqual(used, 2**nbits // 2) + def test_fp16_rounding(self): + cases = { # float32 bits: float16 bits + 0x3F801000: 0x3C00, # tie between two normal halves + 0x33000000: 0x0000, # tie between two subnormal halves + 0x7F802000: 0x7E01, # signaling NaN keeps its payload + } + # d = 16, so that every level runs its own quantizer + x = np.array(list(cases) * 6, dtype="uint32")[:16].view("float32") + sq = faiss.ScalarQuantizer(16, faiss.ScalarQuantizer.QT_fp16) + codes = sq.compute_codes(x[None]).view("uint16")[0] + np.testing.assert_array_equal(codes, (list(cases.values()) * 6)[:16]) + def test_codes_match_none(self): - """SQ codes are integer; encode dispatch (sq-dispatch.h) must - produce bit-identical output at every SIMD level. Catches drift in - the per-ISA scalar-quantizer encode kernels.""" + """Encode must be bit-identical at every SIMD level.""" if not faiss.SIMDConfig.is_simd_level_available(faiss.SIMDLevel_NONE): self.skipTest("SIMDLevel.NONE not available") for qtype in ( @@ -134,10 +129,6 @@ def setUp(self): self.ds = SyntheticDataset(d=self.d, nt=0, nb=10000, nq=100, seed=42) self.xb = self.ds.get_database() self.xq = self.ds.get_queries() - self.xb_unit = self.xb.copy() - self.xq_unit = self.xq.copy() - faiss.normalize_L2(self.xb_unit) - faiss.normalize_L2(self.xq_unit) def do_search(self, factory_str, min_recall): index_gt = faiss.IndexFlatL2(self.d) @@ -159,9 +150,13 @@ def test_SQfp16(self): self.do_search("SQfp16", 0.99) def test_tqmse_search(self): + xb_unit = self.xb.copy() + xq_unit = self.xq.copy() + faiss.normalize_L2(xb_unit) + faiss.normalize_L2(xq_unit) index_gt = faiss.IndexFlatL2(self.d) - index_gt.add(self.xb_unit) - _, I_gt = index_gt.search(self.xq_unit, 10) + index_gt.add(xb_unit) + _, I_gt = index_gt.search(xq_unit, 10) recalls = {} for factory_str in ["L2norm,RR,SQtqmse4", "L2norm,RR,SQtqmse8"]: @@ -239,7 +234,6 @@ def test_constant_vectors(self): self.assertTrue(np.allclose(D, 0, atol=1e-3)) def test_extreme_dims(self): - """Test extreme dimension values (very small and very large).""" for d in [1, 1024]: with self.subTest(d=d): ds = SyntheticDataset(d=d, nt=0, nb=100, nq=10, seed=42) @@ -253,7 +247,6 @@ def test_extreme_dims(self): self.assertEqual(I.shape, (10, 10)) def test_non_simd_dims(self): - """Test dimensions not aligned to SIMD width (8/16).""" for d in [7, 9, 15, 17, 31, 33, 63, 65]: with self.subTest(d=d): ds = SyntheticDataset(d=d, nt=0, nb=100, nq=5, seed=42) @@ -290,6 +283,35 @@ def test_tqmse_non_simd_dims(self): self.assertEqual(I.shape, (5, 10)) +class TestScalarQuantizerNonUniformTraining(unittest.TestCase): + + def train(self, x): + sq = faiss.ScalarQuantizer(x.shape[1], faiss.ScalarQuantizer.QT_8bit) + sq.rangestat = faiss.ScalarQuantizer.RS_meanstd + sq.rangestat_arg = 2.0 + sq.train(x) + return faiss.vector_to_array(sq.trained) + + def test_meanstd_matches_reference(self): + x = np.random.RandomState(123).rand(200, 256).astype("float32") + x[0] = 50 + mean, std = x.mean(0), x.std(0) + ref = np.hstack([mean - 2 * std, 4 * std]) + np.testing.assert_allclose(self.train(x), ref, rtol=1e-4) + + def test_multithreaded_matches_single_threaded(self): + x = np.random.RandomState(123).rand(3, 8192).astype("float32") + nt = faiss.omp_get_max_threads() + faiss.omp_set_num_threads(1) + try: + ref = self.train(x) + faiss.omp_set_num_threads(32) + for _ in range(100): + np.testing.assert_array_equal(self.train(x), ref) + finally: + faiss.omp_set_num_threads(nt) + + @for_all_simd_levels class TestScalarQuantizerIP(unittest.TestCase): @@ -312,13 +334,9 @@ def test_inner_product(self): class TestTurboQUnbiasedness(unittest.TestCase): - """Verify TurboQuant reconstruction preserves inner products.""" def test_reconstruction_quality(self): rng = np.random.RandomState(42) - print("\n=== TurboQuant reconstruction quality ===") - print(f"{'d':>6} {'qt':>8} {'self_ip':>10} {'cos_sim':>10}") - print("-" * 42) for d in [128, 256, 384, 512, 768]: n = 500 @@ -335,22 +353,9 @@ def test_reconstruction_quality(self): xr = np.vstack([index.reconstruct(i) for i in range(n)]) - # Self inner product: for each vector self_ip = np.array([xb[i] @ xr[i] for i in range(n)]) mean_self_ip = self_ip.mean() - # Cosine similarity - xr_norms = np.linalg.norm(xr, axis=1) - cos_sim = np.array( - [xb[i] @ xr[i] / (xr_norms[i] + 1e-30) for i in range(n)] - ).mean() - - print( - f"{d:>6} {qt_name:>8} " - f"{mean_self_ip:>10.4f} {cos_sim:>10.4f}" - ) - - # Reconstruction should point in the right direction self.assertGreater( mean_self_ip, 0.1, @@ -359,7 +364,6 @@ def test_reconstruction_quality(self): class TestTurboQFullFactory(unittest.TestCase): - """Test factory string construction for TurboQ full types.""" def test_factory_sqtq(self): cases = [ @@ -381,15 +385,13 @@ def test_factory_ivf_sqtq(self): factory_str = f"IVF16,{sq_str}" index = faiss.index_factory(d, factory_str) self.assertIsInstance(index, faiss.IndexIVFScalarQuantizer) - ivf = faiss.downcast_index(index) - self.assertFalse(ivf.by_residual) + self.assertFalse(index.by_residual) class TestTurboQFullEncodeDecode(unittest.TestCase): - """Encode/decode roundtrip for TurboQ full types.""" def test_encode_decode_roundtrip(self): - for d in [32, 64, 128]: + for d in [7, 9, 15, 17, 32, 33, 64, 65, 128]: for qtype, max_err in [ (faiss.ScalarQuantizer.QT_2bit_tq, 1.5), (faiss.ScalarQuantizer.QT_3bit_tq, 1.2), @@ -403,25 +405,11 @@ def test_encode_decode_roundtrip(self): sq.train(xb) codes = sq.compute_codes(xb) xr = sq.decode(codes) - self.assertEqual(xr.shape, xb.shape) err = np.abs(xb - xr).max() self.assertLess(err, max_err) - def test_non_simd_aligned_dims(self): - for d in [7, 9, 15, 17, 33, 65]: - with self.subTest(d=d): - rng = np.random.RandomState(42) - xb = rng.randn(100, d).astype("float32") - faiss.normalize_L2(xb) - sq = faiss.ScalarQuantizer(d, faiss.ScalarQuantizer.QT_2bit_tq) - sq.train(xb) - codes = sq.compute_codes(xb) - xr = sq.decode(codes) - self.assertEqual(xr.shape, xb.shape) - class TestTurboQFullSearch(unittest.TestCase): - """Search recall tests for TurboQ full types.""" def setUp(self): self.d = 64 @@ -442,40 +430,19 @@ def _recall_at_1(self, index): return (self.I_gt[:, 0] == I[:, 0]).mean() def test_flat_sqtq_search(self): - for sq_str in ["SQtq2", "SQtq3", "SQtq4"]: - with self.subTest(sq_str=sq_str): - index = faiss.index_factory(self.d, sq_str) - index.train(self.xb) - index.add(self.xb) - recall = self._recall_at_1(index) - self.assertGreater(recall, 0.05) - - def test_recall_increases_with_bits(self): recalls = {} for sq_str in ["SQtq2", "SQtq3", "SQtq4"]: index = faiss.index_factory(self.d, sq_str) index.train(self.xb) index.add(self.xb) recalls[sq_str] = self._recall_at_1(index) + self.assertGreater(recalls[sq_str], 0.05) self.assertGreaterEqual(recalls["SQtq3"], recalls["SQtq2"] - 0.05) self.assertGreaterEqual(recalls["SQtq4"], recalls["SQtq3"] - 0.05) - def test_ivf_sqtq_search(self): - for sq_str in ["SQtq2", "SQtq3"]: - with self.subTest(sq_str=sq_str): - factory_str = f"IVF32,{sq_str}" - index = faiss.index_factory(self.d, factory_str) - index.train(self.xb) - index.add(self.xb) - index.nprobe = 8 - _, I = index.search(self.xq, 10) - self.assertEqual(I.shape, (self.nq, 10)) - self.assertTrue(np.all(I[:, 0] >= 0)) - class TestTurboQFullSerialization(unittest.TestCase): - """Serialization roundtrip for TurboQ full types.""" def _roundtrip(self, index): fd, fname = tempfile.mkstemp() @@ -529,6 +496,7 @@ def test_ivf_serialize_roundtrip(self): index.nprobe = 4 D1, I1 = index.search(xq, 5) + self.assertTrue(np.all(I1[:, 0] >= 0)) index2 = self._roundtrip(index) index2.nprobe = 4 D2, I2 = index2.search(xq, 5) @@ -558,7 +526,6 @@ def test_serialize_preserves_qtype(self): class TestTurboQFullDistances(unittest.TestCase): - """Verify distance computation is consistent for TurboQ.""" def test_search_distances_are_finite(self): d = 64 @@ -582,28 +549,6 @@ def test_search_distances_are_finite(self): self.assertTrue(np.all(D[:, 0] >= 0)) self.assertTrue(np.all(I >= 0)) - def test_search_distances_sorted(self): - d = 64 - rng = np.random.RandomState(42) - xb = rng.randn(500, d).astype("float32") - xq = rng.randn(10, d).astype("float32") - faiss.normalize_L2(xb) - faiss.normalize_L2(xq) - - for qtype in [ - faiss.ScalarQuantizer.QT_2bit_tq, - faiss.ScalarQuantizer.QT_3bit_tq, - ]: - with self.subTest(qtype=qtype): - index = faiss.IndexScalarQuantizer(d, qtype) - index.train(xb) - index.add(xb) - - D, _ = index.search(xq, 10) - for q in range(len(xq)): - for k in range(1, 10): - self.assertLessEqual(D[q, k - 1], D[q, k]) - @for_all_simd_levels class TestSQByteDirectAcrossSIMDLevels(unittest.TestCase): @@ -611,10 +556,8 @@ class TestSQByteDirectAcrossSIMDLevels(unittest.TestCase): distances. The distances are integers, so this class computes them from the - definition and compares. An earlier version measured a second time at - SIMDLevel.NONE and compared the two runs. A static build reports only the - one level it compiles, and omits NONE, so that version skipped itself in - the build shape that ships. + definition and compares. Comparing against SIMDLevel.NONE instead would + skip in static builds, which report only the one level they compile. d = 16 and d = 32 pass the d % 16 == 0 test in sq-dispatch.h. That test routes the query to DistanceComputerByte and DistanceComputerByteSigned. @@ -624,9 +567,7 @@ class TestSQByteDirectAcrossSIMDLevels(unittest.TestCase): """ def reference(self, xq, xb, metric): - """Returns the exact distances. The values are small integers. Every - product and sum stays below 2**24, so the float32 result loses - nothing.""" + """Exact distances: all values stay below 2**24, so float32 is exact.""" a = xq.astype("int64") b = xb.astype("int64") if metric == faiss.METRIC_L2: diff --git a/thirdparty/faiss/tests/test_search_params.py b/thirdparty/faiss/tests/test_search_params.py index d56a0a308..dbe9ff48d 100644 --- a/thirdparty/faiss/tests/test_search_params.py +++ b/thirdparty/faiss/tests/test_search_params.py @@ -18,10 +18,6 @@ @for_all_simd_levels class TestSelector(unittest.TestCase): - """ - Test the IDSelector filtering for as many (index class, id selector class) - combinations as possible. - """ def do_test_id_selector( self, @@ -32,10 +28,7 @@ def do_test_id_selector( use_heap=True, ): """Verify that the id selector returns the subset of results that are - members according to the IDSelector. - Supports id_selector_type="batch", "bitmap", "range", - "range_sorted", "and", "or", "xor" - """ + members according to the IDSelector.""" d = 32 # make sure dimension is multiple of 8 for binary ds = datasets.SyntheticDataset(d, 1000, 100, 20) @@ -45,7 +38,6 @@ def do_test_id_selector( xq = rs.randint(256, size=(ds.nq, d // 8), dtype="uint8") index = faiss.IndexBinaryFlat(d) index.use_heap = use_heap - # Use smaller radius for Hamming distance base_radius = 4 is_binary = True else: @@ -57,7 +49,6 @@ def do_test_id_selector( base_radius = float("inf") # Will be set based on results is_binary = False - # reference result if "range" in id_selector_type: subset = np.arange(30, 80).astype("int64") elif id_selector_type == "or": @@ -66,18 +57,6 @@ def do_test_id_selector( rhs_rs = np.random.RandomState(456) rhs_subset = rhs_rs.choice(ds.nb, 20, replace=False).astype("int64") subset = np.union1d(lhs_subset, rhs_subset) - elif id_selector_type == "and": - lhs_rs = np.random.RandomState(123) - lhs_subset = lhs_rs.choice(ds.nb, 50, replace=False).astype("int64") - rhs_rs = np.random.RandomState(456) - rhs_subset = rhs_rs.choice(ds.nb, 10, replace=False).astype("int64") - subset = np.intersect1d(lhs_subset, rhs_subset) - elif id_selector_type == "xor": - lhs_rs = np.random.RandomState(123) - lhs_subset = lhs_rs.choice(ds.nb, 50, replace=False).astype("int64") - rhs_rs = np.random.RandomState(456) - rhs_subset = rhs_rs.choice(ds.nb, 40, replace=False).astype("int64") - subset = np.setxor1d(lhs_subset, rhs_subset) else: rs = np.random.RandomState(123) subset = rs.choice(ds.nb, 50, replace=False).astype("int64") @@ -103,7 +82,6 @@ def do_test_id_selector( raise else: RIref = subset[RIref] - # normalize the range search results RDref, RIref = sort_range_res_2(Rlims_ref, RDref, RIref) have_range_search = True @@ -132,53 +110,25 @@ def do_test_id_selector( faiss.IDSelectorBatch(lhs_subset), faiss.IDSelectorBatch(rhs_subset), ) - elif id_selector_type == "and": - sel = faiss.IDSelectorAnd( - faiss.IDSelectorBatch(lhs_subset), - faiss.IDSelectorBatch(rhs_subset), - ) - elif id_selector_type == "xor": - sel = faiss.IDSelectorXOr( - faiss.IDSelectorBatch(lhs_subset), - faiss.IDSelectorBatch(rhs_subset), - ) else: sel = faiss.IDSelectorBatch(subset) params = ( faiss.SearchParametersIVF(sel=sel) if "IVF" in index_key - else ( - faiss.SearchParametersPQ(sel=sel) - if "PQ" in index_key - else faiss.SearchParameters(sel=sel) - ) + else faiss.SearchParameters(sel=sel) ) Dnew, Inew = index.search(xq, k, params=params) if is_binary: - # For binary indexes, we need to check: - # 1. All returned IDs are valid (in the subset or -1) - # 2. The distances match - - # Check that all returned IDs are valid - valid_ids = np.ones_like(Inew, dtype=bool) - # Create a mask of valid IDs (those in subset) - subset_set = set(subset) # Convert to set for O(1) lookups - # Handle -1 values separately (they're always valid) - valid_ids = np.logical_or( - Inew == -1, np.isin(Inew, list(subset_set)) - ) + valid_ids = np.logical_or(Inew == -1, np.isin(Inew, subset)) self.assertTrue( np.all(valid_ids), "Some returned IDs are not in the subset" ) - - # Check that distances match np.testing.assert_almost_equal(Dref, Dnew, decimal=5) else: - # For non-binary indexes, we can do exact comparison np.testing.assert_array_equal(Iref, Inew) np.testing.assert_almost_equal(Dref, Dnew, decimal=5) @@ -190,21 +140,14 @@ def do_test_id_selector( RDref, RIref = sort_range_res_2(Rlims_ref, RDref, RIref) if is_binary: - # For binary indexes, check that all returned IDs are valid - valid_ids = np.ones(len(RInew), dtype=bool) - # Use vectorized operation instead of loop - subset_set = set(subset) # Convert to set for O(1) lookups - valid_ids = np.isin(RInew, list(subset_set)) + valid_ids = np.isin(RInew, subset) self.assertTrue( np.all(valid_ids), "Some range search IDs are not in the subset", ) - - # Check that distances match np.testing.assert_almost_equal(RDref, RDnew, decimal=5) else: - # For non-binary indexes, we can do exact comparison np.testing.assert_array_equal(RIref, RInew) np.testing.assert_almost_equal(RDref, RDnew, decimal=5) @@ -267,16 +210,7 @@ def test_Flat_id_not(self): def test_Flat_id_or(self): self.do_test_id_selector("Flat", id_selector_type="or") - # not implemented - - # def test_PQ(self): - # self.do_test_id_selector("PQ4x4np") - - # def test_AQ(self): - # self.do_test_id_selector("RQ3x4") - def do_test_id_selector_weak(self, index_key): - """verify that the selected subset is the subset in the list""" ds = datasets.SyntheticDataset(32, 1000, 100, 20) index = faiss.index_factory(ds.d, index_key) index.train(ds.get_train()) @@ -284,7 +218,6 @@ def do_test_id_selector_weak(self, index_key): k = 10 Dref, Iref = index.search(ds.get_queries(), k) - # reference result rs = np.random.RandomState(123) subset = rs.choice(ds.nb, 50, replace=False).astype("int64") sel = faiss.IDSelectorBatch(subset) @@ -368,12 +301,9 @@ def test_idmap(self): mask = ids % 2 == 0 index = faiss.index_factory(ds.d, "IDMap,SQ8") index.train(ds.get_train()) - - # ref result index.add_with_ids(ds.get_database()[mask], ids[mask]) Dref, Iref = index.search(ds.get_queries(), 10) - # with selector index.reset() index.add_with_ids(ds.get_database(), ids) @@ -454,12 +384,12 @@ def test_idmap_range_ivf_params(self): def test_bounds(self): # https://github.com/facebookresearch/faiss/issues/3156 - d = 64 # dimension - nb = 100000 # database size + d = 64 + nb = 100000 xb = np.random.random((nb, d)) index_ip = faiss.IndexFlatIP(d) index_ip.add(xb) - index_l2 = faiss.IndexFlatIP(d) + index_l2 = faiss.IndexFlatL2(d) index_l2.add(xb) out_of_bounds_id = nb + 15 # + 14 or lower will work fine @@ -473,12 +403,6 @@ def test_bounds(self): def test_BinaryFlat(self): self.do_test_id_selector("BinaryFlat") - def test_BinaryFlat_id_range(self): - self.do_test_id_selector("BinaryFlat", id_selector_type="range") - - def test_BinaryFlat_id_array(self): - self.do_test_id_selector("BinaryFlat", id_selector_type="array") - def test_BinaryFlat_no_heap(self): self.do_test_id_selector("BinaryFlat", use_heap=False) @@ -487,11 +411,7 @@ def test_BinaryFlat_no_heap(self): class TestSearchParams(unittest.TestCase): def do_test_with_param(self, index_key, ps_params, params): - """ - Test equivalence between setting - 1. param_name_2 = value with ParameterSpace - 2. pass in a SearchParameters with param_name = value - """ + """ParameterSpace settings and SearchParameters give the same result""" ds = datasets.SyntheticDataset(32, 1000, 100, 20) index = faiss.index_factory(ds.d, index_key) if index_key.startswith("PQ"): @@ -500,7 +420,7 @@ def do_test_with_param(self, index_key, ps_params, params): index.train(ds.get_train()) index.add(ds.get_database()) - I0, D0 = index.search(ds.get_queries(), 10) + D0, I0 = index.search(ds.get_queries(), 10) Dnew, Inew = index.search(ds.get_queries(), 10, params=params) @@ -544,7 +464,6 @@ def test_PQ_polysemous_ht(self): ) def test_max_codes(self): - "tests whether the max nb codes is taken into account" ds = datasets.SyntheticDataset(32, 1000, 100, 20) index = faiss.index_factory(ds.d, "IVF32,Flat") index.train(ds.get_train()) @@ -584,7 +503,6 @@ def test_ownership(self): new_count = sys.getrefcount(sel) self.assertEqual(new_count, prev_count - 1) - # check for other objects as well sel1 = faiss.IDSelectorBatch([1, 2, 3]) sel2 = faiss.IDSelectorBatch([4, 5, 6]) sel = faiss.IDSelectorAnd(sel1, sel2) @@ -622,15 +540,123 @@ def is_member(idx): np.testing.assert_almost_equal(Dref, Dnew, decimal=5) +@for_all_simd_levels +class TestSelAfterDistance(unittest.TestCase): + + def do_test(self, metric): + # odd list sizes reach the tail of the batched scan + ds = datasets.SyntheticDataset(32, 2000, 2003, 10, metric=metric) + mt = faiss.METRIC_INNER_PRODUCT if metric == "IP" else faiss.METRIC_L2 + index = faiss.index_factory(ds.d, "IVF8,SQ8", mt) + index.train(ds.get_train()) + index.add(ds.get_database()) + + def search(k, max_codes, after): + calls = [0] + + def is_member(i): + calls[0] += 1 + return i % 5 != 0 + + params = faiss.SearchParametersIVF( + sel=faiss.PyCallbackIDSelector(is_member), + nprobe=8, + max_codes=max_codes, + sel_after_distance=after, + ) + D, I = index.search(ds.get_queries(), k, params=params) + return D, I, calls[0] + + # k 2000 exceeds the 1602 accepted ids, so the heap never fills + for k, max_codes in (10, 0), (2000, 0), (10, 300): + D0, I0, calls0 = search(k, max_codes, False) + D1, I1, calls1 = search(k, max_codes, True) + np.testing.assert_array_equal(I0, I1) + np.testing.assert_array_equal(D0, D1) + if max_codes != 0: + # max_codes counts codes that pass the selector + self.assertEqual(calls0, calls1) + elif k == 10: + self.assertLess(calls1, calls0 / 4) + + def test_L2(self): + self.do_test("L2") + + def test_IP(self): + self.do_test("IP") + + +@for_all_simd_levels +class TestRaBitQSelAfterDistance(unittest.TestCase): + + def do_test(self, metric, nb_bits): + ds = datasets.SyntheticDataset(32, 2000, 2003, 10, metric=metric) + mt = faiss.METRIC_INNER_PRODUCT if metric == "IP" else faiss.METRIC_L2 + index = faiss.IndexRaBitQ(ds.d, mt, nb_bits) + index.train(ds.get_train()) + index.add(ds.get_database()) + + def search(k, after, accept=lambda i: i % 5 != 0): + calls = [0] + + def is_member(i): + calls[0] += 1 + return accept(i) + + params = faiss.RaBitQSearchParameters( + sel=faiss.PyCallbackIDSelector(is_member), + sel_after_distance=after, + ) + D, I = index.search(ds.get_queries(), k, params=params) + return D, I, calls[0] + + # k 1, 10 and 200 take the top-1, heap and reservoir handlers; k 2000 + # exceeds the 1602 accepted ids, so no threshold is ever set + for k in 1, 10, 200, 2000: + D0, I0, calls0 = search(k, False) + D1, I1, calls1 = search(k, True) + np.testing.assert_array_equal(I0, I1) + np.testing.assert_array_equal(D0, D1) + if k == 2000: + self.assertEqual(calls0, calls1) + elif k == 200: + self.assertLess(calls1, calls0) + else: + self.assertLess(calls1, calls0 / 4) + + # with 1 id in 10 accepted (201 ids) and k 99, over a third of the + # estimates beat the threshold in each of the 3 windows of 64, so the + # selector stays first + def sparse(i): + return i % 10 == 0 + + D0, I0, calls0 = search(99, False, sparse) + D1, I1, calls1 = search(99, True, sparse) + np.testing.assert_array_equal(I0, I1) + np.testing.assert_array_equal(D0, D1) + self.assertEqual(calls0, calls1) + + def test_L2(self): + self.do_test("L2", 1) + + def test_IP(self): + self.do_test("IP", 1) + + def test_L2_multibit(self): + self.do_test("L2", 4) + + def test_IP_multibit(self): + self.do_test("IP", 4) + + class TestSortedIDSelectorRange(unittest.TestCase): - """to test the sorted id bounds, there are a few cases to consider""" - def do_test_sorted(self, imin, imax, n=100): + def do_test_sorted(self, imin, imax): selr = faiss.IDSelectorRange(imin, imax, True) sp = faiss.swig_ptr for seed in range(10): rs = np.random.RandomState(seed) - ids = rs.choice(30, n).astype("int64") + ids = rs.choice(30, 100).astype("int64") ids.sort() j01 = np.zeros(2, dtype="uint64") selr.find_sorted_ids_bounds( @@ -649,9 +675,6 @@ def test_sorted_out_0(self): def test_sorted_out_1(self): self.do_test_sorted(10, 40) - def test_sorted_in_range_smalln(self): - self.do_test_sorted(10, 20, n=5) - def test_12_92(self): selr = faiss.IDSelectorRange(30, 80, True) ids = np.array([12, 92], dtype="int64") @@ -686,12 +709,6 @@ def do_test_knn_and_range(self, factory, range=True): ) check_ref_range_results(Lref, Dref, Iref, Lnew, Dnew, Inew) - def test_knn_and_range_Flat(self): - self.do_test_knn_and_range("IVF32,Flat") - - def test_knn_and_range_SQ(self): - self.do_test_knn_and_range("IVF32,SQ8") - def test_knn_and_range_PQ(self): self.do_test_knn_and_range("IVF32,PQ8x4np") @@ -700,191 +717,13 @@ def test_knn_and_range_FS(self): class TestIVFEarlyTermination(unittest.TestCase): - """ - Coverage for the new SearchParametersIVF early-stop fields: - - ensure_topk_full - - max_empty_result_buckets - - max_lists_num - """ - - def _build(self, factory, mt=faiss.METRIC_L2, d=32): - ds = datasets.SyntheticDataset(d, 2000, 500, 30) - index = faiss.index_factory(d, factory, mt) - index.train(ds.get_train()) - index.add(ds.get_database()) - return ds, index - - def test_ensure_topk_full_fills_heap(self): - ds, index = self._build("IVF32,Flat") - k = 10 - params = faiss.SearchParametersIVF() - params.nprobe = 32 - params.max_codes = k // 2 # tight budget: forces truncation - params.ensure_topk_full = False - _, I_tight = index.search(ds.get_queries(), k, params=params) - - params.ensure_topk_full = True - _, I_full = index.search(ds.get_queries(), k, params=params) - - # ensure_topk_full=true must produce at least as many valid slots. - miss_tight = np.sum(I_tight == -1) - miss_full = np.sum(I_full == -1) - self.assertLessEqual(miss_full, miss_tight) - # Test precondition: tight budget produced some misses. - self.assertGreater(miss_tight, 0) - - def test_range_default_matches_baseline(self): - """Default max_empty_result_buckets=0 must preserve pre-existing - range_search results byte-for-byte.""" - ds, index = self._build("IVF32,Flat") - # Set nprobe via the index attribute for the no-params baseline. - index.nprobe = 8 - radius = 2.0 - Lref, Dref, Iref = index.range_search(ds.get_queries(), radius) - - params = faiss.SearchParametersIVF() - params.nprobe = 8 - # all new fields are at defaults - Lnew, Dnew, Inew = index.range_search( - ds.get_queries(), radius, params=params - ) - - np.testing.assert_array_equal(Lref, Lnew) - # Per-query (id, distance) pairs must match as sorted sets since - # within-query order is not guaranteed across OMP threads. - for q in range(ds.nq): - a = sorted( - zip( - Iref[Lref[q] : Lref[q + 1]].tolist(), - Dref[Lref[q] : Lref[q + 1]].tolist(), - ) - ) - b = sorted( - zip( - Inew[Lnew[q] : Lnew[q + 1]].tolist(), - Dnew[Lnew[q] : Lnew[q + 1]].tolist(), - ) - ) - self.assertEqual(a, b) - - def test_range_early_exit_is_subset(self): - ds, index = self._build("IVF32,Flat") - # Radius chosen empirically against this synthetic dataset - # (d=32, nb=500, IVF32) so that several probed buckets per - # query yield zero in-radius hits — required to exercise - # the empty-bucket exit path. Too-tight or too-wide radii - # leave the test vacuous. - radius = 15.0 - p_full = faiss.SearchParametersIVF() - p_full.nprobe = 32 - p_full.max_empty_result_buckets = 0 # disabled - Lf, Df, If = index.range_search(ds.get_queries(), radius, params=p_full) - - p_early = faiss.SearchParametersIVF() - p_early.nprobe = 32 - p_early.max_empty_result_buckets = 1 # aggressive early-exit - Le, De, Ie = index.range_search( - ds.get_queries(), radius, params=p_early - ) - - # Early-exit must never expand the result set. - self.assertTrue(np.all(np.diff(Le) <= np.diff(Lf))) - # And each per-query id-set must be a subset of the full result. - for q in range(ds.nq): - full = set(If[Lf[q] : Lf[q + 1]].tolist()) - early = set(Ie[Le[q] : Le[q + 1]].tolist()) - self.assertTrue(early.issubset(full)) - # At least one query must strictly shrink. - any_shrunk = bool(np.any(np.diff(Le) < np.diff(Lf))) - self.assertTrue( - any_shrunk, - "no query shrank: max_empty_result_buckets has no effect", - ) - - def test_range_early_exit_counter_resets_on_hit(self): - """Tightening max_empty_result_buckets (1 vs 3) must never - produce *more* results. With 3 the loop tolerates two - intervening empty buckets between non-empty ones; with 1 it - terminates on the first empty bucket. Per-query result - counts must therefore satisfy tight ≤ relaxed.""" - ds, index = self._build("IVF32,Flat") - radius = 15.0 - p_tight = faiss.SearchParametersIVF() - p_tight.nprobe = 32 - p_tight.max_empty_result_buckets = 1 - Lt, _, _ = index.range_search(ds.get_queries(), radius, params=p_tight) - - p_relaxed = faiss.SearchParametersIVF() - p_relaxed.nprobe = 32 - p_relaxed.max_empty_result_buckets = 3 - Lr, _, _ = index.range_search( - ds.get_queries(), radius, params=p_relaxed - ) - - self.assertTrue(np.all(np.diff(Lt) <= np.diff(Lr))) - - def test_range_rejects_non_default_parallel_mode(self): - ds, index = self._build("IVF32,Flat") - ivf = faiss.downcast_index(index) - ivf.parallel_mode = 1 - - params = faiss.SearchParametersIVF() - params.nprobe = 4 - params.max_empty_result_buckets = 2 - with self.assertRaises(RuntimeError): - index.range_search(ds.get_queries()[:1], 1.0, params=params) - - def test_ndis_stats_post_filter(self): - """IndexIVFStats::ndis is documented as 'nb of distances - computed' — a post-filter quantity. With a 50%-keep selector, - ndis must drop because rejected codes don't have a distance - computed.""" - ds, index = self._build("IVF32,Flat") - index.nprobe = 32 - stats = faiss.cvar.indexIVF_stats - - stats.reset() - index.search(ds.get_queries(), 10) - ndis_no_sel = stats.ndis - self.assertGreater(ndis_no_sel, 0) - - # 50%-keep batch selector. - keep = np.arange(0, ds.nb, 2).astype("int64") - sel = faiss.IDSelectorBatch(keep) - params = faiss.SearchParametersIVF(nprobe=32, sel=sel) - stats.reset() - index.search(ds.get_queries(), 10, params=params) - ndis_with_sel = stats.ndis - - self.assertLess(ndis_with_sel, ndis_no_sel) - # Loose-bound sanity: ~50% retention should drop ndis at least - # noticeably below the no-selector value. - self.assertLess(ndis_with_sel * 4, ndis_no_sel * 3) - - def test_ensure_topk_full_with_restrictive_selector(self): - """Under a 10%-keep selector and - max_codes < k, the heap must still be filled (no -1 entries) - because the post-filter break condition keeps probing until k - valid candidates have been observed.""" - ds, index = self._build("IVF32,Flat") - # 10%-keep selector — 50 valid ids in 500-vector dataset. - keep = np.arange(0, ds.nb, 10).astype("int64") - sel = faiss.IDSelectorBatch(keep) - - params = faiss.SearchParametersIVF() - params.nprobe = 32 - params.max_codes = 5 # tight pre-filter budget - params.ensure_topk_full = True # post-filter soft cap - params.sel = sel - _, I = index.search(ds.get_queries(), 10, params=params) - - self.assertEqual(int(np.sum(I == -1)), 0) def test_fields_exposed_and_defaulted(self): p = faiss.SearchParametersIVF() self.assertEqual(p.max_lists_num, 0) self.assertIs(p.ensure_topk_full, False) self.assertEqual(p.max_empty_result_buckets, 0) + self.assertIs(p.sel_after_distance, False) p.max_lists_num = 5 p.ensure_topk_full = True p.max_empty_result_buckets = 2 diff --git a/thirdparty/faiss/tests/test_simd_dispatch.py b/thirdparty/faiss/tests/test_simd_dispatch.py index 4ac6a649b..ec1e71e56 100644 --- a/thirdparty/faiss/tests/test_simd_dispatch.py +++ b/thirdparty/faiss/tests/test_simd_dispatch.py @@ -53,14 +53,7 @@ def is_simd_level_compiled(name): def get_available_simd_levels(): - """ - Returns the SIMD levels this build can be forced to with FAISS_SIMD_LEVEL. - - Asks faiss rather than reading /proc/cpuinfo: a level is only honoured - when it is compiled into the build, and a CPU feature does not imply - that. is_simd_level_available() reports compiled and supported, which is - a subset of compiled, so every level it returns is one the override - accepts. + """Levels this build can be forced to (compiled and CPU-supported). Setting FAISS_SIMD_LEVEL collapses the supported set to the forced level, so the caller must not already have it set. @@ -88,35 +81,6 @@ def get_available_simd_levels(): class TestSIMDDispatch(unittest.TestCase): - """Tests for SIMD dispatch via FAISS_SIMD_LEVEL environment variable.""" - - def test_dispatch_function_exists(self): - """Verify SIMDConfig.get_dispatched_level() is available.""" - try: - import faiss - except ImportError: - self.skipTest("faiss not available") - - # Method should exist on SIMDConfig - self.assertTrue(hasattr(faiss.SIMDConfig, "get_dispatched_level")) - - # Should return a value (SIMDLevel enum) - result = faiss.SIMDConfig.get_dispatched_level() - # In SWIG, enum values are integers - self.assertIsNotNone(result) - - def test_get_level_equals_get_dispatched_level(self): - """Verify get_level() and get_dispatched_level() return the same - value.""" - try: - import faiss - except ImportError: - self.skipTest("faiss not available") - - level = faiss.SIMDConfig.get_level() - dispatched = faiss.SIMDConfig.get_dispatched_level() - self.assertEqual(level, dispatched) - def test_dispatch_with_env_var(self): """ Test that FAISS_SIMD_LEVEL controls dispatch. @@ -124,16 +88,12 @@ def test_dispatch_with_env_var(self): Runs faiss in subprocesses with different SIMD levels and verifies that get_dispatched_level() returns the expected value. """ - # Only run in DD mode - try: - import faiss + import faiss - if "DD" not in faiss.get_compile_options(): - self.skipTest( - "Not a DD build - SIMD level is fixed at compile time" - ) - except ImportError: - self.skipTest("faiss not available") + if "DD" not in faiss.get_compile_options(): + self.skipTest( + "Not a DD build - SIMD level is fixed at compile time" + ) if os.environ.get("FAISS_SIMD_LEVEL"): self.skipTest( @@ -143,12 +103,10 @@ def test_dispatch_with_env_var(self): levels = get_available_simd_levels() - # Get the PYTHONPATH that includes faiss module python_path = os.pathsep.join(sys.path) for level_name in levels: with self.subTest(level=level_name): - # Run a subprocess with FAISS_SIMD_LEVEL set env = os.environ.copy() env["FAISS_SIMD_LEVEL"] = level_name env["PYTHONPATH"] = python_path @@ -159,12 +117,10 @@ def test_dispatch_with_env_var(self): dispatched = faiss.SIMDConfig.get_dispatched_level() level_name = faiss.SIMDConfig.get_level_name() -# Verify dispatch matches if level != dispatched: print(f"FAIL: get_level() != get_dispatched_level()") exit(1) -# Verify it's the expected level if level_name != "{level_name}": print(f"FAIL: expected {level_name}, got {{level_name}}") exit(1) @@ -184,23 +140,48 @@ def test_dispatch_with_env_var(self): f"Failed for {level_name}: {result.stdout} {result.stderr}", ) + def test_env_var_keeps_uarch_flags(self): + """FAISS_SIMD_LEVEL forces the level, but the microarchitecture + flags (avx512_split, scalar_gather) still describe the CPU.""" + import faiss + + if "DD" not in faiss.get_compile_options(): + self.skipTest("Not a DD build") + if os.environ.get("FAISS_SIMD_LEVEL"): + self.skipTest("FAISS_SIMD_LEVEL is already set") + + env = os.environ.copy() + env["FAISS_SIMD_LEVEL"] = faiss.SIMDConfig.get_level_name() + env["PYTHONPATH"] = os.pathsep.join(sys.path) + script = ( + "import faiss; " + "print(faiss.cvar.SIMDConfig_avx512_split, " + "faiss.cvar.SIMDConfig_scalar_gather)" + ) + result = subprocess.run( + [sys.executable, "-c", script], + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + result.stdout.split(), + [ + str(faiss.cvar.SIMDConfig_avx512_split), + str(faiss.cvar.SIMDConfig_scalar_gather), + ], + ) + def test_detected_level_does_not_crash_fp16(self): - """The auto-detected SIMD level must always be safe to execute on the - running CPU. AVX512_SPR is compiled with -mavx512fp16, so it must - only be detected on CPUs that actually have AVX512_FP16. AMD Zen 4 - (bergamo) has AVX512_BF16 but NOT AVX512_FP16; before the fix, - detection classified it as SPR and SQfp16 distance computations - dispatched to SPR code, which crashed. - """ - try: - import faiss + """Every detected level must run SQfp16 without SIGILL. Regression: + AMD Zen 4 (BF16, no FP16) was detected as AVX512_SPR.""" + import faiss - if "DD" not in faiss.get_compile_options(): - self.skipTest( - "Not a DD build - SIMD level is fixed at compile time" - ) - except ImportError: - self.skipTest("faiss not available") + if "DD" not in faiss.get_compile_options(): + self.skipTest( + "Not a DD build - SIMD level is fixed at compile time" + ) env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(sys.path) @@ -260,15 +241,12 @@ def test_spr_detection_matches_cpu_features(self): """ import platform - try: - import faiss + import faiss - if "DD" not in faiss.get_compile_options(): - self.skipTest( - "Not a DD build - SIMD level is fixed at compile time" - ) - except ImportError: - self.skipTest("faiss not available") + if "DD" not in faiss.get_compile_options(): + self.skipTest( + "Not a DD build - SIMD level is fixed at compile time" + ) if platform.machine().lower() not in ("x86_64", "amd64"): self.skipTest("x86_64-only test") @@ -326,15 +304,12 @@ def test_vpopcnt_detection_matches_cpu_features(self): """The VPOPCNT level requires baseline AVX-512, VPOPCNTDQ and BITALG.""" import platform - try: - import faiss + import faiss - if "DD" not in faiss.get_compile_options(): - self.skipTest( - "Not a DD build - SIMD level is fixed at compile time" - ) - except ImportError: - self.skipTest("faiss not available") + if "DD" not in faiss.get_compile_options(): + self.skipTest( + "Not a DD build - SIMD level is fixed at compile time" + ) if platform.machine().lower() not in ("x86_64", "amd64"): self.skipTest("x86_64-only test") diff --git a/thirdparty/faiss/tests/test_simd_levels.cpp b/thirdparty/faiss/tests/test_simd_levels.cpp index 48a58a34d..2ac89a9e6 100644 --- a/thirdparty/faiss/tests/test_simd_levels.cpp +++ b/thirdparty/faiss/tests/test_simd_levels.cpp @@ -16,33 +16,19 @@ #include #include -// Helper to check if we're in DD mode static bool is_dd_mode() { return faiss::get_compile_options().find("DD") != std::string::npos; } -TEST(SIMDConfig, get_level_returns_valid_level) { - // Works in both static and DD modes - faiss::SIMDLevel level = faiss::SIMDConfig::get_level(); - EXPECT_NE(level, faiss::SIMDLevel::COUNT); - EXPECT_GE(static_cast(level), 0); - EXPECT_LT( - static_cast(level), static_cast(faiss::SIMDLevel::COUNT)); -} - TEST(SIMDConfig, supported_simd_levels_not_empty) { - // Works in both static and DD modes - // Current level should always be in supported levels EXPECT_TRUE( faiss::SIMDConfig::is_simd_level_available( faiss::SIMDConfig::get_level())); } TEST(SIMDConfig, set_level_to_supported_level_succeeds) { - // Works in both static and DD modes faiss::SIMDLevel original_level = faiss::SIMDConfig::get_level(); - // Setting to any supported level should succeed for (int i = 0; i < static_cast(faiss::SIMDLevel::COUNT); ++i) { auto level = static_cast(i); if (faiss::SIMDConfig::is_simd_level_available(level)) { @@ -53,13 +39,10 @@ TEST(SIMDConfig, set_level_to_supported_level_succeeds) { } } - // Restore original level faiss::SIMDConfig::set_level(original_level); } TEST(SIMDConfig, set_level_to_unsupported_level_throws) { - // Works in both static and DD modes - // Find a level that's NOT supported faiss::SIMDLevel unsupported = faiss::SIMDLevel::COUNT; for (int i = 0; i < static_cast(faiss::SIMDLevel::COUNT); ++i) { auto level = static_cast(i); @@ -95,17 +78,7 @@ TEST(SIMDConfig, static_mode_has_single_level) { << "Static mode should have exactly 1 level (compiled-in)"; } -TEST(SIMDConfig, get_level_name_matches_level) { - // Works in both static and DD modes - faiss::SIMDLevel level = faiss::SIMDConfig::get_level(); - std::string name = faiss::SIMDConfig::get_level_name(); - std::string expected = faiss::to_string(level); - EXPECT_EQ(name, expected); -} - TEST(SIMDConfig, get_dispatched_level_matches_get_level) { - // Works in both static and DD modes - // Verifies that dispatch mechanism returns the same level as get_level() faiss::SIMDLevel level = faiss::SIMDConfig::get_level(); faiss::SIMDLevel dispatched = faiss::SIMDConfig::get_dispatched_level(); EXPECT_EQ(level, dispatched) @@ -126,7 +99,6 @@ TEST(SIMDLevel, to_string_all_levels) { EXPECT_EQ("ARM_SVE", faiss::to_string(faiss::SIMDLevel::ARM_SVE)); EXPECT_EQ("RISCV_RVV", faiss::to_string(faiss::SIMDLevel::RISCV_RVV)); - // COUNT should throw EXPECT_THROW( faiss::to_string(faiss::SIMDLevel::COUNT), faiss::FaissException); } @@ -143,13 +115,11 @@ TEST(SIMDLevel, to_simd_level_all_strings) { EXPECT_EQ(faiss::SIMDLevel::ARM_SVE, faiss::to_simd_level("ARM_SVE")); EXPECT_EQ(faiss::SIMDLevel::RISCV_RVV, faiss::to_simd_level("RISCV_RVV")); - // Invalid strings should throw EXPECT_THROW(faiss::to_simd_level("INVALID"), faiss::FaissException); EXPECT_THROW(faiss::to_simd_level(""), faiss::FaissException); } TEST(SIMDConfig, modern_hardware_has_simd_support) { - // In DD mode, verify modern hardware detects SIMD support if (!is_dd_mode()) { GTEST_SKIP() << "Static build - level is fixed at compile time"; } @@ -170,7 +140,6 @@ TEST(SIMDConfig, modern_hardware_has_simd_support) { TEST(CompileOptions, lists_expected_levels) { std::string options = faiss::get_compile_options(); - // All supported levels (except NONE) should be in compile options for (int i = 0; i < static_cast(faiss::SIMDLevel::COUNT); ++i) { auto level = static_cast(i); if (!faiss::SIMDConfig::is_simd_level_available(level)) { @@ -184,10 +153,4 @@ TEST(CompileOptions, lists_expected_levels) { << "Supported level " << name << " should be in compile options: " << options; } - - // DD mode should have "DD" marker - if (is_dd_mode()) { - EXPECT_NE(options.find("DD"), std::string::npos) - << "DD mode should have 'DD' in compile options: " << options; - } } diff --git a/thirdparty/faiss/tests/test_simd_levels_x86_avx512.cpp b/thirdparty/faiss/tests/test_simd_levels_x86_avx512.cpp index 64c49c26c..ee6755eae 100644 --- a/thirdparty/faiss/tests/test_simd_levels_x86_avx512.cpp +++ b/thirdparty/faiss/tests/test_simd_levels_x86_avx512.cpp @@ -54,44 +54,6 @@ std::vector run_avx512f_computation() { return {result, result + 8}; } -std::vector run_avx512cd_computation() { - run_avx512f_computation(); - - __m512i indices = _mm512_set_epi32( - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - __m512i conflict_mask = _mm512_conflict_epi32(indices); - - alignas(64) int mask_array[16]; - _mm512_store_epi32(mask_array, conflict_mask); - - return std::vector(); -} - -std::vector run_avx512vl_computation() { - run_avx512f_computation(); - - __m256i vec1 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); - __m256i vec2 = _mm256_set_epi32(0, 1, 2, 3, 4, 5, 6, 7); - __m256i result = _mm256_add_epi32(vec1, vec2); - alignas(32) int result_array[8]; - _mm256_store_si256(reinterpret_cast<__m256i*>(result_array), result); - - return std::vector(result_array, result_array + 8); -} - -std::vector run_avx512dq_computation() { - run_avx512f_computation(); - - __m512i vec1 = _mm512_set_epi64(7, 6, 5, 4, 3, 2, 1, 0); - __m512i vec2 = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); - __m512i result = _mm512_add_epi64(vec1, vec2); - - alignas(64) long long result_array[8]; - _mm512_store_si512(result_array, result); - - return std::vector(result_array, result_array + 8); -} - std::vector run_avx512bw_computation() { run_avx512f_computation(); @@ -111,38 +73,6 @@ std::vector run_avx512bw_computation() { } // namespace -TEST(SIMDConfig, successful_avx512f_execution_on_x86arch) { - if (faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX512)) { - auto actual_result = try_execute_avx512(run_avx512f_computation); - EXPECT_TRUE(actual_result.first); - auto expected_result_vector = std::vector(8, 9); - EXPECT_EQ(actual_result.second, expected_result_vector); - } -} - -TEST(SIMDConfig, successful_avx512cd_execution_on_x86arch) { - if (faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX512)) { - auto actual = try_execute_avx512(run_avx512cd_computation); - EXPECT_TRUE(actual.first); - } -} - -TEST(SIMDConfig, successful_avx512vl_execution_on_x86arch) { - if (faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX512)) { - auto actual = try_execute_avx512(run_avx512vl_computation); - EXPECT_TRUE(actual.first); - EXPECT_EQ(actual.second, std::vector(8, 7)); - } -} - -TEST(SIMDConfig, successful_avx512dq_execution_on_x86arch) { - if (faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX512)) { - auto actual = try_execute_avx512(run_avx512dq_computation); - EXPECT_TRUE(actual.first); - EXPECT_EQ(actual.second, std::vector(8, 7)); - } -} - TEST(SIMDConfig, successful_avx512bw_execution_on_x86arch) { if (faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX512)) { auto actual = try_execute_avx512(run_avx512bw_computation); diff --git a/thirdparty/faiss/tests/test_simd_perf.cpp b/thirdparty/faiss/tests/test_simd_perf.cpp index fef3d842a..1f1be7693 100644 --- a/thirdparty/faiss/tests/test_simd_perf.cpp +++ b/thirdparty/faiss/tests/test_simd_perf.cpp @@ -6,23 +6,8 @@ */ /** - * Performance validation test for SIMD Dynamic Dispatch. - * - * This test verifies that the DD infrastructure is correctly dispatching - * to optimized SIMD implementations by checking that: - * 1. Dispatch actually routes to different code when set_level() is called - * 2. AVX2 is faster than NONE (scalar) for explicit-intrinsics functions - * 3. AVX512 does not catastrophically regress vs AVX2 - * - * We benchmark fvec_inner_products_ny with d=8, which has a large algorithmic - * difference between SIMD levels: AVX2 uses an 8x8 register transpose to - * process 8 vectors simultaneously, while NONE processes one vector at a time. - * This gives a reliable 4-8x speedup that is robust against CI noise. - * - * Benchmarking methodology: we use the minimum (best) time across multiple - * interleaved runs. For microbenchmarks, the minimum is the most stable - * estimator of true performance because system interference (context switches, - * cache evictions, VM scheduling) only makes runs slower, never faster. + * Checks that DD routes AVX2 to real AVX2 code: fvec_inner_products_ny at d=8 + * (8x8 transpose kernel) must beat NONE, and at d=128 must not be slower. */ #include @@ -42,7 +27,6 @@ class SIMDPerfTest : public ::testing::Test { void SetUp() override { original_level = faiss::SIMDConfig::get_level(); - // Generate random test data x.resize(d); y.resize(ny * d); dis.resize(ny); @@ -55,24 +39,7 @@ class SIMDPerfTest : public ::testing::Test { faiss::SIMDConfig::set_level(original_level); } - // Verify that dispatch actually routes to the requested level. - // This catches DD being broken (always routing to one level) - // without relying on performance measurements. - void verify_dispatch(faiss::SIMDLevel level) { - faiss::SIMDConfig::set_level(level); - faiss::SIMDLevel dispatched = faiss::SIMDConfig::get_dispatched_level(); - ASSERT_EQ(dispatched, level) - << "Dispatch broken: set_level(" << faiss::to_string(level) - << ") but get_dispatched_level() returned " - << faiss::to_string(dispatched); - } - - // Benchmark fvec_inner_products_ny which has explicit AVX2/AVX512 - // intrinsics with 8x8 register transpose — large algorithmic difference - // from the scalar NONE fallback. - double benchmark_fvec_inner_products_ny( - faiss::SIMDLevel level, - int n_runs = 5000) { + double benchmark_fvec_inner_products_ny(faiss::SIMDLevel level) { faiss::SIMDConfig::set_level(level); // Warmup to stabilize CPU frequency @@ -82,7 +49,7 @@ class SIMDPerfTest : public ::testing::Test { } auto start = std::chrono::high_resolution_clock::now(); - for (int run = 0; run < n_runs; run++) { + for (int run = 0; run < 5000; run++) { faiss::fvec_inner_products_ny( dis.data(), x.data(), y.data(), d, ny); } @@ -94,7 +61,6 @@ class SIMDPerfTest : public ::testing::Test { faiss::SIMDLevel original_level = faiss::SIMDLevel::NONE; - // d=8: AVX2 uses 8x8 transpose to process 8 vectors simultaneously. // ny=4096: y=128KB fits in L2 cache, dis=16KB fits in L1. size_t d = 8; size_t ny = 4096; @@ -103,25 +69,6 @@ class SIMDPerfTest : public ::testing::Test { std::vector dis; static constexpr int kBenchmarkReps = 7; - - // Run benchmark multiple times with interleaved measurements, return - // minimum (best) time. For microbenchmarks, the minimum is the most - // stable estimator because system interference only makes runs slower. - template - std::pair benchmark_interleaved_best( - BenchmarkFunc bench_fn, - faiss::SIMDLevel level_a, - faiss::SIMDLevel level_b) { - double best_a = std::numeric_limits::max(); - double best_b = std::numeric_limits::max(); - - for (int i = 0; i < kBenchmarkReps; i++) { - best_a = std::min(best_a, bench_fn(level_a)); - best_b = std::min(best_b, bench_fn(level_b)); - } - - return {best_a, best_b}; - } }; TEST_F(SIMDPerfTest, AVX2FasterThanNONE) { @@ -129,19 +76,19 @@ TEST_F(SIMDPerfTest, AVX2FasterThanNONE) { GTEST_SKIP() << "AVX2 not available on this machine"; } - // First verify dispatch actually routes to different levels. - // This catches DD being broken without relying on performance. - verify_dispatch(faiss::SIMDLevel::NONE); - verify_dispatch(faiss::SIMDLevel::AVX2); - - // Benchmark fvec_inner_products_ny (d=8) which has explicit AVX2 - // intrinsics with 8x8 register transpose. The NONE version processes - // one vector at a time, giving a large and reliable speedup. - auto bench_fn = [this](faiss::SIMDLevel level) { - return benchmark_fvec_inner_products_ny(level); - }; - auto [none_time, avx2_time] = benchmark_interleaved_best( - bench_fn, faiss::SIMDLevel::NONE, faiss::SIMDLevel::AVX2); + // Interleave the levels and keep the minimum (best) time of each. For + // microbenchmarks, the minimum is the most stable estimator because + // system interference only makes runs slower. + double none_time = std::numeric_limits::max(); + double avx2_time = std::numeric_limits::max(); + for (int i = 0; i < kBenchmarkReps; i++) { + none_time = std::min( + none_time, + benchmark_fvec_inner_products_ny(faiss::SIMDLevel::NONE)); + avx2_time = std::min( + avx2_time, + benchmark_fvec_inner_products_ny(faiss::SIMDLevel::AVX2)); + } printf("fvec_inner_products_ny NONE: %.2f ms (best of %d runs)\n", none_time, @@ -153,28 +100,19 @@ TEST_F(SIMDPerfTest, AVX2FasterThanNONE) { double speedup = none_time / avx2_time; printf("fvec_inner_products_ny Speedup: %.2fx\n", speedup); - // AVX2 fvec_inner_products_ny (d=8) uses 8x8 register transpose to - // process 8 vectors simultaneously vs scalar one-at-a-time. Expected - // speedup is 4-8x on bare metal. We use 1.5x threshold which gives - // generous headroom for CI noise while still catching dispatch failures. + // Expected 4-8x; 1.5x leaves headroom for CI noise. EXPECT_GT(speedup, 1.5) << "AVX2 should be faster than NONE for fvec_inner_products_ny. " << "NONE=" << none_time << "ms, AVX2=" << avx2_time << "ms"; } -// Additional test: Verify fvec_L2sqr dispatch is at least not slower. -// fvec_L2sqr uses auto-vectorization, so AVX2 may only be slightly faster. TEST_F(SIMDPerfTest, L2sqrAutoVecDispatchWorks) { if (!faiss::SIMDConfig::is_simd_level_available(faiss::SIMDLevel::AVX2)) { GTEST_SKIP() << "AVX2 not available on this machine"; } - verify_dispatch(faiss::SIMDLevel::NONE); - verify_dispatch(faiss::SIMDLevel::AVX2); - - // Use fvec_inner_products_ny at larger d where the algorithmic - // advantage is smaller (less transpose benefit) to verify dispatch - // doesn't regress even with autovectorized code paths. + // At d=128 fvec_inner_products_ny runs the autovectorized loop, compiled + // separately per level. size_t large_d = 128; size_t large_ny = 1024; std::vector lx(large_d); @@ -185,7 +123,6 @@ TEST_F(SIMDPerfTest, L2sqrAutoVecDispatchWorks) { auto bench_fn = [&](faiss::SIMDLevel level) { faiss::SIMDConfig::set_level(level); - // Warmup for (int i = 0; i < 100; i++) { faiss::fvec_inner_products_ny( ldis.data(), lx.data(), ly.data(), large_d, large_ny); @@ -200,8 +137,12 @@ TEST_F(SIMDPerfTest, L2sqrAutoVecDispatchWorks) { return elapsed.count(); }; - auto [none_time, avx2_time] = benchmark_interleaved_best( - bench_fn, faiss::SIMDLevel::NONE, faiss::SIMDLevel::AVX2); + double none_time = std::numeric_limits::max(); + double avx2_time = std::numeric_limits::max(); + for (int i = 0; i < kBenchmarkReps; i++) { + none_time = std::min(none_time, bench_fn(faiss::SIMDLevel::NONE)); + avx2_time = std::min(avx2_time, bench_fn(faiss::SIMDLevel::AVX2)); + } printf("fvec_inner_products_ny (d=128) NONE: %.2f ms (best of %d runs)\n", none_time, @@ -213,8 +154,6 @@ TEST_F(SIMDPerfTest, L2sqrAutoVecDispatchWorks) { double speedup = none_time / avx2_time; printf("fvec_inner_products_ny (d=128) Speedup: %.2fx\n", speedup); - // At larger d, both NONE and AVX2 use the same autovectorized loop, - // just compiled with different flags. This only catches regressions. EXPECT_GT(speedup, 0.8) << "AVX2 code should not be significantly slower than SSE4. " << "NONE=" << none_time << "ms, AVX2=" << avx2_time << "ms"; diff --git a/thirdparty/faiss/tests/test_simd_registry.py b/thirdparty/faiss/tests/test_simd_registry.py new file mode 100644 index 000000000..0384baf3d --- /dev/null +++ b/thirdparty/faiss/tests/test_simd_registry.py @@ -0,0 +1,370 @@ +# 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. + +"""Checks the SIMD guard rules in faiss/docs/simd_dynamic_dispatch_migration.md: +per-level files are registered in the build lists and have no whole-file +guard, and only per-level code and a fixed list of headers use SIMD +intrinsics or compiler macros for SIMD features.""" + +import ast +import os +import re +import unittest +from importlib import resources +from pathlib import Path + +# CMake list name suffix -> SIMDLevel name. +CMAKE_LEVELS = { + "AVX2": "AVX2", + "AVX512": "AVX512", + "AVX512_VPOPCNT": "AVX512_VPOPCNT", + "AVX512_SPR": "AVX512_SPR", + "NEON": "ARM_NEON", + "SVE": "ARM_SVE", + "RVV": "RISCV_RVV", +} + +# Directories that are not part of the CPU library. +EXCLUDED_DIRS = { + "benchs", + "c_api", + "contrib", + "cppcontrib", + "demos", + "docs", + "fb", + "gpu", + "gpu_rocm", + "perf_tests", + "public_tld", + "python", + "tests", + "tutorial", +} + +# A file whose name contains one of these words, between "-", "_" or ".", +# holds per-level code. Only per-level files include such a header ("sse": x86 +# code for the AVX2 and AVX512 files). +PER_LEVEL_NAME = re.compile( + r"(?:^|[-_.])(?:avx2|avx512|neon|sve|rvv|riscv|ppc64|sse)(?=[-_.])" +) + +# Headers that common files include and that select SIMD code with compiler +# macros. Add a header here only after review. +COMPILER_MACRO_HEADERS = { + "impl/Panorama.h", # __BMI2__ next to FAISS_SIMD_TU(AVX2) + "impl/platform_macros.h", # MSVC defines of __F16C__ and __FMA__ + "impl/simdlib/simdlib.h", + "utils/bf16.h", + "utils/fp16-fp16c.h", + "utils/fp16-arm.h", + "utils/fp16.h", + "utils/hamming_distance/common.h", # NEON under __aarch64__ + "utils/prefetch.h", # architecture helper + "utils/simd_levels.h", # defines FAISS_SIMD_TU +} + +# Common files that test COMPILE_SIMD_. They only declare, reference or +# dispatch to per-level code. Add a file here only after review. +COMPILE_SIMD_FILES = { + "impl/ProductQuantizer.cpp", # selects the dsub2 kernels + "impl/nndescent/gram.h", # declares the gram_upper_rows kernel + "impl/pq_code_distance/pq_code_distance-generic.h", # scalar NEON body + "impl/scalar_quantizer/EDENQuantizer.cpp", + "impl/simd_dispatch.h", + "utils/simd_impl/fp16_kernels.h", + "utils/simd_impl/super_kmeans_kernels.h", + "utils/simd_levels.cpp", + "utils/simd_levels.h", +} + +# Common headers that include per-level headers under FAISS_SIMD_TU or an +# architecture macro. Add a header here only after review. +PER_LEVEL_INCLUDERS = { + "impl/fast_scan/accumulate_loops.h", + "impl/fast_scan/decompose_qbs.h", + "impl/simdlib/simdlib.h", + "impl/simdlib/simdlib_dispatch.h", +} + +ISA_MACRO = re.compile( + r"\b__(?:AVX\w*__|F16C__|FMA4?__|BMI2?__|LZCNT__|POPCNT__|PCLMUL__" + r"|VPCLMULQDQ__|GFNI__|V?AES__|SHA__|SSE\w*__|ARM_FEATURE_\w+" + r"|ARM_NEON\w*|riscv_vector)\b" +) +# Not : MSVC also needs it for scalar helpers such as __cpuid. +# INTRINSIC_CODE catches vector intrinsics used through it. +INTRINSIC_INCLUDE = re.compile( + r"#\s*include\s*<(?:[a-z]mmintrin|x86intrin|x86gprintrin|immintrin|arm_neon" + r"|arm_sve|arm_acle|arm_fp16|arm_bf16|riscv_vector)\.h>" +) +# Intrinsic calls and vector types (x86, NEON, SVE, RVV). The SVE call +# pattern excludes "svs_", the prefix of the SVS library functions. +INTRINSIC_CODE = re.compile( + r"\b_mm\w*_\w+\s*\(|\b__m(?:128|256|512)[dhi]?\b|\b__mmask\d+\b" + r"|\b(?:u?int|float|poly)(?:8|16|32|64)x\d+(?:x\d+)?_t\b" + r"|\bv[a-z0-9_]+_[supf](?:8|16|32|64)\s*\(" + r"|\bsv(?:float|int|uint|bool)\d*_t\b" + r"|\bsv(?!s_)\w+_[suf](?:8|16|32|64)(?:_[xmz])?\s*\(" + r"|\b__riscv_v\w+\s*\(" +) +COMPILE_SIMD = re.compile(r"\bCOMPILE_SIMD_\w+") +LEVEL_WORD = re.compile( + r"(?:^|[-_.])(avx2|avx512|neon|sve|rvv|riscv|ppc64|sse)(?=[-_.])" +) +# The levels that a file with this word in its name can belong to. +WORD_LEVELS = { + "avx2": {"AVX2"}, + "avx512": {"AVX512", "AVX512_VPOPCNT", "AVX512_SPR"}, + "sse": {"AVX2", "AVX512", "AVX512_VPOPCNT", "AVX512_SPR"}, + "neon": {"ARM_NEON"}, + "sve": {"ARM_SVE"}, + "rvv": {"RISCV_RVV"}, + "riscv": {"RISCV_RVV"}, +} +CONDITION = re.compile(r"^\s*#\s*(?:if|ifdef|ifndef|elif)\b") +OPEN = re.compile(r"^\s*#\s*(?:if|ifdef|ifndef)\b(.*)$") +CLOSE = re.compile(r"^\s*#\s*endif\b") +CODE = re.compile(r"^\s*(?!#|//|/\*|\*)\S") +INCLUDE = re.compile(r'^\s*#\s*include\s*(?:"([^"]+)"|<(faiss/[^>]+)>)') + + +# base_module of the test in tests/BUCK. +BUCK_PACKAGE = "faiss_simd_registry" + + +def find_faiss_root(): + candidates = [os.environ.get("FAISS_SOURCE_DIR")] + if __package__: + # Buck packages the sources as a resource of this test. + try: + sources = resources.files(__package__) / "faiss_sources" + candidates.append(str(sources)) + except (ModuleNotFoundError, TypeError): + pass + here = Path(__file__).resolve().parent + candidates += [here.parent / "faiss", here.parent] + for candidate in candidates: + if candidate is None: + continue + root = Path(candidate) + if (root / "CMakeLists.txt").is_file() and ( + root / "utils" / "simd_levels.h" + ).is_file(): + return root + return None + + +def cmake_list(cmake_text, name): + match = re.search(r"set\(" + name + r"\s*\n(.*?)\)", cmake_text, re.S) + return match.group(1).split() if match else [] + + +def cmake_simd_files(root): + text = (root / "CMakeLists.txt").read_text() + files = {} + for suffix, level in CMAKE_LEVELS.items(): + for path in cmake_list(text, f"FAISS_SIMD_{suffix}_SRC"): + files[path] = level + return files + + +def buck_simd_files(root): + tree = ast.parse((root / "xplat.bzl").read_text()) + for node in tree.body: + if ( + isinstance(node, ast.Assign) + and isinstance(node.targets[0], ast.Name) + and node.targets[0].id == "SIMD_FILES" + ): + return { + key.value: value.elts[1].id + for key, value in zip(node.value.keys, node.value.values) + } + return {} + + +def logical_lines(path): + """(line number, line) with each backslash continuation joined.""" + number, parts = 0, [] + for i, line in enumerate(path.read_text(errors="replace").splitlines(), 1): + if not parts: + number = i + if line.endswith("\\"): + parts.append(line[:-1]) + continue + parts.append(line) + yield number, " ".join(parts) + parts = [] + if parts: + yield number, " ".join(parts) + + +def library_files(root): + for path in sorted(root.rglob("*")): + rel = path.relative_to(root) + if path.suffix not in (".h", ".cpp") or rel.parts[0] in EXCLUDED_DIRS: + continue + yield rel.as_posix(), path + + +def whole_file_guard(path): + """The condition of an #if that encloses all code of the file, or None.""" + lines = [line for _, line in logical_lines(path)] + starts = [ + i + for i, line in enumerate(lines) + if OPEN.match(line) or CODE.match(line) + ] + first = starts[0] if starts else None + if first is None or not OPEN.match(lines[first]): + return None + depth = 0 + for i in range(first, len(lines)): + if OPEN.match(lines[i]): + depth += 1 + elif CLOSE.match(lines[i]): + depth -= 1 + if depth == 0: + rest = lines[i + 1 :] + if any(CODE.match(line) for line in rest): + return None + return OPEN.match(lines[first]).group(1).strip() + return None + + +def common_line_error(rel, line): + """The rule that a line of a common file breaks, or None.""" + macro_header = rel in COMPILER_MACRO_HEADERS + if INTRINSIC_INCLUDE.search(line) and not macro_header: + return "intrinsic header" + if CONDITION.match(line): + if ISA_MACRO.search(line) and not macro_header: + return "compiler macro for a SIMD feature; use FAISS_SIMD_TU(level)" + if COMPILE_SIMD.search(line) and rel not in COMPILE_SIMD_FILES: + return ( + "COMPILE_SIMD_ in a common file; level code uses " + "FAISS_SIMD_TU(level), and a declaration or a dispatch needs " + "review (COMPILE_SIMD_FILES)" + ) + include = INCLUDE.match(line) + if include: + header = include.group(1) or include.group(2) + if ( + PER_LEVEL_NAME.search(Path(header).name) + and rel not in PER_LEVEL_INCLUDERS + ): + return f"per-level header {header} in a common file" + code = line.split("//")[0] + if INTRINSIC_CODE.search(code) and not macro_header: + return "intrinsic call or vector type in a common file" + return None + + +class SIMDRegistryTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root = find_faiss_root() + if cls.root is None: + # Buck declares the sources as a resource, and FAISS_SOURCE_DIR + # names them, so they must exist then. Other runs, such as the + # conda package tests, may have only the tests directory. + expected = __package__ == BUCK_PACKAGE or os.environ.get( + "FAISS_SOURCE_DIR" + ) + if expected: + raise RuntimeError( + "Faiss source files not found; check FAISS_SOURCE_DIR or " + "the //faiss:simd_registry_sources resource" + ) + raise unittest.SkipTest( + "Faiss source files not found; set FAISS_SOURCE_DIR" + ) + cls.from_buck = cls.root.name == "faiss_sources" + cls.cmake = (cls.root / "CMakeLists.txt").read_text() + cls.simd_files = cmake_simd_files(cls.root) + + def test_sources_are_complete(self): + # A parser that misses a list, or a resource that misses files, would + # make the other checks pass on nothing. + for suffix in CMAKE_LEVELS: + self.assertGreater( + len(cmake_list(self.cmake, f"FAISS_SIMD_{suffix}_SRC")), + 0, + f"FAISS_SIMD_{suffix}_SRC is empty or not parsed", + ) + common = cmake_list(self.cmake, "FAISS_SRC") + self.assertIn("IndexFlat.cpp", common, "FAISS_SRC is not parsed") + rels = {rel for rel, _ in library_files(self.root)} + known = ("IndexFlat.cpp", "utils/simd_levels.h", "impl/simd_dispatch.h") + for rel in known: + self.assertIn(rel, rels) + self.assertGreater(len(rels), 300, "too few library files found") + + def test_per_level_files_exist_and_are_not_common(self): + self.assertGreater(len(self.simd_files), 0) + common = set(cmake_list(self.cmake, "FAISS_SRC")) + for path in self.simd_files: + self.assertTrue((self.root / path).is_file(), path) + self.assertNotIn(path, common, f"{path} is in FAISS_SRC") + for path in common: + self.assertIsNone( + PER_LEVEL_NAME.search(Path(path).name), + f"{path}: a per-level file is in FAISS_SRC", + ) + + def test_per_level_files_are_registered(self): + # A per-level .cpp in no list is never compiled. + for rel, path in library_files(self.root): + if path.suffix == ".cpp" and LEVEL_WORD.search(path.name): + message = f"{rel}: in no FAISS_SIMD__SRC list" + self.assertIn(rel, self.simd_files, message) + + def test_file_names_match_levels(self): + # An avx512 file in the AVX2 list of both build files passes the + # parity check, but gets the wrong flags. + for path, level in self.simd_files.items(): + for word in LEVEL_WORD.findall(Path(path).name): + allowed = WORD_LEVELS.get(word) + if allowed is not None: + self.assertIn(level, allowed, f"{path}: listed as {level}") + + def test_per_level_files_have_no_whole_file_guard(self): + # The build files select per-level files, so a whole-file guard on a + # level or on a compiler macro is always true, or always false and + # empties the file. + for path in self.simd_files: + condition = whole_file_guard(self.root / path) + guarded = condition is not None and bool( + COMPILE_SIMD.search(condition) or ISA_MACRO.search(condition) + ) + self.assertFalse( + guarded, f"{path}: remove the whole-file guard {condition}" + ) + + def test_simd_code_only_in_allowed_files(self): + errors = [] + for rel, path in library_files(self.root): + if rel in self.simd_files or PER_LEVEL_NAME.search(path.name): + continue + for number, line in logical_lines(path): + error = common_line_error(rel, line) + if error: + errors.append(f"{rel}:{number}: {error}") + self.assertEqual(errors, [], "\n".join(errors)) + + def test_buck_and_cmake_list_the_same_files(self): + if not (self.root / "xplat.bzl").is_file(): + # The GitHub checkout has no xplat.bzl; the Buck resource must. + self.assertFalse(self.from_buck, "xplat.bzl is missing") + self.skipTest("xplat.bzl is not available") + buck = buck_simd_files(self.root) + self.assertGreater(len(buck), 0, "SIMD_FILES is empty or not parsed") + cmake = { + path: level + for path, level in self.simd_files.items() + if level != "RISCV_RVV" + } + self.assertEqual(buck, cmake) diff --git a/thirdparty/faiss/tests/test_simdlib.cpp b/thirdparty/faiss/tests/test_simdlib.cpp index e7eeaa87c..41342d580 100644 --- a/thirdparty/faiss/tests/test_simdlib.cpp +++ b/thirdparty/faiss/tests/test_simdlib.cpp @@ -11,7 +11,6 @@ using namespace faiss; -// Explicit SIMD-level aliases (no global bare aliases). using simd8float32 = simd8float32_tpl; using simd8uint32 = simd8uint32_tpl; using simd16uint16 = simd16uint16_tpl; diff --git a/thirdparty/faiss/tests/test_single_query_collect_handler.cpp b/thirdparty/faiss/tests/test_single_query_collect_handler.cpp index ad3e05d85..76e2cca94 100644 --- a/thirdparty/faiss/tests/test_single_query_collect_handler.cpp +++ b/thirdparty/faiss/tests/test_single_query_collect_handler.cpp @@ -1,5 +1,13 @@ /* - * Copyright (c) Meta Platforms, Inc. and affiliates. + * Portions 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. + */ + +/* + * Portions Copyright 2026 Arm Limited and/or its affiliates + * * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. @@ -10,10 +18,9 @@ * * Drives the handler through the actual fast_scan accumulate loop * by building an IndexPQFastScan, computing its quantized LUT, - * and calling pq4_accumulate_loop_qbs_fixed_scaler_256 directly. + * and calling pq4_accumulate_loop_qbs_fixed_scaler_simd directly. */ -#include #include #include #include @@ -43,19 +50,16 @@ std::vector make_data(size_t n, int64_t seed) { } /// Build, train and populate an IndexPQFastScan with bbs=32. -std::unique_ptr make_index(size_t db_size = nb) { +std::unique_ptr make_index() { auto index = std::make_unique(d, 4, 4, METRIC_L2, 32); auto xt = make_data(nt, 1234); index->train(nt, xt.data()); - auto xb = make_data(db_size, 4567); - index->add(db_size, xb.data()); + auto xb = make_data(nb, 4567); + index->add(nb, xb.data()); return index; } -/// The following code relies on 1 query, because -/// SingleQueryResultCollectHandler is hardcoded to use -/// only 1 query. - +/// SingleQueryResultCollectHandler supports only 1 query. /// Run the collect handler through the real accumulate loop for one query. /// Returns collected (id, distance) pairs. std::vector> run_collect_handler( @@ -65,7 +69,6 @@ std::vector> run_collect_handler( // CMax = L2 metric (keep the largest threshold, collect distances below it) using C = CMax; - // 1. Compute quantized LUT + normalizers for 1 query size_t dim12 = index.ksub * index.M2; AlignedTable quantized_dis_tables(dim12); float normalizers[2]; @@ -74,22 +77,18 @@ std::vector> run_collect_handler( index.compute_quantized_LUT( 1, query, quantized_dis_tables.get(), normalizers, context); - // 2. Pack the LUT int qbs = pq4_preferred_qbs(1); AlignedTable LUT(dim12); pq4_pack_LUT_qbs(qbs, index.M2, quantized_dis_tables.get(), LUT.get()); - // 3. Create the handler std::vector> results; SingleQueryResultCollectHandler handler( results, index.ntotal, sel); - // 4. Begin + set normalizers handler.begin(normalizers); - // 5. Run the accumulate loop DummyScaler<> scaler; - pq4_accumulate_loop_qbs_fixed_scaler_256( + pq4_accumulate_loop_qbs_fixed_scaler_simd( qbs, index.ntotal2, index.M2, @@ -99,16 +98,11 @@ std::vector> run_collect_handler( scaler, index.get_block_stride()); - // 6. End (applies normalizer scaling) handler.end(); return results; } -/************************************************************* - * Test: handler collects results and count matches expectation - *************************************************************/ - TEST(TestSingleQueryCollectHandler, BasicResultCount) { auto index = make_index(); auto xq = make_data(1, 7890); @@ -120,13 +114,11 @@ TEST(TestSingleQueryCollectHandler, BasicResultCount) { EXPECT_EQ(results.size(), nb) << "Expected " << nb << " results, got " << results.size(); - // Each result should have a valid ID in [0, nb) for (auto& [id, dist] : results) { EXPECT_GE(id, 0); EXPECT_LT(id, static_cast(nb)); } - // IDs should be unique std::unordered_set id_set; for (auto& [id, dist] : results) { id_set.insert(id); @@ -134,15 +126,10 @@ TEST(TestSingleQueryCollectHandler, BasicResultCount) { EXPECT_EQ(id_set.size(), nb) << "Expected unique IDs, got duplicates"; } -/************************************************************* - * Test: handler with IDSelector only returns allowed IDs - *************************************************************/ - TEST(TestSingleQueryCollectHandler, WithIDSelector) { auto index = make_index(); auto xq = make_data(1, 7890); - // Allow only even IDs std::vector subset; for (idx_t i = 0; i < static_cast(nb); i += 2) { subset.push_back(i); @@ -152,26 +139,19 @@ TEST(TestSingleQueryCollectHandler, WithIDSelector) { auto results = run_collect_handler(*index, xq.data(), &sel); - // Should collect exactly the allowed IDs (nb/2) EXPECT_EQ(results.size(), nb / 2) << "Expected " << nb / 2 << " results, got " << results.size(); - // Every result must be in the allowed set for (auto& [id, dist] : results) { EXPECT_TRUE(allowed.count(id) > 0) << "Got id " << id << " which is not in the allowed set"; } } -/************************************************************* - * Test: empty selector -> no results - *************************************************************/ - TEST(TestSingleQueryCollectHandler, EmptySelector) { auto index = make_index(); auto xq = make_data(1, 7890); - // Empty batch = accept nothing IDSelectorBatch sel(0, nullptr); auto results = run_collect_handler(*index, xq.data(), &sel); @@ -180,74 +160,11 @@ TEST(TestSingleQueryCollectHandler, EmptySelector) { << "Expected 0 results with empty selector, got " << results.size(); } -/************************************************************* - * Test: results are consistent with normal search - * - * The top-k from a normal search should be a subset of the - * collected results (since the handler collects everything). - *************************************************************/ - -TEST(TestSingleQueryCollectHandler, ConsistentWithSearch) { - auto index = make_index(); - auto xq = make_data(1, 7890); - - // Normal top-10 search - int k = 10; - std::vector Dref(k); - std::vector Iref(k); - index->search(1, xq.data(), k, Dref.data(), Iref.data()); - - // Collect all results - auto results = run_collect_handler(*index, xq.data(), nullptr); - - // Build a map of id -> distance from collected results - std::unordered_map collected; - for (auto& [id, dist] : results) { - collected[id] = dist; - } - - // Every reference result should appear in the collected set - for (int j = 0; j < k; j++) { - if (Iref[j] >= 0) { - EXPECT_TRUE(collected.count(Iref[j]) > 0) - << "Top-" << k << " result id " << Iref[j] - << " not found in collected results"; - } - } -} - -/************************************************************* - * Test: ntotal not a multiple of 32 - *************************************************************/ - -TEST(TestSingleQueryCollectHandler, NonAlignedNtotal) { - size_t db_size = 77; // not a multiple of 32 - auto index = make_index(db_size); - auto xq = make_data(1, 7890); - - auto results = run_collect_handler(*index, xq.data(), nullptr); - - // Should collect exactly db_size results - EXPECT_EQ(results.size(), db_size) - << "Expected " << db_size << " results, got " << results.size(); - - // All IDs should be in [0, db_size) - for (auto& [id, dist] : results) { - EXPECT_GE(id, 0); - EXPECT_LT(id, static_cast(db_size)); - } -} - -/************************************************************* - * Test: IDSelector that excludes entire 32-vector blocks - * (exercises the block-skip optimization) - *************************************************************/ - +// Excludes a whole 32-vector block (block skip in for_each_block). TEST(TestSingleQueryCollectHandler, BlockSkipWithSelector) { auto index = make_index(); auto xq = make_data(1, 7890); - // Exclude the first 32 IDs (one full block) std::vector excluded; for (idx_t i = 0; i < 32; i++) { excluded.push_back(i); @@ -259,11 +176,9 @@ TEST(TestSingleQueryCollectHandler, BlockSkipWithSelector) { auto results = run_collect_handler(*index, xq.data(), &sel); - // Should collect nb - 32 results EXPECT_EQ(results.size(), nb - 32) << "Expected " << nb - 32 << " results, got " << results.size(); - // No excluded ID should appear for (auto& [id, dist] : results) { EXPECT_TRUE(excluded_set.count(id) == 0) << "Got excluded id " << id; } diff --git a/thirdparty/faiss/tests/test_sliding_ivf.cpp b/thirdparty/faiss/tests/test_sliding_ivf.cpp deleted file mode 100644 index 33068843b..000000000 --- a/thirdparty/faiss/tests/test_sliding_ivf.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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. - */ - -#include -#include - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include - -using namespace faiss; - -// dimension of the vectors to index -int d = 32; - -// nb of training vectors -size_t nt = 5000; - -// size of the database points per window step -size_t nb = 1000; - -// nb of queries -size_t nq = 200; - -int total_size = 40; -int window_size = 10; - -std::vector make_data(size_t n) { - std::vector database(n * d); - std::mt19937 rng; - std::uniform_real_distribution<> distrib; - for (size_t i = 0; i < n * d; i++) { - database[i] = distrib(rng); - } - return database; -} - -std::unique_ptr make_trained_index(const char* index_type) { - auto index = std::unique_ptr(index_factory(d, index_type)); - auto xt = make_data(nt * d); - index->train(nt, xt.data()); - ParameterSpace().set_index_parameter(index.get(), "nprobe", 4); - return index; -} - -std::vector search_index(Index* index, const float* xq) { - int k = 10; - std::vector I(k * nq); - std::vector D(k * nq); - index->search(nq, xq, k, D.data(), I.data()); - return I; -} - -/************************************************************* - * Test functions for a given index type - *************************************************************/ - -// make a few slices of indexes that can be merged -void make_index_slices( - const Index* trained_index, - std::vector>& sub_indexes) { - for (int i = 0; i < total_size; i++) { - sub_indexes.emplace_back(clone_index(trained_index)); - - Index* index = sub_indexes.back().get(); - - auto xb = make_data(nb * d); - std::vector ids(nb); - std::mt19937 rng; - std::uniform_int_distribution<> distrib; - for (size_t j = 0; j < nb; j++) { - ids[j] = distrib(rng); - } - index->add_with_ids(nb, xb.data(), ids.data()); - } -} - -// build merged index explicitly at sliding window position i -Index* make_merged_index( - const Index* trained_index, - const std::vector>& sub_indexes, - int i) { - Index* merged_index = clone_index(trained_index); - for (int j = i - window_size + 1; j <= i; j++) { - if (j < 0 || j >= total_size) { - continue; - } - std::unique_ptr sub_index(clone_index(sub_indexes[j].get())); - IndexIVF* ivf0 = ivflib::extract_index_ivf(merged_index); - IndexIVF* ivf1 = ivflib::extract_index_ivf(sub_index.get()); - ivf0->merge_from(*ivf1, 0); - merged_index->ntotal = ivf0->ntotal; - } - return merged_index; -} - -int test_sliding_window(const char* index_key) { - std::unique_ptr trained_index = make_trained_index(index_key); - - // make the index slices - std::vector> sub_indexes; - - make_index_slices(trained_index.get(), sub_indexes); - - // now slide over the windows - std::unique_ptr index(clone_index(trained_index.get())); - ivflib::SlidingIndexWindow window(index.get()); - - auto xq = make_data(nq * d); - - for (int i = 0; i < total_size + window_size; i++) { - // update the index - window.step( - i < total_size ? sub_indexes[i].get() : nullptr, - i >= window_size); - - auto new_res = search_index(index.get(), xq.data()); - - std::unique_ptr merged_index( - make_merged_index(trained_index.get(), sub_indexes, i)); - - auto ref_res = search_index(merged_index.get(), xq.data()); - - EXPECT_EQ(ref_res.size(), new_res.size()); - - EXPECT_EQ(ref_res, new_res); - } - return 0; -} - -int test_sliding_invlists(const char* index_key) { - std::unique_ptr trained_index = make_trained_index(index_key); - - // make the index slices - std::vector> sub_indexes; - - make_index_slices(trained_index.get(), sub_indexes); - - // now slide over the windows - std::unique_ptr index(clone_index(trained_index.get())); - IndexIVF* index_ivf = ivflib::extract_index_ivf(index.get()); - - auto xq = make_data(nq * d); - - for (int i = 0; i < total_size + window_size; i++) { - // update the index - std::vector ils; - for (int j = i - window_size + 1; j <= i; j++) { - if (j < 0 || j >= total_size) { - continue; - } - ils.push_back( - ivflib::extract_index_ivf(sub_indexes[j].get())->invlists); - } - if (ils.size() == 0) { - continue; - } - - ConcatenatedInvertedLists* ci = - new ConcatenatedInvertedLists(ils.size(), ils.data()); - - // will be deleted by the index - index_ivf->replace_invlists(ci, true); - - auto new_res = search_index(index.get(), xq.data()); - - std::unique_ptr merged_index( - make_merged_index(trained_index.get(), sub_indexes, i)); - - auto ref_res = search_index(merged_index.get(), xq.data()); - - EXPECT_EQ(ref_res.size(), new_res.size()); - EXPECT_EQ(ref_res, new_res); - } - return 0; -} - -/************************************************************* - * Test entry points - *************************************************************/ - -TEST(SlidingWindow, IVFFlat) { - test_sliding_window("IVF32,Flat"); -} - -TEST(SlidingWindow, PCAIVFFlat) { - test_sliding_window("PCA24,IVF32,Flat"); -} - -TEST(SlidingInvlists, IVFFlat) { - test_sliding_invlists("IVF32,Flat"); -} - -TEST(SlidingInvlists, PCAIVFFlat) { - test_sliding_invlists("PCA24,IVF32,Flat"); -} diff --git a/thirdparty/faiss/tests/test_sliding_ivf.py b/thirdparty/faiss/tests/test_sliding_ivf.py new file mode 100644 index 000000000..f0fb07a8f --- /dev/null +++ b/thirdparty/faiss/tests/test_sliding_ivf.py @@ -0,0 +1,124 @@ +# 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. + +"""Sliding window tests.""" + +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + +d = 32 +nt = 5000 +nb = 1000 +nq = 200 + +total_size = 40 +window_size = 10 + + +def make_data(n): + rs = np.random.RandomState(0) + return rs.rand(n, d).astype(np.float32) + + +def make_trained_index(index_key): + index = faiss.index_factory(d, index_key) + index.train(make_data(nt)) + faiss.ParameterSpace().set_index_parameter(index, "nprobe", 4) + return index + + +def search_index(index, xq): + _D, I = index.search(xq, 10) + return I + + +def make_index_slices(trained_index): + rs = np.random.RandomState(1) + sub_indexes = [] + for _i in range(total_size): + index = faiss.clone_index(trained_index) + xb = rs.rand(nb, d).astype(np.float32) + ids = rs.randint(0, 2**31, size=nb).astype(np.int64) + index.add_with_ids(xb, ids) + sub_indexes.append(index) + return sub_indexes + + +def make_merged_index(trained_index, sub_indexes, i): + merged_index = faiss.clone_index(trained_index) + for j in range(i - window_size + 1, i + 1): + if j < 0 or j >= total_size: + continue + sub_index = faiss.clone_index(sub_indexes[j]) + ivf0 = faiss.extract_index_ivf(merged_index) + ivf1 = faiss.extract_index_ivf(sub_index) + ivf0.merge_from(ivf1, 0) + merged_index.ntotal = ivf0.ntotal + return merged_index + + +class TestSlidingWindow(unittest.TestCase): + def check_sliding_window(self, index_key): + trained_index = make_trained_index(index_key) + sub_indexes = make_index_slices(trained_index) + + index = faiss.clone_index(trained_index) + window = faiss.SlidingIndexWindow(index) + + xq = make_data(nq) + + for i in range(total_size + window_size): + window.step( + sub_indexes[i] if i < total_size else None, + i >= window_size, + ) + + new_res = search_index(index, xq) + merged_index = make_merged_index(trained_index, sub_indexes, i) + ref_res = search_index(merged_index, xq) + + np.testing.assert_array_equal(ref_res, new_res) + + def test_pca_ivf_flat(self): + self.check_sliding_window("PCA24,IVF32,Flat") + + +class TestSlidingInvlists(unittest.TestCase): + def check_sliding_invlists(self, index_key): + trained_index = make_trained_index(index_key) + sub_indexes = make_index_slices(trained_index) + + index = faiss.clone_index(trained_index) + index_ivf = faiss.extract_index_ivf(index) + + xq = make_data(nq) + + for i in range(total_size + window_size): + ils = faiss.InvertedListsPtrVector() + for j in range(i - window_size + 1, i + 1): + if j < 0 or j >= total_size: + continue + ils.push_back( + faiss.extract_index_ivf(sub_indexes[j]).invlists) + if ils.size() == 0: + continue + + ci = faiss.ConcatenatedInvertedLists(ils.size(), ils.data()) + index_ivf.replace_invlists(ci, True) + ci.this.disown() + + new_res = search_index(index, xq) + merged_index = make_merged_index(trained_index, sub_indexes, i) + ref_res = search_index(merged_index, xq) + + np.testing.assert_array_equal(ref_res, new_res) + + def test_ivf_flat(self): + self.check_sliding_invlists("IVF32,Flat") diff --git a/thirdparty/faiss/tests/test_sorting.cpp b/thirdparty/faiss/tests/test_sorting.cpp index 1ccb4a9b2..3e724a00c 100644 --- a/thirdparty/faiss/tests/test_sorting.cpp +++ b/thirdparty/faiss/tests/test_sorting.cpp @@ -13,8 +13,7 @@ #include TEST(TestSorting, argsort_parallel_matches_serial) { - // n > 1M to exercise the parallel merge path - size_t n = 2000000; + size_t n = 100000; std::vector vals(n); std::mt19937 rng(42); @@ -35,45 +34,3 @@ TEST(TestSorting, argsort_parallel_matches_serial) { << "mismatch at position " << i; } } - -TEST(TestSorting, hashtable_lookup) { - int log2_capacity = 12; - size_t capacity = (size_t)1 << log2_capacity; - - std::vector tab(capacity * 2); - faiss::hashtable_int64_to_int64_init(log2_capacity, tab.data()); - - size_t n = 200; - std::vector keys(n), vals(n); - for (size_t i = 0; i < n; i++) { - keys[i] = static_cast(i * 3); - vals[i] = static_cast(i + 1); - } - faiss::hashtable_int64_to_int64_add( - log2_capacity, tab.data(), n, keys.data(), vals.data()); - - // Interleave present and absent keys - size_t n_query = n * 2; - std::vector query_keys(n_query); - std::vector expected(n_query); - for (size_t i = 0; i < n; i++) { - query_keys[2 * i] = keys[i]; - expected[2 * i] = vals[i]; - query_keys[2 * i + 1] = - keys[i] + 1; // not a multiple of 3, never inserted - expected[2 * i + 1] = -1; - } - - std::vector result(n_query); - faiss::hashtable_int64_to_int64_lookup( - log2_capacity, - tab.data(), - n_query, - query_keys.data(), - result.data()); - - for (size_t i = 0; i < n_query; i++) { - ASSERT_EQ(result[i], expected[i]) - << "query key " << query_keys[i] << " at index " << i; - } -} diff --git a/thirdparty/faiss/tests/test_sq_fastscan.py b/thirdparty/faiss/tests/test_sq_fastscan.py index 9248f70e8..6c79d70a0 100644 --- a/thirdparty/faiss/tests/test_sq_fastscan.py +++ b/thirdparty/faiss/tests/test_sq_fastscan.py @@ -3,27 +3,7 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -""" -Unit tests for IndexSQFastScan. - -Tests cover: - - Construction for native 4-bit types only - - Rejection of non-4-bit types - - Train / add / search round-trip - - Recall parity with IndexScalarQuantizer (within expected bounds) - - Conversion constructor from IndexScalarQuantizer - - Reset clears state - - Edge cases: k=1, single vector, zero vectors, odd dimensions - - Inner product metric - - sa_encode / sa_decode consistency - - I/O round-trip - - Factory strings - - get_distance_computer - - range_search -""" - -from __future__ import absolute_import, division, print_function - +import math import os import tempfile import unittest @@ -39,7 +19,6 @@ def recall_at_k(I_gt, I_test, k): return np.mean([I_gt[i, 0] in I_test[i, :k] for i in range(len(I_gt))]) -# Native 4-bit types (only types supported by IndexSQFastScan) SQ = faiss.ScalarQuantizer NATIVE_4BIT = [ @@ -49,67 +28,14 @@ def recall_at_k(I_gt, I_test, k): class TestSQFastScanConstruction(unittest.TestCase): - """IndexSQFastScan can be constructed for native 4-bit types only.""" - - def test_native_4bit_construct(self): - d = 64 - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(d, qtype) - self.assertEqual(index.d, d) - self.assertFalse(index.is_trained) - self.assertEqual(index.ntotal, 0) - - def test_default_construct(self): - index = faiss.IndexSQFastScan() - self.assertEqual(index.d, 0) - self.assertEqual(index.ntotal, 0) - def test_rejects_non_4bit(self): + def test_accepts_reranked_types_rejects_fallback(self): d = 64 - with self.assertRaises(RuntimeError): - faiss.IndexSQFastScan(d, SQ.QT_8bit) - with self.assertRaises(RuntimeError): - faiss.IndexSQFastScan(d, SQ.QT_6bit) with self.assertRaises(RuntimeError): faiss.IndexSQFastScan(d, SQ.QT_fp16) - with self.assertRaises(RuntimeError): - faiss.IndexSQFastScan(d, SQ.QT_bf16) - - -class TestSQFastScanTrainAddSearch(unittest.TestCase): - """Basic train/add/search works for native 4-bit types.""" - - def setUp(self): - self.d = 64 - self.nb = 5000 - self.nq = 50 - self.k = 10 - self.ds = SyntheticDataset(d=self.d, nt=2000, nb=self.nb, - nq=self.nq, seed=42) - - def test_native_4bit(self): - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(self.d, qtype) - index.train(self.ds.get_train()) - self.assertTrue(index.is_trained) - - index.add(self.ds.get_database()) - self.assertEqual(index.ntotal, self.nb) - - D, I = index.search(self.ds.get_queries(), self.k) - self.assertEqual(D.shape, (self.nq, self.k)) - self.assertEqual(I.shape, (self.nq, self.k)) - self.assertTrue(np.all(I[:, 0] >= 0)) - self.assertTrue(np.all(np.isfinite(D))) - for q in range(self.nq): - for j in range(1, self.k): - self.assertLessEqual(D[q, j - 1], D[q, j] + 1e-5) class TestSQFastScanRecallParity(unittest.TestCase): - """IndexSQFastScan recall should match IndexScalarQuantizer for 4-bit.""" def setUp(self): self.d = 64 @@ -120,7 +46,6 @@ def setUp(self): self.D_gt, self.I_gt = gt_index.search(self.ds.get_queries(), 10) def test_native_4bit_parity(self): - """Native 4-bit: FastScan should match SQ recall exactly.""" for name, qtype in NATIVE_4BIT: with self.subTest(qtype=name): sq = faiss.IndexScalarQuantizer(self.d, qtype) @@ -140,7 +65,6 @@ def test_native_4bit_parity(self): class TestSQFastScanConversionConstructor(unittest.TestCase): - """Conversion from IndexScalarQuantizer preserves search results.""" def setUp(self): self.d = 64 @@ -156,56 +80,43 @@ def test_conversion_native_4bit(self): fs = faiss.IndexSQFastScan(sq) self.assertEqual(fs.ntotal, sq.ntotal) - self.assertTrue(fs.is_trained) - D_sq, I_sq = sq.search(self.ds.get_queries(), 10) - D_fs, I_fs = fs.search(self.ds.get_queries(), 10) + _, I_sq = sq.search(self.ds.get_queries(), 10) + _, I_fs = fs.search(self.ds.get_queries(), 10) r1_sq = (I_sq[:, 0] >= 0).mean() r1_fs = (I_fs[:, 0] >= 0).mean() self.assertEqual(r1_sq, r1_fs) - def test_conversion_rejects_non_4bit(self): + def test_conversion_accepts_8bit_and_rejects_fallback(self): sq = faiss.IndexScalarQuantizer(self.d, SQ.QT_8bit) sq.train(self.ds.get_train()) + sq.add(self.ds.get_database()) + converted = faiss.IndexSQFastScan(sq) + self.assertEqual(converted.ntotal, sq.ntotal) + + fp16 = faiss.IndexScalarQuantizer(self.d, SQ.QT_fp16) + fp16.train(self.ds.get_train()) with self.assertRaises(RuntimeError): - faiss.IndexSQFastScan(sq) + faiss.IndexSQFastScan(fp16) class TestSQFastScanReset(unittest.TestCase): - """Reset should clear all stored data.""" def test_reset(self): d = 64 ds = SyntheticDataset(d=d, nt=1000, nb=500, nq=0, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(d, qtype) - index.train(ds.get_train()) - index.add(ds.get_database()) - self.assertEqual(index.ntotal, 500) + index = faiss.IndexSQFastScan(d, SQ.QT_4bit) + index.train(ds.get_train()) + index.add(ds.get_database()) - index.reset() - self.assertEqual(index.ntotal, 0) + index.reset() + self.assertEqual(index.ntotal, 0) - index.add(ds.get_database()) - self.assertEqual(index.ntotal, 500) + index.add(ds.get_database()) + self.assertEqual(index.ntotal, 500) class TestSQFastScanEdgeCases(unittest.TestCase): - """Edge cases: k=1, single vector, zero vectors, odd dimensions.""" - - def test_k_equals_1(self): - d = 32 - ds = SyntheticDataset(d=d, nt=500, nb=1000, nq=10, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(d, qtype) - index.train(ds.get_train()) - index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 1) - self.assertEqual(D.shape, (10, 1)) - self.assertEqual(I.shape, (10, 1)) - self.assertTrue(np.all(I >= 0)) def test_single_vector(self): d = 32 @@ -232,20 +143,17 @@ def test_zero_vectors(self): self.assertTrue(np.all(np.isfinite(D))) def test_odd_dimensions(self): - """Dimensions not aligned to SIMD width.""" for d in [7, 9, 15, 17, 31, 33, 63, 65]: with self.subTest(d=d): ds = SyntheticDataset(d=d, nt=500, nb=500, nq=5, seed=42) index = faiss.IndexSQFastScan(d, SQ.QT_4bit) index.train(ds.get_train()) index.add(ds.get_database()) - D, I = index.search(ds.get_queries(), 10) - self.assertEqual(D.shape, (5, 10)) + _, I = index.search(ds.get_queries(), 10) self.assertTrue(np.all(I[:, 0] >= 0)) class TestSQFastScanInnerProduct(unittest.TestCase): - """Inner product metric works correctly.""" def test_ip_basic(self): d = 64 @@ -262,7 +170,6 @@ def test_ip_basic(self): index.train(xb) index.add(xb) D, I = index.search(xq, 10) - self.assertEqual(D.shape, (50, 10)) self.assertTrue(np.all(I[:, 0] >= 0)) self.assertTrue(np.all(np.isfinite(D))) for q in range(50): @@ -271,54 +178,7 @@ def test_ip_basic(self): D[q, j - 1] + 1e-5, D[q, j]) -class TestSQFastScanSaDecode(unittest.TestCase): - """sa_decode should reconstruct vectors close to the original.""" - - def test_sa_decode(self): - d = 64 - ds = SyntheticDataset(d=d, nt=1000, nb=100, nq=0, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(d, qtype) - index.train(ds.get_train()) - index.add(ds.get_database()) - - xr = index.reconstruct_n(0, index.ntotal) - self.assertEqual(xr.shape, (100, d)) - self.assertTrue(np.all(np.isfinite(xr))) - - -class TestSQFastScanIncrementalAdd(unittest.TestCase): - """Adding vectors in batches should give same results as all-at-once.""" - - def test_incremental_add(self): - d = 64 - ds = SyntheticDataset(d=d, nt=1000, nb=1000, nq=20, seed=42) - xb = ds.get_database() - xq = ds.get_queries() - - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - idx1 = faiss.IndexSQFastScan(d, qtype) - idx1.train(ds.get_train()) - idx1.add(xb) - - idx2 = faiss.IndexSQFastScan(d, qtype) - idx2.train(ds.get_train()) - idx2.add(xb[:500]) - idx2.add(xb[500:]) - - self.assertEqual(idx1.ntotal, idx2.ntotal) - - D1, I1 = idx1.search(xq, 10) - D2, I2 = idx2.search(xq, 10) - - np.testing.assert_array_equal(I1, I2) - np.testing.assert_allclose(D1, D2, atol=1e-5) - - class TestSQFastScanSaEncode(unittest.TestCase): - """sa_encode / sa_decode round-trip matches IndexScalarQuantizer.""" def test_sa_encode_matches_sq(self): d = 64 @@ -332,7 +192,6 @@ def test_sa_encode_matches_sq(self): fs.train(ds.get_train()) xb = ds.get_database() - cs = fs.sa_code_size() sq_codes = sq.sa_encode(xb) fs_codes = fs.sa_encode(xb) @@ -345,53 +204,7 @@ def test_sa_encode_matches_sq(self): err_msg=f"{name}: sa_decode differs") -class TestSQFastScanAddSaCodes(unittest.TestCase): - """add_sa_codes should produce working indexes.""" - - def test_add_sa_codes(self): - d = 64 - ds = SyntheticDataset(d=d, nt=1000, nb=500, nq=20, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - ref = faiss.IndexSQFastScan(d, qtype) - ref.train(ds.get_train()) - ref.add(ds.get_database()) - - test = faiss.IndexSQFastScan(d, qtype) - test.train(ds.get_train()) - codes = test.sa_encode(ds.get_database()) - test.add_sa_codes(codes) - - self.assertEqual(ref.ntotal, test.ntotal) - - D_ref, I_ref = ref.search(ds.get_queries(), 10) - D_test, I_test = test.search(ds.get_queries(), 10) - self.assertTrue(np.all(I_ref[:, 0] >= 0)) - self.assertTrue(np.all(I_test[:, 0] >= 0)) - - -class TestSQFastScanPermuteEntries(unittest.TestCase): - """permute_entries reorders the packed codes.""" - - def test_permute_entries(self): - d, nb = 64, 100 - ds = SyntheticDataset(d=d, nt=1000, nb=nb, nq=0, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - index = faiss.IndexSQFastScan(d, qtype) - index.train(ds.get_train()) - index.add(ds.get_database()) - - before = index.reconstruct_n(0, nb) - perm = np.arange(nb - 1, -1, -1).astype("int64") - index.permute_entries(perm) - - np.testing.assert_allclose( - index.reconstruct_n(0, nb), before[perm], atol=1e-5) - - class TestSQFastScanDistanceComputer(unittest.TestCase): - """get_distance_computer works for native 4-bit types.""" def test_distance_computer(self): d = 64 @@ -405,36 +218,7 @@ def test_distance_computer(self): self.assertIsNotNone(dc) -class TestSQFastScanRangeSearch(unittest.TestCase): - """range_search produces results consistent with kNN search.""" - - def test_range_search(self): - d = 64 - ds = SyntheticDataset(d=d, nt=1000, nb=1000, nq=10, seed=42) - for name, qtype in NATIVE_4BIT: - with self.subTest(qtype=name): - sq = faiss.IndexScalarQuantizer(d, qtype) - sq.train(ds.get_train()) - sq.add(ds.get_database()) - - fs = faiss.IndexSQFastScan(d, qtype) - fs.train(ds.get_train()) - fs.add(ds.get_database()) - - D, _ = sq.search(ds.get_queries()[:1], 1000) - radius = float(D[0, 500]) - - lims_sq, D_sq, I_sq = sq.range_search( - ds.get_queries(), radius) - lims_fs, D_fs, I_fs = fs.range_search( - ds.get_queries(), radius) - - np.testing.assert_array_equal(lims_sq, lims_fs, - err_msg=f"{name}: lims differ") - - class TestSQFastScanIO(unittest.TestCase): - """I/O round-trip preserves index state and search results.""" def test_io_roundtrip(self): d = 64 @@ -456,8 +240,6 @@ def test_io_roundtrip(self): os.unlink(fname) self.assertIsInstance(loaded, faiss.IndexSQFastScan) - self.assertEqual(loaded.ntotal, index.ntotal) - self.assertEqual(loaded.d, d) D2, I2 = loaded.search(ds.get_queries(), 10) np.testing.assert_array_equal(I1, I2) @@ -465,13 +247,6 @@ def test_io_roundtrip(self): class TestSQFastScanFactory(unittest.TestCase): - """Factory string produces IndexSQFastScan.""" - - def test_factory_strings(self): - d = 64 - index = faiss.index_factory(d, "SQ4fs") - self.assertIsInstance(index, faiss.IndexSQFastScan) - self.assertEqual(index.d, d) def test_factory_with_bbs(self): d = 64 @@ -479,11 +254,202 @@ def test_factory_with_bbs(self): self.assertIsInstance(index, faiss.IndexSQFastScan) self.assertEqual(index.bbs, 64) - def test_factory_metric(self): - d = 64 - index = faiss.index_factory(d, "SQ4fs", faiss.METRIC_INNER_PRODUCT) - self.assertIsInstance(index, faiss.IndexSQFastScan) - -if __name__ == '__main__': - unittest.main() +class TestFastScanLUTScaleRounding(unittest.TestCase): + """Rounding must not push the summed table over the uint16 limit. + + Each entry is rounded up by as much as 0.5, so M entries can add M/2 on + top of the sum the scale was chosen to fit. The scale has to leave room + for that. + """ + + def test_equal_spans_do_not_overflow_the_accumulator(self): + # M equal spans is the worst case: with a scale of 65535 / total the + # per-column maximum lands just under an integer and every one of them + # rounds up together. + for m in (256, 512, 1024, 2048): + scale = faiss.fastscan_lut_scale(1.0, float(m), m) + per_entry = math.floor(1.0 * scale + 0.5) + self.assertLessEqual( + per_entry * m, + 65535, + f"M={m}: {m} entries of {per_entry} sum to {per_entry * m}", + ) + self.assertLessEqual(per_entry, 255, f"M={m} overflows the uint8") + + def test_scale_still_uses_the_range_it_has(self): + # The headroom must not collapse the scale: a 1024-column table should + # still reach most of the accumulator. + scale = faiss.fastscan_lut_scale(1.0, 1024.0, 1024) + total = math.floor(1.0 * scale + 0.5) * 1024 + self.assertGreater(total, 60000, f"scale too conservative, total {total}") + + def test_sq_fastscan_recall_at_d1024(self): + # d = 1024 means M = 1024, four times the M = 257 point where the + # accumulator can wrap. A wrap makes the ranking noise, so R@1 collapses. + d, n, nq = 1024, 2000, 50 + rng = np.random.default_rng(123) + xb = rng.standard_normal((n, d), dtype=np.float32) + xq = xb[:nq].copy() + index = faiss.index_factory(d, "SQ4fs") + index.train(xb) + index.add(xb) + _, ids = index.search(xq, 1) + self.assertGreater( + (ids[:, 0] == np.arange(nq)).mean(), 0.9, "R@1 collapsed, LUT wrapped" + ) + + +class TestRaBitQFastScanBiasBound(unittest.TestCase): + """The per-probe bias is rounded into the same uint16 as the entries. + + The scale must bound span_j + probe_b[j] - glob_b, not span_j alone. A + query whose probed lists have very different biases makes the difference + large enough to wrap if only the span is bounded. + """ + + def test_matches_non_fastscan_with_uneven_probe_biases(self): + """Regression guard on the biased path at d = 1024, where the sum + bound binds. It does not isolate the overflow.""" + d, nlist, per, nq = 1024, 16, 40, 40 + rng = np.random.default_rng(7) + centers = (np.arange(nlist, dtype=np.float32)[:, None] * 10.0) * np.ones( + (1, d), dtype=np.float32 + ) + xb = np.repeat(centers, per, axis=0) + rng.standard_normal( + (nlist * per, d) + ).astype(np.float32) + xq = xb[:nq].copy() + + def recall_at_1(factory): + index = faiss.index_factory(d, factory) + index.train(xb) + index.add(xb) + ivf = faiss.try_extract_index_ivf(index) + ivf.nprobe = nlist + _, ids = index.search(xq, 1) + return (ids[:, 0] == np.arange(nq)).mean() + + ref = recall_at_1(f"HR,IVF{nlist},RaBitQ4") + fs = recall_at_1(f"HR,IVF{nlist},RaBitQfs4") + self.assertGreaterEqual( + fs, ref - 0.1, f"fast scan R@1 {fs:.2f} trails the reference {ref:.2f}" + ) + + +class TestSQFastScanSplitCodePaths(unittest.TestCase): + """Paths that rebuild a full code from the split halves. + + QT_4bit hides every bug here, because its code is already one nibble per + dimension and sq.code_size equals the fast-scan code size. + """ + + def _pair(self, qtype, d=32, n=200): + rng = np.random.default_rng(0) + xb = rng.standard_normal((n, d), dtype=np.float32) + ref = faiss.IndexScalarQuantizer(d, qtype) + ref.train(xb) + ref.add(xb) + fs = faiss.IndexSQFastScan(d, qtype) + fs.train(xb) + fs.add(xb) + return xb, ref, fs + + def test_reconstruct_matches_reference(self): + for qtype in (SQ.QT_4bit, SQ.QT_6bit, SQ.QT_8bit): + _, ref, fs = self._pair(qtype) + for i in (0, 7, 199): + np.testing.assert_array_equal( + ref.reconstruct(i), fs.reconstruct(i) + ) + + def test_range_search_matches_reference(self): + for qtype in (SQ.QT_4bit, SQ.QT_6bit, SQ.QT_8bit): + xb, ref, fs = self._pair(qtype) + lref, _, iref = ref.range_search(xb[:5], 20.0) + lfs, _, ifs = fs.range_search(xb[:5], 20.0) + np.testing.assert_array_equal(lref, lfs) + self.assertEqual(sorted(iref.tolist()), sorted(ifs.tolist())) + + def test_permute_entries_moves_both_halves(self): + for qtype in (SQ.QT_4bit, SQ.QT_6bit, SQ.QT_8bit): + _, _, fs = self._pair(qtype) + n = fs.ntotal + before = fs.reconstruct_n(0, n) + perm = np.arange(n - 1, -1, -1, dtype="int64") + fs.permute_entries(perm) + np.testing.assert_array_equal(fs.reconstruct_n(0, n), before[perm]) + + def test_direct_qtypes_match_reference(self): + rng = np.random.default_rng(0) + d, n = 32, 200 + for qtype, lo in ( + (SQ.QT_8bit_direct, 0), + (SQ.QT_8bit_direct_signed, -128), + ): + xb = rng.integers(lo, lo + 256, size=(n, d)).astype(np.float32) + ref = faiss.IndexScalarQuantizer(d, qtype) + ref.train(xb) + ref.add(xb) + fs = faiss.IndexSQFastScan(d, qtype) + fs.train(xb) + fs.add(xb) + _, iref = ref.search(xb[:10], 5) + _, ifs = fs.search(xb[:10], 5) + hits = sum(len(set(a) & set(b)) for a, b in zip(iref, ifs)) + self.assertGreaterEqual(hits, 0.9 * iref.size) + + def test_lo_codes_track_ntotal_across_add_paths(self): + rng = np.random.default_rng(0) + d, qtype = 8, SQ.QT_8bit + # over the blocking size of IndexFastScan::add, which re-enters add() + n = 70000 + xb = rng.standard_normal((n, d), dtype=np.float32) + ref = faiss.IndexScalarQuantizer(d, qtype) + ref.train(xb) + ref.add(xb) + + one = faiss.IndexSQFastScan(d, qtype) + one.train(xb) + one.add(xb) + self.assertEqual(one.ntotal, n) + + split = faiss.IndexSQFastScan(d, qtype) + split.train(xb) + split.add(xb[:40000]) + split.add(xb[40000:]) + self.assertEqual(split.ntotal, n) + + for i in (0, 39999, 65536, n - 1): + expect = ref.reconstruct(i) + np.testing.assert_array_equal(expect, one.reconstruct(i)) + np.testing.assert_array_equal(expect, split.reconstruct(i)) + + def test_add_sa_codes_fills_the_rerank_half(self): + xb, ref, _ = self._pair(SQ.QT_8bit) + fs = faiss.IndexSQFastScan(ref.d, SQ.QT_8bit) + fs.train(xb) + fs.add_sa_codes(ref.sa_encode(xb)) + self.assertEqual(fs.ntotal, ref.ntotal) + for i in (0, 7, 199): + np.testing.assert_array_equal(ref.reconstruct(i), fs.reconstruct(i)) + + def test_merge_from_moves_the_rerank_half(self): + rng = np.random.default_rng(0) + d, n = 16, 100 + xb = rng.standard_normal((2 * n, d), dtype=np.float32) + parts = [] + for lo, hi in ((0, n), (n, 2 * n)): + idx = faiss.IndexSQFastScan(d, SQ.QT_8bit) + idx.train(xb) + idx.add(xb[lo:hi]) + parts.append(idx) + parts[0].merge_from(parts[1]) + self.assertEqual(parts[0].ntotal, 2 * n) + + whole = faiss.IndexSQFastScan(d, SQ.QT_8bit) + whole.train(xb) + whole.add(xb) + np.testing.assert_array_equal( + whole.reconstruct_n(0, 2 * n), parts[0].reconstruct_n(0, 2 * n) + ) diff --git a/thirdparty/faiss/tests/test_sq_rvv_tail_and_semantics.cpp b/thirdparty/faiss/tests/test_sq_rvv_tail_and_semantics.cpp index 16bdcc8dc..4d6adaeab 100644 --- a/thirdparty/faiss/tests/test_sq_rvv_tail_and_semantics.cpp +++ b/thirdparty/faiss/tests/test_sq_rvv_tail_and_semantics.cpp @@ -5,51 +5,7 @@ * LICENSE file in the root directory of this source tree. */ -/* - * - * SQ-RVV review-response tests (see - * docs/sq_rvv_review_analysis_and_test_plan.md for the full analysis): - * - * D1 CounterexampleRegression — uniform L2 half-grid semantics (the - * review's literal q == recon(c) counterexample) - * D2 TailBoundaryParity — d past VLMAX so the tail pass runs - * (may pass on well-behaved hardware; regression + VLEN sensitivity) - * D3 DirectBitExact — in-contract integer data => exactly equal - * D5 OverflowGuard — large-d float-domain parity for the direct - * codecs (the kernels accumulate in f32; f32 saturates near 3.4e38, - * so there is no integer-wraparound failure mode to guard) - * D5b LargeDimParity — large-d direct-codec parity vs the exact - * double reference (regression net for the old per-lane i32/u32 - * wraparound and the signed-IP query-bias overflow, both gone now - * that the kernels are float-domain) - * D6 ZeroDim — d == 0 must return 0, not hang; each case - * runs in a forked child under alarm() so a hang only fails its own - * case (POSIX only; skipped on Windows hosts) - * D7 SpecialQueries — clamp boundaries / systematic-value - * queries / huge-but-finite magnitudes - * D8 SmallDimensionParity — odd & very small d (1/2/3/5/7) across every - * qtype x metric (packing tail: 4-bit odd-d padding, 6-bit ng==0) - * D9 ReconQuery — q == recon(code) => L2 distance ~ 0, for - * every qtype (not just uniform) - * D10 FloatQueryParity — direct codecs retain FLOAT-query - * semantics: fractional queries must match the scalar NONE - * reference (the review's literal q=0.75 counterexample; an - * earlier integer-domain kernel truncated the query and ranked - * candidates differently) - * - * Expected status against the CURRENT sq-rvv.cpp (all codecs, direct - * included, are float-domain in the query): - * D1: PASS (uniform L2/IP float-domain semantics) - * D2: PASS expected on board - * D3: PASS expected (in-contract integer data keeps f32 sums exact) - * D5: PASS (float-domain, no wraparound) - * D5b: PASS (float-domain, no wraparound / bias overflow) - * D6: PASS (all kernels guard vsetvl(0) with `d > 0 ? d : 1`) - * D7: PASS (exact float-domain) - * D8: PASS expected - * D9: PASS expected - * D10: PASS (float-query semantics retained) - */ +// RVV vs scalar (NONE) scalar-quantizer kernel parity and edge-case semantics. #include @@ -62,12 +18,6 @@ #include #include -#ifndef _WIN32 -#include -#include -#include -#endif - // D5b derives the test dimensions from the board's real VLMAX. #if defined(__riscv) && defined(COMPILE_SIMD_RISCV_RVV) #include @@ -89,10 +39,6 @@ using SQ = faiss::ScalarQuantizer; using faiss::METRIC_INNER_PRODUCT; using faiss::METRIC_L2; -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - struct ScopedSIMDLevel { faiss::SIMDLevel original; explicit ScopedSIMDLevel(faiss::SIMDLevel level) @@ -149,22 +95,6 @@ static bool is_direct(SQ::QuantizerType qtype) { return class_of(qtype) == QClass::Direct; } -/// All SQ qtypes with RVV specializations. -static const std::vector& all_rvv_qtypes() { - static const std::vector qtypes = { - SQ::QT_4bit, - SQ::QT_4bit_uniform, - SQ::QT_6bit, - SQ::QT_8bit, - SQ::QT_8bit_uniform, - SQ::QT_8bit_direct, - SQ::QT_8bit_direct_signed, - SQ::QT_fp16, - SQ::QT_bf16, - }; - return qtypes; -} - /// One scalar (NONE) + one RVV distance computer over the same trained /// parameters and code array. codes may be null when only query_to_code on /// caller-supplied bytes is used. @@ -237,17 +167,9 @@ static void trained_range( } } -// =========================================================================== -// D1 — Uniform L2 must keep the scalar float-domain semantics. -// -// Scalar: L2(q, code) = (q - recon(c))^2 with recon(c) = vmin + -// vdiff*(c+0.5)/max_code — a HALF-INTEGER grid in code units. -// -// The float-domain kernels retain the original query (no integer-grid -// pre-quantization), so they must match the scalar argmin and distance. -// Sweep A pins the review's literal counterexample (q = recon(c) must be -// distance 0 to code c); sweep B pins full parity at integer queries. -// =========================================================================== +// D1: uniform L2 must keep the scalar half-integer grid +// recon(c) = vmin + vdiff * (c + 0.5) / max_code, so q = recon(c) is at +// distance 0 from code c. struct UniformL2Params { SQ::QuantizerType qtype; @@ -267,7 +189,6 @@ TEST_P(SQRVVCounterexample, HalfGridCounterexample) { const size_t d = 1; // vmin=0, vdiff=max_code => recon(c) = c + 0.5, code-unit step exactly 1 std::vector trained = {0.0f, float(max_code)}; - // code_size: d=1 -> 1 byte for both codecs const size_t code_size = 1; DcPair dc = @@ -280,7 +201,7 @@ TEST_P(SQRVVCounterexample, HalfGridCounterexample) { bytes[c] = static_cast(c); } - // ---- Sweep A: q = recon(c) = c + 0.5 (the review counterexample) ---- + // ---- Sweep A: q = recon(c) = c + 0.5 ---- for (int code = 0; code <= max_code; code++) { std::vector q = {float(code) + 0.5f}; dc.scalar_dc->set_query(q.data()); @@ -332,20 +253,9 @@ INSTANTIATE_TEST_SUITE_P( UniformL2Params{SQ::QT_4bit_uniform, 4, "4bit_uniform_L2"}, UniformL2Params{SQ::QT_8bit_uniform, 8, "8bit_uniform_L2"})); -/// vdiff == 0: the trained range collapses to a single point recon(c) == -/// vmin for every code. The scalar distance is therefore NOT the all-zero -/// defect: -/// L2(q, code) = sum_i (q_i - vmin)^2 -/// IP(q, code) = vmin * sum_i q_i -/// Covers every uniform codec under both metrics — the float-domain kernels -/// must match the scalar NONE reference to reassociation precision. -/// Case A: all-zero code. Case B: max code (0xFF / 0x0F) with a huge -/// finite query — the review's literal counterexample. An intermediate -/// sum(q_i*c_i) overflows to inf there, and the retired factorization -/// K_q + scale*sum(q_i*c_i) evaluated 0*inf == NaN; the per-dim -/// pre-scaled form K_q + sum((q_i*scale)*c_i) must return exactly what -/// the scalar reference returns (0 for vmin==0, vmin*sum(q) otherwise), -/// finite in every case. +/// vdiff == 0: recon(c) == vmin for every code, so L2 = sum_i (q_i - vmin)^2 +/// and IP = vmin * sum_i q_i, not 0. With a huge query, a kernel that +/// computes scale * sum(q_i * c_i) gets 0 * inf == NaN. struct ZeroVdiffParams { SQ::QuantizerType qtype; faiss::MetricType metric; @@ -397,13 +307,9 @@ TEST_P(SQRVVZeroVdiff, UniformVdiffZero) { << expect << " (all-distances-zero defect)"; } - // ---- Case B: max code + huge finite query (review counterexample) ---- - // d=1, trained={0,0}, q=FLT_MAX, code 15/255. IP: the scalar per-dim - // form is q_i * recon_i = q_i * 0 == 0, so the exact answer is 0; the - // retired factorization K_q + scale*sum(q_i*c_i) returned NaN there - // (intermediate sum overflowed to inf, then 0*inf). L2 legitimately - // overflows in BOTH implementations ((FLT_MAX)^2 -> inf, per-dim - // semantics), so it only asserts scalar/RVV agreement. + // ---- Case B: max code + FLT_MAX query, vmin == vdiff == 0 ---- + // IP must be exactly 0. L2 overflows to inf in both implementations, so + // only scalar/RVV agreement is asserted. { const size_t d1 = 1; std::vector trained1 = {0.0f, 0.0f}; // vdiff == 0, vmin == 0 @@ -428,11 +334,9 @@ TEST_P(SQRVVZeroVdiff, UniformVdiffZero) { } } - // ---- Case C: max code + huge finite query, vmin != 0 (IP only) ---- - // vdiff == 0, vmin = 0.5: the true IP is finite and nonzero - // (vmin * q), while an overflowing sum(q_i*c_i) intermediate would - // still yield NaN — catches kernels that collapse the result to - // zero as well as the NaN defect. + // ---- Case C: max code + huge query, vmin != 0 (IP only) ---- + // The IP vmin * q is finite and nonzero: catches both NaN and a result + // collapsed to 0. if (p.metric == METRIC_INNER_PRODUCT) { const size_t d1 = 1; const float vmin1 = 0.5f; @@ -478,15 +382,8 @@ INSTANTIATE_TEST_SUITE_P( return std::string(info.param.name); }); -// =========================================================================== -// D1c — Uniform IP query-constant overflow semantics. IP = K_q + S with -// K_q = sum_i (q_i * c0) accumulated PER DIM. The retired form -// K_q = c0 * sum(q) overflowed the bare sum(q) to inf first -// (multi-dim huge finite query), then c0 == 0 produced 0*inf == -// NaN; the scalar per-dim form returns exactly 0 (every term -// q_i * 0 == 0). Same contract checked for both uniform codecs -// with c0 == 0 (vmin == 0, vdiff == 0). -// =========================================================================== +// D1c: uniform IP query constant K_q = sum_i (q_i * c0) must be accumulated +// per dim: c0 * sum(q) gives 0 * inf == NaN when sum(q) overflows and c0 == 0. TEST(SQRVVQueryConstOverflow, HugeQueryZeroC0ReturnsZero) { if (!faiss::SIMDConfig::is_simd_level_available( @@ -532,14 +429,8 @@ TEST(SQRVVQueryConstOverflow, HugeQueryZeroC0ReturnsZero) { } } -// =========================================================================== -// D1b — symmetric_dis overflow semantics. Identical codes must return -// exactly 0. The retired 8bit_uniform-L2 factored form -// float(sum(delta_c^2)) * (a*a) returned 0 * inf == NaN when -// a = vdiff/255 was so large that a*a overflowed; the per-dim -// scaled form (diff = a*(c1-c2) before squaring) keeps identical -// codes at exact 0. Same contract checked for all uniform codecs. -// =========================================================================== +// D1b: symmetric_dis of identical codes must be exactly 0 even when +// (vdiff / 255)^2 overflows: float(sum(delta_c^2)) * (a * a) gives 0 * inf. TEST(SQRVVSymmetricOverflow, HugeVdiffIdenticalCodesReturnZero) { if (!faiss::SIMDConfig::is_simd_level_available( @@ -575,7 +466,7 @@ TEST(SQRVVSymmetricOverflow, HugeVdiffIdenticalCodesReturnZero) { dc.rvv_dc->codes = zero_codes.data(); dc.rvv_dc->code_size = c.code_size; - // (a) identical codes -> exact 0 (the review's counterexample) + // (a) identical codes -> exact 0 for (size_t i = 0; i < 2; i++) { float ref = dc.scalar_dc->symmetric_dis(i, i); float tst = dc.rvv_dc->symmetric_dis(i, i); @@ -592,13 +483,9 @@ TEST(SQRVVSymmetricOverflow, HugeVdiffIdenticalCodesReturnZero) { } } -// =========================================================================== -// D2 — Tail-boundary parity: dimensions that split the vector loop into -// (full chunks) + (short tail). The tail pass must not corrupt lanes -// covered by the final reduction. On well-behaved hardware this may -// pass even with the tail-agnostic bug; it is the regression net and -// the VLEN-sensitivity probe (run also under QEMU vlen=256/512). -// =========================================================================== +// D2: dimensions that split the vector loop into full chunks + a short tail; +// the tail pass must not corrupt lanes covered by the final reduction. +// Some hardware hides a tail-agnostic bug, so also run under QEMU vlen=256/512. struct TailParams { SQ::QuantizerType qtype; @@ -657,7 +544,6 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { ::testing::Message() << p.name << " metric=" << metric_name(p.metric) << " d=" << p.d); - // query_to_code for (size_t i = 0; i < n_db; i++) { const uint8_t* code = db_codes.data() + i * sq.code_size; float ref = dc.scalar_dc->query_to_code(code); @@ -668,7 +554,6 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { << p.name << " query_to_code code=" << i; } - // zero + max codes { std::vector zero_code(sq.code_size, 0); float ref = dc.scalar_dc->query_to_code(zero_code.data()); @@ -684,7 +569,6 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { << p.name << " max code"; } - // symmetric_dis for (size_t i = 0; i + 1 < n_db; i += 2) { float ref = dc.scalar_dc->symmetric_dis(i, i + 1); float tst = dc.rvv_dc->symmetric_dis(i, i + 1); @@ -692,7 +576,6 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { << p.name << " symmetric_dis(" << i << "," << (i + 1) << ")"; } - // batch_4 { const uint8_t *c0 = db_codes.data(), *c1 = db_codes.data() + sq.code_size, @@ -711,7 +594,6 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { << p.name << " batch_4[3]"; } - // scanner parity std::unique_ptr scalar_scanner( faiss::scalar_quantizer::sq_select_InvertedListScanner< faiss::SIMDLevel::NONE>( @@ -759,10 +641,7 @@ TEST_P(SQRVVTailBoundary, ParityAtTailDimensions) { * 6bit on ng=d/4 groups: 68 -> 17g = 16+1, 69 -> +1 scalar dim, * 127 -> 31g = 16+15 + 3 scalar dims * bf16 e16m2: 17 = 16+1, 33 = 32+1; fp16 e16m1: 9, 17, 23 - * Tolerances: all float-domain codecs (uniform and non-uniform) 1e-3 - * (reassociation); direct in-contract integer data 1e-3 (exact integer - * sums). Uniform L2/IP are now float-domain — their semantic contract is - * pinned tightly by D1. + * Tolerance 1e-3: f32 reassociation (direct codecs on integer data are exact). */ INSTANTIATE_TEST_SUITE_P( D2, @@ -968,12 +847,8 @@ INSTANTIATE_TEST_SUITE_P( 1e-3f, "fp16_IP/d23"})); -// =========================================================================== -// D3 — Direct codecs: in-contract (integer-grid) data must give EXACTLY -// equal results (both kernels are float-domain now; integer-grid -// distances and their partial sums stay < 2^24 at these d, so f32 -// represents them exactly and the f32 accumulators cannot round). -// =========================================================================== +// D3: direct codecs on integer-grid data must match exactly (partial sums stay +// below 2^24 at these d, so f32 accumulation does not round). struct DirectExactParams { SQ::QuantizerType qtype; @@ -1092,102 +967,12 @@ INSTANTIATE_TEST_SUITE_P( 129, "8bit_direct_signed_IP_d129"})); -// =========================================================================== -// D5 — Large-d parity for the direct codecs. The kernels are float-domain -// (f32 accumulators saturate near 3.4e38), so magnitudes that used to -// overflow 32-bit integer accumulators must simply stay in parity with -// the scalar reference. -// =========================================================================== - -static void run_overflow_case( - SQ::QuantizerType qtype, - faiss::MetricType metric, - size_t d, - uint8_t code_byte, - float q_value, - const char* name, - double expected_exact) { - if (!faiss::SIMDConfig::is_simd_level_available( - faiss::SIMDLevel::RISCV_RVV)) { - GTEST_SKIP() << "RISCV_RVV not available"; - } - // direct codecs ignore trained params; d=34000 training would be - // wasteful, so hand the computer a minimal trained vector. - std::vector trained; - DcPair dc = make_dc_pair(qtype, metric, d, trained, nullptr, d); - ASSERT_TRUE(dc.scalar_dc && dc.rvv_dc); - - std::vector q(d, q_value); - dc.scalar_dc->set_query(q.data()); - dc.rvv_dc->set_query(q.data()); - - std::vector code(d, code_byte); - float ref = dc.scalar_dc->query_to_code(code.data()); - float tst = dc.rvv_dc->query_to_code(code.data()); - - // Scalar reference accumulates in f32 — allow 1e-3 relative slack; - // the RVV float kernel matches it to reassociation precision. - const float tol = float(expected_exact * 1e-3); - EXPECT_NEAR(tst, expected_exact, tol) - << name << " d=" << d << " rvv=" << tst - << " expected=" << expected_exact; - EXPECT_NEAR(ref, expected_exact, tol) << name << " scalar ref drifted"; -} - -TEST(D5Overflow, DirectL2LargeDim) { - // 65025 per dim — magnitudes that overflowed the old i32 accumulator - // at d > ~33025; the float kernel must track the scalar reference. - const size_t d = 34000; - run_overflow_case( - SQ::QT_8bit_direct, - METRIC_L2, - d, - 0x00, - 255.0f, - "8bit_direct_L2", - double(d) * 65025.0); -} - -TEST(D5Overflow, DirectIPLargeDim) { - const size_t d = 68000; - run_overflow_case( - SQ::QT_8bit_direct, - METRIC_INNER_PRODUCT, - d, - 0xff, - 255.0f, - "8bit_direct_IP", - double(d) * 65025.0); -} - -TEST(D5Overflow, DirectSignedL2LargeDim) { - // query 127 in value space <-> storage byte 127+128 = 255; - // code byte 0x00 (value -128): diff 127-(-128) = 255 -> 65025 per dim. - const size_t d = 34000; - run_overflow_case( - SQ::QT_8bit_direct_signed, - METRIC_L2, - d, - 0x00, - 127.0f, - "8bit_direct_signed_L2", - double(d) * 65025.0); -} - -// =========================================================================== -// D5b — Large-d parity at (and past) the old per-lane i32/u32 wrap point -// and the signed-IP query-bias overflow point. These dimensions sat -// exactly past the wrap thresholds of the retired integer-domain -// kernels; they are a regression net pinning the float-domain -// semantics at scale (RVV vs scalar parity + exact double reference). -// The chunk count is parameterized per case so EVERY integer -// accumulator a regression could reintroduce is pushed past its own -// wrap threshold: -// - L2 / signed i32 lanes: ceil(2^31 / 65025) = 33026 -// - IP / unsigned u32 lanes: ceil(2^32 / 65025) = 66052 -// - signed-IP worst-case term ceil(2^31 / 32640) = 65794 -// (qs = -128 * code value +127 -> |term| = 32640 per chunk) -// =========================================================================== +// D5b: large-d direct-codec parity. Each case pushes a per-lane integer +// accumulator past its wrap threshold, so a reintroduced integer kernel fails: +// - L2 / signed i32 lanes: ceil(2^31 / 65025) = 33026 chunks +// - IP / unsigned u32 lanes: ceil(2^32 / 65025) = 66052 chunks +// - signed-IP worst-case term: ceil(2^31 / 32640) = 65794 chunks +// (q = -128 against code value +127 -> |term| = 32640 per chunk) static void run_flush_case( SQ::QuantizerType qtype, @@ -1201,18 +986,14 @@ static void run_flush_case( faiss::SIMDLevel::RISCV_RVV)) { GTEST_SKIP() << "RISCV_RVV not available"; } - // VLMAX at this VLEN, derived at runtime so the dimensions below sit - // past the old wrap thresholds on VLEN=128/256/... boards alike. + // VLMAX at this VLEN, so the thresholds hold for any VLEN. #if defined(FAISS_RVV_HAS_INTRINSICS) const size_t vl = __riscv_vsetvlmax_e8m2(); #else GTEST_SKIP() << "no RVV intrinsics at test compile time"; const size_t vl = 32; #endif - // d = n_chunks full per-lane chunks + 1 tail dim. n_chunks must be - // chosen per case to cross THAT case's integer-accumulator threshold - // (see the derivation in the block comment above); the tail dim adds - // one extra term to lane 0 only and never rescues an undershoot. + // n_chunks full per-lane chunks + 1 tail dim. const size_t d = vl * n_chunks + 1; std::vector trained; @@ -1224,13 +1005,8 @@ static void run_flush_case( dc.rvv_dc->set_query(q.data()); std::vector code(d, code_byte); - // Exact reference computed in the test (double: no drift at these - // magnitudes). Both kernels accumulate in f32, so the sequential / - // lane-reassociated sums drift by up to ~n*ulp(intermediate) — about - // 1e-2 relative at d ~ 5e5 (ulp ~4096 once the partial sum passes - // 2^35). That drift is still 100x tighter than a 2^31 integer - // wraparound (>= 100% error), which is the failure mode this test is - // a regression net for. + // f32 accumulation drifts by ~1e-2 relative at these d; an integer + // wraparound gives >= 100% error. const double expected_exact = per_dim * double(d); const float ref = dc.scalar_dc->query_to_code(code.data()); const float tst = dc.rvv_dc->query_to_code(code.data()); @@ -1299,50 +1075,8 @@ TEST(D5bLargeDim, DirectSignedIPParityPastWorstTermWrap) { -16256.0); } -TEST(D5bLargeDim, DirectSignedIPParityPastOldBiasOverflow) { - // An all-127 query makes the old integer bias 128*sum(q) cross 2^31 - // at d = 132105 (int32_t UB there). The float kernel must stay in - // parity: exact = d * 127 * (0 - 128) = -16256 * d. - if (!faiss::SIMDConfig::is_simd_level_available( - faiss::SIMDLevel::RISCV_RVV)) { - GTEST_SKIP() << "RISCV_RVV not available"; - } - const size_t d = 132105; - std::vector trained; - DcPair dc = make_dc_pair( - SQ::QT_8bit_direct_signed, - METRIC_INNER_PRODUCT, - d, - trained, - nullptr, - d); - ASSERT_TRUE(dc.scalar_dc && dc.rvv_dc); - - std::vector q(d, 127.0f); - dc.scalar_dc->set_query(q.data()); - dc.rvv_dc->set_query(q.data()); - std::vector code(d, 0x00); // value -128: qs*(c-128) = 127*128 - - const double expected_exact = -16256.0 * double(d); - const float ref = dc.scalar_dc->query_to_code(code.data()); - const float tst = dc.rvv_dc->query_to_code(code.data()); - // f32 accumulation drift bound: ~n*ulp(intermediate), ~2e-2 relative - // here (vs the >=100% error a 2^31 bias overflow would produce). - const double tol = std::fabs(expected_exact) * 2e-2; - EXPECT_NEAR(tst, expected_exact, tol) - << "signed-IP bias overflow at d=" << d << " rvv=" << tst; - EXPECT_NEAR(ref, tst, tol) << "signed-IP parity at d=" << d - << " rvv=" << tst << " scalar=" << ref; -} - -// =========================================================================== -// D10 — Direct codecs retain FLOAT-query semantics. The review's literal -// counterexample: d=1, q=0.75, codes {0, 1} — the scalar L2 -// distances are 0.5625 / 0.0625 so code 1 must win. An earlier -// integer-domain RVV kernel truncated the query to 0, flipping the -// ranking. Fractional queries must match the scalar NONE reference -// for all four direct codec x metric combinations. -// =========================================================================== +// D10: direct codecs must keep float-query semantics: a kernel that +// truncates q = 0.75 to 0 ranks code 0 above code 1. static void run_float_query_case( SQ::QuantizerType qtype, @@ -1357,9 +1091,7 @@ static void run_float_query_case( DcPair dc = make_dc_pair(qtype, metric, d, trained, nullptr, d); ASSERT_TRUE(dc.scalar_dc && dc.rvv_dc); - // ---- The review's literal counterexample ---- - // codes 0 and 1 (storage byte = value for direct; value + 128 for - // signed direct). q = 0.75 must sit strictly closer to code 1. + // codes 0 and 1 (storage byte = value + 128 for signed direct). { uint8_t bytes[2]; float r[2], t[2]; @@ -1452,171 +1184,7 @@ TEST(D10FloatQuery, DirectSignedIPFractionalParity) { "8bit_direct_signed_IP"); } -// =========================================================================== -// D6 — d == 0 must return 0 without hanging. Kernels guard vsetvl with -// `d > 0 ? d : 1` and the tail with `remaining > 0`, so d == 0 must -// terminate immediately. Each case runs in a forked child under -// alarm() so a hang only fails its own case (POSIX only). -// =========================================================================== - -struct ZeroDimParams { - SQ::QuantizerType qtype; - faiss::MetricType metric; - const char* name; -}; - -class SQRVVZeroDim : public ::testing::TestWithParam {}; - -#ifndef _WIN32 -TEST_P(SQRVVZeroDim, ReturnsZeroNoHang) { - const auto& p = GetParam(); - if (!faiss::SIMDConfig::is_simd_level_available( - faiss::SIMDLevel::RISCV_RVV)) { - GTEST_SKIP() << "RISCV_RVV not available"; - } - - // Minimal trained vector per codec family (d=0 loops never read it, - // but the uniform constructors index [0] and [1]). - std::vector trained; - if (class_of(p.qtype) == QClass::UniformApprox) { - trained = {0.0f, 1.0f}; - } - - const size_t d = 0; - - pid_t pid = fork(); - ASSERT_GE(pid, 0) << "fork failed"; - if (pid == 0) { - // child: run the kernel under a hard deadline; _exit a status code - alarm(20); - DcPair dc = [&] { - DcPair dp; - dp.scalar_dc.reset( - faiss::scalar_quantizer::sq_select_distance_computer< - faiss::SIMDLevel::NONE>( - p.metric, p.qtype, d, trained)); - { - ScopedSIMDLevel _(faiss::SIMDLevel::RISCV_RVV); - dp.rvv_dc.reset( - faiss::scalar_quantizer::sq_select_distance_computer< - faiss::SIMDLevel::RISCV_RVV>( - p.metric, p.qtype, d, trained)); - } - return dp; - }(); - if (!dc.scalar_dc || !dc.rvv_dc) - _exit(3); - float q_dummy = 0.0f; - dc.scalar_dc->set_query(&q_dummy); - dc.rvv_dc->set_query(&q_dummy); - uint8_t code_dummy = 0; - float ref = dc.scalar_dc->query_to_code(&code_dummy); - float tst = dc.rvv_dc->query_to_code(&code_dummy); - if (!std::isfinite(tst) || !std::isfinite(ref)) - _exit(4); - if (tst != 0.0f) - _exit(1); // must be exactly 0 for d=0 - if (std::abs(ref - tst) > 1e-6f) - _exit(2); // parity broken - _exit(0); - } - - int status = 0; - waitpid(pid, &status, 0); - if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) { - FAIL() << "qtype=" << int(p.qtype) << " " << metric_name(p.metric) - << ": d=0 kernel HUNG (vsetvl(0)==0 loop) — killed after 20s"; - } else if (WIFEXITED(status)) { - int rc = WEXITSTATUS(status); - switch (rc) { - case 0: - GTEST_SUCCEED(); - break; - case 1: - FAIL() << "d=0 RVV distance != 0 (qtype=" << int(p.qtype) << " " - << metric_name(p.metric) << ")"; - break; - case 2: - FAIL() << "d=0 RVV != scalar parity (qtype=" << int(p.qtype) - << " " << metric_name(p.metric) << ")"; - break; - case 3: - FAIL() << "distance computer is null (qtype=" << int(p.qtype) - << " " << metric_name(p.metric) << ")"; - break; - case 4: - FAIL() << "d=0 non-finite result (qtype=" << int(p.qtype) << " " - << metric_name(p.metric) << ")"; - break; - default: - FAIL() << "child exit " << rc; - } - } else { - FAIL() << "child abnormal exit"; - } -} -#endif // !_WIN32 - -#ifdef _WIN32 -TEST_P(SQRVVZeroDim, ReturnsZeroNoHang) { - GTEST_SKIP() << "fork-based hang isolation requires POSIX"; -} -#endif - -INSTANTIATE_TEST_SUITE_P( - D6, - SQRVVZeroDim, - ::testing::Values( - ZeroDimParams{SQ::QT_4bit, METRIC_L2, "4bit_L2"}, - ZeroDimParams{SQ::QT_4bit, METRIC_INNER_PRODUCT, "4bit_IP"}, - ZeroDimParams{ - SQ::QT_4bit_uniform, - METRIC_L2, - "4bit_uniform_L2"}, - ZeroDimParams{ - SQ::QT_4bit_uniform, - METRIC_INNER_PRODUCT, - "4bit_uniform_IP"}, - ZeroDimParams{SQ::QT_6bit, METRIC_L2, "6bit_L2"}, - ZeroDimParams{SQ::QT_6bit, METRIC_INNER_PRODUCT, "6bit_IP"}, - ZeroDimParams{SQ::QT_8bit, METRIC_L2, "8bit_L2"}, - ZeroDimParams{SQ::QT_8bit, METRIC_INNER_PRODUCT, "8bit_IP"}, - ZeroDimParams{ - SQ::QT_8bit_uniform, - METRIC_L2, - "8bit_uniform_L2"}, - ZeroDimParams{ - SQ::QT_8bit_uniform, - METRIC_INNER_PRODUCT, - "8bit_uniform_IP"}, - ZeroDimParams{SQ::QT_8bit_direct, METRIC_L2, "8bit_direct_L2"}, - ZeroDimParams{ - SQ::QT_8bit_direct, - METRIC_INNER_PRODUCT, - "8bit_direct_IP"}, - ZeroDimParams{ - SQ::QT_8bit_direct_signed, - METRIC_L2, - "8bit_direct_signed_L2"}, - ZeroDimParams{ - SQ::QT_8bit_direct_signed, - METRIC_INNER_PRODUCT, - "8bit_direct_signed_IP"}, - ZeroDimParams{SQ::QT_bf16, METRIC_L2, "bf16_L2"}, - ZeroDimParams{SQ::QT_bf16, METRIC_INNER_PRODUCT, "bf16_IP"}, - ZeroDimParams{SQ::QT_fp16, METRIC_L2, "fp16_L2"}, - ZeroDimParams{SQ::QT_fp16, METRIC_INNER_PRODUCT, "fp16_IP"}), - [](const ::testing::TestParamInfo& info) { - return std::string(info.param.name); - }); - -// =========================================================================== -// D7 — Special queries. -// FloatDomain + UniformApprox: exact float-domain kernels — clamp -// boundaries, far-out-of-range, and huge-but-finite magnitudes must -// stay in parity with the scalar reference (1e-4 rel). -// Direct: integer-grid in-contract queries — exact. -// =========================================================================== +// D7: clamp-boundary, far-out-of-range and huge-but-finite queries. struct SpecialQParams { SQ::QuantizerType qtype; @@ -1661,7 +1229,6 @@ TEST_P(SQRVVSpecialQueries, EdgeQueriesParity) { bool has_range = false; trained_range(p.qtype, p.d, sq.trained, vmin, vdiff, has_range); - // Query set per class std::vector> queries; queries.emplace_back(p.d, 0.0f); // all-zero if (direct) { @@ -1676,9 +1243,6 @@ TEST_P(SQRVVSpecialQueries, EdgeQueriesParity) { queries.push_back(std::move(q)); } } else if (qclass == QClass::UniformApprox) { - // Uniform codecs are now float-domain (exact affine), so any query - // stays in parity; in-range systematic values are a conservative - // subset that still exercises the affine reconstruction path. if (has_range) { queries.emplace_back(p.d, vmin); queries.emplace_back(p.d, vmin + vdiff); @@ -1691,7 +1255,6 @@ TEST_P(SQRVVSpecialQueries, EdgeQueriesParity) { } } } else { - // FloatDomain: exact kernels — full-range + far-out + huge finite queries.emplace_back(p.d, 1.0f); queries.emplace_back(p.d, -1.0f); queries.emplace_back(p.d, 1e4f); @@ -1705,9 +1268,6 @@ TEST_P(SQRVVSpecialQueries, EdgeQueriesParity) { } } - // Relative tolerance: 1e-4 for all float-domain / exact kernels - // (uniform L2/IP are now float-domain, same precision class as the - // non-uniform codecs). const float rel_tol = 1e-4f; for (size_t qi = 0; qi < queries.size(); qi++) { @@ -1728,10 +1288,7 @@ TEST_P(SQRVVSpecialQueries, EdgeQueriesParity) { } } -/* - * d=17 crosses VLMAX for the e8m1 kernels AND exercises tails, keeping - * runtime modest across all 9 qtypes x 2 metrics. - */ +// d=17 crosses VLMAX for the e8m1 kernels and leaves a tail. INSTANTIATE_TEST_SUITE_P( D7, SQRVVSpecialQueries, @@ -1820,13 +1377,8 @@ INSTANTIATE_TEST_SUITE_P( 1e-3f, "fp16_IP"})); -// =========================================================================== -// D8 — Very small / odd dimensions. The review asks for "odd and very small -// dimensions" in addition to VLMAX boundaries. d < 8 exercises the -// packing tail: 4-bit odd-d padding nibble, 6-bit ng==0 (d<4) pure -// scalar tail vs ng>=1 with a d%4 scalar tail, and the single-lane / -// tail-only vector path for every codec. -// =========================================================================== +// D8: d < 8 covers the packing tails: 4-bit odd-d padding nibble, 6-bit +// ng == 0 (d < 4) vs ng >= 1 with a d % 4 scalar tail, and tail-only vectors. struct SmallDimParams { SQ::QuantizerType qtype; @@ -1875,8 +1427,7 @@ TEST_P(SQRVVSmallDim, SmallDimensionParity) { ::testing::Message() << p.name << " d=" << p.d << " " << metric_name(p.metric)); - // All kernels are float-domain after the review fix -> reassociation - // precision only; direct codecs are additionally integer-exact here. + // f32 reassociation only; direct codecs are integer-exact here. const float tol = 1e-3f; for (size_t i = 0; i < n_db; i++) { @@ -1976,14 +1527,7 @@ INSTANTIATE_TEST_SUITE_P( return std::string(info.param.name); }); -// =========================================================================== -// D9 — q == recon(code). For every qtype under L2, decode a code back to its -// reconstructed vector and use that as the query; the L2 distance to -// that same code must be ~0 (the code reconstructs exactly to the -// query). This pins the general semantic baseline the review asks for -// ("queries equal to reconstructed code values"), beyond the uniform-L2 -// counterexample already covered by D1. -// =========================================================================== +// D9: with q = decode(code), the L2 distance to that code must be ~0. struct ReconParams { SQ::QuantizerType qtype; diff --git a/thirdparty/faiss/tests/test_standalone_codec.py b/thirdparty/faiss/tests/test_standalone_codec.py index 9a9df0dd4..bf9ad8ff3 100644 --- a/thirdparty/faiss/tests/test_standalone_codec.py +++ b/thirdparty/faiss/tests/test_standalone_codec.py @@ -3,9 +3,6 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -"""test byte codecs""" - -from __future__ import print_function import numpy as np import unittest import faiss @@ -26,8 +23,6 @@ def do_encode_twice(self, factory_key): xt, x, _ = get_dataset_2(d, nt, nb, nq) - assert x.size > 0 - codec = faiss.index_factory(d, factory_key) codec.train(xt) @@ -73,9 +68,6 @@ def test_SQtqmse4(self): def test_SQtqmse8(self): self.do_encode_twice("SQtqmse8") - def test_IVFSQ8(self): - self.do_encode_twice("IVF256,SQ8") - def test_PCAIVFSQ8(self): self.do_encode_twice("PCAR32,IVF256,SQ8") @@ -150,7 +142,6 @@ def test_IMI(self): class TestAccuracy(unittest.TestCase): - """comparative accuracy of a few types of indexes""" def compare_accuracy(self, lowac, highac, max_errs=(1e10, 1e10)): d = 96 @@ -165,7 +156,6 @@ def compare_accuracy(self, lowac, highac, max_errs=(1e10, 1e10)): for factory_string in lowac, highac: codec = faiss.index_factory(d, factory_string) - print("sa codec: code size %d" % codec.sa_code_size()) codec.train(xt) codes = codec.sa_encode(x) @@ -179,7 +169,6 @@ def compare_accuracy(self, lowac, highac, max_errs=(1e10, 1e10)): self.assertGreater(max_errs[0], errs[0]) self.assertGreater(max_errs[1], errs[1]) - # just a small IndexLattice I/O test if "Lattice" in highac: codec2 = faiss.deserialize_index(faiss.serialize_index(codec)) codes = codec2.sa_encode(x) @@ -204,9 +193,6 @@ def test_SQ3(self): def test_SQ4(self): self.compare_accuracy("SQ8", "SQbf16") - def test_SQtqmse(self): - self.compare_accuracy("SQtqmse4", "SQtqmse8") - def test_SQtqmse_ordering(self): d = 96 nb = 1000 @@ -230,7 +216,7 @@ def test_SQtqmse_ordering(self): errs.append(((x - x2) ** 2).sum()) for i in range(len(errs) - 1): - self.assertGreaterEqual(errs[i], errs[i + 1]) + self.assertGreater(errs[i], errs[i + 1]) def test_PQ(self): self.compare_accuracy("PQ6x8np", "PQ8x8np") @@ -259,7 +245,6 @@ def test_Lattice2(self): class LatticeTest(unittest.TestCase): - """Low-level lattice tests""" def test_repeats(self): rs = np.random.RandomState(123) @@ -300,8 +285,6 @@ def test_ZnSphereCodecRec(self): assert code == i def run_ZnSphereCodecAlt(self, dim, r2): - # dim = 32 - # r2 = 14 codec = faiss.ZnSphereCodecAlt(dim, r2) rs = np.random.RandomState(123) n = 100 @@ -336,7 +319,6 @@ def test_lattice_index(self): class TestBitstring(unittest.TestCase): def test_rw(self): - """Low-level bit string tests""" rs = np.random.RandomState(1234) nbyte = 1000 sz = 0 @@ -344,20 +326,15 @@ def test_rw(self): bs = np.ones(nbyte, dtype="uint8") bw = faiss.BitstringWriter(swig_ptr(bs), nbyte) - if False: - ctrl = [(7, 0x35), (13, 0x1D74)] - for nbit, x in ctrl: - bw.write(x, nbit) - else: - ctrl = [] - while True: - nbit = int(1 + 62 * rs.rand() ** 4) - if sz + nbit > nbyte * 8: - break - x = int(rs.randint(1 << nbit, dtype="int64")) - bw.write(x, nbit) - ctrl.append((nbit, x)) - sz += nbit + ctrl = [] + while True: + nbit = int(1 + 62 * rs.rand() ** 4) + if sz + nbit > nbyte * 8: + break + x = int(rs.randint(1 << nbit, dtype="int64")) + bw.write(x, nbit) + ctrl.append((nbit, x)) + sz += nbit bignum = 0 sz = 0 @@ -426,7 +403,6 @@ def test_idmap(self): index.reset() - index.train(ds.get_train()) codes = index.index.sa_encode(ds.get_database()) index.add_sa_codes(codes, ids) Dnew, Inew = index.search(ds.get_queries(), 10) @@ -459,7 +435,7 @@ def _check_idmap_ivf(self, factory, with_reconstruct): np.testing.assert_array_equal(Dref, Dnew) if with_reconstruct: - # reconstruct should work too (rev_map is updated) — IDMap2 only + # needs IDMap2::rev_map faiss.extract_index_ivf(test).make_direct_map() for key in ids[:5]: recons = test.reconstruct(int(key)) @@ -510,14 +486,7 @@ def test_refine_sa_decode(self): np.testing.assert_allclose(x_decoded, x_decoded_ref) def test_equiv_rcq_rq(self): - """make sure that the codes generated by the standalone codec are - the same - between an - IndexRefine with ResidualQuantizer - and - IVF with ResidualCoarseQuantizer - both are the centroid id concatenated with the code. - """ + """RQ+Refine(Flat) and IVF(RCQ),Flat produce identical sa codes.""" ds = SyntheticDataset(16, 400, 100, 0) index1 = faiss.index_factory(ds.d, "RQ2x3,Refine(Flat)") index1.train(ds.get_train()) diff --git a/thirdparty/faiss/tests/test_super_kmeans.py b/thirdparty/faiss/tests/test_super_kmeans.py index d5f59f5ab..9976ff24c 100644 --- a/thirdparty/faiss/tests/test_super_kmeans.py +++ b/thirdparty/faiss/tests/test_super_kmeans.py @@ -17,6 +17,34 @@ def test_train_rejects_too_few_points(self): with self.assertRaises(RuntimeError): sc.train(x) + def test_train_float16_matches_rounded_float32(self): + d, k, n = 32, 4, 96 + rows = np.arange(n, dtype="float32")[:, None] + dims = np.arange(d, dtype="float32")[None, :] + values = (rows % k) * 8.0 + ((rows * 17 + dims * 13) % 31) / 100.0 + x16 = values.astype("float16") + rounded = x16.astype("float32") + + p = faiss.SuperKMeansParameters() + p.seed = 1234 + p.niter = 3 + p.min_points_per_centroid = 1 + p.decode_block_size = n + + expected = faiss.SuperKMeans(d, k, p) + expected.train(rounded) + actual = faiss.SuperKMeans(d, k, p) + actual.train(x16, numeric_type=faiss.Float16) + + np.testing.assert_array_equal( + faiss.vector_to_array(actual.centroids), + faiss.vector_to_array(expected.centroids), + ) + np.testing.assert_array_equal( + faiss.vector_to_array(actual.gemm_pruning_rates), + faiss.vector_to_array(expected.gemm_pruning_rates), + ) + def test_objective_decreases_monotonically(self): d, k, n = 32, 8, 1000 x = SyntheticDataset(d, n, 0, 0).get_train() @@ -32,27 +60,6 @@ def test_objective_decreases_monotonically(self): for i in range(1, len(objs)): self.assertLessEqual(objs[i], objs[i - 1] * 1.001) - def test_pruned_iter_assignments_close_to_vanilla(self): - d, k, n = 64, 16, 2000 - x = SyntheticDataset(d, n, 0, 0).get_train() - - p = faiss.SuperKMeansParameters() - p.seed = 42 - p.niter = 10 - sc = faiss.SuperKMeans(d, k, p) - sc.train(x) - - quant = faiss.IndexFlatL2(d) - vanilla = faiss.Clustering(d, k) - vanilla.seed = 42 - vanilla.niter = 10 - vanilla.train(x, quant) - - sc_final = sc.iteration_stats.at(sc.iteration_stats.size() - 1).obj - v_stats = vanilla.iteration_stats - v_final = v_stats.at(v_stats.size() - 1).obj - self.assertLess(abs(sc_final - v_final) / v_final, 0.05) - def test_spherical_objective_close_to_vanilla_spherical(self): # With cp.spherical=true, SuperKMeans unit-normalizes centroids so the # L2 assignment it computes is equivalent to inner-product assignment. @@ -79,29 +86,10 @@ def test_spherical_objective_close_to_vanilla_spherical(self): v_final = v_stats.at(v_stats.size() - 1).obj self.assertLess(abs(sc_final - v_final) / v_final, 0.05) - def test_spherical_produces_unit_centroids(self): - d, k, n = 64, 16, 2000 - x = SyntheticDataset(d, n, 0, 0).get_train() - - p = faiss.SuperKMeansParameters() - p.seed = 42 - p.niter = 10 - p.spherical = True - sc = faiss.SuperKMeans(d, k, p) - sc.train(x) - centroids = faiss.vector_to_array(sc.centroids).reshape(k, d) norms = np.linalg.norm(centroids, axis=1) np.testing.assert_allclose(norms, 1.0, atol=1e-4) - def test_use_super_kmeans_field_is_inherited(self): - # use_super_kmeans lives on ClusteringParameters and is inherited by - # SuperKMeansParameters; it must be settable from Python. - p = faiss.SuperKMeansParameters() - self.assertFalse(p.use_super_kmeans) - p.use_super_kmeans = True - self.assertTrue(p.use_super_kmeans) - def test_pruning_rate_in_expected_range(self): # The 10-d intrinsic manifold of SyntheticDataset gives ADSampling # the assigned-vs-other distance gap it needs to prune effectively. @@ -115,20 +103,17 @@ def test_pruning_rate_in_expected_range(self): sc.train(x) rates = faiss.vector_to_array(sc.gemm_pruning_rates) - self.assertEqual(rates.shape, (5,)) self.assertEqual(rates[0], 0.0) # iter 0: no pruning - # Lower bound 0.30: looser than the 0.93 design target because - # synthetic d=64 data lacks the cluster gap real embeddings have at - # d=768; the assertion still confirms meaningful pruning occurs. + # 0.30, not the 0.93 target: synthetic d=64 data has a smaller + # cluster gap than real embeddings. for i in range(2, 5): self.assertGreaterEqual(rates[i], 0.30) def test_pdx_offset_correct_for_unaligned_y_batch(self): - # PDX block layout is sized for the full k centroids, not per y-batch - # tile. The y-batch tile boundary must be invisible to PDX-offset - # arithmetic. k=70 with y_batch=32 forces a 6-wide tail tile; assert - # the resulting centroids are identical to running with y_batch=70 - # (single tile, no tail). + # k=70, y_batch=32 leaves a 6-wide tail tile; centroids must match + # the single-tile run. Bit-exact reproducibility requires + # MKL_CBWR=COMPATIBLE and a fixed OMP thread count. The BUCK target + # sets these in `env`; for OSS ctest the user must export them. d, k, n = 64, 70, 5000 x = SyntheticDataset(d, n, 0, 0).get_train() @@ -145,31 +130,6 @@ def train_with_y_batch(y_batch): single = train_with_y_batch(k) # k % y_batch = 0 np.testing.assert_array_equal(tiled, single) - def test_determinism(self): - # Bit-exact reproducibility requires MKL_CBWR=COMPATIBLE and a fixed - # OMP thread count. The BUCK target sets these in `env`; for OSS - # ctest the user must export them before running. - d, k, n = 128, 64, 5000 - x = SyntheticDataset(d, n, 0, 0).get_train() - - p = faiss.SuperKMeansParameters() - p.niter = 5 - p.seed = 1234 - - sc1 = faiss.SuperKMeans(d, k, p) - sc1.train(x) - sc2 = faiss.SuperKMeans(d, k, p) - sc2.train(x) - - np.testing.assert_array_equal( - faiss.vector_to_array(sc1.centroids), - faiss.vector_to_array(sc2.centroids), - ) - np.testing.assert_array_equal( - faiss.vector_to_array(sc1.gemm_pruning_rates), - faiss.vector_to_array(sc2.gemm_pruning_rates), - ) - def test_rejects_nan_input(self): # check_input_data_for_NaNs defaults to True. sc = faiss.SuperKMeans(128, 64) @@ -212,7 +172,6 @@ def test_train_populates_kmeans_surface(self): km = faiss.SuperKmeans(d, k, niter=5, seed=42) final_obj = km.train(x) - self.assertEqual(km.centroids.shape, (k, d)) self.assertEqual(km.obj.shape, (5,)) self.assertEqual(len(km.iteration_stats), 5) self.assertEqual(final_obj, km.obj[-1]) @@ -249,27 +208,9 @@ def test_smoke(self): [coeff.at(i) for i in range(coeff.size())], dtype="float32" ) cp = faiss.SuperKMeansParameters() - total, pruned = faiss.super_kmeans_assign_iteration( - X, Y, tau, A, dp, coeff_np, cp - ) - self.assertGreater(total, 0) - self.assertTrue((A >= 0).all()) - self.assertTrue((A < k).all()) - def test_rejects_bad_input(self): # The wrapper must reject wrong dtypes and mismatched shapes at the # Python boundary rather than passing a bad pointer to C++. - n, d, k, dp = 50, 32, 8, 8 - X = np.random.RandomState(0).randn(n, d).astype("float32") - Y = np.random.RandomState(1).randn(k, d).astype("float32") - tau = np.full(n, 1e30, dtype="float32") - A = np.zeros(n, dtype="int32") - coeff = faiss.precompute_ad_thresholds(d, 1.0 / d) - coeff_np = np.array( - [coeff.at(i) for i in range(coeff.size())], dtype="float32" - ) - cp = faiss.SuperKMeansParameters() - # int64 assignments (numpy's default int) must be rejected, not # reinterpreted as int32. with self.assertRaises(TypeError): @@ -286,3 +227,9 @@ def test_rejects_bad_input(self): faiss.super_kmeans_assign_iteration( X, Y, tau, A, dp, coeff_np[:d], cp ) + total, _ = faiss.super_kmeans_assign_iteration( + X, Y, tau, A, dp, coeff_np, cp + ) + self.assertGreater(total, 0) + self.assertTrue((A >= 0).all()) + self.assertTrue((A < k).all()) diff --git a/thirdparty/faiss/tests/test_super_kmeans_foundations.cpp b/thirdparty/faiss/tests/test_super_kmeans_foundations.cpp index 62cf1192a..9b4201214 100644 --- a/thirdparty/faiss/tests/test_super_kmeans_foundations.cpp +++ b/thirdparty/faiss/tests/test_super_kmeans_foundations.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -27,15 +28,9 @@ // AdSampling tests // ===================================================================== -// Reference values from scipy.stats.norm.ppf, cited so a reader can -// reproduce. Covers all three branches: lower tail (p < 0.02425), central -// region, and upper tail. +// Reference values from scipy.stats.norm.ppf; cover the lower-tail (p < +// 0.02425), central and upper-tail branches. TEST(AdSampling, NormalQuantile_KnownValues) { - // scipy.stats.norm.ppf(0.001) == -3.0902323061678135 - // scipy.stats.norm.ppf(0.025) == -1.959963984540054 - // scipy.stats.norm.ppf(0.5) == 0.0 - // scipy.stats.norm.ppf(0.975) == 1.959963984540054 - // scipy.stats.norm.ppf(0.999) == 3.090232306167813 EXPECT_NEAR( faiss::detail::normal_quantile(0.001), -3.0902323061678135, 1e-6); EXPECT_NEAR( @@ -160,13 +155,7 @@ TEST(BlockL2, ScalarMatchesReference) { y[m] = static_cast(m + 1); } - EXPECT_NEAR( - faiss::detail::block_l2( - x.data(), y.data(), N), - static_cast(N), - 1e-4f); - - for (int n = 1; n < N; ++n) { + for (int n = 1; n <= N; ++n) { const float ref = static_cast(n); EXPECT_NEAR( faiss::detail::block_l2( @@ -187,13 +176,7 @@ TEST(BlockL2, DispatchMatchesScalar) { y[m] = dist(rng); } - const float scalar = faiss::detail::block_l2( - x.data(), y.data(), N); - const float dispatched = - faiss::detail::block_l2_dispatch(x.data(), y.data(), N); - EXPECT_NEAR(dispatched, scalar, 1e-4f); - - for (int n = 1; n < N; ++n) { + for (int n = 1; n <= N; ++n) { const float s = faiss::detail::block_l2( x.data(), y.data(), n); const float d = faiss::detail::block_l2_dispatch(x.data(), y.data(), n); @@ -219,7 +202,7 @@ TEST(SuperKMeansAssignIteration, GemmBoundaryPrunesAllWithTightTau) { A[i] = static_cast(i % k); } std::vector A_in = A; - std::vector T(n, 1e-30f); // tight tau forces GEMM-boundary prune + std::vector T(n, 1e-30f); auto coeff = faiss::detail::precompute_ad_thresholds(d, 1.0 / d); faiss::SuperKMeansParameters cp; int64_t tot = 0, pr = 0; @@ -239,8 +222,8 @@ TEST(SuperKMeansAssignIteration, GemmBoundaryPrunesAllWithTightTau) { &pr); EXPECT_GT(tot, 0); - EXPECT_EQ(tot, pr); // tight tau -> everything prunes at GEMM - EXPECT_EQ(A, A_in); // no survivor refinement -> assignments unchanged + EXPECT_EQ(tot, pr); + EXPECT_EQ(A, A_in); } TEST(SuperKMeansAssignIteration, ProgressivePruningRefinesSurvivors) { @@ -294,49 +277,7 @@ TEST(SuperKMeansAssignIteration, ProgressivePruningRefinesSurvivors) { ++matches; } } - EXPECT_GE(matches, n - 5); // <= 5% ADSampling false-prune tolerance -} - -TEST(SuperKMeansAssignIteration, Determinism) { - constexpr int n = 200, d = 64, k = 32, d_prime = 8; - std::vector X(n * d), Y(k * d); - faiss::float_rand(X.data(), X.size(), 7); - faiss::float_rand(Y.data(), Y.size(), 11); - auto coeff = faiss::detail::precompute_ad_thresholds(d, 1.0 / d); - faiss::SuperKMeansParameters cp; - - auto run = [&](std::vector& A, - std::vector& T, - int64_t& tot, - int64_t& pr) { - for (int i = 0; i < n; ++i) { - A[i] = 0; - T[i] = 1e30f; - } - faiss::super_kmeans_assign_iteration( - X.data(), - n, - d, - Y.data(), - k, - T.data(), - A.data(), - d_prime, - coeff.data(), - cp, - &tot, - &pr); - }; - - std::vector A1(n), A2(n); - std::vector T1(n), T2(n); - int64_t tot1 = 0, pr1 = 0, tot2 = 0, pr2 = 0; - run(A1, T1, tot1, pr1); - run(A2, T2, tot2, pr2); - EXPECT_EQ(A1, A2); - EXPECT_EQ(0, std::memcmp(T1.data(), T2.data(), n * sizeof(float))); - EXPECT_EQ(tot1, tot2); - EXPECT_EQ(pr1, pr2); + EXPECT_GE(matches, n - 5); // ADSampling false-prune tolerance } TEST(SuperKMeansAssignIteration, MaxDPrimeMatchesBruteForce) { @@ -495,3 +436,145 @@ TEST(SuperKMeansAssignIteration, MultipleTilesMatchBruteForce) { } EXPECT_GE(matches, n - 10); // <= 5% ADSampling false-prune tolerance } + +namespace { + +std::vector encode_fp16_values(const std::vector& values) { + std::vector encoded(values.size()); + for (size_t i = 0; i < values.size(); ++i) { + encoded[i] = faiss::encode_fp16(values[i]); + } + return encoded; +} + +std::vector decode_fp16_values(const std::vector& values) { + std::vector decoded(values.size()); + for (size_t i = 0; i < values.size(); ++i) { + decoded[i] = faiss::decode_fp16(values[i]); + } + return decoded; +} + +std::vector make_super_kmeans_training_data(int n, int d) { + std::vector x(static_cast(n) * d); + for (int i = 0; i < n; ++i) { + const float center = static_cast(i % 4) * 8.0f; + for (int j = 0; j < d; ++j) { + x[static_cast(i) * d + j] = center + + static_cast((i * 17 + j * 13) % 31) / 100.0f; + } + } + return x; +} + +void expect_same_super_kmeans_result( + const faiss::SuperKMeans& actual, + const faiss::SuperKMeans& expected) { + EXPECT_EQ(actual.centroids, expected.centroids); + ASSERT_EQ(actual.iteration_stats.size(), expected.iteration_stats.size()); + for (size_t i = 0; i < actual.iteration_stats.size(); ++i) { + EXPECT_EQ( + actual.iteration_stats[i].obj, expected.iteration_stats[i].obj); + EXPECT_EQ( + actual.iteration_stats[i].nsplit, + expected.iteration_stats[i].nsplit); + } + EXPECT_EQ(actual.gemm_pruning_rates, expected.gemm_pruning_rates); +} + +faiss::SuperKMeansParameters small_super_kmeans_params() { + faiss::SuperKMeansParameters cp; + cp.seed = 1234; + cp.niter = 3; + cp.min_points_per_centroid = 1; + return cp; +} + +} // namespace + +TEST(SuperKMeans, TrainExFloat16SubsamplingMatchesRoundedFloat32) { + constexpr int n = 129, d = 32, k = 4; + auto encoded = encode_fp16_values(make_super_kmeans_training_data(n, d)); + auto rounded = decode_fp16_values(encoded); + auto cp = small_super_kmeans_params(); + cp.max_points_per_centroid = 16; + cp.decode_block_size = n; + + faiss::SuperKMeans expected(d, k, cp); + expected.train(n, rounded.data()); + faiss::SuperKMeans actual(d, k, cp); + actual.train_ex(n, encoded.data(), faiss::NumericType::Float16); + + expect_same_super_kmeans_result(actual, expected); +} + +TEST(SuperKMeans, TrainExFloat16MultiBlockMatchesRoundedFloat32) { + constexpr int n = 129, d = 32, k = 4; + auto encoded = encode_fp16_values(make_super_kmeans_training_data(n, d)); + auto rounded = decode_fp16_values(encoded); + auto cp = small_super_kmeans_params(); + cp.decode_block_size = 64; + + faiss::SuperKMeans expected(d, k, cp); + expected.train(n, rounded.data()); + faiss::SuperKMeans actual(d, k, cp); + actual.train_ex(n, encoded.data(), faiss::NumericType::Float16); + + ASSERT_EQ(actual.centroids.size(), expected.centroids.size()); + for (size_t i = 0; i < actual.centroids.size(); ++i) { + EXPECT_NEAR(actual.centroids[i], expected.centroids[i], 1e-4f); + } + ASSERT_EQ(actual.iteration_stats.size(), expected.iteration_stats.size()); + for (size_t i = 0; i < actual.iteration_stats.size(); ++i) { + EXPECT_NEAR( + actual.iteration_stats[i].obj, + expected.iteration_stats[i].obj, + 1e-3f); + EXPECT_EQ( + actual.iteration_stats[i].nsplit, + expected.iteration_stats[i].nsplit); + } + + cp.spherical = true; + faiss::SuperKMeans spherical_expected(d, k, cp); + spherical_expected.train(n, rounded.data()); + faiss::SuperKMeans spherical_actual(d, k, cp); + spherical_actual.train_ex(n, encoded.data(), faiss::NumericType::Float16); + expect_same_super_kmeans_result(spherical_actual, spherical_expected); + for (int i = 0; i < k; ++i) { + EXPECT_NEAR( + faiss::fvec_norm_L2sqr( + spherical_actual.centroids.data() + i * d, d), + 1.0f, + 1e-5f); + } +} + +TEST(SuperKMeans, TrainExFloat16ValidatesInput) { + constexpr int n = 8, d = 32, k = 2; + auto encoded = encode_fp16_values(make_super_kmeans_training_data(n, d)); + auto cp = small_super_kmeans_params(); + cp.niter = 1; + + for (uint16_t bad : + {uint16_t(0x7e00), uint16_t(0x7c00), uint16_t(0xfc00)}) { + auto invalid = encoded; + invalid.back() = bad; + faiss::SuperKMeans clustering(d, k, cp); + EXPECT_THROW( + clustering.train_ex( + n, invalid.data(), faiss::NumericType::Float16), + faiss::FaissException); + } + + cp.decode_block_size = 0; + faiss::SuperKMeans zero_block(d, k, cp); + EXPECT_THROW( + zero_block.train_ex(n, encoded.data(), faiss::NumericType::Float16), + faiss::FaissException); + + faiss::SuperKMeans unsupported(d, k, small_super_kmeans_params()); + EXPECT_THROW( + unsupported.train_ex(n, encoded.data(), faiss::NumericType::UInt8), + faiss::FaissException); +} diff --git a/thirdparty/faiss/tests/test_svs.cpp b/thirdparty/faiss/tests/test_svs.cpp index 816298ef9..5d83a03c4 100644 --- a/thirdparty/faiss/tests/test_svs.cpp +++ b/thirdparty/faiss/tests/test_svs.cpp @@ -42,11 +42,9 @@ namespace { pthread_mutex_t temp_file_mutex = PTHREAD_MUTEX_INITIALIZER; -// Test fixture class to manage shared test data class SVS : public ::testing::Test { protected: static void SetUpTestSuite() { - // Generate test data once for all tests constexpr size_t d = 64; constexpr size_t n = 100; test_data.resize(d * n); @@ -63,7 +61,6 @@ class SVS : public ::testing::Test { static constexpr size_t n = 100; }; -// LVQ/LeanVec tests are only executed if LVQ/LeanVec support is available class SVSLL : public SVS { protected: void SetUp() override { @@ -74,8 +71,6 @@ class SVSLL : public SVS { } }; -// Consistency checks for behavior if LVQ/LeanVec are not available -// Only runs if LVQ/LeanVec is NOT available class SVSNoLL : public SVS { protected: void SetUp() override { @@ -86,7 +81,6 @@ class SVSNoLL : public SVS { } }; -// Define static members std::vector SVS::test_data; } // namespace @@ -98,16 +92,13 @@ void write_and_read_index(T& index, const std::vector& xb, size_t n) { std::string temp_filename_template = "/tmp/faiss_svs_test_XXXXXX"; Tempfilename filename(&temp_file_mutex, temp_filename_template); - // Serialize ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - // Deserialize T* loaded = nullptr; ASSERT_NO_THROW({ loaded = dynamic_cast(faiss::read_index(filename.c_str())); }); - // Basic checks ASSERT_NE(loaded, nullptr); ASSERT_NE(loaded->impl, nullptr); EXPECT_EQ(loaded->d, index.d); @@ -120,16 +111,8 @@ void write_and_read_index(T& index, const std::vector& xb, size_t n) { EXPECT_EQ(loaded->max_candidate_pool_size, index.max_candidate_pool_size); EXPECT_EQ(loaded->prune_to, index.prune_to); EXPECT_EQ(loaded->use_full_search_history, index.use_full_search_history); - if constexpr (std::is_same_v< - std::decay_t, - faiss::IndexSVSVamanaLeanVec>) { - auto* leanvec_loaded = - dynamic_cast(loaded); - ASSERT_NE(leanvec_loaded, nullptr); - EXPECT_EQ(leanvec_loaded->leanvec_d, index.leanvec_d); - - EXPECT_NE(leanvec_loaded->training_data, nullptr); - } + EXPECT_EQ(loaded->leanvec_d, index.leanvec_d); + EXPECT_NE(loaded->training_data, nullptr); delete loaded; } @@ -172,41 +155,6 @@ void save_and_load_index() { delete loaded; } -TEST_F(SVS, WriteAndReadIndexSVS) { - faiss::IndexSVSVamana index{d, 64ul}; - write_and_read_index(index, test_data, n); -} - -TEST_F(SVS, WriteAndReadIndexSVSFP16) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16}; - write_and_read_index(index, test_data, n); -} - -TEST_F(SVS, WriteAndReadIndexSVSSQ8) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_SQ8}; - write_and_read_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSLVQ4x0) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x0; - write_and_read_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSLVQ4x4) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x4; - write_and_read_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSLVQ4x8) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x8; - write_and_read_index(index, test_data, n); -} - TEST_F(SVSLL, WriteAndReadIndexSVSVamanaLeanVec4x4) { faiss::IndexSVSVamanaLeanVec index{ d, @@ -252,36 +200,6 @@ TEST_F(SVS, VamanaTrainSaveLoadAndAdd) { train_save_load_and_add_index(index, test_data, n); } -TEST_F(SVS, VamanaFP16TrainSaveLoadAndAdd) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16}; - train_save_load_and_add_index(index, test_data, n); -} - -TEST_F(SVS, VamanaSQ8TrainSaveLoadAndAdd) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_SQ8}; - train_save_load_and_add_index(index, test_data, n); -} - -TEST_F(SVSLL, LVQ4x0TrainSaveLoadAndAdd) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x0; - train_save_load_and_add_index(index, test_data, n); -} - -TEST_F(SVSLL, LVQ4x4TrainSaveLoadAndAdd) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x4; - train_save_load_and_add_index(index, test_data, n); -} - -TEST_F(SVSLL, LVQ4x8TrainSaveLoadAndAdd) { - faiss::IndexSVSVamanaLVQ index{d, 64ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x8; - train_save_load_and_add_index(index, test_data, n); -} - TEST_F(SVSLL, LeanVec4x4TrainSaveLoadAndAdd) { faiss::IndexSVSVamanaLeanVec index{ d, @@ -292,128 +210,36 @@ TEST_F(SVSLL, LeanVec4x4TrainSaveLoadAndAdd) { train_save_load_and_add_index(index, test_data, n); } -TEST_F(SVSLL, LeanVec4x8TrainSaveLoadAndAdd) { - faiss::IndexSVSVamanaLeanVec index{ - d, - 64ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec4x8}; - train_save_load_and_add_index(index, test_data, n); -} - -TEST_F(SVSLL, LeanVec8x8TrainSaveLoadAndAdd) { - faiss::IndexSVSVamanaLeanVec index{ - d, - 64ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec8x8}; - train_save_load_and_add_index(index, test_data, n); -} - TEST_F(SVS, SaveAndLoadIndexSVSFlat) { save_and_load_index(); } -TEST_F(SVS, SaveAndLoadIndexSVSVamana) { - save_and_load_index(); -} - -TEST_F(SVSLL, SaveAndLoadIndexSVSVamanaLVQ) { - save_and_load_index(); -} - TEST_F(SVSLL, SaveAndLoadIndexSVSVamanaLeanVec) { save_and_load_index(); } -TEST_F(SVS, WriteAndReadIndexSVSFlat) { - faiss::IndexSVSFlat index{d}; - index.add(n, test_data.data()); - - std::string temp_filename_template = "/tmp/faiss_svs_test_XXXXXX"; - Tempfilename filename(&temp_file_mutex, temp_filename_template); - - // Serialize - ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - - // Deserialize - faiss::IndexSVSFlat* loaded = nullptr; - ASSERT_NO_THROW({ - loaded = dynamic_cast( - faiss::read_index(filename.c_str())); - }); - - ASSERT_NE(loaded, nullptr); - ASSERT_NE(loaded->impl, nullptr); - EXPECT_EQ(loaded->d, index.d); - EXPECT_EQ(loaded->nlabels, index.nlabels); - EXPECT_EQ(loaded->metric_type, index.metric_type); - - delete loaded; -} - -// Test search with IDSelector filtering -TEST_F(SVS, SearchWithIDSelector) { - faiss::IndexSVSVamana index{d, 64ul}; - index.add(n, test_data.data()); - - const int nq = 8; // number of queries - const float* xq = test_data.data(); // reuse first nq vectors as queries - const int k = 10; - - size_t min_id = n / 5; // inclusive - size_t max_id = n * 4 / 5; // exclusive - faiss::IDSelectorRange selector(min_id, max_id); - - faiss::SearchParameters params; // generic search parameters with selector - params.sel = &selector; - - std::vector distances(nq * k); - std::vector labels(nq * k); - - ASSERT_NO_THROW( - index.search(nq, xq, k, distances.data(), labels.data(), ¶ms)); - - // All returned labels must fall inside the selected range - for (int i = 0; i < nq * k; ++i) { - EXPECT_GE(labels[i], (faiss::idx_t)min_id); - EXPECT_LT(labels[i], (faiss::idx_t)max_id); - } -} - -// Basic functional test for range_search and parameter override helper TEST_F(SVS, RangeSearchFunctional) { faiss::IndexSVSVamana index{d, 64ul}; index.add(n, test_data.data()); const int nq = 5; const float* xq = test_data.data(); - // Small radius - faiss::RangeSearchResult res_small(nq); - ASSERT_NO_THROW(index.range_search(nq, xq, 0.05f, &res_small)); - - // Larger radius to exercise loop continuation - faiss::RangeSearchResult res_big(nq); - ASSERT_NO_THROW(index.range_search(nq, xq, 5.0f, &res_big)); - EXPECT_GE(res_big.lims[nq], res_small.lims[nq]); - - // Provide custom params to ensure branch coverage (non-null params) + // SearchParametersSVSVamana override and selector branches faiss::SearchParametersSVSVamana params; params.search_window_size = 15; params.search_buffer_capacity = 20; - // Provide IDSelector to ensure branch coverage (non-null params->sel) size_t min_id = n / 5; // inclusive size_t max_id = n * 4 / 5; // exclusive faiss::IDSelectorRange selector(min_id, max_id); params.sel = &selector; + // The radius covers nearly every vector, so the batch iterator loop + // continues past its first batch. faiss::RangeSearchResult res_params(nq); - ASSERT_NO_THROW(index.range_search(nq, xq, 1.0f, &res_params, ¶ms)); + ASSERT_NO_THROW(index.range_search(nq, xq, 20.0f, &res_params, ¶ms)); + ASSERT_GT(res_params.lims[nq], 0); - // All returned labels must fall inside the selected range for (size_t i = 0; i < res_params.lims[nq]; ++i) { EXPECT_GE(res_params.labels[i], (faiss::idx_t)min_id); EXPECT_LT(res_params.labels[i], (faiss::idx_t)max_id); @@ -421,28 +247,13 @@ TEST_F(SVS, RangeSearchFunctional) { } TEST_F(SVSLL, LVQAndLeanVecDoNotThrowWhenEnabled) { - // explicit constructor with LVQ dataset - ASSERT_NO_THROW({ - faiss::IndexSVSVamanaLVQ index( - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_LVQ4x4); - }); - // default constructor, will initialize dataset on first add() ASSERT_NO_THROW({ faiss::IndexSVSVamanaLVQ index; + index.d = d; index.add(n, test_data.data()); }); - // explicit constructor with LeanVec dataset - ASSERT_NO_THROW({ - faiss::IndexSVSVamanaLeanVec index( - d, - 64ul, - faiss::METRIC_L2, - faiss::SVSStorageKind::SVS_LeanVec4x4); - }); - - // default constructor, will initialize dataset on first add() ASSERT_NO_THROW({ faiss::IndexSVSVamanaLeanVec index; index.d = 64; @@ -453,7 +264,6 @@ TEST_F(SVSLL, LVQAndLeanVecDoNotThrowWhenEnabled) { } TEST_F(SVSNoLL, LVQAndLeanVecThrowWhenNotEnabled) { - // explicit constructor with LVQ dataset ASSERT_THROW( { faiss::IndexSVSVamanaLVQ index( @@ -472,7 +282,6 @@ TEST_F(SVSNoLL, LVQAndLeanVecThrowWhenNotEnabled) { }, faiss::FaissException); - // explicit constructor with LeanVec dataset ASSERT_THROW( { faiss::IndexSVSVamanaLeanVec index( @@ -483,7 +292,6 @@ TEST_F(SVSNoLL, LVQAndLeanVecThrowWhenNotEnabled) { }, faiss::FaissException); - // default constructor, will initialize dataset on first add() ASSERT_THROW( { faiss::IndexSVSVamanaLeanVec index; @@ -504,20 +312,18 @@ void write_and_read_ivf_index( const std::vector& xb, size_t n) { index.train(n, xb.data()); + index.add(n, xb.data()); std::string temp_filename_template = "/tmp/faiss_svs_ivf_test_XXXXXX"; Tempfilename filename(&temp_file_mutex, temp_filename_template); - // Serialize ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - // Deserialize T* loaded = nullptr; ASSERT_NO_THROW({ loaded = dynamic_cast(faiss::read_index(filename.c_str())); }); - // Basic checks ASSERT_NE(loaded, nullptr); ASSERT_NE(loaded->impl, nullptr); EXPECT_EQ(loaded->d, index.d); @@ -539,61 +345,12 @@ void write_and_read_ivf_index( delete loaded; } -template -void train_and_add_ivf_index(T& index, const std::vector& xb, size_t n) { - index.train(n, xb.data()); - - // Additional data to add after training - ASSERT_NO_THROW({ index.add(n, xb.data()); }); -} - -TEST_F(SVS, WriteAndReadIndexSVSIVF) { - faiss::IndexSVSIVF index{d, 4ul}; - write_and_read_ivf_index(index, test_data, n); -} - -TEST_F(SVS, WriteAndReadIndexSVSIVFFP16) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16}; - write_and_read_ivf_index(index, test_data, n); -} - -TEST_F(SVS, WriteAndReadIndexSVSIVFSQ8) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_SQ8}; - write_and_read_ivf_index(index, test_data, n); -} - TEST_F(SVSLL, WriteAndReadIndexSVSIVFLVQ4x0) { faiss::IndexSVSIVFLVQ index{d, 4ul}; index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x0; write_and_read_ivf_index(index, test_data, n); } -TEST_F(SVSLL, WriteAndReadIndexSVSIVFLVQ4x4) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x4; - write_and_read_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSIVFLVQ4x8) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x8; - write_and_read_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSIVFLVQ8x0) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ8x0; - write_and_read_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadIndexSVSIVFLeanVec4x4) { - faiss::IndexSVSIVFLeanVec index{ - d, 4ul, faiss::METRIC_L2, 0, faiss::SVSStorageKind::SVS_LeanVec4x4}; - write_and_read_ivf_index(index, test_data, n); -} - TEST_F(SVSLL, WriteAndReadIndexSVSIVFLeanVec4x8) { faiss::IndexSVSIVFLeanVec index{ d, 4ul, faiss::METRIC_L2, 0, faiss::SVSStorageKind::SVS_LeanVec4x8}; @@ -645,116 +402,10 @@ TEST_F(SVS, IVFHonorsDeserializationVectorByteLimit) { expect_byte_limit_enforced(index, test_data, n); } -TEST_F(SVS, IVFTrainAndAdd) { - faiss::IndexSVSIVF index{d, 4ul}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVS, IVFFP16TrainAndAdd) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVS, IVFSQ8TrainAndAdd) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_SQ8}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLVQ4x0TrainAndAdd) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x0; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLVQ4x4TrainAndAdd) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x4; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLVQ4x8TrainAndAdd) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ4x8; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLVQ8x0TrainAndAdd) { - faiss::IndexSVSIVFLVQ index{d, 4ul}; - index.storage_kind = faiss::SVSStorageKind::SVS_LVQ8x0; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLeanVec4x4TrainAndAdd) { - faiss::IndexSVSIVFLeanVec index{ - d, 4ul, faiss::METRIC_L2, 0, faiss::SVSStorageKind::SVS_LeanVec4x4}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLeanVec4x8TrainAndAdd) { - faiss::IndexSVSIVFLeanVec index{ - d, 4ul, faiss::METRIC_L2, 0, faiss::SVSStorageKind::SVS_LeanVec4x8}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, IVFLeanVec8x8TrainAndAdd) { - faiss::IndexSVSIVFLeanVec index{ - d, 4ul, faiss::METRIC_L2, 0, faiss::SVSStorageKind::SVS_LeanVec8x8}; - train_and_add_ivf_index(index, test_data, n); -} - -TEST_F(SVS, IVFSearchWithIDSelector) { - faiss::IndexSVSIVF index{d, 4ul}; - index.train(n, test_data.data()); - index.add(n, test_data.data()); - - const int nq = 8; - const float* xq = test_data.data(); - const int k = 10; - - size_t min_id = n / 5; - size_t max_id = n * 4 / 5; - faiss::IDSelectorRange selector(min_id, max_id); - - faiss::SearchParameters params; - params.sel = &selector; - - std::vector distances(nq * k); - std::vector labels(nq * k); - - // The current SVS runtime IVFIndex::search() API does not accept an - // IDFilter parameter (unlike VamanaIndex::search()), so the IDSelector - // passed via SearchParameters is silently ignored. This test verifies - // that search still works (without filtering). Once the SVS runtime - // exposes IDFilter support for IVF search, this can be wired up the - // same way Vamana uses make_faiss_id_filter(). - ASSERT_NO_THROW(index.search(nq, xq, k, distances.data(), labels.data())); -} - -TEST_F(SVSLL, IVFLeanVecThrowsWithoutTraining) { - faiss::IndexSVSIVFLeanVec index{ - 64, - 4ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec4x4}; - ASSERT_THROW(index.add(100, test_data.data()), faiss::FaissException); -} - -TEST_F(SVS, IVFThrowsAddWithoutTraining) { - faiss::IndexSVSIVF index{d, 4ul}; - ASSERT_THROW(index.add(n, test_data.data()), faiss::FaissException); -} - TEST_F(SVS, SaveAndLoadIndexSVSIVF) { save_and_load_index(); } -TEST_F(SVSLL, SaveAndLoadIndexSVSIVFLVQ) { - save_and_load_index(); -} - TEST_F(SVSLL, SaveAndLoadIndexSVSIVFLeanVec) { save_and_load_index(); } @@ -771,7 +422,6 @@ void write_and_read_static_ivf_index( ASSERT_TRUE(index.is_static); index.train(n, xb.data()); - // Verify search works after training const int nq = 4; const int k = 5; std::vector distances(nq * k); @@ -783,16 +433,13 @@ void write_and_read_static_ivf_index( "/tmp/faiss_svs_static_ivf_test_XXXXXX"; Tempfilename filename(&temp_file_mutex, temp_filename_template); - // Serialize ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - // Deserialize T* loaded = nullptr; ASSERT_NO_THROW({ loaded = dynamic_cast(faiss::read_index(filename.c_str())); }); - // Basic checks ASSERT_NE(loaded, nullptr); ASSERT_NE(loaded->impl, nullptr); EXPECT_TRUE(loaded->is_static); @@ -800,73 +447,24 @@ void write_and_read_static_ivf_index( EXPECT_EQ(loaded->metric_type, index.metric_type); EXPECT_EQ(loaded->num_centroids, index.num_centroids); EXPECT_EQ(loaded->storage_kind, index.storage_kind); - if constexpr (std::is_same_v, faiss::IndexSVSIVFLeanVec>) { - auto* leanvec_loaded = dynamic_cast(loaded); - ASSERT_NE(leanvec_loaded, nullptr); - EXPECT_EQ(leanvec_loaded->leanvec_d, index.leanvec_d); - EXPECT_NE(leanvec_loaded->training_data, nullptr); - } - // Verify search works on loaded index ASSERT_NO_THROW( loaded->search(nq, xb.data(), k, distances.data(), labels.data())); delete loaded; } -TEST_F(SVS, WriteAndReadStaticIVF) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - write_and_read_static_ivf_index(index, test_data, n); -} - TEST_F(SVS, WriteAndReadStaticIVFFP16) { faiss::IndexSVSIVF index{ d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16, true}; write_and_read_static_ivf_index(index, test_data, n); } -TEST_F(SVSLL, WriteAndReadStaticIVFLVQ4x4) { - faiss::IndexSVSIVFLVQ index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_LVQ4x4, true}; - write_and_read_static_ivf_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadStaticIVFLeanVec4x4) { - faiss::IndexSVSIVFLeanVec index{ - d, - 4ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec4x4, - true}; - write_and_read_static_ivf_index(index, test_data, n); -} - -TEST_F(SVS, StaticIVFAddThrows) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.train(n, test_data.data()); - ASSERT_THROW(index.add(n, test_data.data()), faiss::FaissException); -} - -TEST_F(SVS, StaticIVFRemoveThrows) { - faiss::IndexSVSIVF index{ - d, 4ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.train(n, test_data.data()); - faiss::IDSelectorRange selector(0, 10); - ASSERT_THROW(index.remove_ids(selector), faiss::FaissException); -} - -// Verify that intra_query_threads must be set before train(). -// The SVS runtime API does not currently expose a setter for -// intra_query_threads after index creation, so changes made between -// train() and search() are silently ignored. This test documents the -// expected usage pattern. +// The SVS runtime only takes intra_query_threads when the index is built or +// loaded and has no setter afterwards, so it must be set before train(). TEST_F(SVS, IVFIntraQueryThreadsSetBeforeTrain) { faiss::IndexSVSIVF index{d, 4ul}; - // Set intra_query_threads BEFORE train — this is the supported pattern. index.intra_query_threads = 2; index.train(n, test_data.data()); index.add(n, test_data.data()); @@ -877,12 +475,6 @@ TEST_F(SVS, IVFIntraQueryThreadsSetBeforeTrain) { std::vector labels(nq * k); ASSERT_NO_THROW(index.search( nq, test_data.data(), k, distances.data(), labels.data())); - - // Changing intra_query_threads AFTER train() has no effect — this is a - // known limitation of the current SVS runtime API. - index.intra_query_threads = 4; - ASSERT_NO_THROW(index.search( - nq, test_data.data(), k, distances.data(), labels.data())); } /**************************************************************** @@ -897,14 +489,11 @@ void write_and_read_static_vamana_index( int read_io_flags = 0) { ASSERT_TRUE(index.is_static); - // For LeanVec the training step seeds training_data; for plain Vamana - // it is a no-op. The static build itself happens inside add(). - index.train(n, xb.data()); + // The static build itself happens inside add(). index.add(n, xb.data()); ASSERT_NE(index.impl, nullptr); ASSERT_TRUE(index.is_trained); - // Verify search works after the static build const int nq = 4; const int k = 5; std::vector distances(nq * k); @@ -916,17 +505,14 @@ void write_and_read_static_vamana_index( "/tmp/faiss_svs_static_vamana_test_XXXXXX"; Tempfilename filename(&temp_file_mutex, temp_filename_template); - // Serialize ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - // Deserialize T* loaded = nullptr; ASSERT_NO_THROW({ loaded = dynamic_cast( faiss::read_index(filename.c_str(), read_io_flags)); }); - // Basic checks ASSERT_NE(loaded, nullptr); ASSERT_NE(loaded->impl, nullptr); EXPECT_TRUE(loaded->is_static); @@ -934,29 +520,13 @@ void write_and_read_static_vamana_index( EXPECT_EQ(loaded->metric_type, index.metric_type); EXPECT_EQ(loaded->graph_max_degree, index.graph_max_degree); EXPECT_EQ(loaded->storage_kind, index.storage_kind); - if constexpr (std::is_same_v< - std::decay_t, - faiss::IndexSVSVamanaLeanVec>) { - auto* leanvec_loaded = - dynamic_cast(loaded); - ASSERT_NE(leanvec_loaded, nullptr); - EXPECT_EQ(leanvec_loaded->leanvec_d, index.leanvec_d); - EXPECT_NE(leanvec_loaded->training_data, nullptr); - } - // Verify search works on the loaded index ASSERT_NO_THROW( loaded->search(nq, xb.data(), k, distances.data(), labels.data())); delete loaded; } -TEST_F(SVS, WriteAndReadStaticVamana) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - write_and_read_static_vamana_index(index, test_data, n); -} - TEST_F(SVS, WriteAndReadStaticVamanaFP16) { faiss::IndexSVSVamana index{ d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP16, true}; @@ -969,85 +539,6 @@ TEST_F(SVS, WriteAndReadStaticVamanaSQ8) { write_and_read_static_vamana_index(index, test_data, n); } -TEST_F(SVSLL, WriteAndReadStaticVamanaLVQ4x4) { - faiss::IndexSVSVamanaLVQ index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_LVQ4x4, true}; - write_and_read_static_vamana_index(index, test_data, n); -} - -TEST_F(SVSLL, WriteAndReadStaticVamanaLeanVec4x4) { - faiss::IndexSVSVamanaLeanVec index{ - d, - 64ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec4x4, - true}; - write_and_read_static_vamana_index(index, test_data, n); -} - -TEST_F(SVS, StaticVamanaAddThrowsOnSecondCall) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.add(n, test_data.data()); - ASSERT_THROW(index.add(n, test_data.data()), faiss::FaissException); -} - -TEST_F(SVS, StaticVamanaRemoveThrows) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.add(n, test_data.data()); - faiss::IDSelectorRange selector(0, 10); - ASSERT_THROW(index.remove_ids(selector), faiss::FaissException); -} - -TEST_F(SVS, StaticVamanaResetAndRebuild) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.add(n, test_data.data()); - EXPECT_EQ(index.ntotal, static_cast(n)); - - index.reset(); - EXPECT_EQ(index.ntotal, 0); - EXPECT_FALSE(index.is_trained); - - // After reset, a fresh add() must rebuild the static index. - ASSERT_NO_THROW(index.add(n, test_data.data())); - EXPECT_EQ(index.ntotal, static_cast(n)); - EXPECT_TRUE(index.is_trained); - - const int nq = 4; - const int k = 5; - std::vector distances(nq * k); - std::vector labels(nq * k); - ASSERT_NO_THROW(index.search( - nq, test_data.data(), k, distances.data(), labels.data())); -} - -TEST_F(SVS, StaticVamanaReconstruct) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - index.add(n, test_data.data()); - - std::vector recons(d); - ASSERT_NO_THROW(index.reconstruct(0, recons.data())); - for (size_t i = 0; i < d; ++i) { - EXPECT_EQ(recons[i], test_data[i]); - } -} - -// store_vectors defaults to true, so the fp32 copy backing reconstruct() is -// still kept unless the caller opts out. -TEST_F(SVS, VamanaStoresVectorsByDefault) { - faiss::IndexSVSVamana index{d, 64ul}; - EXPECT_TRUE(index.store_vectors); - index.add(n, test_data.data()); - EXPECT_EQ(index.stored_vectors.size(), n * d); - - std::vector recons(d); - ASSERT_NO_THROW(index.reconstruct(0, recons.data())); -} - TEST_F(SVS, VamanaStoreVectorsDisabled) { faiss::IndexSVSVamana index{ d, @@ -1056,21 +547,7 @@ TEST_F(SVS, VamanaStoreVectorsDisabled) { faiss::SVSStorageKind::SVS_FP32, false, false}; - EXPECT_FALSE(index.store_vectors); index.add(n, test_data.data()); - EXPECT_EQ(index.ntotal, static_cast(n)); - EXPECT_TRUE(index.stored_vectors.empty()); - - std::vector recons(d); - EXPECT_THROW(index.reconstruct(0, recons.data()), faiss::FaissException); - - // Dropping the copy must not affect search. - const int nq = 4; - const int k = 5; - std::vector distances(nq * k); - std::vector labels(nq * k); - ASSERT_NO_THROW(index.search( - nq, test_data.data(), k, distances.data(), labels.data())); // The opt-out survives reset(). index.reset(); @@ -1087,22 +564,12 @@ TEST_F(SVS, StaticVamanaStoreVectorsDisabled) { true, false}; index.add(n, test_data.data()); - EXPECT_EQ(index.ntotal, static_cast(n)); EXPECT_TRUE(index.stored_vectors.empty()); std::vector recons(d); EXPECT_THROW(index.reconstruct(0, recons.data()), faiss::FaissException); } -// The flag is a plain public field, so setting it after construction (as the -// Python bindings do) must take effect too. -TEST_F(SVS, VamanaStoreVectorsDisabledAfterConstruction) { - faiss::IndexSVSVamana index{d, 64ul}; - index.store_vectors = false; - index.add(n, test_data.data()); - EXPECT_TRUE(index.stored_vectors.empty()); -} - // Opting out mid-stream cannot keep the remaining copy aligned with the ids, // so it is dropped rather than left partially populated. TEST_F(SVS, VamanaStoreVectorsDroppedOnMidStreamOptOut) { @@ -1119,51 +586,6 @@ TEST_F(SVS, VamanaStoreVectorsDroppedOnMidStreamOptOut) { EXPECT_THROW(index.reconstruct(0, recons.data()), faiss::FaissException); } -// An index built without the copy is written as ISVD, loads back and searches -// identically; only reconstruct() is unavailable. -TEST_F(SVS, VamanaStoreVectorsDisabledWriteAndRead) { - faiss::IndexSVSVamana index{ - d, - 64ul, - faiss::METRIC_L2, - faiss::SVSStorageKind::SVS_FP32, - false, - false}; - index.add(n, test_data.data()); - - const int nq = 4; - const int k = 5; - std::vector distances(nq * k), distances_loaded(nq * k); - std::vector labels(nq * k), labels_loaded(nq * k); - index.search(nq, test_data.data(), k, distances.data(), labels.data()); - - std::string temp_filename_template = "/tmp/faiss_svs_test_XXXXXX"; - Tempfilename filename(&temp_file_mutex, temp_filename_template); - ASSERT_NO_THROW({ faiss::write_index(&index, filename.c_str()); }); - - faiss::IndexSVSVamana* loaded = nullptr; - ASSERT_NO_THROW({ - loaded = dynamic_cast( - faiss::read_index(filename.c_str())); - }); - ASSERT_NE(loaded, nullptr); - EXPECT_EQ(loaded->ntotal, static_cast(n)); - EXPECT_TRUE(loaded->stored_vectors.empty()); - - loaded->search( - nq, - test_data.data(), - k, - distances_loaded.data(), - labels_loaded.data()); - EXPECT_EQ(labels, labels_loaded); - - std::vector recons(d); - EXPECT_THROW(loaded->reconstruct(0, recons.data()), faiss::FaissException); - - delete loaded; -} - TEST_F(SVSLL, LVQStoreVectorsDisabled) { faiss::IndexSVSVamanaLVQ index{ d, @@ -1173,11 +595,7 @@ TEST_F(SVSLL, LVQStoreVectorsDisabled) { false, false}; index.add(n, test_data.data()); - EXPECT_EQ(index.ntotal, static_cast(n)); EXPECT_TRUE(index.stored_vectors.empty()); - - std::vector recons(d); - EXPECT_THROW(index.reconstruct(0, recons.data()), faiss::FaissException); } TEST_F(SVSLL, LeanVecStoreVectorsDisabled) { @@ -1191,18 +609,7 @@ TEST_F(SVSLL, LeanVecStoreVectorsDisabled) { false}; index.train(n, test_data.data()); index.add(n, test_data.data()); - EXPECT_EQ(index.ntotal, static_cast(n)); EXPECT_TRUE(index.stored_vectors.empty()); - - std::vector recons(d); - EXPECT_THROW(index.reconstruct(0, recons.data()), faiss::FaissException); -} - -TEST_F(SVS, WriteAndMapStaticVamana) { - faiss::IndexSVSVamana index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_FP32, true}; - write_and_read_static_vamana_index( - index, test_data, n, faiss::IO_FLAG_MMAP_IFC); } TEST_F(SVS, WriteAndMapStaticVamanaFP16) { @@ -1218,22 +625,3 @@ TEST_F(SVS, WriteAndMapStaticVamanaSQ8) { write_and_read_static_vamana_index( index, test_data, n, faiss::IO_FLAG_MMAP_IFC); } - -TEST_F(SVSLL, WriteAndMapStaticVamanaLVQ4x4) { - faiss::IndexSVSVamanaLVQ index{ - d, 64ul, faiss::METRIC_L2, faiss::SVSStorageKind::SVS_LVQ4x4, true}; - write_and_read_static_vamana_index( - index, test_data, n, faiss::IO_FLAG_MMAP_IFC); -} - -TEST_F(SVSLL, WriteAndMapStaticVamanaLeanVec4x4) { - faiss::IndexSVSVamanaLeanVec index{ - d, - 64ul, - faiss::METRIC_L2, - 0, - faiss::SVSStorageKind::SVS_LeanVec4x4, - true}; - write_and_read_static_vamana_index( - index, test_data, n, faiss::IO_FLAG_MMAP_IFC); -} diff --git a/thirdparty/faiss/tests/test_svs_metric.cpp b/thirdparty/faiss/tests/test_svs_metric.cpp deleted file mode 100644 index a630a6e8f..000000000 --- a/thirdparty/faiss/tests/test_svs_metric.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include - -#include - -// Verify that to_svs_metric throws FaissException (not abort) for unsupported -// metric types. - -// Direct call: exercises the deserialization path where metric_type is read -// from a serialized stream and passed to to_svs_metric(). -TEST(SVSMetric, UnsupportedMetricThrowsDirect) { - EXPECT_THROW(faiss::to_svs_metric(faiss::METRIC_L1), faiss::FaissException); - EXPECT_THROW( - faiss::to_svs_metric(faiss::METRIC_Linf), faiss::FaissException); - EXPECT_THROW( - faiss::to_svs_metric(faiss::METRIC_Jaccard), faiss::FaissException); -} - -// Supported metrics should not throw. -TEST(SVSMetric, SupportedMetricsSucceed) { - EXPECT_NO_THROW(faiss::to_svs_metric(faiss::METRIC_L2)); - EXPECT_NO_THROW(faiss::to_svs_metric(faiss::METRIC_INNER_PRODUCT)); -} - -// Construction path: creating an IndexSVSFlat with an unsupported metric and -// calling add() triggers create_impl() -> to_svs_metric(). Verifies the throw -// propagates through the index construction API. -TEST(SVSMetric, IndexSVSFlatCreateImplUnsupportedMetricThrows) { - faiss::IndexSVSFlat idx(4, faiss::METRIC_L1); - std::vector data = {1.0f, 2.0f, 3.0f, 4.0f}; - EXPECT_THROW(idx.add(1, data.data()), faiss::FaissException); -} diff --git a/thirdparty/faiss/tests/test_svs_metric.py b/thirdparty/faiss/tests/test_svs_metric.py new file mode 100644 index 000000000..afbc87ab1 --- /dev/null +++ b/thirdparty/faiss/tests/test_svs_metric.py @@ -0,0 +1,25 @@ +# 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. + +"""Tests for the SVS metric mapping.""" + +import unittest + +import numpy as np + +import faiss + + +@unittest.skipIf( + "SVS" not in faiss.get_compile_options().split(), + "SVS support not compiled in", +) +class TestSVSMetric(unittest.TestCase): + def test_index_svs_flat_create_impl_unsupported_metric_throws(self): + index = faiss.IndexSVSFlat(4, faiss.METRIC_L1) + data = np.array( + [[1.0, 2.0, 3.0, 4.0]], dtype=np.float32) + with self.assertRaises(RuntimeError): + index.add(data) diff --git a/thirdparty/faiss/tests/test_svs_py.py b/thirdparty/faiss/tests/test_svs_py.py index d2a6e2962..a3e7e8b87 100644 --- a/thirdparty/faiss/tests/test_svs_py.py +++ b/thirdparty/faiss/tests/test_svs_py.py @@ -27,7 +27,6 @@ _SKIP_SVS = "SVS" not in faiss.get_compile_options().split() _SKIP_REASON = "SVS support not compiled in" -# Check if LVQ/LeanVec support is available _SKIP_SVS_LL = _SKIP_SVS or not faiss.IndexSVSVamana.is_lvq_leanvec_enabled() _SKIP_SVS_LL_REASON = ( "LVQ/LeanVec support not available on this platform or build configuration" @@ -36,16 +35,9 @@ @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSAdapter(unittest.TestCase): - """Test the FAISS-SVS adapter layer integration""" - target_class = None # set in setUpClass def _create_instance(self) -> "faiss.IndexSVSVamana | faiss.IndexSVSFlat": - """Create an instance of the SVS index""" - self.assertIsNotNone( - self.target_class, - "target_class must be configured in setUpClass()", - ) return self.target_class(self.d, 64) @classmethod @@ -60,36 +52,17 @@ def setUpClass(cls): cls.xb = np.random.random((cls.nb, cls.d)).astype("float32") cls.xq = np.random.random((cls.nq, cls.d)).astype("float32") - def test_svs_construction(self): - """Test construction and basic properties""" - # Test default construction - index = self._create_instance() - self.assertEqual(index.d, self.d) - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, 0) - self.assertEqual(index.metric_type, faiss.METRIC_L2) - - index_ip = self._create_instance() - index_ip.metric_type = faiss.METRIC_INNER_PRODUCT - self.assertEqual(index_ip.metric_type, faiss.METRIC_INNER_PRODUCT) - def test_svs_add_search_remove_interface(self): - """Test FAISS add/search/remove_ids interface compatibility""" index = self._create_instance() - # Test add interface index.add(self.xb) self.assertEqual(index.ntotal, self.nb) - # Test search interface k = 4 - D, I = index.search(self.xq, k) - self.assertEqual(D.shape, (self.nq, k)) - self.assertEqual(I.shape, (self.nq, k)) + _, I = index.search(self.xq, k) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(I < self.nb)) - # Test remove ids = np.arange(index.ntotal) toremove = np.ascontiguousarray(ids[0:200:3]) sel = faiss.IDSelectorArray(50, faiss.swig_ptr(toremove[:50])) @@ -103,155 +76,80 @@ def test_svs_add_search_remove_interface(self): nremove = index.remove_ids(toremove) self.assertEqual(nremove, len(toremove)) - # Test reset index.reset() self.assertEqual(index.ntotal, 0) def test_svs_search_selected(self): - """Test FAISS search with IDSelector interface compatibility""" index = self._create_instance() - # Test add interface index.add(self.xb) - self.assertEqual(index.ntotal, self.nb) - # Create selector to select a subset of ids min = self.nb // 5 max = self.nb * 4 // 5 - sel = faiss.IDSelectorRange(min, max) # select ids in [100, 200) + sel = faiss.IDSelectorRange(min, max) params = faiss.SearchParameters(sel=sel) - # Test search interface k = 10 - D, I = index.search(self.xq, k, params=params) - self.assertEqual(D.shape, (self.nq, k)) - self.assertEqual(I.shape, (self.nq, k)) + _, I = index.search(self.xq, k, params=params) self.assertTrue(np.all(I >= min)) self.assertTrue(np.all(I < max)) - def test_svs_range_search(self): - """Test FAISS range_search interface compatibility""" - index = self._create_instance() - - # Test add interface - index.add(self.xb) - self.assertEqual(index.ntotal, self.nb) - - # Test search interface - range = 0.1 - lims, D, I = index.range_search(self.xq, range) - self.assertEqual(D.shape, I.shape) - self.assertTrue(np.all(D <= range)) - self.assertTrue(np.all(I >= 0)) - self.assertTrue(np.all(I < self.nb)) - def test_svs_range_search_ip(self): - """Test FAISS range_search interface compatibility""" index = self._create_instance() index.metric_type = faiss.METRIC_INNER_PRODUCT index.alpha = 0.95 - # Test add interface index.add(self.xb) - self.assertEqual(index.ntotal, self.nb) - # Test search interface range = 10 lims, D, I = index.range_search(self.xq, range) - self.assertEqual(D.shape, I.shape) self.assertTrue(np.all(D >= range)) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(I < self.nb)) def test_svs_range_search_selected(self): - """Test FAISS add/search/remove_ids interface compatibility""" index = self._create_instance() - # Test add interface index.add(self.xb) - self.assertEqual(index.ntotal, self.nb) - # Create selector to select a subset of ids min = self.nb // 5 max = self.nb * 4 // 5 - sel = faiss.IDSelectorRange(min, max) # select ids in [100, 200) + sel = faiss.IDSelectorRange(min, max) params = faiss.SearchParameters(sel=sel) - # Test search interface - radius = 0.1 + radius = 4.0 lims, D, I = index.range_search(self.xq, radius, params=params) - self.assertEqual(D.shape, I.shape) + self.assertGreater(len(I), 0) self.assertTrue(np.all(D <= radius)) self.assertTrue(np.all(I >= min)) self.assertTrue(np.all(I < max)) - # Test reset - index.reset() - self.assertEqual(index.ntotal, 0) - - def test_svs_metric_types(self): - """Test different metric types are handled correctly""" - # L2 metric - index_l2 = self._create_instance() - index_l2.metric_type = faiss.METRIC_L2 - index_l2.add(self.xb) - D_l2, _ = index_l2.search(self.xq[:10], 4) - - index_ip = self._create_instance() - index_ip.metric_type = faiss.METRIC_INNER_PRODUCT - index_ip.alpha = 0.95 - index_ip.add(self.xb) - D_ip, _ = index_ip.search(self.xq[:10], 4) - - # Results should be different - # (testing adapter forwards metric correctly) - self.assertFalse(np.array_equal(D_l2, D_ip)) - def test_svs_serialization(self): - """Test FAISS serialization system works with SVS indices""" index = self._create_instance() index.add(self.xb) D_before, I_before = index.search(self.xq, 4) loaded = faiss.deserialize_index(faiss.serialize_index(index)) - # Verify adapter layer preserves type and parameters - self.assertIsInstance(loaded, self.target_class) + self.assertEqual(type(loaded), self.target_class) self.assertEqual(loaded.d, self.d) self.assertEqual(loaded.ntotal, self.nb) self.assertEqual(loaded.metric_type, index.metric_type) - # Verify functionality is preserved D_after, I_after = loaded.search(self.xq, 4) np.testing.assert_array_equal(I_before, I_after) np.testing.assert_allclose(D_before, D_after, rtol=1e-6) def test_svs_error_handling(self): - """Test that FAISS error handling works with SVS indices""" index = self._create_instance() - # Test wrong dimension wrong_dim_data = np.random.random((100, self.d + 1)).astype("float32") with self.assertRaises(AssertionError): index.add(wrong_dim_data) - def test_svs_fourcc_handling(self): - """Test that FAISS I/O system handles SVS fourccs correctly""" - # Create and populate index - index = self._create_instance() - index.add(self.xb[:100]) # Smaller dataset for speed - - # Test round-trip serialization preserves exact type - loaded = faiss.deserialize_index(faiss.serialize_index(index)) - - # Verify exact type preservation (fourcc working correctly) - self.assertEqual(type(loaded), self.target_class) - def test_svs_batch_operations(self): - """Test that batch operations work correctly through adapter""" index = self._create_instance() - # Add in multiple batches batch_size = 250 for i in range(0, self.nb, batch_size): end_idx = min(i + batch_size, self.nb) @@ -259,9 +157,7 @@ def test_svs_batch_operations(self): self.assertEqual(index.ntotal, self.nb) - # Verify search still works after batch operations - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) + index.search(self.xq, 4) @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) @@ -323,8 +219,6 @@ def test_store_vectors_disabled_survives_serialization(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSFactory(unittest.TestCase): - """Test that SVS factory works correctly""" - def test_svs_factory_flat(self): index = faiss.index_factory(32, "SVSFlat") self.assertEqual(index.d, 32) @@ -351,8 +245,6 @@ def test_svs_factory_sq8(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSFactoryLVQLeanVec(unittest.TestCase): - """Test that SVS factory works correctly for LVQ and LeanVec""" - def test_svs_factory_lvq(self): index = faiss.index_factory(16, "SVSVamana32,LVQ4x8") self.assertEqual(index.d, 16) @@ -369,27 +261,13 @@ def test_svs_factory_leanvec(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFCoarseQuantizerFactory(unittest.TestCase): - """Test that IVF with SVSVamana coarse quantizer supports storage kinds""" - - def test_ivf_svsvamana_default(self): - index = faiss.index_factory(32, "IVF256_SVSVamana32,Flat") - self.assertEqual(index.d, 32) - self.assertEqual(index.nlist, 256) - - def test_ivf_svsvamana_sq8(self): - index = faiss.index_factory(32, "IVF256_SVSVamana32_SQ8,Flat") - self.assertEqual(index.d, 32) - self.assertEqual(index.nlist, 256) - - def test_ivf_svsvamana_fp16(self): - index = faiss.index_factory(32, "IVF256_SVSVamana32_FP16,Flat") - self.assertEqual(index.d, 32) - self.assertEqual(index.nlist, 256) - - def test_ivf_svsvamana_fp32_explicit(self): - index = faiss.index_factory(32, "IVF256_SVSVamana32_FP32,Flat") - self.assertEqual(index.d, 32) - self.assertEqual(index.nlist, 256) + def test_ivf_svsvamana_storage(self): + for storage in ("SQ8", "FP16", "FP32"): + index = faiss.index_factory( + 32, f"IVF256_SVSVamana32_{storage},Flat" + ) + self.assertEqual(index.d, 32) + self.assertEqual(index.nlist, 256) def test_ivf_svsvamana_invalid_storage(self): with self.assertRaises(RuntimeError): @@ -398,8 +276,6 @@ def test_ivf_svsvamana_invalid_storage(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSAdapterFP16(TestSVSAdapter): - """Repeat all tests for SVS Float16 variant""" - def _create_instance(self): idx = self.target_class(self.d, 64) idx.storage_kind = faiss.SVS_FP16 @@ -408,8 +284,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSAdapterSQ8(TestSVSAdapter): - """Repeat all tests for SVS SQ int8 variant""" - def _create_instance(self): idx = self.target_class(self.d, 64) idx.storage_kind = faiss.SVS_SQ8 @@ -418,8 +292,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSAdapterLVQ4x0(TestSVSAdapter): - """Repeat all tests for SVSLVQ4x0 variant""" - @classmethod def setUpClass(cls): super().setUpClass() @@ -433,8 +305,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSAdapterLVQ4x4(TestSVSAdapter): - """Repeat all tests for SVSLVQ4x4 variant""" - @classmethod def setUpClass(cls): super().setUpClass() @@ -448,8 +318,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSAdapterLVQ4x8(TestSVSAdapter): - """Repeat all tests for SVSLVQ4x8 variant""" - @classmethod def setUpClass(cls): super().setUpClass() @@ -462,8 +330,6 @@ def _create_instance(self): class TestSVSAdapterFlat(TestSVSAdapter): - """Repeat all tests for SVSFlat variant""" - @classmethod def setUpClass(cls): super().setUpClass() @@ -473,8 +339,6 @@ def _create_instance(self): return self.target_class(self.d) def test_svs_metric_types(self): - """Test different metric types are handled correctly""" - # L2 metric index_l2 = self._create_instance() index_l2.metric_type = faiss.METRIC_L2 index_l2.add(self.xb) @@ -485,20 +349,14 @@ def test_svs_metric_types(self): index_ip.add(self.xb) D_ip, _ = index_ip.search(self.xq[:10], 4) - # Results should be different - # (testing adapter forwards metric correctly) + # the distances differ only if the adapter forwards the metric self.assertFalse(np.array_equal(D_l2, D_ip)) - # The following tests are expected to fail for IndexSVSFlat as it - # doesn't support yet + # IndexSVSFlat has no selector, range search or remove_ids support @unittest.expectedFailure def test_svs_search_selected(self): return super().test_svs_search_selected() - @unittest.expectedFailure - def test_svs_range_search(self): - return super().test_svs_range_search() - @unittest.expectedFailure def test_svs_range_search_ip(self): return super().test_svs_range_search_ip() @@ -518,8 +376,6 @@ def test_svs_batch_operations(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSVamanaParameters(unittest.TestCase): - """Test Vamana-specific parameter forwarding and persistence.""" - @classmethod def setUpClass(cls): cls.target_class = faiss.IndexSVSVamana @@ -531,38 +387,11 @@ def setUpClass(cls): cls.xq = np.random.random((cls.nq, cls.d)).astype("float32") def _create_instance(self): - """Create an instance of the SVS Vamana index""" return self.target_class(self.d, 64) - def test_vamana_parameter_setting(self): - """Test that all Vamana parameters can be set and retrieved""" - index = self._create_instance() - - # Set non-default values for all parameters - index.graph_max_degree = 32 - index.alpha = 1.5 - index.search_window_size = 20 - index.search_buffer_capacity = 25 - index.construction_window_size = 80 - index.max_candidate_pool_size = 150 - index.prune_to = 30 - index.use_full_search_history = False - - # Verify all parameters are set correctly - self.assertEqual(index.graph_max_degree, 32) - self.assertAlmostEqual(index.alpha, 1.5, places=6) - self.assertEqual(index.search_window_size, 20) - self.assertEqual(index.search_buffer_capacity, 25) - self.assertEqual(index.construction_window_size, 80) - self.assertEqual(index.max_candidate_pool_size, 150) - self.assertEqual(index.prune_to, 30) - self.assertEqual(index.use_full_search_history, False) - def test_vamana_parameter_defaults(self): - """Test that Vamana parameters have correct default values""" index = self._create_instance() - # Verify default values match C++ header self.assertEqual(index.graph_max_degree, 64) self.assertAlmostEqual(index.alpha, 1.2, places=6) self.assertEqual(index.search_window_size, 10) @@ -573,10 +402,8 @@ def test_vamana_parameter_defaults(self): self.assertEqual(index.use_full_search_history, True) def test_vamana_parameter_serialization(self): - """Test that Vamana parameters are preserved through serialization.""" index = self._create_instance() - # Set distinctive non-default values index.graph_max_degree = 48 index.alpha = 1.8 index.search_window_size = 15 @@ -586,14 +413,10 @@ def test_vamana_parameter_serialization(self): index.prune_to = 45 index.use_full_search_history = False - # Add data and train index.add(self.xb) - # Serialize and deserialize loaded = faiss.deserialize_index(faiss.serialize_index(index)) - # Verify all parameters are preserved - self.assertIsInstance(loaded, self.target_class) self.assertEqual(loaded.graph_max_degree, 48) self.assertAlmostEqual(loaded.alpha, 1.8, places=6) self.assertEqual(loaded.search_window_size, 15) @@ -603,77 +426,6 @@ def test_vamana_parameter_serialization(self): self.assertEqual(loaded.prune_to, 45) self.assertEqual(loaded.use_full_search_history, False) - # Verify results are unaffected - D_before, I_before = index.search(self.xq, 4) - D_after, I_after = loaded.search(self.xq, 4) - np.testing.assert_array_equal(I_before, I_after) - np.testing.assert_allclose(D_before, D_after, rtol=1e-6) - - -@unittest.skipIf(_SKIP_SVS, _SKIP_REASON) -class TestSVSVamanaParametersFP16(TestSVSVamanaParameters): - """Repeat Vamana parameter tests for SVS Float16 variant""" - - def _create_instance(self): - idx = self.target_class(self.d, 64) - idx.storage_kind = faiss.SVS_FP16 - return idx - - -@unittest.skipIf(_SKIP_SVS, _SKIP_REASON) -class TestSVSVamanaParametersSQ8(TestSVSVamanaParameters): - """Repeat Vamana parameter tests for SVS SQ int8 variant""" - - def _create_instance(self): - idx = self.target_class(self.d, 64) - idx.storage_kind = faiss.SVS_SQ8 - return idx - - -@unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) -class TestSVSVamanaParametersLVQ4x0(TestSVSVamanaParameters): - """Repeat Vamana parameter tests for SVSLVQ4x0 variant""" - - @classmethod - def setUpClass(cls): - super().setUpClass() - cls.target_class = faiss.IndexSVSVamanaLVQ - - def _create_instance(self): - idx = self.target_class(self.d, 64) - idx.storage_kind = faiss.SVS_LVQ4x0 - return idx - - -@unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) -class TestSVSVamanaParametersLVQ4x4(TestSVSVamanaParameters): - """Repeat Vamana parameter tests for SVSLVQ4x4 variant""" - - @classmethod - def setUpClass(cls): - super().setUpClass() - cls.target_class = faiss.IndexSVSVamanaLVQ - - def _create_instance(self): - idx = self.target_class(self.d, 64) - idx.storage_kind = faiss.SVS_LVQ4x4 - return idx - - -@unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) -class TestSVSVamanaParametersLVQ4x8(TestSVSVamanaParameters): - """Repeat Vamana parameter tests for SVSLVQ4x8 variant""" - - @classmethod - def setUpClass(cls): - super().setUpClass() - cls.target_class = faiss.IndexSVSVamanaLVQ - - def _create_instance(self): - idx = self.target_class(self.d, 64) - idx.storage_kind = faiss.SVS_LVQ4x8 - return idx - @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSVamanaSetIndexParameter(unittest.TestCase): @@ -700,7 +452,6 @@ def setUp(self): self.ps = faiss.ParameterSpace() def _create_instance(self): - """Create an SVS Vamana index that is ready to accept vectors""" return self.target_class(self.d, 64) def _storage_kind(self): @@ -744,7 +495,6 @@ def test_build_parameters(self): index.add(self.xb) self.assertEqual(index.ntotal, self.nb) _, I = index.search(self.xq, 4) - self.assertEqual(I.shape, (self.nq, 4)) self.assertTrue((I >= 0).all()) def test_build_parameters_rejected_after_build(self): @@ -815,23 +565,8 @@ def test_coarse_quantizer_parameters(self): self.assertEqual(quantizer.graph_max_degree, 48) -@unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) -class TestSVSVamanaSetIndexParameterLVQ(TestSVSVamanaSetIndexParameter): - """Repeat the ParameterSpace tests on the LVQ variant""" - - @classmethod - def setUpClass(cls): - super().setUpClass() - cls.target_class = faiss.IndexSVSVamanaLVQ - - def _storage_kind(self): - return faiss.SVS_LVQ4x8 - - @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSVamanaSetIndexParameterLeanVec(TestSVSVamanaSetIndexParameter): - """Repeat the ParameterSpace tests on the LeanVec variant""" - @classmethod def setUpClass(cls): super().setUpClass() @@ -861,42 +596,6 @@ def test_leanvec_d(self): self.assertEqual(index.ntotal, self.nb) -@unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) -class TestSVSLeanVecOOD(unittest.TestCase): - """Test out-of-distribution training for LeanVec SVS indices""" - - def setUp(self): - self.d = 256 - self.idx = faiss.IndexSVSVamanaLeanVec( - self.d, 64, faiss.METRIC_INNER_PRODUCT, 64, faiss.SVS_LeanVec4x8 - ) - self.idx.alpha = 0.95 - - self.x = np.random.rand(1000, self.d).astype("float32") - self.tq = np.random.rand(1000, self.d).astype("float32") - - def test_svs_leanvec_ood_training(self): - self.assertIsNone(self.idx.training_data) - self.idx.train(self.x, xq_train=self.tq) - self.assertIsNotNone(self.idx.training_data) - - def test_svs_leanvec_ood_training_smaller(self): - self.idx.train(self.x, xq_train=self.tq[:500]) - - def test_svs_leanvec_ood_training_wrong_dim(self): - wrong_dim = np.random.rand(1000, self.d + 1).astype("float32") - with self.assertRaises(AssertionError): - self.idx.train(self.x, xq_train=wrong_dim) - - def test_svs_leanvec_ood_training_wrong_type(self): - with self.assertRaises(TypeError): - self.idx.train( - self.x, - xq_train=self.tq, - numeric_type=faiss.Float16, - ) - - ############################################################################### # SVS IVF Tests ############################################################################### @@ -904,8 +603,6 @@ def test_svs_leanvec_ood_training_wrong_type(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFAdapter(unittest.TestCase): - """Test the FAISS-SVS IVF adapter layer integration""" - target_class = None @classmethod @@ -927,39 +624,18 @@ def _create_instance(self): return idx def test_ivf_construction(self): - """Test construction and basic properties""" index = self._create_instance() self.assertEqual(index.d, self.d) self.assertFalse(index.is_trained) self.assertEqual(index.ntotal, 0) self.assertEqual(index.metric_type, faiss.METRIC_L2) - def test_ivf_train_add_search(self): - """Test FAISS train/add/search interface""" - index = self._create_instance() - - # Train first - index.train(self.xb) - self.assertTrue(index.is_trained) - - # Add more data - extra = np.random.random((200, self.d)).astype("float32") - index.add(extra) - - # Search - k = 4 - D, I = index.search(self.xq, k) - self.assertEqual(D.shape, (self.nq, k)) - self.assertEqual(I.shape, (self.nq, k)) - def test_ivf_throws_add_without_train(self): - """Test that add throws without training""" index = self._create_instance() with self.assertRaises(RuntimeError): index.add(self.xb) def test_ivf_serialization(self): - """Test serialization round-trip""" index = self._create_instance() index.train(self.xb) @@ -979,7 +655,6 @@ def test_ivf_serialization(self): np.testing.assert_allclose(D_before, D_after, rtol=1e-4) def test_ivf_remove_ids(self): - """Test remove_ids interface""" index = self._create_instance() index.train(self.xb) @@ -994,13 +669,11 @@ def test_ivf_remove_ids(self): self.assertEqual(index.ntotal, before - nremoved) def test_ivf_reset(self): - """Test reset clears the index""" index = self._create_instance() index.train(self.xb) extra = np.random.random((100, self.d)).astype("float32") index.add(extra) - self.assertGreater(index.ntotal, 0) index.reset() self.assertEqual(index.ntotal, 0) @@ -1009,8 +682,6 @@ def test_ivf_reset(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFAdapterFP16(TestSVSIVFAdapter): - """Repeat IVF tests for FP16 variant""" - def _create_instance(self): idx = self.target_class( self.d, self.nlist, faiss.METRIC_L2, faiss.SVS_FP16 @@ -1021,8 +692,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFAdapterSQ8(TestSVSIVFAdapter): - """Repeat IVF tests for SQ8 variant""" - def _create_instance(self): idx = self.target_class( self.d, self.nlist, faiss.METRIC_L2, faiss.SVS_SQ8 @@ -1033,8 +702,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSIVFAdapterLVQ4x4(TestSVSIVFAdapter): - """Repeat IVF tests for LVQ4x4 variant""" - @classmethod def setUpClass(cls): cls.target_class = faiss.IndexSVSIVFLVQ @@ -1048,8 +715,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSIVFAdapterLVQ4x8(TestSVSIVFAdapter): - """Repeat IVF tests for LVQ4x8 variant""" - @classmethod def setUpClass(cls): cls.target_class = faiss.IndexSVSIVFLVQ @@ -1063,8 +728,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSIVFAdapterLVQ8x0(TestSVSIVFAdapter): - """Repeat IVF tests for LVQ8x0 variant""" - @classmethod def setUpClass(cls): cls.target_class = faiss.IndexSVSIVFLVQ @@ -1078,8 +741,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSIVFAdapterLeanVec4x4(TestSVSIVFAdapter): - """Repeat IVF tests for LeanVec4x4 variant""" - @classmethod def setUpClass(cls): cls.target_class = faiss.IndexSVSIVFLeanVec @@ -1094,8 +755,6 @@ def _create_instance(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFFactory(unittest.TestCase): - """Test SVS IVF factory strings""" - def test_svs_factory_ivf(self): index = faiss.index_factory(32, "SVSIVF4") self.assertEqual(index.d, 32) @@ -1118,8 +777,6 @@ def test_svs_factory_ivf_sq8(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSIVFFactoryLVQLeanVec(unittest.TestCase): - """Test SVS IVF factory strings for LVQ and LeanVec""" - def test_svs_factory_ivf_lvq(self): index = faiss.index_factory(16, "SVSIVF4,LVQ4x8") self.assertEqual(index.d, 16) @@ -1136,8 +793,6 @@ def test_svs_factory_ivf_leanvec(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSIVFParameters(unittest.TestCase): - """Test IVF-specific parameter forwarding and persistence.""" - def setUp(self): self.d = 32 self.nb = 5000 @@ -1147,26 +802,7 @@ def setUp(self): self.xb = np.random.random((self.nb, self.d)).astype("float32") self.xq = np.random.random((self.nq, self.d)).astype("float32") - def test_ivf_parameter_setting(self): - """Test that IVF parameters can be set and retrieved""" - index = faiss.IndexSVSIVF(self.d, self.nlist) - - index.num_centroids = 8 - index.n_probes = 4 - index.k_reorder = 2.0 - index.num_iterations = 20 - index.minibatch_size = 512 - index.seed = 99 - - self.assertEqual(index.num_centroids, 8) - self.assertEqual(index.n_probes, 4) - self.assertAlmostEqual(index.k_reorder, 2.0, places=6) - self.assertEqual(index.num_iterations, 20) - self.assertEqual(index.minibatch_size, 512) - self.assertEqual(index.seed, 99) - def test_ivf_parameter_defaults(self): - """Test that IVF parameters have correct default values""" index = faiss.IndexSVSIVF(self.d, self.nlist) self.assertEqual(index.num_centroids, self.nlist) @@ -1177,7 +813,6 @@ def test_ivf_parameter_defaults(self): self.assertEqual(index.seed, 42) def test_ivf_parameter_serialization(self): - """Test that IVF parameters are preserved through serialization""" index = faiss.IndexSVSIVF(self.d, self.nlist) index.n_probes = 5 @@ -1187,7 +822,6 @@ def test_ivf_parameter_serialization(self): index.seed = 77 index.num_threads = 4 - # Train and add index.train(self.xb) extra = np.random.random((100, self.d)).astype("float32") index.add(extra) @@ -1233,45 +867,18 @@ def _create_instance(self): idx.num_threads = 4 return idx - def test_ivf_leanvec_ood_training(self): - """OOD training stores training data and produces a working index""" - idx = self._create_instance() - idx.train(self.x, xq_train=self.tq) - self.assertTrue(idx.is_trained) - self.assertEqual(idx.ntotal, self.n) - - def test_ivf_leanvec_ood_training_smaller_queries(self): - """OOD training works with fewer query vectors than data vectors""" - idx = self._create_instance() - idx.train(self.x, xq_train=self.tq[:100]) - self.assertTrue(idx.is_trained) - def test_ivf_leanvec_ood_training_wrong_dim(self): - """OOD training rejects query vectors with wrong dimension""" idx = self._create_instance() wrong_dim = np.random.rand(500, self.d + 1).astype("float32") with self.assertRaises(AssertionError): idx.train(self.x, xq_train=wrong_dim) def test_ivf_leanvec_ood_training_wrong_type(self): - """OOD training rejects non-Float32 numeric_type with xq_train""" idx = self._create_instance() with self.assertRaises(TypeError): idx.train(self.x, xq_train=self.tq, numeric_type=faiss.Float16) - def test_ivf_leanvec_ood_search(self): - """OOD-trained IVF LeanVec index returns valid search results""" - idx = self._create_instance() - idx.train(self.x, xq_train=self.tq) - - xq = np.random.rand(50, self.d).astype("float32") - k = 4 - D, I = idx.search(xq, k) - self.assertEqual(D.shape, (50, k)) - self.assertEqual(I.shape, (50, k)) - def test_ivf_leanvec_ood_serialization(self): - """OOD-trained IVF LeanVec index survives serialization round-trip""" idx = self._create_instance() idx.train(self.x, xq_train=self.tq) @@ -1292,27 +899,7 @@ class TestSVSLeanVecResetRetrain(unittest.TestCase): def _make_data(self, d, n): return np.random.rand(n, d).astype("float32") - def test_ivf_leanvec_reset_retrain(self): - """IVFLeanVec: train → reset → retrain should succeed.""" - d, n = 64, 5000 - X = self._make_data(d, n) - idx = faiss.index_factory(d, "SVSIVF100,LeanVec4x8_32") - idx.num_threads = 4 - - idx.train(X) - self.assertTrue(idx.is_trained) - self.assertEqual(idx.ntotal, n) - - idx.reset() - self.assertFalse(idx.is_trained) - self.assertEqual(idx.ntotal, 0) - - idx.train(X) - self.assertTrue(idx.is_trained) - self.assertEqual(idx.ntotal, n) - def test_ivf_leanvec_ood_reset_retrain(self): - """IVFLeanVec OOD: train → reset → retrain should succeed.""" d, n = 64, 5000 X = self._make_data(d, n) Xq = self._make_data(d, 100) @@ -1329,33 +916,13 @@ def test_ivf_leanvec_ood_reset_retrain(self): self.assertTrue(idx.is_trained) self.assertEqual(idx.ntotal, n) - def test_vamana_leanvec_reset_retrain(self): - """VamanaLeanVec: train → reset → retrain should succeed.""" - d = 64 - X = self._make_data(d, 1000) - idx = faiss.IndexSVSVamanaLeanVec( - d, 64, faiss.METRIC_L2, 32, faiss.SVS_LeanVec4x8 - ) - idx.alpha = 0.95 - - idx.train(X) - self.assertTrue(idx.is_trained) - - idx.reset() - self.assertFalse(idx.is_trained) - - idx.train(X) - self.assertTrue(idx.is_trained) - def test_vamana_leanvec_ood_reset_retrain(self): - """VamanaLeanVec OOD: train → reset → retrain should succeed.""" d = 64 X = self._make_data(d, 1000) Xq = self._make_data(d, 100) idx = faiss.IndexSVSVamanaLeanVec( d, 64, faiss.METRIC_INNER_PRODUCT, 32, faiss.SVS_LeanVec4x8 ) - idx.alpha = 0.95 idx.train(X, xq_train=Xq) self.assertTrue(idx.is_trained) @@ -1369,8 +936,6 @@ def test_vamana_leanvec_ood_reset_retrain(self): @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSStaticIVF(unittest.TestCase): - """Test the static (immutable) IVF index variant.""" - def setUp(self): self.d = 32 self.nb = 1000 @@ -1380,35 +945,14 @@ def setUp(self): self.xb = np.random.random((self.nb, self.d)).astype("float32") self.xq = np.random.random((self.nq, self.d)).astype("float32") - def _create_static(self, storage=None): - if storage is None: - storage = faiss.SVS_FP32 + def _create_static(self): idx = faiss.IndexSVSIVF( - self.d, self.nlist, faiss.METRIC_L2, storage, True + self.d, self.nlist, faiss.METRIC_L2, faiss.SVS_FP32, True ) idx.num_threads = 4 return idx - def test_static_ivf_construction(self): - """Test construction sets is_static flag""" - index = self._create_static() - self.assertTrue(index.is_static) - self.assertFalse(index.is_trained) - - def test_static_ivf_train_and_search(self): - """Train includes all data; search works normally""" - index = self._create_static() - index.train(self.xb) - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, self.nb) - - k = 4 - D, I = index.search(self.xq, k) - self.assertEqual(D.shape, (self.nq, k)) - self.assertEqual(I.shape, (self.nq, k)) - def test_static_ivf_add_throws(self): - """add() must raise on a static index""" index = self._create_static() index.train(self.xb) extra = np.random.random((100, self.d)).astype("float32") @@ -1416,7 +960,6 @@ def test_static_ivf_add_throws(self): index.add(extra) def test_static_ivf_remove_throws(self): - """remove_ids() must raise on a static index""" index = self._create_static() index.train(self.xb) ids = np.arange(0, 10, dtype=np.int64) @@ -1425,7 +968,6 @@ def test_static_ivf_remove_throws(self): index.remove_ids(sel) def test_static_ivf_serialization(self): - """Serialize/deserialize preserves is_static and search results""" index = self._create_static() index.train(self.xb) @@ -1439,18 +981,7 @@ def test_static_ivf_serialization(self): D_after, I_after = loaded.search(self.xq, 4) np.testing.assert_allclose(D_before, D_after, rtol=1e-4) - def test_static_ivf_fp16(self): - """Static IVF with FP16 storage""" - index = self._create_static(faiss.SVS_FP16) - index.train(self.xb) - self.assertTrue(index.is_trained) - self.assertTrue(index.is_static) - - D, I = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - def test_static_ivf_reset(self): - """reset() clears the static index so it can be retrained""" index = self._create_static() index.train(self.xb) self.assertTrue(index.is_trained) @@ -1459,7 +990,6 @@ def test_static_ivf_reset(self): self.assertEqual(index.ntotal, 0) self.assertFalse(index.is_trained) - # Retrain should work after reset index.train(self.xb) self.assertTrue(index.is_trained) self.assertEqual(index.ntotal, self.nb) @@ -1467,8 +997,6 @@ def test_static_ivf_reset(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSStaticIVFLVQ(unittest.TestCase): - """Test static IVF with LVQ storage""" - def setUp(self): self.d = 32 self.nb = 1000 @@ -1485,25 +1013,7 @@ def _create_static_lvq(self): idx.num_threads = 4 return idx - def test_static_ivf_lvq_train_search(self): - """Static IVF LVQ: train and search""" - index = self._create_static_lvq() - index.train(self.xb) - self.assertTrue(index.is_static) - self.assertTrue(index.is_trained) - - D, I = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - - def test_static_ivf_lvq_add_throws(self): - """Static IVF LVQ: add() must raise""" - index = self._create_static_lvq() - index.train(self.xb) - with self.assertRaises(RuntimeError): - index.add(self.xb) - def test_static_ivf_lvq_serialization(self): - """Static IVF LVQ: serialization round-trip""" index = self._create_static_lvq() index.train(self.xb) @@ -1519,8 +1029,6 @@ def test_static_ivf_lvq_serialization(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSStaticIVFLeanVec(unittest.TestCase): - """Test static IVF with LeanVec storage""" - def setUp(self): self.d = 64 self.nb = 5000 @@ -1537,25 +1045,7 @@ def _create_static_leanvec(self): idx.num_threads = 4 return idx - def test_static_ivf_leanvec_train_search(self): - """Static IVF LeanVec: train and search""" - index = self._create_static_leanvec() - index.train(self.xb) - self.assertTrue(index.is_static) - self.assertTrue(index.is_trained) - - D, I = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - - def test_static_ivf_leanvec_add_throws(self): - """Static IVF LeanVec: add() must raise""" - index = self._create_static_leanvec() - index.train(self.xb) - with self.assertRaises(RuntimeError): - index.add(self.xb) - def test_static_ivf_leanvec_serialization(self): - """Static IVF LeanVec: serialization round-trip""" index = self._create_static_leanvec() index.train(self.xb) @@ -1568,21 +1058,9 @@ def test_static_ivf_leanvec_serialization(self): D_after, _ = loaded.search(self.xq, 4) np.testing.assert_allclose(D_before, D_after, rtol=1e-4) - def test_static_ivf_leanvec_ood_train_search(self): - """Static IVF LeanVec OOD: train with queries and search""" - index = self._create_static_leanvec() - index.train(self.xb, xq_train=self.xq) - self.assertTrue(index.is_static) - self.assertTrue(index.is_trained) - - D, I = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - @unittest.skipIf(_SKIP_SVS, _SKIP_REASON) class TestSVSStaticVamana(unittest.TestCase): - """Test the static (immutable) Vamana index variant.""" - def setUp(self): self.d = 32 self.nb = 1000 @@ -1592,32 +1070,12 @@ def setUp(self): self.xb = np.random.random((self.nb, self.d)).astype("float32") self.xq = np.random.random((self.nq, self.d)).astype("float32") - def _create_static(self, storage=None): - if storage is None: - storage = faiss.SVS_FP32 + def _create_static(self): return faiss.IndexSVSVamana( - self.d, self.degree, faiss.METRIC_L2, storage, True + self.d, self.degree, faiss.METRIC_L2, faiss.SVS_FP32, True ) - def test_static_construction(self): - """is_static is set on the constructed index""" - index = self._create_static() - self.assertTrue(index.is_static) - - def test_static_add_and_search(self): - """add() builds the static index and search returns shaped output""" - index = self._create_static() - index.add(self.xb) - self.assertTrue(index.is_trained) - self.assertEqual(index.ntotal, self.nb) - - k = 4 - D, I = index.search(self.xq, k) - self.assertEqual(D.shape, (self.nq, k)) - self.assertEqual(I.shape, (self.nq, k)) - def test_static_second_add_throws(self): - """A second add() must raise on a static Vamana index""" index = self._create_static() index.add(self.xb) extra = np.random.random((100, self.d)).astype("float32") @@ -1625,7 +1083,6 @@ def test_static_second_add_throws(self): index.add(extra) def test_static_remove_throws(self): - """remove_ids() must raise on a static Vamana index""" index = self._create_static() index.add(self.xb) ids = np.arange(0, 10, dtype=np.int64) @@ -1634,11 +1091,10 @@ def test_static_remove_throws(self): index.remove_ids(sel) def test_static_serialization(self): - """Serialize/deserialize preserves is_static and search results""" index = self._create_static() index.add(self.xb) - D_before, I_before = index.search(self.xq, 4) + D_before, _ = index.search(self.xq, 4) loaded = faiss.deserialize_index(faiss.serialize_index(index)) self.assertIsInstance(loaded, faiss.IndexSVSVamana) @@ -1649,11 +1105,10 @@ def test_static_serialization(self): np.testing.assert_allclose(D_before, D_after, rtol=1e-4) def test_static_memmapping(self): - """Serialize/deserialize preserves is_static and search results""" index = self._create_static() index.add(self.xb) - D_before, I_before = index.search(self.xq, 4) + D_before, _ = index.search(self.xq, 4) fd, fname = tempfile.mkstemp() os.close(fd) @@ -1676,28 +1131,7 @@ def test_static_memmapping(self): except OSError: pass - def test_static_fp16(self): - """Static Vamana with FP16 storage""" - index = self._create_static(faiss.SVS_FP16) - index.add(self.xb) - self.assertTrue(index.is_trained) - self.assertTrue(index.is_static) - - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - - def test_static_sq8(self): - """Static Vamana with SQ8 storage""" - index = self._create_static(faiss.SVS_SQ8) - index.add(self.xb) - self.assertTrue(index.is_trained) - self.assertTrue(index.is_static) - - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - def test_static_reset_and_readd(self): - """reset() clears the static index so it can be rebuilt via add()""" index = self._create_static() index.add(self.xb) self.assertTrue(index.is_trained) @@ -1711,7 +1145,6 @@ def test_static_reset_and_readd(self): self.assertEqual(index.ntotal, self.nb) def test_static_reconstruct(self): - """reconstruct() returns the original vector for the static path""" index = self._create_static() index.add(self.xb) recons = index.reconstruct(0) @@ -1720,8 +1153,6 @@ def test_static_reconstruct(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSStaticVamanaLVQ(unittest.TestCase): - """Test static Vamana with LVQ storage""" - def setUp(self): self.d = 32 self.nb = 1000 @@ -1736,21 +1167,6 @@ def _create_static_lvq(self): self.d, self.degree, faiss.METRIC_L2, faiss.SVS_LVQ4x4, True ) - def test_static_lvq_add_search(self): - index = self._create_static_lvq() - index.add(self.xb) - self.assertTrue(index.is_static) - self.assertTrue(index.is_trained) - - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - - def test_static_lvq_second_add_throws(self): - index = self._create_static_lvq() - index.add(self.xb) - with self.assertRaises(RuntimeError): - index.add(self.xb) - def test_static_lvq_serialization(self): index = self._create_static_lvq() index.add(self.xb) @@ -1793,8 +1209,6 @@ def test_static_lvq_memmapping(self): @unittest.skipIf(_SKIP_SVS_LL, _SKIP_SVS_LL_REASON) class TestSVSStaticVamanaLeanVec(unittest.TestCase): - """Test static Vamana with LeanVec storage""" - def setUp(self): self.d = 64 self.nb = 5000 @@ -1809,23 +1223,6 @@ def _create_static_leanvec(self): self.d, self.degree, faiss.METRIC_L2, 0, faiss.SVS_LeanVec4x4, True ) - def test_static_leanvec_train_add_search(self): - index = self._create_static_leanvec() - index.train(self.xb) - index.add(self.xb) - self.assertTrue(index.is_static) - self.assertTrue(index.is_trained) - - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) - - def test_static_leanvec_second_add_throws(self): - index = self._create_static_leanvec() - index.train(self.xb) - index.add(self.xb) - with self.assertRaises(RuntimeError): - index.add(self.xb) - def test_static_leanvec_ood(self): """train_with_queries followed by add() builds the static OOD index""" index = self._create_static_leanvec() @@ -1834,8 +1231,7 @@ def test_static_leanvec_ood(self): self.assertTrue(index.is_static) self.assertTrue(index.is_trained) - D, _ = index.search(self.xq, 4) - self.assertEqual(D.shape, (self.nq, 4)) + index.search(self.xq, 4) def test_static_leanvec_serialization(self): index = self._create_static_leanvec() diff --git a/thirdparty/faiss/tests/test_swig_wrapper.py b/thirdparty/faiss/tests/test_swig_wrapper.py index 7f9e868ce..b448e4127 100644 --- a/thirdparty/faiss/tests/test_swig_wrapper.py +++ b/thirdparty/faiss/tests/test_swig_wrapper.py @@ -3,24 +3,12 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -# a few tests of the swig wrapper - import unittest import faiss import numpy as np class TestSWIGWrap(unittest.TestCase): - """various regressions with the SWIG wrapper""" - - def test_size_t_ptr(self): - # issue 1064 - index = faiss.IndexHNSWFlat(10, 32) - - hnsw = index.hnsw - index.add(np.random.rand(100, 10).astype("float32")) - be = np.empty(2, "uint64") - hnsw.neighbor_range(23, 0, faiss.swig_ptr(be), faiss.swig_ptr(be[1:])) def test_id_map_at(self): # issue 1020 @@ -44,12 +32,10 @@ def test_downcast_Refine(self): faiss.IndexScalarQuantizer(10, faiss.ScalarQuantizer.QT_8bit) ) - # serialize and deserialize index2 = faiss.deserialize_index(faiss.serialize_index(index)) assert isinstance(index2, faiss.IndexRefineFlat) - # Verify deserialized index is serializable again index3 = faiss.deserialize_index(faiss.serialize_index(index2)) assert isinstance(index3, faiss.IndexRefineFlat) @@ -82,92 +68,36 @@ def test_int64(self): assert a.dtype == "int64" np.testing.assert_array_equal(a, np.arange(10, dtype="int64")) - # check if it works in an IDMap - idx = faiss.IndexIDMap(faiss.IndexFlatL2(32)) - idx.add_with_ids( - np.random.rand(10, 32).astype("float32"), - np.random.randint(1000, size=10, dtype="int64"), - ) - faiss.vector_to_array(idx.id_map) - - def test_asan(self): - # this test should fail with ASAN - index = faiss.IndexFlatL2(32) - index.this.own(False) # this is a mem leak, should be catched by ASAN - def test_SWIG_version(self): self.assertLess(faiss.swig_version(), 0x050000) def test_attribute_validation(self): - """Test that setting invalid attributes raises AttributeError""" - - # Test IndexPreTransform - the main use case from the issue index = faiss.index_factory(256, "OPQ64,IVF16384,PQ64") - # Should raise AttributeError when trying to set nprobe directly on - # wrapper with self.assertRaises(AttributeError) as cm: index.nprobe = 16 - # Check that the error message contains basic information error_msg = str(cm.exception) self.assertIn("IndexPreTransform", error_msg) self.assertIn("nprobe", error_msg) - # Test with other IVF parameters that should be blocked - with self.assertRaises(AttributeError) as cm: - index.nlist = 8192 - - # Valid attributes should still work - index.verbose = True # This should be allowed + index.verbose = True self.assertEqual(index.verbose, True) - def test_attribute_validation_other_indexes(self): - """Test that other index types allow normal attribute setting""" - - # Test with a regular IndexFlat - should allow most attributes now - index = faiss.IndexFlatL2(10) - - # Valid attributes should work - index.verbose = False - self.assertEqual(index.verbose, False) - - def test_rabitq(self): - """Test that other index types allow normal attribute setting""" - - # Test with a regular IndexFlat - should allow most attributes now - index = faiss.IndexRaBitQ(10) - # Valid attributes should work - index.qb = 4 - index.centered = True - - with self.assertRaises(AttributeError): - index.centered2 = False - def test_ivfsq_turboq_search_parameters(self): params = faiss.IVFSQTurboQSearchParameters() self.assertEqual(params.qb, 0) self.assertFalse(params.int_qjl) - params.qb = 4 - params.int_qjl = True - self.assertEqual(params.qb, 4) - self.assertTrue(params.int_qjl) - - def test_scalar_quantizer_tq_enum_values(self): - # QT_2bit_tq..QT_5bit_tq were added in the TurboQuant commit and must - # be accessible as ScalarQuantizer class attributes (pyi stub regression - # test: they were absent until this fix). + + def test_scalar_quantizer_qtype_values(self): + # qtype is serialized as an int: these values must not change sq = faiss.ScalarQuantizer + self.assertEqual(sq.QT_0bit, 9) self.assertEqual(sq.QT_2bit_tq, 15) self.assertEqual(sq.QT_3bit_tq, 16) self.assertEqual(sq.QT_4bit_tq, 17) self.assertEqual(sq.QT_5bit_tq, 18) - def test_scalar_quantizer_0bit_enum_value(self): - # QT_0bit (centroid-only SQ, for IVF) was likewise absent from the - # pyi stub until this fix. - self.assertEqual(faiss.ScalarQuantizer.QT_0bit, 9) - class TestRevSwigPtr(unittest.TestCase): @@ -193,13 +123,11 @@ def test_exception(self): # an unsupported operation for IndexFlat self.assertRaises(RuntimeError, index.add_with_ids, a, b) - # assert 'add_with_ids not implemented' in str(e) def test_exception_2(self): self.assertRaises( RuntimeError, faiss.index_factory, 12, "IVF256,Flat,PQ8" ) - # assert 'could not parse' in str(e) class TestAddSACodes(unittest.TestCase): @@ -212,8 +140,6 @@ def setUp(self): rng = np.random.default_rng(42) self.xb = rng.random((self.NB, self.D), dtype=np.float32) self.xtrain = rng.random((500, self.D), dtype=np.float32) - # IDMap2 wrapping PQ8x2: outer index stores (id → code) pairs; - # inner PQ8x2 encodes vectors via sa_encode / add_sa_codes. self.index = faiss.index_factory(self.D, "IDMap2,PQ8x2") self.index.train(self.xtrain) @@ -233,21 +159,9 @@ def test_add_sa_codes_int32_ids_stored_correctly(self): stored = faiss.vector_to_array(self.index.id_map) np.testing.assert_array_equal(stored, ids_int64) - def test_add_sa_codes_int64_ids_unchanged(self): - """int64 ids must pass through as-is (np.ascontiguousarray is a no-op - when the array is already int64 and contiguous).""" - codes = self.index.index.sa_encode(self.xb) - - ids = np.arange(self.NB, dtype="int64") + 500 - self.index.add_sa_codes(codes, ids) - - stored = faiss.vector_to_array(self.index.id_map) - np.testing.assert_array_equal(stored, ids) - def test_sa_encode_preallocated_matches_auto_allocated(self): - """sa_encode with a pre-allocated buffer must return the same codes - as the auto-allocated path, exercising both branches of the hoisted - sa_code_size() call.""" + """sa_encode into a caller buffer returns that buffer with the same + codes.""" inner = self.index.index codes_auto = inner.sa_encode(self.xb) @@ -311,24 +225,13 @@ def test_doxygen_comments(self): class TestMapLong2Long(unittest.TestCase): - def test_add_coerces_keys_and_vals(self): - for dtype in (np.int32, np.int64): - with self.subTest(dtype=dtype): - m = faiss.MapLong2Long() - keys = np.array([0, 1, 2, 3, 4], dtype=dtype) - vals = np.array([100, 101, 102, 103, 104], dtype=dtype) - m.add(keys, vals) - for k, v in zip(range(5), range(100, 105)): - self.assertEqual(m.search(k), v) - - def test_search_multiple_coerces_int32_keys(self): + def test_add_and_search_multiple_coerce_int32(self): m = faiss.MapLong2Long() - m.add( - np.arange(5, dtype=np.int64), - np.arange(5, dtype=np.int64) + 300, - ) - result = m.search_multiple(np.array([0, 2, 4], dtype=np.int32)) - np.testing.assert_array_equal(result, [300, 302, 304]) + keys = np.arange(5, dtype=np.int32) + vals = np.arange(5, dtype=np.int32) + 300 + m.add(keys, vals) + result = m.search_multiple(keys) + np.testing.assert_array_equal(result, vals) class TestInvertedListsDowncast(unittest.TestCase): diff --git a/thirdparty/faiss/tests/test_threaded_index.cpp b/thirdparty/faiss/tests/test_threaded_index.cpp index e2464ec03..09d6a8b8e 100644 --- a/thirdparty/faiss/tests/test_threaded_index.cpp +++ b/thirdparty/faiss/tests/test_threaded_index.cpp @@ -103,9 +103,7 @@ TEST(ThreadedIndex, SingleException) { } }; - // Try with threading and without for (bool threaded : {true, false}) { - // clear flags for (auto& idx : idxs) { idx->resetMock(); } @@ -115,10 +113,8 @@ TEST(ThreadedIndex, SingleException) { ti.addIndex(idx.get()); } - // The second index should throw EXPECT_THROW(ti.runOnIndex(fn), TestException); - // Index 0 and 2 should have processed EXPECT_TRUE(idxs[0]->flag); EXPECT_TRUE(idxs[2]->flag); } @@ -141,9 +137,7 @@ TEST(ThreadedIndex, MultipleException) { } }; - // Try with threading and without for (bool threaded : {true, false}) { - // clear flags for (auto& idx : idxs) { idx->resetMock(); } @@ -157,7 +151,6 @@ TEST(ThreadedIndex, MultipleException) { // FaissException EXPECT_THROW(ti.runOnIndex(fn), faiss::FaissException); - // Index 2 should have processed EXPECT_TRUE(idxs[2]->flag); } } @@ -168,10 +161,9 @@ TEST(ThreadedIndex, TestReplica) { int d = 3; int k = 6; - // Try with threading and without - for ([[maybe_unused]] const bool threaded : {true, false}) { + for (const bool threaded : {true, false}) { std::vector> idxs; - faiss::IndexReplicas replica(d); + faiss::IndexReplicas replica(d, threaded); for (int i = 0; i < numReplicas; ++i) { idxs.emplace_back(new MockIndex(d)); @@ -217,7 +209,6 @@ TEST(ThreadedIndex, TestShards) { int n = 10 * numShards; int k = 6; - // Try with threading and without for (bool threaded : {true, false}) { std::vector> idxs; faiss::IndexShards shards(d, threaded); diff --git a/thirdparty/faiss/tests/test_transfer_invlists.cpp b/thirdparty/faiss/tests/test_transfer_invlists.cpp deleted file mode 100644 index 78fcca1b4..000000000 --- a/thirdparty/faiss/tests/test_transfer_invlists.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { - -// parameters to use for the test -int d = 64; -size_t nb = 1000; -size_t nq = 100; -size_t nt = 500; -int k = 10; -int nlist = 40; - -using namespace faiss; - -using idx_t = faiss::idx_t; - -std::vector get_data(size_t nb_in, int seed) { - std::vector x(nb_in * d); - float_randn(x.data(), nb_in * d, seed); - return x; -} - -void test_index_type(const char* factory_string) { - // transfer inverted lists in nslice slices - int nslice = 3; - - /**************************************************************** - * trained reference index - ****************************************************************/ - - std::unique_ptr trained(index_factory(d, factory_string)); - - { - auto xt = get_data(nt, 123); - trained->train(nt, xt.data()); - } - - // sample nq query vectors to check if results are the same - auto xq = get_data(nq, 818); - - /**************************************************************** - * source index - ***************************************************************/ - std::unique_ptr src_index(clone_index(trained.get())); - - { // add some data to source index - auto xb = get_data(nb, 245); - src_index->add(nb, xb.data()); - } - - ParameterSpace().set_index_parameter(src_index.get(), "nprobe", 4); - - // remember reference search result on source index - std::vector Iref(nq * k); - std::vector Dref(nq * k); - src_index->search(nq, xq.data(), k, Dref.data(), Iref.data()); - - /**************************************************************** - * destination index -- should be replaced by source index - ***************************************************************/ - - std::unique_ptr dst_index(clone_index(trained.get())); - - { // initial state: filled in with some garbage - int nb2 = nb + 10; - auto xb = get_data(nb2, 366); - dst_index->add(nb2, xb.data()); - } - - std::vector Inew(nq * k); - std::vector Dnew(nq * k); - - ParameterSpace().set_index_parameter(dst_index.get(), "nprobe", 4); - - // transfer from source to destination in nslice slices - for (int sl = 0; sl < nslice; sl++) { - // so far, the indexes are different - dst_index->search(nq, xq.data(), k, Dnew.data(), Inew.data()); - EXPECT_TRUE(Iref != Inew); - EXPECT_TRUE(Dref != Dnew); - - // range of inverted list indices to transfer - long i0 = sl * nlist / nslice; - long i1 = (sl + 1) * nlist / nslice; - - std::vector data_to_transfer; - { - std::unique_ptr il( - ivflib::get_invlist_range(src_index.get(), i0, i1)); - // serialize inverted lists - VectorIOWriter wr; - write_InvertedLists(il.get(), &wr); - data_to_transfer.swap(wr.data); - } - - // transfer data here from source machine to dest machine - - { - VectorIOReader reader; - reader.data.swap(data_to_transfer); - - // deserialize inverted lists - std::unique_ptr il( - dynamic_cast( - read_InvertedLists(&reader))); - - // swap inverted lists. Block searches here! - { - ivflib::set_invlist_range(dst_index.get(), i0, i1, il.get()); - } - } - } - EXPECT_EQ(dst_index->ntotal, src_index->ntotal); - - // now, the indexes are the same - dst_index->search(nq, xq.data(), k, Dnew.data(), Inew.data()); - EXPECT_TRUE(Iref == Inew); - EXPECT_TRUE(Dref == Dnew); -} - -} // namespace - -TEST(TRANS, IVFFlat) { - test_index_type("IVF40,Flat"); -} - -TEST(TRANS, IVFFlatPreproc) { - test_index_type("PCAR32,IVF40,Flat"); -} diff --git a/thirdparty/faiss/tests/test_transfer_invlists.py b/thirdparty/faiss/tests/test_transfer_invlists.py new file mode 100644 index 000000000..94cf05009 --- /dev/null +++ b/thirdparty/faiss/tests/test_transfer_invlists.py @@ -0,0 +1,77 @@ +# 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. + +"""Inverted list transfer tests.""" + +import unittest + +import numpy as np + +import faiss + +faiss.omp_set_num_threads(4) + +d = 64 +nb = 1000 +nq = 100 +nt = 500 +k = 10 + + +def get_data(n, seed): + return np.random.RandomState(seed).randn(n, d).astype(np.float32) + + +class TestTransferInvlists(unittest.TestCase): + def check_index_type(self, index_key): + nslice = 3 + + trained = faiss.index_factory(d, index_key) + trained.train(get_data(nt, 123)) + + xq = get_data(nq, 818) + + src = faiss.clone_index(trained) + src.add(get_data(nb, 245)) + faiss.ParameterSpace().set_index_parameter(src, "nprobe", 4) + + Dref, Iref = src.search(xq, k) + + # destination index: filled with garbage, replaced by source index + dst = faiss.clone_index(trained) + dst.add(get_data(nb + 10, 366)) + faiss.ParameterSpace().set_index_parameter(dst, "nprobe", 4) + + nlist = faiss.extract_index_ivf(src).nlist + + for sl in range(nslice): + Dnew, Inew = dst.search(xq, k) + self.assertFalse(np.array_equal(Iref, Inew)) + + i0 = sl * nlist // nslice + i1 = (sl + 1) * nlist // nslice + + il = faiss.get_invlist_range(src, i0, i1) + wr = faiss.VectorIOWriter() + faiss.write_InvertedLists(il, wr) + + # transfer data here from source machine to dest machine + + reader = faiss.VectorIOReader() + reader.data = wr.data + + il2 = faiss.read_InvertedLists(reader) + + # swap inverted lists. Block searches here! + faiss.set_invlist_range(dst, i0, i1, il2) + + self.assertEqual(dst.ntotal, src.ntotal) + + Dnew, Inew = dst.search(xq, k) + np.testing.assert_array_equal(Iref, Inew) + np.testing.assert_array_equal(Dref, Dnew) + + def test_ivf_flat_preproc(self): + self.check_index_type("PCAR32,IVF40,Flat") diff --git a/thirdparty/faiss/tests/test_util.h b/thirdparty/faiss/tests/test_util.h index 1ccf59c08..bed2ee838 100644 --- a/thirdparty/faiss/tests/test_util.h +++ b/thirdparty/faiss/tests/test_util.h @@ -25,7 +25,7 @@ struct Tempfilename { } ~Tempfilename() { - if (access(filename.c_str(), F_OK)) { + if (access(filename.c_str(), F_OK) == 0) { unlink(filename.c_str()); } } diff --git a/thirdparty/faiss/tests/test_utils.cpp b/thirdparty/faiss/tests/test_utils.cpp index f297c793f..a156b9574 100644 --- a/thirdparty/faiss/tests/test_utils.cpp +++ b/thirdparty/faiss/tests/test_utils.cpp @@ -7,7 +7,13 @@ #include +#include + +#include + #include +#include +#include #include TEST(TestUtils, get_version) { @@ -17,3 +23,74 @@ TEST(TestUtils, get_version) { EXPECT_EQ(version, faiss::get_version()); } + +// IndexIVFFastScan sizes per-thread LUTs for the largest slice; a smaller +// slice whose size rounds to a smaller capacity must keep the same buffer. +TEST(TestUtils, AlignedTableKeepCapacity) { + faiss::AlignedTable table; + table.keep_capacity = true; + table.resize(3 * 32768); + const uint8_t* ptr = table.get(); + table.resize(2 * 32768); + EXPECT_EQ(ptr, table.get()); + EXPECT_EQ(2 * 32768, table.size()); +} + +TEST(Threading, flat_search_in_parallel_region) { + struct RestoreOpenMP { + int threads = omp_get_max_threads(); + int dynamic = omp_get_dynamic(); +#if _OPENMP >= 200805 + int max_active_levels = omp_get_max_active_levels(); +#else + int nested = omp_get_nested(); +#endif + + ~RestoreOpenMP() { + omp_set_num_threads(threads); + omp_set_dynamic(dynamic); +#if _OPENMP >= 200805 + omp_set_max_active_levels(max_active_levels); +#else + omp_set_nested(nested); +#endif + } + } restore; + omp_set_num_threads(4); + omp_set_dynamic(0); +#if _OPENMP >= 200805 + omp_set_max_active_levels(1); +#else + omp_set_nested(0); +#endif + + constexpr faiss::idx_t nb = 10001; + for (auto metric : {faiss::METRIC_L2, faiss::METRIC_INNER_PRODUCT}) { + SCOPED_TRACE(metric); + const float query = metric == faiss::METRIC_L2 ? 0.0f : 1.0f; + std::vector database(nb, 10.0f); + database.back() = metric == faiss::METRIC_L2 ? 0.0f : 100.0f; + faiss::IndexFlat index(1, metric); + index.add(nb, database.data()); + + float expected_distance; + faiss::idx_t expected_label; + index.search(1, &query, 1, &expected_distance, &expected_label); + ASSERT_EQ(expected_label, nb - 1); + + float distance = -1; + faiss::idx_t label = -1; + int outer_threads = 0; +#pragma omp parallel num_threads(2) + { + if (omp_get_thread_num() == 0) { + outer_threads = omp_get_num_threads(); + omp_set_num_threads(4); + index.search(1, &query, 1, &distance, &label); + } + } + ASSERT_EQ(outer_threads, 2); + EXPECT_EQ(label, expected_label); + EXPECT_EQ(distance, expected_distance); + } +} diff --git a/thirdparty/faiss/tests/test_wheel_smoke.py b/thirdparty/faiss/tests/test_wheel_smoke.py index 322d0e586..56b7f8e03 100644 --- a/thirdparty/faiss/tests/test_wheel_smoke.py +++ b/thirdparty/faiss/tests/test_wheel_smoke.py @@ -29,15 +29,10 @@ class TestImportAndMetadata(unittest.TestCase): """Catch: missing shared libs, broken SWIG, wrong Python ABI.""" def test_version_attribute(self): - assert hasattr(faiss, "__version__") parts = faiss.__version__.split(".") assert len(parts) == 3 assert all(p.isdigit() for p in parts) - def test_compile_options(self): - opts = faiss.get_compile_options() - assert isinstance(opts, str) - class TestOpenMP(unittest.TestCase): """Catch: OpenMP not linked.""" @@ -47,7 +42,6 @@ def test_openmp_threads(self): assert n >= 1 faiss.omp_set_num_threads(2) assert faiss.omp_get_max_threads() == 2 - # Restore faiss.omp_set_num_threads(n) @@ -61,10 +55,7 @@ def test_flat_l2(self): index = faiss.IndexFlatL2(d) index.add(xb) D, I = index.search(xb[:5], 10) - assert I.shape == (5, 10) - # Nearest neighbor of each vector should be itself np.testing.assert_array_equal(I[:, 0], np.arange(5)) - # Self-distance should be ~0 np.testing.assert_allclose(D[:, 0], 0, atol=1e-5) def test_flat_ip(self): @@ -75,7 +66,6 @@ def test_flat_ip(self): index = faiss.IndexFlatIP(d) index.add(xb) D, I = index.search(xb[:5], 10) - assert I.shape == (5, 10) np.testing.assert_array_equal(I[:, 0], np.arange(5)) np.testing.assert_allclose(D[:, 0], 1.0, atol=1e-5) @@ -88,9 +78,7 @@ def test_ivf_pq(self): np.random.seed(42) xb = np.random.random((n, d)).astype("float32") index = faiss.index_factory(d, "IVF32,PQ8") - assert not index.is_trained index.train(xb) - assert index.is_trained index.add(xb) assert index.ntotal == n D, I = index.search(xb[:5], 10) @@ -105,8 +93,6 @@ def test_hnsw(self): index.add(xb) assert index.ntotal == n D, I = index.search(xb[:5], 10) - assert I.shape == (5, 10) - # HNSW should find the vector itself as nearest neighbor np.testing.assert_array_equal(I[:, 0], np.arange(5)) @@ -120,16 +106,9 @@ def test_serialize_deserialize_roundtrip(self): index = faiss.IndexFlatL2(d) index.add(xb) - # Serialize to bytes data = faiss.serialize_index(index) - assert isinstance(data, np.ndarray) - assert data.dtype == np.uint8 - - # Deserialize index2 = faiss.deserialize_index(data) - assert index2.ntotal == 100 - # Results should match D1, I1 = index.search(xb[:3], 5) D2, I2 = index2.search(xb[:3], 5) np.testing.assert_array_equal(I1, I2) @@ -163,6 +142,8 @@ class TestContribImports(unittest.TestCase): def test_contrib_modules(self): import faiss.contrib.datasets import faiss.contrib.evaluation + from faiss.contrib.e_means import NumpyEmeans + assert callable(NumpyEmeans) import faiss.contrib.inspect_tools import faiss.contrib.ivf_tools import faiss.contrib.exhaustive_search @@ -194,7 +175,6 @@ def test_dd_selects_simd_path(self): opts = faiss.get_compile_options() if "DD" not in opts: raise unittest.SkipTest("Not a Dynamic Dispatch build") - # DD builds should select at least AVX2 on modern x86_64 assert ( "AVX2" in opts or "AVX512" in opts ), f"DD build did not select a SIMD path: {opts}" diff --git a/thirdparty/faiss/tests/test_wheel_smoke_gpu.py b/thirdparty/faiss/tests/test_wheel_smoke_gpu.py index a0f8c74fa..937e83994 100644 --- a/thirdparty/faiss/tests/test_wheel_smoke_gpu.py +++ b/thirdparty/faiss/tests/test_wheel_smoke_gpu.py @@ -24,6 +24,7 @@ import numpy as np from packaging.requirements import Requirement from packaging.specifiers import SpecifierSet +from packaging.version import Version import faiss @@ -233,32 +234,64 @@ def test_knn_gpu_use_cuvs(self): @_skip_unless_cuvs_build class TestCuvsCagra(unittest.TestCase): - """Catch: GpuIndexCagra construction + cuVS CAGRA graph build.""" + """Catch: Dataset bindings, CAGRA build/search, and CPU graph import.""" + + def check_cagra(self, binary): + n, d = 512, 19 + random = np.random.RandomState(4321 if binary else 1234) + if binary: + xb = random.randint(0, 2**32, (n, d), dtype=np.uint32).astype("uint8") + else: + xb = random.uniform(-1, 1, (n, d)).astype("float32") + res = faiss.StandardGpuResources() + config = faiss.GpuIndexCagraConfig() + config.build_algo = faiss.graph_build_algo_NN_DESCENT + config.graph_degree = 16 + config.intermediate_graph_degree = 32 + if binary: + index = faiss.GpuIndexBinaryCagra(res, d * 8, config) + imported = faiss.GpuIndexBinaryCagra(res, d * 8, config) + cpu = faiss.IndexBinaryHNSWCagra() + else: + index = faiss.GpuIndexCagra(res, d, faiss.METRIC_L2, config) + imported = faiss.GpuIndexCagra(res, d, faiss.METRIC_L2, config) + cpu = faiss.IndexHNSWCagra() + host = faiss.Dataset.viewHost(xb) + storage = faiss.Dataset.makeDevicePadded(res, host, 0) + index.train(storage) + cpu.base_level_only = True + index.copyTo(cpu) + empty = np.zeros_like(xb) + empty_host = faiss.Dataset.viewHost(empty) + destination = faiss.Dataset.makeDevicePadded(res, empty_host, 0) + imported.copyFrom(cpu, destination) + del cpu + np.testing.assert_array_equal(destination.copyToHost(), xb) + for searched in (index, imported): + self.assertEqual(searched.ntotal, n) + self.assertTrue(searched.isSearchReady()) + distances, labels = searched.search(xb[:8], 1) + self.assertTrue(np.all((labels >= 0) & (labels < n))) + self_hits = labels[:, 0] == np.arange(8) + # Match the C++ Dataset smoke fixtures' accepted threshold. + self.assertGreaterEqual(np.count_nonzero(self_hits), 6) + np.testing.assert_allclose(distances[self_hits], 0, atol=1e-5) + searched.reset() @skip_if_no_gpu def test_gpu_index_cagra(self): - d, n, nq = 32, 2000, 5 - np.random.seed(42) - xb = np.random.random((n, d)).astype("float32") - - res = faiss.StandardGpuResources() - index = faiss.GpuIndexCagra(res, d, faiss.METRIC_L2) - index.train(xb) - # CAGRA is a graph-based index; ntotal reflects the training set. - self.assertEqual(index.ntotal, n) + self.check_cagra(binary=False) - D, I = index.search(xb[:nq], 10) - self.assertEqual(I.shape, (nq, 10)) - # CAGRA is approximate, so allow itself-as-first-NN as the contract. - np.testing.assert_array_equal(I[:, 0], np.arange(nq)) + @skip_if_no_gpu + def test_gpu_index_binary_cagra(self): + self.check_cagra(binary=True) -# Keep in step with the `libcuvs-cu13==.*` pins in -# pyproject-gpu-cuvs.toml. The wheel does not ship that file, so nothing else -# ties the two together. Compared via SpecifierSet, never by string prefix: -# PEP 440 strips the leading zero, so the series pinned as `26.06` installs as -# `26.6.0`. -_RAPIDS_SERIES = SpecifierSet("==26.06.*") +# Keep in step with the libcuvs-cu13 pin in pyproject-gpu-cuvs.toml. The +# wheel does not ship that file, so nothing else ties the two together. +# Compared via SpecifierSet, never by string prefix: PEP 440 strips a +# leading zero, so a series pinned as `26.06` installs as `26.6.0`. +_RAPIDS_SERIES = SpecifierSet("==26.10.*") # RAPIDS >=26.08 wraps RMM in a per-release inline namespace # (rmm::_RMM_26_8::), so a neighbouring series renames every rmm:: symbol @@ -347,8 +380,13 @@ def test_installed_rapids_matches_the_build_series(self): version = importlib.metadata.version(dist) except importlib.metadata.PackageNotFoundError: self.fail(f"{dist} is declared but not installed") + parsed_version = Version(version) + self.assertFalse( + parsed_version.is_prerelease, + f"{dist} {version} is a prerelease; stable RAPIDS is required", + ) self.assertTrue( - _RAPIDS_SERIES.contains(version), + _RAPIDS_SERIES.contains(parsed_version), f"{dist} {version} is outside the {_RAPIDS_SERIES} series " f"the wheel was built against", ) diff --git a/thirdparty/faiss/tests/test_zerocopy.cpp b/thirdparty/faiss/tests/test_zerocopy.cpp index 0df5757bd..17382eb04 100644 --- a/thirdparty/faiss/tests/test_zerocopy.cpp +++ b/thirdparty/faiss/tests/test_zerocopy.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include #include @@ -34,20 +33,6 @@ std::vector make_data(const size_t n, const size_t d, size_t seed) { return database; } -std::vector make_binary_data( - const size_t n, - const size_t d, - size_t seed) { - std::vector database(n * d); - std::mt19937 rng(seed); - std::uniform_int_distribution distrib(0, 255); - - for (size_t i = 0; i < n * d; i++) { - database[i] = distrib(rng); - } - return database; -} - std::unique_ptr make_rabitq_index( const size_t nt, const size_t d, @@ -82,7 +67,6 @@ bool points_into( // on top of the existing Buf1 TEST(TestZeroCopy, zerocopy_flatcodes) { - // generate data const size_t nt = 1000; const size_t nq = 10; const size_t d = 32; @@ -92,32 +76,23 @@ TEST(TestZeroCopy, zerocopy_flatcodes) { std::vector xt2 = make_data(nt, d, 456); std::vector xq = make_data(nq, d, 789); - // ensure that the data is different - ASSERT_NE(xt1, xt2); - - // make index1 and create reference results faiss::IndexFlatL2 index1(d); - index1.train(nt, xt1.data()); index1.add(nt, xt1.data()); std::vector ref_dis_1(k * nq); std::vector ref_ids_1(k * nq); index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data()); - // make index2 and create reference results faiss::IndexFlatL2 index2(d); - index2.train(nt, xt2.data()); index2.add(nt, xt2.data()); std::vector ref_dis_2(k * nq); std::vector ref_ids_2(k * nq); index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data()); - // ensure that the results are different ASSERT_NE(ref_dis_1, ref_dis_2); ASSERT_NE(ref_ids_1, ref_ids_2); - // serialize both in a form of vectors faiss::VectorIOWriter wr1; faiss::write_index(&index1, &wr1); @@ -126,21 +101,17 @@ TEST(TestZeroCopy, zerocopy_flatcodes) { ASSERT_EQ(wr1.data.size(), wr2.data.size()); - // clone a buffer std::vector buffer = wr1.data; - // create a zero-copy index faiss::ZeroCopyIOReader reader(buffer.data(), buffer.size()); auto index1zc = faiss::read_index_up(&reader); ASSERT_NE(index1zc, nullptr); - // perform a search std::vector cand_dis_1(k * nq); std::vector cand_ids_1(k * nq); index1zc->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data()); - // match vs ref1 ASSERT_EQ(ref_ids_1, cand_ids_1); ASSERT_EQ(ref_dis_1, cand_dis_1); @@ -149,138 +120,20 @@ TEST(TestZeroCopy, zerocopy_flatcodes) { buffer[i] = wr2.data[i]; } - // perform a search std::vector cand_dis_2(k * nq); std::vector cand_ids_2(k * nq); index1zc->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data()); - // match vs ref2 - ASSERT_EQ(ref_ids_2, cand_ids_2); - ASSERT_EQ(ref_dis_2, cand_dis_2); - - // overwrite again - for (size_t i = 0; i < buffer.size(); i++) { - buffer[i] = wr1.data[i]; - } - - // perform a search - std::vector cand_dis_3(k * nq); - std::vector cand_ids_3(k * nq); - index1zc->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_3); - ASSERT_EQ(ref_dis_1, cand_dis_3); -} - -TEST(TestZeroCopy, zerocopy_binary_flatcodes) { - // generate data - const size_t nt = 1000; - const size_t nq = 10; - // in bits - const size_t d = 64; - // in bytes - const size_t d8 = (d + 7) / 8; - const size_t k = 25; - - std::vector xt1 = make_binary_data(nt, d8, 123); - std::vector xt2 = make_binary_data(nt, d8, 456); - std::vector xq = make_binary_data(nq, d8, 789); - - // ensure that the data is different - ASSERT_NE(xt1, xt2); - - // make index1 and create reference results - faiss::IndexBinaryFlat index1(d); - index1.train(nt, xt1.data()); - index1.add(nt, xt1.data()); - - std::vector ref_dis_1(k * nq); - std::vector ref_ids_1(k * nq); - index1.search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data()); - - // make index2 and create reference results - faiss::IndexBinaryFlat index2(d); - index2.train(nt, xt2.data()); - index2.add(nt, xt2.data()); - - std::vector ref_dis_2(k * nq); - std::vector ref_ids_2(k * nq); - index2.search(nq, xq.data(), k, ref_dis_2.data(), ref_ids_2.data()); - - // ensure that the results are different - ASSERT_NE(ref_dis_1, ref_dis_2); - ASSERT_NE(ref_ids_1, ref_ids_2); - - // serialize both in a form of vectors - faiss::VectorIOWriter wr1; - faiss::write_index_binary(&index1, &wr1); - - faiss::VectorIOWriter wr2; - faiss::write_index_binary(&index2, &wr2); - - ASSERT_EQ(wr1.data.size(), wr2.data.size()); - - // clone a buffer - std::vector buffer = wr1.data; - - // create a zero-copy index - faiss::ZeroCopyIOReader reader(buffer.data(), buffer.size()); - auto index1zc = faiss::read_index_binary_up(&reader); - - ASSERT_NE(index1zc, nullptr); - - // perform a search - std::vector cand_dis_1(k * nq); - std::vector cand_ids_1(k * nq); - index1zc->search(nq, xq.data(), k, cand_dis_1.data(), cand_ids_1.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_1); - ASSERT_EQ(ref_dis_1, cand_dis_1); - - // overwrite buffer without moving it - for (size_t i = 0; i < buffer.size(); i++) { - buffer[i] = wr2.data[i]; - } - - // perform a search - std::vector cand_dis_2(k * nq); - std::vector cand_ids_2(k * nq); - index1zc->search(nq, xq.data(), k, cand_dis_2.data(), cand_ids_2.data()); - - // match vs ref2 ASSERT_EQ(ref_ids_2, cand_ids_2); ASSERT_EQ(ref_dis_2, cand_dis_2); - - // overwrite again - for (size_t i = 0; i < buffer.size(); i++) { - buffer[i] = wr1.data[i]; - } - - // perform a search - std::vector cand_dis_3(k * nq); - std::vector cand_ids_3(k * nq); - index1zc->search(nq, xq.data(), k, cand_dis_3.data(), cand_ids_3.data()); - - // match vs ref1 - ASSERT_EQ(ref_ids_1, cand_ids_3); - ASSERT_EQ(ref_dis_1, cand_dis_3); } namespace { -// the logic is the following: -// 1. generate a rabitq index, Index1, and create reference results -// 2. serialize it into a std::vector<> buffer, Buf1 -// 3. deserialize Buf1 twice: with a copying reader into Index1C, and with -// the zero-copy feature into Index1ZC -// 4. ensure that Index1C owns its codes while Index1ZC views Buf1 -// 5. ensure that both act as Index1 -// 6. ensure that Index1ZC follows Buf1 if we overwrite a code byte in -// place, while Index1C does not +// Deserialize a rabitq index with a copying reader (owns its codes) and with +// the zero-copy reader (codes view the buffer); both must search like the +// original, and the zero-copy one follows an in-place buffer overwrite. void check_rabitq_zerocopy(const uint8_t nb_bits) { - // generate data const size_t nt = 500; const size_t nq = 10; const size_t d = 32; @@ -289,16 +142,13 @@ void check_rabitq_zerocopy(const uint8_t nb_bits) { const auto index1 = make_rabitq_index(nt, d, nb_bits, 123); const std::vector xq = make_data(nq, d, 789); - // create reference results std::vector ref_dis_1(k * nq); std::vector ref_ids_1(k * nq); index1->search(nq, xq.data(), k, ref_dis_1.data(), ref_ids_1.data()); - // serialize in a form of a vector faiss::VectorIOWriter wr1; faiss::write_index(index1.get(), &wr1); - // clone a buffer std::vector buffer = wr1.data; // create a copying index, it owns its codes @@ -318,14 +168,6 @@ void check_rabitq_zerocopy(const uint8_t nb_bits) { ASSERT_TRUE(points_into( index1zc_rq->codes.data(), index1zc_rq->codes.size(), buffer)); - // match the remaining fields vs index1 - ASSERT_EQ(index1zc_rq->d, index1->d); - ASSERT_EQ(index1zc_rq->ntotal, index1->ntotal); - ASSERT_EQ(index1zc_rq->metric_type, index1->metric_type); - ASSERT_EQ(index1zc_rq->code_size, index1->code_size); - ASSERT_EQ(index1zc_rq->qb, index1->qb); - ASSERT_EQ(index1zc_rq->rabitq.nb_bits, index1->rabitq.nb_bits); - ASSERT_EQ(index1zc_rq->center, index1->center); ASSERT_EQ(index1zc_rq->codes.size(), index1->codes.size()); ASSERT_TRUE( std::equal( @@ -333,7 +175,6 @@ void check_rabitq_zerocopy(const uint8_t nb_bits) { index1zc_rq->codes.data() + index1zc_rq->codes.size(), index1->codes.data())); - // perform a search on both std::vector cand_dis_zc(k * nq); std::vector cand_ids_zc(k * nq); index1zc->search(nq, xq.data(), k, cand_dis_zc.data(), cand_ids_zc.data()); @@ -342,7 +183,6 @@ void check_rabitq_zerocopy(const uint8_t nb_bits) { std::vector cand_ids_c(k * nq); index1c->search(nq, xq.data(), k, cand_dis_c.data(), cand_ids_c.data()); - // match vs ref1 ASSERT_EQ(ref_ids_1, cand_ids_zc); ASSERT_EQ(ref_dis_1, cand_dis_zc); ASSERT_EQ(ref_ids_1, cand_ids_c); @@ -352,9 +192,7 @@ void check_rabitq_zerocopy(const uint8_t nb_bits) { const size_t codes_offset = index1zc_rq->codes.data() - buffer.data(); buffer[codes_offset] ^= 0xFF; - // the zero-copy index follows the buffer, the copying one does not ASSERT_EQ(index1zc_rq->codes[0], buffer[codes_offset]); - ASSERT_NE(index1c_rq->codes[0], index1zc_rq->codes[0]); } } // namespace diff --git a/thirdparty/faiss/tests/torch_test_contrib.py b/thirdparty/faiss/tests/torch_test_contrib.py index 5b255a972..cf8af3ca6 100644 --- a/thirdparty/faiss/tests/torch_test_contrib.py +++ b/thirdparty/faiss/tests/torch_test_contrib.py @@ -14,40 +14,21 @@ class TestTorchUtilsCPU(unittest.TestCase): - # tests add, search def test_lookup(self): d = 128 index = faiss.IndexFlatL2(d) - # Add to CPU index with torch CPU xb_torch = torch.rand(10000, d) index.add(xb_torch) - # Test reconstruct - y_torch = index.reconstruct(10) - self.assertTrue(torch.equal(y_torch, xb_torch[10])) - - # Add to CPU index with numpy CPU - xb_np = torch.rand(500, d).numpy() - index.add(xb_np) - self.assertEqual(index.ntotal, 10500) - - y_np = np.zeros(d, dtype=np.float32) - index.reconstruct(10100, y_np) - self.assertTrue(np.array_equal(y_np, xb_np[100])) - - # Search with np cpu xq_torch = torch.rand(10, d, dtype=torch.float32) d_np, I_np = index.search(xq_torch.numpy(), 5) - # Search with torch cpu d_torch, I_torch = index.search(xq_torch, 5) - # The two should be equivalent self.assertTrue(np.array_equal(d_np, d_torch.numpy())) self.assertTrue(np.array_equal(I_np, I_torch.numpy())) - # Search with np cpu using pre-allocated arrays d_np_input = np.zeros((10, 5), dtype=np.float32) I_np_input = np.zeros((10, 5), dtype=np.int64) index.search(xq_torch.numpy(), 5, d_np_input, I_np_input) @@ -55,7 +36,6 @@ def test_lookup(self): self.assertTrue(np.array_equal(d_np, d_np_input)) self.assertTrue(np.array_equal(I_np, I_np_input)) - # Search with torch cpu using pre-allocated arrays d_torch_input = torch.zeros(10, 5, dtype=torch.float32) I_torch_input = torch.zeros(10, 5, dtype=torch.int64) index.search(xq_torch, 5, d_torch_input, I_torch_input) @@ -63,7 +43,6 @@ def test_lookup(self): self.assertTrue(np.array_equal(d_torch_input.numpy(), d_np)) self.assertTrue(np.array_equal(I_torch_input.numpy(), I_np)) - # tests train, add_with_ids def test_train_add_with_ids(self): d = 32 nlist = 5 @@ -73,20 +52,11 @@ def test_train_add_with_ids(self): xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) - # Test add_with_ids with torch cpu ids = torch.arange(1000, 1000 + xb.shape[0], dtype=torch.int64) index.add_with_ids(xb, ids) _, I = index.search(xb[10:20], 1) self.assertTrue(torch.equal(I.view(10), ids[10:20])) - # Test add_with_ids with numpy - index.reset() - index.train(xb.numpy()) - index.add_with_ids(xb.numpy(), ids.numpy()) - _, I = index.search(xb.numpy()[10:20], 1) - self.assertTrue(np.array_equal(I.reshape(10), ids.numpy()[10:20])) - - # tests reconstruct, reconstruct_n def test_reconstruct(self): d = 32 index = faiss.IndexFlatL2(d) @@ -94,35 +64,28 @@ def test_reconstruct(self): xb = torch.rand(100, d, dtype=torch.float32) index.add(xb) - # Test reconstruct with torch cpu (native return) y = index.reconstruct(7) self.assertTrue(torch.equal(xb[7], y)) - # Test reconstruct with numpy output provided y = np.empty(d, dtype=np.float32) index.reconstruct(11, y) self.assertTrue(np.array_equal(xb.numpy()[11], y)) - # Test reconstruct with torch cpu output providesd y = torch.empty(d, dtype=torch.float32) index.reconstruct(12, y) self.assertTrue(torch.equal(xb[12], y)) - # Test reconstruct_n with torch cpu (native return) y = index.reconstruct_n(10, 10) self.assertTrue(torch.equal(xb[10:20], y)) - # Test reconstruct with numpy output provided y = np.empty((10, d), dtype=np.float32) index.reconstruct_n(20, 10, y) self.assertTrue(np.array_equal(xb.cpu().numpy()[20:30], y)) - # Test reconstruct_n with torch cpu output provided y = torch.empty(10, d, dtype=torch.float32) index.reconstruct_n(40, 10, y) self.assertTrue(torch.equal(xb[40:50].cpu(), y)) - # tests assign def test_assign(self): d = 32 index = faiss.IndexFlatL2(d) @@ -132,30 +95,19 @@ def test_assign(self): index_ref = faiss.IndexFlatL2(d) index_ref.add(xb.numpy()) - # Test assign with native cpu output xq = torch.rand(10, d, dtype=torch.float32) labels = index.assign(xq, 5) - labels_ref = index_ref.assign(xq.cpu(), 5) - - self.assertTrue(torch.equal(labels, labels_ref)) - - # Test assign with np input - labels = index.assign(xq.numpy(), 5) labels_ref = index_ref.assign(xq.numpy(), 5) - self.assertTrue(np.array_equal(labels, labels_ref)) + self.assertTrue(np.array_equal(labels.numpy(), labels_ref)) - # Test assign with numpy output provided labels = np.empty((xq.shape[0], 5), dtype="int64") index.assign(xq.numpy(), 5, labels) self.assertTrue(np.array_equal(labels, labels_ref)) - # Test assign with torch cpu output provided labels = torch.empty(xq.shape[0], 5, dtype=torch.int64) index.assign(xq, 5, labels) - labels_ref = index_ref.assign(xq, 5) - self.assertTrue(torch.equal(labels, labels_ref)) + self.assertTrue(np.array_equal(labels.numpy(), labels_ref)) - # tests remove_ids def test_remove_ids(self): # only implemented for cpu index + numpy at the moment d = 32 @@ -172,11 +124,9 @@ def test_remove_ids(self): ids_remove = np.array([1010], dtype=np.int64) index.remove_ids(ids_remove) - # We should find this y = index.reconstruct(1011) self.assertTrue(np.array_equal(xb[11].numpy(), y)) - # We should not find this with self.assertRaises(RuntimeError): y = index.reconstruct(1010) @@ -185,7 +135,6 @@ def test_remove_ids(self): with self.assertRaises(AssertionError): index.remove_ids(ids_remove) - # tests update_vectors def test_update_vectors(self): d = 32 quantizer_np = faiss.IndexFlatL2(d) @@ -221,7 +170,6 @@ def test_update_vectors(self): self.assertTrue(np.array_equal(D_np, D_torch.numpy())) self.assertTrue(np.array_equal(I_np, I_torch.numpy())) - # tests range_search def test_range_search(self): torch.manual_seed(10) d = 32 @@ -229,19 +177,16 @@ def test_range_search(self): xb = torch.rand(100, d, dtype=torch.float32) index.add(xb) - # torch cpu as ground truth thresh = 2.9 xq = torch.rand(10, d, dtype=torch.float32) lims, D, I = index.range_search(xq, thresh) - # compare against np lims_np, D_np, I_np = index.range_search(xq.numpy(), thresh) self.assertTrue(np.array_equal(lims.numpy(), lims_np)) self.assertTrue(np.array_equal(D.numpy(), D_np)) self.assertTrue(np.array_equal(I.numpy(), I_np)) - # tests search_and_reconstruct def test_search_and_reconstruct(self): d = 32 nlist = 10 @@ -253,22 +198,18 @@ def test_search_and_reconstruct(self): xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) - # different set xb = torch.rand(500, d, dtype=torch.float32) index.add(xb) - # torch cpu as ground truth xq = torch.rand(10, d, dtype=torch.float32) D, I, R = index.search_and_reconstruct(xq, k) - # compare against numpy D_np, I_np, R_np = index.search_and_reconstruct(xq.numpy(), k) self.assertTrue(np.array_equal(D.numpy(), D_np)) self.assertTrue(np.array_equal(I.numpy(), I_np)) self.assertTrue(np.array_equal(R.numpy(), R_np)) - # numpy input values D_input = np.zeros((xq.shape[0], k), dtype=np.float32) I_input = np.zeros((xq.shape[0], k), dtype=np.int64) R_input = np.zeros((xq.shape[0], k, d), dtype=np.float32) @@ -279,7 +220,6 @@ def test_search_and_reconstruct(self): self.assertTrue(np.array_equal(I.numpy(), I_input)) self.assertTrue(np.array_equal(R.numpy(), R_input)) - # torch input values D_input = torch.zeros(xq.shape[0], k, dtype=torch.float32) I_input = torch.zeros(xq.shape[0], k, dtype=torch.int64) R_input = torch.zeros(xq.shape[0], k, d, dtype=torch.float32) @@ -303,20 +243,17 @@ def test_search_preassigned(self): index.quantizer.reset() index.quantizer.add(np.zeros((20, 32), dtype="float32")) - # test numpy codepath Dq, Iq = quantizer.search(ds.get_queries(), 4) Dref2, Iref2 = index.search_preassigned(ds.get_queries(), 10, Iq, Dq) np.testing.assert_array_equal(Iref, Iref2) np.testing.assert_array_equal(Dref, Dref2) - # test torch codepath xq = torch.from_numpy(ds.get_queries()) Dq, Iq = quantizer.search(xq, 4) Dref2, Iref2 = index.search_preassigned(xq, 10, Iq, Dq) np.testing.assert_array_equal(Iref, Iref2.numpy()) np.testing.assert_array_equal(Dref, Dref2.numpy()) - # tests sa_encode, sa_decode def test_sa_encode_decode(self): d = 16 index = faiss.IndexScalarQuantizer(d, faiss.ScalarQuantizer.QT_8bit) @@ -324,12 +261,10 @@ def test_sa_encode_decode(self): xb = torch.rand(1000, d, dtype=torch.float32) index.train(xb) - # torch cpu as ground truth nq = 10 xq = torch.rand(nq, d, dtype=torch.float32) encoded_torch = index.sa_encode(xq) - # numpy cpu encoded_np = index.sa_encode(xq.numpy()) self.assertTrue(np.array_equal(encoded_torch.numpy(), encoded_np)) @@ -341,18 +276,16 @@ def test_sa_encode_decode(self): torch.equal(decoded_torch, torch.from_numpy(decoded_np)) ) - # torch cpu as output parameter encoded_torch_param = torch.zeros(nq, d, dtype=torch.uint8) index.sa_encode(xq, encoded_torch_param) - self.assertTrue(torch.equal(encoded_torch, encoded_torch)) + self.assertTrue(torch.equal(encoded_torch, encoded_torch_param)) decoded_torch_param = torch.zeros(nq, d, dtype=torch.float32) index.sa_decode(encoded_torch, decoded_torch_param) self.assertTrue(torch.equal(decoded_torch, decoded_torch_param)) - # np as output parameter encoded_np_param = np.zeros((nq, d), dtype=np.uint8) index.sa_encode(xq.numpy(), encoded_np_param) @@ -372,15 +305,10 @@ def test_non_contiguous(self): with self.assertRaises(AssertionError): index.add(xb) - # disabled since we now accept non-contiguous arrays - # with self.assertRaises(ValueError): - # index.add(xb.numpy()) - class TestClustering(unittest.TestCase): def test_python_kmeans(self): - """Test the python implementation of kmeans""" ds = datasets.SyntheticDataset(32, 10000, 0, 0) x = ds.get_train() @@ -398,8 +326,6 @@ def test_python_kmeans(self): centroids = centroids.numpy() err2 = faiss.knn(xt, centroids, 1)[0].sum() - # 33498.332 33380.477 - # print(err, err2) 1/0 self.assertLess(err2, err * 1.1) diff --git a/thirdparty/faiss/tests/torch_test_dino_streaming.py b/thirdparty/faiss/tests/torch_test_dino_streaming.py new file mode 100644 index 000000000..319081f03 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_dino_streaming.py @@ -0,0 +1,157 @@ +# 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. + +"""CUDA ownership and read-ahead checks for the faithful SSD prefetcher.""" + +from contextlib import closing +import importlib.util +from pathlib import Path +import tempfile +import unittest + +import numpy as np +import torch + + +def load(name): + try: + return importlib.import_module(name) + except ImportError: + pass + path = Path(__file__).resolve().parents[1] / "benchs/e_means" / (name + ".py") + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +DinoBvecs = load("dino_data").DinoBvecs +_ssd = load("ssd_streaming") +SSDRowSource, SSDPrefetch = _ssd.SSDRowSource, _ssd.SSDPrefetch + + +@unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") +class TestDinoStreaming(unittest.TestCase): + def source(self, data): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + root = Path(directory.name) + chunks = root / "chunked_base_10B" + chunks.mkdir() + split = len(data) // 3 + for name, rows in (("00", data[:split]), ("01", data[split:])): + packed = np.empty((len(rows), data.shape[1] + 4), dtype=np.uint8) + packed[:, :4] = np.frombuffer(data.shape[1].to_bytes(4, "little"), dtype=np.uint8) + packed[:, 4:] = rows + packed.tofile(chunks / (name + ".bvecs")) + reader = DinoBvecs(root, n=len(data)) + source = SSDRowSource(reader.paths, reader.d, 0, reader.n, header_bytes=4) + self.addCleanup(source.close) + return source + + def loader(self, source, batch_size): + return SSDPrefetch( + source, "cuda", batch_size, n_prefetch=2, + chunk_bytes=batch_size * source.row_bytes, + ram_budget_bytes=4 * batch_size * source.d, + read_threads=1, extract_threads=1, + ) + + def test_nondefault_stream_order_dtype_and_logical_tails(self): + data = np.random.RandomState(8).randint(0, 256, (37, 8), dtype=np.uint8) + source = self.source(data) + consumer = torch.cuda.Stream() + mean = torch.from_numpy(np.arange(8, dtype=np.float32)).to("cuda") + consumer.wait_stream(torch.cuda.current_stream()) + for sequential in (False, True): + loader = self.loader(source, 10) + order = loader.order(9) + outputs = [] + with torch.cuda.stream(consumer): + with closing(loader.batches( + order, sequential=sequential, + mean=mean if sequential else None, + scale=2.0 if sequential else None, + )) as iterator: + for rows in iterator: + self.assertEqual(rows.dtype, torch.float32) + outputs.append(rows.clone()) + consumer.synchronize() + self.assertEqual([len(x) for x in outputs], [10, 10, 10, 7]) + expected = torch.from_numpy(data if sequential else data[order]).float() + if sequential: + expected = (expected - mean.cpu()) / 2.0 + torch.testing.assert_close(torch.cat(outputs).cpu(), expected, rtol=0, atol=0) + + def test_early_close_preserves_owned_output(self): + data = np.arange(37 * 8, dtype=np.uint16).astype(np.uint8).reshape(37, 8) + source = self.source(data) + loader = self.loader(source, 10) + consumer = torch.cuda.Stream() + with torch.cuda.stream(consumer): + iterator = loader.batches(sequential=True) + first = next(iterator) + copied = first.clone() + iterator.close() + retained = first.clone() + consumer.synchronize() + torch.testing.assert_close(copied.cpu(), torch.from_numpy(data[:10]).float()) + torch.testing.assert_close(retained, copied) + np.testing.assert_array_equal(source.read(10, 14), data[10:14]) + + def test_fractional_pass_stops_reads_and_keeps_batch_tail(self): + data = np.arange(37 * 8, dtype=np.uint16).astype(np.uint8).reshape(37, 8) + source = self.source(data) + for count in (0, 7, 23, 37): + with self.subTest(rows=count): + loader = self.loader(source, 10) + order = loader.order(9)[:count] + requests = [] + original = loader.fill_window + + def record(request, out, *, original=original, requests=requests): + requests.append(request.copy()) + original(request, out) + + loader.fill_window = record + with closing(loader.batches(order)) as iterator: + outputs = [rows.clone() for rows in iterator] + torch.cuda.synchronize() + self.assertEqual( + [len(rows) for rows in outputs], + [min(10, count - start) for start in range(0, count, 10)], + ) + if count: + np.testing.assert_array_equal( + np.concatenate(requests), order + ) + torch.testing.assert_close( + torch.cat(outputs).cpu(), + torch.from_numpy(data[order]).float(), rtol=0, atol=0, + ) + else: + self.assertEqual(requests, []) + self.assertEqual(loader.stats["bytes_read"], 0) + + def test_read_ahead_exception_propagates(self): + data = np.zeros((37, 8), dtype=np.uint8) + source = self.source(data) + loader = self.loader(source, 10) + original = source.read_views + + def fail(begin, end, buffer): + if begin >= loader.batch_size: + raise OSError("injected read failure") + return original(begin, end, buffer) + + source.read_views = fail + with self.assertRaisesRegex(OSError, "injected read failure"): + with closing(loader.batches(sequential=True)) as iterator: + for rows in iterator: + rows.sum() + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means.py b/thirdparty/faiss/tests/torch_test_e_means.py new file mode 100644 index 000000000..4b1956eda --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means.py @@ -0,0 +1,4751 @@ +# 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 math +import unittest +import tempfile +import importlib.util +import datetime +import subprocess +import sys +import time +from pathlib import Path +from unittest import mock + +import torch +import numpy as np + +from faiss.contrib.e_means import DistributedEmeans, DistributedNumpyEmeans, NumpyEmeans +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.e_means_torch import Emeans +from faiss.contrib.e_means import torch_backend +from faiss.contrib.e_means.e_means import _epoch_seed +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer +from faiss.contrib.e_means import e_means_torch as e_means +from e_means_test_utils import ( + EmeansReferenceContracts, backend_class, native_options, highest_fp32, known_torch_centroids, +) + +TRITON_CUDA = (torch.cuda.is_available() and not torch.version.hip + and torch.cuda.get_device_capability() >= (8, 0) + and importlib.util.find_spec("triton") is not None) +FP8_CUDA = (TRITON_CUDA and torch.cuda.get_device_capability() + in ((9, 0), (10, 0), (10, 3))) +INT8_CUDA = (TRITON_CUDA and torch.cuda.get_device_capability() + in ((8, 0), (9, 0), (10, 0))) + + +def _cpu_gloo_replica(rank, rendezvous, numpy_state=False): + import torch.distributed as dist + from faiss.contrib.e_means.e_means_distributed import _combine + + torch.set_num_threads(1) + dist.init_process_group( + "gloo", + init_method=rendezvous, + rank=rank, + world_size=2, + timeout=datetime.timedelta(seconds=60), + ) + try: + check = unittest.TestCase() + model_class = DistributedNumpyEmeans if numpy_state else DistributedEmeans + reference_class = NumpyEmeans if numpy_state else Emeans + + def array(values): + return (np.asarray(values, dtype="float32") if numpy_state + else torch.tensor(values, dtype=torch.float32)) + + def host(value): + return np.asarray(value) if numpy_state else value.detach().numpy() + + for transport in ("dense", "sparse", "auto"): + initial = array([[0.0], [2.0], [100.0], [200.0]]) + caller_initial = initial + rank * 1000 + saved_initial = host(caller_initial).copy() + rows = array( + np.array([0.0, 0.25, 2.0, 2.25])[np.arange(10) % 4, None] + ) + args = { + "nepochs": 2, + "batch_size": 4, + "alpha0": 0.5, + "seed": 7, + "capture_assignments": True, + "unused_threshold": 0.1, + } + model = model_class( + 1, 4, group=dist.group.WORLD, transport=transport, **args + ) + reference = reference_class(1, 4, **args) + with check.assertRaisesRegex(ValueError, "divisible"): + model.begin(9, caller_initial) + with check.assertRaises(NotImplementedError): + model.train(rows) + model = model_class( + 1, 4, group=dist.group.WORLD, transport=transport, **args + ) + model.begin(len(rows), caller_initial) + reference.begin(len(rows), initial) + np.testing.assert_array_equal( + host(model.current_centroids()), host(initial) + ) + np.testing.assert_array_equal(host(caller_initial), saved_initial) + if rank: + if numpy_state: + model._split_rng.seed(123456) + else: + model._split_rng.manual_seed(123456) + for epoch in range(2): + for begin in range(0, len(rows), 4): + n = min(4, len(rows) - begin) + start = begin + rank * (n // 2) + local = rows[start : start + n // 2] + if epoch == begin == 0: + labels = (host(local)[:, 0] >= 2).astype("int64") + sums = array( + np.bincount( + labels, weights=host(local)[:, 0], minlength=4 + )[:, None] + ) + counts = array(np.bincount(labels, minlength=4)) + objective = np.float64( + ((host(local)[:, 0] - 2 * labels) ** 2).sum() + ) + if numpy_state: + sums = sums[::-1].copy()[::-1] + sums.flags.writeable = counts.flags.writeable = False + else: + objective = torch.tensor(objective, dtype=torch.float64) + stats = { + "sums": sums, + "counts": counts, + "objective": objective, + "n": len(local), + } + else: + before = host(model.current_centroids()).copy() + if rank == 0 and len(local) > 1: + partial = model.accumulate(local[:1]) + assert partial["n"] == 1 and partial["sums"] is None + assert partial["counts"] is None + with check.assertRaisesRegex( + ValueError, "complete the pending" + ): + model.update({}) + np.testing.assert_array_equal( + host(model.current_centroids()), before + ) + stats = model.accumulate(local[1:]) + else: + stats = model.accumulate(local) + if epoch == 1: + supplied = ( + local[1:] + if rank == 0 and len(local) > 1 + else local + ) + labels = ( + ( + ( + host(supplied)[:, None, :] + - before[None, :, :] + ) + ** 2 + ) + .sum(2) + .argmin(1) + ) + np.testing.assert_array_equal( + host(stats["labels"]), labels + ) + stats = { + name: ( + value.copy() if isinstance(value, np.ndarray) + else value.clone() + if isinstance(value, torch.Tensor) + else value + ) + for name, value in stats.items() + } + saved = { + name: host(stats[name]).copy() + for name in ("sums", "counts") + } + with check.assertRaisesRegex( + ValueError, "prescribed batch size" + ): + model.update(dict(stats, n=n)) + model.update(stats) + assert model._epoch_rows == begin + n + for name, value in saved.items(): + np.testing.assert_array_equal(host(stats[name]), value) + reference_stats = reference.accumulate(rows[begin : begin + n]) + if epoch == begin == 0 and reference._batch_removal is not None: + reference._batch_removal[...] = 0 # Caller-owned statistics carry no U. + reference.update(reference_stats) + np.testing.assert_allclose( + host(model.current_centroids()), + host(reference.current_centroids()), + rtol=1e-06, + atol=1e-06, + ) + np.testing.assert_array_equal( + host(model._pass_counts), host(reference._pass_counts) + ) + if model._pass_sums is not None: + np.testing.assert_allclose( + host(model._pass_sums), + host(reference._pass_sums), + rtol=1e-06, + atol=1e-06, + ) + model.end_epoch() + reference.end_epoch() + np.testing.assert_allclose( + float(model._objective), + float(reference._objective), + rtol=1e-06, + atol=1e-06, + ) + np.testing.assert_allclose( + host(model.finalize()), + host(reference.finalize()), + rtol=1e-06, + atol=1e-06, + ) + np.testing.assert_allclose( + host(model.obj), host(reference.obj), rtol=1e-06, atol=1e-06 + ) + assert model.assignments is None + assert model.n_splits == reference.n_splits and model.n_splits >= 2 + final = model.centroids + saved_final = host(final).copy() + del model + np.testing.assert_array_equal(host(final), saved_final) + + class CollectiveFailure(BaseException): + pass + + model = model_class( + 1, + 1, + group=dist.group.WORLD, + transport="dense", + nepochs=1, + batch_size=2, + alpha0=0.5, + ) + initial = array([[0.0]]) + broadcast = dist.broadcast + + def failed_broadcast(*args, **kwargs): + broadcast(*args, **kwargs) + raise CollectiveFailure() + + with mock.patch.object(dist, "broadcast", new=failed_broadcast): + with check.assertRaises(CollectiveFailure): + model.begin(2, initial) + with check.assertRaises(RuntimeError): + model.current_centroids() + model = model_class( + 1, + 1, + group=dist.group.WORLD, + transport="dense", + nepochs=1, + batch_size=2, + alpha0=0.5, + ) + model.begin(2, initial) + stats = model.accumulate(array([[0.25]])) + with check.assertRaisesRegex(ValueError, "prescribed batch size"): + model.update(dict(stats, n=2)) + np.testing.assert_array_equal( + host(model.current_centroids()), host(initial) + ) + + def failed_combine(*args, **kwargs): + _combine(*args, **kwargs) + raise CollectiveFailure() + + with mock.patch( + "faiss.contrib.e_means.e_means_distributed._combine", + new=failed_combine, + ): + with check.assertRaises(CollectiveFailure): + model.update(stats) + for call in ( + lambda: model.accumulate(array([[0.25]])), + lambda: model.update(stats), + model.end_epoch, + model.finalize, + model.current_centroids, + ): + with check.assertRaises(RuntimeError): + call() + model = model_class( + 1, + 1, + group=dist.group.WORLD, + transport="dense", + nepochs=1, + batch_size=2, + alpha0=0.5, + ) + model.begin(2, initial) + model.update(model.accumulate(array([[0.25]]))) + model.end_epoch() + np.testing.assert_array_equal(host(model.finalize()), [[0.25]]) + for all_empty in (False, True): + counts = array([0.0, 0.0] if rank or all_empty else [2.0, 0.0]) + sums = array([[0.0], [0.0]]) + workspace = (np.empty((2, 2), dtype="float32") if numpy_state + else torch.empty((2, 2))) + ids, combined_sums, combined_counts = _combine( + sums, counts, workspace, dist.group.WORLD, "sparse", 4 + ) + assert isinstance(ids, np.ndarray if numpy_state else torch.Tensor) + assert isinstance(combined_sums, np.ndarray if numpy_state else torch.Tensor) + np.testing.assert_array_equal(host(ids), [] if all_empty else [0]) + np.testing.assert_array_equal( + host(combined_counts), [] if all_empty else [2.0] + ) + assert combined_sums.shape == (0 if all_empty else 1, 1) + dist.barrier() + finally: + dist.destroy_process_group() + + +class TestTorchEmeans(EmeansReferenceContracts, unittest.TestCase): + @unittest.skipUnless(torch.distributed.is_available() and + torch.distributed.is_gloo_available(), "Gloo unavailable") + def test_cpu_gloo_caller_owned_statistics(self): + for numpy_state in (False, True): + with self.subTest(numpy_state=numpy_state), tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes( + _cpu_gloo_replica, + args=("file://" + directory + "/group", numpy_state), + nprocs=2, join=True, start_method="spawn", + ) + + def test_removal_cost_keeps_far_blob_and_revives_dead(self): + rs = np.random.RandomState(0) + x = torch.from_numpy(np.vstack([rs.randn(4000, 4), rs.randn(40, 4) + 20]).astype("float32")) + init = torch.cat([x[:2], x[-1:], torch.full((1, 4), -50.0)]) + for threshold, far_kept in ((None, True), (0.1, False)): + centroids, _ = Emeans(4, 4, nepochs=3, unused_threshold=threshold).train(x, init) + self.assertEqual(bool((centroids - 20).abs().amax(dim=1).min() < 1), far_kept) + self.assertLess(centroids.abs().max().item(), 30) # the dead centroid moved + + def test_removal_moves_every_candidate(self): + # Candidates (R <= 0 or R < 0.3 median) go cheapest first (here every split pays); donors are the other used + # centroids by gain, ties by index. + centers = np.array([[0.], [1.], [-2.], [10.]], dtype='float32') + for cls in (NumpyEmeans, Emeans): + with self.subTest(cls=cls.__name__): + model = cls(1, 4, nepochs=1, batch_size=4) + model.begin(4, centers if cls is NumpyEmeans else torch.from_numpy(centers)) + sources, victims = model._choose_removal_splits( + np.array([1., 100., 0., 100.]), np.ones(4), np.array([1., 3., 2., 4.])) + np.testing.assert_array_equal(victims, [2, 0]) + np.testing.assert_array_equal(sources, [3, 1]) + sources, victims = model._choose_removal_splits( + np.array([0., 0., 0., 100.]), np.array([1., 1., 1., 0.]), np.ones(4)) + self.assertIsNone(sources) # every used centroid is a candidate: no donor + self.assertIsNone(victims) + + def test_removal_moves_only_pairs_that_pay(self): + # A pair moves only if (2/pi)|U_donor| > R_candidate, or R_candidate <= 0. + centers = np.array([[0.], [.1], [5.], [10.], [20.], [30.]], dtype='float32') + removal = np.array([1., 2., 100., 100., 100., 100.]) + for cls in (NumpyEmeans, Emeans): + with self.subTest(cls=cls.__name__): + model = cls(1, 6, nepochs=1, batch_size=6) + model.begin(6, centers if cls is NumpyEmeans else torch.from_numpy(centers)) + sources, victims = model._choose_removal_splits( + removal, np.ones(6), np.array([1., 1., 10., 2., 1., 1.])) + np.testing.assert_array_equal(victims, [0]) + np.testing.assert_array_equal(sources, [2]) + sources, victims = model._choose_removal_splits( + np.array([0., 2., 100., 100., 100., 100.]), np.ones(6), + np.array([1., 1., .1, .1, 1., 1.])) + np.testing.assert_array_equal(victims, [0]) + np.testing.assert_array_equal(sources, [4]) + sources, victims = model._choose_removal_splits(removal, np.ones(6), np.ones(6)) + self.assertIsNone(sources) + self.assertIsNone(victims) + + def test_profit_prefix_shared_selectors(self): + from types import SimpleNamespace + from faiss.contrib.e_means.sharded_centroids import ( + EmeansShardedCentroids, _partial_removal_donors, + ) + + # FP32 donor keys tie, but FP64 gains straddle the cost. Preserve the + # prefix using the represented norm; reversing the tie distinguishes + # this boundary from the author's unrounded comparison. + a = np.float32(0.9999999403953552) + norms = np.array([0.9999999586579397, 0.9999999606579396]) + b = np.sqrt(norms**2 - float(a)**2).astype('float32') + tie = [[0., 0.], [0., 0.], [a, b[0]], [a, b[1]]] + cost = float(np.float32(2 / np.pi)) + cases = [ + ([1., 2., 3., 4.], [10., 50., 100., 100.], [], []), + ([1., 1., 30., 4.], [5., 6., 100., 100.], [2], [0]), + ([0.] * 4, [-1., 0., 100., 100.], [2, 3], [0, 1]), + (tie, [cost, cost, 100., 100.], [], []), + (tie[:2] + tie[2:][::-1], [cost, cost, 100., 100.], [], []), + ] + model = Emeans(2, 4, nepochs=1, batch_size=4) + for axes, removal, sources, victims in cases: + with self.subTest(removal=removal): + axes = torch.tensor(axes, dtype=torch.float32) + if axes.ndim == 1: + axes = torch.stack((axes, torch.zeros_like(axes)), dim=1) + model._removal_stats = torch.cat((axes, torch.tensor(removal)[:, None]), dim=1) + model._usage = torch.ones(4) + norm = torch.linalg.vector_norm(axes.double(), dim=1) + if removal[0] == cost: + self.assertEqual(norm[2:].float().tolist(), [float(a)] * 2) + unrounded = [False, True] if norm[2] < norm[3] else [True, False] + self.assertEqual(((2 / np.pi) * norm[2:] > cost).tolist(), unrounded) + self.assertEqual(((2 / np.pi) * norm[2:].float().double() > cost).tolist(), [False, False]) + host_s, host_v = model._choose_removal_splits(np.array(removal), np.ones(4), norm.numpy()) + self.assertEqual([] if host_s is None else host_s.tolist(), sources) + self.assertEqual([] if host_v is None else host_v.tolist(), victims) + counter = torch.tensor(7) + v, s, moves = model._removal_pairs(counter) # Actual shared GPU-selector arithmetic on CPU. + self.assertEqual(int(moves), len(sources)) + self.assertEqual(int(counter), 7 + len(sources)) + self.assertEqual(s[:moves].tolist(), sources) + self.assertEqual(v[:moves].tolist(), victims) + scalars = torch.stack((model._removal_stats[:, -1], model._usage, norm.float()), dim=1) + owner = SimpleNamespace(_rank=0, _gather_removal_scalars=lambda: scalars, + _choose_removal_donors=_partial_removal_donors) + s, v = EmeansShardedCentroids._choose_sharded_removal_splits(owner) + self.assertEqual([] if s is None else s.tolist(), sources) + self.assertEqual([] if v is None else v.tolist(), victims) + + @unittest.skipUnless(TRITON_CUDA, 'Triton CUDA required') + def test_device_removal_pairs_match_host_choice(self): + rng = np.random.RandomState(20261119) + for k in (5, 64, 2049): + with self.subTest(k=k): + model = Emeans(4, k, nepochs=1, batch_size=k, assignment_backend='triton') + model.begin(k, torch.from_numpy(rng.randn(k, 4).astype('float32')).cuda()) + model._input_dtype = torch.float32 + stats = rng.randn(k, 5).astype('float32') + stats[rng.rand(k) < .3, -1] = 0 + usage = (rng.rand(k) > .2).astype('float32') + model._removal_stats = torch.from_numpy(stats).cuda() + model._axes = torch.nn.functional.normalize(torch.from_numpy(rng.randn(k, 4).astype('float32')), dim=1).cuda() + model._usage = torch.from_numpy(usage).cuda() + norm = np.linalg.norm(stats[:, :-1].astype('float64'), axis=1) + sources, victims = model._choose_removal_splits(stats[:, -1].astype('float64'), usage, norm) + model._check_splits = torch.zeros((), dtype=torch.int64, device='cuda') + model._removal_check() + v, s, moves = model._check_pairs + n = 0 if sources is None else len(sources) + self.assertEqual(int(moves), n) + self.assertEqual(int(model._check_splits), n) + self.assertEqual(v[:n].tolist(), [] if victims is None else victims.tolist()) + self.assertEqual(s[:n].tolist(), [] if sources is None else sources.tolist()) + + @unittest.skipUnless(TRITON_CUDA, 'Triton CUDA required') + def test_device_removal_membership_and_replay(self): + centers = torch.tensor([[0., 0.], [1., 0.], [10., 0.], [20., 0.]]) + # Name, U, R, usage, independent expected sources/victims. + cases = [ + ('none', [1., 2., 3., 4.], [100.] * 4, [1.] * 4, [], []), + ('finite', [1., 2., 3., 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('finite_replay', [1., 2., 3., 4.], [0., 100., 100., 100.], [1., 0., 1., 0.], [2], [0]), + ('nan', [1., float('nan'), 3., 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('two', [1., 1., float('nan'), 4.], [0., 0., 100., 100.], [1.] * 4, [3, 2], [0, 1]), + ('all_candidates', [1., 2., 3., 4.], [0.] * 4, [1.] * 4, [], []), + ('shortage', [1., 2., 3., 4.], [0., 0., 0., 100.], [1.] * 4, [3], [0]), + ('zero', [1., 0., 3., 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('inf', [1., float('inf'), 3., 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('negative_inf', [1., -float('inf'), 3., 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('nan_unused', [1., 2., float('nan'), 4.], [0., 100., 100., 100.], [1., 1., 0., 0.], [1], [0]), + ('ties', [1., 2., 2., 1.], [0., 100., 100., 100.], [1.] * 4, [1], [0]), + ('unprofitable', [1., 2., 3., 4.], [10., 50., 100., 100.], [1.] * 4, [], []), + ('profitable_prefix', [1., 1., 30., 4.], [5., 6., 100., 100.], [1.] * 4, [2], [0]), + ] + for replay in (False, True): + model = Emeans(2, 4, nepochs=1, batch_size=4, assignment_backend='triton') + model.begin(4, centers.cuda()) + model._input_dtype = torch.float32 + model._check_splits = torch.zeros((), dtype=torch.int64, device='cuda') + model._handover_start(torch.zeros(4, dtype=torch.int64, device='cuda'), centers.cuda(), second=True) + total = 0 + for step, (name, axis, removal, usage, sources, victims) in enumerate(cases, 1): + with self.subTest(replay=replay, case=name): + stats = torch.stack((torch.tensor(axis), torch.zeros(4), torch.tensor(removal)), dim=1) + model._centroids.copy_(centers) + model._removal_stats.copy_(stats) + model._usage.copy_(torch.tensor(usage)) + model._axes.copy_(torch.tensor([[1., 0.]] * 4)) + model._handover['moved_at'].fill_(-1) + model._handover['done'].fill_(step) + norm = torch.linalg.vector_norm(stats[:, :-1].double(), dim=1).numpy() + host_s, host_v = model._choose_removal_splits(np.array(removal), np.array(usage), norm) + self.assertEqual([] if host_s is None else host_s.tolist(), sources) + self.assertEqual([] if host_v is None else host_v.tolist(), victims) + if replay: + model._removal_check_graph() + self.assertTrue(model._check_graph) + else: + model._removal_check() + v, s, moves = model._check_pairs + total += len(sources) + self.assertEqual(int(moves), len(sources)) + self.assertEqual(int(model._check_splits), total) + self.assertEqual(s[:len(sources)].tolist(), sources) + self.assertEqual(v[:len(victims)].tolist(), victims) + self.assertEqual(len(set(sources)), len(sources)) + self.assertEqual(len(set(victims)), len(victims)) + self.assertFalse(set(sources) & set(victims)) + self.assertTrue(all(usage[i] > 0 for i in sources)) + expected = torch.full((4,), -1, dtype=torch.int64) + expected[victims] = step + torch.testing.assert_close(model._handover['moved_at'].cpu(), expected, rtol=0, atol=0) + # Replay must refresh the split effects as well as the pair buffers. + expected_stats = stats.clone() + if sources: + expected_stats[sources] /= 2 + expected_stats[victims] = expected_stats[sources] + torch.testing.assert_close(model._removal_stats.cpu(), expected_stats, + rtol=0, atol=0, equal_nan=True) + model._check_graph = None + model._check_pairs = model._graph_pairs = None + model._check_pool = None + + def test_sharder_hooks_training_and_frozen_closing(self): + import torch.distributed as dist + from faiss.contrib.e_means.sharded_centroids import ( + EmeansShardedCentroids, + ) + + class ObservedSharder(EmeansShardedCentroids): + # CPU seam test: bypass only the production CUDA begin guard. + def begin(self, n, centroids): + QuantizedEmeans.begin(self, n, centroids) + + def _reduce_winners(self, distance, labels, return_score=False): + calls.append("reduce") + return super()._reduce_winners(distance, labels, return_score) + + def _local_assignment(self, rows, prepared, **kwargs): + calls.append("local") + return super()._local_assignment(rows, prepared, **kwargs) + + def _add_owned(self, rows, winner, sums, counts, objective, **kwargs): + calls.append("owned") + return super()._add_owned(rows, winner, sums, counts, objective, **kwargs) + + self.assertFalse(dist.is_initialized()) + with tempfile.TemporaryDirectory() as directory: + dist.init_process_group("gloo", init_method="file://" + directory + "/group", + rank=0, world_size=1) + try: + for frozen in (False, True): + with self.subTest(frozen=frozen), highest_fp32("cpu"): + calls = [] + rows = torch.tensor([[0.], [2.], [10.], [12.]]) + initial = torch.tensor([[0.], [10.]]) + args = dict(nepochs=1, batch_size=2, alpha0=.5, + assignment_chunk_size=1, capture_assignments=True) + model = ObservedSharder(1, 2, group=dist.group.WORLD, + quantizer=None, **args) + reference = Emeans(1, 2, **args) + model.begin(4, initial) + reference.begin(4, initial) + for batch in rows.split(2): + expected = reference.accumulate(batch) + actual = expected if frozen else model.accumulate(batch) + if not frozen: + for key in ("sums", "counts", "objective", "labels"): + torch.testing.assert_close(actual[key], expected[key], rtol=0, atol=0) + model.update(actual) + reference.update(expected) + model.end_epoch() + reference.end_epoch() + if frozen: + distance = (rows[:, None, :] - model._centroids[None, :, :]).square().sum(2) + labels = distance.argmin(1) + sums = torch.zeros_like(initial).index_add_(0, labels, rows) + counts = torch.bincount(labels, minlength=2) + expected = sums / counts[:, None] + actual = model.final_closing_mean(rows.split(2)) + self.assertEqual(model.closing_stats["assignment_mse"], + float(distance.min(1).values.double().mean())) + else: + actual, expected = model.finalize(), reference.finalize() + torch.testing.assert_close(model.obj, reference.obj, rtol=0, atol=0) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + self.assertEqual(calls.count("local"), 4) + self.assertEqual(calls.count("reduce"), 2) + self.assertEqual(calls.count("owned"), 4) + finally: + dist.destroy_process_group() + + @unittest.skipUnless( + TRITON_CUDA + and torch.cuda.get_device_capability() in ((8, 0), (9, 0), (10, 0)), + "qualified INT8 CUDA required", + ) + def test_native_byte_exact_distance_output(self): + from faiss.contrib.e_means.triton_assignment import ( + prepare_int8_centroids, + assign_int8_rows, + ) + + for dtype, offset, representation in ((torch.int8, 0, "int8"), (torch.uint8, 128, "uint8")): + rows = torch.full((1, 8192), offset, dtype=dtype, device="cuda") + c = torch.full((1, 8192), float(offset), device="cuda") + c[:, :1024] -= 128 + c[:, 1024] += 1 + prepared = prepare_int8_centroids(c, representation, validate=False) + normal, labels = assign_int8_rows(rows, *prepared, representation) + output = torch.full((3,), -123, dtype=torch.int64, device="cuda") + exact, exact_labels = assign_int8_rows(rows, *prepared, representation, output[1:-1]) + self.assertEqual(normal.dtype, torch.float32) + self.assertEqual((normal.item(), exact.item()), (2**24, 2**24 + 1)) + self.assertEqual(exact.data_ptr(), output[1:-1].data_ptr()) + self.assertEqual(output[[0, -1]].tolist(), [-123, -123]) + torch.testing.assert_close(labels, exact_labels) + saved = exact.clone() + assign_int8_rows(rows, *prepared, representation) + torch.testing.assert_close(exact, saved, rtol=0, atol=0) + invalid = torch.full((1,), -123, dtype=torch.float16, device="cuda") + with self.assertRaises(ValueError): + assign_int8_rows(rows, *prepared, representation, invalid) + self.assertEqual(invalid.item(), -123) + + @staticmethod + def _fp8_backends(): + from torch_test_e_means_cute import _ready + return ('triton', 'cute') if _ready() else ('triton',) + + _byte_backends = _fp8_backends + + def test_explicit_int8_quantizer_and_scope(self): + x = torch.tensor([[10., 100.], [12., 104.], [14., 108.], [16., 112.]]) + q = Int8Quantizer(2) + with self.assertRaises(RuntimeError): + q.compute_codes(x) + q.train(x) + self.assertEqual((q.code_size, q.scale), (2, 16.)) + self.assertIs(q.to("cpu"), q) + expected = torch.tensor([[-48, -96], [-16, -32], [16, 32], [48, 96]], dtype=torch.int8) + torch.testing.assert_close(q.compute_codes(x), expected) + torch.testing.assert_close(q.decode(expected), x) + torch.testing.assert_close(q.compute_codes(torch.tensor([[1e6, -1e6]])), + torch.tensor([[127, -128]], dtype=torch.int8)) + q.validate(x) + with self.assertRaises(ValueError): + q.validate(torch.full((1, 2), float("nan"))) + self.assertEqual(q.compute_codes(x[:0]).shape, (0, 2)) + for dtype in (torch.float32, torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + q.train(x.to(dtype)) + torch.testing.assert_close(q.shift, torch.tensor([13., 106.]), rtol=0, atol=0) + torch.testing.assert_close(q.compute_codes(x.to(dtype)), expected, rtol=0, atol=0) + torch.testing.assert_close(q.decode(expected), x, rtol=0, atol=0) + q.validate(torch.tensor([[1.e6, -1.e6]])) # Finite outliers clip. + self.assertEqual(q.decode(expected[:0]).shape, (0, 2)) + for method in (q.compute_codes, q.decode): + with self.assertRaises(ValueError): + method(torch.zeros(1, 3)) + q.train(torch.zeros(2, 2)) + self.assertEqual((q.scale, q.exponent), (1., 0)) + for bad in (torch.full((1, 2), float('nan')), torch.full((1, 2), float('inf'))): + with self.assertRaises(ValueError): + q.train(bad) + self.assertFalse(q.is_trained) + with self.assertRaises(RuntimeError): + q.decode(expected) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((8, 0), (9, 0), (10, 0)) + and importlib.util.find_spec("triton") is not None, + "qualified INT8 CUDA required", + ) + def test_native_int8_uint8_and_decoded_training(self): + for backend in self._byte_backends(): + base = torch.tensor([[-4.], [-2.], [4.], [6.]], device="cuda") + q = Int8Quantizer(1) + q.train(base) + for dtype, offset, quantizer in ((torch.int8, 0, None), + (torch.uint8, 128, None), (torch.int8, 0, q)): + with self.subTest(dtype=dtype, calibrated=quantizer is not None): + codes = (base + offset).to(dtype) if quantizer is None else q.compute_codes(base) + initial = base[[0, 2]] + offset + km = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + quantizer=quantizer, + assignment_backend=backend, + assignment_chunk_size=1, + ) + centroids, captured_labels = km.train(codes, initial) + self.assertEqual(km.obj[-1], 8.) + self.assertIs(centroids, km.centroids) + self.assertIs(captured_labels, km.assignments) + torch.testing.assert_close( + km.centroids, + torch.tensor([[-3. + offset], [5. + offset]], device="cuda"), + ) + distance, labels = km.assign(codes) + torch.testing.assert_close(distance, torch.ones(4, device="cuda")) + torch.testing.assert_close(labels, torch.tensor([0, 0, 1, 1], device="cuda")) + self.assertEqual((km.centroids.dtype, distance.dtype, labels.dtype), + (torch.float32, torch.float32, torch.int64)) + self.assertEqual(km.recipe["representation"], str(dtype).removeprefix("torch.")) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((8, 0), (9, 0), (10, 0)) + and importlib.util.find_spec("triton") is not None, + "qualified INT8 CUDA required", + ) + def test_raw_integer_statistics_dtype_and_totals(self): + for dtype, value, cap in ((torch.int8, 127, 131072), (torch.uint8, 255, 65793)): + for n in (0, 7, cap, cap + 1, 262145): + with self.subTest(dtype=dtype, n=n): + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=max(n, 1), + alpha0=0.5, + assignment_backend='triton', + assignment_chunk_size=70001, + ) + model.begin(max(n, 1), torch.tensor([[float(value)]], device='cuda')) + rows = torch.full((n, 1), value, dtype=dtype, device='cuda') + stats = model.accumulate(rows) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), + (torch.int64, torch.int64)) + self.assertEqual(stats['objective'].dtype, torch.float64) + self.assertEqual((stats['sums'].item(), stats['counts'].item(), stats['n']), + (value * n, n, n)) + del model + # Same run: full batch followed by one-row kept tail stays INT64. + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=cap + 1, + alpha0=0.5, + assignment_backend='triton', + assignment_chunk_size=70001, + ) + model.begin(cap + 2, torch.tensor([[float(value)]], device='cuda')) + for n in (cap + 1, 1): + stats = model.accumulate(torch.full((n, 1), value, dtype=dtype, device='cuda')) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), (torch.int64, torch.int64)) + self.assertEqual((stats['sums'].item(), stats['counts'].item()), (value * n, n)) + model.update(stats) + model.end_epoch() + self.assertEqual(model.finalize().item(), float(value)) + + previous, warn = torch.are_deterministic_algorithms_enabled(), torch.is_deterministic_algorithms_warn_only_enabled() + try: + for deterministic in (False, True): + torch.use_deterministic_algorithms(deterministic) + rows = torch.empty(33, 6, dtype=torch.int8, device='cuda')[:, ::2] + rows[::2] = -128 + rows[1::2] = 127 + model = QuantizedEmeans( + 3, + 1, + nepochs=1, + batch_size=33, + alpha0=0.5, + assignment_backend='triton', + assignment_chunk_size=7, + ) + model.begin(33, torch.zeros(1, 3, device='cuda')) + stats = model.accumulate(rows) + truth = rows.cpu().long() + torch.testing.assert_close(stats['sums'].cpu(), truth.sum(0, keepdim=True), rtol=0, atol=0) + self.assertEqual(stats['counts'].item(), 33) + self.assertEqual(stats['objective'].item(), truth.square().sum().item()) + model.update(stats) + model.end_epoch() + model.finalize() + finally: + torch.use_deterministic_algorithms(previous, warn_only=warn) + + @unittest.skipUnless(TRITON_CUDA, "qualified Triton CUDA required") + def test_raw_integer_full_population_accumulation_boundaries(self): + # FP16 is supported on floating targets even when byte assignment is not. + cases = [(torch.float16, 1, 2**24 + 2)] + if INT8_CUDA: + cases += [(torch.int8, -128, 2**24), (torch.uint8, 0, 2**24), + (torch.int8, -128, 2**24 + 1), + (torch.uint8, 255, 2**31 // 255), + (torch.uint8, 255, 2**31 // 255 + 1)] + for dtype, value, n in cases: + for backend in (("triton",) if dtype == torch.float16 else self._byte_backends()): + with self.subTest(dtype=dtype, n=n, backend=backend): + torch.cuda.reset_peak_memory_stats() + start = time.monotonic() + rows = torch.full((n, 1), value, dtype=dtype, device='cuda') + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=n, + alpha0=0.5, + assignment_backend=backend, + assignment_chunk_size=65536, + ) + model.begin(n, torch.tensor([[float(value)]], device='cuda')) + # Both halves fit the small-call bound. Scratch/shift selection + # must still protect the whole prescribed population. + partial = model.accumulate(rows[:n // 2]) + self.assertEqual(partial['n'], n // 2) + self.assertIsNone(partial['sums']) + self.assertIsNone(partial['counts']) + stats = model.accumulate(rows[n // 2:]) + expected_dtype = torch.float32 if dtype == torch.float16 else torch.int64 + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), (expected_dtype, expected_dtype)) + self.assertEqual((stats['sums'].item(), stats['counts'].item()), (value*n, n)) + self.assertEqual(stats['objective'].item(), 0.) + empty = model.accumulate(rows[:0]) + self.assertEqual((empty['sums'].item(), empty['counts'].item(), empty['n']), (value*n, n, n)) + print('raw boundary correctness cost', backend, str(dtype), n, + time.monotonic()-start, 'seconds, peak', torch.cuda.max_memory_allocated(), 'bytes') + del rows, stats, model + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_raw_integer_nonpower_two_closing_division(self): + for backend in self._byte_backends(): + n = 1048577 + for total in (266199830, 132023843, -134153956): + with self.subTest(total=total): + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=n, + alpha0=0.5, + assignment_backend=backend, + ) + model.begin(n, torch.zeros(1, 1, device='cuda')) + stats = dict(sums=torch.tensor([[total]], dtype=torch.int64, device='cuda'), + counts=torch.tensor([n], dtype=torch.int64, device='cuda'), + objective=torch.zeros((), dtype=torch.float64, device='cuda'), n=n) + model.update(stats) + self.assertEqual((model._pass_counts.dtype, model._pass_sums.dtype), + (torch.int64, torch.int64)) + self.assertEqual((model._pass_counts.item(), model._pass_sums.item()), (n, total)) + model.end_epoch() + expected = np.float32(np.float64(total) / np.float64(n)) + self.assertNotEqual(expected, np.float32(np.float32(total) / np.float32(n))) + self.assertNotEqual(expected, np.float32(np.float64(np.float32(total)) / np.float64(n))) + self.assertEqual(model.finalize().item(), float(expected)) + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_encoded_integer_second_exact_keys(self): + from faiss.contrib.e_means.triton_assignment import assign_int8_rows, prepare_int8_centroids + + signed = torch.stack([torch.full((273,), x, dtype=torch.int8) for x in (-128, 0, 127)]).repeat(23, 1) + centers = torch.full((259, 273), 50.) + centers[128] = centers[258] = signed[0].float() + unsigned = torch.full((1, 260), 255, dtype=torch.uint8) + unsigned[0, 0] = 0 + near = torch.zeros((2, 260)) + near[1, 0] = 1 + for rows, centroids in ((signed, centers), (unsigned, near)): + with self.subTest(dtype=rows.dtype): + truth = (rows.long()[:, None] - centroids.long()[None]).square().sum(2) + order = truth.argsort(dim=1, stable=True)[:, :2] + rows, centroids = rows.cuda(), centroids.cuda() + representation = "uint8" if rows.dtype == torch.uint8 else "int8" + prepared, norms = prepare_int8_centroids(centroids, representation) + first = torch.empty(len(rows), dtype=torch.int64, device="cuda") + second, other = torch.empty_like(first), torch.empty_like(first) + _, ids = assign_int8_rows(rows, prepared, norms, representation, first, + second_out=second, second_labels_out=other) + torch.testing.assert_close(torch.stack((first, second), 1).cpu(), + truth.gather(1, order), rtol=0, atol=0) + torch.testing.assert_close(torch.stack((ids, other), 1).cpu(), order, rtol=0, atol=0) + if rows.dtype == torch.uint8: + self.assertGreater(first.item(), 2**24) + self.assertEqual((second - first).item(), 1) + self.assertEqual((second.float() - first.float()).item(), 0) + + model = QuantizedEmeans(260, 2, quantizer=None, assignment_backend="triton", + nepochs=1, batch_size=1) + model.begin(1, near.cuda()) + stats = model.accumulate(unsigned.cuda()) + self.assertEqual(stats["removal"][0, -1].item(), 1.) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_second_completes_selected_ids(self): + from faiss.contrib.e_means.triton_assignment import assign_rows + + rows = torch.full((1, 128), 448., device="cuda") + rows[:, -1] = 0 + centers = torch.full((2, 128), 448., device="cuda") + centers[0, -1], centers[1, -1] = .25, .125 + rows, centers = rows.to(torch.float8_e4m3fn), centers.to(torch.float8_e4m3fn) + second = torch.empty(1, device="cuda") + other = torch.empty(1, dtype=torch.int64, device="cuda") + first, ids = assign_rows(rows, centers, centers.float().square().sum(1), + second_out=second, second_labels_out=other) + self.assertEqual((ids.item(), other.item()), (0, 1)) + self.assertEqual((first.item(), second.item()), (.0625, .015625)) + self.assertEqual((second - first).item(), -.046875) + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_native_bytes_integer_ranking_clipping_and_large_distance(self): + for dtype, offset in ((torch.int8, 0), (torch.uint8, 128)): + for n, k, d in ((2, 3, 17), (3, 257, 32), (65, 513, 129), (2, 3, 257), (1, 2, 43919)): + with self.subTest(dtype=dtype, n=n, k=k, d=d): + g = torch.Generator(device='cuda').manual_seed(n+k+d) + signed = torch.randint(-128, 128, (n, d), device='cuda', dtype=torch.int8, generator=g) + c = torch.randint(-128, 128, (k, d), device='cuda', generator=g).float() + if d == 43919: + signed.fill_(127) + c.fill_(-128) + rows = (signed.int()+offset).to(dtype) + model = self._known_centroids( + c + offset, + model_class=QuantizedEmeans, + assignment_backend='triton', + ) + distance, labels = model.assign(rows) + truth = (rows.cpu().long()[:, None] - (c+offset).cpu().long()[None]).square().sum(2) + torch.testing.assert_close(labels.cpu(), truth.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance.cpu(), truth.min(1).values.float(), rtol=0, atol=0) + if d == 43919: + self.assertGreater(truth[0, 0].item(), 2**31) + model.centroids.fill_(offset) + tied_distance, tied_labels = model.assign(rows) + self.assertTrue(bool((tied_labels == 0).all())) + torch.testing.assert_close(tied_distance.cpu(), + (rows.cpu().long()-offset).square().sum(1).float(), rtol=0, atol=0) + # Begin with actual raw rows, then mutate the exposed closing table + # for a finite rounding/clipping query, not impossible raw totals. + model = QuantizedEmeans( + 257, + 1, + nepochs=1, + batch_size=2, + alpha0=0.5, + assignment_backend='triton', + ) + model.train(torch.full((2, 257), offset, device='cuda', dtype=dtype)) + model.centroids[0, :6] = torch.tensor([-1.5, -.5, .5, 1.5, 200., -200.], device='cuda')+offset + wanted = torch.zeros(1, 257, device='cuda', dtype=torch.int32) + wanted[0, :6] = torch.tensor([-2, 0, 0, 2, 127, -128], device='cuda') + distance, labels = model.assign((wanted+offset).to(dtype)) + self.assertEqual((distance.item(), labels.item()), (0., 0)) + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_native_bytes_typed_tail_lifecycle_and_seed_ownership(self): + for backend in self._byte_backends(): + x = torch.tensor([[.1, -.2], [2.2, .3], [10.3, .4], [12.4, .5], [11.8, .25]], device='cuda') + q = Int8Quantizer(2) + q.train(x) + for dtype, offset, selected_q in ( + (torch.int8, 0, None), + (torch.uint8, 128, None), + (torch.int8, 0, q), + ): + codes = q.compute_codes(x) if selected_q else (x.round()+offset).to(dtype) + initial = x[[0, 2]] if selected_q else codes[[0, 2]].float() + args = dict(nepochs=2, batch_size=2, alpha0=.5, seed=7, quantizer=selected_q, + assignment_backend=backend, assignment_chunk_size=1, capture_assignments=True) + matrix, caller = QuantizedEmeans( + 2, 2, **args + ), QuantizedEmeans(2, 2, **args) + saved = codes.clone() + matrix.train(codes, initial) + caller.begin(len(codes), initial) + for epoch in range(2): + order = torch.randperm( + len(codes), + generator=e_means._torch_generator( + x.device, _epoch_seed(7, epoch) + ), + device=x.device, + ) + for start in range(0, len(codes), 2): + batch = codes[order[start:start+2]] + before = caller.current_centroids().clone() + c = (q.compute_codes(before) if selected_q else + before.round().clamp(offset-128, offset+127).to(dtype)) + oracle = (batch.cpu().long()[:, None]-c.cpu().long()[None]).square().sum(2) + labels = oracle.argmin(1).to(x.device) + distances = oracle.min(1).values.float().to(x.device) + if selected_q: + distances = torch.ldexp(distances, q._distance_exponent) + for position in range(len(batch)): + stats = caller.accumulate(batch[position:position + 1]) + torch.testing.assert_close(caller.current_centroids(), before, rtol=0, atol=0) + if position + 1 < len(batch): + self.assertIsNone(stats['sums']) + self.assertIsNone(stats['counts']) + if epoch == caller.nepochs - 1: + torch.testing.assert_close(stats['labels'], labels[position:position + 1], rtol=0, atol=0) + else: + self.assertNotIn('labels', stats) + expected_dtype = torch.float32 if selected_q else torch.int64 + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), (expected_dtype, expected_dtype)) + sums = torch.zeros_like(stats['sums']) + sums.index_add_(0, labels, q.decode(batch) if selected_q else batch.long()) + torch.testing.assert_close(stats['sums'], sums, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], torch.bincount(labels, minlength=2).to(expected_dtype), rtol=0, atol=0) + torch.testing.assert_close(stats['objective'], distances.double().sum(), rtol=0, atol=0) + caller.update(stats) + caller.end_epoch() + caller.finalize() + torch.testing.assert_close(caller.centroids, matrix.centroids, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(caller.obj, matrix.obj, rtol=0, atol=0) + indices = torch.randperm(len(codes), device=x.device, generator=torch.Generator(device=x.device).manual_seed(7))[:2] + initial = q.decode(codes[indices]) if selected_q else codes[indices].float() + default, explicit = QuantizedEmeans( + 2, 2, **args + ), QuantizedEmeans(2, 2, **args) + default.train(codes) + explicit.train(codes, initial) + torch.testing.assert_close( + default.centroids, explicit.centroids, rtol=0, atol=0 + ) + torch.testing.assert_close( + default.obj, explicit.obj, rtol=0, atol=0 + ) + torch.testing.assert_close(codes, saved, rtol=0, atol=0) + output, before = default.centroids, default.centroids.clone() + del default + torch.testing.assert_close(output, before, rtol=0, atol=0) + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_native_bytes_scaling_revival_and_finite_failure(self): + from faiss.contrib.e_means.quantizer_int8 import separate_splits + + q = Int8Quantizer(2) + q.train(torch.tensor([[8., 8.], [12., 12.]], device='cuda')) + base = torch.tensor([[0., 0.], [3., 2.], [-128., 1.], [127., 1.]], device='cuda') + for offset, selected_q in ((0, None), (128, None), (0, q)): + representation = 'uint8' if offset else 'int8' + donor = q.decode(base) if selected_q else base+offset + child = donor.clone() + untouched = child[:, 1:].clone() + separate_splits(donor, child, representation, selected_q) + encoded = q.compute_codes(child) if selected_q else (child-offset).round().to(torch.int8) + torch.testing.assert_close(encoded[:, 0], torch.tensor([1, 4, -127, 126], dtype=torch.int8, device='cuda'), rtol=0, atol=0) + torch.testing.assert_close(child[:, 1:], untouched, rtol=0, atol=0) + ordinary = donor + (8/q.scale if selected_q else 8) + saved = ordinary.clone() + separate_splits(donor, ordinary, representation, selected_q) + torch.testing.assert_close(ordinary, saved, rtol=0, atol=0) + initial = torch.tensor([[8., 8.], [20., 20.]], device='cuda')+offset + model = QuantizedEmeans( + 2, + 2, + nepochs=1, + batch_size=10, + alpha0=0.5, + seed=7, + assignment_backend='triton', + quantizer=selected_q, + unused_threshold=0, # Synthetic geometry/external-statistics fixture. + ) + model.begin(10, initial) + dtype = torch.int8 if selected_q or not offset else torch.uint8 + # Isolate split geometry without pinning update-check cadence. The + # empty public contribution binds the representation and stays pending + # until a legitimate full external contribution consumes it below. + empty_stats = model.accumulate(torch.empty(0, 2, dtype=dtype, device='cuda')) + self.assertEqual(empty_stats['n'], 0) + model._usage.copy_(torch.tensor([10., 0.], device='cuda')) + origin, mass = model._centroids[0].clone(), model._usage[0].clone() + model._apply_splits(torch.tensor([0], device='cuda'), torch.tensor([1], device='cuda')) + self.assertEqual(model.n_splits, 1) + # U = 0: both copies start at the donor; separation moves the child's coordinate zero. + torch.testing.assert_close(model._centroids[0], origin, rtol=0, atol=0) + torch.testing.assert_close(model._centroids[1, 1:], origin[1:], rtol=0, atol=0) + torch.testing.assert_close(model._usage, (mass/2).expand(2), rtol=0, atol=0) + represented = (q.compute_codes(model._centroids) if selected_q else model._centroids.round()) + self.assertNotEqual(represented[0, 0].item(), represented[1, 0].item()) + stats_dtype = torch.float32 if selected_q else torch.int64 + sums = torch.zeros(2, 2, dtype=stats_dtype, device='cuda') + sums[0] = initial[0].to(stats_dtype)*10 # Ten represented copies at label0. + model.update(dict(sums=sums, counts=torch.tensor([10, 0], dtype=stats_dtype, device='cuda'), + objective=torch.zeros((), dtype=torch.float64, device='cuda'), n=10)) + model.end_epoch() + empty = model._centroids[1].clone() + final = model.finalize() + torch.testing.assert_close(final[1], empty, rtol=0, atol=0) + for backend in self._byte_backends(): + for exponent, encoded in ((75, 2), (-100, 0)): + q = Int8Quantizer(1) + peak = 2. ** (6-exponent) + q.train(torch.tensor([[-peak], [peak]], device='cuda')) + self.assertEqual(q.exponent, exponent) + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=1, + alpha0=0.5, + quantizer=q, + assignment_backend=backend, + ) + model.begin(1, torch.zeros(1, 1, device='cuda')) + codes = torch.tensor([[encoded]], dtype=torch.int8, device='cuda') + stats = model.accumulate(codes) + self.assertEqual(stats['objective'].item(), 2.**-148 if exponent == 75 else 0.) + model.update(stats) + model.end_epoch() + model.finalize() + self.assertEqual(model.assign(codes)[0].item(), 0.) + maximum = torch.finfo(torch.float32).max + q = Int8Quantizer(1) + q.train(torch.tensor([[-maximum], [maximum]], device='cuda')) + self.assertEqual(q.exponent, -122) + donor = torch.tensor([[.99*maximum]], device='cuda')*(1-1.e-4) + child = torch.tensor([[.99*maximum]], device='cuda')*(1+1.e-4) + saved = child.clone() + torch.testing.assert_close(q.compute_codes(donor), q.compute_codes(child), rtol=0, atol=0) + separate_splits(donor, child, 'int8', q) + torch.testing.assert_close(child, saved, rtol=0, atol=0) + # A generated split beyond FP32 must fail before either centroid or + # mass is written. Public training cannot isolate this finite limit; + # this minimal existing split primitive probe makes no cache/API claim. + model = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=2, + alpha0=0.5, + assignment_backend='triton', + unused_threshold=0.1, + ) + model.begin(2, torch.full((2, 1), maximum, device='cuda')) + model.accumulate(torch.empty(0, 1, dtype=torch.int8, device='cuda')) + # A long axis on a light donor puts one copy beyond FP32. + model._removal_stats[0, 0], model._usage[0] = maximum, 1e-30 + saved_centroids, saved_usage = model._centroids.clone(), model._usage.clone() + with self.assertRaisesRegex(ValueError, 'finite'): + model._apply_splits(torch.tensor([0], device='cuda'), torch.tensor([1], device='cuda')) + torch.testing.assert_close(model._centroids, saved_centroids, rtol=0, atol=0) + torch.testing.assert_close(model._usage, saved_usage, rtol=0, atol=0) + del model + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA required") + def test_native_bytes_current_stream_decode_and_schema(self): + for backend in self._byte_backends(): + current = torch.cuda.current_device() + # One-GPU execution still checks caller streams, but only >=2 GPUs + # exercise a genuinely noncurrent tensor device. + device = torch.device('cuda', 1 if torch.cuda.device_count() >= 2 and current == 0 else 0) + q = Int8Quantizer(2) + q.train(torch.tensor([[-1.0, -1.0], [1.0, 1.0]])) + q.to(device) + QuantizedEmeans( + 2, 1, quantizer=Int8Quantizer(2), assignment_backend=backend + ) + on_cpu = Int8Quantizer(2) + on_cpu.train(torch.zeros(2, 2)) + for selected_q in (None, q): + dtype = torch.int8 if selected_q else torch.uint8 + known = torch.tensor([[0, 0], [64, 64]], dtype=dtype, device=device) if selected_q else torch.tensor([[128, 128], [129, 129]], dtype=dtype, device=device) + initial = q.decode(known) if selected_q else known.float() + model = QuantizedEmeans( + 2, + 2, + nepochs=1, + batch_size=2, + alpha0=0.5, + quantizer=selected_q, + assignment_backend=backend, + ) + model.train(known, initial) + model.assign(known) + torch.cuda.synchronize(device) + rows = torch.empty(2, 4, dtype=dtype, device=device)[:, ::2] + producer, consumer = torch.cuda.Stream(device=device), torch.cuda.Stream(device=device) + with torch.cuda.stream(producer): + torch.cuda._sleep(50_000_000) + rows.copy_(known) + consumer.wait_stream(producer) + with torch.cuda.stream(consumer): + distance, labels = model.assign(rows) + decoded = q.decode(rows) if selected_q else rows.float() + torch.cuda.current_stream(device).wait_stream(consumer) + torch.testing.assert_close(distance, torch.zeros(2, device=device), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.tensor([0, 1], device=device), rtol=0, atol=0) + torch.testing.assert_close(decoded, initial, rtol=0, atol=0) + torch.testing.assert_close(rows, known, rtol=0, atol=0) + model = QuantizedEmeans( + 2, + 2, + nepochs=1, + batch_size=2, + alpha0=0.5, + quantizer=selected_q, + assignment_backend=backend, + ) + model.begin(2, initial) + previous = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode('error') + model.update(model.accumulate(known)) + if selected_q: + q.decode(known) + finally: + torch.cuda.set_sync_debug_mode(previous) + model.end_epoch() + model.finalize() + self.assertEqual(torch.cuda.current_device(), current) + if selected_q: + model.centroids[0, 0] = float('nan') + with self.assertRaisesRegex(ValueError, 'finite'): + model.assign(known) + constant = Int8Quantizer(1) + constant.train(torch.full((2, 1), 255.0, device=device)) + model = QuantizedEmeans(1, 1, nepochs=1, batch_size=2, alpha0=.5, + quantizer=constant, assignment_backend=backend) + model.begin(2, torch.full((1, 1), 255., device=device)) + stats = model.accumulate(constant.compute_codes(torch.full((2, 1), 255., device=device))) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), (torch.float32, torch.float32)) + self.assertEqual((stats['sums'].item(), stats['counts'].item()), (510., 2.)) + model.update(stats) + model.end_epoch() + self.assertEqual(model.finalize().item(), 255.0) + extreme = Int8Quantizer(1) + extreme.train(torch.tensor([[-(2.0**-69)], [2.0**-69]])) + extreme.to(device) + model = self._known_centroids( + torch.zeros(1, 1, device=device), + model_class=QuantizedEmeans, + quantizer=extreme, + assignment_backend=backend, + ) + distance, _ = model.assign(torch.tensor([[2]], dtype=torch.int8, device=device)) + self.assertEqual((distance.item(), distance.device, torch.cuda.current_device()), (2.**-148, device, current)) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((8, 0), (9, 0), (10, 0)) + and importlib.util.find_spec("triton") is not None, + "qualified INT8 CUDA required", + ) + def test_raw_integer_closing_partition_and_assign(self): + for dtype, value in ((torch.int8, 127), (torch.uint8, 255)): + for batch in (65795, 131073): + with self.subTest(dtype=dtype, batch=batch): + rows = torch.full((131603, 1), value, dtype=dtype, device='cuda') + model = QuantizedEmeans( + 1, + 1, + nepochs=2, + batch_size=batch, + alpha0=0.5, + assignment_backend='triton', + assignment_chunk_size=70001, + ) + model.train(rows, torch.tensor([[float(value)]], device='cuda')) + self.assertEqual(model.centroids.dtype, torch.float32) + self.assertEqual(model.centroids.item(), float(value)) + self.assertIs(model.finalize(), model.centroids) + # Default matrix training and caller batches share exact raw closing. + for backend in self._byte_backends(): + for dtype in (torch.int8, torch.uint8): + rows = (torch.arange(2049, device='cuda') % 256).reshape(-1, 1) + rows = (rows - 128 if dtype == torch.int8 else rows).to(dtype) + saved = rows.clone() + expected = float(np.float32(np.float64(rows.cpu().long().sum().item()) / len(rows))) + for nepochs in (1, 2, 3): + with self.subTest(raw_closing=dtype, nepochs=nepochs, backend=backend): + initial = torch.zeros(1, 1, device='cuda') + model = QuantizedEmeans( + 1, + 1, + nepochs=nepochs, + seed=7, + assignment_backend=backend, + capture_assignments=True, + ) + model.train(rows, initial) + torch.testing.assert_close(model.assignments, torch.zeros(len(rows), dtype=torch.int64, device='cuda'), rtol=0, atol=0) + self.assertEqual(model.centroids.item(), expected) + output = model.centroids + self.assertIs(model.finalize(), output) + del model + self.assertEqual(output.item(), expected) + caller = QuantizedEmeans( + 1, + 1, + nepochs=nepochs, + seed=7, + assignment_backend=backend, + capture_assignments=True, + ) + caller.begin(len(rows), initial) + for epoch in range(nepochs): + for start in range(0, len(rows), caller.recipe['batch_size']): + piece = rows[start:start + caller.recipe['batch_size']] + stats = caller.accumulate(piece[:1]) + if len(piece) > 1: + self.assertIsNone(stats['sums']) + self.assertIsNone(stats['counts']) + stats = caller.accumulate(piece[1:]) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), + (torch.int64, torch.int64)) + if epoch == nepochs - 1: + torch.testing.assert_close(stats['labels'], torch.zeros_like(stats['labels']), rtol=0, atol=0) + caller.update(stats) + caller.end_epoch() + self.assertEqual(caller.finalize().item(), expected) + torch.testing.assert_close(rows, saved, rtol=0, atol=0) + torch.testing.assert_close(initial, torch.zeros_like(initial), rtol=0, atol=0) + # An even-population balanced mean must be254.5 despite odd partitions. + rows = torch.full((300002, 1), 255, dtype=torch.uint8, device='cuda') + rows[::2] = 254 + model = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=131073, + alpha0=0.5, + assignment_backend='triton', + assignment_chunk_size=70001, + ) + model.train(rows, torch.tensor([[255.]], device='cuda')) + self.assertEqual(model.centroids.item(), 254.5) + query = torch.tensor([[255]], dtype=torch.uint8, device='cuda') + # After finalize, raw assignment must neither need running epoch fields + # nor change finalization.254.5 rounds RN-even to represented254. + distance, labels = model.assign(query) + self.assertEqual((distance.item(), labels.item()), (1., 0)) + self.assertIs(model.finalize(), model.centroids) + # Untrained assignment remains unsupported; do not override centroids. + pair = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + assignment_backend='triton', + ) + pair.begin(4, torch.cat((model.centroids, torch.tensor([[255.]], device='cuda')))) + # Caller-supplied integer totals produce the intended closing table. + pair.update(dict(sums=torch.tensor([[int(2 * model.centroids.item())], [510]], + dtype=torch.int64, device='cuda'), + counts=torch.tensor([2, 2], dtype=torch.int64, device='cuda'), + objective=torch.zeros((), dtype=torch.float64, device='cuda'), n=4)) + pair.end_epoch() + torch.testing.assert_close(pair.finalize(), torch.tensor([[254.5], [255.]], device='cuda'), + rtol=0, atol=0) + distance, labels = pair.assign(query) + self.assertEqual((distance.item(), labels.item()), (0., 1)) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((8, 0), (9, 0), (10, 0)) + and importlib.util.find_spec("triton") is not None, + "qualified INT8 CUDA required", + ) + def test_raw_integer_external_schema_empty_and_fresh_objects(self): + for backend in self._byte_backends(): + + def supplied(dtype, n=2): + return dict(sums=torch.tensor([[255 * n]], dtype=dtype, device='cuda'), + counts=torch.tensor([n], dtype=dtype, device='cuda'), + objective=torch.zeros((), dtype=torch.float64, device='cuda'), n=n) + + args = dict(nepochs=1, batch_size=2, alpha0=.5, assignment_backend=backend) + model = QuantizedEmeans(1, 1, **args) + initial = torch.tensor([[255.]], device='cuda') + model.begin(4, initial) + current = model.current_centroids() + self.assertEqual((current.dtype, current.device), (torch.float32, initial.device)) + torch.testing.assert_close(current, initial, rtol=0, atol=0) + # External-first selects integer schema. Ordinary copies remain valid. + copied = {k: v.clone() if isinstance(v, torch.Tensor) else v + for k, v in supplied(torch.int64).items()} + model.update(copied) + stats = model.accumulate(torch.full((2, 1), 255, dtype=torch.uint8, device='cuda')) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype), (torch.int64, torch.int64)) + model.update(stats) + self.assertEqual((model._pass_counts.dtype, model._pass_sums.dtype), + (torch.int64, torch.int64)) + self.assertEqual((model._pass_counts.item(), model._pass_sums.item()), (4, 1020)) + model.end_epoch() + self.assertEqual(model.finalize().item(), 255.0) + self.assertEqual(copied['sums'].item(), 510) + model = QuantizedEmeans(1, 1, **args) + + # A supplied quantizer keeps decoded FP32 statistics even when + # the caller first supplies totals, before any encoded rows. + q = Int8Quantizer(1) + q.train(torch.full((2, 1), 255., device='cuda')) + calibrated = QuantizedEmeans(1, 1, quantizer=q, **args) + calibrated.begin(4, initial) + calibrated.update(supplied(torch.float32)) + contribution = calibrated.accumulate(q.compute_codes(initial.expand(2, 1))) + self.assertEqual((contribution['sums'].dtype, contribution['counts'].dtype), + (torch.float32, torch.float32)) + calibrated.update(contribution) + calibrated.end_epoch() + self.assertEqual(calibrated.finalize().item(), 255.) + + model.begin(2, initial) + empty = model.accumulate(torch.empty((0, 1), dtype=torch.uint8, device='cuda')) + self.assertEqual((empty['sums'].dtype, empty['counts'].dtype), (torch.int64, torch.int64)) + self.assertEqual((empty['sums'].item(), empty['counts'].item(), empty['n']), (0, 0, 0)) + # Empty selection consumed no prescribed rows; a full external update fits. + model.update(supplied(torch.int64)) + model.end_epoch() + self.assertEqual(model.finalize().item(), 255.0) + model = QuantizedEmeans(1, 1, **args) + + model.begin(4, initial) + model.update(supplied(torch.float32)) + model = QuantizedEmeans(1, 1, **args) + model.begin(2, initial) + model.update(supplied(torch.float32)) + model.end_epoch() + self.assertEqual(model.finalize().item(), 255.0) + + # Declared-N/schema boundary only: no population or permutation. + limit = 2**53 // 255 + for n in (limit, limit + 1): + model = QuantizedEmeans(1, 1, quantizer=None, **args) + model.begin(n, initial) + before = model._batch_stats + empty = torch.empty((0, 1), dtype=torch.uint8, device='cuda') + if n == limit: + stats = model.accumulate(empty) + self.assertEqual(model._input_dtype, torch.uint8) + self.assertEqual(stats['sums'].dtype, torch.int64) + self.assertEqual((stats['sums'].item(), stats['counts'].item(), stats['n']), (0, 0, 0)) + else: + for _ in range(2): + with self.assertRaisesRegex(ValueError, '255\\*n'): + model.accumulate(empty) + self.assertIsNone(model._input_dtype) + self.assertIsNone(model._cast_dtype) + self.assertIsNone(model.quantizer) + self.assertIs(model._batch_stats, before) + self.assertFalse(model._failed) + model = QuantizedEmeans(1, 1, **args) + + # Actual schema-allocation failure poisons; host schema checks above do not. + model.begin(2, initial) + allocate = torch.Tensor.new_empty + + def failed_allocation(tensor, *args, **kwargs): + allocate(tensor, *args, **kwargs) + raise RuntimeError('injected statistics allocation failure') + + with mock.patch.object(torch.Tensor, 'new_empty', failed_allocation): + with self.assertRaisesRegex(RuntimeError, 'injected statistics allocation'): + model.accumulate(torch.empty((0, 1), dtype=torch.uint8, device='cuda')) + self.assertTrue(model._failed) + with self.assertRaises(RuntimeError): + model.accumulate(torch.empty((0, 1), dtype=torch.uint8, device='cuda')) + model = QuantizedEmeans(1, 1, **args) + model.begin(2, initial) + model.update(model.accumulate(torch.full((2, 1), 255, dtype=torch.uint8, device='cuda'))) + model.end_epoch() + self.assertEqual(model.finalize().item(), 255.) + + def test_explicit_fp8_calibration_and_scope(self): + q = Fp8Quantizer(1) + with self.assertRaises(RuntimeError): + q.compute_codes(torch.zeros((1, 1))) + sample = torch.tensor([[0.], [2.], [10.], [12.]]) + q.train(sample) + self.assertTrue(q.is_trained) + self.assertEqual(q.code_size, 1) + self.assertEqual((q.scale, q.decision), (8., "small_sample_centered")) + self.assertIs(q.to("cpu"), q) + torch.testing.assert_close(q.decode(q.compute_codes(sample)), sample) + self.assertEqual(q.compute_codes(sample[:0]).shape, (0, 1)) + with self.assertRaises(ValueError): + q.validate(torch.tensor([[float("nan")]])) + + for n in (17, 2047, 2048, 3072): + with self.subTest(rows=n): + zero = torch.zeros(n, 3) + fitted = Fp8Quantizer(3) + fitted.train(zero) + self.assertEqual(fitted.scale, 1.) + self.assertEqual(fitted.code_size, 3) + self.assertIsInstance(fitted.fit_rows, int) + self.assertTrue(0 < fitted.fit_rows <= n) + self.assertEqual(fitted.scale, 2. ** fitted.exponent) + if n < 2048: + self.assertEqual(fitted.decision, "small_sample_centered") + self.assertIsNone(fitted.plain_excess) + self.assertIsNone(fitted.centered_excess) + else: + self.assertEqual(fitted.decision, "uncentered_near_parity") + self.assertEqual((fitted.plain_excess, fitted.centered_excess), (0., 0.)) + self.assertEqual(fitted.decode(fitted.compute_codes(zero[:0])).shape, (0, 3)) + with self.assertRaises(ValueError): + fitted.validate(torch.zeros(1, 2)) + with self.assertRaises(TypeError): + fitted.train(torch.zeros(1, 3, dtype=torch.int32)) + self.assertFalse(fitted.is_trained) + with self.assertRaises(RuntimeError): + fitted.decode(torch.zeros(1, 3)) + for bad in (torch.tensor([[float("nan")]]), torch.tensor([[float("inf")]]), + torch.tensor([[1.e-40], [-1.e-40]]), torch.empty(0, 1)): + q.train(sample) + with self.assertRaises(ValueError): + q.train(bad) + self.assertFalse(q.is_trained) + + def test_fp8_zero_reference_sse_selection(self): + # The first2048 rows are queries and the last1024 are probe centroids. + # Plain E4M3 collapses both values to32 and incurs SSE1/64; centering + # preserves them as -32/+32 with zero SSE. A zero denominator must + # therefore distinguish the positive-error candidate from parity. + values = torch.tensor([1., 257. / 256.]) + collapse = values.repeat(1536).reshape(-1, 1) + selected = Fp8Quantizer(1) + selected.train(collapse) + self.assertEqual((selected.centered, selected.decision), + (True, "centered_nonpositive_excess")) + self.assertEqual((selected.plain_excess, selected.centered_excess), + (1., 0.)) + + parity = Fp8Quantizer(3) + parity.train(torch.zeros(3072, 3)) + self.assertEqual((parity.centered, parity.decision), + (False, "uncentered_near_parity")) + self.assertEqual((parity.plain_excess, parity.centered_excess), + (0., 0.)) + + positive = Fp8Quantizer(4) + positive.train(torch.randn( + 2048, 4, generator=torch.Generator().manual_seed(7))) + self.assertEqual((positive.centered, positive.decision), + (False, "uncentered_insufficient_gain;both_above_quality_gate")) + self.assertGreater(positive.plain_excess, 0.) + self.assertGreater(positive.centered_excess, 0.) + + def test_fp8_positive_reference_selector_and_explicit_validation(self): + x = torch.randn(2048, 4, generator=torch.Generator().manual_seed(7)) + quantizers = [] + for scale in (1., 2. ** -60): + q = Fp8Quantizer(4) + q.train(x * scale) + quantizers.append(q) + self.assertTrue(0 < q.fit_rows <= len(x)) + self.assertTrue(np.isfinite(q.sample_peak)) + self.assertGreater(q.scale, 0.) + q.validate(x * scale) + with self.assertRaises(ValueError): + q.validate(torch.full((1, 4), float("inf"))) + a, b = quantizers + self.assertEqual(a.decision, b.decision) + self.assertEqual(a.centered, b.centered) + self.assertEqual(a.plain_excess, b.plain_excess) + self.assertEqual(a.centered_excess, b.centered_excess) + self.assertEqual(b.exponent - a.exponent, 60) + shifted = Fp8Quantizer(4) + shifted.train(x + torch.tensor([1.e4, -2.e4, 3.e4, -4.e4])) + self.assertTrue(shifted.centered) + plain = Fp8Quantizer(4) + plain.train(torch.randn(2048, 4, generator=torch.Generator().manual_seed(4))) + self.assertFalse(plain.centered) + with self.assertRaises(ValueError): + plain.validate(torch.full((1, 4), 1.e20)) + with mock.patch.object(torch, "float8_e4m3fn", None): + with self.assertRaisesRegex(RuntimeError, "float8_e4m3fn"): + Fp8Quantizer(1).train(torch.zeros(2, 1)) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((9, 0), (10, 0), (10, 3)) + and importlib.util.find_spec("triton") is not None, + "qualified FP8 CUDA required", + ) + def test_fp8_native_jit_decoded_lifecycle(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + x = torch.tensor([[0.1], [2.2], [10.3], [12.4]], device="cuda") + q = Fp8Quantizer(1) + q.train(x) + codes = q.compute_codes(x) + represented = q.decode(codes) + self.assertFalse(torch.equal(x, represented)) + init = torch.tensor([[0.], [10.]], device="cuda") + args = dict(nepochs=1, batch_size=4, alpha0=0.5, quantizer=q, capture_assignments=True, + assignment_backend=backend, assignment_chunk_size=2) + jit, native, steps = ( + QuantizedEmeans(1, 2, **args) for _ in range(3) + ) + jit.train(x, init) + native.train(codes, init) + steps.begin(len(x), init) + current = steps.current_centroids() + self.assertEqual((current.dtype, current.device), (torch.float32, init.device)) + torch.testing.assert_close(current, init, rtol=0, atol=0) + partial = steps.accumulate(codes[:1]) + self.assertIsNone(partial['sums']) + self.assertIsNone(partial['counts']) + torch.testing.assert_close(steps.current_centroids(), init, rtol=0, atol=0) + stats = steps.accumulate(codes[1:]) + torch.testing.assert_close(stats['labels'], torch.tensor([0, 1, 1], device="cuda"), rtol=0, atol=0) + steps.update(stats) + steps.end_epoch() + steps.finalize() + expected = represented.reshape(2, 2, 1).mean(dim=1) + for model in (jit, native, steps): + torch.testing.assert_close(model.centroids, expected) + torch.testing.assert_close(model.obj, jit.obj, atol=0, rtol=0) + distance, labels = model.assign(codes) + operands = q.decode(q.compute_codes(expected)) + oracle = (represented[:, None] - operands[None, :]).square().sum(2) + torch.testing.assert_close(distance, oracle.min(1).values, atol=2e-5, rtol=2e-5) + torch.testing.assert_close(labels, oracle.argmin(1)) + self.assertEqual((jit.centroids.dtype, distance.dtype, labels.dtype), + (torch.float32, torch.float32, torch.int64)) + raw = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + capture_assignments=True, + assignment_backend=backend, + ) + raw.train(codes, codes[[0, 2]].float()) + torch.testing.assert_close(raw.centroids, codes.float().reshape(2, 2, 1).mean(1)) + torch.testing.assert_close(raw.assignments, native.assignments, rtol=0, atol=0) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() in ((9, 0), (10, 0), (10, 3)) + and importlib.util.find_spec("triton") is not None, + "qualified FP8 CUDA required", + ) + def test_fp8_long_positive_selected_distances(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + d = 4096 + base = (torch.arange(d, device='cuda') % 251).float() + x = torch.stack((base, base + 32, base + 40)) + q = Fp8Quantizer(d) + q.train(torch.stack((torch.full_like(base, -128), torch.full_like(base, 128)))) + codes = q.compute_codes(x) + for k in (2, 1024): + initial = (base + 96).repeat(k, 1) + initial[:2] = x[:2] + operands = q.decode(q.compute_codes(initial)).double() + oracle = (q.decode(codes).double()[:, None] - operands[None]).square().sum(2) + for rows in (codes, x): + with self.subTest(k=k, native=rows is codes): + model = self._known_centroids( + initial, + model_class=QuantizedEmeans, + quantizer=q, + assignment_backend=backend, + ) + distance, labels = model.assign(rows) + torch.testing.assert_close(labels, oracle.argmin(1)) + chosen = oracle.gather(1, labels[:, None]).flatten() + torch.testing.assert_close(distance.double(), chosen, rtol=2e-6, atol=1e-3) + self.assertEqual(distance[:2].tolist(), [0., 0.]) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_matched_norm_ragged_integer_and_allowed_ties(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + rows = torch.tensor([[-8.5485334, .5754005, 5.9468751]], device="cuda") + centroids = torch.tensor([[1.3439447, -6.8812032, 5.9468989], + [1.6238794, -.7164297, -.9630429]], device="cuda") + xq, cq = rows.to(torch.float8_e4m3fn).float(), centroids.to(torch.float8_e4m3fn).float() + self.assertEqual(((xq[:, None] - cq).square().sum(2)).argmin(1).item(), 1) + wrong = centroids.square().sum(1)[None] - 2 * xq @ cq.T + self.assertEqual(wrong.argmin(1).item(), 0) + model = self._known_centroids( + centroids, + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + self.assertEqual(model.assign(xq.to(torch.float8_e4m3fn))[1].item(), 1) + for n, k, d in ((3, 7, 17), (17, 8065, 65), (65, 513, 129), (3, 4232, 512)): + with self.subTest(n=n, k=k, d=d): + g = torch.Generator(device="cuda").manual_seed(n + k + d) + c = torch.randint(-4, 5, (k, d), generator=g, device="cuda").float() + x = torch.randint(-4, 5, (n, d), generator=g, device="cuda").float() + # Integer products/sums here are far below the FP32 exact bound. + oracle = (x.double()[:, None] - c.double()).square().sum(2) + m = self._known_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + distance, labels = m.assign(x.to(torch.float8_e4m3fn)) + torch.testing.assert_close(labels, oracle.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance.double(), oracle.min(1).values, rtol=0, atol=0) + tied = self._known_centroids( + torch.zeros_like(c), + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + self.assertTrue(torch.equal(tied.assign(torch.zeros_like(x).to(torch.float8_e4m3fn))[1], + torch.zeros(n, dtype=torch.int64, device="cuda"))) + d = 4096 + x = (torch.arange(d, device="cuda") % 31 + 128).to(torch.float8_e4m3fn) + c = x.float().repeat(3, 1) + c[0, 0] += 16 + c[1, 1] += 16 + c[2] += 64 + m = self._known_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + distance, labels = m.assign(x[None]) + self.assertIn(labels.item(), (0, 1)) + selected = (x.double() - c.to(torch.float8_e4m3fn).double()[labels.item()]).square().sum() + torch.testing.assert_close(distance.double()[0], selected, rtol=2e-6, atol=1e-6) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_decoded_tail_statistics_and_exact_code_lattice(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + x = torch.tensor( + [ + [0.1, -0.2], + [2.2, 0.3], + [10.3, 0.4], + [12.4, 0.5], + [11.8, 0.25], + ], + device="cuda", + ) + q = Fp8Quantizer(2) + q.train(x) + initial = torch.tensor([[0., 0.], [10., 0.]], device="cuda") + for dtype in ( + torch.float32, + torch.float16, + torch.bfloat16, + torch.float8_e4m3fn, + ): + with self.subTest(dtype=dtype): + incoming = q.compute_codes(x) if dtype is torch.float8_e4m3fn else x.to(dtype) + codes = incoming if dtype is torch.float8_e4m3fn else q.compute_codes(incoming) + decoded = q.decode(codes) + m = QuantizedEmeans( + 2, + 2, + nepochs=2, + batch_size=2, + alpha0=0.5, + seed=7, + quantizer=q, + assignment_backend=backend, + assignment_chunk_size=1, + capture_assignments=True, + ) + m.begin(len(x), initial) + for epoch in range(2): + order = torch.randperm( + len(x), + generator=e_means._torch_generator( + x.device, _epoch_seed(7, epoch) + ), + device=x.device, + ) + for start in range(0, len(x), 2): + indices = order[start:start + 2] + batch = codes[indices] + before = m.current_centroids().clone() + cq = q.compute_codes(before).float() + squared = (batch.float()[:, None] - cq[None]).square().sum(2) + labels = squared.argmin(1) + sums = torch.zeros_like(before) + sums.index_add_(0, labels, decoded[indices]) + counts = torch.bincount(labels, minlength=2).float() + for offset in range(len(indices)): + stats = m.accumulate(incoming[indices[offset:offset + 1]]) + torch.testing.assert_close(m.current_centroids(), before, rtol=0, atol=0) + if offset + 1 < len(indices): + self.assertIsNone(stats['sums']) + self.assertIsNone(stats['counts']) + if epoch == m.nepochs - 1: + torch.testing.assert_close(stats['labels'], labels[offset:offset + 1], rtol=0, atol=0) + self.assertEqual((stats['sums'].dtype, stats['counts'].dtype, + stats['objective'].dtype), (torch.float32, torch.float32, torch.float64)) + torch.testing.assert_close(stats['sums'], sums, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], counts, rtol=0, atol=0) + expected = torch.ldexp(squared.min(1).values, torch.tensor(-2 * q.exponent, device="cuda")).double().sum() + torch.testing.assert_close(stats['objective'], expected, rtol=1e-6, atol=3e-3) + m.update(stats) + m.end_epoch() + m.finalize() + reference = QuantizedEmeans( + 2, + 2, + nepochs=2, + batch_size=2, + alpha0=0.5, + seed=7, + quantizer=q, + assignment_backend=backend, + assignment_chunk_size=1, + ) + reference.train(codes, initial) + torch.testing.assert_close(m.centroids, reference.centroids, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(m.obj, reference.obj, rtol=1e-6, atol=3e-5) + # Abs 2**-9 lattice units per coordinate <2**24; bounded norm/dot + # intermediates and normal power-of-two decode make these totals exact. + q = Fp8Quantizer(2) + q.train( + torch.tensor( + [[-8.0, -8.0], [8.0, 8.0]], device="cuda" + ).repeat(1024, 1) + ) + self.assertFalse(q.centered) + codes = torch.tensor([[1., 2.], [-1., 0.], [2. ** -9, -2. ** -9]], device="cuda").to(torch.float8_e4m3fn) + self.assertTrue(bool((codes.float().abs().sum(0) * 512 < 2 ** 24).all())) + previous = torch.are_deterministic_algorithms_enabled() + try: + for deterministic, incoming in ((False, codes), (True, codes), + (False, q.decode(codes)), (True, q.decode(codes))): + with self.subTest(code_lattice_deterministic=deterministic, + native=incoming is codes): + torch.use_deterministic_algorithms(deterministic) + m = QuantizedEmeans( + 2, + 1, + nepochs=1, + batch_size=3, + alpha0=1.0, + quantizer=q, + assignment_backend=backend, + assignment_chunk_size=1, + capture_assignments=True, + ) + m.begin(3, torch.zeros(1, 2, device="cuda")) + partial = m.accumulate(incoming[:1]) + self.assertEqual(partial['n'], 1) + self.assertIsNone(partial['sums']) + self.assertIsNone(partial['counts']) + empty = m.accumulate(incoming[:0]) + self.assertEqual(empty['n'], 1) + self.assertEqual(empty['labels'].numel(), 0) + # Changing helper eligibility must not mix decoded and + # code-unit contributions within one frozen batch. + torch.use_deterministic_algorithms(not deterministic) + stats = m.accumulate(incoming[1:]) + expected = q.decode(codes).sum(0, keepdim=True) + torch.testing.assert_close(stats['sums'], expected, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], torch.tensor([3.], device="cuda"), rtol=0, atol=0) + saved = stats['sums'].clone() + torch.testing.assert_close(m.accumulate(incoming[:0])['sums'], saved, rtol=0, atol=0) + m.update(stats) + m.end_epoch() + torch.testing.assert_close(m.finalize(), expected / 3, rtol=0, atol=0) + finally: + torch.use_deterministic_algorithms(previous) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_ldexp_scaling_and_finite_decoded_neighbor(self): + from faiss.contrib.e_means.quantizer_fp8 import separate_splits + + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + for exponent, expected in ((75, 2. ** -148), (-100, 0.)): + peak = 2. ** (5 - exponent) + q = Fp8Quantizer(1) + q.train(torch.tensor([[-peak], [peak]], device="cuda")) + self.assertEqual(q.exponent, exponent) + encoded = 0. if exponent == -100 else 2. + codes = torch.tensor([[encoded]], device="cuda").to(torch.float8_e4m3fn) + m = QuantizedEmeans( + 1, + 1, + nepochs=1, + batch_size=1, + alpha0=1.0, + quantizer=q, + assignment_backend=backend, + ) + m.begin(1, torch.zeros(1, 1, device="cuda")) + stats = m.accumulate(codes) + self.assertEqual(stats['objective'].item(), expected) + m.update(stats) + m.end_epoch() + m.finalize() + self.assertEqual(m.assign(codes)[0].item(), 0.) + donor = torch.tensor([[0., 0.], [1., 2.], [-1., 3.], [448., 1.]], device="cuda") + child = donor.clone() + saved = donor.clone() + separate_splits(donor, child, None) + torch.testing.assert_close(child[:, 0], torch.tensor([2. ** -9, 1.125, -.9375, 416.], device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(child[:, 1:], saved[:, 1:], rtol=0, atol=0) + ordinary = saved + 10 + separate_splits(donor, ordinary, None) + torch.testing.assert_close(ordinary, saved + 10, rtol=0, atol=0) + q = Fp8Quantizer(2) + q.train(torch.tensor([[0., -2.], [2., 2.]], device="cuda")) + donor = saved / q.scale + q.shift + child = donor.clone() + untouched = child[:, 1:].clone() + separate_splits(donor, child, q) + torch.testing.assert_close(q.compute_codes(child).float()[:, 0], + torch.tensor([2. ** -9, 1.125, -.9375, 416.], device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(child[:, 1:], untouched, rtol=0, atol=0) + maximum = torch.finfo(torch.float32).max + q = Fp8Quantizer(1) + q.train(torch.tensor([[-.97 * maximum], [.97 * maximum]], device="cuda")) + self.assertEqual(q.exponent, -123) + donor = torch.tensor([[.97 * maximum * (1 - 1.e-4)]], device="cuda") + child = torch.tensor([[.97 * maximum * (1 + 1.e-4)]], device="cuda") + saved = child.clone() + torch.testing.assert_close(q.compute_codes(donor).float(), q.compute_codes(child).float(), rtol=0, atol=0) + separate_splits(donor, child, q) + torch.testing.assert_close(child, saved, rtol=0, atol=0) + + # Compare mass-rule model writes with the stock represented-row + # primitive. Cost revival also applies Gaussian axis arithmetic. + code_rows = torch.tensor([[0., -0.], [0., 1.0625], [-1., 3.], [448., 1.]], device='cuda') + for kind in ('raw', 'plain', 'centered', 'tiny'): + q = None + if kind != 'raw': + sample = torch.tensor([[-.5, -.5], [.5, .5]]) + if kind == 'centered': + sample = sample + 10 + elif kind == 'tiny': + sample = sample * 2. ** -121 + q = Fp8Quantizer(2) + q.train(sample if kind == 'centered' else sample.repeat(1024, 1)) + q.to('cuda') + self.assertEqual(q.centered, kind == 'centered') + donors = code_rows if q is None else q.decode(code_rows) + for backend in self._fp8_backends(): + with self.subTest(model_writer=kind, backend=backend): + initial = torch.cat((donors, donors, donors[:1])) + model = QuantizedEmeans( + 2, + 9, + nepochs=1, + batch_size=9, + alpha0=0.5, + quantizer=q, + assignment_backend=backend, + unused_threshold=0, + ) + model.begin(9, initial) + model.accumulate(code_rows[:0].to(torch.float8_e4m3fn)) + model._usage.fill_(8) + low, high = donors.clone(), donors.clone() # U = 0: copies start at the donor. + separate_splits(low, high, q) + expected = torch.cat((low, high, donors[:1])) + source = torch.arange(4, device='cuda', dtype=torch.int64) + self.assertEqual(model._apply_splits(source, source + 4), 4) + torch.testing.assert_close(model._centroids.view(torch.int32), + expected.view(torch.int32), rtol=0, atol=0) + torch.testing.assert_close(model._usage, + donors.new_tensor([4.] * 8 + [8.]), rtol=0, atol=0) + del model + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_metadata_default_codes_and_output_ownership(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + initial = torch.zeros(1, 1, device="cuda") + q = Fp8Quantizer(1) + m = QuantizedEmeans(1, 1, nepochs=1, batch_size=1, alpha0=.5, + quantizer=q, assignment_backend=backend) + q.train(torch.zeros(2, 1)) + q.to(initial.device) + m.begin(1, initial) + m.update(dict(sums=initial.clone(), counts=torch.ones(1, device="cuda"), + objective=torch.zeros((), device="cuda", dtype=torch.float64), n=1)) + m.end_epoch() + torch.testing.assert_close(m.finalize(), initial, rtol=0, atol=0) + x = torch.randn(7, 3, device="cuda", generator=torch.Generator(device="cuda").manual_seed(123)) + q = Fp8Quantizer(3) + q.train(x) + codes = q.compute_codes(x) + before = codes.view(torch.uint8).clone() + indices = torch.randperm(7, device="cuda", generator=torch.Generator(device="cuda").manual_seed(7))[:2] + for calibrated in (False, True): + with self.subTest(calibrated=calibrated): + selected = q if calibrated else None + args = dict(nepochs=1, batch_size=3, alpha0=.5, seed=7, + assignment_chunk_size=1, quantizer=selected, assignment_backend=backend) + default, explicit = QuantizedEmeans( + 3, 2, **args + ), QuantizedEmeans(3, 2, **args) + chosen = codes.float()[indices] + initial = q.decode(chosen) if calibrated else chosen + explicit.train(codes, initial) + default.train(codes) + torch.testing.assert_close(default.centroids, explicit.centroids, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(default.obj, explicit.obj, rtol=1e-6, atol=3e-5) + torch.testing.assert_close(codes.view(torch.uint8), before, rtol=0, atol=0) + output, saved = default.centroids, default.centroids.clone() + del default + torch.testing.assert_close(output, saved, rtol=0, atol=0) + # Foreign statistics are a mass-rule API. Default cost + # revival requires this model's removal contribution. + cost = QuantizedEmeans(3, 2, **args) + cost.begin(7, initial) + cost.accumulate(codes[:0]) + self.assertIsNone(cost._unused_threshold) + saved_centroids = cost._centroids.clone() + saved_usage = cost._usage.clone() + supplied = torch.zeros(2, 3, device="cuda") + supplied[0] = initial[0] * 3 + manual = dict(sums=supplied, + counts=torch.tensor([3., 0.], device="cuda"), + objective=torch.zeros((), device="cuda", dtype=torch.float64), n=3) + with self.assertRaisesRegex(ValueError, "this model's accumulate"): + cost.update(manual) + torch.testing.assert_close(cost._centroids, saved_centroids, rtol=0, atol=0) + torch.testing.assert_close(cost._usage, saved_usage, rtol=0, atol=0) + raw = QuantizedEmeans(3, 2, unused_threshold=0, **args) + raw.begin(7, initial) + empty = raw.accumulate(codes[:0]) + self.assertEqual(empty["n"], 0) + # Consume the empty pending contribution using a prescribed + # three-copy contribution at its represented first centroid. + raw.update(manual) + if not calibrated: + pass + else: + contribution = raw.accumulate(x[:1]) + self.assertEqual(contribution['n'], 1) + self.assertIsNone(contribution['sums']) + self.assertIsNone(contribution['counts']) + contribution = raw.accumulate(x[1:3]) + self.assertEqual( + ( + contribution["sums"].dtype, + contribution["counts"].dtype, + ), + (torch.float32, torch.float32), + ) + self.assertEqual(contribution['counts'].sum().item(), 3.) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_finite_warm_updates_and_real_range_rejection(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + from faiss.contrib.e_means.quantizer_fp8 import separate_splits + + x = torch.tensor([[-1., -1.], [1., 1.]], device="cuda") + q = Fp8Quantizer(2) + q.train(x) + for route in ("raw", "codes", "floating"): + with self.subTest(route=route): + selected = None if route == "raw" else q + batch = x if route == "floating" else q.compute_codes(x) + initial = q.compute_codes(x).float() if route == "raw" else x + m = QuantizedEmeans( + 2, + 2, + nepochs=1, + batch_size=2, + alpha0=0.5, + quantizer=selected, + assignment_backend=backend, + unused_threshold=0.1, + ) + m.begin(2, initial) + m.update(m.accumulate(batch)) + m = QuantizedEmeans( + 2, + 2, + nepochs=1, + batch_size=2, + alpha0=0.5, + quantizer=selected, + assignment_backend=backend, + unused_threshold=0.1, + ) + m.begin(4, initial) + m.update(m.accumulate(batch)) + donor = torch.zeros(1, 2, device="cuda") + child = donor.clone() + torch.cuda.synchronize() + previous = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode("error") + m.update(m.accumulate(batch)) + separate_splits(donor, child, selected) + finally: + torch.cuda.set_sync_debug_mode(previous) + self.assertTrue(bool((child != donor).any())) + stable = torch.full((2, 1), 1000., device="cuda") + q = Fp8Quantizer(1) + q.train(stable) + m = QuantizedEmeans( + 1, + 2, + nepochs=3, + batch_size=2, + alpha0=0.5, + quantizer=q, + assignment_backend=backend, + unused_threshold=0.1, + ) + m.train(stable, stable) + self.assertTrue(bool(torch.isfinite(m.centroids).all())) + large = torch.full((10, 1), 1.e7, device="cuda") + q.train(large) + m = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=2, + alpha0=0.05, + quantizer=q, + assignment_backend=backend, + unused_threshold=0.1, + ) + m.begin(10, torch.tensor([[1.e7], [1.e7 + 400]], device="cuda")) + m.accumulate(q.compute_codes(large[:0])) + # Identical rows give U = 0; a long axis moves one copy beyond the codec's range. + m._removal_stats[0, 0] = 1.e14 + m._apply_splits(torch.tensor([0], device="cuda"), torch.tensor([1], device="cuda")) + with self.assertRaisesRegex(ValueError, "representable range"): + m._epoch_totals() + self.assertEqual(m.n_splits, 1) + for calibrated in (False, True): + codec = Fp8Quantizer(1) if calibrated else None + if codec is not None: + codec.train(torch.tensor([[-1.], [1.]], device="cuda")) + model = self._known_centroids( + torch.ones(1, 1, device="cuda"), + model_class=QuantizedEmeans, + quantizer=codec, + assignment_backend=backend, + ) + model.centroids.fill_(17. if calibrated else 512.) + query = torch.zeros(1, 1, device="cuda").to(torch.float8_e4m3fn) + for _ in range(2): + with self.assertRaisesRegex(ValueError, "centroids.*representable range"): + model.assign(query) + model.centroids.fill_(1.) + for _ in range(2): + distance, labels = model.assign(query) + torch.testing.assert_close(distance, torch.ones_like(distance), rtol=0, atol=0) + self.assertEqual(labels.item(), 0) + + @unittest.skipUnless( + FP8_CUDA and torch.cuda.device_count() >= 2, + "FP8 and two CUDA devices required", + ) + def test_fp8_noncurrent_device_decode_assign_and_split(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + from faiss.contrib.e_means.quantizer_fp8 import separate_splits + + current = torch.cuda.current_device() + other = torch.device("cuda", 1 if current == 0 else 0) + for exponent in (6, 75): + peak = 2. ** (5 - exponent) + q = Fp8Quantizer(1) + q.train(torch.tensor([[-peak], [peak]])) + q.to(other) + codes = torch.tensor([[2.]], device=other).to(torch.float8_e4m3fn) + m = self._known_centroids( + torch.zeros(1, 1, device=other), + model_class=QuantizedEmeans, + quantizer=q, + assignment_backend=backend, + ) + distance, labels = m.assign(codes) + expected = torch.ldexp(torch.tensor([4.]), torch.tensor(-2 * exponent)) + torch.testing.assert_close(distance.cpu(), expected, rtol=0, atol=0) + self.assertEqual((distance.device, labels.device), (other, other)) + if exponent == 6: + torch.testing.assert_close(q.decode(codes).cpu(), torch.tensor([[2. ** -5]]), rtol=0, atol=0) + donor = torch.zeros(1, 1, device=other) + child = donor.clone() + separate_splits(donor, child, q) + torch.testing.assert_close(child.cpu(), torch.tensor([[2. ** -15]]), rtol=0, atol=0) + self.assertEqual(torch.cuda.current_device(), current) + + @unittest.skipUnless(FP8_CUDA, "qualified FP8 CUDA required") + def test_fp8_conditioned_positive_distances_and_ranking_margin(self): + for backend in self._fp8_backends(): + with self.subTest(backend=backend): + for d, offset in ((384, 128), (4096, 0)): + with self.subTest(d=d, offset=offset): + g = torch.Generator(device="cuda").manual_seed(1818) + c = (torch.randint(0, 32, (384, d), device="cuda", generator=g).float() + offset).to(torch.float8_e4m3fn).float() + x = (torch.randint(0, 32, (8, d), device="cuda", generator=g).float() + offset).to(torch.float8_e4m3fn) + x[0].copy_(c[7]) + m = self._known_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + distance, labels = m.assign(x) + selected = (x.double() - c[labels].double()).square().sum(1) + torch.testing.assert_close(distance.double(), selected, rtol=2e-6, atol=1e-6) + self.assertEqual((labels[0].item(), distance[0].item()), (7, 0.)) + saved = distance.clone(), labels.clone() + m.assign(x[1:]) + torch.testing.assert_close(distance, saved[0], rtol=0, atol=0) + torch.testing.assert_close(labels, saved[1], rtol=0, atol=0) + for d in (384, 4096): + g = torch.Generator(device="cuda").manual_seed(20261016) + population = torch.randint(0, 256, (4096 + 128, d), device="cuda", dtype=torch.uint8, generator=g) + population = population.float().mul_(.125).to(torch.float8_e4m3fn) + c, x = population[:4096].float(), population[4096:].clone() + x[33].copy_(population[1052]) + m = self._known_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend=backend, + ) + _, labels = m.assign(x) + minimum = torch.full((len(x),), float("inf"), device="cuda", dtype=torch.float64) + for start in range(0, len(c), 32): + direct = (x.double()[:, None] - c[start:start + 32].double()).square().sum(2) + minimum = torch.minimum(minimum, direct.min(1).values) + selected = (x.double() - c[labels].double()).square().sum(1) + # This retained separated-positive fixture permits near ties; it is + # not a universal FP64 argmin or low-precision error bound. + self.assertTrue(bool((selected - minimum <= minimum * 2e-4 + 1e-6).all())) + + + def test_default_backend_matches_native_cpu(self): + self.assertEqual(Emeans(1, 1).assignment_backend, "auto") + args = dict(nepochs=2, batch_size=7, alpha0=0.2, seed=9) + rows = torch.arange(68, dtype=torch.float32).reshape(17, 4) + default = Emeans(4, 3, **args) + explicit = Emeans(4, 3, assignment_backend="native", **args) + default.train(rows) + explicit.train(rows) + torch.testing.assert_close(default.centroids, explicit.centroids, rtol=0, atol=0) + torch.testing.assert_close(default.obj, explicit.obj, rtol=0, atol=0) + + def test_assign_resolves_independently_without_changing_training_recipe(self): + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=.5) + rows = torch.tensor([[0.], [2.], [10.], [12.]]) + centroids, captured = model.train(rows, rows[[0, 2]]) + recipe = dict(model.recipe) + model._input_dtype = torch.bfloat16 # Represents a completed BF16 run. + with mock.patch.object(torch_backend, '_get_triton_assign_rows', side_effect=AssertionError("CPU probed Triton")), \ + mock.patch.object(torch_backend, '_get_cute_functions', side_effect=AssertionError("CPU probed CuTe")): + distance, labels = model.assign(rows) + torch.testing.assert_close(distance, torch.ones(4), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.tensor([0, 0, 1, 1]), rtol=0, atol=0) + self.assertIs(model.centroids, centroids) + self.assertIs(model.assignments, captured) + self.assertEqual(model.recipe, recipe) + self.assertEqual(model._input_dtype, torch.bfloat16) + self.assertEqual(model.assignment_recipe['representation'], 'float32') + self.assertEqual(model.assignment_recipe['assignment_backend'], 'native') + + def test_auto_metadata_preference_and_no_encoded_fallback(self): + from types import SimpleNamespace + + # Actual metadata selection and requirement boundaries; no GPU launch. + check_cute = mock.Mock() + with mock.patch.object(torch.version, 'hip', None), \ + mock.patch.object(torch.cuda, 'get_device_capability', return_value=(9, 0)), \ + mock.patch.object(torch_backend, '_get_cute_functions', + return_value=(None, None, check_cute)), \ + mock.patch.object(torch_backend, '_get_triton_assign_rows', return_value=object()) as triton: + for dtype, quantizer, expected in ( + (torch.bfloat16, None, 'cute'), (torch.float32, None, 'triton'), + (torch.float16, None, 'triton'), + (torch.float32, CastQuantizer(1, torch.bfloat16), 'cute')): + with self.subTest(dtype=dtype, explicit_codec=quantizer is not None): + model = QuantizedEmeans(1, 2, quantizer=quantizer) + rows = SimpleNamespace(device=torch.device('cuda:7'), dtype=dtype) + model._resolve_input_dtype(rows) + model._resolve_assignment_backend(rows) + self.assertEqual(model._assignment_backend, expected) + self.assertEqual(model.assignment_backend, 'auto') + calls = (triton.call_count, check_cute.call_count) + model._resolve_assignment_backend(rows) + self.assertEqual((triton.call_count, check_cute.call_count), calls) + for error in (ImportError('required CuTe unavailable'), RuntimeError('broken CuTe API')): + check_cute.side_effect = error + rows = SimpleNamespace(device=torch.device('cuda:7'), dtype=torch.bfloat16) + model = QuantizedEmeans(1, 2, quantizer=None) + model._resolve_input_dtype(rows) + calls = triton.call_count + with self.assertRaises(type(error)) as observed: + model._resolve_assignment_backend(rows) + self.assertIs(observed.exception, error) + self.assertIsNone(model._resolved_assignment_backend) + self.assertEqual(triton.call_count, calls) # No backend downgrade. + check_cute.side_effect = None + triton.side_effect = ImportError('optional dependency unavailable') + for dtype in (torch.float32, torch.int8, torch.uint8, torch.float8_e4m3fn): + with self.subTest(required_triton=dtype): + rows = SimpleNamespace(device=torch.device('cuda:7'), dtype=dtype) + model = QuantizedEmeans(1, 2, quantizer=None) + model._resolve_input_dtype(rows) + with self.assertRaises(ImportError): + model._resolve_assignment_backend(rows) + self.assertIsNone(model._resolved_assignment_backend) + + def test_assign_runtime_failure_is_not_retried(self): + model = Emeans(1, 1) + model.centroids = torch.zeros((1, 1)) + with mock.patch.object(model, '_assign_rows', side_effect=RuntimeError('selected runtime fault')) as selected: + with self.assertRaisesRegex(RuntimeError, 'selected runtime fault'): + model.assign(torch.zeros((2, 1))) + self.assertEqual(selected.call_count, 1) + self.assertIsNone(model.assignment_recipe) + + def test_auto_new_begin_and_typed_empty_fix_run_metadata(self): + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=.5) + model.begin(4, torch.tensor([[0.], [10.]])) + self.assertIsNone(model._resolved_assignment_backend) + model.accumulate(torch.empty((0, 1))) + self.assertEqual(model._assignment_backend, 'native') + self.assertEqual(model.recipe['assignment_backend'], 'native') + self.assertEqual(model.recipe['assignment_backend_requested'], 'auto') + self.assertEqual(model._input_dtype, torch.float32) + self.assertEqual(model._step, 0) + + + + @unittest.skipUnless(torch.cuda.is_available() and not torch.version.hip + and torch.cuda.get_device_capability() >= (8, 0), "NVIDIA SM80 BF16 required") + def test_bf16_default_and_native_opt_out_query_law(self): + rows = torch.ones((17, 3), dtype=torch.bfloat16, device='cuda') + initial = torch.tensor([[1., 1., 1.], [0., 0., 0.]], device='cuda') + model = QuantizedEmeans(3, 2, quantizer=None, nepochs=1, batch_size=17, + alpha0=.5, assignment_backend='native') + centroids, captured = model.train(rows, initial) + train_recipe = dict(model.recipe) + distance, labels = model.assign(rows.float()) + self.assertEqual(model.assignment_recipe['representation'], 'float32') + self.assertEqual(model.assignment_recipe['assignment_backend'], 'native') + self.assertEqual(model.recipe, train_recipe) + self.assertIs(model.centroids, centroids) + self.assertIs(model.assignments, captured) + torch.testing.assert_close(distance, torch.zeros(17, device='cuda'), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.zeros(17, dtype=torch.int64, device='cuda'), rtol=0, atol=0) + + source = torch.tensor([[1+2**-10], [1+2**-9], [3+2**-10], [3+2**-9]], device='cuda') + rounded = source.bfloat16().float() + expected_sums = rounded.reshape(2, 2, 1).sum(1) + expected_means = expected_sums / 2 + self.assertFalse(torch.equal(expected_means, source.reshape(2, 2, 1).mean(1))) + initial = torch.tensor([[1.], [3.]], device='cuda') + options = dict(nepochs=1, batch_size=4, alpha0=1, assignment_backend='native') + default = Emeans(1, 2, **options) + centroids, captured = default.train(source, initial) + self.assertEqual(default.recipe['representation'], 'bfloat16') + self.assertEqual(centroids.dtype, torch.float32) + torch.testing.assert_close(centroids, expected_means, rtol=0, atol=0) + torch.testing.assert_close(captured, torch.tensor([0, 0, 1, 1], device='cuda'), rtol=0, atol=0) + train_recipe = dict(default.recipe) + original_query = default.assign(source) + self.assertEqual(default.assignment_recipe['representation'], 'bfloat16') + code_query = default.assign(source.bfloat16()) + self.assertEqual(default.assignment_recipe['representation'], 'bfloat16') + torch.testing.assert_close(original_query[0].view(torch.int32), code_query[0].view(torch.int32), rtol=0, atol=0) + torch.testing.assert_close(original_query[1], code_query[1], rtol=0, atol=0) + self.assertEqual(default.recipe, train_recipe) + self.assertIs(default.centroids, centroids) + self.assertIs(default.assignments, captured) + + caller = Emeans(1, 2, **options) + caller.begin(len(source), initial) + stats = caller.accumulate(source) + self.assertEqual(caller.recipe['representation'], 'bfloat16') + torch.testing.assert_close(stats['sums'], expected_sums, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], torch.tensor([2., 2.], device='cuda'), rtol=0, atol=0) + caller.update(stats) + caller.end_epoch() + torch.testing.assert_close(caller.finalize(), expected_means, rtol=0, atol=0) + + def test_optional_triton_dependency_isolation(self): + # A fresh interpreter avoids accidentally reusing an already imported + # optional backend. Native execution must not require Triton. + script = ''' +import importlib.abc, importlib.util, sys, pathlib, torch +import faiss.contrib +faiss.contrib.__path__.insert(0, str(pathlib.Path(sys.argv[1]).resolve().parents[1])) +from faiss.contrib.e_means import Emeans +from faiss.contrib.e_means import e_means_torch as e_means +assert pathlib.Path(e_means.__file__).resolve() == pathlib.Path(sys.argv[1]).resolve() +class NoTriton(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "triton" or fullname.startswith("triton."): + raise ImportError("test blocks optional Triton") +available = importlib.util.find_spec("triton") is not None +cuda_supported = (torch.cuda.is_available() and not torch.version.hip + and torch.cuda.get_device_capability() >= (8, 0)) +sys.meta_path.insert(0, NoTriton()) +assert "triton" not in sys.modules +model = Emeans(1, 1, nepochs=1, batch_size=2, alpha0=0.5) +model.train(torch.zeros((2, 1))) +assert "triton" not in sys.modules +if cuda_supported: + tiled = Emeans(1, 1, assignment_backend="triton", nepochs=1, batch_size=2, alpha0=0.5) + try: + tiled.train(torch.zeros((2, 1), device="cuda")) + except ImportError as error: + assert "triton package" in str(error) + else: + raise AssertionError("missing Triton did not reject the requested backend") + sys.meta_path.pop(0) + if available: + tiled = Emeans(1, 1, assignment_backend="triton", nepochs=1, batch_size=2, alpha0=0.5) + tiled.train(torch.zeros((2, 1), device="cuda")) + assert float(tiled.centroids[0, 0]) == 0 +''' + subprocess.run([sys.executable, "-c", script, str(Path(e_means.__file__).resolve())], + check=True, timeout=60) + + @unittest.skipUnless(importlib.util.find_spec('triton') is not None, 'Triton package required') + def test_selected_descriptor_interface_and_unselected_full_d(self): + from types import SimpleNamespace + from faiss.contrib.e_means import triton_assignment as backend + + initialized = torch.cuda.is_initialized() + rows = torch.empty((8192, 256), dtype=torch.bfloat16) + centroids = torch.empty((128, 256), dtype=torch.bfloat16) + kernel = mock.MagicMock() + with mock.patch.object(torch.cuda, 'get_device_capability', return_value=(9, 0)), \ + mock.patch.object(backend, '_assign_kernel', kernel): + for api in (None, SimpleNamespace(from_tensor=None)): + with mock.patch.object(backend, 'TensorDescriptor', api), self.assertRaises(ImportError): + backend._launch_assignment(rows, centroids, None, None, None, False) + kernel.__getitem__.assert_not_called() + made = [] + + def descriptor(tensor, block): + made.append((tensor, block)) + return object() + + with mock.patch.object(backend, 'TensorDescriptor', SimpleNamespace(from_tensor=descriptor)): + backend._launch_assignment(rows, centroids, None, None, None, False) + self.assertEqual(len(made), 2) + self.assertEqual(kernel.__getitem__.return_value.call_count, 1) + kernel.reset_mock() + with mock.patch.object(backend, 'TensorDescriptor', None), \ + mock.patch.object(backend, '_full_d_config', + return_value=backend._FULL_D_CONFIG): + backend._launch_assignment(rows[:, :96], centroids[:, :96], None, None, None, False) + self.assertEqual(kernel.__getitem__.return_value.call_count, 1) + self.assertNotIn('x_desc', kernel.__getitem__.return_value.call_args.kwargs) + self.assertEqual(torch.cuda.is_initialized(), initialized) + + @unittest.skipUnless(importlib.util.find_spec('triton') is not None, 'Triton package required') + def test_scaled_fp8_split_requires_selected_ldexp(self): + from contextlib import nullcontext + from faiss.contrib.e_means import triton_assignment as backend + + q = Fp8Quantizer(1) + q.train(torch.tensor([[-.5], [.5]]).repeat(1024, 1)) + self.assertFalse(q.centered) + centroids, usage = torch.zeros((2, 1)), torch.ones(2) + kernel = mock.MagicMock() + with mock.patch.object(backend, '_fp8_libdevice', None), \ + mock.patch.object(torch.Tensor, 'is_cuda', new_callable=mock.PropertyMock, return_value=True), \ + mock.patch.object(backend, '_write_float_splits_kernel', kernel): + with self.assertRaises(ImportError): + backend._write_float_splits(centroids, usage, [0], [1], torch.float8_e4m3fn, quantizer=q) + kernel.__getitem__.assert_not_called() + # Raw FP8 uses no scale conversion and must not require ldexp. + with mock.patch.object(torch.cuda, 'device', return_value=nullcontext()): + self.assertTrue(backend._write_float_splits( + centroids, usage, [0], [1], torch.float8_e4m3fn)) + self.assertEqual(kernel.__getitem__.return_value.call_count, 1) + + @unittest.skipUnless(INT8_CUDA and torch.cuda.get_device_capability() == (9, 0), + 'INT8 descriptor execution requires SM90') + def test_int8_descriptor_requires_api_before_staging(self): + from faiss.contrib.e_means import triton_assignment as backend + + for d in (257, 272): + with self.subTest(d=d): + rows = torch.zeros((2, d), dtype=torch.int8, device='cuda') + centroids, norms = backend.prepare_int8_centroids( + torch.zeros((128, d), device='cuda'), 'int8') + stage = mock.MagicMock() + with mock.patch.object(backend, 'TensorDescriptor', None), \ + mock.patch.object(backend, '_stage_int8_rows_kernel', stage), \ + self.assertRaises(ImportError): + backend.assign_int8_rows(rows, centroids, norms, 'int8') + stage.__getitem__.assert_not_called() + distance, labels = backend.assign_int8_rows(rows, centroids, norms, 'int8') + torch.testing.assert_close(distance, torch.zeros_like(distance), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.zeros_like(labels), rtol=0, atol=0) + + def _floating_backends(self): + return ("native", "triton") if TRITON_CUDA else ("native",) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_planted_ragged_and_long_assignments(self): + # Large searches use separated planted winners, not another expanded + # matmul as a supposedly independent ranking oracle. + cases = ((torch.float32, 1, 1, 1), (torch.float32, 17, 19, 17), + (torch.float16, 17, 19, 17), (torch.bfloat16, 17, 19, 17), + (torch.float32, 2, 1025, 129), (torch.float32, 1, 17, 3000), + (torch.bfloat16, 2, 8193, 511), (torch.float16, 2, 4097, 512), + (torch.bfloat16, 2, 8193, 513), (torch.float16, 1025, 257, 65), + (torch.bfloat16, 3, 257, 128)) + with highest_fp32("cuda"): + for dtype, b, k, d in cases: + with self.subTest(dtype=dtype, shape=(b, k, d)): + generator = torch.Generator(device="cuda").manual_seed(1000+b+k+d) + centroids = torch.randn(k, d, generator=generator, device="cuda")/4 + expected = (torch.arange(b, device="cuda")*17+3) % k + rows = centroids[expected].clone() + rows[:, 0] += 1/32 + saved = rows.clone() + model = self._known_centroids(centroids, assignment_backend="triton") + distance, labels = model.assign(rows.to(dtype)) + direct = (rows.to(dtype).float()-centroids[expected].to(dtype).float()).square().sum(1) + torch.testing.assert_close(labels, expected, rtol=0, atol=0) + # Retained bounded factorized fixtures' tolerance, not a + # dimension-wide accuracy guarantee for arbitrary inputs. + torch.testing.assert_close(distance, direct, atol=max(2e-4, d*1e-5), rtol=2e-5) + torch.testing.assert_close(rows, saved, rtol=0, atol=0) + self.assertEqual((distance.dtype, labels.dtype), (torch.float32, torch.int64)) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_global_ties_ieee_and_large_half_norms(self): + for dtype, b, k, d, first, second in ( + (torch.bfloat16, 1025, 257, 65, 3, 130), + (torch.float16, 2, 3969, 128, 255, 256), + (torch.float32, 1, 257, 17, 124, 125), + ): + with self.subTest(dtype=dtype, shape=(b, k, d)): + rows = torch.ones((b, d), device="cuda", dtype=dtype) + centroids = torch.full((k, d), 10., device="cuda") + centroids[[first, second]] = 1 + distance, labels = self._known_centroids(centroids, assignment_backend="triton").assign(rows) + torch.testing.assert_close(labels, torch.full((b,), first, device="cuda", dtype=torch.int64), rtol=0, atol=0) + torch.testing.assert_close(distance, torch.zeros(b, device="cuda"), rtol=0, atol=0) + for d, k, value in ((1024, 2, 10.), (512, 3969, 12.)): + rows = torch.full((2, d), value, device="cuda", dtype=torch.float16) + centroids = torch.full((k, d), value+1, device="cuda") + centroids[0] = value + self.assertGreater(float(centroids[0].square().sum()), torch.finfo(torch.float16).max) + distance, labels = self._known_centroids(centroids, assignment_backend="triton").assign(rows) + torch.testing.assert_close(distance, torch.zeros(2, device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.zeros(2, device="cuda", dtype=torch.int64), rtol=0, atol=0) + with highest_fp32("cuda"): + rows = torch.tensor([[473.1382141113281]], device="cuda") + centroids = torch.tensor([[477.6440734863281], [469.184814453125]], device="cuda") + norm = centroids.square().sum(1) + ieee = norm-2*(rows*centroids).sum(1) + # Deliberately truncate the low 13 mantissa bits to exhibit why + # this named fixture needs IEEE FP32 rather than TF32 ranking. + rounded_rows = (rows.view(torch.int32) & -8192).view(torch.float32) + rounded_centroids = (centroids.view(torch.int32) & -8192).view(torch.float32) + tf32 = norm-2*(rounded_rows*rounded_centroids).sum(1) + self.assertEqual(int(ieee.argmin()), 1) + self.assertEqual(int(tf32.argmin()), 0) + _, labels = self._known_centroids(centroids, assignment_backend="triton").assign(rows) + self.assertEqual(int(labels[0]), 1) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_strided_current_stream_and_tensor_device(self): + current = torch.cuda.current_device() + device = torch.device("cuda", (current+1) % torch.cuda.device_count()) + for dtype in (torch.float32, torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype), highest_fp32("cuda"): + # Pitched rows and transposed/offset centroid views exercise + # real public layouts, not synthetic enormous address strides. + storage = torch.zeros((7, 9), dtype=dtype, device=device) + rows = storage[1:6, 1:7:2] + centroids = torch.arange(15, device=device, dtype=torch.float32).reshape(3, 5).t()[1:4] + model = self._known_centroids(centroids, assignment_backend="triton") + warm = model.assign(rows) + torch.cuda.synchronize(device) + del warm + producer = torch.cuda.Stream(device=device) + consumer = torch.cuda.Stream(device=device) + with torch.cuda.stream(producer): + # Test-only delay keeps writes pending after the already + # warmed assignment is queued on its consumer stream. + torch.cuda._sleep(50_000_000) + rows.copy_(centroids[[0, 1, 2, 0, 1]].to(dtype)) + consumer.wait_stream(producer) + with torch.cuda.stream(consumer): + saved = rows.clone() + distance, labels = model.assign(rows) + torch.cuda.current_stream(device).wait_stream(consumer) + direct = (rows.float()[:, None]-centroids.to(dtype).float()[None]).square().sum(2) + torch.testing.assert_close(labels, direct.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance, direct.min(1).values, rtol=2e-5, atol=2e-4) + torch.testing.assert_close(rows, saved, rtol=0, atol=0) + self.assertEqual(distance.device, device) + self.assertEqual(labels.device, device) + self.assertEqual(torch.cuda.current_device(), current) + if dtype == torch.float32: + # The exported wrapper also accepts FP32 rows with reduced + # centroid operands; model.assign's preparation is distinct. + from faiss.contrib.e_means.triton_assignment import ( + assign_rows, + ) + + backing = torch.zeros((5, 4), dtype=torch.bfloat16, device=device) + reduced = backing[1:4, :3].t() + reduced.copy_(centroids.bfloat16()) + saved_centroids = reduced.clone() + norm = reduced.float().square().sum(1).contiguous() + distance, labels = assign_rows(rows, reduced, norm) + direct = (rows[:, None]-reduced.float()[None]).square().sum(2) + torch.testing.assert_close(labels, direct.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance, direct.min(1).values, rtol=2e-5, atol=2e-4) + torch.testing.assert_close(reduced, saved_centroids, rtol=0, atol=0) + self.assertEqual((distance.device, labels.device), (device, device)) + self.assertEqual(torch.cuda.current_device(), current) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_second_output_metadata_rejects_before_launch(self): + from faiss.contrib.e_means import triton_assignment as backend + + rows = torch.zeros((3, 3), dtype=torch.bfloat16, device='cuda') + centers = torch.zeros((2, 3), dtype=torch.bfloat16, device='cuda') + norms = torch.zeros(2, device='cuda') + backing = torch.full((6,), -123., device='cuda') + saved_backing = backing.clone() + cases = [backing[::2], torch.full((2,), -123., device='cuda'), + torch.full((4,), -123., device='cuda'), torch.full((3, 1), -123., device='cuda'), + torch.full((), -123., device='cuda'), torch.full((3,), -123., dtype=torch.float16, device='cuda'), + torch.full((3,), -123., dtype=torch.float64, device='cuda'), torch.full((3,), -123., device='cpu'), + [1., 2., 3.]] + if torch.cuda.device_count() >= 2: + other = torch.device('cuda', (rows.device.index + 1) % torch.cuda.device_count()) + cases.append(torch.full((3,), -123., device=other)) + saved_inputs = rows.clone(), centers.clone(), norms.clone() + for index, second in enumerate(cases): + with self.subTest(index=index): + saved = second.clone() if isinstance(second, torch.Tensor) else list(second) + error = ValueError if isinstance(second, torch.Tensor) else TypeError + with mock.patch.object(backend, '_pad_columns', side_effect=AssertionError('invalid output reached padding')) as pad, \ + mock.patch.object(backend, '_launch_assignment', side_effect=AssertionError('invalid output reached launch')) as launch, \ + self.assertRaisesRegex(error, 'second output'): + backend.assign_rows(rows, centers, norms, second_out=second) + pad.assert_not_called() + launch.assert_not_called() + if isinstance(second, torch.Tensor): + torch.testing.assert_close(second, saved, rtol=0, atol=0) + else: + self.assertEqual(second, saved) + torch.testing.assert_close(backing, saved_backing, rtol=0, atol=0) + for actual, expected in zip((rows, centers, norms), saved_inputs): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_second_output_owned_views_and_score_modes(self): + from faiss.contrib.e_means.triton_assignment import assign_rows + + for dtype in (torch.float32, torch.float16, torch.bfloat16): + for mode in ('l2', 'score', 'spherical'): + with self.subTest(dtype=dtype, mode=mode): + rows = torch.zeros((3, 3), device='cuda') + centers = torch.zeros((2, 3), dtype=dtype, device='cuda') + rows[:, 0] = torch.tensor([1., .5, -1.] if mode == 'spherical' else [0., .5, 2.], device='cuda') + centers[:, 0] = torch.tensor([1., -1.] if mode == 'spherical' else [0., 2.], device='cuda') + norms = torch.zeros(2, device='cuda') if mode == 'spherical' else centers.float().square().sum(1) + represented = rows.to(dtype).double() + scores = norms.double()[None] - 2 * (represented[:, None] * centers.double()[None]).sum(2) + truth = (represented[:, None] - centers.double()[None]).square().sum(2) if mode == 'l2' else scores + backing = torch.full((5,), -123., device='cuda') + second = backing[1:-1] + pointer = second.data_ptr() + distance, labels = assign_rows(rows, centers, norms, spherical=mode == 'spherical', + return_score=mode == 'score', second_out=second) + torch.testing.assert_close(distance.double(), truth.min(1).values, rtol=0, atol=0) + torch.testing.assert_close(labels, truth.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(second.double(), truth.max(1).values, rtol=0, atol=0) + self.assertEqual(second.data_ptr(), pointer) + self.assertEqual(backing[[0, -1]].tolist(), [-123., -123.]) + empty = torch.empty(0, device='cuda') + distance, labels = assign_rows(rows[:0], centers, norms, second_out=empty) + self.assertEqual((distance.shape, labels.shape, empty.shape), ((0,), (0,), (0,))) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_exact_half_lattice_statistics(self): + # Every partial sum is representable: per-slot absolute 2**-24 + # lattice units are 2**23 and 8, both <=2**24, in any atomic order. + rows = torch.tensor([[1/16 if i % 2 else -1/16, 2**-24] for i in range(8)], + dtype=torch.float16, device="cuda") + saved = rows.clone() + deterministic = torch.are_deterministic_algorithms_enabled() + warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + try: + for mode in (False, True): + torch.use_deterministic_algorithms(mode) + model = Emeans(2, 1, nepochs=1, batch_size=8, alpha0=1, + assignment_backend="triton", capture_assignments=True) + model.begin(8, torch.zeros((1, 2), device="cuda")) + partial = model.accumulate(rows[:3]) + self.assertEqual(partial["n"], 3) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + stats = model.accumulate(rows[3:]) + torch.testing.assert_close(stats["labels"], torch.zeros(5, dtype=torch.int64, device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(stats["sums"], torch.tensor([[0., 2**-21]], device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(stats["counts"], torch.tensor([8.], device="cuda"), rtol=0, atol=0) + self.assertEqual((stats["sums"].dtype, stats["counts"].dtype, stats["objective"].dtype), + (torch.float32, torch.float32, torch.float64)) + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.finalize(), torch.tensor([[0., 2**-24]], device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(rows, saved, rtol=0, atol=0) + finally: + torch.use_deterministic_algorithms(deterministic, warn_only=warn_only) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_long_segment_sums_poisoned_partials(self): + from faiss.contrib.e_means import triton_assignment as backend + + pieces = backend._pieces + + def poisoned_pieces(*args): + result = pieces(*args) + result[1].fill_(poison) + return result + + for d, dtype in ((1024, torch.float32), (2048, torch.bfloat16)): + base, labels = self._long_segment_fixture(d, dtype) + for trial in range(8): + with self.subTest(d=d, dtype=dtype, trial=trial): + # Current rows and scratch differ from the preceding call. + rows = (base * (-1 if trial % 2 else 1) + (trial % 4) / 8).to(dtype) + poison = float('nan') if trial % 2 == 0 else 1e20 + stats = torch.full((5, d + 1), .25, device='cuda') + expected = stats.double() + for j in range(5): + selected = rows[labels == j].double() + expected[j, :d] += selected.sum(0) + expected[j, d] += len(selected) + with mock.patch.object(backend, '_pieces', side_effect=poisoned_pieces) as scratch: + self.assertIs(backend.accumulate_segments(rows, labels, stats), True) + scratch.assert_called_once() + # Dyadic bounded data has exact FP32 sums in any reduction order. + torch.testing.assert_close(stats.double(), expected, rtol=0, atol=0) + + def _long_segment_fixture(self, d, dtype): + # Three long segments start/end within pieces; also a short and an empty one. + counts = torch.tensor([10003, 15017, 7711, 37, 0], device='cuda') + labels = torch.repeat_interleave(torch.arange(5, device='cuda'), counts).roll(257) + row = (torch.arange(len(labels), device='cuda') % 5 - 2).float() + col = (torch.arange(d, device='cuda') % 5 - 2).float() + return ((row[:, None] + col[None, :]) / 8).to(dtype), labels + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_long_segment_removal_poisoned_partials(self): + from faiss.contrib.e_means import triton_assignment as backend + + pieces = backend._pieces + + def poisoned_pieces(*args): + result = pieces(*args) + result[1].fill_(poison) + return result + + for d in (512, 1024): # Production removal launches use two and four warps. + base, labels = self._long_segment_fixture(d, torch.float32) + centers = (torch.arange(5, device='cuda').float()[:, None] / 8).expand(5, d).contiguous() + for ema in (False, True): + for trial in range(8): + with self.subTest(d=d, ema=ema, trial=trial): + rows = base * (-1 if trial % 2 else 1) + (trial % 4) / 8 + poison = float('nan') if trial % 2 == 0 else 1e20 + distance = (torch.arange(len(rows), device='cuda') % 3).float() / 8 + second = distance + (trial + 1) / 8 + axes = torch.zeros((5, d), device='cuda') + axes[:, 0] = 1 + before_axes = axes.clone() + stats = torch.full((5, d + 1), .25, device='cuda') + removal = torch.full_like(stats, 0 if ema else .5) + state = torch.full_like(stats, .5) + expected_stats = stats.double() + batch = torch.zeros((5, d + 1), dtype=torch.float64, device='cuda') + for j in range(5): + mask = labels == j + selected = rows[mask].double() + expected_stats[j, :d] += selected.sum(0) + expected_stats[j, d] += len(selected) + y = selected - centers[j].double() + # With axis e0, the independent FP64 Oja oracle is y0*y. + batch[j, :d] = (y[:, :1] * y).sum(0) + batch[j, d] = (second[mask].double() - distance[mask].double()).sum() + expected_removal = state.double() * .75 + batch * .25 if ema else removal.double() + batch + with mock.patch.object(backend, '_pieces', side_effect=poisoned_pieces) as scratch: + result = backend.accumulate_removal( + rows, labels, stats, distance, second, axes, centers, removal, + ema=(state, .25, .75) if ema else None, + ) + scratch.assert_called_once() + self.assertEqual(result, 'folded' if ema else True) + torch.testing.assert_close(stats.double(), expected_stats, rtol=0, atol=0) + torch.testing.assert_close((state if ema else removal).double(), expected_removal, rtol=0, atol=0) + if ema: + torch.testing.assert_close(removal, torch.zeros_like(removal), rtol=0, atol=0) + direction = expected_removal[:, :d] + expected_axes = (direction / direction.norm(dim=1, keepdim=True)).float() + torch.testing.assert_close(axes, expected_axes, rtol=1e-6, atol=1e-7) + else: + torch.testing.assert_close(axes, before_axes, rtol=0, atol=0) + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_external_statistics_rounding_and_revival(self): + objective = torch.zeros((), device="cuda", dtype=torch.float64) + for alpha, zero_mass, value in ((0.5, False, 3.), (1., False, 1e8), + (0.5, True, 1e8)): + for strided in (False, True): + with self.subTest(alpha=alpha, zero_mass=zero_mass, strided=strided): + initial = torch.tensor([[value, value], [8.25, 8.25]], device="cuda") + models = [ + Emeans( + 2, + 2, + nepochs=2, + batch_size=2, + alpha0=alpha, + assignment_backend=backend, + unused_threshold=0.1, + ) + for backend in ("native", "triton") + ] + backing = torch.zeros((2, 4 if strided else 2), device="cuda") + sums = backing[:, ::2] if strided else backing + sums[0] = 2 + counts = torch.tensor([2., 0.], device="cuda") + saved = sums.clone() + for model in models: + model.begin(2, initial) + if zero_mass: + model._usage[0] = 0 # Isolate documented zero-mass reentry. + model.update(dict(sums=sums, counts=counts, objective=objective, n=2)) + torch.testing.assert_close(models[0]._centroids, models[1]._centroids, rtol=0, atol=0) + torch.testing.assert_close(models[0]._usage, models[1]._usage, rtol=0, atol=0) + mass = 0 if zero_mass else 2**-16 + weight = alpha*2/((1-alpha)*mass+alpha*2) + expected = 1 if weight == 1 else value+weight*(1-value) + torch.testing.assert_close(models[1]._centroids[0], torch.full((2,), expected, device="cuda", dtype=torch.float32), + rtol=2e-7, atol=0) + torch.testing.assert_close(sums, saved, rtol=0, atol=0) + del models + models = [Emeans(1, 2, nepochs=1, batch_size=1, alpha0=0.9, + assignment_backend=backend, unused_threshold=0) + for backend in ("native", "triton")] + for model in models: + model.begin(400, torch.tensor([[0.], [8.25]], device="cuda")) + mass, position = 2**-16, 0. + saw_subnormal = False + # Revival has separate actual controls; this probe isolates RN decay, + # including subnormals. Identical RN operations on identical external + # inputs justify equality here, not on arbitrary assignment trajectories. + with mock.patch.object(models[0], "_revive_unused", return_value=0), \ + mock.patch.object(models[1], "_revive_unused", return_value=0): + for step in range(400): + value = (step % 7-3)/8 + alpha = e_means._scheduled_alpha(0.9, step, 400) + mass = (1-alpha)*mass+alpha + position += alpha/mass*(value-position) + stats = dict(sums=torch.tensor([[value], [0.]], device="cuda"), + counts=torch.tensor([1., 0.], device="cuda"), objective=objective, n=1) + for model in models: + model.update(stats) + torch.testing.assert_close(models[0]._centroids, models[1]._centroids, rtol=0, atol=0) + torch.testing.assert_close(models[0]._usage, models[1]._usage, rtol=0, atol=0) + np.testing.assert_allclose(float(models[1]._centroids[0, 0]), position, rtol=3e-6, atol=3e-7) + saw_subnormal |= 0 < float(models[1]._usage[1]) < torch.finfo(torch.float32).tiny + self.assertTrue(saw_subnormal) + self.assertLessEqual(float(models[1]._usage[1]), torch.finfo(torch.float32).tiny) + for model in models: + model.end_epoch() + model.finalize() + # Same bounded donor/seed/represented arithmetic on one device; this + # compares the real split writer, not an arbitrary floating trajectory. + for dtype in (None, torch.bfloat16): + with self.subTest(writer_dtype=dtype): + models = [ + Emeans( + 1, + 3, + nepochs=1, + batch_size=10, + alpha0=0.5, + seed=7, + assignment_backend=backend, + unused_threshold=0.1, + ) + for backend in ("native", "triton") + ] + for model in models: + model.begin(50, torch.tensor([[0.], [10.], [30.]], device="cuda")) + if dtype is not None: + model.accumulate(torch.empty((0, 1), device="cuda", dtype=dtype)) + for _ in range(5): + model.update(dict(sums=torch.tensor([[0.], [0.], [300.]], device="cuda"), + counts=torch.tensor([0., 0., 10.], device="cuda"), objective=objective, n=10)) + self.assertGreater(model.n_splits, 0) + torch.testing.assert_close(models[0]._centroids, models[1]._centroids, rtol=0, atol=0) + torch.testing.assert_close(models[0]._usage, models[1]._usage, rtol=0, atol=0) + for model in models: + model.end_epoch() + model.finalize() + + @unittest.skipUnless(TRITON_CUDA, "Triton NVIDIA SM80 required") + def test_triton_warmed_streaming_workspace(self): + for k, seed in ((4097, 321), (16384, 654)): + with self.subTest(k=k): + generator = torch.Generator(device="cuda").manual_seed(seed) + rows = torch.randn(512, 17, generator=generator, device="cuda").bfloat16() + centroids = torch.randn(k, 17, generator=generator, device="cuda") + model = self._known_centroids(centroids, assignment_backend="triton") + warm = model.assign(rows) # Inputs, conversion and compile outside measurement. + torch.cuda.synchronize() + del warm + before = torch.cuda.memory_allocated() + torch.cuda.reset_peak_memory_stats() + distance, labels = model.assign(rows) + torch.cuda.synchronize() + extra = torch.cuda.max_memory_allocated()-before + self.assertEqual(distance.shape, (512,)) + self.assertEqual(labels.shape, (512,)) + self.assertLess(extra, 512*k*4//4) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() >= (8, 0) + and importlib.util.find_spec("triton") is not None, + "Triton CUDA required", + ) + def test_triton_matches_represented_training(self): + initial = torch.tensor([[0.], [3.]], device="cuda") + for dtype in (torch.float32, torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + x = torch.tensor([[0.125], [0.25], [3.125], [3.25], [3.5]], + dtype=dtype, device="cuda") + args = dict(nepochs=2, batch_size=2, alpha0=0.5, seed=7) + native = QuantizedEmeans(1, 2, quantizer=None, assignment_backend="native", **args) + tiled = QuantizedEmeans(1, 2, quantizer=None, assignment_backend="triton", **args) + native.train(x, initial) + tiled.train(x, initial) + torch.testing.assert_close(tiled.centroids, native.centroids, atol=2e-6, rtol=2e-6) + torch.testing.assert_close(tiled.obj, native.obj, atol=1e-5, rtol=2e-6) + torch.testing.assert_close(tiled.assign(x)[1], native.assign(x)[1]) + self.assertEqual(tiled.recipe["assignment_backend"], "triton") + + def test_stateless_cast_and_cpu_scope(self): + for bad_dimension, bad_dtype in ((0, torch.float16), (1, torch.float32)): + with self.assertRaises(ValueError): + CastQuantizer(bad_dimension, bad_dtype) + for dtype in (torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + q = CastQuantizer(2, dtype) + q.train() + self.assertTrue(q.is_trained) + self.assertEqual(q.code_size, 4) + self.assertIs(q.to("cpu"), q) + x = torch.tensor([[1.001, 9., 3.001, 9.], + [2.001, 9., 4.001, 9.]], requires_grad=True)[:, ::2] + saved = x.detach().clone() + codes = q.compute_codes(x) + self.assertTrue(codes.is_contiguous()) + self.assertFalse(codes.requires_grad) + torch.testing.assert_close(q.decode(codes), x.to(dtype).float(), rtol=0, atol=0) + torch.testing.assert_close(x, saved, rtol=0, atol=0) + q.validate(x) + for bad in (x[0], x[:, :1], x.detach().to_sparse()): + with self.assertRaises(ValueError): + q.compute_codes(bad) + with self.assertRaises(TypeError): + q.compute_codes(x.to(torch.int32)) + with self.assertRaises(TypeError): + q.decode(x) + with self.assertRaises(ValueError): + q.to("meta") + for value in (float("nan"), float("inf")): + with self.assertRaises(ValueError): + q.validate(torch.full((1, 2), value)) + model = Emeans(2, 1, nepochs=1, batch_size=2, alpha0=0.5) + model.train(codes) + torch.testing.assert_close(model.centroids, codes.float().mean(0, keepdim=True)) + self.assertEqual(model.centroids.dtype, torch.float32) + model = Emeans(2, 1, nepochs=1, batch_size=2, alpha0=0.5) + model.begin(2, codes[:1].float()) + partial = model.accumulate(codes[:1]) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + stats = model.accumulate(codes[1:]) + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.finalize(), codes.float().mean(0, keepdim=True)) + half = CastQuantizer(1, torch.float16) + half.validate(torch.tensor([[65504.]])) + with self.assertRaises(ValueError): + half.validate(torch.tensor([[65505.]])) + # Unchecked conversion follows Torch; it is not a validating API. + torch.testing.assert_close(half.compute_codes(torch.tensor([[65520.]])), + torch.tensor([[65520.]]).half(), rtol=0, atol=0) + + def _known_centroids(self, centroids, **kwargs): + return known_torch_centroids(centroids, **kwargs) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() >= (8, 0), + "NVIDIA SM80 required", + ) + def test_represented_assignment_norms_ties_and_high_finite(self): + for backend in self._floating_backends(): + for dtype in (torch.float16, torch.bfloat16): + for n, k, d in ((17, 7, 3), (31, 13, 65)): + with self.subTest(backend=backend, dtype=dtype, shape=(n, k, d)): + rng = torch.Generator(device="cuda").manual_seed(123+d) + rows = torch.randn(n, d, generator=rng, device="cuda")/4 + centroids = torch.randn(k, d, generator=rng, device="cuda")/4 + reference = (rows.to(dtype).float()[:, None] - + centroids.to(dtype).float()[None]).square().sum(2) + expected_distance, expected_labels = reference.min(1) + for quantizer in (None, CastQuantizer(d, dtype)): + model = self._known_centroids( + centroids, + model_class=QuantizedEmeans, + assignment_backend=backend, + quantizer=quantizer, + assignment_chunk_size=5, + centroid_chunk_size=2, + ) + distance, labels = model.assign( + rows.to(dtype) if quantizer is None else rows + ) + torch.testing.assert_close(labels, expected_labels, rtol=0, atol=0) + torch.testing.assert_close(distance, expected_distance, atol=2e-4, rtol=2e-5) + self.assertEqual((distance.dtype, labels.dtype), (torch.float32, torch.int64)) + small = (1.0001, 1.0004) if dtype == torch.float16 else (1.001, 1.002) + centroids = torch.tensor([[small[0], 0.], [small[1], 0.], [3., 0.]], device="cuda") + rows = centroids[1:2].clone() + self.assertEqual(int(torch.cdist(rows, centroids).argmin(1)), 1) + torch.testing.assert_close(centroids[0].to(dtype), centroids[1].to(dtype), rtol=0, atol=0) + model = self._known_centroids(centroids, assignment_backend=backend, centroid_chunk_size=1) + distance, labels = model.assign(rows.to(dtype)) + self.assertEqual(int(labels[0]), 0) + self.assertEqual(float(distance[0]), 0) + rows = torch.tensor([[-0.4678138, 0.03789843, -0.6960376]], device="cuda") + centroids = torch.tensor([[-0.8843690, 1.0697185, -0.7981653], + [0.4984003, 0.5734861, -0.5365824]], device="cuda") + represented = (rows.bfloat16().float()[:, None] - + centroids.bfloat16().float()[None]).square().sum(2) + wrong_norm = centroids.square().sum(1) - 2*(rows.bfloat16().float()[:, None]* + centroids.bfloat16().float()[None]).sum(2) + self.assertEqual(int(represented.argmin(1)), 0) + self.assertEqual(int(wrong_norm.argmin(1)), 1) + model = self._known_centroids(centroids, assignment_backend=backend, centroid_chunk_size=1) + distance, labels = model.assign(rows.bfloat16()) + self.assertEqual(int(labels[0]), 0) + torch.testing.assert_close(distance, represented[:, 0], atol=1e-6, rtol=0) + centroids = torch.tensor([[300.], [302.]], device="cuda") + rows = torch.tensor([[300.], [301.]], device="cuda", dtype=torch.float16) + self.assertGreater(float(centroids[0].square().sum()), torch.finfo(torch.float16).max) + distance, labels = self._known_centroids(centroids, assignment_backend=backend, centroid_chunk_size=1).assign(rows) + torch.testing.assert_close(labels, torch.zeros(2, dtype=torch.int64, device="cuda"), rtol=0, atol=0) + torch.testing.assert_close(distance, torch.tensor([0., 1.], device="cuda"), rtol=0, atol=0) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() >= (8, 0), + "NVIDIA SM80 required", + ) + def test_represented_empty_metadata_split_and_range(self): + for backend in self._floating_backends(): + for dtype in (torch.float16, torch.bfloat16): + with self.subTest(backend=backend, dtype=dtype): + model = Emeans( + 1, + 2, + assignment_backend=backend, + nepochs=1, + batch_size=2, + alpha0=0.5, + capture_assignments=True, + unused_threshold=0.1, + ) + model.begin(4, torch.tensor([[0.0], [10.0]], device="cuda")) + empty = model.accumulate(torch.empty((0, 1), dtype=dtype, device="cuda")) + self.assertEqual(empty["n"], 0) + model.update(dict(sums=torch.tensor([[2.], [0.]], device="cuda"), + counts=torch.tensor([2., 0.], device="cuda"), + objective=torch.zeros((), dtype=torch.float64, device="cuda"), n=2)) + rows = torch.ones((2, 1), dtype=dtype, device="cuda") + before = model.current_centroids().clone() + partial = model.accumulate(rows[:1]) + self.assertEqual(partial["n"], 1) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + stats = model.accumulate(rows[1:]) + torch.testing.assert_close(stats["labels"], torch.zeros(1, dtype=torch.int64, device="cuda"), rtol=0, atol=0) + self.assertEqual(stats["sums"].dtype, torch.float32) + self.assertEqual(stats["counts"].dtype, torch.float32) + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.finalize(), torch.tensor([[1.], [10.]], device="cuda"), rtol=0, atol=0) + maximum = torch.finfo(dtype).max + donor = torch.tensor([[0., 0.], [1., 1.], [1., 2.], [maximum, 0.]], device="cuda") + child = torch.tensor([[0., 0.], [1.0001, 0.9999], [2., 1.], [maximum, 0.]], device="cuda") + ordinary = child[2].clone() + previous = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode("error") + e_means._separate_splits(donor, child, dtype) + finally: + torch.cuda.set_sync_debug_mode(previous) + self.assertFalse(bool((donor.to(dtype) == child.to(dtype)).all(1).any())) + torch.testing.assert_close(child[2], ordinary, rtol=0, atol=0) + self.assertLess(float(child[3, 0]), maximum) + torch.testing.assert_close(child[:2, 1], torch.tensor([0., 0.9999], device="cuda"), rtol=0, atol=0) + for dtype, value in ((torch.float16, 65504.), (torch.bfloat16, 70000.)): + rows = torch.full((2, 1), value, device="cuda", dtype=dtype) + model = Emeans( + 1, + 1, + assignment_backend=backend, + nepochs=1, + batch_size=2, + alpha0=0.5, + ) + model.train(rows, rows[:1].float()) + torch.testing.assert_close(model.centroids, rows[:1].float(), rtol=0, atol=0) + torch.testing.assert_close(model.assign(rows)[0], torch.zeros(2, device="cuda"), rtol=0, atol=0) + model = Emeans( + 1, + 2, + assignment_backend=backend, + nepochs=1, + batch_size=2, + alpha0=0.5, + unused_threshold=0.1, + ) + model.begin(10, torch.full((2, 1), 65504., device="cuda")) + model.accumulate(torch.empty((0, 1), dtype=torch.float16, device="cuda")) + # A long axis on a light donor puts one copy beyond FP16; nothing is written. + model._removal_stats[0, 0] = 1e6 + centroids, usage = model._centroids.clone(), model._usage.clone() + with self.assertRaisesRegex(ValueError, "65504"): + model._apply_splits(torch.tensor([0], device="cuda"), torch.tensor([1], device="cuda")) + torch.testing.assert_close(model._centroids, centroids, rtol=0, atol=0) + torch.testing.assert_close(model._usage, usage, rtol=0, atol=0) + self.assertEqual(model.n_splits, 0) + rows = torch.zeros((2, 2), device="cuda", dtype=torch.bfloat16) + + @unittest.skipUnless( + torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and torch.cuda.get_device_capability() >= (8, 0), + "NVIDIA SM80 required", + ) + def test_native_and_cast_represented_means(self): + x = torch.tensor([[1.001], [1.002], [3.001], [3.002]], device="cuda") + mean_initial = torch.tensor([[1.0], [3.0]], device="cuda") + for dtype in (torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + q = CastQuantizer(1, dtype) + codes = q.compute_codes(x) + # Compare represented arithmetic with the same no-revival mode. + native = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5, + unused_threshold=0) + cast = QuantizedEmeans( + 1, 2, nepochs=1, batch_size=4, alpha0=0.5, quantizer=q, + unused_threshold=0, + ) + native.train(codes, mean_initial) + cast.train(x, mean_initial) + expected = codes.float().reshape(2, 2, 1).mean(dim=1) + torch.testing.assert_close(native.centroids, expected, atol=0, rtol=0) + torch.testing.assert_close(cast.centroids, expected, atol=0, rtol=0) + torch.testing.assert_close(native.obj, cast.obj, atol=0, rtol=0) + dn, ln = native.assign(codes) + dc, lc = cast.assign(x) + torch.testing.assert_close(dn, dc, atol=0, rtol=0) + torch.testing.assert_close(ln, lc) + self.assertEqual((native.centroids.dtype, dn.dtype), + (torch.float32, torch.float32)) + # Retained decimal T2/N17/B4 fixture includes the final row. + rows = torch.arange(34, device="cuda", dtype=torch.float32).reshape(17, 2)/10 + represented = CastQuantizer(2, dtype).compute_codes(rows) + initial = represented[[0, 5, 10, 16]].float() + saved_rows, saved_initial = rows.clone(), initial.clone() + args = dict(nepochs=2, batch_size=4, alpha0=0.5, seed=7, + unused_threshold=0) + reference = Emeans( + 2, + 4, + assignment_chunk_size=2, + centroid_chunk_size=2, + **args, + ) + reference.train(represented, initial) + q = CastQuantizer(2, dtype) + cast = QuantizedEmeans( + 2, + 4, + quantizer=q, + assignment_chunk_size=2, + centroid_chunk_size=2, + **args, + ) + cast.train(rows, initial) + unblocked = Emeans( + 2, + 4, + assignment_chunk_size=64, + centroid_chunk_size=16, + **args, + ) + unblocked.train(represented, initial) + caller = QuantizedEmeans( + 2, + 4, + quantizer=q, + assignment_chunk_size=2, + centroid_chunk_size=2, + **args, + ) + caller_initial = initial.clone() + caller.begin(len(rows), caller_initial) + caller_initial.fill_(-7) + current = caller.current_centroids() + self.assertEqual((current.dtype, current.device), (torch.float32, initial.device)) + torch.testing.assert_close(current, initial, rtol=0, atol=0) + for epoch in range(2): + generator = torch.Generator(device="cuda").manual_seed(_epoch_seed(7, epoch)) + order = torch.randperm(len(rows), generator=generator, device="cuda") + for begin in range(0, len(rows), 4): + batch = rows[order[begin:begin+4]] + before = caller.current_centroids().clone() + for start in range(0, len(batch), 2): + stats = caller.accumulate(batch[start:start+2]) + if start + 2 < len(batch): + self.assertIsNone(stats["sums"]) + self.assertIsNone(stats["counts"]) + torch.testing.assert_close(caller.current_centroids(), before, rtol=0, atol=0) + self.assertEqual(stats["sums"].dtype, torch.float32) + self.assertEqual(stats["counts"].dtype, torch.float32) + self.assertEqual(stats["objective"].dtype, torch.float64) + caller.update(stats) + caller.end_epoch() + result = caller.finalize() + for other in (cast, unblocked, caller): + torch.testing.assert_close(other.centroids, reference.centroids, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(other.obj, reference.obj, atol=3e-5, rtol=1e-6) + for field in ("nsplit", "imbalance_factor"): + self.assertEqual([s[field] for s in other.iteration_stats], + [s[field] for s in reference.iteration_stats]) + torch.testing.assert_close(cast.assign(rows)[0], reference.assign(represented)[0], atol=1e-6, rtol=1e-6) + torch.testing.assert_close(rows, saved_rows, rtol=0, atol=0) + torch.testing.assert_close(initial, saved_initial, rtol=0, atol=0) + saved_result = result.clone() + caller = QuantizedEmeans( + 2, + 4, + quantizer=q, + assignment_chunk_size=2, + centroid_chunk_size=2, + **args, + ) + caller.train(rows, initial) + torch.testing.assert_close(caller.centroids, saved_result, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(result, saved_result, rtol=0, atol=0) + + def test_local_update_has_no_group_argument(self): + model = Emeans(1, 1, nepochs=1, batch_size=2, alpha0=0.5) + model.begin(4, torch.zeros((1, 1))) + stats = model.accumulate(torch.zeros((2, 1))) + with self.assertRaises(TypeError): + model.update(stats, group=object()) + model.update(stats) + stats = model.accumulate(torch.ones((2, 1))) + with self.assertRaises(TypeError): + model.update(stats, group=object()) + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.finalize(), torch.tensor([[0.5]])) + + def reference_arrays(self): + devices = ("cpu", "cuda") if torch.cuda.is_available() else ("cpu",) + return [(device, lambda values, dtype="float32", device=device: + torch.tensor(values, dtype=getattr(torch, dtype), device=device)) + for device in devices] + + def test_fractional_native_and_numpy_training(self): + rng = np.random.RandomState(123) + centers = (10*rng.randn(4, 6)).astype("float32") + rows = centers[np.arange(80) % 4] + (0.1*rng.randn(80, 6)).astype("float32") + args = dict(nepochs=3, batch_size=len(rows), alpha0=0.2, seed=7) + from faiss.contrib.e_means import NumpyEmeans + + reference = NumpyEmeans(6, 4, **args) + reference.train(rows, centers) + for backend, array in self.reference_arrays(): + with self.subTest(backend=backend): + model = QuantizedEmeans(6, 4, quantizer=None, **args) + model.train(array(rows), array(centers)) + np.testing.assert_allclose(model.centroids.cpu().numpy(), reference.centroids, + atol=2e-5, rtol=1e-6) + np.testing.assert_allclose(model.obj.cpu().numpy(), reference.obj, + atol=3e-3, rtol=1e-3) + self.assertEqual(model.n_splits, reference.n_splits) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA not available") + def test_cuda_local_updates_do_not_synchronize(self): + model = backend_class('cuda')(1, 2, nepochs=1, batch_size=2, alpha0=0.5, **native_options('cuda')) + model.begin(4, torch.tensor([[0.0], [10.0]], device="cuda")) + rows = torch.tensor([[0.0], [1.0]], device="cuda") + donor = torch.zeros((2, 1), device="cuda") + child = donor.clone() + model.update(model.accumulate(rows)) # Preparation outside sync-debug. + previous = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode("error") + model.update(model.accumulate(rows)) + self.assertEqual(model.current_centroids().device, rows.device) + # Split-separation has no standalone public operation; this + # bounded private probe checks its no-host-sync repair path. + e_means._separate_splits(donor, child) + finally: + torch.cuda.set_sync_debug_mode(previous) + model.end_epoch() + torch.testing.assert_close(child, torch.nextafter(donor, torch.full_like(donor, float("inf"))), + rtol=0, atol=0) + torch.testing.assert_close(model.finalize(), torch.tensor([[0.5], [10.0]], device="cuda"), + rtol=0, atol=0) + + @unittest.skipUnless( + torch.cuda.device_count() >= 2, "two CUDA devices required" + ) + def test_noncurrent_device_and_mismatch_recovery(self): + current = torch.cuda.current_device() + device = torch.device("cuda", (current+1) % torch.cuda.device_count()) + rows = torch.tensor([[0.0], [2.0], [10.0], [12.0]], device=device) + initial = rows[[0, 2]].clone() + model = backend_class('cuda')(1, 2, nepochs=1, batch_size=4, alpha0=0.5, **native_options('cuda')) + model.begin(4, initial) + self.assertEqual(model.current_centroids().device, device) + self.assertFalse(model.current_centroids().requires_grad) + model.update(model.accumulate(rows)) + model.end_epoch() + result = model.finalize() + self.assertEqual(result.device, device) + self.assertEqual(torch.cuda.current_device(), current) + torch.testing.assert_close(result, torch.tensor([[1.0], [11.0]], device=device), rtol=0, atol=0) + + def test_large_cpu_batch_preserves_sum_and_count(self): + n = 2**24 + 2 + x = torch.full((n, 1), 0.25) + km = Emeans(1, 1, nepochs=1, batch_size=n, alpha0=1.0) + km.begin(n, torch.zeros((1, 1))) + partial = km.accumulate(x[:2**24]) + self.assertEqual(partial["n"], 2**24) + self.assertIsNone(partial["sums"]) + self.assertIsNone(partial["counts"]) + stats = km.accumulate(x[2**24:]) + self.assertEqual(stats["sums"].dtype, torch.float32) + self.assertEqual(stats["counts"].dtype, torch.float32) + self.assertEqual(stats["sums"][0, 0].item(), n * 0.25) + self.assertEqual(stats["counts"][0].item(), n) + km.update(stats) + km.end_epoch() + self.assertEqual(km.finalize()[0, 0].item(), 0.25) + + def test_caller_batches_match_matrix_training(self): + for device in ("cpu", "cuda") if torch.cuda.is_available() else ("cpu",): + for overrides in ( + dict(batch_size=4, alpha0=0.2, + assignment_chunk_size=2, centroid_chunk_size=2), + {}, + ): + with self.subTest(device=device, overrides=overrides): + # Binary values keep this exact fixture's FP32 sums independent + # of CUDA atomic addition order. + x = torch.arange(51, device=device, dtype=torch.float32) + x = x.reshape(17, 3) / 8 + init = x[[0, 5, 10, 16]].clone() + args = dict(nepochs=3, seed=7, **overrides) + cls = backend_class(device) + matrix, caller = cls(3, 4, **args, **native_options(device)), cls( + 3, 4, **args, **native_options(device) + ) + matrix.train(x, init_centroids=init) + caller.begin(len(x), init) + batch_size = caller.recipe["batch_size"] + for epoch in range(caller.nepochs): + generator = torch.Generator(device=device).manual_seed( + _epoch_seed(caller.seed, epoch) + ) + order = torch.randperm( + len(x), generator=generator, device=device + ) + for begin in range(0, len(x), batch_size): + stats = caller.accumulate(x[order[begin:begin + batch_size]]) + caller.update(stats) + caller.end_epoch() + torch.testing.assert_close( + caller.finalize(), matrix.centroids, rtol=0, atol=0 + ) + torch.testing.assert_close(caller.obj, matrix.obj, rtol=0, atol=0) + self.assertEqual(caller.n_splits, matrix.n_splits) + + def test_closing_mean_and_assign(self): + x = torch.tensor( + [[0.0], [2.0], [10.0], [12.0]], requires_grad=True + ) + init = torch.tensor([[0.0], [10.0]], requires_grad=True) + km = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5) + + centroids, captured_labels = km.train(x, init_centroids=init) + + torch.testing.assert_close(km.centroids, torch.tensor([[1.0], [11.0]])) + self.assertEqual(km.obj[-1], 8.0) + self.assertIs(centroids, km.centroids) + self.assertIs(captured_labels, km.assignments) + self.assertFalse(km.centroids.requires_grad) + km.centroids.requires_grad_() + distance, labels = km.assign(x) + torch.testing.assert_close(distance, torch.ones(4)) + torch.testing.assert_close(labels, torch.tensor([0, 0, 1, 1])) + self.assertFalse(distance.requires_grad) + + def test_alpha_one_preserves_an_empty_cluster(self): + x = torch.tensor([[99.0], [0.0], [1.0], [100.0]]) + init = torch.tensor([[0.0], [100.0]]) + km = Emeans(1, 2, nepochs=1, batch_size=2, alpha0=1.0) + + km.train(x, init_centroids=init) + + torch.testing.assert_close( + km.centroids, torch.tensor([[0.5], [99.5]]) + ) + + def test_closing_mean_uses_only_the_final_pass(self): + x = torch.tensor([[3.0], [4.0], [4.0], [6.0], [12.0]]) + init = torch.tensor([[0.0], [10.0]]) + km = Emeans(1, 2, nepochs=2, batch_size=5, alpha0=1.0, unused_threshold=0) + + km.train(x, init_centroids=init) + + torch.testing.assert_close( + km.centroids, torch.tensor([[4.25], [12.0]]) + ) + + # A private FP64 closing-scan table must be divided before narrowing. + # Use the same non-power-of-two integer ratio for both FP64 and INT64 + # inputs: early FP32 conversion changes the correctly rounded result. + n, total = 1048577, 266199830 + expected = np.float32(np.float64(total) / np.float64(n)) + early = np.float32(np.float32(total) / np.float32(n)) + self.assertNotEqual(expected, early) + for device in ( + ("cpu", "cuda") if torch.cuda.is_available() else ("cpu",) + ): + for dtype in (torch.float64, torch.int64): + with self.subTest(closing_dtype=dtype, device=device): + model = Emeans(1, 2, nepochs=1, batch_size=n, alpha0=0.5, unused_threshold=0) + initial = torch.tensor([[254.], [9.]], device=device) + model.begin(n, initial) + model.update({ + "sums": torch.tensor([[total], [0.]], dtype=torch.float32, + device=device), + "counts": torch.tensor([n, 0.], dtype=torch.float32, + device=device), + "objective": torch.zeros((), dtype=torch.float64, device=device), + "n": n, + }) + model.end_epoch() + retained = model.current_centroids()[1].clone() + # The optional sharded scan supplies this private table; + # no new public FP64 statistics schema is being exercised. + model._pass_sums = torch.tensor([[total], [0]], dtype=dtype, + device=device) + closed = model.finalize() + self.assertEqual(closed.dtype, torch.float32) + self.assertEqual(closed.device, initial.device) + self.assertEqual(closed[0, 0].item(), float(expected)) + torch.testing.assert_close(closed[1], retained, rtol=0, atol=0) + self.assertIs(model.finalize(), closed) + self.assertIsNone(model._pass_sums) + + def test_blocked_assignment_matches_cdist(self): + generator = torch.Generator().manual_seed(123) + x = torch.randn(23, 7, generator=generator) + centroids = torch.randn(11, 7, generator=generator) + km = Emeans(7, 11, nepochs=1, batch_size=11, alpha0=0.5, + centroid_chunk_size=3) + km.train(centroids, init_centroids=centroids) + self.assertEqual(km.recipe["centroid_chunk_size"], 3) + + distance, labels = km.assign(x) + reference = torch.cdist(x, centroids).square() + expected_distance, expected_labels = reference.min(dim=1) + + torch.testing.assert_close( + distance, expected_distance, atol=2e-5, rtol=1e-5 + ) + torch.testing.assert_close(labels, expected_labels) + + def test_blocked_assignment_breaks_ties_by_index(self): + x = torch.zeros((1, 2)) + centroids = torch.ones((5, 2)) + km = Emeans(2, 5, nepochs=1, batch_size=5, alpha0=0.5, + centroid_chunk_size=2) + km.train(centroids, init_centroids=centroids) + + _, labels = km.assign(x) + + self.assertEqual(labels.item(), 0) + + def test_revival_occurs_during_training(self): + x = torch.zeros((10, 1)) + init = torch.tensor([[0.0], [10.0]]) + km = Emeans(1, 2, nepochs=5, batch_size=10, alpha0=0.5, + unused_threshold=0.1) + + km.train(x, init_centroids=init) + + self.assertEqual(km.n_splits, 1) + + def test_chunking_does_not_change_updates(self): + generator = torch.Generator().manual_seed(123) + x = torch.randn(41, 5, generator=generator) + init = x[:4].clone() + args = {"nepochs": 3, "batch_size": 13, "alpha0": 0.2, "seed": 7} + a = Emeans( + 5, + 4, + assignment_chunk_size=4, + centroid_chunk_size=2, + **args, + ) + b = Emeans( + 5, + 4, + assignment_chunk_size=64, + centroid_chunk_size=8, + **args, + ) + + a.train(x, init_centroids=init) + b.train(x, init_centroids=init) + + torch.testing.assert_close( + a.centroids, b.centroids, atol=2e-6, rtol=1e-6 + ) + torch.testing.assert_close(a.obj, b.obj, atol=2e-5, rtol=1e-6) + + def test_training_does_not_advance_global_rng(self): + for device in ("cpu", "cuda") if torch.cuda.is_available() else ("cpu",): + with self.subTest(device=device): + x = torch.arange(80, dtype=torch.float32, device=device).reshape(20, 4) + cpu_state = torch.random.get_rng_state() + state = torch.cuda.get_rng_state() if device == "cuda" else cpu_state + km = backend_class(device)(4, 3, nepochs=1, batch_size=7, + alpha0=0.2, **native_options(device)) + km.train(x) + after = torch.cuda.get_rng_state() if device == "cuda" else torch.random.get_rng_state() + self.assertTrue(torch.equal(state, after)) + self.assertTrue(torch.equal(cpu_state, torch.random.get_rng_state())) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA not available") + def test_cuda_replay_failure_drains_and_fresh_model_recovers(self): + cases = [(torch.float32, None)] + if not torch.version.hip and torch.cuda.get_device_capability() >= (8, 0): + cases.extend(((torch.bfloat16, None), + (torch.float32, CastQuantizer(3, torch.bfloat16)))) + for dtype, quantizer in cases: + with self.subTest(dtype=dtype, quantizer=quantizer is not None): + self._check_cuda_replay_failure(dtype, quantizer) + if "triton" in self._floating_backends(): + self._check_cuda_replay_failure(torch.float32, None, "triton") + self._check_cuda_replay_failure(torch.bfloat16, None, "triton") + if FP8_CUDA: + self._check_cuda_replay_failure(torch.float32, Fp8Quantizer(3), "triton") + if INT8_CUDA: + self._check_cuda_replay_failure(torch.uint8, None, "triton") + self._check_cuda_replay_failure(torch.float32, Int8Quantizer(3), "triton") + from torch_test_e_means_cute import _ready + if _ready(): + self._check_cuda_replay_failure(torch.bfloat16, None, "cute") + self._check_cuda_replay_failure(torch.float32, CastQuantizer(3, torch.bfloat16), "cute") + self._check_cuda_replay_failure(torch.float32, Fp8Quantizer(3), "cute") + self._check_cuda_replay_failure(torch.uint8, None, "cute") + self._check_cuda_replay_failure(torch.float32, Int8Quantizer(3), "cute") + + + @unittest.skipUnless(torch.cuda.is_available(), 'CUDA required') + def test_replay_accepts_either_fitted_law(self): + # An explicit throughput recipe at d <= 16, where batch_law="auto" + # resolves to the quality law, keeps CUDA-graph replay; other manual + # recipes still train eagerly. + from faiss.contrib.e_means.base import _resolve_recipe + n, d, k, nepochs = 100_000, 8, 64, 5 + x = torch.rand(n, d, device='cuda') + throughput = _resolve_recipe(n, k, nepochs, "throughput", None, None) + quality = _resolve_recipe(n, k, nepochs, "quality", None, None) + self.assertNotEqual(throughput, quality) + cases = [ + ({}, True), + ({"batch_size": throughput[0], "alpha0": throughput[1]}, True), + ({"batch_size": quality[0], "alpha0": quality[1]}, True), + ({"batch_size": throughput[0], "alpha0": throughput[1] / 2}, False), + ] + for options, expected in cases: + with self.subTest(options=options): + model = Emeans(d, k, nepochs=nepochs, assignment_backend='native', **options) + model._resolve_assignment_backend(x) + model.begin(n, x[:k].clone()) + self.assertEqual(model._replay_eligible(x), expected) + + @unittest.skipUnless(torch.cuda.is_available(), 'CUDA required') + def test_equivalent_replay_preserves_real_assignment_and_step_hooks(self): + class Inherited(QuantizedEmeans): + pass + + class AssignObserved(QuantizedEmeans): + def _assign_rows(self, *args, **kwargs): + self.assign_calls += 1 + return super()._assign_rows(*args, **kwargs) + + class StepObserved(QuantizedEmeans): + def _finish_step(self, expected_n): + self.step_calls += 1 + return super()._finish_step(expected_n) + + class InvalidateObserved(QuantizedEmeans): + def _invalidate_readout(self): + self.invalidate_calls += 1 + return super()._invalidate_readout() + + rows = torch.tensor([0., .25, .5, .75, 10., 10.25, 10.5, 10.75], + device='cuda').repeat(4)[:, None] + initial = torch.tensor([[0.], [10.]], device='cuda') + captures = {} + capture = Emeans._capture_step + + def recorded(model, *args, **kwargs): + captures[id(model)] = captures.get(id(model), 0) + 1 + return capture(model, *args, **kwargs) + + args = dict(nepochs=3, seed=7, quantizer=None, assignment_backend='native') + models = [] + invalidation = None + with highest_fp32('cuda'), mock.patch.object(Emeans, '_capture_step', new=recorded): + automatic = QuantizedEmeans(1, 2, **args) + automatic.train(rows, initial) + models.append(automatic) + self.assertGreater(captures.get(id(automatic), 0), 0) + equal = dict(batch_size=automatic.recipe['batch_size'], alpha0=automatic.recipe['alpha0'], + assignment_chunk_size=automatic.recipe['assignment_chunk_size']) + for cls in (QuantizedEmeans, Inherited, StepObserved, AssignObserved, InvalidateObserved): + explicit = dict(equal) + if cls is QuantizedEmeans: + explicit['alpha0'] = None # Same law-derived B; no added fit. + model = cls(1, 2, **args, **explicit) + model.assign_calls = model.step_calls = 0 + model.invalidate_calls = 0 + model.train(rows, initial) + models.append(model) + if cls is QuantizedEmeans: + self.assertEqual(model.recipe['name'], 'manual_batch') + self.assertEqual(model.recipe['alpha0_source'], 'step_law') + self.assertEqual(model.recipe['alpha0'], automatic.recipe['alpha0']) + if cls in (AssignObserved, InvalidateObserved): + self.assertEqual(captures.get(id(model), 0), 0) + if cls is AssignObserved: + self.assertEqual(model.assign_calls, model.recipe['total_steps']) + else: + invalidation = model + else: + self.assertGreater(captures.get(id(model), 0), 0) + if cls is StepObserved: + self.assertEqual(model.step_calls, model.recipe['total_steps']) + eager = InvalidateObserved(1, 2, **args) + eager.invalidate_calls = 0 + with mock.patch.object(eager, '_replay_eligible', return_value=False): + eager.train(rows, initial) + models.append(eager) + self.assertEqual(captures.get(id(eager), 0), 0) + self.assertEqual(invalidation.invalidate_calls, eager.invalidate_calls) + for model in models[1:]: + for field in ('centroids', 'obj', 'assignments'): + torch.testing.assert_close(getattr(model, field), getattr(automatic, field), rtol=0, atol=0) + self.assertEqual(model.n_splits, automatic.n_splits) + + @unittest.skipUnless(TRITON_CUDA, 'Triton CUDA required') + def test_fusible_quantized_split_preserves_supplied_separation(self): + model = QuantizedEmeans(1, 2, nepochs=1, batch_size=2, quantizer=None, + assignment_backend='triton') + model.begin(2, torch.tensor([[1.], [4.]], device='cuda')) + model.accumulate(torch.ones((2, 1), dtype=torch.bfloat16, device='cuda')) + mass = model._usage[0].clone() + calls = [] + + def supplied(donor, child): + calls.append(True) + child[:, 0] = 42 + + with mock.patch.object(model, '_separate_split_values', new=supplied): + model._apply_splits(torch.tensor([0], device='cuda'), torch.tensor([1], device='cuda')) + self.assertEqual(calls, [True]) + self.assertEqual(model._centroids[1, 0].item(), 42.) + torch.testing.assert_close(model._usage[:2], mass.expand(2)/2, rtol=0, atol=0) + + def _check_cuda_replay_failure(self, dtype, quantizer, backend="native"): + x = (torch.arange(93, device="cuda", dtype=torch.float32) / 8).reshape(31, 3) + initial = x[[0, 5, 10, 16]].clone() + x = x.to(dtype) + if isinstance(quantizer, Fp8Quantizer): + quantizer.train(x) + if isinstance(quantizer, Int8Quantizer): + quantizer.train(x) + x = quantizer.compute_codes(x) + saved_input, saved_initial = x.clone(), initial.clone() + model_class = QuantizedEmeans + codec = {"quantizer": quantizer} + replay, reset = torch.cuda.CUDAGraph.replay, torch.cuda.CUDAGraph.reset + + class InjectedFailure(BaseException): + pass + + for error_type in (RuntimeError, InjectedFailure): + with self.subTest(error_type=error_type.__name__): + model = model_class( + 3, + 4, + nepochs=3, + seed=7, + **codec, + assignment_backend=backend, + capture_assignments=True, + ) + events, retired = [], [] + + def fail_after_replay( + graph, + _error_type=error_type, + _events=events, + _replay=replay, + ): + # Torch's test-only delay is needed to prove work remains + # queued behind the delay at the host raise. + torch.cuda._sleep(50_000_000) + _replay(graph) + done = torch.cuda.Event() + done.record() + _events.append(done) + self.assertFalse(done.query()) + raise _error_type("injected replay failure") + + def checked_reset( + graph, + _events=events, + _reset=reset, + _retired=retired, + ): + if _events: + complete = _events[-1].query() + _retired.append(complete) + self.assertTrue(complete) # BEFORE pool retirement. + _reset(graph) + + with mock.patch.object(torch.cuda.CUDAGraph, "replay", fail_after_replay), \ + mock.patch.object(torch.cuda.CUDAGraph, "reset", checked_reset): + with self.assertRaisesRegex(error_type, "injected replay failure"): + model.train(x, initial) + self.assertEqual(len(events), 1) # No retry. + self.assertTrue(retired) + self.assertIsNone(model.assignments) + model = model_class( + 3, + 4, + nepochs=3, + seed=7, + **codec, + assignment_backend=backend, + capture_assignments=True, + ) + recovered = [] + + def counted_replay(graph): + recovered.append(True) # noqa: B023 - rebound for closing replay + replay(graph) + + with mock.patch.object(torch.cuda.CUDAGraph, "replay", counted_replay): + model.train(x, initial) + self.assertTrue(recovered) + reference = model_class( + 3, + 4, + nepochs=3, + seed=7, + assignment_backend=backend, + assignment_chunk_size=2, + **codec, + capture_assignments=True, + ) + # The explicit override keeps this reference eager. + reference.train(x, initial) + torch.testing.assert_close(model.centroids, reference.centroids, rtol=0, atol=0) + torch.testing.assert_close(model.obj, reference.obj, rtol=0, atol=0) + torch.testing.assert_close(model.assignments, reference.assignments, rtol=0, atol=0) + self.assertEqual(model.n_splits, reference.n_splits) + torch.testing.assert_close(x, saved_input, rtol=0, atol=0) + torch.testing.assert_close(initial, saved_initial, rtol=0, atol=0) + + # A one-epoch capture already owns closing sums at capture time. + recovered = [] + single = model_class( + 3, + 4, + nepochs=1, + seed=7, + **codec, + assignment_backend=backend, + capture_assignments=True, + ) + with mock.patch.object(torch.cuda.CUDAGraph, "replay", counted_replay): + single.train(x, initial) + self.assertTrue(recovered) + eager = model_class( + 3, + 4, + nepochs=1, + seed=7, + assignment_chunk_size=2, + **codec, + assignment_backend=backend, + capture_assignments=True, + ) + eager.train(x, initial) + torch.testing.assert_close(single.centroids, eager.centroids, rtol=0, atol=0) + torch.testing.assert_close(single.obj, eager.obj, rtol=0, atol=0) + torch.testing.assert_close(single.assignments, eager.assignments, rtol=0, atol=0) + + +class EmeansBackendContractsTest(unittest.TestCase): + def test_public_emeans_has_distinct_canonical_hierarchy(self): + import faiss.contrib.e_means as package + from faiss.contrib.e_means.base import _EmeansBase + from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids + from faiss.contrib.e_means.sharded_centroids_ivf import EmeansShardedCentroidsIVF + + self.assertIs(package.Emeans, Emeans) + self.assertIs(package.QuantizedEmeans, QuantizedEmeans) + self.assertIs(package.NumpyEmeans, NumpyEmeans) + self.assertIsNot(Emeans, QuantizedEmeans) + self.assertEqual(Emeans.__name__, "Emeans") + self.assertEqual(QuantizedEmeans.__name__, "QuantizedEmeans") + self.assertEqual(Emeans.__bases__, (_EmeansBase,)) + self.assertEqual(QuantizedEmeans.__bases__, (Emeans,)) + self.assertEqual(NumpyEmeans.__bases__, (_EmeansBase,)) + self.assertTrue(issubclass(DistributedEmeans, QuantizedEmeans)) + self.assertTrue(issubclass(DistributedNumpyEmeans, NumpyEmeans)) + self.assertEqual(EmeansShardedCentroids.__bases__, (QuantizedEmeans,)) + self.assertEqual(EmeansShardedCentroidsIVF.__bases__, (EmeansShardedCentroids,)) + for module in (package, e_means, + sys.modules[NumpyEmeans.__module__], + sys.modules[QuantizedEmeans.__module__]): + for name in ("TorchEmeans", "QuantizedTorchEmeans", "NumPyEmeans", "DistributedNumPyEmeans"): + self.assertFalse(hasattr(module, name), (module.__name__, name)) + with self.assertRaises(TypeError): + Emeans(1, 1, quantizer=None) + rows = torch.tensor([[0.], [2.], [10.], [12.]]) + for model_class in (Emeans, QuantizedEmeans): + with self.subTest(model_class=model_class.__name__): + model = model_class(1, 2, nepochs=1, batch_size=4, alpha0=.5) + model.train(rows, rows[[0, 2]]) + torch.testing.assert_close(model.centroids, torch.tensor([[1.], [11.]]), rtol=0, atol=0) + + def test_triton_byte_spherical_is_rejected_before_l2_dispatch(self): + model = QuantizedEmeans(2, 1, assignment_backend="triton", spherical=True) + model._execution_backend = torch_backend.TritonBackend(model.centroid_chunk_size) + model._input_dtype = torch.int8 + with mock.patch("faiss.contrib.e_means.e_means_quantized._get_triton_int8_functions") as factory: + with self.assertRaisesRegex(ValueError, "L2 only"): + model._assign_rows(torch.tensor([[1, 0]], dtype=torch.int8), object()) + factory.assert_not_called() + + def test_cute_fp8_fuses_only_existing_floating_sources(self): + q = Fp8Quantizer(2) + q.train(torch.tensor([[1., 2.], [2., 4.]])) + model = QuantizedEmeans(2, 1, quantizer=q, assignment_backend="cute") + model._execution_backend = torch_backend.CuteBackend(model.centroid_chunk_size) + for dtype in (torch.float32, torch.float16, torch.bfloat16): + rows = torch.tensor([[1., 2.]], dtype=dtype) + torch.testing.assert_close(model._prepare_rows(rows), rows.float(), rtol=0, atol=0) + codes = q.compute_codes(torch.tensor([[1., 2.]])) + prepared = model._prepare_rows(codes) + self.assertEqual(prepared.dtype, codes.dtype) + self.assertEqual(prepared.data_ptr(), codes.data_ptr()) + torch.testing.assert_close(prepared.view(torch.uint8), codes.view(torch.uint8), rtol=0, atol=0) + with mock.patch.object(q, "compute_codes", side_effect=TypeError("floating source required")): + with self.assertRaisesRegex(TypeError, "floating source"): + model._prepare_rows(torch.ones((1, 2), dtype=torch.int8)) + + def test_auto_query_transition_retains_cute_owner_and_public_outputs(self): + from types import SimpleNamespace + + owners = [] + def prepare(centroids, cache, **kwargs): + if cache is None: + cache = SimpleNamespace(centroids=centroids) + owners.append(cache) + self.assertIs(cache.centroids, centroids) + return cache + def assign(rows, cache, distances, labels): + values, ids = (rows[:, None] - cache.centroids).square().sum(-1).min(1) + distances.copy_(values) + labels.copy_(ids) + return distances, labels + + model = known_torch_centroids(torch.tensor([[0.], [10.]]), assignment_chunk_size=2) + training_backend, recipe = model._execution_backend, dict(model.recipe) + captured = model.assignments + rows = torch.tensor([[1.], [9.], [2.]]) + with mock.patch.object(e_means, "select_backend", return_value=torch_backend.CuteBackend), \ + mock.patch.object(torch_backend, "_get_cute_functions", + return_value=(assign, prepare, lambda device: None)): + first = model.assign(rows) + saved = tuple(value.clone() for value in first) + model.assign(rows) + model.centroids.copy_(model.centroids.flip(0)) + changed = model.assign(rows) + self.assertEqual(len(owners), 1) + self.assertIs(model._query_backend.cache, owners[0]) + self.assertIs(model._execution_backend, training_backend) + self.assertEqual(model.recipe, recipe) + self.assertIs(model.assignments, captured) + torch.testing.assert_close(changed[1], torch.tensor([1, 0, 1]), rtol=0, atol=0) + for value, expected in zip(first, saved): + torch.testing.assert_close(value, expected, rtol=0, atol=0) + + def test_inherited_accumulation_handles_statistics_dtype_changes(self): + from faiss.contrib.e_means.torch_backend import ( + TorchBackend, + TritonBackend, + CuteBackend, + ) + + rows = torch.tensor([[2.0, 4.0], [8.0, 12.0]]) + labels = torch.tensor([0, 2]) + for cls in (TorchBackend, TritonBackend, CuteBackend): + backend = cls(4096) + for dtype in (torch.float32, torch.float64): + with self.subTest(backend=cls.__name__, dtype=dtype): + stats = torch.zeros((3, 3), dtype=dtype) + backend.begin_batch(stats, 2) + backend.accumulate(rows, labels, stats, 2) + torch.testing.assert_close( + stats, + torch.tensor( + [ + [2.0, 4.0, 1.0], + [0.0, 0.0, 0.0], + [8.0, 12.0, 1.0], + ], + dtype=dtype, + ), + ) + + def test_inherited_ema_handles_dense_and_sparse_statistics(self): + from faiss.contrib.e_means.torch_backend import ( + TorchBackend, + TritonBackend, + CuteBackend, + ) + + sums = torch.tensor([[2.0, 4.0], [0.0, 0.0], [8.0, 12.0]]) + counts = torch.tensor([1.0, 0.0, 1.0]) + for cls in (TorchBackend, TritonBackend, CuteBackend): + for ids in (None, torch.tensor([0, 2])): + with self.subTest( + backend=cls.__name__, sparse=ids is not None + ): + centroids = torch.tensor( + [[0.0, 0.0], [4.0, 4.0], [10.0, 10.0]] + ) + usage = torch.ones(3) + cls(4096).update( + centroids, + usage, + ids, + sums if ids is None else sums[ids], + counts if ids is None else counts[ids], + alpha=0.5, + decay=0.5, + replace_usage=False, + ) + torch.testing.assert_close( + centroids, + torch.tensor( + [ + [1.0, 2.0], + [4.0, 4.0], + [9.0, 11.0], + ] + ), + ) + torch.testing.assert_close( + usage, torch.tensor([1.0, 0.5, 1.0]) + ) + + def test_inherited_split_places_half_means_and_halves_usage(self): + from faiss.contrib.e_means.torch_backend import ( + TorchBackend, + TritonBackend, + CuteBackend, + ) + + for cls in (TorchBackend, TritonBackend, CuteBackend): + with self.subTest(backend=cls.__name__): + centroids = torch.tensor([[4.0, 4.0], [0.0, 0.0]]) + usage = torch.tensor([2.0, 0.0]) + # s = sqrt(2 ||U|| / (pi N)) = 1 along the axis (0.6, 0.8). + cls(4096).split( + centroids, + usage, + torch.tensor([0]), + torch.tensor([1]), + torch.float32, + axes=torch.tensor([[0.6, 0.8], [1.0, 0.0]]), + norm=torch.tensor([math.pi, 0.0], dtype=torch.float64), + ) + torch.testing.assert_close( + centroids, + torch.tensor( + [ + [3.4, 3.2], + [4.6, 4.8], + ] + ), + ) + torch.testing.assert_close(usage, torch.ones(2)) + + def test_cute_dispatch_retains_cache_and_writes_query_output_views(self): + from types import SimpleNamespace + from faiss.contrib.e_means import torch_backend + + pointers = [] + + def prepare(centroids, cache, **kwargs): + if cache is None: + return SimpleNamespace( + centroids=centroids, source_version=0, bindings={} + ) + self.assertIs(cache.centroids, centroids) + return cache + + def assign(rows, prepared, distances, labels): + reference = (rows[:, None] - prepared.centroids).square().sum(-1) + values, ids = reference.min(1) + distances.copy_(values) + labels.copy_(ids) + pointers.append((distances.data_ptr(), labels.data_ptr())) + return distances, labels + + model = known_torch_centroids( + torch.tensor([[0.0], [10.0]]), + assignment_backend="cute", + assignment_chunk_size=2, + ) + rows = torch.tensor([[1.0], [9.0], [2.0]]) + with mock.patch.object( + torch_backend, + "_get_cute_functions", + return_value=(assign, prepare, lambda device: None), + ): + distance, labels = model.assign(rows) + query_backend = model._query_backend + cache = query_backend.capture_state() + model.assign(rows + 100) + torch.testing.assert_close(distance, torch.tensor([1.0, 1.0, 4.0])) + torch.testing.assert_close(labels, torch.tensor([0, 1, 0])) + self.assertEqual( + pointers[:2], + [ + (distance.data_ptr(), labels.data_ptr()), + (distance[2:].data_ptr(), labels[2:].data_ptr()), + ], + ) + self.assertIs(model._query_backend, query_backend) + self.assertIs(query_backend.cache, cache) + self.assertIsNone(cache.source_version) + query_backend.finish_capture(cache, captured=False) + self.assertIsNone(query_backend.cache) + + def test_floating_class_keeps_fp32_state_on_cpu(self): + from faiss.contrib.e_means import Emeans + + for dtype in (torch.float32, torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + model = Emeans(1, 2, nepochs=1, batch_size=4, alpha0=0.5) + rows = torch.tensor([[0], [2], [10], [12]], dtype=dtype) + initial = torch.tensor([[0], [10]], dtype=torch.float32) + centroids, assignments = model.train(rows, initial) + self.assertIs(centroids, model.centroids) + torch.testing.assert_close(assignments, torch.tensor([0, 0, 1, 1])) + self.assertEqual(model.obj.item(), 8) + self.assertEqual(model.centroids.dtype, torch.float32) + torch.testing.assert_close( + model.centroids, initial + 1, rtol=0, atol=0 + ) + + def test_floating_execution_does_not_load_encoded_modules(self): + import faiss.contrib + + code = """ +import builtins +import sys +import torch +import faiss.contrib +faiss.contrib.__path__.insert(0, sys.argv[1]) +original_import = builtins.__import__ +def floating_only(name, *args, **kwargs): + if name.endswith(( + 'quantizer_fp8', 'quantizer_int8', 'triton_assignment', 'cute' + )): + raise AssertionError('native execution loaded an optional module') + return original_import(name, *args, **kwargs) +builtins.__import__ = floating_only +from faiss.contrib.e_means import Emeans +model = Emeans(1, 1, nepochs=1, batch_size=2, alpha0=.5) +model.train(torch.tensor([[0.], [2.]])) +assert model.centroids.item() == 1 +""" + child = subprocess.run( + [sys.executable, "-c", code, str(Path(faiss.contrib.__file__).resolve().parent)], + text=True, + capture_output=True, + timeout=60, + ) + self.assertEqual(child.returncode, 0, child.stderr) + + @unittest.skipUnless(INT8_CUDA, "qualified INT8 CUDA device required") + def test_quantized_caller_batches_match_matrix_training(self): + from faiss.contrib.e_means import QuantizedEmeans + + rows = torch.tensor( + [[0], [2], [10], [12]], dtype=torch.uint8, device="cuda" + ) + initial = rows[[0, 2]].float() + args = { + "nepochs": 1, + "batch_size": 4, + "alpha0": 0.5, + "assignment_backend": "triton", + "capture_assignments": True, + } + model = QuantizedEmeans(1, 2, **args) + control = QuantizedEmeans(1, 2, **args) + model.begin(4, initial) + stats = model.accumulate(rows) + self.assertEqual(stats["sums"].dtype, torch.int64) + self.assertEqual(stats["counts"].dtype, torch.int64) + model.update(stats) + model.end_epoch() + model.finalize() + control.train(rows, initial) + torch.testing.assert_close( + model.centroids, control.centroids, rtol=0, atol=0 + ) + torch.testing.assert_close(model.obj, control.obj, rtol=0, atol=0) + + +def _check_closing_handover(case, x, init, backends, spherical=False, nepochs=1): + """One run per backend: rows held by a centroid revived while closing take + their second-nearest from the same assignment unless it moved after them + too, and are otherwise assigned again; closing means match the returned + labels, and the training error is lower than with the labels before.""" + for backend in backends: + km = Emeans(x.shape[1], len(init), nepochs=nepochs, batch_size=500, assignment_backend=backend, + spherical=spherical) + state = {} + + def handover_finish(order, rows, km=km, state=state, finish=km._handover_finish): + h = km._handover + state.update(before=h["labels"].clone(), second=h["second"].clone(), + moved_at=h["moved_at"].clone(), order=order[:rows].clone()) + return finish(order, rows) + + def finalize(km=km, state=state, finalize=km.finalize): + state["ema"] = km._centroids.clone() + return finalize() + + km._handover_finish, km.finalize = handover_finish, finalize + centroids, labels = km.train(x, init) + before = state["before"] + case.assertEqual(km.recipe["closing_handover"], "second_nearest") + case.assertGreater(km.closing_handover_stats["second"], 0) + rows = x.float() + # The rule, row by row, in visiting order. + order, second, moved_at = state["order"], state["second"].long(), state["moved_at"] + rank = torch.empty_like(order) + rank[order] = torch.arange(len(order), device=order.device) + visited = torch.zeros(len(x), dtype=torch.bool, device=order.device) + visited[order] = True + stale = visited & (rank < moved_at[before.clamp_min(0)]) + case.assertTrue(bool((second[stale] >= 0).all()), backend) # Every stale row has one. + handed = stale & (moved_at[second.clamp_min(0)] <= rank) + searched = stale & ~handed + case.assertEqual(int(handed.sum()), km.closing_handover_stats["second"], backend) + case.assertEqual(int(searched.sum()), km.closing_handover_stats["searched"], backend) + # Other rows change only to a centroid of a split made after them (the twin reassignment), + # and only when it is nearer to the positions training ended on. + changed = visited & ~stale & (labels != before) + case.assertTrue(bool((moved_at[labels[changed]] > rank[changed]).all()), backend) + ema = state["ema"].double() + if not spherical: + gap = ((rows[changed].double() - ema[labels[changed]]).square().sum(1) + - (rows[changed].double() - ema[before[changed]]).square().sum(1)) + case.assertTrue(bool((gap <= 1e-6).all()), backend) + case.assertTrue(bool((labels[handed] == second[handed]).all()), backend) + case.assertTrue(bool((second[visited] != before[visited]).all()), backend) + if searched.any(): + # Searched rows: nearest to the EMA positions training ended on + # (up to the backend's assignment rounding). + ema = state["ema"].double() + if spherical: + ema = torch.nn.functional.normalize(ema, dim=1) + distance = torch.cdist(rows[searched].double(), ema).square() + chosen = distance.gather(1, labels[searched][:, None])[:, 0] + case.assertTrue(bool((chosen <= distance.min(1).values * (1 + 1e-2) + 1e-3).all()), backend) + + def closing(lab, centroids=centroids, rows=rows): + sums = torch.zeros_like(centroids, dtype=torch.float64).index_add_(0, lab, rows.double()) + counts = torch.bincount(lab, minlength=len(centroids)) + closed = counts > 0 # Every centroid with rows returns their mean. + mean = sums[closed] / counts[closed, None] + if spherical: + mean = torch.nn.functional.normalize(mean, dim=1) + out = centroids.clone() + out[closed] = mean.float() + return out + + torch.testing.assert_close(centroids, closing(labels), rtol=1e-5, atol=1e-5) + error = float((rows - centroids[labels]).square().sum(1).mean()) + without = float((rows - closing(before)[before]).square().sum(1).mean()) + case.assertLess(error, without, backend) + + +def _handover_mixture(): + # Draw 12: a pair moves only if its split pays (the profit check), so draws 1-11 leave at most one + # closing-pass revival at nepochs=1.6; draw 12 leaves at least 10 in every configuration tested here. + rs = np.random.RandomState(12) + x = ((rs.randn(64, 8) * 4)[rs.randint(0, 64, 20000)] + rs.randn(20000, 8)).astype("float32") + return torch.from_numpy(x), torch.from_numpy(x[rs.choice(len(x), 64, replace=False)]) + + +def _check_twin_rule(case, numpy_class): + """Twin reassignment on hand-made closing-pass records: rows the stale + rule relabels keep that label, any other row moves only to the child of a + split made after it and only when that child is nearer, and both ends of + every split close from their final rows.""" + rs = np.random.RandomState(1) + k, d, n = 6, 3, 80 + x = rs.randn(n, d).astype("float32") + centroids = rs.randn(k, d).astype("float32") + labels = rs.randint(0, k, n) + second = np.where(labels == 5, 3, 5) # Never revived, so every stale row takes it. + order = rs.permutation(n) + # Splits (target, donor, rows done): 0 -> 1 at 20, 1 -> 2 at 40, 0 -> 4 at 50, 4 moved again from 3 at 70. + events = [(np.array([1]), np.array([0]), 20), (np.array([2]), np.array([1]), 40), + (np.array([4]), np.array([0]), 50), (np.array([4]), np.array([3]), 70)] + moved_at = np.array([-1, 20, 40, -1, 70, -1]) + moved = np.isin(np.arange(k), [0, 1, 2, 3, 4]) + if numpy_class: + km = NumpyEmeans(d, k, nepochs=1, batch_size=500) + km.begin(n, centroids) + out = labels.copy() + km._handover_start(out, second.astype("int16"), x) + km._handover.update(moved_at=moved_at.copy(), events=events) + km._pass_sums, km._pass_counts = np.zeros((k, d), "float32"), np.zeros(k) + km._handover_finish(order, n) + final, counts = out, np.asarray(km._pass_counts) + else: + km = Emeans(d, k, nepochs=1, batch_size=500, assignment_backend="native") + tx = torch.from_numpy(x) + km.begin(n, torch.from_numpy(centroids)) + km._prepare_input(tx) + out = torch.from_numpy(labels.copy()) + km._handover_start(out, tx, second=True) + km._handover["second"].copy_(torch.from_numpy(second)) + km._handover["moved_at"].copy_(torch.from_numpy(moved_at)) + km._handover["events"] = [(torch.from_numpy(t), torch.from_numpy(s), None, b) for t, s, b in events] + km._pass_sums, km._pass_counts = torch.zeros(k, d), torch.zeros(k) + km._handover_finish(torch.from_numpy(order), n) + final, counts = out.numpy(), km._pass_counts.numpy() + rank = np.empty(n, dtype=int) + rank[order] = np.arange(n) + stale = rank < moved_at[labels] + np.testing.assert_array_equal(final[stale], second[stale]) # Exempt from twin reassignment. + changed = ~stale & (final != labels) + case.assertTrue(changed.any()) + case.assertTrue((moved_at[final[changed]] > rank[changed]).all()) + def near(lab): + return np.square((x[changed] - centroids[lab]).astype("float64")).sum(1) + case.assertTrue((near(final[changed]) <= near(labels[changed])).all()) + np.testing.assert_array_equal(counts[moved], np.bincount(final, minlength=k)[moved]) + + +@unittest.skipUnless(TRITON_CUDA, "CUDA with Triton required") +class TestClosingSums(unittest.TestCase): + def test_sums_of_grouped_rows_including_one_large_group(self): + from faiss.contrib.e_means.triton_assignment import closing_sums + + torch.manual_seed(0) + n, k, d, step = 20000, 7, 33, 3000 + x = torch.randn(n, d, device="cuda").bfloat16() + labels = torch.cat((torch.zeros(12000, dtype=torch.int64), torch.randint(1, k, (n - 12000,)))).cuda() + labels[torch.randperm(n, device="cuda")[:50]] = 3 + index = torch.argsort(labels, stable=True) + starts = torch.searchsorted(labels[index], torch.arange(k + 1, device="cuda")) + sums = torch.ones(k, d, device="cuda") + counts = torch.ones(k, dtype=torch.float64, device="cuda") + closing_sums(x, index, starts, sums, counts, step) + want = torch.ones(k, d, dtype=torch.float64, device="cuda").index_add_(0, labels, x.double()) + torch.testing.assert_close(sums.double(), want, rtol=1e-6, atol=1e-4) + torch.testing.assert_close(counts, 1 + torch.bincount(labels, minlength=k).double()) + + def test_encoded_closing_sums_keep_numeric_units(self): + from faiss.contrib.e_means.triton_assignment import closing_sums + + cases = [(torch.int8, 127, 2**18 + 13), (torch.uint8, 255, 2**18 + 13)] + if FP8_CUDA: + cases.append((torch.float8_e4m3fn, None, 13)) + for dtype, value, n in cases: + with self.subTest(dtype=dtype): + rows = (torch.full((n, 1), value, device="cuda").to(dtype) if value is not None else + torch.tensor([0., -0., 448., -448., 2**-9, -2**-9, 1.125, + -3.5, 2., 16., -16., .5, .25], device="cuda").to(dtype)[:, None]) + index = torch.arange(n - 1, -1, -1, device="cuda") + sums = torch.zeros(1, 1, device="cuda", dtype=torch.int64 if value else torch.float64) + counts = torch.zeros(1, dtype=torch.float64, device="cuda") + closing_sums(rows, index, torch.tensor([0, n], device="cuda"), sums, counts, 65536) + expected = rows.long().sum(0) if value else rows.float().double().sum(0) + torch.testing.assert_close(sums[0], expected, rtol=0, atol=0) + self.assertEqual(counts.item(), n) + + def test_cast_rounding_matches_precast_rows(self): + from faiss.contrib.e_means.triton_assignment import closing_sums + + # Half-ulp ties of both parities in BF16 and FP16; signs and row order vary. + for dtype, bits in ((torch.bfloat16, 7), (torch.float16, 10)): + x = torch.tensor([1 + i * 2.**(-bits-1) for i in (1, 3, 5, 7)], + device="cuda")[:, None] + x = torch.cat((x, -x)) + index = torch.tensor([6, 1, 4, 3, 0, 7, 2, 5], device="cuda") + starts = torch.tensor([0, 3, 8], device="cuda") + sources = (x, x.half()) if dtype == torch.bfloat16 else (x, (x * 2.**-25).bfloat16()) + for source in sources: + actual = torch.zeros(2, 1, device="cuda") + expected = torch.zeros_like(actual) + ac = torch.zeros(2, dtype=torch.float64, device="cuda") + ec = torch.zeros_like(ac) + closing_sums(source, index, starts, actual, ac, 2, cast=dtype) + closing_sums(source.to(dtype), index, starts, expected, ec, 2) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + torch.testing.assert_close(ac, ec, rtol=0, atol=0) + + +class TestTwinReassignment(unittest.TestCase): + def test_cpu_twin_closing_does_not_import_gpu_helper(self): + script = ''' +import faiss, importlib.abc, sys +sys.path.insert(0, sys.argv[1]) +from torch_test_e_means import TestTwinReassignment +class NoGpuClosing(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.endswith(".triton_assignment"): + raise ImportError("CPU closing must not import a GPU helper") +for name in list(sys.modules): + if name.endswith(".triton_assignment"): + del sys.modules[name] +sys.meta_path.insert(0, NoGpuClosing()) +TestTwinReassignment("test_tensor_class").test_tensor_class() +''' + subprocess.run([sys.executable, "-c", script, str(Path(__file__).resolve().parent)], + check=True, timeout=60) + + def test_cpu_closing_row_scratch_obeys_assignment_chunk(self): + # Retain the numerical handover oracle while observing actual row gathers. + gathered = {} + + class Rows: + def __init__(self, x, name): + self.x, self.name = x, name + + def __getitem__(self, index): + gathered[self.name].append(len(index)) + return self.x[index] + + def observe(original, name): + def closing(km, order, rows, labels, x, moved_at, events, stale_rows): + gathered[name] = [] + return original(km, order, rows, labels, Rows(x, name), + moved_at, events, stale_rows) + return closing + + with mock.patch.object(NumpyEmeans, "_close_split_centroids", + observe(NumpyEmeans._close_split_centroids, "numpy")), \ + mock.patch.object(Emeans, "_close_split_centroids", + observe(Emeans._close_split_centroids, "torch")): + _check_handover_parity(self, "cpu") + self.assertEqual(set(gathered), {"numpy", "torch"}) + for name, sizes in gathered.items(): + self.assertGreater(max(sizes), 0, name) + self.assertLessEqual(max(sizes), 500, name) + + def test_numpy_class(self): + _check_twin_rule(self, True) + + def test_tensor_class(self): + _check_twin_rule(self, False) + + def test_split_ends_close_from_their_rows_after_the_split_in_the_caller_loop(self): + x, init = _handover_mixture() + km, seen, last = Emeans(8, 64, nepochs=1, batch_size=500, assignment_backend="native"), [], {} + apply = km._apply_splits + + def record(source, target): # Both ends of a split, by the batches seen before it. + last.update({int(j): len(seen) for j in np.concatenate((np.asarray(source), np.asarray(target)))}) + return apply(source, target) + + km._apply_splits = record + km.begin(len(x), init) + for batch in x.split(500): + stats = km.accumulate(batch) + seen.append((batch, stats["labels"].clone())) + km.update(stats) + km.end_epoch() + centroids = km.finalize() + self.assertTrue(last) + for j, after in last.items(): + rows = torch.cat([batch[labels == j] for batch, labels in seen[after:]] + [x[:0]]) + if len(rows): + torch.testing.assert_close(centroids[j], rows.double().mean(0).float(), rtol=1e-5, atol=1e-5) + + +def _check_handover_parity(case, device): + """The NumPy class and the tensor class apply the rule identically: the same + closing-pass state (captured labels, second labels, when each centroid was + revived, visiting order) gives the same labels, counts and closing sums.""" + rs = np.random.RandomState(0) + k, d, n = 64, 8, 6000 + centroids = (rs.randn(k, d) * 10).astype("float32") + owner = rs.randint(0, k, n) + x = (centroids[owner] + 0.05 * rs.randn(n, d)).astype("float32") + second = (owner + 1 + rs.randint(0, k - 1, n)) % k + order = rs.permutation(n) + moved_at = np.full(k, -1, dtype="int64") + revived = rs.choice(k, 20, replace=False) + moved_at[revived] = rs.randint(0, n, len(revived)) # Each revived at a random point of the pass. + results = [] + for numpy_class in (True, False): + if numpy_class: + km = NumpyEmeans(d, k, nepochs=1, batch_size=500, assignment_chunk_size=500) + km.begin(n, centroids) + labels_np = owner.copy() # Rewritten in place by the handover. + km._handover_start(labels_np, second.astype("int16"), x) + km._handover["moved_at"] = moved_at.copy() + km._handover_finish(order, n) + results.append((km.closing_handover_stats, km._pass_sums.astype("float64"), + np.asarray(km._pass_counts, dtype="float64"), labels_np)) + else: + # Compare the same raw FP32 representation on CPU and CUDA. + km = QuantizedEmeans(d, k, nepochs=1, batch_size=500, + assignment_backend="native", quantizer=None, assignment_chunk_size=500) + tx = torch.from_numpy(x).to(device) + km.begin(n, torch.from_numpy(centroids).to(device)) + km._prepare_input(tx) + labels_t = torch.from_numpy(owner.copy()).to(device) # Rewritten in place too. + km._handover_start(labels_t, tx, second=True) + km._handover["second"].copy_(torch.from_numpy(second).to(device)) + km._handover["moved_at"].copy_(torch.from_numpy(moved_at).to(device)) + km._handover_finish(torch.from_numpy(order).to(device), n) + results.append((km.closing_handover_stats, km._pass_sums.double().cpu().numpy(), + km._pass_counts.double().cpu().numpy(), labels_t.cpu().numpy())) + (stats_np, sums_np, counts_np, labels_np), (stats_t, sums_t, counts_t, labels_t) = results + np.testing.assert_array_equal(labels_np, labels_t) + case.assertGreater(int((labels_np != owner).sum()), 0) + case.assertEqual(stats_np, stats_t) + case.assertGreater(stats_np["second"], 0) + case.assertGreater(stats_np["searched"], 0) + np.testing.assert_array_equal(counts_np, counts_t) + np.testing.assert_allclose(sums_np, sums_t, rtol=1e-5, atol=1e-3) + + +class TestHandoverParity(unittest.TestCase): + def test_numpy_and_tensor_classes_agree_on_cpu(self): + _check_handover_parity(self, "cpu") + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") + def test_numpy_and_tensor_classes_agree_on_cuda(self): + _check_handover_parity(self, "cuda") + + +class TestClosingHandoverCpu(unittest.TestCase): + def test_rows_of_centroid_revived_while_closing_are_assigned_again(self): + x, init = _handover_mixture() + _check_closing_handover(self, x, init, ("auto",)) + + +@unittest.skipUnless(TRITON_CUDA, "CUDA with Triton required") +class TestClosingHandover(unittest.TestCase): + def test_strided_twin_closing_matches_contiguous_with_actual_moves(self): + # Reuse the closing-mixture fixture and one real training trajectory. + # Replaying its identical closing state isolates layout from atomic sums. + x, initial = _handover_mixture() + x, initial = x.cuda(), initial.cuda() + for cls, options in ((QuantizedEmeans, {"quantizer": None}), (Emeans, {})): + with self.subTest(model=cls.__name__): + model = cls(8, 64, nepochs=1.6, batch_size=500, + assignment_backend="triton", **options) + close = model._close_split_centroids + witnessed = [] + + def compare(order, rows, labels, values, moved_at, events, stale_rows, + model=model, close=close, witnessed=witnessed): + before = labels.clone() + sums, counts = model._pass_sums.clone(), model._pass_counts.clone() + close(order, rows, labels, values, moved_at, events, stale_rows) + expected = labels.clone(), model._pass_sums.clone(), model._pass_counts.clone() + self.assertTrue(events) + self.assertGreater(int((expected[0] != before).sum()), 0) + from faiss.contrib.e_means.e_means_torch import _closing_centroid_values + means = _closing_centroid_values(expected[1], expected[2], model._centroids) + padded = values.new_empty((len(values), 2 * values.shape[1] + 1)) + sliced = padded[:, 1::2] + sliced.copy_(values) + transposed = values.t().contiguous().t() + for source in (sliced, transposed): + labels.copy_(before) + model._pass_sums.copy_(sums) + model._pass_counts.copy_(counts) + contiguous = torch.Tensor.contiguous + + def bounded(tensor, *args, **kwargs): + self.assertFalse(tensor is source, "whole closing input copied") + return contiguous(tensor, *args, **kwargs) + + with mock.patch.object(torch.Tensor, "contiguous", bounded): + close(order, rows, labels, source, moved_at, events, stale_rows) + for actual, wanted in zip((labels, model._pass_sums, model._pass_counts), expected): + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + actual_means = _closing_centroid_values(model._pass_sums, model._pass_counts, + model._centroids) + torch.testing.assert_close(actual_means, means, rtol=0, atol=0) + witnessed.append(len(events)) + + model._close_split_centroids = compare + model.train(x, initial) + self.assertTrue(witnessed) + + def test_triton_second_labels_match_reference(self): + from faiss.contrib.e_means.triton_assignment import _use_split_k, assign_rows + torch.manual_seed(0) + # Second labels resolved after the scan (d <= 128) and searched in it (d > 128), on + # both kernels: direct (the paper's 32768-row batches) and split-K, padded included. + for b, k, d, split in ((32768, 4096, 96, False), (32768, 4096, 128, False), + (32768, 4096, 256, False), (4096, 2048, 96, True), + (128, 8192, 128, True), (300, 5000, 100, True), + (128, 8192, 256, True), (2048, 8192, 1024, True)): + self.assertEqual(_use_split_k(b, k, d, True), split, (b, k, d)) + x = torch.randn(b, d, device="cuda").bfloat16() + c = torch.randn(k, d, device="cuda").bfloat16() + norm = c.float().square().sum(1) + second = torch.empty(b, device="cuda") + second_labels = torch.empty(b, dtype=torch.int32, device="cuda") + _, labels = assign_rows(x, c, norm, second_out=second, second_labels_out=second_labels) + score = norm.double()[None] - 2 * x.double() @ c.double().t() + want = score.topk(2, dim=1, largest=False).values[:, 1] + got = score.gather(1, second_labels.long()[:, None])[:, 0] + scale = want.abs() + x.double().square().sum(1) + self.assertTrue(bool(((got - want).abs() <= 2e-3 * scale).all()), (b, k, d)) + self.assertTrue(bool((second_labels.long() != labels).all()), (b, k, d)) + # The label's distance is the reported second distance. + torch.testing.assert_close( + (score.gather(1, second_labels.long()[:, None])[:, 0] + x.double().square().sum(1)).float(), + second, rtol=2e-3, atol=2e-3) + + def test_rows_of_centroid_revived_while_closing_are_assigned_again(self): + x, init = _handover_mixture() + for nepochs in (1, 1.2, 1.6): + _check_closing_handover(self, x.cuda().bfloat16(), init.cuda(), ("triton", "native"), + nepochs=nepochs) + + def test_spherical(self): + x, init = _handover_mixture() + x, init = (torch.nn.functional.normalize(t, dim=1) for t in (x, init)) + _check_closing_handover(self, x.cuda().bfloat16(), init.cuda(), ("triton", "native"), spherical=True) + + +@unittest.skipUnless(importlib.util.find_spec("triton"), "Triton required") +class TestTritonFullDSharedMemory(unittest.TestCase): + def test_capacity_selection_and_device_property_cache(self): + from faiss.contrib.e_means import triton_assignment as backend + + default = backend._FULL_D_CONFIG + device = torch.device("cuda", 3) + with mock.patch.object(torch.version, "hip", None): + for capability, limit, expected_k in ( + ((7, 5), 65536, 64), ((7, 5), 98303, 64), + ((7, 0), 98304, 128), ((7, 5), 101376, 128), + ((8, 0), 49152, 128), ((8, 6), 101376, 128), + ((9, 0), 232448, 128), ((10, 0), 232448, 128), + ): + with self.subTest(capability=capability, limit=limit), mock.patch.object( + backend, "_cuda_assignment_device_properties", + return_value=(capability, limit), + ) as properties: + self.assertEqual(backend._full_d_config(device), + (default[0], expected_k, default[2], default[3])) + if expected_k == 128: + self.assertIs(backend._full_d_config(device), default) + self.assertTrue(all(call == mock.call(3) + for call in properties.call_args_list)) + with mock.patch.object(backend, "_cuda_assignment_device_properties", + return_value=((7, 5), 49152)): + with self.assertRaisesRegex(RuntimeError, "cuda:3; device limit is 49152"): + backend._full_d_config(device) + with mock.patch.object(torch.cuda, "current_device", return_value=2), \ + mock.patch.object(backend, "_cuda_assignment_device_properties", + return_value=((7, 5), 65536)) as properties: + self.assertEqual(backend._full_d_config(torch.device("cuda"))[1], 64) + properties.assert_called_once_with(2) + with mock.patch.object(torch.version, "hip", "test"), mock.patch.object( + backend, "_cuda_assignment_device_properties", + side_effect=AssertionError("HIP queried CUDA properties"), + ): + self.assertEqual(backend._full_d_config(device), default) + + backend._cuda_assignment_device_properties.cache_clear() + try: + utils = mock.Mock() + utils.get_device_properties.return_value = {"max_shared_mem": 65536} + with mock.patch.object(torch.cuda, "get_device_capability", return_value=(7, 5)) as cc, \ + mock.patch.object(backend.triton.runtime, "driver", mock.Mock(active=mock.Mock(utils=utils))): + for index in (3, 3, 1, 1): + self.assertEqual(backend._cuda_assignment_device_properties(index), + ((7, 5), 65536)) + self.assertEqual(cc.call_args_list, [mock.call(3), mock.call(1)]) + self.assertEqual(utils.get_device_properties.call_args_list, + [mock.call(3), mock.call(1)]) + finally: + backend._cuda_assignment_device_properties.cache_clear() + + @unittest.skipUnless(torch.cuda.is_available() and not torch.version.hip, + "NVIDIA CUDA required") + def test_full_d_tiles_exact_outputs_ties_and_second_labels(self): + from faiss.contrib.e_means import triton_assignment as backend + + device = torch.device("cuda", torch.cuda.current_device()) + capability, limit = backend._cuda_assignment_device_properties(device.index) + dtypes = [torch.float16] + if capability >= (8, 0): + dtypes.append(torch.bfloat16) + # The real low-memory route runs K64. Compare both shapes only where + # K128 is legal; never try to launch the known oversized T4 config. + tiles = [64] if capability < (8, 0) and limit < 98304 else [128, 64] + generator = torch.Generator(device=device).manual_seed(5918) + for dtype in dtypes: + for d in (65, 96, 100, 128): + for k in (16, 65, 129, 512): + rows = (torch.randint(-4, 5, (97, d), device=device, + generator=generator).float() / 4).to(dtype) + centers = (torch.randint(-4, 5, (k, d), device=device, + generator=generator).float() / 4).to(dtype) + # Exact ties on either side of the new tile boundary. + if k > 64: + centers[64].copy_(centers[63]) + rows[0].copy_(centers[63]) + if k > 100: + centers[100].copy_(centers[10]) + rows[1].copy_(centers[10]) + saved = rows.clone(), centers.clone() + norms = centers.float().square().sum(1) + scores = norms.double()[None] - 2 * rows.double() @ centers.double().t() + order = torch.argsort(scores, dim=1, stable=True) + self.assertFalse(backend._use_split_k(len(rows), k, + (d + 15) // 16 * 16, True)) + for mode in ("l2", "score", "spherical"): + truth = scores if mode != "l2" else (scores + rows.double().square().sum(1)[:, None]) + reference = None + for outputs in (0, 1, 2): + for tile in tiles: + with self.subTest(dtype=dtype, d=d, k=k, mode=mode, + outputs=outputs, tile=tile): + second = torch.full((97,), -123., device=device) if outputs else None + second_ids = (torch.full((97,), -123, device=device, dtype=torch.int32) + if outputs == 2 else None) + config = (64, tile, 4, backend._NUM_STAGES) + with mock.patch.object(backend, "_full_d_config", return_value=config): + distance, labels = backend.assign_rows( + rows, centers, norms, spherical=mode == "spherical", + return_score=mode == "score", second_out=second, + second_labels_out=second_ids, + ) + self.assertEqual(distance.dtype, torch.float32) + self.assertEqual(labels.dtype, torch.int64) + self.assertTrue(torch.equal(labels, order[:, 0])) + self.assertTrue(torch.equal(distance.double(), + truth.gather(1, order[:, :1]).flatten())) + if k > 64: + self.assertEqual(labels[0].item(), 63) + if k > 100: + self.assertEqual(labels[1].item(), 10) + if second is not None: + self.assertTrue(torch.equal(second.double(), + truth.gather(1, order[:, 1:2]).flatten())) + if second_ids is not None: + self.assertTrue(torch.equal(second_ids.long(), order[:, 1])) + actual = tuple(t.clone() for t in (distance, labels)) + if reference is None: + reference = actual + else: + for value, expected in zip(actual, reference): + self.assertTrue(torch.equal(value, expected)) + for value, expected in zip((rows, centers), saved): + self.assertTrue(torch.equal(value, expected)) + # Finally exercise the unmodified hardware selection itself. + actual, labels = backend.assign_rows(rows, centers, norms) + self.assertTrue(torch.equal(labels, order[:, 0])) + self.assertTrue(torch.equal(actual.double(), + (scores + rows.double().square().sum(1)[:, None]) + .gather(1, order[:, :1]).flatten())) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_autocast.py b/thirdparty/faiss/tests/torch_test_e_means_autocast.py new file mode 100644 index 000000000..833f3ba01 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_autocast.py @@ -0,0 +1,117 @@ +# 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 unittest + +import torch + +from faiss.contrib.e_means import Emeans, QuantizedEmeans +from e_means_test_utils import highest_fp32, known_torch_centroids + + +class TestEmeansAutocast(unittest.TestCase): + def check_assignment(self, device, dtype=torch.float32, + autocast_dtype=torch.bfloat16): + for spherical in (False, True): + if spherical: + centroids = torch.eye(2, device=device) + rows = torch.tensor( + [[1.003, 1.004], [1.004, 1.003]], device=device + ) + rows = torch.nn.functional.normalize(rows, dim=1) + expected_labels = [1, 0] + else: + rows = torch.tensor([[1.003, 0.], [1.004, 0.]], device=device) + centroids = rows.clone() + expected_labels = [0, 1] + rows = rows.to(dtype) + classes = (Emeans, QuantizedEmeans) if device == "cpu" else ( + QuantizedEmeans, + ) + for cls in classes: + for chunk_size in (1, 2): + with self.subTest( + device=device, dtype=dtype, cls=cls.__name__, + spherical=spherical, chunk_size=chunk_size, + ): + model = known_torch_centroids( + centroids, model_class=cls, + assignment_backend="native", + spherical=spherical, + centroid_chunk_size=chunk_size, + ) + expected = model.assign(rows) + if dtype == torch.float32: + self.assertEqual( + expected[1].tolist(), expected_labels + ) + before = torch.is_autocast_enabled(device) + with torch.autocast(device, dtype=autocast_dtype): + actual = model.assign(rows) + self.assertTrue(torch.is_autocast_enabled(device)) + self.assertEqual( + (rows @ rows.t()).dtype, autocast_dtype + ) + self.assertEqual( + torch.is_autocast_enabled(device), before + ) + for result, reference in zip(actual, expected): + torch.testing.assert_close( + result, reference, rtol=0, atol=0 + ) + self.assertEqual( + model.assignment_recipe["representation"], + str(dtype).removeprefix("torch."), + ) + + def test_cpu_assignment(self): + self.check_assignment("cpu") + + def test_cpu_training(self): + generator = torch.Generator().manual_seed(123) + rows = torch.randn(97, 8, generator=generator) + for cls in (Emeans, QuantizedEmeans): + for spherical in (False, True): + with self.subTest(cls=cls.__name__, spherical=spherical): + data = (torch.nn.functional.normalize(rows, dim=1) + if spherical else rows) + options = dict( + nepochs=2, batch_size=16, alpha0=0.2, + unused_threshold=0, assignment_backend="native", + assignment_chunk_size=7, centroid_chunk_size=3, + spherical=spherical, + ) + if cls is QuantizedEmeans: + options["quantizer"] = None + reference = cls(8, 5, **options) + model = cls(8, 5, **options) + reference.train(data, data[:5]) + with torch.autocast("cpu", dtype=torch.bfloat16): + model.train(data, data[:5]) + self.assertTrue(torch.is_autocast_enabled("cpu")) + for name in ("centroids", "assignments", "_usage", "obj"): + torch.testing.assert_close( + getattr(model, name), getattr(reference, name), + rtol=0, atol=0, + ) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_fp32_assignment(self): + with highest_fp32("cuda"): + self.check_assignment("cuda", autocast_dtype=torch.float16) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_assignment(self): + if torch.version.hip or torch.cuda.get_device_capability() < (8, 0): + self.skipTest("native reduced precision requires NVIDIA SM80+") + if not torch.cuda.is_bf16_supported(): + self.skipTest("requires BF16 autocast") + with highest_fp32("cuda"): + for dtype in (torch.float32, torch.float16, torch.bfloat16): + self.check_assignment("cuda", dtype) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_bf16_pitch.py b/thirdparty/faiss/tests/torch_test_e_means_bf16_pitch.py new file mode 100644 index 000000000..1003a6ed9 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_bf16_pitch.py @@ -0,0 +1,118 @@ +# 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 unittest + +import torch + +from faiss.contrib.e_means import cute as backend +from torch_test_e_means_cute import _ready + + +class TestBf16Pitch(unittest.TestCase): + def test_large_meta_allocations_keep_legal_layouts(self): + limit = 2**31 + for rows, dim in ( + (2, 100), + (20_000_000, 100), + (limit // 16 - 1, 1), + (limit // 16, 1), + (limit // 16 + 1, 1), + ): + with self.subTest(rows=rows, dim=dim): + backend._check_padded_span('rows', rows, dim) + value = backend._aligned_operand(rows, dim, 'meta', torch.bfloat16) + pitch = value.stride(0) + self.assertEqual(value.device.type, 'meta') + self.assertEqual(tuple(value.shape), (rows, dim)) + self.assertEqual(value.dtype, torch.bfloat16) + self.assertEqual(value.stride(1), 1) + self.assertGreaterEqual(pitch, dim) + self.assertEqual(pitch * value.element_size() % 16, 0) + span = rows * pitch + self.assertLess(span, limit) + capacity = value.untyped_storage().nbytes() // value.element_size() + self.assertGreaterEqual(capacity - value.storage_offset(), span) + with self.assertRaisesRegex(ValueError, 'signed int32'): + backend._check_padded_span('rows', limit // 8, 1) + + def test_small_storage_suffix_and_other_dtypes(self): + cases = [(torch.bfloat16, dim) for dim in (1, 8, 9, 16, 17, 24, 25, 96, 100, 256)] + cases += [(dtype, 17) for dtype in (torch.float32, torch.float16, + torch.float8_e4m3fn, torch.int8, torch.uint8)] + for dtype, dim in cases: + with self.subTest(dtype=dtype, dim=dim): + rows = backend._aligned_operand(3, dim, 'cpu', dtype) + pitch = rows.stride(0) + self.assertEqual(tuple(rows.shape), (3, dim)) + self.assertEqual(rows.dtype, dtype) + self.assertEqual(rows.stride(1), 1) + self.assertGreaterEqual(pitch, dim) + self.assertEqual(pitch * rows.element_size() % 16, 0) + self.assertEqual(rows.data_ptr() % 16, 0) + capacity = rows.untyped_storage().nbytes() // rows.element_size() + self.assertGreaterEqual(capacity - rows.storage_offset(), 3 * pitch) + physical = rows.as_strided((3, pitch), (pitch, 1)) + self.assertEqual(torch.count_nonzero(physical[:, dim:].view(torch.uint8)).item(), 0) + + @unittest.skipUnless(_ready(), 'pinned CuTe stack on SM90 required') + def test_mixed_pitches_native_and_grouped(self): + from faiss.contrib.e_means.cute_kernel import ( + prepare_tiled_gemm, launch_tiled_gemm) + from faiss.contrib.e_means.cute_row_owned import ( + prepare_row_owned, launch_row_owned) + from faiss.contrib.e_means.cute_grouped import ( + prepare_grouped, launch_grouped) + + # Reuse the n33/k512/d96 integer/tie fixture, with four zero coordinates. + n, k, original_dim, dim = 33, 512, 96, 100 + generator = torch.Generator(device='cuda').manual_seed(n + k + original_dim) + original_rows = torch.randint(-2, 3, (n, original_dim), + generator=generator, device='cuda').bfloat16() + original_centroids = torch.randint(-2, 3, (k, original_dim), + generator=generator, device='cuda').float() + original_centroids[1].copy_(original_centroids[0]) + rows_source = torch.nn.functional.pad(original_rows, (0, dim - original_dim)) + centroids_source = torch.nn.functional.pad(original_centroids, (0, dim - original_dim)) + for row_pitch, centroid_pitch in ((104, 112), (112, 104)): + with self.subTest(row_pitch=row_pitch, centroid_pitch=centroid_pitch): + row_storage = torch.zeros((n, row_pitch), dtype=torch.bfloat16, device='cuda') + centroid_storage = torch.zeros((k, centroid_pitch), dtype=torch.bfloat16, device='cuda') + rows, centroids = row_storage[:, :dim], centroid_storage[:, :dim] + rows.copy_(rows_source) + centroids.copy_(centroids_source) + prepared = backend._prepare_centroids(centroids_source, dtype=torch.bfloat16) + prepared.centroids = centroids + keys = prepared.norms.double()[None] - 2 * rows.double() @ centroids.double().T + expected_labels = keys.argmin(1) + expected_keys = keys.gather(1, expected_labels[:, None]).flatten().float() + for name, prepare, launch, plan in ( + ('tiled', prepare_tiled_gemm, launch_tiled_gemm, None), + ('row_owned', prepare_row_owned, launch_row_owned, (128, 128, 3)), + ('grouped', prepare_grouped, launch_grouped, (112, 256, 3)), + ): + with self.subTest(consumer=name): + values = torch.full((n + 2,), -123., device='cuda') + labels = torch.full((n + 2,), -123, dtype=torch.int64, device='cuda') + if plan is None: + operation = prepare(rows, prepared, labels[1:-1], values[1:-1]) + else: + operation = prepare(rows, prepared, values[1:-1], labels[1:-1], plan) + launch(operation) + torch.testing.assert_close(labels[1:-1], expected_labels, rtol=0, atol=0) + torch.testing.assert_close(values[1:-1].view(torch.int32), + expected_keys.view(torch.int32), rtol=0, atol=0) + self.assertEqual(labels[[0, -1]].tolist(), [-123, -123]) + self.assertEqual(values[[0, -1]].tolist(), [-123., -123.]) + torch.testing.assert_close(rows.view(torch.int16), + rows_source.view(torch.int16), rtol=0, atol=0) + torch.testing.assert_close(centroids.view(torch.int16), + centroids_source.bfloat16().view(torch.int16), rtol=0, atol=0) + self.assertEqual(torch.count_nonzero(row_storage[:, dim:].view(torch.int16)).item(), 0) + self.assertEqual(torch.count_nonzero(centroid_storage[:, dim:].view(torch.int16)).item(), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_bf16_revival.py b/thirdparty/faiss/tests/torch_test_e_means_bf16_revival.py new file mode 100644 index 000000000..3f2a30968 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_bf16_revival.py @@ -0,0 +1,546 @@ +# 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. + +"""BF16 removal revival: CPU selection/collectives and optional CUDA kernels.""" + +import datetime +import tempfile +import unittest +from unittest import mock + +import numpy as np +import torch +import torch.distributed as dist + +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.ivf_flat import IndexIVFFlat +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.sharded_centroids import ( + EmeansShardedCentroids, _partial_removal_donors, + _removal_candidates, _removal_scalar_stats, +) +from faiss.contrib.e_means.sharded_centroids_ivf import EmeansShardedCentroidsIVF +from faiss.contrib.e_means.torch_backend import TorchBackend + + +class _CPUAssignment(TorchBackend): + """Evaluate rounded BF16 operands with CPU FP32 dots.""" + + def assign(self, rows, centroids, *args, **kwargs): + return super().assign(rows.float(), centroids.float(), *args, **kwargs) + + +def _index(coarse, candidates, nprobe, **kwargs): + index = IndexIVFFlat(coarse, nprobe=nprobe, **kwargs) + index.dtype = "bf16" + index.add(candidates) + return index + + +def _ivf_revival_worker(rank, rendezvous, device_type): + torch.set_num_threads(1) + device = torch.device(device_type, rank) if device_type == "cuda" else torch.device("cpu") + if device_type == "cuda": + torch.cuda.set_device(device) + dist.init_process_group("nccl" if device_type == "cuda" else "gloo", + init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=120)) + try: + check = unittest.TestCase() + initial = torch.tensor([[0., 0.], [.25, 0.], [10., 0.], + [10.25, 0.], [30., 0.], [50., 0.]], device=device) + coarse = initial[[0, 2, 5]] + shard = slice(rank * 3, (rank + 1) * 3) + model = EmeansShardedCentroidsIVF(2, 6, group=dist.group.WORLD, + nlist=3, nprobe=1, batch_size=2) + QuantizedEmeans.begin(model, 20, initial[shard]) + model._ivf = _index(coarse, initial[shard], 1) + model._prepare_assignment() # Training prepares global routing occupancy. + all_centroids = initial.clone() + # Only rank 0 ranks the donors. The two equal-gain winners must be + # IDs 1 and 3, and both owners receive the same split decisions. + state = torch.tensor([[1., 0., 0.], [20., 0., 10.], [2., 0., 0.], + [20., 0., 10.], [20., 0., 10.], [20., 0., 10.]], device=device) + model._usage.fill_(1) + model._removal_stats.copy_(state[shard]) + model._axes[:] = torch.tensor([1., 0.], device=device) + oracle = QuantizedEmeans(2, 6, quantizer=CastQuantizer(2, torch.bfloat16)) + oracle.begin(20, all_centroids) + oracle._usage.fill_(1) + oracle._removal_stats.copy_(state) + oracle._axes[:] = torch.tensor([1., 0.], device=device) + oracle._apply_splits(torch.tensor([1, 3], device=device), + torch.tensor([0, 2], device=device)) + check.assertEqual(model._revive_unused(torch.Generator()), 2) + for name in ("_centroids", "_usage", "_removal_stats", "_axes"): + torch.testing.assert_close(getattr(model, name), getattr(oracle, name)[shard], rtol=0, atol=0) + # A split invalidates cached lengths. A check before another update + # recomputes them; only rank 0 receives the global FP32 table. + scalars = model._gather_removal_scalars() + if rank == 0: + torch.testing.assert_close(scalars, + _removal_scalar_stats(oracle._removal_stats, oracle._usage).float()) + else: + check.assertEqual(scalars.shape, (0, 3)) + model._removal_stats[:, -1].fill_(10.) + check.assertEqual(model._revive_unused(torch.Generator()), 0) + model._removal_stats[:, -1].zero_() + model._usage.zero_() + check.assertEqual(model._revive_unused(torch.Generator()), 0) # Candidates, but no donors. + finally: + dist.destroy_process_group() + + +def _ivf_statistics_worker(rank, rendezvous): + """Exercise the default IVF backend against its unfused statistics path.""" + from faiss.contrib.e_means import ivf_kernels, triton_assignment + + torch.set_num_threads(1) + torch.cuda.set_device(rank) + device = torch.device("cuda", rank) + dist.init_process_group("nccl", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=60)) + try: + check = unittest.TestCase() + for d in (17, 1024): + generator = torch.Generator(device=device).manual_seed(53) + initial = torch.randn(32, d, device=device, generator=generator) + rows = torch.randn(64, d, device=device, generator=generator) + shard = slice(rank * 16, (rank + 1) * 16) + local = rows[rank * 32:(rank + 1) * 32] + models = [] + for _ in range(2): + model = EmeansShardedCentroidsIVF(d, 32, group=dist.group.WORLD, + nlist=2, nprobe=2, batch_size=64, nepochs=3, alpha0=.5, seed=7) + model.begin(256, initial[shard]) + model._ivf = _index(initial[:2], initial[shard], 2) + # Include an axis whose squared norm overflows FP32. + model._removal_stats[1, :-1] = 1e20 + models.append(model) + actual, expected = models + with mock.patch.object(expected, "_use_fused_owned_statistics", return_value=False), \ + mock.patch.object(expected, "_update_removal_statistics", return_value=False), \ + mock.patch.object(ivf_kernels, "accumulate_owned", wraps=ivf_kernels.accumulate_owned) as accumulate, \ + mock.patch.object(triton_assignment, "removal_update", wraps=triton_assignment.removal_update) as update: + for _ in range(2): + stats = [] + for model in models: + check.assertIsNone(model.accumulate(local[:16])["sums"]) + stats.append(model.accumulate(local[16:])) + check.assertEqual(actual._assignment_backend, "native") + for key in ("sums", "counts", "removal", "objective"): + torch.testing.assert_close(stats[0][key], stats[1][key], rtol=1e-4, atol=1e-4) + for model, batch in zip(models, stats): + model.update(batch) + for name in ("_centroids", "_usage", "_removal_stats", "_axes", "_batch_removal"): + torch.testing.assert_close(getattr(actual, name), getattr(expected, name), + rtol=1e-4, atol=1e-4) + check.assertFalse(bool(actual._batch_removal.any())) + expected_scalars = _removal_scalar_stats(expected._removal_stats, expected._usage).float() + actual_norms = torch.linalg.vector_norm(actual._removal_stats[:, :-1], + dim=1, dtype=torch.float64).float() + torch.testing.assert_close(actual._axis_norms, actual_norms, rtol=1e-6, atol=1e-6) + full_expected = expected._gather_local(expected_scalars) + # No vector-table scan or CPU cost transfer is needed + # after a normal update writes the cached axis lengths. + with mock.patch.object(torch.linalg, "vector_norm", + side_effect=AssertionError("recomputed cached norms")): + scalars = actual._gather_removal_scalars() + check.assertEqual(scalars.dtype, torch.float32) + if rank == 0: + torch.testing.assert_close(scalars, full_expected, rtol=1e-4, atol=1e-4) + else: + check.assertEqual(scalars.shape, (0, 3)) + check.assertEqual(accumulate.call_count, 4) + check.assertEqual(update.call_count, 2) + _owner_keys(rank, device) + model = EmeansShardedCentroidsIVF(2, 2, group=dist.group.WORLD, quantizer=None, + nlist=1, nprobe=1, coarse_niter=1, nepochs=1, + batch_size=2, alpha0=1, assignment_chunk_size=1) + model.begin(2, torch.tensor([[.5 + .25 * rank, 0.]], device=device)) + model._axes[:] = torch.tensor([1., 0.], device=device) + stats = model.accumulate(torch.zeros(1, 2, dtype=torch.int8, device=device)) + expected = torch.tensor([[.5, 0., .625] if rank == 0 else [0., 0., 0.]], device=device) + torch.testing.assert_close(stats["removal"], expected, rtol=0, atol=0) + assert stats["counts"].item() == (2 if rank == 0 else 0) + model.update(stats) + model.end_epoch() + model.finalize() + except BaseException: + # Report an assertion before NCCL teardown waits for another rank. + import traceback + traceback.print_exc() + raise + finally: + dist.destroy_process_group() + + +def _owner_keys(rank, device): + cases = [(torch.tensor([[8192., 0.]], device=device), + torch.tensor([[0., 1.], [0., 0.]], device=device), 1, 1.)] + cap = torch.cuda.get_device_capability(device) if device.type == "cuda" else None + if cap in ((8, 0), (9, 0), (10, 0)): + rows = torch.full((1, 512), -128, device=device, dtype=torch.int8) + rows[0, -1] = 0 + for last, margin in (([0., 1.], 1.), ([1., 1.], 0.)): + centers = torch.full((2, 512), 127., device=device) + centers[:, -1] = torch.tensor(last, device=device) + cases.append((rows, centers, 0, margin)) + if cap in ((9, 0), (10, 0), (10, 3)): + centers = torch.full((4, 128), 448., device=device) + centers[:, -1] = torch.tensor([.25, .125, .5, .75], device=device) + rows = torch.full((2, 128), 448., device=device) + rows[:, -1] = 0 + cases.append((rows.to(torch.float8_e4m3fn), centers, 0, -.046875)) + for rows, centers, winner, margin in cases: + k = len(centers) // 2 + model = EmeansShardedCentroids(rows.shape[1], len(centers), group=dist.group.WORLD, + quantizer=None, assignment_backend="native" if cap is None else "triton", + nepochs=1, batch_size=2 * len(rows), assignment_chunk_size=1) + QuantizedEmeans.begin(model, 2 * len(rows), centers[rank * k:(rank + 1) * k]) + model.accumulate(rows[:0]) # Bind raw dtype and its cost state. + model._axes.zero_() + model._axes[:, 0] = 1 + stats = model.accumulate(rows) + assert stats["labels"].tolist() == [winner] * len(rows) + expected = torch.zeros_like(stats["removal"]) + if winner // k == rank: + residual = rows[0].float() - centers[winner] + expected[winner % k, :-1] = 2 * len(rows) * residual[0] * residual + expected[winner % k, -1] = 2 * len(rows) * margin + torch.testing.assert_close(stats["removal"], expected, rtol=1e-5, atol=0) + model.update(stats) + model.end_epoch() + model.finalize() + + +def _collective_worker(rank, rendezvous): + torch.set_num_threads(1) + dist.init_process_group("gloo", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=60)) + try: + check = unittest.TestCase() + initial = torch.tensor([[0., 0.], [2., 0.], [2., 0.], [10., 0.]]) + rows = torch.tensor([[.25, 0.], [2., .5], [9., .25], [1., 0.]]) + shard = slice(rank * 2, (rank + 1) * 2) + for ivf in (False, True): + cls = EmeansShardedCentroidsIVF if ivf else EmeansShardedCentroids + kwargs = dict(nlist=2, nprobe=2) if ivf else dict(quantizer=CastQuantizer(2, torch.bfloat16)) + model = cls(2, 4, group=dist.group.WORLD, nepochs=2.6, + batch_size=4, alpha0=.5, assignment_chunk_size=1, **kwargs) + # Exercise production owner logic on CPU; public begin requires CUDA. + QuantizedEmeans.begin(model, 40, initial[shard]) + model._execution_backend = _CPUAssignment(model.centroid_chunk_size) + if ivf: + model._ivf = _index(initial[[0, 3]], initial[shard], 2) + model._axes[:] = torch.tensor([1., 0.]) + local = rows[shard] if ivf else rows[shard].bfloat16() + partial = model.accumulate(local[:1]) + check.assertIsNone(partial["sums"]) + stats = model.accumulate(local[1:]) + distances = (rows[:, None] - initial[None]).square().sum(-1) + order = torch.argsort(distances, dim=1, stable=True) + winner = order[:, 0] + costs = distances.gather(1, order[:, 1:2]).flatten() - distances.gather(1, order[:, :1]).flatten() + owned = (winner >= rank * 2) & (winner < (rank + 1) * 2) + sums, counts = torch.zeros(2, 2), torch.zeros(2) + removal = torch.zeros(2, 3) + for i in torch.nonzero(owned).flatten(): + j = winner[i] - rank * 2 + sums[j] += rows[i] + counts[j] += 1 + y = rows[i] - initial[winner[i]] + removal[j, :2] += y[0] * y + removal[j, 2] += costs[i] + torch.testing.assert_close(stats["sums"], sums) + torch.testing.assert_close(stats["counts"], counts) + torch.testing.assert_close(stats["removal"], removal) + check.assertEqual(stats["n"], 4) + model.update(stats) + torch.testing.assert_close(model._removal_stats, removal * .5) + torch.testing.assert_close(model._batch_removal, torch.zeros_like(removal)) + + # Adjacent candidates both move; Oja gain picks donors 3 then 2. + model._centroids[:] = initial[shard] + model._usage[:] = 1 + state = torch.tensor([[1., 0., 0.], [10., 0., 0.], + [2., 0., 10.], [20., 0., 10.]]) + model._removal_stats[:] = state[shard] + model._axes[:] = torch.tensor([1., 0.]) + oracle = QuantizedEmeans(2, 4, quantizer=CastQuantizer(2, torch.bfloat16)) + oracle.begin(40, initial) + oracle._execution_backend = _CPUAssignment(oracle.centroid_chunk_size) + oracle._usage[:] = 1 + oracle._removal_stats[:] = state + oracle._axes[:] = torch.tensor([1., 0.]) + oracle._apply_splits(torch.tensor([3, 2]), torch.tensor([0, 1])) + model._pass_sums = torch.full_like(model._centroids, 7) + model._pass_counts = torch.tensor([3., 5.]) + check.assertEqual(model._revive_unused(torch.Generator(), chunk_rows=1), 2) + for name in ("_centroids", "_usage", "_removal_stats", "_axes"): + torch.testing.assert_close(getattr(model, name), getattr(oracle, name)[shard], rtol=0, atol=0) + check.assertEqual(model.n_splits, 2) + torch.testing.assert_close(model._pass_sums, torch.zeros_like(model._centroids), rtol=0, atol=0) + torch.testing.assert_close(model._pass_counts, torch.zeros(2), rtol=0, atol=0) + torch.testing.assert_close(model._discarded_closing_counts, torch.tensor([3., 5.]), rtol=0, atol=0) + # One centroid per owner still has a global second candidate. + model = EmeansShardedCentroids(1, 2, group=dist.group.WORLD, + quantizer=CastQuantizer(1, torch.bfloat16), batch_size=2) + QuantizedEmeans.begin(model, 2, torch.tensor([[float(rank)]])) + check.assertIsNotNone(model._removal_stats) + first = torch.tensor([0., 1., 0.]) if rank == 0 else torch.tensor([0., 0., 2.]) + labels = torch.zeros(3, dtype=torch.int64) + winner, best, second = model._reduce_top2(first, labels, torch.full((3,), torch.inf)) + torch.testing.assert_close(winner, torch.tensor([0, 1, 0])) + torch.testing.assert_close(best, torch.tensor([0., 0., 0.])) + torch.testing.assert_close(second, torch.tensor([0., 1., 2.])) + _owner_keys(rank, torch.device("cpu")) + finally: + dist.destroy_process_group() + + +class TestBF16Removal(unittest.TestCase): + def test_candidate_selection(self): + self._check_candidate_selection("cpu") + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_candidate_selection(self): + self._check_candidate_selection("cuda") + + def _check_candidate_selection(self, device): + rng = np.random.RandomState(37) + for n in (0, 1, 2, 17, 128, 1025): + values = rng.randint(-3, 20, size=n).astype("float32") + for special in (None, float("nan"), float("inf"), -float("inf")): + removal = values.copy() + if n and special is not None: + removal[-1] = special + with np.errstate(invalid="ignore"): + median = np.median(removal.astype("float64")) if n else np.nan + candidates = np.flatnonzero((removal <= 0) | (removal.astype("float64") < .3 * median)) + candidates = candidates[np.argsort(removal[candidates], kind="stable")] + actual = _removal_candidates(torch.as_tensor(removal, device=device)) + np.testing.assert_array_equal(actual.cpu().numpy(), candidates) + # FP32 thresholds must still be compared in the original FP64 units. + removal = np.array([.3, np.nextafter(np.float32(.3), np.float32(0)), 1., 1., 1.]) + np.testing.assert_array_equal(_removal_candidates(torch.as_tensor(removal, device=device)).cpu(), [1]) + def test_partial_donor_selection(self): + self._check_partial_donor_selection("cpu") + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_partial_donor_selection(self): + self._check_partial_donor_selection("cuda") + + def _check_partial_donor_selection(self, device): + rng = np.random.RandomState(83) + gains = rng.randint(0, 7, size=1003).astype("float64") + # Stable ties include FP64 gains that collapse to the same FP32 value. + gains[3:7] = [np.inf, np.nan, 1. + 1e-10, 1.] + usage = (rng.rand(len(gains)) > .25).astype("float64") + for count in (0, 1, 5, 111, 750, 1003): + kept = rng.permutation(len(gains))[:count] + eligible = usage > 0 + eligible[kept] = False + donors = np.flatnonzero(eligible) + expected = donors[np.argsort(-gains[donors].astype("float32"), kind="stable")][:count] + with mock.patch.object(torch, "argsort", wraps=torch.argsort) as sort: + actual = _partial_removal_donors(kept, + torch.as_tensor(usage, device=device), + torch.as_tensor(gains, device=device)) + np.testing.assert_array_equal(actual.cpu().numpy(), expected) + if len(expected): + sort.assert_called_once() + self.assertEqual(len(sort.call_args.args[0]), len(expected)) + else: + sort.assert_not_called() + # Every gain is tied: select the lowest eligible IDs, not arbitrary + # IDs from the kth-value kernel. Cover eligible NaNs as well. + for gain in (0., float("inf"), float("nan")): + result = _partial_removal_donors(np.array([1, 4]), + torch.ones(7, device=device), torch.full((7,), gain, device=device)) + np.testing.assert_array_equal(result.cpu().numpy(), [0, 2]) + + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "requires Gloo") + def test_ivf_cost_revival(self): + self._check_ivf_cost_revival("cpu") + + @unittest.skipUnless(torch.cuda.device_count() >= 2 and dist.is_nccl_available(), + "requires two CUDA GPUs and NCCL") + def test_cuda_ivf_cost_revival(self): + self._check_ivf_cost_revival("cuda") + + def _check_ivf_cost_revival(self, device_type): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes(_ivf_revival_worker, + args=("file://" + directory + "/rendezvous", device_type), + nprocs=2, start_method="spawn") + + def test_ivf_top2(self): + self._check_ivf_top2("cpu") + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_ivf_top2(self): + if torch.version.hip is None and torch.cuda.get_device_capability() < (8, 0): + self.skipTest("BF16 IVF GEMM requires NVIDIA SM80 or later") + self._check_ivf_top2("cuda") + + def _check_ivf_top2(self, device): + torch.set_num_threads(1) + generator = torch.Generator(device=device).manual_seed(19) + coarse = torch.tensor([[0., 0.], [10., 0.], [20., 0.]], device=device) + candidates = torch.randn(31, 2, generator=generator, device=device) * .25 + candidates[10:20, 0] += 10 + candidates[20:, 0] += 20 + candidates[1] = candidates[0] + queries = torch.cat((candidates[:2], torch.randn(13, 2, generator=generator, device=device) * 10)) + reference = candidates.bfloat16().float() + represented = queries.bfloat16().float() + scores = reference.square().sum(1) - 2 * represented @ reference.T + ids = torch.argsort(scores, dim=1, stable=True)[:, :2] + index = _index(coarse, candidates, 3) + actual_scores, actual_ids = index.search_2nn(queries) + torch.testing.assert_close(actual_ids.long(), ids) + torch.testing.assert_close(actual_scores, scores.gather(1, ids)) + first_scores, first_ids = index.search_1nn(queries) + torch.testing.assert_close(first_scores, actual_scores[:, 0]) + torch.testing.assert_close(first_ids, actual_ids[:, 0]) + + def test_ivf_missing_candidates(self): + coarse = torch.tensor([[0.], [10.], [20.]]) + for candidates in (torch.empty(0, 1), torch.tensor([[0.]]), torch.tensor([[0.], [0.]])): + index = _index(coarse, candidates, 3) + scores, ids = index.search_2nn(torch.zeros(2, 1)) + expected = [0, 1] if len(candidates) == 2 else [0, -1] if len(candidates) == 1 else [-1, -1] + torch.testing.assert_close(ids, torch.tensor([expected, expected], dtype=torch.int32)) + self.assertTrue(torch.isinf(scores[ids < 0]).all()) + empty_scores, empty_ids = index.search_2nn(torch.empty(0, 1)) + self.assertEqual(empty_scores.shape, (0, 2)) + self.assertEqual(empty_ids.shape, (0, 2)) + + def test_bf16_selection_and_lazy_binding(self): + initial = torch.tensor([[0.], [2.]]) + model = QuantizedEmeans(1, 2, batch_size=2) + model.begin(4, initial) + self.assertIsNone(model._removal_stats) + model._bind_input_dtype(torch.bfloat16, cast=True) + self.assertIsNone(model._unused_threshold) + self.assertIsNone(model.recipe["unused_threshold"]) + self.assertEqual(model._removal_stats.shape, (2, 2)) + for dtype in (torch.float16, torch.float32): + other = QuantizedEmeans(1, 2, quantizer=None) + other.begin(4, initial) + other._bind_input_dtype(dtype) + self.assertEqual(other._removal_stats.shape, (2, 2)) + self.assertIsNone(other._unused_threshold) + self.assertIsNone(other.recipe["unused_threshold"]) + for dtype in (torch.float8_e4m3fn, torch.int8): + other = QuantizedEmeans(1, 2, quantizer=None) + other.begin(4, initial) + other._bind_input_dtype(dtype) + self.assertEqual(other._removal_stats.shape, (2, 2)) + self.assertIsNone(other._unused_threshold) + self.assertIsNone(other.recipe["unused_threshold"]) + for threshold in (0, .1): + other = QuantizedEmeans(1, 2, quantizer=CastQuantizer(1, torch.bfloat16), unused_threshold=threshold) + other.begin(4, initial) + if threshold == 0: + self.assertIsNone(other._removal_stats) + else: + self.assertEqual(other._removal_stats.shape, (2, 2)) + self.assertEqual(other._unused_threshold, threshold) + + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "requires Gloo") + def test_owner_statistics_and_cost_splits(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes(_collective_worker, + args=("file://" + directory + "/rendezvous",), + nprocs=2, start_method="spawn") + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_fused_owner_statistics(self): + from faiss.contrib.e_means.ivf_kernels import accumulate_owned + + generator = torch.Generator(device="cuda").manual_seed(31) + for d in (17, 128, 1024): + for dtype in (torch.float32, torch.bfloat16): + for cost in (False, True): + k, n, begin = 32, 513, 32 + rows = torch.randn(n, d, device="cuda", generator=generator).to(dtype) + centroids = torch.randn(k, d, device="cuda", generator=generator) + axes = torch.randn_like(centroids) + axes /= axes.norm(dim=1, keepdim=True) + winners = torch.randint(2 * k, (n,), device="cuda", generator=generator) + margins = torch.rand(n, device="cuda", generator=generator) if cost else None + if cost: + winners[:3] = begin + margins[:3] = torch.tensor([float("nan"), float("inf"), float("-inf")], device="cuda") + reference = QuantizedEmeans(d, k, quantizer=None) + reference._centroids, reference._axes = centroids, axes + reference.centroid_begin = begin + expected = torch.zeros(k, d + 1, device="cuda") + expected_removal = torch.zeros_like(expected) + expected_obj = torch.zeros((), device="cuda", dtype=torch.float64) + reference._batch_removal = expected_removal + # Activate the ordinary owner Oja/removal path used by the + # COST kernel; constructing an unbound model leaves it off. + reference._removal_stats = torch.zeros_like(expected_removal) if cost else None + EmeansShardedCentroids._add_owned(reference, rows, winners, + expected[:, :-1], expected[:, -1], expected_obj, removal=margins) + actual, actual_removal = torch.zeros_like(expected), torch.zeros_like(expected) + actual_obj = torch.zeros_like(expected_obj) + self.assertTrue(accumulate_owned(rows, winners, centroids, axes, + actual, actual_removal if cost else None, actual_obj, margins, begin)) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) + if cost: + torch.testing.assert_close(actual_removal, expected_removal, rtol=1e-4, atol=1e-4) + torch.testing.assert_close(actual_obj, expected_obj, rtol=1e-10, atol=1e-6) + + @unittest.skipUnless(torch.cuda.device_count() >= 2 and dist.is_nccl_available(), + "requires two CUDA GPUs and NCCL") + def test_cuda_ivf_fused_statistics(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes(_ivf_statistics_worker, + args=("file://" + directory + "/rendezvous",), nprocs=2, start_method="spawn") + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_centered_bf16_statistics(self): + import importlib.util + + initial = torch.tensor([[1000., 1000.], [1002., 1000.], [1010., 1000.], [1020., 1000.]], device="cuda") + rows = initial + torch.tensor([[.25, .5], [.5, -.25], [-.5, .25], [-1., .5]], device="cuda") + backends = ["native"] + if importlib.util.find_spec("triton") is not None: + backends.append("triton") + if (torch.version.hip is None + and torch.cuda.get_device_capability() == (9, 0) + and importlib.util.find_spec("cutlass") is not None): + backends.append("cute") + for backend in backends: + with self.subTest(backend=backend): + quantizer = CastQuantizer(2, torch.bfloat16, center=True) + quantizer.train(rows) + model = QuantizedEmeans(2, 4, nepochs=1, batch_size=4, alpha0=.5, + assignment_backend=backend, quantizer=quantizer) + model.begin(4, initial) + model._axes[:] = torch.tensor([1., 0.], device="cuda") + stats = model.accumulate(rows) + encoded = quantizer.compute_codes(rows).float() + represented = quantizer.compute_codes(initial).float() + distances = (encoded[:, None] - represented[None]).square().sum(-1) + order = distances.argsort(dim=1, stable=True) + winner = order[:, 0] + values = quantizer.decode(encoded.bfloat16()) + y = values - initial[winner] + removal = torch.zeros(4, 3, device="cuda") + margin = distances.gather(1, order[:, 1:2]) - distances.gather(1, order[:, :1]) + removal.index_add_(0, winner, torch.cat((y[:, :1] * y, margin), dim=1)) + sums = torch.zeros_like(initial).index_add_(0, winner, values) + torch.testing.assert_close(stats["sums"], sums) + torch.testing.assert_close(stats["removal"], removal, rtol=1e-5, atol=1e-5) + + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_centered_cast.py b/thirdparty/faiss/tests/torch_test_e_means_centered_cast.py new file mode 100644 index 000000000..0fee037d9 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_centered_cast.py @@ -0,0 +1,524 @@ +# 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. + +"""Explicit centered casts: represented rows, original state, unchanged defaults. + +CPU tests qualify codec/metadata only; CPU E-means still rejects quantizers. +GPU tests are small synthetic contracts, not accuracy or performance claims. +""" +import datetime +import gc +import importlib.metadata +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest +import weakref +from unittest import mock + +import torch + +from faiss.contrib.e_means import QuantizedEmeans, DistributedEmeans +from faiss.contrib.e_means.base import _resolve_recipe +from faiss.contrib.e_means.torch_backend import _separate_splits +from faiss.contrib.e_means.quantizer import CastQuantizer +from e_means_test_utils import known_torch_centroids + +_DISTRIBUTED_EVIDENCE = [] + + +def _cuda_ready(): + return (torch.cuda.is_available() and not torch.version.hip + and torch.cuda.get_device_capability() >= (8, 0)) + + +def _cute_ready(): + if not _cuda_ready() or torch.cuda.get_device_capability() != (9, 0): + return False + try: + return (importlib.metadata.version("quack-kernels") == "0.6.5" + and importlib.metadata.version("nvidia-cutlass-dsl") == "4.7.1" + and importlib.metadata.version("cuda-python").startswith("13.")) + except importlib.metadata.PackageNotFoundError: + return False + + +def _fit(shift, dtype, device="cpu"): + shift = torch.as_tensor(shift, dtype=torch.float32) + q = CastQuantizer(shift.numel(), dtype, center=True) + q.train(torch.stack((shift - 1, shift + 1))) + return q.to(device) + + +class TestCenteredCastCPU(unittest.TestCase): + def test_fit_and_frozen_metadata(self): + for dtype in (torch.float16, torch.bfloat16): + q = CastQuantizer(2, dtype, center=True) + self.assertFalse(q.is_trained) + with self.assertRaisesRegex(RuntimeError, "trained explicitly"): + q.compute_codes(torch.zeros(1, 2)) + with self.assertRaisesRegex(RuntimeError, "trained explicitly"): + q.to("cpu") + sample = torch.tensor([[99., -51.], [101., -49.]], requires_grad=True) + saved = sample.detach().clone() + with torch.inference_mode(): + self.assertIsNone(q.train(sample)) + self.assertTrue(q.is_trained) + self.assertFalse(q.shift.is_inference()) + self.assertFalse(q.shift.requires_grad) + torch.testing.assert_close(q.shift, torch.tensor([100., -50.]), rtol=0, atol=0) + token = q._fit_token() + self.assertIs(q.to("cpu"), q) + self.assertEqual(q._fit_token(), token) + with torch.no_grad(): + sample.add_(10) + torch.testing.assert_close(q.shift, saved.mean(0), rtol=0, atol=0) + with self.assertRaises(AttributeError): + q.center = False + with self.assertRaises(AttributeError): + q.shift = torch.zeros(2) + self.assertIsNone(q.train(saved + 2)) + self.assertNotEqual(q._fit_token(), token) + q.shift.add_(1) + with self.assertRaisesRegex(RuntimeError, "frozen"): + q.decode(torch.zeros(1, 2, dtype=dtype)) + + def test_fit_validation(self): + with self.assertRaises(TypeError): + CastQuantizer(1, torch.float16, center=torch.tensor(True)) + for sample, error in ((None, TypeError), (torch.zeros(0, 2), ValueError), + (torch.zeros(2), ValueError), (torch.zeros(2, 1), ValueError), + (torch.zeros(1, 2, dtype=torch.int32), TypeError), + (torch.zeros(1, 2, dtype=torch.float64), TypeError)): + q = CastQuantizer(2, torch.float16, center=True) + with self.assertRaises(error): + q.train(sample) + self.assertFalse(q.is_trained) + for value in (float("nan"), float("inf")): + q = CastQuantizer(2, torch.float16, center=True) + with mock.patch.object(torch.Tensor, "__bool__", side_effect=AssertionError("value sync")), \ + mock.patch.object(torch.Tensor, "item", side_effect=AssertionError("value sync")): + q.train(torch.full((1, 2), value)) + self.assertTrue(q.is_trained) # Unchecked fit follows Torch. + with self.assertRaises(ValueError): + q.validate(torch.zeros(1, 2, dtype=torch.float16)) + q = _fit([100000.], torch.float16) + q.validate(torch.tensor([[100001.]])) + q.validate(torch.tensor([[1.]], dtype=torch.float16)) # Matching codes. + with self.assertRaises(ValueError): + q.validate(torch.tensor([[200000.]])) + with self.assertRaises(ValueError): + q.validate(torch.tensor([[float("inf")]], dtype=torch.float16)) + with self.assertRaises(ValueError): + q.to("meta") + # Finite BF16 residuals can round up, then overflow FP32 add-back. + maximum = torch.finfo(torch.float32).max + q = CastQuantizer(1, torch.bfloat16, center=True) + q.train(torch.tensor([[maximum * .25]], dtype=torch.float32)) + original = torch.tensor([[maximum]], dtype=torch.float32) + codes = q.compute_codes(original) + self.assertTrue(bool(torch.isfinite(codes).all())) + self.assertTrue(bool(torch.isinf(q.decode(codes)).all())) + for value in (original, codes): + with self.assertRaisesRegex(ValueError, "decode to finite"): + q.validate(value) + safe = original * .5 + q.validate(safe) + q.validate(q.compute_codes(safe)) + + def test_original_encoding_and_preencoded_model_convention(self): + for dtype in (torch.float16, torch.bfloat16): + q = _fit([100., -50.], dtype) + x = torch.tensor([[100.25, 0., -49.5, 0.], + [99.75, 0., -50.5, 0.]], requires_grad=True)[:, ::2] + saved = x.detach().clone() + codes = q.compute_codes(x) + self.assertTrue(codes.is_contiguous()) + self.assertFalse(codes.requires_grad) + torch.testing.assert_close(codes.float(), x.detach() - q.shift, rtol=0, atol=0) + torch.testing.assert_close(q.decode(codes), saved, rtol=0, atol=0) + torch.testing.assert_close(x, saved, rtol=0, atol=0) + model = QuantizedEmeans(2, 1, quantizer=q) + torch.testing.assert_close(model._prepare_rows(codes), codes, rtol=0, atol=0) + # compute_codes always encodes original rows, even matching dtype. + original_rounded = torch.tensor([[100., -50.]], dtype=dtype) + torch.testing.assert_close(q.compute_codes(original_rounded), + torch.zeros(1, 2, dtype=dtype), rtol=0, atol=0) + torch.testing.assert_close(q.decode(model._prepare_rows(original_rounded)), + original_rounded.float() + q.shift, rtol=0, atol=0) + with self.assertRaises(TypeError): + q.decode(saved) # Explicit FP32 state is never decoded as codes. + with self.assertRaisesRegex(ValueError, "quantizer=None"): + model.begin(2, saved[:1]) + model._cast_fit_token = q._fit_token() + q.train(saved + 1) + with self.assertRaisesRegex(RuntimeError, "fit changed"): + model._prepare_rows(saved) + # A new run can seed with the new fit without changing old binding. + torch.testing.assert_close(model._prepare_rows(saved, new_run=True), + q.compute_codes(saved), rtol=0, atol=0) + + def test_hot_conversion_has_no_tensor_value_read(self): + q = _fit([100., -50.], torch.bfloat16) + rows = torch.tensor([[100.25, -49.5]]) + with mock.patch.object(torch.Tensor, "__bool__", side_effect=AssertionError("value sync")), \ + mock.patch.object(torch.Tensor, "item", side_effect=AssertionError("value sync")): + codes = q.compute_codes(rows) + decoded = q.decode(codes) + q._fit_token() + q.to("cpu") + torch.testing.assert_close(decoded, rows, rtol=0, atol=0) + + def test_spherical_guard_split_frame_and_decoded_row_rounding(self): + for dtype in (torch.float16, torch.bfloat16): + with self.assertRaisesRegex(ValueError, "spherical"): + QuantizedEmeans(1, 1, spherical=True, + quantizer=CastQuantizer(1, dtype, center=True)) + QuantizedEmeans(1, 1, spherical=True, quantizer=CastQuantizer(1, dtype)) + for shift in (0., 3., 50., 1000., -1000., float(2**39), -float(2**39)): + q = _fit([shift], dtype) + donor = torch.tensor([[shift]], dtype=torch.float32) + child = donor.clone() + with mock.patch.object(torch.Tensor, "__bool__", side_effect=AssertionError("value sync")), \ + mock.patch.object(torch.Tensor, "item", side_effect=AssertionError("value sync")): + _separate_splits(donor, child, dtype, q) + self.assertFalse(torch.equal(q.compute_codes(donor), q.compute_codes(child))) + q.validate(child) + # At 2**40, even the closest FP32 neighbour exceeds FP16 range. + q = _fit([float(2**40)], dtype) + donor = torch.tensor([[float(2**40)]], dtype=torch.float32) + child = donor.clone() + _separate_splits(donor, child, dtype, q) + if dtype == torch.float16: + torch.testing.assert_close(child, donor, rtol=0, atol=0) + for direction in (float("inf"), float("-inf")): + adjacent = torch.nextafter(donor, torch.full_like(donor, direction)) + self.assertGreater((adjacent - donor).abs().item(), torch.finfo(dtype).max) + self.assertFalse(bool(torch.isfinite(q.compute_codes(adjacent)).all())) + else: + self.assertFalse(torch.equal(q.compute_codes(donor), q.compute_codes(child))) + q.validate(child) + tiny = CastQuantizer(1, dtype, center=True) + tiny.train(torch.tensor([[2**-24]])) + decoded = tiny.decode(torch.ones(3, 1, dtype=dtype)) + torch.testing.assert_close(decoded, torch.ones(3, 1), rtol=0, atol=0) + self.assertEqual(decoded.sum().item(), 3.) + self.assertNotEqual((torch.tensor(3.) + 3 * tiny.shift[0]).item(), 3.) + + +class _GPUContracts: + def arms(self): + backends = ["native"] + if importlib.util.find_spec("triton") is not None: + backends.append("triton") + return [(backend, dtype) for backend in backends + for dtype in (torch.float16, torch.bfloat16)] + + def test_chunk_statistics_state_and_jit_codes(self): + for backend, dtype in self.arms(): + with self.subTest(backend=backend, dtype=dtype): + q = _fit([100., -50.], dtype, "cuda") + initial = torch.tensor([[100., -50.], [104., -50.]], device="cuda") + x = initial[[0, 1, 0, 1, 0]] + torch.tensor( + [[.25, .5], [-.25, -.5], [-.25, -.5], [.25, .5], [0., 0.]], device="cuda") + codes, expected_labels = q.compute_codes(x), torch.tensor([0, 1, 0, 1, 0], device="cuda") + decoded = q.decode(codes) + model = QuantizedEmeans(2, 2, nepochs=1, batch_size=3, alpha0=1, quantizer=q, + assignment_backend=backend, assignment_chunk_size=2, + capture_assignments=True) + model.begin(5, initial) + handle = model.current_centroids() + self.assertEqual(handle.data_ptr(), model._centroids.data_ptr()) + model.accumulate(x[:0]) + partial = model.accumulate(x[:1]) + self.assertIsNone(partial["sums"]) + torch.testing.assert_close(handle, initial, rtol=0, atol=0) + all_sums = torch.zeros_like(initial) + all_counts = initial.new_zeros(2) + for start, end, stats in ((0, 3, model.accumulate(codes[1:3])), + (3, 5, None)): + if stats is None: + stats = model.accumulate(x[start:end]) + sums, counts = torch.zeros_like(initial), initial.new_zeros(2) + sums.index_add_(0, expected_labels[start:end], decoded[start:end]) + counts.index_add_(0, expected_labels[start:end], counts.new_ones(end-start)) + torch.testing.assert_close(stats["sums"], sums, rtol=0, atol=0) + torch.testing.assert_close(stats["counts"], counts, rtol=0, atol=0) + self.assertFalse(model._batch_code_units) + model.update(stats) + all_sums += sums + all_counts += counts + model.end_epoch() + torch.testing.assert_close(model._pass_sums, all_sums, rtol=0, atol=0) + final = model.finalize() + torch.testing.assert_close(final, all_sums / all_counts[:, None], rtol=0, atol=0) + self.assertEqual(final.dtype, torch.float32) + distance, labels = model.assign(x) + code_distance, code_labels = model.assign(codes) + torch.testing.assert_close(labels, expected_labels, rtol=0, atol=0) + torch.testing.assert_close(labels, code_labels, rtol=0, atol=0) + torch.testing.assert_close(distance, code_distance, rtol=0, atol=0) + oracle = (codes.double()[:, None] - q.compute_codes(final).double()[None]).square().sum(2) + torch.testing.assert_close(labels, oracle.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance.double(), oracle.min(1).values, atol=2e-4, rtol=2e-5) + + def test_decode_before_statistics_and_fit_guards(self): + for backend, dtype in self.arms(): + with self.subTest(backend=backend, dtype=dtype): + q = CastQuantizer(1, dtype, center=True) + initial = torch.ones(1, 1, device="cuda") + model = QuantizedEmeans(1, 1, nepochs=1, batch_size=3, alpha0=1, + quantizer=q, assignment_backend=backend) + with self.assertRaisesRegex(RuntimeError, "trained explicitly"): + model.begin(3, initial) + q.train(torch.tensor([[2**-24]])) + with self.assertRaisesRegex(ValueError, "same device"): + model.begin(3, initial) + q.to("cuda") + model.begin(3, initial) + codes = torch.ones(3, 1, device="cuda", dtype=dtype) + model.accumulate(codes[:1]) + stats = model.accumulate(codes[1:]) + self.assertEqual(stats["sums"].item(), 3.) + self.assertEqual(stats["counts"].item(), 3.) + model.update(stats) + model.end_epoch() + self.assertEqual(model.finalize().item(), 1.) + q.train(torch.tensor([[2**-23]], device="cuda")) + with self.assertRaisesRegex(RuntimeError, "fit changed"): + model.assign(codes) + with self.assertRaisesRegex(RuntimeError, "fit changed"): + model.finalize() + # Tuple results and implicit seed decoding survive refit. + model = QuantizedEmeans(1, 1, nepochs=1, batch_size=3, alpha0=1, quantizer=q, assignment_backend=backend) + centroids, labels = model.train(codes) + self.assertIs(centroids, model.centroids) + self.assertIs(labels, model.assignments) + self.assertEqual(model.obj[-1].ndim, 0) + self.assertEqual(model.centroids.item(), q.decode(codes)[0].item()) + model = QuantizedEmeans(1, 1, nepochs=1, batch_size=3, alpha0=1, quantizer=q, assignment_backend=backend) + model.begin(3, initial) + q.shift.add_(1) + with self.assertRaisesRegex(RuntimeError, "frozen"): + model.accumulate(codes) + + def test_resident_replay_and_seeded_encoding_parity(self): + for backend, dtype in self.arms(): + with self.subTest(backend=backend, dtype=dtype): + q = _fit([100., -40., 30.], dtype, "cuda") + ids = torch.arange(129, device="cuda") + x = q.shift + torch.stack(((ids % 4).float(), (ids % 3).float() / 4, + (ids % 5).float() / 8), dim=1) + args = dict(nepochs=2, seed=10, quantizer=q, assignment_backend=backend, + capture_assignments=True) + batch, _ = _resolve_recipe(129, 4, 2, batch_law="throughput", + batch_size=None, alpha0=None) + eager = QuantizedEmeans(3, 4, assignment_chunk_size=batch, **args) + eager.train(q.compute_codes(x)) + replay = QuantizedEmeans(3, 4, **args) + calls = [0] + original = torch.cuda.CUDAGraph.replay + capture = QuantizedEmeans._capture_step + owners = [] + graphs, pools, bindings = [], [], [] + + def retained( + model, + *args, + _capture=capture, + _backend=backend, + _bindings=bindings, + _graphs=graphs, + _owners=owners, + _pools=pools, + _q=q, + **kwargs, + ): + result = _capture(model, *args, **kwargs) + _graphs.append(weakref.ref(result[0])) + _pools.append( + weakref.ref(result[1] if len(result) == 2 else result[2]) + ) + if _backend == "cute": + _owners.append(weakref.ref(result[1])) + _bindings.extend( + weakref.ref(binding) + for binding in result[1].bindings.values() + ) + self.assertIs(result[1].transform_bias, _q.shift) + return result + + def counted( + graph, + _calls=calls, + _bindings=bindings, + _graphs=graphs, + _owners=owners, + _pools=pools, + _original=original, + ): + _calls[0] += 1 + self.assertTrue( + all( + owner() is not None + for owner in _owners + _graphs + _pools + _bindings + ) + ) + return _original(graph) + + with mock.patch.object(torch.cuda.CUDAGraph, "replay", counted), \ + mock.patch.object(QuantizedEmeans, "_capture_step", retained): + centroids, labels = replay.train(x) + self.assertGreater(calls[0], 0) + self.assertIs(centroids, replay.centroids) + self.assertIs(labels, replay.assignments) + torch.testing.assert_close(replay.centroids, eager.centroids, atol=2e-5, rtol=2e-6) + torch.testing.assert_close(replay.assignments, eager.assignments, rtol=0, atol=0) + torch.testing.assert_close(replay.obj, eager.obj, atol=2e-4, rtol=2e-5) + gc.collect() + # Train retires the graph and pool; the backend owns its cache. + self.assertTrue(graphs and pools) + self.assertTrue(all(owner() is None for owner in graphs + pools)) + if backend == "cute": + self.assertTrue(owners and bindings) + self.assertIs(replay._execution_backend.cache, owners[-1]()) + self.assertIs(replay._execution_backend.cache.transform_bias, q.shift) + del replay + gc.collect() + self.assertTrue(all(owner() is None for owner in owners + bindings)) + + +@unittest.skipUnless(_cuda_ready(), "NVIDIA SM80 or later required") +class TestCenteredCastCUDA(_GPUContracts, unittest.TestCase): + pass + + +@unittest.skipUnless(_cute_ready(), "pinned CuTe BF16 stack on SM90 required") +class TestCenteredCastCute(_GPUContracts, unittest.TestCase): + def arms(self): + return [("cute", torch.bfloat16)] + + def test_prepared_identity_refresh(self): + q = _fit([100.] * 65, torch.bfloat16, "cuda") + c = q.shift + torch.arange(257, device="cuda").float()[:, None].expand(-1, 65) / 8 + rows = q.compute_codes(c[:17] + .03125) + model = known_torch_centroids(c, model_class=QuantizedEmeans, quantizer=q, assignment_backend="cute") + allocations = [] + center_rows = q._center_rows + + def measured(value): + before = torch.cuda.memory_allocated() + result = center_rows(value) + allocations.append(dict(shape=list(result.shape), device=str(result.device), + dtype=str(result.dtype), logical_bytes=result.numel() * result.element_size(), + allocated_delta=torch.cuda.memory_allocated() - before)) + return result + + def check_result(result): + distance, labels = result + oracle = (rows.double()[:, None] - q.compute_codes(model.centroids).double()[None]).square().sum(2) + torch.testing.assert_close(labels, oracle.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance.double(), oracle.min(1).values, atol=2e-4, rtol=2e-5) + + with mock.patch.object(q, "_center_rows", measured): + check_result(model.assign(rows)) + cached = model._query_backend.cache + pointers = (cached.centroids.data_ptr(), cached.norms.data_ptr()) + torch.testing.assert_close(cached.centroids[:, :65], q.compute_codes(c), rtol=0, atol=0) + check_result(model.assign(rows)) + self.assertIs(model._query_backend.cache, cached) + model.centroids.add_(.25) + check_result(model.assign(rows)) + self.assertIs(model._query_backend.cache, cached) + self.assertEqual((cached.centroids.data_ptr(), cached.norms.data_ptr()), pointers) + torch.testing.assert_close(cached.centroids[:, :65], q.compute_codes(model.centroids), rtol=0, atol=0) + self.assertIs(cached.transform_bias, q.shift) + print("CENTERED_CAST_MIRROR_TEMP " + json.dumps(allocations, sort_keys=True), flush=True) + + +def _distributed_worker(rank, rendezvous): + import torch.distributed as dist + torch.cuda.set_device(rank) + device = torch.device("cuda", rank) + torch.cuda.reset_peak_memory_stats(device) + dist.init_process_group("nccl", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=90)) + try: + for dtype in (torch.float16, torch.bfloat16): + for transport in ("dense", "sparse"): + # Cover independent external mass statistics and default cost + # statistics without weakening removal provenance. + for threshold in (.1, None): + q = _fit([100.], dtype, device) + initial = torch.tensor([[100.], [104.]], device=device) + model = DistributedEmeans(1, 2, nepochs=1, batch_size=8, alpha0=1, + quantizer=q, group=dist.group.WORLD, transport=transport, + unused_threshold=threshold) + model.begin(10, initial) + expected_sums = torch.zeros_like(initial) + expected_counts = initial.new_zeros(2) + for n in (4, 1): + # Both ranks contribute distinct dyadic rows, stable labels. + x = initial[rank:rank+1].expand(n, -1) + (-.25 if rank else .25) + codes = q.compute_codes(x) + model.accumulate(codes[:0]) + if n > 1: + model.accumulate(codes[:1]) + stats = model.accumulate(x[1:] if n > 1 else x) + sums, counts = torch.zeros_like(initial), initial.new_zeros(2) + sums[rank] = q.decode(codes).sum(0) + counts[rank] = n + torch.testing.assert_close(stats["sums"], sums, rtol=0, atol=0) + torch.testing.assert_close(stats["counts"], counts, rtol=0, atol=0) + external = {key: value.clone() if isinstance(value, torch.Tensor) else value + for key, value in stats.items()} + if threshold is None: + # Cost statistics belong to accumulate; cloned sums and + # counts remain caller-owned, but removal keeps identity. + before = model.current_centroids().clone() + with unittest.TestCase().assertRaisesRegex(ValueError, "statistics from this model"): + model.update(external) + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + external["removal"] = stats["removal"] + model.update(external) + torch.testing.assert_close(external["sums"], sums, rtol=0, atol=0) + torch.testing.assert_close(external["counts"], counts, rtol=0, atol=0) + dist.all_reduce(sums) + dist.all_reduce(counts) + expected_sums += sums + expected_counts += counts + torch.testing.assert_close(model._pass_sums, expected_sums, rtol=0, atol=0) + model.end_epoch() + torch.testing.assert_close(model.current_centroids(), expected_sums / expected_counts[:, None], rtol=0, atol=0) + torch.testing.assert_close(model.finalize(), expected_sums / expected_counts[:, None], rtol=0, atol=0) + dist.barrier() + peak = torch.cuda.max_memory_allocated(device) + assert peak <= 2**30, "child Torch allocated peak exceeds 1 GiB" + record = dict(rank=rank, pid=os.getpid(), device=str(device), + torch_peak_allocated_bytes=peak, source=__file__, + gpu_name=torch.cuda.get_device_name(device), + gpu_sm=list(torch.cuda.get_device_capability(device))) + path = Path(rendezvous.removeprefix("file://")).parent / ("rank_%d.json" % rank) + path.write_text(json.dumps(record, sort_keys=True) + "\n") + finally: + dist.destroy_process_group() + + +@unittest.skipUnless(_cuda_ready() and torch.cuda.device_count() >= 2, + "two NVIDIA SM80 or later devices required") +class TestCenteredCastDistributed(unittest.TestCase): + def test_two_rank_original_statistics_dense_sparse(self): + with tempfile.TemporaryDirectory() as folder: + torch.multiprocessing.spawn(_distributed_worker, + args=("file://" + folder + "/rendezvous",), nprocs=2, join=True) + records = [json.loads((Path(folder) / ("rank_%d.json" % rank)).read_text()) for rank in range(2)] + _DISTRIBUTED_EVIDENCE.extend(records) + print("CENTERED_CAST_DISTRIBUTED_PEAK " + json.dumps(records, sort_keys=True), flush=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_closing.py b/thirdparty/faiss/tests/torch_test_e_means_closing.py new file mode 100644 index 000000000..66e732232 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_closing.py @@ -0,0 +1,477 @@ +# 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. + +"""Closing consistency on the base sharded/caller APIs; no cost integration.""" +import datetime +import gc +import tempfile +import unittest +from unittest import mock + +import torch +import torch.distributed as dist + +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids +from faiss.contrib.e_means.torch_backend import TorchBackend + + +class _CPUAssignment(TorchBackend): + """Evaluate rounded BF16 operands with CPU FP32 dots.""" + + def assign(self, rows, centroids, *args, **kwargs): + return super().assign(rows.float(), centroids.float(), *args, **kwargs) + + + +def _completed_closing_model(group, rows, labels, initial, budget, dtype, *, quantizer=None, spherical=False): + """Small caller-driven completed snapshot; CPU uses the existing begin seam.""" + size, rank = dist.get_world_size(group), dist.get_rank(group) + local_k = len(initial) // size + shard = slice(rank * local_k, (rank + 1) * local_k) + model = EmeansShardedCentroids(initial.shape[1], len(initial), group=group, + nepochs=budget, batch_size=len(rows), alpha0=1, unused_threshold=0, + assignment_chunk_size=1, quantizer=quantizer, spherical=spherical, + assignment_backend="native") + if rows.is_cuda: + model.begin(len(rows), initial[shard]) + else: + QuantizedEmeans.begin(model, len(rows), initial[shard]) + model._execution_backend = _CPUAssignment(model.centroid_chunk_size) + local_n = len(rows) // size + model._resolve_first_input(rows[rank * local_n:(rank + 1) * local_n]) + represented = rows if quantizer is None else quantizer.decode(quantizer.compute_codes(rows)) + for epoch_rows in model.recipe["epoch_rows"]: + indices = torch.cat([torch.arange(r * local_n, r * local_n + epoch_rows // size, + device=rows.device) for r in range(size)]) + sums = torch.zeros(local_k, rows.shape[1], dtype=dtype, device=rows.device) + counts = torch.zeros(local_k, dtype=dtype, device=rows.device) + for j in range(local_k): + selected = represented[indices[labels[indices] == j + rank * local_k]].to(dtype) + sums[j] = selected.sum(0) + counts[j] = len(selected) + model.update(dict( + sums=sums, counts=counts, + objective=torch.zeros( + (), dtype=torch.float64, device=rows.device), + n=epoch_rows)) + model.end_epoch() + return model, represented + + + +def _split_closing_worker(rank, rendezvous): + torch.set_num_threads(1) + dist.init_process_group("gloo", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=90)) + try: + check = unittest.TestCase() + initial = torch.tensor([[0.], [10.], [20.], [30.]]) + local = torch.tensor([0., 10., 1., 11., 2., 12., 3., 13.] if rank == 0 + else [20., 30., 21., 31., 22., 32., 23., 33.])[:, None] + all_rows = [torch.empty_like(local) for _ in range(2)] + dist.all_gather(all_rows, local) + all_rows = torch.cat(all_rows) + shard = slice(2 * rank, 2 * rank + 2) + for mode in ("ordinary", "saved", "wrong"): + model = EmeansShardedCentroids(1, 4, group=dist.group.WORLD, + nepochs=1, batch_size=4, alpha0=.5, + assignment_backend="native", + quantizer=CastQuantizer(1, torch.bfloat16)) + # The established CPU/Gloo seam exercises actual owner collectives. + QuantizedEmeans.begin(model, 16, initial[shard]) + model._execution_backend = _CPUAssignment(model.centroid_chunk_size) + codes = torch.empty(8, dtype=torch.int32) + history, after = [], {0: 0, 1: 0, 2: 0, 3: 0} + for step, begin in enumerate(range(0, 8, 2)): + batch = local[begin:begin + 2].bfloat16() + stats = model.accumulate(batch) + codes[begin:begin + 2] = stats["labels"].int() + labels = [torch.empty_like(stats["labels"]) for _ in range(2)] + dist.all_gather(labels, stats["labels"]) + values = [torch.empty_like(batch) for _ in range(2)] + dist.all_gather(values, batch) + history.append((torch.cat(values).float(), torch.cat(labels))) + model.update(stats) + if step < 2: + # Repeat the same cross-owner split; every interval removed + # from both ends must be counted once for saved validation. + def choose(*, rank=rank): + return ((torch.tensor([0]), torch.tensor([2])) if rank == 0 + else (None, None)) + + model._choose_sharded_removal_splits = choose + check.assertEqual(model._revive_unused(torch.Generator(), chunk_rows=1), 1) + after[0] = after[2] = step + 1 + owned_end = 0 + torch.testing.assert_close(model._pass_sums[owned_end], torch.zeros(1), rtol=0, atol=0) + check.assertEqual(model._pass_counts[owned_end].item(), 0) + model.end_epoch() + all_codes = [torch.empty_like(codes) for _ in range(2)] + dist.all_gather(all_codes, codes) + all_codes = torch.cat(all_codes).long() + full_counts = torch.bincount(all_codes, minlength=4) + torch.testing.assert_close( + model._pass_counts + model._discarded_closing_counts, + full_counts[shard].double(), rtol=0, atol=0, + ) + current = model._centroids.clone() + expected = current.clone() + if mode == "ordinary": + for local_j in range(2): + global_j = 2 * rank + local_j + selected = [values[labels == global_j] for values, labels in history[after[global_j]:]] + selected = torch.cat(selected) if selected else local[:0] + check.assertEqual(model._pass_counts[local_j].item(), len(selected)) + torch.testing.assert_close(model._pass_sums[local_j], + selected.to(model._pass_sums.dtype).sum(0), rtol=0, atol=0) + if len(selected): + expected[local_j] = selected.mean(0) + result = model.finalize() + else: + saved = codes.clone() + for local_j in range(2): + selected = all_rows[all_codes == 2 * rank + local_j] + if len(selected): + expected[local_j] = selected.mean(0) + + def no_search(): + raise AssertionError("saved closing performed a search") + + with mock.patch.object(model, "_prepare_assignment", new=no_search), \ + mock.patch.object(torch.cuda, "synchronize"): + if mode == "wrong": + with check.assertRaisesRegex(ValueError, "counts differ"): + model.final_closing_mean([local], assignments=torch.zeros_like(codes), chunk_rows=1) + check.assertTrue(model._failed) + continue + result = model.final_closing_mean([local[:3], local[3:]], assignments=codes, chunk_rows=1) + torch.testing.assert_close(codes, saved, rtol=0, atol=0) + check.assertEqual(model.closing_stats["rows"], 16) + torch.testing.assert_close(result, expected, rtol=0, atol=0) + if mode == "saved": + outputs = [torch.empty_like(result) for _ in range(2)] + dist.all_gather(outputs, result) + returned = torch.cat(outputs) + mse = (all_rows.double() - returned[all_codes].double()).square().mean().item() + check.assertAlmostEqual(model.closing_stats["assignment_mse"], mse, places=6) + check.assertIsNone(model._discarded_closing_counts) + check.assertIs(model.finalize(), result) + finally: + dist.destroy_process_group() + + +def _closing_consistency_worker(rank, rendezvous): + torch.set_num_threads(1) + dist.init_process_group("gloo", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=90)) + def checks(): + model = fresh = None + try: + check = unittest.TestCase() + rows = torch.tensor([0., 1., 2., 40., 50., 3., 4., 6., 8., 10.])[:, None] + labels = torch.tensor([0] * 5 + [1] * 5) + initial = torch.tensor([[0.], [4.], [20.], [30.]]) + shard = slice(rank * 2, rank * 2 + 2) + local = rows[rank * 5:(rank + 1) * 5] + for dtype in (torch.float32, torch.float64, torch.int64): + for budget in (.6, 1.4, 2.6): + model, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, budget, dtype) + if rank == 0: + model._centroids[0] = 10 + frozen = model._centroids.clone() + coverage = model.recipe["epoch_rows"][-1] // 2 + codes = torch.full((5,), -1, dtype=torch.int32) + codes[:coverage] = rank + previews = [] + where = torch.where + def recorded_where(*args, _where=where, _previews=previews, **kwargs): + result = _where(*args, **kwargs) + if result.dtype == torch.float32 and result.shape == (2, 1): + _previews.append(result.clone()) + return result + alias = model._pass_sums + immutable_sums = alias.clone() + reductions = [] + reduce = dist.all_reduce + def recorded_reduce(value, *args, _reduce=reduce, _reductions=reductions, **kwargs): + _reductions.append(tuple(value.shape)) + return _reduce(value, *args, **kwargs) + with mock.patch.object(torch.cuda, "synchronize"), \ + mock.patch.object(torch, "where", new=recorded_where), \ + mock.patch.object(dist, "all_reduce", new=recorded_reduce): + result = model.final_closing_mean([local[:2], local[2:]], assignments=codes, chunk_rows=1) + check.assertEqual(reductions, [(1,), (2,)]) + check.assertGreaterEqual(len(previews), 2) + check.assertTrue(torch.equal(previews[0].view(torch.int32), result.view(torch.int32))) + global_result = [torch.empty_like(result) for _ in range(2)] + dist.all_gather(global_result, result) + returned = torch.cat(global_result) + index = torch.cat((torch.arange(coverage), torch.arange(5, 5 + coverage))) + expected_error = (rows[index].double() - returned[labels[index]].double()).square().sum().item() / len(index) + check.assertAlmostEqual(model.closing_stats["assignment_mse"], expected_error, places=6) + check.assertEqual(model.closing_stats["rows"], 2 * coverage) + if rank == 0: + mean = rows[5:5 + coverage].to(dtype).sum(0).to( + torch.float64 if dtype != torch.float32 else torch.float32) / coverage + torch.testing.assert_close(result[1], mean.float(), rtol=0, atol=0) + first = rows[:coverage].to(dtype).sum(0).to( + torch.float64 if dtype != torch.float32 else torch.float32) / coverage + torch.testing.assert_close(result[0], first.float(), rtol=0, atol=0) + else: + torch.testing.assert_close(result, frozen, rtol=0, atol=0) + torch.testing.assert_close(alias, immutable_sums, rtol=0, atol=0) + check.assertIs(model.finalize(), result) + with check.assertRaisesRegex(RuntimeError, "complete epochs"): + model.final_closing_mean([local], assignments=codes) + + # Same completed state, now a full fresh scan and its old snapshot error. + fresh, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, budget, dtype) + if rank == 0: + fresh._centroids[0] = 10 + snapshots = [torch.empty_like(fresh._centroids) for _ in range(2)] + dist.all_gather(snapshots, fresh._centroids) + snapshot = torch.cat(snapshots) + distance = (rows[:, None] - snapshot[None]).square().sum(2) + winners = distance.argmin(1) + expected = snapshot.clone() + for j in range(4): + selected = rows[winners == j].to(dtype) + if len(selected): + expected[j] = (selected.sum(0).to(torch.float64 if dtype != torch.float32 else torch.float32) / len(selected)).float() + result = fresh.final_closing_mean([local[:2], local[2:]]) + torch.testing.assert_close(result, expected[shard], rtol=0, atol=0) + check.assertEqual(fresh.closing_stats["assignment_mse"], distance.min(1).values.double().sum().item() / len(rows)) + check.assertIs(fresh.finalize(), result) + print("closing CPU seam", rank, dtype, budget, "passed", flush=True) + finally: + del model, fresh + + try: + checks() + finally: + # Release test-owned cycles before the caller-owned group joins Gloo work. + gc.collect() + dist.destroy_process_group() + + + +class TestClosingConsistency(unittest.TestCase): + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "requires Gloo") + def test_cpu_gloo_repeated_split_ordinary_and_saved_closing(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes(_split_closing_worker, + args=("file://" + directory + "/closing",), + nprocs=2, start_method="spawn") + + def test_pure_closing_values_and_strided_finalizer(self): + from faiss.contrib.e_means.e_means_torch import Emeans, _closing_centroid_values + + devices = ["cpu"] + (["cuda"] if torch.cuda.is_available() else []) + for device in devices: + for dtype in (torch.float32, torch.float64, torch.int64): + with self.subTest(device=device, dtype=dtype): + backing = torch.full((4, 6), -99, dtype=dtype, device=device) + sums = backing[:, ::2] + sums.copy_(torch.tensor([[6, 12, 18], [13, 7, 4], [0, 0, 0], [9, 12, 15]], device=device)) + count_backing = torch.full((8,), -99, dtype=torch.float64, device=device) + counts = count_backing[::2] + counts.copy_(torch.tensor([3, 2**24 + 1, 0, 5], dtype=torch.float64, device=device)) + current = torch.tensor([[10., 20., 30.], [4., 5., 6.], [-0., 7., 8.], [9., 8., 7.]], + device=device).t().contiguous().t() + originals = [v.clone() for v in (backing, count_backing, current)] + # Original finalize arithmetic on an owned copy, including count conversion. + promote = torch.float64 if dtype != torch.float32 else torch.float32 + reference = sums.to(promote).clone() + divisor = counts.clamp_min(1).to(promote)[:, None] + if promote == torch.float64: + reference.div_(divisor) + reference = reference.float() + else: + reference = reference / divisor + expected = torch.where((counts > 0)[:, None], reference, current) + values = _closing_centroid_values(sums, counts, current) + self.assertTrue(torch.equal(values.view(torch.int32), expected.view(torch.int32))) + model = Emeans(3, 4, nepochs=1, batch_size=4, unused_threshold=0, assignment_backend="native") + model.begin(4, current) + model.update(dict(sums=torch.zeros(4, 3, device=device), counts=torch.ones(4, device=device), + objective=torch.zeros((), dtype=torch.float64, device=device), n=4)) + model.end_epoch() + # A value-only completed carrier exercises admitted strided working views. + model._centroids, model._pass_sums, model._pass_counts = current, sums, counts + result = model.finalize() + self.assertTrue(result.is_contiguous()) + self.assertTrue(torch.equal(result.view(torch.int32), expected.contiguous().view(torch.int32))) + self.assertIs(model.finalize(), result) + for actual, original in zip((backing, count_backing, current), originals): + self.assertTrue(torch.equal(actual.contiguous().view(torch.uint8), original.contiguous().view(torch.uint8))) + + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "requires Gloo") + def test_cpu_gloo_saved_and_fresh_closing(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.start_processes(_closing_consistency_worker, + args=("file://" + directory + "/closing",), + nprocs=2, start_method="spawn") + + @unittest.skipUnless(torch.cuda.is_available() and dist.is_nccl_available(), "requires CUDA and NCCL") + def test_cuda_typed_saved_and_fresh_closing(self): + from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer + + with tempfile.TemporaryDirectory() as directory: + dist.init_process_group("nccl", init_method="file://" + directory + "/closing", + rank=0, world_size=1, timeout=datetime.timedelta(seconds=90)) + def checks(): + model = fresh = empty = wide = failed = None + try: + device = torch.device("cuda") + # Actual supported single-rank CUDA path; no additional GPU allocation. + for dtype in (torch.float32, torch.float64, torch.int64): + for budget in (.6, 1.4, 2.6): + with self.subTest(dtype=dtype, budget=budget): + rows = torch.zeros(10, 1, device=device) + labels = torch.zeros(10, dtype=torch.int64, device=device) + initial = torch.tensor([[10.], [20.]], device=device) + model, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, budget, dtype) + model._centroids[0] = 10 + coverage = model.recipe["epoch_rows"][-1] + codes = torch.full((10,), -1, dtype=torch.int32) + codes[:coverage] = 0 + result = model.final_closing_mean([rows[:3], rows[3:]], assignments=codes, chunk_rows=2) + torch.testing.assert_close(result, torch.tensor([[0.], [20.]], device=device), rtol=0, atol=0) + self.assertEqual(model.closing_stats["assignment_mse"], 0.) + self.assertEqual(model.closing_stats["rows"], coverage) + self.assertIs(model.finalize(), result) + with self.assertRaisesRegex(RuntimeError, "complete epochs"): + model.final_closing_mean([rows]) + + fresh, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, budget, dtype) + fresh._centroids[0] = 10 + result = fresh.final_closing_mean([rows[:3], rows[3:]]) + torch.testing.assert_close(result, torch.tensor([[0.], [20.]], device=device), rtol=0, atol=0) + self.assertEqual(fresh.closing_stats["assignment_mse"], 100.) + self.assertNotIn("returned_mse", fresh.closing_stats) + self.assertIs(fresh.finalize(), result) + + floating = torch.tensor([0., .5, 1., 2., 2.5, 3.], device=device)[:, None] + codecs = [None, CastQuantizer(1, torch.bfloat16, center=True), Int8Quantizer(1)] + for q in codecs: + if q is not None: + q.train(floating) + rows = floating + labels = torch.zeros(len(rows), dtype=torch.int64, device=device) + initial = torch.tensor([[10.], [20.]], device=device) + model, represented = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float32, quantizer=q) + model._centroids[0] = 10 + codes = torch.zeros(len(rows), dtype=torch.int32) + scan = q.compute_codes(rows) if q is not None and q.dtype == torch.int8 else rows + result = model.final_closing_mean([scan], assignments=codes, chunk_rows=2) + torch.testing.assert_close(result[0], represented.double().mean(0).float()) + torch.testing.assert_close(result[1], initial[1], rtol=0, atol=0) + expected = (represented.double() - result[0].double()).square().sum().item() / len(rows) + self.assertAlmostEqual(model.closing_stats["assignment_mse"], expected, places=6) + + for dtype in (torch.int8, torch.uint8): + rows = torch.tensor([-2, -1, 0, 1, 2, 3] if dtype == torch.int8 else [0, 1, 2, 3, 4, 5], + dtype=dtype, device=device)[:, None] + labels = torch.zeros(len(rows), dtype=torch.int64, device=device) + initial = torch.tensor([[10.], [20.]], device=device) + model, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.int64) + model._centroids[0] = 10 + result = model.final_closing_mean([rows], assignments=torch.zeros(len(rows), dtype=torch.int32), chunk_rows=2) + torch.testing.assert_close(result[0], rows.double().mean(0).float()) + torch.testing.assert_close(result[1], initial[1], rtol=0, atol=0) + self.assertAlmostEqual(model.closing_stats["assignment_mse"], + (rows.double() - result[0].double()).square().sum().item() / len(rows), places=6) + + rows = torch.tensor([[1., 0.], [0., 1.], [1., 0.], [0., 1.]], device=device) + labels = torch.zeros(4, dtype=torch.int64, device=device) + initial = torch.tensor([[1., 0.], [-1., 0.]], device=device) + model, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float32, spherical=True) + model._centroids.copy_(initial) + result = model.final_closing_mean([rows]) + expected = torch.nn.functional.normalize(torch.tensor([[1., 1.], [-1., 0.]], device=device), dim=1) + torch.testing.assert_close(result, expected) + self.assertEqual(model.closing_stats["assignment_error"], 1.) + self.assertNotIn("assignment_mse", model.closing_stats) + self.assertIs(model.finalize(), result) + + rejected, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float32, spherical=True) + with self.assertRaisesRegex(ValueError, "spherical=False"): + rejected.final_closing_mean([rows], assignments=torch.zeros(4, dtype=torch.int32)) + + rows = torch.zeros(4, 1, device=device) + labels = torch.zeros(4, dtype=torch.int64, device=device) + initial = torch.tensor([[10.], [20.]], device=device) + rejected, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float32) + with self.assertRaisesRegex(ValueError, "counts differ"): + rejected.final_closing_mean([rows], assignments=torch.ones(4, dtype=torch.int32)) + self.assertTrue(rejected._failed) + self.assertIsNone(rejected.centroids) + rejected, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float32) + with self.assertRaisesRegex(ValueError, "cover global_n"): + rejected.final_closing_mean([rows[:1]]) + self.assertTrue(rejected._failed) + + # Controlled zero-observation state: omitted rows contribute no error. + empty, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float64) + empty._pass_counts.zero_() + empty._centroids.copy_(initial) + result = empty.final_closing_mean([rows], assignments=torch.full((4,), -1, dtype=torch.int32)) + torch.testing.assert_close(result, initial, rtol=0, atol=0) + self.assertEqual(empty.closing_stats["rows"], 0) + self.assertEqual(empty.closing_stats["assignment_mse"], 0.) + + # Scoring and finalization share the same two bounded pure blocks. + width, count = 65536, 16 + rows = torch.ones(count, width, device=device) + labels = torch.zeros(count, dtype=torch.int64, device=device) + initial = torch.full((count, width), 7., device=device) + wide, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float64) + wide._centroids[0] = 10 + previews = [] + where = torch.where + def observed_preview(*args, _where=where, _width=width, _previews=previews, **kwargs): + result = _where(*args, **kwargs) + if result.dtype == torch.float32 and result.ndim == 2 and result.shape[1] == _width: + _previews.append(result.cpu()) + return result + def unexpected_assignment(): + raise AssertionError("saved scan searched") + with mock.patch.object(torch, "where", new=observed_preview), \ + mock.patch.object(wide, "_prepare_assignment", new=unexpected_assignment): + result = wide.final_closing_mean([rows[:8], rows[8:]], + assignments=torch.zeros(count, dtype=torch.int32), + chunk_rows=4) + self.assertEqual([len(block) for block in previews], [10, 6, 16]) + self.assertTrue(torch.equal(torch.cat(previews[:2]).view(torch.int32), result.cpu().view(torch.int32))) + self.assertTrue(torch.equal(torch.cat(previews[2:]).view(torch.int32), result.cpu().view(torch.int32))) + self.assertTrue(result.is_contiguous()) + self.assertEqual(wide.closing_stats["assignment_mse"], 0.) + + # Failure after division must not publish the owned but unfinished output. + failed, _ = _completed_closing_model(dist.group.WORLD, rows, labels, initial, 1, torch.float64) + unchanged = failed._pass_sums.clone() + def failed_preview(*args, **kwargs): + raise RuntimeError("injected closing block") + with mock.patch.object(torch, "where", new=failed_preview), \ + self.assertRaisesRegex(RuntimeError, "injected closing block"): + failed.finalize() + self.assertTrue(failed._failed) + self.assertIsNone(failed.centroids) + torch.testing.assert_close(failed._pass_sums, unchanged, rtol=0, atol=0) + finally: + del model, fresh, empty, wide, failed + + try: + checks() + finally: + gc.collect() + dist.destroy_process_group() + + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_cute.py b/thirdparty/faiss/tests/torch_test_e_means_cute.py new file mode 100644 index 000000000..f7397a30e --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_cute.py @@ -0,0 +1,1727 @@ +# 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 importlib.metadata +import gc +import unittest +import weakref +import subprocess +import sys +import time +from contextlib import nullcontext +from types import SimpleNamespace +from unittest import mock + +import numpy as np +import torch + +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.e_means_torch import Emeans +from faiss.contrib.e_means import torch_backend +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer +from faiss.contrib.e_means import e_means_torch as e_means +from e_means_test_utils import known_torch_centroids + + +def _ready(): + if not torch.cuda.is_available() or getattr(torch.version, 'hip', None) is not None: + return False + if torch.cuda.get_device_capability() != (9, 0): + return False + try: + return (importlib.metadata.version('quack-kernels') == '0.6.5' + and importlib.metadata.version('nvidia-cutlass-dsl') == '4.7.1' + and importlib.metadata.version('cuda-python').startswith('13.')) + except importlib.metadata.PackageNotFoundError: + return False + + +def _integer_second(k): + from faiss.contrib.e_means import cute + + for dtype in (torch.int8, torch.uint8, torch.float8_e4m3fn): + centers = torch.zeros(k, 16, device="cuda") + centers[:, 0] = 100 + centers[0, 0], centers[128, 0], centers[-1, 0] = 0, 1, 1 + rows = torch.zeros(129, 16, device="cuda", dtype=dtype) + prepared = cute._prepare_centroids(centers, dtype=dtype) + first = torch.empty(129, device="cuda", dtype=torch.float32 if dtype == torch.float8_e4m3fn else torch.int64) + second = torch.empty_like(first) + other = torch.empty(129, device="cuda", dtype=torch.int64) + _, ids = cute._assign_rows(rows, prepared, first, second_out=second, second_labels_out=other) + for actual, value in ((first, 0), (second, 1), (ids, 0), (other, 128)): + torch.testing.assert_close(actual, torch.full_like(actual, value), rtol=0, atol=0) + + +class TestEmeansCute(unittest.TestCase): + def test_quack_helper_accepts_three_positional_operands(self): + from faiss.contrib.e_means import cute + + def renamed(copy, source, thread): + raise AssertionError('capability check must not execute the helper') + + def incompatible(copy, source, thread, required): + raise AssertionError('capability check must not execute the helper') + + versions = {'quack-kernels': '0.6.5', 'nvidia-cutlass-dsl': '4.7.1', + 'cuda-python': '13.4.1'} + for helper, expected in ((renamed, True), (incompatible, False)): + modules = { + 'cuda.bindings.driver': SimpleNamespace(CUstream=object), + 'quack.epilogue.ops': SimpleNamespace(_lane_warp_info_n=helper), + 'quack.gemm_sm90': SimpleNamespace(GemmSm90=object), + 'quack.tile_scheduler': SimpleNamespace(TileScheduler=object), + 'quack.gemm_tvm_ffi_utils': SimpleNamespace(compile_gemm_kernel=object), + } + cute._stack_status.cache_clear() + try: + with mock.patch.object(cute.importlib.metadata, 'version', side_effect=versions.__getitem__), \ + mock.patch.object(cute.importlib.util, 'find_spec', return_value=object()), \ + mock.patch.object(cute.importlib, 'import_module', side_effect=modules.__getitem__): + self.assertEqual(cute._stack_status()[0], expected) + finally: + cute._stack_status.cache_clear() + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_second_distance_is_exact(self): + # Centroid j holds the bits of j, so its nearest others differ by one + # bit, often in its own tile; in the last two cases only the winner's + # tile holds the second. Rows sit 0.5 off their centroid; the tolerance + # is the kernel's norm-plus-dot rounding. As in training, the + # label-sorted accumulate completes the tiled kernel's seconds below + # 13 k-tiles. + backend = torch_backend.CuteBackend(4096) + cases = [] + for k, d in ((2, 96), (130, 96), (192 * 86, 96), (16384, 768), (16384, 1024)): + c = torch.zeros(k, d, device='cuda') + c[:, :15] = (torch.arange(k, device='cuda')[:, None] >> torch.arange(15, device='cuda')) & 1 + labels = torch.arange(65536, device='cuda') % k + x = c[labels] + x[:, -1] = 0.5 + cases.append((c, x, labels, 0.25, 1.25)) + for d in (96, 768): + c = torch.zeros(2048, d, device='cuda') + c[1, 0] = 1 + c[2:, 0] = 100 + cases.append((c, torch.zeros(1024, d, device='cuda'), torch.zeros(1024, dtype=torch.long, device='cuda'), 0.0, 1.0)) + for c, x, labels, d1, d2 in cases: + k, d = c.shape + second = torch.empty(len(x), device='cuda') + distance, assigned = backend.assign( + x.bfloat16(), backend.prepare_centroids(c, torch.bfloat16)[0], second_out=second) + backend.accumulate_removal(x.bfloat16(), assigned, torch.zeros(k, d + 1, device='cuda'), distance, second, + torch.zeros(k, d, device='cuda'), c, torch.zeros(k, d + 1, device='cuda')) + self.assertTrue(torch.equal(assigned.long(), labels)) + torch.testing.assert_close(distance, torch.full_like(distance, d1), rtol=0, atol=1e-5) + torch.testing.assert_close(second, torch.full_like(second, d2), rtol=0, atol=1e-5) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_second_output_metadata_rejects_before_binding(self): + from faiss.contrib.e_means import cute as backend + + rows = torch.zeros((3, 16), dtype=torch.bfloat16, device='cuda') + centers = torch.zeros((2, 16), device='cuda') + backing = torch.full((6,), -123., device='cuda') + saved_backing = backing.clone() + cases = [backing[::2], torch.full((2,), -123., device='cuda'), + torch.full((4,), -123., device='cuda'), torch.full((3, 1), -123., device='cuda'), + torch.full((), -123., device='cuda'), torch.full((3,), -123., dtype=torch.float16, device='cuda'), + torch.full((3,), -123., dtype=torch.float64, device='cuda'), torch.full((3,), -123., device='cpu'), + [1., 2., 3.]] + if torch.cuda.device_count() >= 2: + other = torch.device('cuda', (rows.device.index + 1) % torch.cuda.device_count()) + cases.append(torch.full((3,), -123., device=other)) + for spherical in (False, True): + prepared = backend._prepare_centroids(centers, spherical=spherical) + distance = torch.full((3,), -456., device='cuda') + labels = torch.full((3,), -789, dtype=torch.int64, device='cuda') + for index, second in enumerate(cases): + with self.subTest(spherical=spherical, index=index): + saved = second.clone() if isinstance(second, torch.Tensor) else list(second) + error = ValueError if isinstance(second, torch.Tensor) else TypeError + with mock.patch.object(backend, '_binding_for', side_effect=AssertionError('invalid output reached binding')) as bind, \ + self.assertRaisesRegex(error, 'second distances'): + backend._assign_rows(rows, prepared, distance, labels, second) + bind.assert_not_called() + if isinstance(second, torch.Tensor): + torch.testing.assert_close(second, saved, rtol=0, atol=0) + else: + self.assertEqual(second, saved) + torch.testing.assert_close(backing, saved_backing, rtol=0, atol=0) + torch.testing.assert_close(distance, torch.full_like(distance, -456.), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.full_like(labels, -789), rtol=0, atol=0) + self.assertFalse(prepared.bindings) + # Stock primary-output guards remain ahead of binding and output writes. + for bad_distance, bad_labels in ((distance[:2], labels), (distance, labels[:, None])): + with mock.patch.object(backend, '_binding_for', side_effect=AssertionError('invalid primary reached binding')) as bind, \ + self.assertRaises(ValueError): + backend._assign_rows(rows, prepared, bad_distance, bad_labels, torch.zeros(3, device='cuda')) + bind.assert_not_called() + torch.testing.assert_close(distance, torch.full_like(distance, -456.), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.full_like(labels, -789), rtol=0, atol=0) + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_second_output_owned_views_euclidean_and_spherical(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + for spherical in (False, True): + with self.subTest(spherical=spherical): + # D1024 uses exact tiled seconds, without low-D refinement. + rows = torch.zeros((3, 1024), dtype=torch.bfloat16, device='cuda') + centers = torch.zeros((2, 1024), device='cuda') + rows[:, 0] = torch.tensor([1., .5, -1.] if spherical else [0., .5, 2.], device='cuda') + centers[:, 0] = torch.tensor([1., -1.] if spherical else [0., 2.], device='cuda') + truth = -2 * (rows.double()[:, None] * centers.double()[None]).sum(2) if spherical else ( + rows.double()[:, None] - centers.double()[None]).square().sum(2) + prepared = _prepare_centroids(centers, spherical=spherical) + # Disjoint contiguous views may share an allocation, with offset pointers. + backing = torch.full((9,), -123., device='cuda') + distance, second = backing[1:4], backing[5:8] + label_backing = torch.full((5,), -789, dtype=torch.int64, device='cuda') + labels = label_backing[1:-1] + pointer = second.data_ptr() + actual = _assign_rows(rows, prepared, distance, labels, second) + self.assertIs(actual[0], distance) + self.assertIs(actual[1], labels) + self.assertEqual(second.data_ptr(), pointer) + torch.testing.assert_close(distance.double(), truth.min(1).values, rtol=0, atol=0) + torch.testing.assert_close(labels, truth.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(second.double(), truth.max(1).values, rtol=0, atol=0) + self.assertEqual(backing[[0, 4, 8]].tolist(), [-123., -123., -123.]) + self.assertEqual(label_backing[[0, -1]].tolist(), [-789, -789]) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fractional_training_reuses_dynamic_decoder(self): + from collections import OrderedDict + from faiss.contrib.e_means import cute_argmin, cute_kernel + + rows = torch.zeros((31, 256), dtype=torch.bfloat16, device='cuda') + rows[:, 0] = torch.arange(31, device='cuda').float() / 4 + initial = rows[[0, 10, 20, 30]].float() + compile_kernel, prepare = cute_argmin.cute.compile, cute_kernel.prepare_argmin_decode + compiled, sizes, handles, counts, finals = [], [], [], [], [] + + def compile(operation, *args, **kwargs): + result = compile_kernel(operation, *args, **kwargs) + if isinstance(operation, cute_argmin._DecodeArgminOutputsSm90): + compiled.append(result) + return result + + def bind(keys, codes, scores): + result = prepare(keys, codes, scores) + sizes.append(keys.numel()) + handles.append(result.compiled) + return result + + with mock.patch.object(cute_argmin, '_COMPILED', OrderedDict()), \ + mock.patch.object(cute_argmin.cute, 'compile', new=compile), \ + mock.patch.object(cute_kernel, 'prepare_argmin_decode', new=bind): + for _ in range(2): + before = len(compiled) + model = Emeans(256, 4, nepochs=1.25, batch_size=7, alpha0=.2, seed=7, + assignment_backend='cute', capture_assignments=True) + model.train(rows, initial) + counts.append(len(compiled) - before) + order = torch.randperm(31, device=rows.device, generator=e_means._torch_generator( + rows.device, e_means._epoch_seed(7, 1))) + labels = model.assignments[order] + self.assertTrue(bool(((labels >= 0) & (labels < 4)).all())) + for label in range(4): + selected = rows[order][labels == label].float() + if len(selected): + torch.testing.assert_close(model.centroids[label], selected.double().mean(0).float(), + atol=1e-6, rtol=1e-6) + finals.append(model.centroids.clone()) + self.assertEqual(counts, [1, 0]) + self.assertEqual(set(sizes), {1, 3, 7}) + self.assertTrue(all(handle is handles[0] for handle in handles)) + torch.testing.assert_close(finals[0], finals[1], atol=1e-6, rtol=1e-6) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_decoder_bits_tail_reset_and_retained_graph(self): + from collections import OrderedDict + from faiss.contrib.e_means import cute_argmin as decode + + score_pattern = torch.tensor([-float('inf'), -2.5, 0., 2**-149, .25, float('inf')], device='cuda') + label_pattern = torch.tensor([0, 17, 2**31 - 1], device='cuda', dtype=torch.int64) + retained = [] + with mock.patch.object(decode, '_COMPILED', OrderedDict()): + for dtype in (torch.int32, torch.int64): + for n in (1, 257): + scores = score_pattern[torch.arange(n, device='cuda') % len(score_pattern)] + labels = label_pattern[torch.arange(n, device='cuda') % len(label_pattern)] + if n > 5: + labels[5] = 0 # Existing Inf row is the real neutral key. + bits = scores.view(torch.int32).long() & 0xFFFFFFFF + ordered = torch.where(bits >> 31 != 0, (~bits) & 0xFFFFFFFF, bits ^ 0x80000000) + payload = ((ordered - 0x80000000) << 32) | labels + if n > 5: + self.assertEqual(payload[5].item(), decode.INITIAL_KEY) + owners = (torch.full((n + 2,), -123, dtype=torch.int64, device='cuda'), + torch.full((n + 2,), -123, dtype=dtype, device='cuda'), + torch.full((n + 2,), -123., device='cuda')) + key, code, score = (owner[1:-1] for owner in owners) + key.copy_(payload) + bound = decode.prepare_argmin_decode(key, code, score) + retained.append((bound, payload, labels, scores)) + decode.launch_argmin_decode(bound) + torch.testing.assert_close(code.long(), labels, rtol=0, atol=0) + torch.testing.assert_close(score.view(torch.int32), scores.view(torch.int32), rtol=0, atol=0) + self.assertTrue(bool((key == decode.INITIAL_KEY).all())) + for owner in owners: + self.assertEqual(owner[[0, -1]].tolist(), [-123, -123]) + self.assertIs(retained[-1][0].compiled, retained[-2][0].compiled) + self.assertIsNot(retained[0][0].compiled, retained[2][0].compiled) + bound, payload, labels, scores = retained[1] + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + graph = torch.cuda.CUDAGraph() + try: + with torch.cuda.stream(stream): + with torch.cuda.graph(graph, stream=stream): + decode.launch_argmin_decode(bound) + decode._COMPILED.clear() + for shift in (0, 1): + bound.keys.copy_(payload.roll(shift)) + graph.replay() + stream.synchronize() + torch.testing.assert_close(bound.codes.long(), labels.roll(shift), rtol=0, atol=0) + torch.testing.assert_close(bound.scores.view(torch.int32), + scores.roll(shift).view(torch.int32), rtol=0, atol=0) + self.assertTrue(bool((bound.keys == decode.INITIAL_KEY).all())) + finally: + stream.synchronize() + graph.reset() + torch.cuda.current_stream().wait_stream(stream) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_spherical_natural_grouped_route_and_represented_statistics(self): + from faiss.contrib.e_means import cute_grouped + + centers = torch.zeros((32768, 17), device='cuda') + centers[:, 0] = -1 + centers[5, 0] = centers[133, 0] = 1 + centers[-1].zero_() + centers[-1, 1] = 1 + centers[257].zero_() + centers[257, :3] = 1 / (3**.5) + roster = torch.zeros((6, 17), device='cuda', dtype=torch.bfloat16) + roster[0, 0] = roster[1, 1] = 1 + roster[2, 0] = roster[4, 1] = -1 + roster[5, :3] = 1 / (3**.5) + membership = torch.arange(65536, device='cuda') % len(roster) + rows = roster[membership] + # Rounded unit directions can have IP>1; real model statistics must + # retain the resulting negative spherical objective, not clamp it. + ip = torch.tensor([1., 1., 1., 0., 0., 1.002685546875], device='cuda')[membership] + ids = torch.tensor([5, 32767, 0, 0, 0, 257], device='cuda')[membership] + model = Emeans(17, 32768, nepochs=1, batch_size=len(rows), alpha0=1, + assignment_backend='cute', assignment_chunk_size=len(rows), spherical=True) + model.begin(len(rows), centers) + snapshot = model.current_centroids().clone() + selected = [] + prepare = cute_grouped.prepare_grouped + + def observe(*args, **kwargs): + selected.append((len(args[0]), args[1].spherical)) + return prepare(*args, **kwargs) + + with mock.patch.object(cute_grouped, 'prepare_grouped', new=observe): + stats = model.accumulate(rows) + self.assertEqual(selected, [(len(rows), True)]) + counts = torch.bincount(ids, minlength=model.k).float() + sums = torch.zeros_like(centers).index_add_(0, ids, rows.float()) + torch.testing.assert_close(stats['labels'], ids, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], counts, rtol=0, atol=0) + torch.testing.assert_close(stats['sums'], sums, rtol=0, atol=0) + torch.testing.assert_close(stats['objective'], (2 - 2*ip).double().sum(), rtol=0, atol=0) + model.update(stats) + model.end_epoch() + final = model.finalize() + wanted = torch.where((counts > 0)[:, None], torch.nn.functional.normalize(sums, dim=1), snapshot) + torch.testing.assert_close(final, wanted, rtol=2e-6, atol=2e-7) + # Restore the initial directions to check actual public similarity + # conversion independently of the already-checked closing means. + model.centroids.copy_(snapshot) + similarity, labels = model.assign(rows) + torch.testing.assert_close(similarity, ip, rtol=0, atol=0) + torch.testing.assert_close(labels, ids, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_spherical_grouped_fp64_oracle_and_captured_refresh(self): + from faiss.contrib.e_means import cute + + rng = torch.Generator().manual_seed(1417) + rows = torch.randn(129, 17, generator=rng) + centers = torch.randn(256, 17, generator=rng) + rows = torch.nn.functional.normalize(rows, dim=1).to(device='cuda', dtype=torch.bfloat16) + centers = torch.nn.functional.normalize(centers, dim=1).cuda() + prepared = cute._prepare_centroids(centers, spherical=True) + # Explicit legal leaf geometry: this is NOT a small-work auto-route claim. + bound = cute._new_grouped_binding(len(rows), prepared, torch.float32, plan=(128, 64, 2)) + + def launch(): + bound.workspace.copy_(rows) + bound.launcher(bound.kernel, bound.labels) + + launch() + truth = rows.double() @ prepared.centroids.double().T + absolute = rows.double().abs() @ prepared.centroids.double().abs().T + gamma = 17 * 2**-24 / (1 - 17 * 2**-24) + error, regret = gamma * absolute.max(1).values, 4 * gamma * absolute.max(1).values + chosen = truth[torch.arange(len(rows), device='cuda'), bound.labels] + best, wanted = truth.max(1) + self.assertTrue(bool(((-.5*bound.scores - chosen).abs() <= error).all())) + self.assertTrue(bool((best - chosen <= regret).all())) + margin = truth.topk(2, dim=1).values + far = margin[:, 0] - margin[:, 1] > regret + torch.testing.assert_close(bound.labels[far], wanted[far], rtol=0, atol=0) + rows.zero_() + rows[:, 0] = 1 + centers.zero_() + centers[:, 0] = -1 + cute._prepare_centroids(centers, cached=prepared, spherical=True) + launch() + torch.testing.assert_close(bound.scores, torch.full_like(bound.scores, 2), rtol=0, atol=0) + torch.testing.assert_close(bound.labels, torch.zeros_like(bound.labels), rtol=0, atol=0) + centers[7].zero_() # A zero direction must beat all negative similarities. + cute._prepare_centroids(centers, cached=prepared, spherical=True) + launch() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + graph = torch.cuda.CUDAGraph() + try: + with torch.cuda.stream(stream): + with torch.cuda.graph(graph, stream=stream): + prepared.source_version = None + cute._prepare_centroids(centers, cached=prepared, spherical=True) + launch() + centers[7, 0] = -1 + centers[9].zero_() + graph.replay() + stream.synchronize() + torch.testing.assert_close(bound.scores, torch.zeros_like(bound.scores), rtol=0, atol=0) + torch.testing.assert_close(bound.labels, torch.full_like(bound.labels, 9), rtol=0, atol=0) + self.assertEqual(prepared.norms.count_nonzero().item(), 0) + finally: + stream.synchronize() + graph.reset() + torch.cuda.current_stream().wait_stream(stream) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_byte_exact_distance_output(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + for dtype, offset in ((torch.int8, 0), (torch.uint8, 128)): + for d, k in ((8192, 1), (320, 128)): + rows = torch.full((1, d), offset, dtype=dtype, device='cuda') + c = torch.full((k, d), float(offset), device='cuda') + if d == 8192: + c[:, :1024] -= 128 + c[:, 1024] += 1 + expected = 2**24 + 1 + else: + rows[:, :259] = 127 + offset + c[:, :259] -= 128 + expected = 259 * 255**2 + prepared = _prepare_centroids(c, dtype=dtype) + for output_dtype in (torch.float32, torch.int64, torch.float32, torch.int64): + output = torch.full((3,), -123, dtype=output_dtype, device='cuda') + distance, labels = _assign_rows(rows, prepared, output[1:-1]) + self.assertEqual(distance.data_ptr(), output[1:-1].data_ptr()) + self.assertEqual(distance.item(), torch.tensor(expected, dtype=output_dtype).item()) + self.assertEqual((labels.item(), output[[0, -1]].tolist()), (0, [-123, -123])) + saved = distance.clone() + normal, _ = _assign_rows(rows, prepared) + self.assertEqual(normal.dtype, torch.float32) + torch.testing.assert_close(distance, saved, rtol=0, atol=0) + prepared = _prepare_centroids(torch.zeros((1, 2), device='cuda')) + output = torch.full((1,), -123, dtype=torch.int64, device='cuda') + with self.assertRaisesRegex(ValueError, 'INT64 distances require integer operands'): + _assign_rows(torch.zeros((1, 2), dtype=torch.bfloat16, device='cuda'), prepared, output) + self.assertEqual(output.item(), -123) + + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_captured_binding_survives_eviction_and_retires(self): + rows = (torch.arange(10247, device='cuda') % 2).bfloat16() + rows = rows[:, None].expand(-1, 16).contiguous() + initial = torch.tensor([0., 1.], device='cuda')[:, None].expand(-1, 16).contiguous() + capture_step = Emeans._capture_step + end_epoch = Emeans.end_epoch + + for fail_after_tail in (False, True): + with self.subTest(exception=fail_after_tail): + owners = [] + captured_keys = [] + graph_owner = None + prepared_owner = None + + def capture( + model, + *args, + _capture_step=capture_step, + _owners=owners, + **kwargs, + ): + nonlocal graph_owner, prepared_owner + captured = _capture_step(model, *args, **kwargs) + prepared_owner = weakref.ref(captured[1]) + captured_keys.extend( # noqa: B023 + key for key in captured[1].bindings + if (key[0] if isinstance(key, tuple) else key) == model.recipe['batch_size']) + _owners.extend( + weakref.ref(binding) + for binding in captured[1].bindings.values() + ) + graph_owner = weakref.ref(captured[0]) + return captured + + def finish_epoch( + model, + _end_epoch=end_epoch, + _fail_after_tail=fail_after_tail, + _owners=owners, + ): + _end_epoch(model) + self.assertEqual(model.recipe['epoch_rows'], [len(rows), 17, len(rows)]) + gc.collect() + self.assertTrue(_owners) + self.assertTrue(all(owner() is not None for owner in _owners)) + self.assertIs(model._execution_backend.cache, prepared_owner()) # noqa: B023 + if model._epoch == 2: + # The 17-row middle pass evicts the captured full-batch + # binding, but graph owners keep it alive for the final full pass. + self.assertTrue(captured_keys) # noqa: B023 + for key in captured_keys: # noqa: B023 + self.assertNotIn(key, prepared_owner().bindings) # noqa: B023 + if _fail_after_tail and model._epoch == len(model.recipe['epoch_rows']): + raise RuntimeError('injected post-tail failure') + + model = Emeans( + 16, + 2, + nepochs=2 + 17 / len(rows), + seed=10, + assignment_backend='cute', + capture_assignments=True, + closing_handover=False, # No second-label re-capture in the closing pass. + ) + from faiss.contrib.e_means import cute + + # Two bindings per prepared state force the eviction this test covers. + with mock.patch.object( + Emeans, '_capture_step', capture + ), mock.patch.object( + Emeans, 'end_epoch', finish_epoch + ), mock.patch.object(cute, '_MAX_BINDINGS', 2): + gc.collect() + if fail_after_tail: + with self.assertRaisesRegex(RuntimeError, 'injected post-tail failure'): + model.train(rows, initial) + self.assertIsNone(model.assignments) + else: + model.train(rows, initial) + torch.testing.assert_close(model.centroids, initial, rtol=0, atol=0) + torch.testing.assert_close(model.obj, torch.zeros_like(model.obj), rtol=0, atol=0) + torch.testing.assert_close(model.assignments, rows[:, 0].long(), rtol=0, atol=0) + distances, labels = model.assign(rows) + torch.testing.assert_close(distances, torch.zeros_like(distances), rtol=0, atol=0) + torch.testing.assert_close(labels, rows[:, 0].long(), rtol=0, atol=0) + gc.collect() + self.assertIsNotNone(graph_owner) + self.assertIsNone(graph_owner()) + del model + gc.collect() + self.assertTrue(all(owner() is None for owner in owners)) + self.assertIsNone(prepared_owner()) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_and_jit_training(self): + x = torch.tensor([[0.], [2.], [10.], [12.]], device='cuda') + initial = x[[0, 2]] + native = Emeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + assignment_backend='cute', + capture_assignments=True, + ) + jit = QuantizedEmeans( + 1, + 2, + nepochs=1, + batch_size=4, + alpha0=0.5, + assignment_backend='cute', + quantizer=CastQuantizer(1, torch.bfloat16), + capture_assignments=True, + ) + native.train(x.bfloat16(), initial) + jit.train(x, initial) + for model in (native, jit): + torch.testing.assert_close(model.centroids, torch.tensor([[1.], [11.]], device='cuda')) + self.assertEqual(model.obj.item(), 8.) + torch.testing.assert_close(model.assignments, torch.tensor([0, 0, 1, 1], device='cuda'), rtol=0, atol=0) + distance, labels = native.assign(x.bfloat16()) + torch.testing.assert_close(distance, torch.ones(4, device='cuda')) + torch.testing.assert_close(labels, torch.tensor([0, 0, 1, 1], device='cuda')) + for query in (x, x.bfloat16()): + cast_distance, cast_labels = jit.assign(query) + self.assertEqual(jit.assignment_recipe['representation'], 'bfloat16') + torch.testing.assert_close(cast_distance, distance, rtol=0, atol=0) + torch.testing.assert_close(cast_labels, labels, rtol=0, atol=0) + with self.assertRaises(ValueError): + QuantizedEmeans(1, 2, quantizer=None, assignment_backend='cute').train(x, initial) + + def test_optional_stack_and_device_scope(self): + # CUDA initialization may probe optional packages: do it before the + # missing-package blocker. Native use must still avoid CuTe imports. + code = """ +import importlib.abc, pathlib, sys, torch +import faiss.contrib +faiss.contrib.__path__.insert(0, str(pathlib.Path(sys.argv[1]).resolve().parents[1])) +from faiss.contrib.e_means.e_means_torch import Emeans +assert pathlib.Path(sys.modules[Emeans.__module__].__file__).resolve() == pathlib.Path(sys.argv[1]).resolve() +cuda = torch.cuda.is_available() and not torch.version.hip +if cuda: torch.cuda.get_device_capability() +class NoCute(importlib.abc.MetaPathFinder): + def find_spec(self, name, path=None, target=None): + if name.split('.')[0] in ('quack', 'cutlass'): raise ImportError('blocked optional CuTe') +sys.meta_path.insert(0, NoCute()) +Emeans(1, 1, nepochs=1, batch_size=2, alpha0=.5).train(torch.zeros(2, 1)) +assert not any(n.split('.')[0] in ('quack', 'cutlass') for n in sys.modules) +if cuda: + try: + Emeans(1, 1, assignment_backend='cute').train( + torch.zeros(2, 1, dtype=torch.bfloat16, device='cuda')) + except RuntimeError as error: assert 'CuTe assignment requires' in str(error) + else: raise AssertionError('missing optional stack silently accepted') +""" + child = subprocess.run([sys.executable, '-c', code, str(e_means.__file__)], + text=True, capture_output=True, timeout=60) + self.assertEqual(child.returncode, 0, child.stderr) + from faiss.contrib.e_means import cute as backend + from faiss.contrib.e_means import e_means_grouping as grouping + with mock.patch.object(backend, '_stack_status', return_value=(True, 'ready')), \ + mock.patch.object(grouping, '_grouping_provider', + side_effect=ImportError('broken CCCL')) as provider: + backend._require_stack() + backend._require_stack() + provider.assert_not_called() + + model = Emeans(16, 65536, assignment_backend='auto') + rows = SimpleNamespace(device=torch.device('cuda', 17), dtype=torch.bfloat16) + with mock.patch.object(torch.version, 'hip', None), \ + mock.patch.object(backend, '_stack_status', return_value=(True, 'ready')), \ + mock.patch.object(torch.cuda, 'device', return_value=nullcontext()), \ + mock.patch.object(torch.cuda, 'get_device_capability', return_value=(9, 0)), \ + mock.patch.object(torch.cuda, 'get_device_properties', + return_value=mock.Mock(shared_memory_per_block_optin=232448)), \ + mock.patch.object(torch_backend, '_get_triton_assign_rows', return_value=object()), \ + mock.patch.object(grouping, '_grouping_provider', + side_effect=ImportError('broken CCCL')) as provider: + model._resolve_assignment_backend(rows) + self.assertEqual(model._resolved_assignment_backend, 'cute') + provider.assert_not_called() + try: + for major in ('12.9', '14.0'): + backend._stack_status.cache_clear() + with mock.patch.object( + importlib.metadata, + 'version', + side_effect=lambda name, _major=major: ( + _major + if name == 'cuda-python' + else { + 'quack-kernels': '0.6.5', + 'nvidia-cutlass-dsl': '4.7.1', + }[name] + ), + ): + self.assertEqual(backend._stack_status(), (False, 'cuda-python requires major version 13')) + finally: + backend._stack_status.cache_clear() + # Narrow adapter guard diagnostics use an unchecked fictitious device; + # cache clearing prevents prior successful device checks hiding errors. + try: + for capability in ((8, 0), (10, 0), (10, 3)): + backend._check_cuda_device.cache_clear() + with mock.patch.object(torch.cuda, 'device', return_value=nullcontext()), \ + mock.patch.object(torch.version, 'hip', None), \ + mock.patch.object(backend, '_require_stack'), \ + mock.patch.object(torch.cuda, 'get_device_capability', return_value=capability), \ + self.assertRaisesRegex(RuntimeError, 'exactly SM90'): + backend._check_device('cuda:17') + backend._check_cuda_device.cache_clear() + with mock.patch.object(torch.cuda, 'device', return_value=nullcontext()), \ + mock.patch.object(torch.version, 'hip', None), \ + mock.patch.object(backend, '_require_stack'), \ + mock.patch.object(torch.cuda, 'get_device_capability', return_value=(9, 0)), \ + mock.patch.object(torch.cuda, 'get_device_properties', return_value=mock.Mock(shared_memory_per_block_optin=0)), \ + self.assertRaisesRegex(RuntimeError, 'opt-in shared memory'): + backend._check_device('cuda:17') + finally: + backend._check_cuda_device.cache_clear() + with mock.patch.object(torch.version, 'hip', 'rejection-only probe'), \ + self.assertRaisesRegex(RuntimeError, 'NVIDIA CUDA SM90'): + backend._check_device('cuda:17') + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_non_grouped_cute_ignores_broken_cccl(self): + from faiss.contrib.e_means import e_means_grouping as grouping + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + rows = torch.zeros((3, 16), dtype=torch.bfloat16, device='cuda') + # An irregular K uses tiled assignment; grouped requires K % 128 == 0. + centers = torch.zeros((129, 16), device='cuda') + broken = ImportError('broken installed CCCL') + with mock.patch.object(grouping, '_grouping_provider', side_effect=broken) as provider: + prepared = _prepare_centroids(centers, dtype=torch.bfloat16) + distances, labels = _assign_rows(rows, prepared) + provider.assert_not_called() + self.assertNotEqual(prepared.bindings[len(rows)].launcher.__name__, 'launch_grouped') + torch.testing.assert_close(distances, torch.zeros_like(distances), rtol=0, atol=0) + torch.testing.assert_close(labels, torch.zeros_like(labels), rtol=0, atol=0) + + @unittest.skipUnless(_ready(), 'pinned CuTe stack on SM90 required') + def test_bf16_destinations_ragged_ties_and_owned_outputs(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + for dtype in (torch.bfloat16, torch.float8_e4m3fn): + for n, k, d in ((1, 128, 1), (3, 256, 17), (33, 512, 96), (129, 384, 65), (7, 193, 257)) + (((17, 384, 385), (3, 384, 513)) if dtype is torch.float8_e4m3fn else ()): + with self.subTest(dtype=dtype, n=n, k=k, d=d): + g = torch.Generator(device='cuda').manual_seed(n+k+d) + rows = torch.randint(-2, 3, (n, d), generator=g, device='cuda').to(dtype) + c = torch.randint(-2, 3, (k, d), generator=g, device='cuda').float() + c[1].copy_(c[0]) + if (k, d) == (384, 65): + c[-1].fill_(3) + rows[-1].fill_(3) + before_rows, before_centroids = rows.clone(), c.clone() + prepared = _prepare_centroids(c, dtype=dtype) + distances = torch.full((n+2,), -123., device='cuda') + labels = torch.full((n+2,), -123, dtype=torch.int64, device='cuda') + result = _assign_rows(rows, prepared, distances[1:-1], labels[1:-1]) + self.assertEqual(tuple(t.data_ptr() for t in result), + (distances[1:-1].data_ptr(), labels[1:-1].data_ptr())) + truth = (rows.double()[:, None]-c.to(dtype).double()[None]).square().sum(2) + torch.testing.assert_close(distances[1:-1].double(), truth.min(1).values, rtol=0, atol=2e-4 if dtype is torch.bfloat16 else 0) + torch.testing.assert_close(labels[1:-1], truth.argmin(1), rtol=0, atol=0) + if (k, d) == (384, 65): + self.assertEqual(labels[-2].item(), k-1) + self.assertEqual((distances[[0, -1]].tolist(), labels[[0, -1]].tolist()), ([-123., -123.], [-123, -123])) + caller_saved = distances.clone(), labels.clone() + owned = _assign_rows(rows, prepared) + saved = tuple(t.clone() for t in owned) + _assign_rows((-rows.float()).to(dtype), prepared) + _assign_rows(rows[:1], prepared) + for actual, expected in zip(owned, saved): + torch.testing.assert_close( + actual, expected, rtol=0, atol=0 + ) + model = known_torch_centroids( + c, + model_class=( + Emeans + if dtype == torch.bfloat16 + else QuantizedEmeans + ), + assignment_backend='cute', + assignment_chunk_size=max(1, n - 1), + ) + public = model.assign(rows) + torch.testing.assert_close(public[0].double(), truth.min(1).values, rtol=0, atol=2e-4 if dtype is torch.bfloat16 else 0) + torch.testing.assert_close(public[1], truth.argmin(1), rtol=0, atol=0) + for actual, expected in zip((distances, labels), caller_saved): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + torch.testing.assert_close(rows.view(torch.uint8), before_rows.view(torch.uint8), rtol=0, atol=0) + torch.testing.assert_close(c, before_centroids, rtol=0, atol=0) + c = torch.full((193, 17), 10., device='cuda') + c[0].zero_() + c[127].zero_() + c[5].fill_(3) + c[192].fill_(-3) + c[10].zero_() + c[11].zero_() + c[10, 0] = .99609375 + c[11, 0] = 1.00390625 + rows = torch.stack((c[5], c[192], torch.nn.functional.pad(torch.ones(1, device='cuda'), (0, 16)), torch.zeros(17, device='cuda'))) + before_rows, before_centroids = rows.clone(), c.clone() + model = known_torch_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend='cute', + quantizer=CastQuantizer(17, torch.bfloat16), + ) + distance, labels = model.assign(rows) + self.assertEqual(labels[:2].tolist(), [5, 192]) + self.assertIn(labels[2].item(), (10, 11)) + self.assertEqual(labels[3].item(), 0) + truth = (rows.bfloat16().double()[:, None]-c.bfloat16().double()[None]).square().sum(2) + torch.testing.assert_close(distance.double(), truth.gather(1, labels[:, None]).flatten(), rtol=0, atol=1e-5) + torch.testing.assert_close(rows, before_rows, rtol=0, atol=0) + torch.testing.assert_close(c, before_centroids, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_bf16_norm_refresh_and_subnormal_square(self): + from faiss.contrib.e_means.cute import _prepare_centroids + + rows = torch.tensor([[-.4678138, .03789843, -.6960376]], device='cuda') + c = torch.tensor([[-.8843690, 1.0697185, -.7981653], [.4984003, .5734861, -.5365824]], device='cuda') + truth = (rows.bfloat16().float()[:, None]-c.bfloat16().float()[None]).square().sum(2) + wrong = c.square().sum(1)-2*(rows.bfloat16().float()[:, None]*c.bfloat16().float()[None]).sum(2) + self.assertEqual((truth.argmin(1).item(), wrong.argmin(1).item()), (0, 1)) + for q in (None, CastQuantizer(3, torch.bfloat16)): + model = known_torch_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend='cute', + quantizer=q, + ) + distance, labels = model.assign(rows if q else rows.bfloat16()) + self.assertEqual(labels.item(), 0) + torch.testing.assert_close(distance, truth[:, 0], rtol=0, atol=1e-6) + prepared = None + for changed in (c, c*.5+.25): + prepared = _prepare_centroids(changed, prepared) + torch.testing.assert_close(prepared.norms, changed.bfloat16().float().square().sum(1), rtol=0, atol=0) + # Both states are exactly halfway between BF16 values; RN-even gives + # 1 before mutation and 2 after mutation, hence exact norms 1 and 4. + halfway = torch.tensor([[1.+2.**-8]], device='cuda') + prepared = _prepare_centroids(halfway) + torch.testing.assert_close(prepared.norms, torch.tensor([1.], device='cuda'), rtol=0, atol=0) + halfway.mul_(2) + prepared = _prepare_centroids(halfway, prepared) + torch.testing.assert_close(prepared.norms, torch.tensor([4.], device='cuda'), rtol=0, atol=0) + with torch.inference_mode(): + model = known_torch_centroids(torch.tensor([[0.], [2.]], device='cuda'), assignment_backend='cute') + distance, labels = model.assign(torch.tensor([[2.]], device='cuda', dtype=torch.bfloat16)) + self.assertEqual((distance.item(), labels.item()), (0., 1)) + model.centroids[0].fill_(2) + model.centroids[1].zero_() + distance, labels = model.assign(torch.tensor([[2.]], device='cuda', dtype=torch.bfloat16)) + self.assertEqual((distance.item(), labels.item()), (0., 0)) + tiny = torch.full((1, 1), 2.**-70, device='cuda') + prepared = _prepare_centroids(tiny) + torch.testing.assert_close(prepared.norms, torch.tensor([2.**-140], device='cuda'), rtol=0, atol=0) + distance, _ = known_torch_centroids(tiny, assignment_backend='cute').assign(torch.zeros(1, 1, dtype=torch.bfloat16, device='cuda')) + torch.testing.assert_close(distance, torch.tensor([2.**-140], device='cuda'), rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_bf16_high_ids_and_planted_large_batch(self): + for dtype in (torch.bfloat16, torch.float8_e4m3fn): + with self.subTest(dtype=dtype): + from faiss.contrib.e_means.cute import ( + _prepare_centroids, + _assign_rows, + ) + + start = time.monotonic() + torch.cuda.reset_peak_memory_stats() + c = torch.full((16384, 96), 4., device='cuda') + c[0].zero_() + c[128].zero_() + c[777].fill_(1) + c[1024].fill_(1) + c[-1].fill_(-1) + rows = torch.zeros(8192, 96, dtype=dtype, device='cuda') + rows[1].fill_(1) + rows[2].fill_(-1) + rows[3].fill_(0.25) + distance, labels = known_torch_centroids( + c, + model_class=( + Emeans + if dtype == torch.bfloat16 + else QuantizedEmeans + ), + assignment_backend='cute', + assignment_chunk_size=8192, + ).assign(rows) + self.assertEqual(labels[:4].tolist(), [0, 777, 16383, 0]) + torch.testing.assert_close(distance[:4], torch.tensor([0., 0., 0., 6.], device='cuda'), rtol=0, atol=1e-5) + self.assertTrue(bool((labels[4:] == 0).all())) + torch.testing.assert_close(distance[4:], torch.zeros_like(distance[4:]), rtol=0, atol=1e-5) + c = torch.zeros(65537, 1, device='cuda') + c[-1].fill_(2) + labels = torch.full((4,), -123, dtype=torch.int64, device='cuda') + distance, _ = _assign_rows(torch.full((2, 1), 2., dtype=dtype, device='cuda'), + _prepare_centroids(c, dtype=dtype), labels_out=labels[1:-1]) + self.assertEqual(labels.tolist(), [-123, 65536, 65536, -123]) + torch.testing.assert_close(distance, torch.zeros_like(distance), rtol=0, atol=0) + print('CuTe correctness stress cost', dtype, time.monotonic()-start, + 'seconds, peak', torch.cuda.max_memory_allocated(), 'bytes') + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_bf16_decoded_tail_statistics_closing_and_sync(self): + x = torch.tensor([[0., 0.], [.25, .5], [2., 2.], [2.25, 2.5], [4., 4.], [4.25, 4.5], [4.5, 4.75]], device='cuda') + initial = x[[0, 2, 4]].clone() + for q in (None, CastQuantizer(2, torch.bfloat16)): + rows = x if q else x.bfloat16() + before = rows.clone() + args = dict(nepochs=2, batch_size=3, alpha0=.5, seed=7, + assignment_backend='cute', assignment_chunk_size=1, capture_assignments=True) + model_class = Emeans if q is None else QuantizedEmeans + if q is not None: + args['quantizer'] = q + matrix, caller = model_class(2, 3, **args), model_class(2, 3, **args) + matrix.train(rows, initial) + caller.begin(len(rows), initial) + for epoch in range(2): + order = torch.randperm( + len(rows), + generator=e_means._torch_generator( + rows.device, e_means._epoch_seed(7, epoch) + ), + device=rows.device, + ) + for begin in range(0, len(rows), 3): + batch = rows[order[begin:begin+3]] + represented = batch.bfloat16().float() + snapshot = caller.current_centroids().clone() + operands = snapshot.bfloat16().float() + truth = (represented[:, None]-operands[None]).square().sum(2) + labels = truth.argmin(1) + partial = caller.accumulate(batch[:1]) + if len(batch) > 1: + self.assertIsNone(partial['sums']) + self.assertIsNone(partial['counts']) + torch.testing.assert_close(caller.current_centroids(), snapshot, rtol=0, atol=0) + stats = caller.accumulate(batch[1:]) + else: + stats = partial + if epoch == caller.nepochs - 1: + torch.testing.assert_close(stats['labels'], labels[-len(stats['labels']):], rtol=0, atol=0) + else: + self.assertNotIn('labels', stats) + empty = caller.accumulate(batch[:0]) + torch.testing.assert_close(empty['sums'], stats['sums'], rtol=0, atol=0) + torch.testing.assert_close(empty['counts'], stats['counts'], rtol=0, atol=0) + sums = torch.zeros_like(stats['sums']) + sums.index_add_(0, labels, represented) + # At most three small quarter-valued addends: bounded exact + # FP32 sums are independent of the atomic addition order. + torch.testing.assert_close(stats['sums'], sums, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], torch.bincount(labels, minlength=3).float(), rtol=0, atol=0) + torch.testing.assert_close(stats['objective'], truth.min(1).values.double().sum(), rtol=1e-6, atol=3e-5) + caller.update(stats) + caller.end_epoch() + counts, sums, state = caller._pass_counts, caller._pass_sums, caller._centroids + closing = torch.where(counts[:, None] > 0, sums/counts.clamp_min(1).float()[:, None], state) + torch.testing.assert_close(caller.finalize(), closing, rtol=0, atol=0) + torch.testing.assert_close(caller.centroids, matrix.centroids, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(caller.obj, matrix.obj, rtol=1e-6, atol=3e-5) + torch.testing.assert_close(rows, before, rtol=0, atol=0) + saved = caller.centroids.clone() + output = caller.centroids + del caller + torch.testing.assert_close(output, saved, rtol=0, atol=0) + warm = QuantizedEmeans( + 2, + 3, + nepochs=1, + batch_size=3, + alpha0=0.5, + quantizer=q, + assignment_backend='cute', + assignment_chunk_size=1, + ) + warm.begin(3, initial) + warm.update(warm.accumulate(rows[:3])) + warm = QuantizedEmeans( + 2, + 3, + nepochs=1, + batch_size=3, + alpha0=0.5, + quantizer=q, + assignment_backend='cute', + assignment_chunk_size=1, + ) + warm.begin(3, initial) + torch.cuda.synchronize() + previous = torch.cuda.get_sync_debug_mode() + try: + torch.cuda.set_sync_debug_mode('error') + warm.update(warm.accumulate(rows[:3])) + finally: + torch.cuda.set_sync_debug_mode(previous) + warm.end_epoch() + warm.finalize() + x = torch.zeros(10, 17, device='cuda') + x[:, 0] = torch.tensor( + [0.0, 1.0, 2.0, 3.0, 4.0, 10.0, 11.0, 12.0, 13.0, 14.0], + device="cuda", + ) + c = torch.zeros(3, 17, device='cuda') + c[:, 0] = torch.tensor([0.0, 10.0, 100.0], device="cuda") + model = QuantizedEmeans( + 17, + 3, + nepochs=2, + batch_size=2, + alpha0=0.5, + quantizer=CastQuantizer(17, torch.bfloat16), + assignment_backend='cute', + ) + finalize = model.finalize + retained = {} + + def close(): + counts, sums, state = model._pass_counts, model._pass_sums, model._centroids + retained['closing'] = torch.where(counts[:, None] > 0, sums/counts.clamp_min(1).float()[:, None], state) + return finalize() + + with mock.patch.object(model, 'finalize', close): + model.train(x, c) + self.assertGreater(model.n_splits, 0) + torch.testing.assert_close(model.centroids, retained['closing'], rtol=0, atol=0) + self.assertGreater(abs(model.obj[-1].item()-model.assign(x)[0].double().sum().item()), .001) + model.centroids[0].fill_(100) + model.centroids[1].zero_() + self.assertEqual(model.assign(x[:1])[1].item(), 1) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_bf16_ordered_refresh_and_noncurrent_device(self): + for dtype, offset in ((torch.bfloat16, 0), (torch.float8_e4m3fn, 0), + (torch.int8, 0), (torch.uint8, 128)): + for k in ((2, 128) if dtype in (torch.int8, torch.uint8) else (2,)): + with self.subTest(dtype=dtype, k=k): + from faiss.contrib.e_means.cute import ( + _prepare_centroids, + _assign_rows, + ) + + current = torch.cuda.current_device() + device = torch.device('cuda', (current+1) % torch.cuda.device_count()) + c = torch.full((k, 17), 100.+offset, device=device) + c[0].fill_(offset) + c[1].fill_(1+offset) + rows = torch.full((257, 17), offset, dtype=dtype, device=device) + model_class = ( + Emeans + if dtype == torch.bfloat16 + else QuantizedEmeans + ) + model = known_torch_centroids( + c, model_class=model_class, assignment_backend='cute' + ) + first = model.assign(rows) + saved = tuple(t.clone() for t in first) + torch.cuda.synchronize(device) + producer, side = torch.cuda.Stream(device=device), torch.cuda.Stream(device=device) + with torch.cuda.stream(producer): + torch.cuda._sleep(50_000_000) + rows.fill_(1+offset) + side.wait_stream(producer) + with torch.cuda.stream(side): + one = model.assign(rows) + model.centroids[0].fill_(1+offset) + model.centroids[1].fill_(offset) + changed = model.assign(rows) + model.assign(rows[:3]) + model.assign(rows[:2]) + torch.cuda.current_stream(device).wait_stream(side) + for actual, expected in zip(first, saved): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for pair, label in ((one, 1), (changed, 0)): + self.assertEqual((pair[0].device, pair[1].device), (device, device)) + torch.testing.assert_close(pair[0], torch.zeros_like(pair[0]), rtol=0, atol=0) + self.assertTrue(bool((pair[1] == label).all())) + self.assertEqual(torch.cuda.current_device(), current) + if torch.cuda.device_count() >= 2: + with self.assertRaisesRegex(ValueError, 'same device'): + model.assign(rows.to(torch.device('cuda', current))) + prepared = _prepare_centroids(model.centroids, dtype=dtype) + with self.assertRaisesRegex(ValueError, 'contiguous CUDA BF16'): + _assign_rows(rows.float(), prepared) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_recalibration_after_training_matches_fresh_assignment(self): + x = torch.linspace(-1, 1, 32, device='cuda')[:, None].expand(32, 128).contiguous() + initial = x[[4, 12, 20, 28]].clone() + q = Fp8Quantizer(128) + q.train(x) + model = QuantizedEmeans( + 128, 4, nepochs=2, quantizer=q, assignment_backend='cute' + ) + model.train(q.compute_codes(x), initial) + retained = model.assign(q.compute_codes(x[:9])) + saved = tuple(value.clone() for value in retained) + for offset in (0.0625, 0.125, 0.25): + q.train(x + offset) + rows = q.compute_codes(x[:9]) + actual = model.assign(rows) + fresh = known_torch_centroids( + model.centroids.clone(), + model_class=QuantizedEmeans, + quantizer=q, + assignment_backend='cute', + ) + expected = fresh.assign(rows) + for observed, reference in zip(actual, expected): + torch.testing.assert_close(observed, reference, rtol=0, atol=0) + for observed, reference in zip(retained, saved): + torch.testing.assert_close(observed, reference, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_native_and_jit_share_decoded_state_and_output_units(self): + x = torch.tensor([[0.], [2.], [10.], [12.]], device='cuda') + q = Fp8Quantizer(1) + q.train(x) + models = [QuantizedEmeans(1, 2, nepochs=1, batch_size=4, alpha0=.5, + quantizer=q, assignment_backend='cute') for _ in range(2)] + for model,rows in zip(models, (q.compute_codes(x),x)): + model.train(rows, x[[0,2]]) + torch.testing.assert_close(model.centroids,x.new_tensor([[1.],[11.]])) + self.assertEqual(model.obj.item(),8.) + distance,labels = model.assign(rows) + torch.testing.assert_close(distance,torch.ones(4,device=x.device)) + torch.testing.assert_close(labels,torch.tensor([0,0,1,1],device=x.device)) + original_distance, original_labels = model.assign(x) + self.assertEqual(model.assignment_recipe['representation'], 'float8_e4m3fn') + torch.testing.assert_close(original_distance, distance, rtol=0, atol=0) + torch.testing.assert_close(original_labels, labels, rtol=0, atol=0) + low, high = torch.full((5, 65), .1, device='cuda'), torch.full((5, 65), 2.3, device='cuda') + x = torch.cat((low, high)) + q = Fp8Quantizer(65) + q.train(x) + self.assertTrue(q.centered) + represented = q.decode(q.compute_codes(x)) + for rows in (q.compute_codes(x), x): + model = QuantizedEmeans( + 65, + 2, + nepochs=1, + batch_size=10, + alpha0=1.0, + quantizer=q, + assignment_backend='cute', + ) + model.train(rows, torch.stack((low[0], high[0]))) + torch.testing.assert_close(model.centroids, torch.stack((represented[:5].mean(0), represented[5:].mean(0)))) + distance, labels = model.assign(rows) + self.assertEqual((model.centroids.dtype, distance.dtype, labels.dtype), (torch.float32, torch.float32, torch.int64)) + self.assertEqual(labels.tolist(), [0]*5+[1]*5) + torch.testing.assert_close(distance, torch.zeros_like(distance)) + query = low[:1].clone() + query[0, 0] += .125 + distance, labels = model.assign(query) + self.assertEqual(model.assignment_recipe['representation'], 'float8_e4m3fn') + self.assertEqual(labels.item(), 0) + torch.testing.assert_close(distance, torch.tensor([.015625], device='cuda')) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_workspace_bytes_match_public_encoding_before_reuse(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + midpoint = torch.tensor([2**-10, 3*2**-10, 15*2**-10, 17*2**-10, + 1.0625, 31., 62., 432.], device='cuda') + positive = torch.cat((midpoint, + torch.nextafter(midpoint, torch.zeros_like(midpoint)), + torch.nextafter(midpoint, torch.full_like(midpoint, float('inf'))), + midpoint.new_tensor([0., 448.]))) + target = torch.cat((positive, -positive))[:, None].expand(-1, 65) + plain = torch.tensor([-128., 128.], device='cuda')[:, None].expand(-1, 65).repeat(1024, 1) + centered = torch.tensor([.1, 2.3], device='cuda')[:, None].expand(-1, 65) + for sample, center in ((plain, False), (centered, True)): + with self.subTest(centered=center): + q = Fp8Quantizer(65) + q.train(sample) + self.assertEqual(q.centered, center) + rows = target / q.scale + if q.shift is not None: + rows = rows + q.shift + rows = rows.contiguous() + codes = q.compute_codes(rows) + before = codes.view(torch.uint8).clone() + prepared = _prepare_centroids(rows[[4, len(positive)+4]].clone(), transform=q, dtype=q.dtype) + distance, labels = _assign_rows(rows, prepared) + saved = distance.clone(), labels.clone() + # Consume these actual codes BEFORE the next equal-size call + # can overwrite the shared assignment workspace. + encoded = prepared.bindings[len(rows)].workspace.view(torch.uint8).clone() + torch.testing.assert_close(encoded, before, rtol=0, atol=0) + matching = _assign_rows(codes, prepared) + for actual, expected in zip(matching, saved): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + torch.testing.assert_close(codes.view(torch.uint8), before, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_seeded_chunks_selected_distance_and_explicit_validation(self): + g = torch.Generator(device='cuda').manual_seed(31) + x = torch.randn(256, 128, generator=g, device='cuda').mul_(.25) + initial = torch.randn(512, 128, generator=g, device='cuda').mul_(.25) + q = Fp8Quantizer(128) + q.train(x) + codes = q.compute_codes(x) + before = codes.view(torch.uint8).clone() + represented, operands = q.decode(codes).double(), q.decode(q.compute_codes(initial)).double() + for chunk in (len(x), 64): + model = known_torch_centroids( + initial, + model_class=QuantizedEmeans, + quantizer=q, + assignment_backend='cute', + assignment_chunk_size=chunk, + ) + for rows in (x, codes): + with self.subTest(chunk=chunk, native=rows is codes): + distance, labels = model.assign(rows) + self.assertEqual((distance.shape, labels.shape), ((len(x),), (len(x),))) + self.assertTrue(bool(((labels >= 0) & (labels < len(initial))).all())) + selected = (represented - operands[labels]).square().sum(1) + torch.testing.assert_close(distance.double(), selected, rtol=2e-6, atol=1e-3) + saved = tuple(value.clone() for value in (distance, labels)) + model.assign(rows[:3]) + for observed, reference in zip((distance, labels), saved): + torch.testing.assert_close(observed, reference, rtol=0, atol=0) + torch.testing.assert_close(codes.view(torch.uint8), before, rtol=0, atol=0) + for position, value in ((0, 1000.), (3, 1000.), (5, 1000.), + (2, float('nan')), (4, float('inf')), (1, float('-inf'))): + query = torch.zeros(6, 128, device='cuda') + query[position, 0] = value + with self.subTest(position=position, value=value), self.assertRaisesRegex(ValueError, 'representable range'): + q.validate(query) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_decoded_caller_tail_revival_and_closing(self): + x = torch.tensor( + [ + [0.0, 0.0], + [0.25, 0.5], + [2.0, 2.0], + [2.25, 2.5], + [4.0, 4.0], + [4.25, 4.5], + [4.5, 4.75], + ], + device="cuda", + ) + initial = torch.tensor([[0., 0.], [2., 2.], [100., 100.]], device='cuda') + q = Fp8Quantizer(2) + q.train( + torch.tensor( + [[-128.0, -128.0], [128.0, 128.0]], device="cuda" + ).repeat(1024, 1) + ) + self.assertFalse(q.centered) + codes = q.compute_codes(x) + before = codes.view(torch.uint8).clone() + self.assertTrue(bool((codes.float().abs().sum(0)*512 < 2**24).all())) + for incoming in (codes, x): + with self.subTest(native=incoming is codes): + args = dict(nepochs=2, batch_size=3, alpha0=.5, seed=7, quantizer=q, + assignment_backend='cute', assignment_chunk_size=2, capture_assignments=True, + unused_threshold=0.1) + matrix, caller = QuantizedEmeans( + 2, 3, **args + ), QuantizedEmeans(2, 3, **args) + matrix.train(incoming, initial) + caller.begin(len(x), initial) + for epoch in range(2): + order = torch.randperm( + len(x), + generator=e_means._torch_generator( + x.device, e_means._epoch_seed(7, epoch) + ), + device=x.device, + ) + for start in range(0, len(x), 3): + ids = order[start:start+3] + represented = q.decode(codes.float()[ids]) + snapshot = caller.current_centroids().clone() + operands = q.decode(q.compute_codes(snapshot)) + truth = (represented[:, None]-operands[None]).square().sum(2) + labels = truth.argmin(1) + partial = caller.accumulate(incoming[ids[:1]]) + if len(ids) > 1: + self.assertIsNone(partial['sums']) + self.assertIsNone(partial['counts']) + torch.testing.assert_close(caller.current_centroids(), snapshot, rtol=0, atol=0) + stats = caller.accumulate(incoming[ids[1:]]) + else: + stats = partial + if epoch == caller.nepochs - 1: + torch.testing.assert_close(stats['labels'], labels[-len(stats['labels']):], rtol=0, atol=0) + else: + self.assertNotIn('labels', stats) + empty = caller.accumulate(incoming[ids[:0]]) + torch.testing.assert_close(empty['sums'], stats['sums'], rtol=0, atol=0) + torch.testing.assert_close(empty['counts'], stats['counts'], rtol=0, atol=0) + sums = torch.zeros_like(stats['sums']) + sums.index_add_(0, labels, represented) + # At most three bounded dyadic addends, uncentered + # normal decode: exact totals do not depend on order. + torch.testing.assert_close(stats['sums'], sums, rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], torch.bincount(labels, minlength=3).float(), rtol=0, atol=0) + torch.testing.assert_close(stats['objective'], truth.min(1).values.double().sum(), rtol=1e-6, atol=3e-5) + caller.update(stats) + caller.end_epoch() + counts, sums, state = ( + caller._pass_counts, + caller._pass_sums, + caller._centroids, + ) + closing = torch.where( + counts[:, None] > 0, + sums / counts.clamp_min(1).float()[:, None], + state, + ) + torch.testing.assert_close( + caller.finalize(), closing, rtol=0, atol=0 + ) + torch.testing.assert_close( + caller.centroids, matrix.centroids, rtol=1e-6, atol=1e-6 + ) + torch.testing.assert_close( + caller.obj, matrix.obj, rtol=1e-6, atol=3e-5 + ) + self.assertGreater(caller.n_splits, 0) + torch.testing.assert_close(codes.view(torch.uint8), before, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_fp8_seed_decode_and_independent_closing_distortion(self): + x = torch.tensor([[-1.625, -1.875], [-.375, .125], [.375, .625], [1.125, 1.375], + [1.625, 1.875], [.125, .375], [-.625, -.875], [.75, 1.25], [-1.25, -1.75]], device='cuda') + for centered, all_rows in ((False, False), (True, False), (True, True)): + rows = (x + 10 if centered else x)[:2 if all_rows else len(x)] + q = Fp8Quantizer(2) + q.train( + rows.cpu() + if centered + else torch.tensor([[-3.0, -3.0], [3.0, 3.0]]).repeat(2048, 1) + ) + q.to(rows.device) + self.assertEqual(q.centered, centered) + self.assertNotEqual(q.scale, 1.0) + codes = q.compute_codes(rows) + before = codes.view(torch.uint8).clone() + indices = ( + torch.arange(len(rows), device=rows.device) + if all_rows + else torch.randperm( + len(rows), + generator=e_means._torch_generator(rows.device, 7), + device=rows.device, + )[:2] + ) + initial = q.decode(codes.float()[indices]) + args = dict(nepochs=2, batch_size=3, alpha0=.5, seed=7, quantizer=q, + assignment_backend='cute', assignment_chunk_size=2) + native, jit, explicit = ( + QuantizedEmeans(2, 2, **args) for _ in range(3) + ) + for model, incoming in ((native, codes), (jit, rows)): + with mock.patch.object(model, 'begin', wraps=model.begin) as begin: + model.train(incoming) + torch.testing.assert_close(begin.call_args.args[1], initial, rtol=0, atol=0) + explicit.train(rows, initial) + for model in (native, explicit): + torch.testing.assert_close(model.centroids, jit.centroids, rtol=1e-6, atol=1e-6) + torch.testing.assert_close(model.obj, jit.obj, rtol=1e-6, atol=3e-5) + torch.testing.assert_close( + codes.view(torch.uint8), before, rtol=0, atol=0 + ) + d, k = 1024, 4 + g = torch.Generator(device='cuda').manual_seed(1821) + base = (torch.arange(d, device='cuda') % 31 + 128).float() + initial = torch.stack([base + 32*i for i in range(k)]).to(torch.float8_e4m3fn).float() + rows = (initial[torch.arange(128, device='cuda') % k] + torch.randint(-8, 9, (128, d), generator=g, device='cuda')).to(torch.float8_e4m3fn) + scores = [] + for backend in ('triton', 'cute'): + model = QuantizedEmeans( + d, k, nepochs=2, seed=1234, assignment_backend=backend + ) + model.train(rows, initial) + self.assertTrue(bool(torch.isfinite(model.centroids).all())) + # Returned closing centroids stay FP32: this fresh oracle does not + # call assign or compare the moving-pass training objective. + direct = (rows.double()[:, None] - model.centroids.double()[None]).square().sum(2) + scores.append(direct.min(1).values) + torch.testing.assert_close(scores[1], scores[0], rtol=1e-5, atol=1e-3) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_bytes_integer_oracles_destinations_and_refresh(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + for dtype, offset in ((torch.int8, 0), (torch.uint8, 128)): + for n, k, d in ((2, 3, 1), (5, 385, 79), (3, 257, 257), + (2, 384, 343), (2, 384, 344), (1, 2, 43919)): + with self.subTest(dtype=dtype, n=n, k=k, d=d): + g = torch.Generator(device='cuda').manual_seed(n+k+d) + signed = torch.randint(-128, 128, (n, d), generator=g, device='cuda') + c = torch.randint(-128, 128, (k, d), generator=g, device='cuda').float() + if d == 79: + signed[0].zero_() + signed[1].fill_(127) + c[0].zero_() + c[192].zero_() + c[-1].fill_(127) + elif d in (343, 344): + signed.fill_(127) + c.zero_() + c[0].fill_(-128) + c[1].fill_(127) + elif d == 43919: + signed.fill_(127) + c.fill_(-128) + rows = (signed+offset).to(dtype) + c.add_(offset) + before_rows, before_c = rows.clone(), c.clone() + model = known_torch_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend='cute', + ) + owned = model.assign(rows) + saved = tuple(t.clone() for t in owned) + truth = (rows.cpu().long()[:, None]-c.cpu().long()[None]).square().sum(2) + expected = (truth.min(1).values.float(), truth.argmin(1)) + for actual, wanted in zip(owned, expected): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + if d == 79: + self.assertEqual(owned[1][:2].tolist(), [0, k-1]) + elif d in (343, 344): + self.assertEqual(owned[1].tolist(), [1, 1]) + elif d == 43919: + self.assertEqual((truth[0, 0].item(), owned[1].item()), (2855832975, 0)) + distance = torch.full((n+2,), -123., device='cuda') + labels = torch.full((n+2,), -123, dtype=torch.int64, device='cuda') + prepared = _prepare_centroids(model.centroids, dtype=dtype) + out = _assign_rows(rows, prepared, + distance_out=distance[1:-1], labels_out=labels[1:-1]) + for actual, wanted in zip(out, expected): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + self.assertEqual((out[0].data_ptr(), out[1].data_ptr()), + (distance[1:-1].data_ptr(), labels[1:-1].data_ptr())) + self.assertEqual((distance[[0, -1]].tolist(), labels[[0, -1]].tolist()), + ([-123., -123.], [-123, -123])) + caller_before = (distance.clone(), labels.clone()) + changed_rows = rows.clone() + changed_rows[0].fill_(offset+1) + changed_truth = (changed_rows.cpu().long()[:, None]-c.cpu().long()[None]).square().sum(2) + for actual, wanted in zip( + _assign_rows(changed_rows, prepared), + ( + changed_truth.min(1).values.float(), + changed_truth.argmin(1), + ), + ): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + for actual, wanted in zip( + _assign_rows(rows[:1], prepared), + (expected[0][:1], expected[1][:1]), + ): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + backing = torch.empty(n, d*2, dtype=dtype, device='cuda') + backing[:, ::2].copy_(rows) + for actual, wanted in zip(model.assign(backing[:, ::2]), expected): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + for actual, wanted in zip(owned, saved): + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + torch.testing.assert_close(rows, before_rows, rtol=0, atol=0) + torch.testing.assert_close(c, before_c, rtol=0, atol=0) + if d == 79: + for _ in range(2): + model.centroids[0, 0] = float('nan') + with self.assertRaisesRegex(ValueError, 'finite'): + model.assign(rows) + model.centroids.copy_(before_c) + for actual, wanted in zip(model.assign(rows), expected): + torch.testing.assert_close(actual.cpu(), wanted, rtol=0, atol=0) + for actual, wanted in zip((distance, labels), caller_before): + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + # One-unit score gaps above FP32's exact-integer range, with both + # zero and high-dot queries. No implementation/dispatch assertion. + c = torch.full((2, 1537), 127., device='cuda') + c[:, 0] = torch.tensor([1., 0.], device='cuda') + model = known_torch_centroids( + c + offset, + model_class=QuantizedEmeans, + assignment_backend='cute', + ) + distance, labels = model.assign(torch.full((1, 1537), offset, dtype=dtype, device='cuda')) + self.assertEqual((distance.item(), labels.item()), (float(1536*127**2), 1)) + model.centroids.fill_(127+offset) + model.centroids[0, 0] = 126+offset + distance, labels = model.assign(torch.full((1, 1537), 127+offset, dtype=dtype, device='cuda')) + self.assertEqual((distance.item(), labels.item()), (0., 1)) + model.centroids[1, 0] = 125+offset + distance, labels = model.assign(torch.full((1, 1537), 127+offset, dtype=dtype, device='cuda')) + self.assertEqual((distance.item(), labels.item()), (1., 0)) + # Direct prepared norms are the minimal arithmetic observation; + # their object/cache identity is not a public contract. + c = torch.zeros(1, 257, device='cuda')+offset + c[0, :6] = torch.tensor([-1.5, -.5, .5, 1.5, 200., -200.], device='cuda')+offset + wanted = torch.zeros(1, 257, dtype=torch.int64, device='cuda') + wanted[0, :6] = torch.tensor([-2, 0, 0, 2, 127, -128], device='cuda') + model = known_torch_centroids( + c, model_class=QuantizedEmeans, assignment_backend='cute' + ) + for changed in (False, True): + if changed: + model.centroids.fill_(offset) + wanted.zero_() + prepared = _prepare_centroids(model.centroids, dtype=dtype) + torch.testing.assert_close(prepared.centroids[:, :257].long(), wanted, rtol=0, atol=0) + torch.testing.assert_close(prepared.norms[:1].long(), wanted.square().sum(1), rtol=0, atol=0) + query = torch.full((1, 257), offset, dtype=dtype, device='cuda') + distance, labels = model.assign(query) + self.assertEqual((distance.item(), labels.item()), (float(wanted.square().sum()), 0)) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_bytes_stress_and_high_integer_ids(self): + from faiss.contrib.e_means.cute import _prepare_centroids, _assign_rows + + for dtype, offset in ((torch.int8, 0), (torch.uint8, 128)): + with self.subTest(dtype=dtype): + start = time.monotonic() + torch.cuda.reset_peak_memory_stats() + g = torch.Generator(device='cuda').manual_seed(32768) + c = torch.randint(-128, 128, (16384, 128), generator=g, device='cuda').float()+offset + c[128].copy_(c[0]) + rows = torch.full((32768, 128), offset, dtype=dtype, device='cuda') + rows[:4].copy_((torch.randint(-128, 128, (4, 128), generator=g, device='cuda')+offset).to(dtype)) + rows[0].copy_(c[0]) + model = known_torch_centroids( + c, + model_class=QuantizedEmeans, + assignment_backend='cute', + assignment_chunk_size=32768, + ) + distance, labels = model.assign(rows) + probes = (rows[:4].cpu().long()[:, None]-c.cpu().long()[None]).square().sum(2) + torch.testing.assert_close(labels[:4].cpu(), probes.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance[:4].cpu(), probes.min(1).values.float(), rtol=0, atol=0) + zero = (c.cpu().long()-offset).square().sum(1) + self.assertTrue(bool((labels[4:] == zero.argmin()).all())) + torch.testing.assert_close(distance[4:], zero.min().float().to(distance.device).expand_as(distance[4:]), rtol=0, atol=0) + self.assertEqual(labels[0].item(), 0) + c = torch.full((65537, 1), offset, dtype=torch.float32, device='cuda') + c[-1].fill_(offset+2) + sentinels = torch.full((4,), -123, dtype=torch.int64, device='cuda') + distance, labels = _assign_rows( + torch.full((2, 1), offset+2, dtype=dtype, device='cuda'), + _prepare_centroids(c, dtype=dtype), + labels_out=sentinels[1:-1], + ) + self.assertEqual(sentinels.tolist(), [-123, 65536, 65536, -123]) + torch.testing.assert_close(distance, torch.zeros_like(distance), rtol=0, atol=0) + print('CuTe integer stress cost', dtype, time.monotonic()-start, + 'seconds, peak', torch.cuda.max_memory_allocated(), 'bytes') + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_bytes_revival_and_raw_code_workflow(self): + for dtype, value in ((torch.int8, 0), (torch.uint8, 128)): + rows = torch.full((10, 17), value, dtype=dtype, device='cuda') + model = QuantizedEmeans( + 17, + 2, + nepochs=5, + batch_size=10, + alpha0=0.5, + assignment_chunk_size=4, + assignment_backend='cute', + unused_threshold=0.1, # Preserve this synthetic mass-revival witness. + ) + centroids, labels = model.train(rows, rows[:2].float()) + self.assertIs(centroids, model.centroids) + self.assertIs(labels, model.assignments) + self.assertEqual(model.obj[-1], 0.) + self.assertEqual(model.n_splits, 1) + children = model.centroids.round().clamp(value-128, value+127).to(dtype) + self.assertEqual(model.assign(children)[1].tolist(), [0, 1]) + g = torch.Generator(device='cuda').manual_seed(7117) + source = torch.randn(32, 80, generator=g, device='cuda') + q = Int8Quantizer(80) + q.train(source[:16]) + codes = q.compute_codes(source) + model = QuantizedEmeans( + 80, 4, nepochs=1, batch_size=8, alpha0=0.5, assignment_backend='cute' + ) + model.train(codes, codes[:4].float()) # q deliberately NOT supplied. + distance, labels = model.assign(codes) + represented = model.centroids.round().clamp(-128, 127).cpu().long() + truth = (codes.cpu().long()[:, None]-represented[None]).square().sum(2) + torch.testing.assert_close(labels.cpu(), truth.argmin(1), rtol=0, atol=0) + torch.testing.assert_close(distance.cpu(), truth.min(1).values.float(), rtol=0, atol=0) + self.assertTrue(bool(torch.isfinite(q.decode(model.centroids)).all())) + source = torch.tensor([[-.25, .25], [1., 2.], [3., 4.]], device='cuda') + q = Int8Quantizer(2) + q.train(source) + codes = q.compute_codes(source) + decoded = q.decode(codes) + for k in (2, 128): + initial = decoded[0].expand(k, 2).clone() + initial[1] = decoded[2] + results = [ + known_torch_centroids( + initial, + model_class=QuantizedEmeans, + quantizer=q, + assignment_backend=backend, + ).assign(codes) + for backend in ('triton', 'cute') + ] + for actual, wanted in zip(results[1], results[0]): + torch.testing.assert_close(actual, wanted, rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_native_bytes_and_caller_quantizer_use_decoded_units(self): + x = torch.tensor([[0.],[2.],[10.],[12.]],device='cuda') + q = Int8Quantizer(1) + q.train(x) + for rows,quantizer,offset in ( + (x.to(torch.int8),None,0), + ((x+128).to(torch.uint8),None,128), + (q.compute_codes(x),q,0), + ): + with self.subTest(dtype=rows.dtype,calibrated=quantizer is not None): + model = QuantizedEmeans(1,2,nepochs=1,batch_size=4,alpha0=.5, + quantizer=quantizer,assignment_backend='cute') + model.train(rows,(x+offset)[[0,2]]) + torch.testing.assert_close(model.centroids,x.new_tensor([[1.],[11.]])+offset) + self.assertEqual(model.obj.item(),8.) + distance,labels = model.assign(rows) + torch.testing.assert_close(distance,torch.ones(4,device=x.device)) + torch.testing.assert_close(labels,torch.tensor([0,0,1,1],device=x.device)) + with self.assertRaises((TypeError, ValueError)): + QuantizedEmeans( + 1, 2, quantizer=q, assignment_backend='cute' + ).train(x) + + +class TestCuteClosingHandover(unittest.TestCase): + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_revived_centroid_rows_take_second_nearest(self): + from torch_test_e_means import _check_closing_handover, _handover_mixture + + x, init = _handover_mixture() + for nepochs in (1, 1.2, 1.6): + _check_closing_handover(self, x.cuda().bfloat16(), init.cuda(), ("cute",), nepochs=nepochs) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_spherical(self): + from torch_test_e_means import _check_closing_handover, _handover_mixture + + x, init = _handover_mixture() + x, init = (torch.nn.functional.normalize(t, dim=1) for t in (x, init)) + _check_closing_handover(self, x.cuda().bfloat16(), init.cuda(), ("cute",), spherical=True) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_grouped_second_label_ties(self): + from faiss.contrib.e_means import cute + + rows = torch.zeros(17, 96, device="cuda", dtype=torch.bfloat16) + # Winner 89 displaces predecessor 0 after IDs 0 and 1 tie within + # one tile. Winner 128's own runner-up 129 ties other-tile ID 0. + # Winner 256 displaces tile 0 after tiles 0 and 1 tie in selection. + for k, winner, tied in ((256, 89, (0, 1)), (256, 128, (0, 129)), + (384, 256, (0, 128))): + centers = torch.full((k, 96), 4., device="cuda") + centers[list(tied)] = 0 + centers[list(tied), 0] = 1 + centers[winner] = 0 + prepared = cute._prepare_centroids(centers, dtype=torch.bfloat16) + truth = (rows.double()[:, None] - prepared.centroids.double()).square().sum(2) + order = torch.argsort(truth, dim=1, stable=True) + self.assertTrue(bool((order[:, 0] == winner).all())) + self.assertTrue(bool((order[:, 1] == 0).all())) + for second in (0, 1, 2): + with self.subTest(winner=winner, second=second): + # Test the legal grouped leaf without changing auto dispatch. + bound = cute._new_grouped_binding( + len(rows), prepared, torch.float32, plan=(96, 128, 3), second=second) + bound.workspace.copy_(rows) + bound.launcher(bound.kernel, bound.labels) + torch.testing.assert_close(bound.labels, order[:, 0], rtol=0, atol=0) + torch.testing.assert_close( + bound.scores, truth.gather(1, order[:, :1]).flatten().float(), rtol=0, atol=0) + if second: + torch.testing.assert_close( + bound.second_scores, truth.gather(1, order[:, 1:2]).flatten().float(), rtol=0, atol=0) + if second == 2: + torch.testing.assert_close(bound.second_labels.long(), order[:, 1], rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_grouped_recovery_empty_and_clumped_replay(self): + from faiss.contrib.e_means import cute + + for k, b, tiles in ((384, 513, (0, 1, 2)), (4352, 33, (0, 32, 33))): + centers = torch.full((k, 96), 4., device="cuda") + for value, tile in enumerate(tiles): + centers[tile * 128:tile * 128 + 2] = 0 + centers[tile * 128:tile * 128 + 2, 0] = value * 4 + prepared = cute._prepare_centroids(centers, dtype=torch.bfloat16) + selected = torch.tensor(tiles, device="cuda")[torch.arange(b, device="cuda") % 3] + balanced = prepared.centroids[selected * 128] + clumped = prepared.centroids[0].expand_as(balanced) + for second in (0, 1, 2): + bound = cute._new_grouped_binding( + b, prepared, torch.float32, plan=(96, 128, 3), second=second) + bound.workspace.copy_(clumped) + bound.launcher(bound.kernel, bound.labels) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + bound.launcher(bound.kernel, bound.labels) + for visit, rows in enumerate((clumped, balanced, clumped)): + with self.subTest(k=k, b=b, second=second, visit=visit): + bound.workspace.copy_(rows) + graph.replay() + offsets = bound.kernel.grouping.offsets.view(torch.int64) + counts = offsets[1:] - offsets[:-1] + prefix = torch.cat((torch.zeros(1, device="cuda", dtype=torch.int64), + ((counts + 255) // 256).cumsum(0))) + self.assertEqual(bound.kernel.chunk_prefix.dtype, torch.int32) + torch.testing.assert_close(bound.kernel.chunk_prefix.long(), prefix, rtol=0, atol=0) + truth = (rows.double()[:, None] - prepared.centroids.double()).square().sum(2) + order = torch.argsort(truth, dim=1, stable=True) + raw = truth - rows.double().square().sum(1)[:, None] + torch.testing.assert_close(bound.labels, order[:, 0], rtol=0, atol=0) + torch.testing.assert_close( + bound.scores, raw.gather(1, order[:, :1]).flatten().float(), rtol=0, atol=0) + if second: + torch.testing.assert_close( + bound.second_scores, raw.gather(1, order[:, 1:2]).flatten().float(), rtol=0, atol=0) + if second == 2: + torch.testing.assert_close(bound.second_labels.long(), order[:, 1], rtol=0, atol=0) + + @unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") + def test_second_labels_every_route(self): + """Row-owned, tiled and grouped second labels: the float64 second + nearest, and nothing else returned changes.""" + from faiss.contrib.e_means import cute + from faiss.contrib.e_means.torch_backend import CuteBackend + + torch.manual_seed(0) + # Row-owned (4096 x d=96), tiled (4096 x d=256), grouped (labels from 16384 rows), small. + for b, k, d in ((4096, 16384, 96), (4096, 16384, 256), (32768, 16384, 96), (32768, 16384, 100), + (131072, 16384, 96), (300, 5000, 100)): + x = torch.randn(b, d, device="cuda").bfloat16() + c = torch.randn(k, d, device="cuda") + prepared, _ = CuteBackend(4096).prepare_centroids(c, torch.bfloat16) + second, second_labels = torch.empty(b, device="cuda"), torch.empty(b, dtype=torch.int32, device="cuda") + distance, labels = cute._assign_rows(x, prepared, None, None, second, second_labels) + second_ref = torch.empty(b, device="cuda") + distance_ref, labels_ref = cute._assign_rows(x, prepared, None, None, second_ref) + for got, want in ((distance, distance_ref), (labels, labels_ref), (second, second_ref)): + self.assertTrue(torch.equal(got, want), (b, k, d)) + rows = torch.randperm(b, device="cuda")[:2048] + cb = c.bfloat16().double() + score = cb.square().sum(1)[None] - 2 * x[rows].double() @ cb.t() + want = score.topk(2, dim=1, largest=False).values[:, 1] + got = score.gather(1, second_labels[rows].long()[:, None])[:, 0] + scale = want.abs() + x[rows].double().square().sum(1) + self.assertTrue(bool(((got - want).abs() <= 2e-3 * scale).all()), (b, k, d)) + self.assertTrue(bool((second_labels.long() != labels).all()), (b, k, d)) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_cute_dispatch.py b/thirdparty/faiss/tests/torch_test_e_means_cute_dispatch.py new file mode 100644 index 000000000..4cdb8b3ea --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_cute_dispatch.py @@ -0,0 +1,114 @@ +# 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. + +from collections import OrderedDict +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +import torch +from faiss.contrib.e_means import cute as backend + + +GROUPED_READY = backend._stack_status()[0] + + +class TestCuteDispatch(unittest.TestCase): + @staticmethod + def prepared(k, d, dtype=torch.bfloat16, spherical=False, transform=None): + return SimpleNamespace(num_centroids=k, dim=d, spherical=spherical, + transform=transform, centroids=SimpleNamespace(dtype=dtype, device='cuda:0')) + + @staticmethod + def properties(): + return SimpleNamespace(major=9, minor=0, multi_processor_count=132, + shared_memory_per_block_optin=232448) + + @unittest.skipUnless(GROUPED_READY, "optional CuTe stack required") + def test_distance_early_boundary_preserves_other_modes(self): + with patch.object(torch.cuda, 'get_device_properties', return_value=self.properties()): + for k in (512, 3968, 4096, 4224): + for b in (16383, 16384): + with self.subTest(b=b, k=k): + plans = [ + backend._grouped_plan(b, self.prepared(k, 128), torch.float32, second) + for second in (0, 1, 2)] + self.assertIsNone(plans[0]) + self.assertEqual(plans[1] is not None, b >= 16384 and k >= 4096) + self.assertEqual(plans[2] is not None, b >= 16384) + # Lower K still uses the original large-work rule in every mode. + for second in (0, 1, 2): + self.assertIsNotNone(backend._grouped_plan( + 2**31 // 512, self.prepared(512, 96), torch.float32, second)) + + @unittest.skipUnless(GROUPED_READY, "optional CuTe stack required") + def test_any_selected_plan_is_legal(self): + from faiss.contrib.e_means.cute_grouped import _validate_plan + + # Probe metadata properties; benchmark validation decides route performance. + cells = [(3, 128, 7), (70001, 32768, 113), + (70001, 32768, 1024), (70001, 32769, 113)] + with patch.object(torch.cuda, 'get_device_properties', return_value=self.properties()): + for b, k, d in cells: + with self.subTest(b=b, k=k, d=d): + plan = backend._grouped_plan( + b, self.prepared(k, d), torch.float32 + ) + if plan is not None: + _validate_plan(b, k, d, torch.bfloat16, plan, + self.properties().shared_memory_per_block_optin) + + @unittest.skipUnless(GROUPED_READY, "optional CuTe stack required") + def test_identical_operation_metadata_has_identical_choice(self): + with patch.object(torch.cuda, 'get_device_properties', return_value=self.properties()): + plain = backend._grouped_plan( + 70001, self.prepared(32768, 113), torch.float32 + ) + centered = backend._grouped_plan( + 70001, + self.prepared(32768, 113, transform=object()), + torch.float32, + ) + self.assertEqual(plain, centered) + + @unittest.skipUnless(GROUPED_READY, "optional CuTe stack required") + def test_preserves_prepr_grouped_work_cutoff(self): + from faiss.contrib.e_means.cute_grouped import _validate_plan + from faiss.contrib.e_means.cute_row_owned import row_owned_plan + with patch.object(torch.cuda, 'get_device_properties', return_value=self.properties()): + self.assertIsNone(row_owned_plan(64, 128, 256, 'cuda:0')) + for b,k,d in ((64,128,256),(64,128,7),(4096,8192,96)): + with self.subTest(b=b,k=k,d=d): + plan=backend._grouped_plan(b,self.prepared(k,d),torch.float32) + self.assertIsNone(plan) + plan=backend._grouped_plan(65536,self.prepared(49152,96),torch.float32) + self.assertIsNotNone(plan) + _validate_plan(65536,49152,96,torch.bfloat16,plan,self.properties().shared_memory_per_block_optin) + + @unittest.skipUnless(GROUPED_READY, "optional CuTe stack required") + def test_validation_errors_remain_errors(self): + from faiss.contrib.e_means.cute_grouped import _validate_plan + + with self.assertRaisesRegex(ValueError, 'explicit'): + _validate_plan(3, 128, 7, torch.bfloat16, 'invalid', 232448) + with self.assertRaisesRegex(ValueError, 'legal operands'): + _validate_plan(0, 128, 7, torch.bfloat16, (32, 128, 2), 232448) + with self.assertRaisesRegex(ValueError, 'shared memory'): + _validate_plan(3, 128, 7, torch.bfloat16, (32, 128, 2), 0) + + def test_selected_failure_propagates_without_installing_binding(self): + prepared = SimpleNamespace(bindings=OrderedDict()) + failure = ImportError('required grouping dependency is unavailable') + with patch.object(backend, '_grouped_plan', return_value=object()), patch.object( + backend, '_new_grouped_binding', side_effect=failure) as factory: + with self.assertRaises(ImportError) as caught: + backend._binding_for(17, prepared, torch.float32) + self.assertIs(caught.exception, failure) + self.assertEqual(factory.call_count, 1) + self.assertFalse(prepared.bindings) + + +if __name__ == '__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_distributed.py b/thirdparty/faiss/tests/torch_test_e_means_distributed.py new file mode 100644 index 000000000..f999eeacf --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_distributed.py @@ -0,0 +1,1249 @@ +# 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. + +"""Small caller-driven NCCL contracts; invoke explicitly on two or three GPUs.""" +import datetime +import tempfile +import unittest +import importlib.util +from unittest import mock + +import torch +import torch.distributed as dist + +from faiss.contrib.e_means import DistributedEmeans +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer + +# The GPU contracts use the automatic BF16 representation and the Triton, +# CuTe and FP8 paths, so they need NVIDIA SM80 or later. +NCCL_SM80 = (dist.is_available() and dist.is_nccl_available() + and torch.version.hip is None and torch.cuda.is_available() + and torch.cuda.get_device_capability() >= (8, 0)) + + +def _replicas(value, group): + copies = [torch.empty_like(value) for _ in range(dist.get_world_size(group))] + dist.all_gather(copies, value, group=group) + for other in copies: + torch.testing.assert_close(value, other, rtol=0, atol=0) + + +def _nvidia_sm80_triton(): + """The BF16 default representation needs an NVIDIA SM80 or later GPU, and + the IVF coarse assignment, the splits and the shared codecs need Triton.""" + return (torch.cuda.is_available() + and getattr(torch.version, "hip", None) is None + and importlib.util.find_spec("triton") is not None + and torch.cuda.get_device_capability() >= (8, 0)) + + +def _detached(model): + # Running centroid/usage and pass totals have no public result until finalize. + for value in (model._centroids, model._usage, model._batch_stats, + model._pass_counts, model._pass_sums, model._objective): + if value is not None: + assert not value.requires_grad and value.grad_fn is None + + +def _global_totals(group, transport, device): + """Known labels and exact dyadic totals, independent of a second model.""" + assert dist.get_world_size(group) == 2 + rank = dist.get_rank(group) + initial = torch.tensor([[0.], [2.], [4.]], device=device) + caller_initial = (initial + 1000 * rank).requires_grad_() + saved_initial = caller_initial.detach().clone() + model = DistributedEmeans(1, 3, group=group, transport=transport, + nepochs=1, batch_size=8, alpha0=1, seed=7, quantizer=None, + unused_threshold=.1) # This external-statistics witness is legacy mass. + model.begin(12, caller_initial) + torch.testing.assert_close(model._centroids, initial, rtol=0, atol=0) + torch.testing.assert_close(caller_initial, saved_initial, rtol=0, atol=0) + _replicas(model._centroids, group) + expected_counts = torch.zeros(3, device=device, dtype=torch.float64) + expected_sums = torch.zeros((3, 1), device=device) + for step, local_values in enumerate(( + ([0., 0., 0., 0.] if rank == 0 else [0., 2.25, 1.75, 2.]), + ([0., 0.] if rank == 0 else [2., 2.]), + )): + local = torch.tensor(local_values, device=device)[:, None].requires_grad_() + saved_local = local.detach().clone() + before = model.current_centroids().clone() + if rank == 0 and len(local) > 1: + partial = model.accumulate(local[:1]) + assert partial["sums"] is None and partial["counts"] is None + with unittest.TestCase().assertRaisesRegex(ValueError, "complete the pending"): + model.update({}) + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + stats = model.accumulate(local[1:]) + else: + stats = model.accumulate(local) + assert stats["n"] == len(local) + assert stats["sums"].dtype == stats["counts"].dtype == torch.float32 + assert stats["objective"].dtype == torch.float64 + if step == 0: + assert int((stats["counts"] > 0).sum()) == (1 if rank == 0 else 2) + # External copied statistics may require gradients, but update detaches + # them and must not mutate the caller's copies while packing collectives. + external = {name: value.detach().clone().requires_grad_( + value.is_floating_point() or value.is_complex()) + if isinstance(value, torch.Tensor) else value + for name, value in stats.items()} + saved_stats = {name: value.detach().clone() for name, value in external.items() + if isinstance(value, torch.Tensor)} + model.update(external) + assert model._epoch_rows == (8 if step == 0 else 12) + expected_counts += torch.tensor([5, 3, 0] if step == 0 else [2, 2, 0], + device=device, dtype=torch.float64) + expected_sums += torch.tensor( + [[0.], [6. if step == 0 else 4.], [0.]], device=device + ) + assert model._pass_counts.dtype == torch.float64 + assert model._pass_sums.dtype == torch.float32 + torch.testing.assert_close(model._pass_counts, expected_counts, rtol=0, atol=0) + torch.testing.assert_close(model._pass_sums, expected_sums, rtol=0, atol=0) + torch.testing.assert_close(model._objective, torch.tensor( + 0. if rank == 0 else 1 / 8, dtype=torch.float64, device=device), rtol=0, atol=0) + for name, value in saved_stats.items(): + assert external[name].requires_grad == (value.is_floating_point() or value.is_complex()) + torch.testing.assert_close(external[name], value, rtol=0, atol=0) + torch.testing.assert_close(local, saved_local, rtol=0, atol=0) + _detached(model) + _replicas(model._centroids, group) + _replicas(model._usage, group) + model.end_epoch() + torch.testing.assert_close(model._objective, torch.tensor( + 1 / 8, dtype=torch.float64, device=device), rtol=0, atol=0) + final = model.finalize() + torch.testing.assert_close(final, initial, rtol=0, atol=0) + _replicas(final, group) + _detached(model) + saved_final = final.clone() + del model + torch.testing.assert_close(final, saved_final, rtol=0, atol=0) + + +def _rows(begin, end, device): + return ((torch.arange(begin, end, device=device) % 3).float()[:, None] + .expand(-1, 2).contiguous() / 8) + + +def _training(group, transport, device, alpha=0.5, quantizer=None, backend="native", byte_dtype=None): + """Replica/EMA/revival agreement; floating tolerance, not a universal oracle.""" + rank, ranks = dist.get_rank(group), dist.get_world_size(group) + batch, population = 2 * ranks, 11 * ranks + initial = torch.tensor([[0., 0.], [5., 5.], [100., 100.]], device=device) + def represented(rows): + if byte_dtype is not None: + return (8 * rows + (128 if byte_dtype == torch.uint8 else 0)).to(byte_dtype) + return quantizer.compute_codes(rows) if isinstance(quantizer, Int8Quantizer) else rows + if byte_dtype is not None: + initial = 8 * initial + (128 if byte_dtype == torch.uint8 else 0) + args = dict(nepochs=2, batch_size=batch, alpha0=alpha, seed=7, + assignment_chunk_size=2, centroid_chunk_size=2, quantizer=quantizer, + unused_threshold=0.1) + model = DistributedEmeans( + 2, + 3, + group=group, + transport=transport, + assignment_backend=backend, + **args + ) + model_class = QuantizedEmeans + reference = model_class( + 2, + 3, + assignment_backend=( + backend + if byte_dtype is not None or isinstance(quantizer, Int8Quantizer) + else "native" + ), + **args + ) + caller_initial = initial + 1000 * rank + saved_initial = caller_initial.clone() + model.begin(population, caller_initial) + reference.begin(population, initial) + torch.testing.assert_close(caller_initial, saved_initial, rtol=0, atol=0) + torch.testing.assert_close(model._centroids, initial, rtol=0, atol=0) + with unittest.TestCase().assertRaises(NotImplementedError): + model.train(_rows(0, batch, device)) + if rank != 0: + # Noncoordinator split draws must not affect the broadcast revival. + model._split_rng.manual_seed(123456) + for _ in range(2): + for begin in range(0, population, batch): + n = min(batch, population - begin) + local_n = n // ranks + start = begin + rank * local_n + local = represented(_rows(start, start + local_n, device)) + saved_local = local.clone() + before = model.current_centroids().clone() + if rank == 0 and len(local) > 1: + partial = model.accumulate(local[:1]) + assert partial['sums'] is None and partial['counts'] is None + with unittest.TestCase().assertRaisesRegex(ValueError, 'complete the pending'): + model.update({}) + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + stats = model.accumulate(local[1:]) + else: + stats = model.accumulate(local) + expected_dtype = torch.int64 if byte_dtype is not None else torch.float32 + assert stats["sums"].dtype == stats["counts"].dtype == expected_dtype + model.update(stats) + assert model._epoch_rows == begin + n + reference.update(reference.accumulate(represented(_rows(begin, begin + n, device)))) + torch.testing.assert_close(local, saved_local, rtol=0, atol=0) + _detached(model) + _replicas(model._centroids, group) + _replicas(model._usage, group) + torch.testing.assert_close(model._centroids, reference._centroids, + rtol=2e-6, atol=2e-6) + torch.testing.assert_close(model._usage, reference._usage, rtol=2e-6, atol=2e-6) + torch.testing.assert_close(model._pass_counts, reference._pass_counts, + rtol=0, atol=0) + if model._pass_sums is not None: + torch.testing.assert_close(model._pass_sums, reference._pass_sums, + rtol=0, atol=0) + model.end_epoch() + reference.end_epoch() + for field in ("imbalance_factor", "nsplit"): + assert model.iteration_stats[-1][field] == reference.iteration_stats[-1][field] + assert model.n_splits == reference.n_splits and model.n_splits > 0 + final = model.finalize() + torch.testing.assert_close(final, reference.finalize(), rtol=2e-6, atol=2e-6) + torch.testing.assert_close(model.obj, reference.obj, rtol=1e-6, atol=1e-5) + _replicas(final, group) + saved_final = final.clone() + del model + torch.testing.assert_close(final, saved_final, rtol=0, atol=0) + + +def _integer_external_totals(group, transport, device): + """Odd counts above FP32 exactness discriminate typed transport by values.""" + c, rank = 2**24 + 1, dist.get_rank(group) + model = DistributedEmeans( + 1, + 3, + group=group, + transport=transport, + assignment_backend="triton", + nepochs=1, + batch_size=2 * c, + alpha0=1, + seed=7, + unused_threshold=.1, # Explicit legacy law for the sums-only typed witness. + ) + model.begin(2*c, torch.tensor([[254.], [255.], [4.]], device=device)) + counts = torch.tensor([c, 0, 0] if rank == 0 else [c-1, 1, 0], + device=device, dtype=torch.int64) + sums = (counts * torch.tensor([254, 255, 0], device=device))[:, None] + objective = torch.zeros((), device=device, dtype=torch.float64, requires_grad=True) + saved_sums, saved_counts = sums.clone(), counts.clone() + model.update(dict(sums=sums, counts=counts, objective=objective, n=c)) + expected_counts = torch.tensor([2*c-1, 1, 0], device=device, dtype=torch.int64) + expected_sums = (expected_counts * torch.tensor([254, 255, 0], device=device))[:, None] + assert model._pass_counts.dtype == model._pass_sums.dtype == torch.int64 + torch.testing.assert_close(model._pass_counts, expected_counts, rtol=0, atol=0) + torch.testing.assert_close(model._pass_sums, expected_sums, rtol=0, atol=0) + torch.testing.assert_close(sums, saved_sums, rtol=0, atol=0) + torch.testing.assert_close(counts, saved_counts, rtol=0, atol=0) + _detached(model) + model.end_epoch() + # Revival may change an empty cluster; closing retains that current value. + current_empty = model._centroids[2].clone() + final = model.finalize() + torch.testing.assert_close(final[:2], torch.tensor([[254.], [255.]], device=device), rtol=0, atol=0) + torch.testing.assert_close(final[2], current_empty, rtol=0, atol=0) + _replicas(final, group) + + +def _invalid_sizes(group, transport, device): + check = unittest.TestCase() + initial = torch.tensor([[0., 0.], [5., 5.]], device=device) + for n, batch in ((8, 5), (9, 4)): + model = DistributedEmeans(2, 2, group=group, transport=transport, + nepochs=1, batch_size=batch, alpha0=0.5) + with check.assertRaisesRegex(ValueError, "divisible"): + model.begin(n, initial) + for call in ( + lambda _model=model: _model.accumulate(_rows(0, 1, device)), + lambda _model=model: _model.update({}), + model.end_epoch, + model.finalize, + ): + with check.assertRaises(RuntimeError): + call() + # N below nominal B prescribes N, not an unusable nondivisible B. + model = DistributedEmeans(2, 2, group=group, transport=transport, + nepochs=1, batch_size=batch, alpha0=0.5) + model.begin(4, initial) + model.update(model.accumulate(_rows(0, 2, device))) + model.end_epoch() + torch.testing.assert_close(model.finalize(), torch.tensor( + [[1 / 16, 1 / 16], [5., 5.]], device=device), rtol=0, atol=0) + model = DistributedEmeans(2, 2, group=group, transport=transport, + nepochs=1, batch_size=4, alpha0=0.5) + model.begin(6, initial) + stats = model.accumulate(_rows(0, 2, device)) + for wrong_n in (0, 1, 3): + with check.assertRaisesRegex(ValueError, "prescribed batch size"): + model.update(dict(stats, n=wrong_n)) + model.update(stats) + stats = model.accumulate(_rows(0, 1, device)) + with check.assertRaisesRegex(ValueError, "prescribed batch size"): + model.update(dict(stats, n=2)) + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.finalize(), torch.tensor( + [[1 / 24, 1 / 24], [5., 5.]], device=device), rtol=0, atol=0) + + +def _sharder_contracts(group, device): + from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids + from torch_test_e_means_cute import _ready + + rank = dist.get_rank(group) + check = unittest.TestCase() + initial = torch.tensor([[0.0], [2.0], [4.0], [9.0]], device=device) + expected = torch.tensor([[0.25], [1.75], [4.25], [9.0]], device=device) + local = torch.tensor([[.25], [1.75], [4.25]] * 2, device=device) + saved_rows = local.clone() + shard = slice(2 * rank, 2 * rank + 2) + args = dict(group=group, nepochs=2, batch_size=8, alpha0=1, + assignment_chunk_size=3, capture_assignments=True, quantizer=None) + model = EmeansShardedCentroids(1, 4, **args) + with check.assertRaisesRegex(ValueError, "divisible"): + model.begin(11, initial[shard]) + model = EmeansShardedCentroids(1, 4, **args) + model.begin(12, initial[shard]) + torch.testing.assert_close(model.current_centroids(), initial[shard], rtol=0, atol=0) + with check.assertRaises(RuntimeError): + model.final_closing_mean([local]) + retained_labels = [] + for epoch in range(2): + for begin in (0, 4): + rows = local[begin:begin + 4] + parts = [torch.empty_like(model.current_centroids()) for _ in range(2)] + dist.all_gather(parts, model.current_centroids(), group=group) + frozen = torch.cat(parts) + global_rows = torch.cat((rows, rows)) + distances = (global_rows.double()[:, None] - frozen.double()).square().sum(2) + labels = distances.argmin(1) + counts = torch.bincount(labels, minlength=4) + sums = torch.zeros((4, 1), dtype=torch.float64, device=device) + sums.index_add_(0, labels, global_rows.double()) + before = model.current_centroids().clone() + partial = model.accumulate(rows[:1]) + assert partial["n"] == 2 and partial["sums"] is None and partial["counts"] is None + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + stats = model.accumulate(rows[1:]) + assert stats["n"] == 2 * len(rows) + torch.testing.assert_close(stats["sums"], sums[shard].float(), rtol=0, atol=0) + torch.testing.assert_close(stats["counts"], counts[shard].float(), rtol=0, atol=0) + owned = (labels >= 2 * rank) & (labels < 2 * rank + 2) + torch.testing.assert_close(stats["objective"], distances[owned, labels[owned]].sum(), + rtol=0, atol=0) + if epoch == 1: + for contribution, oracle in ((partial, labels[:1]), (stats, labels[1:len(rows)])): + torch.testing.assert_close(contribution["labels"], oracle, rtol=0, atol=0) + retained_labels.append((contribution["labels"], oracle.clone())) + else: + assert "labels" not in partial and "labels" not in stats + model.update(stats) + model.end_epoch() + torch.testing.assert_close(model.current_centroids(), expected[shard], rtol=0, atol=0) + closed = model.final_closing_mean([local[:2], local[2:]]) + torch.testing.assert_close(closed, expected[shard], rtol=0, atol=0) + assert closed.dtype == torch.float32 and not closed.requires_grad + torch.testing.assert_close(local, saved_rows, rtol=0, atol=0) + torch.testing.assert_close(initial, torch.tensor([[0.], [2.], [4.], [9.]], device=device), rtol=0, atol=0) + for labels, oracle in retained_labels: + torch.testing.assert_close(labels, oracle, rtol=0, atol=0) + saved_closed = closed.clone() + model = EmeansShardedCentroids(1, 4, **args) + torch.testing.assert_close(closed, saved_closed, rtol=0, atol=0) + resident = EmeansShardedCentroids(1, 4, **args) + resident.train(local, init_centroids=initial[shard]) + torch.testing.assert_close(resident.centroids, expected[shard], rtol=0, atol=0) + torch.testing.assert_close(resident.assignments, torch.tensor([0, 1, 2, 0, 1, 2], device=device), rtol=0, atol=0) + retained = (resident.centroids, resident.obj, resident.assignments) + saved = tuple(value.clone() for value in retained) + with check.assertRaises(RuntimeError): + resident.begin(12, initial[shard]) + check.assertFalse(resident._failed) + for actual, original, snapshot in zip( + (resident.centroids, resident.obj, resident.assignments), retained, saved): + check.assertIs(actual, original) + torch.testing.assert_close(actual, snapshot, rtol=0, atol=0) + + # Wrong closing row count poisons the run; reset permits real same-model recovery. + failed = EmeansShardedCentroids(1, 2, group=group, nepochs=1, batch_size=4, alpha0=1) + ones = torch.ones((2, 1), device=device) + own_initial = torch.tensor([[1. if rank == 0 else 9.]], device=device) + failed.begin(4, own_initial) + failed.update(failed.accumulate(ones)) + failed.end_epoch() + with check.assertRaisesRegex(ValueError, "cover global_n"): + failed.final_closing_mean([ones[:1]]) + with check.assertRaises(RuntimeError): + failed.accumulate(ones) + failed = EmeansShardedCentroids( + 1, 2, group=group, nepochs=1, batch_size=4, alpha0=1 + ) + failed.begin(4, own_initial) + failed.update(failed.accumulate(ones)) + failed.end_epoch() + torch.testing.assert_close(failed.final_closing_mean([ones]), own_initial, rtol=0, atol=0) + + raw_supported = (not torch.version.hip and torch.cuda.get_device_capability(device) + in ((8, 0), (9, 0), (10, 0))) + if importlib.util.find_spec("triton") is None: + print("sharder raw checks unavailable: Triton not installed", flush=True) + elif not raw_supported: + rejected = EmeansShardedCentroids(1, 2, group=group, assignment_backend="triton") + rejected.begin(4, own_initial) + with check.assertRaisesRegex(RuntimeError, "INT8 assignment requires"): + rejected.accumulate(ones.to(torch.int8)) + else: + for backend in (("triton", "cute") if _ready() else ("triton",)): + for dtype, offset in ((torch.int8, 0), (torch.uint8, 128)): + for tie in (False, True): + d = 8192 + rows = torch.full((2, d), offset, dtype=dtype, device=device) + centers = torch.full((2, d), float(offset), device=device) + centers[:, :1024] -= 128 + if not tie: + centers[0, 1024] += 1 + distances = (centers.long() - rows[0].long()).square().sum(1) + oracle = int(distances.argmin()) # Exact ties choose the lowest global ID. + assert distances.tolist() == ([2**24, 2**24] if tie else [2**24 + 1, 2**24]) + raw = EmeansShardedCentroids( + d, + 2, + group=group, + nepochs=1, + batch_size=4, + alpha0=1, + capture_assignments=True, + assignment_backend=backend, + ) + raw.begin(4, centers[rank:rank + 1]) + stats = raw.accumulate(rows) + torch.testing.assert_close(stats["labels"], torch.full((2,), oracle, device=device), rtol=0, atol=0) + count = 4 if rank == oracle else 0 + torch.testing.assert_close(stats["sums"], torch.full((1, d), count * offset, dtype=torch.int64, device=device), rtol=0, atol=0) + assert stats["counts"].dtype == torch.int64 and stats["counts"].item() == count + saved_labels = stats["labels"].clone() + raw.update(stats) + raw.end_epoch() + frozen = raw.current_centroids().clone() + result = raw.finalize() + expected_raw = rows[:1].float() if rank == oracle else frozen + torch.testing.assert_close(result, expected_raw, rtol=0, atol=0) + torch.testing.assert_close(stats["labels"], saved_labels, rtol=0, atol=0) + # External INT64 stats fix the schema, not signed/unsigned + # row metadata. The first raw closing rows must prepare the + # matching centroid operand without private priming. + raw = EmeansShardedCentroids( + d, + 2, + group=group, + nepochs=1, + batch_size=4, + alpha0=1, + capture_assignments=True, + assignment_backend=backend, + ) + raw.begin(4, centers[rank:rank + 1]) + raw.update({ + "sums": torch.full((1, d), count * offset, dtype=torch.int64, device=device), + "counts": torch.tensor([count], dtype=torch.int64, device=device), + "objective": distances[oracle].double() * count, + "n": 4, + }) + raw.end_epoch() + scanned = raw.final_closing_mean([rows[:1], rows[1:]]) + torch.testing.assert_close(scanned, expected_raw, rtol=0, atol=0) + print("sharder raw exact: %s %s tie=%s" % (backend, dtype, tie), flush=True) + + +def _saved_closing_contracts(group, device, quantizer=None, backend='native'): + from faiss.contrib.e_means import EmeansShardedCentroids + + rank = dist.get_rank(group) + check = unittest.TestCase() + initial = torch.tensor([[0.], [4.], [100.], [200.]], device=device) + local = torch.tensor(([0., 3., 6.] if rank == 0 else [1., 2., 5.]), device=device)[:, None] + if quantizer is not None: + local = local + 2**-10 + if rank == 1: + local = quantizer.compute_codes(local) + model = None + shard = slice(2 * rank, 2 * rank + 2) + + def train(): + nonlocal model + model = EmeansShardedCentroids( + 1, 4, group=group, nepochs=1, batch_size=4, alpha0=1, + assignment_chunk_size=1, capture_assignments=True, + quantizer=quantizer, assignment_backend=backend, + ) + model.begin(6, initial[shard]) + saved = [] + for begin in (0, 2): + stats = model.accumulate(local[begin:begin + 2]) + saved.append(stats["labels"].cpu().to(torch.int32)) + model.update(stats) + model.end_epoch() + return torch.cat(saved) + + codes = train() + labels = [torch.empty(3, device=device, dtype=torch.int32) for _ in range(2)] + represented = local if quantizer is None else quantizer.decode( + local if local.dtype == quantizer.dtype else quantizer.compute_codes(local)) + rows = [torch.empty_like(represented) for _ in range(2)] + dist.all_gather(labels, codes.to(device), group=group) + dist.all_gather(rows, represented, group=group) + labels, rows = torch.cat(labels).long(), torch.cat(rows) + sums = torch.zeros_like(initial) + sums.index_add_(0, labels, rows) + counts = torch.bincount(labels, minlength=4) + # Deliberately move the completed snapshot: means must still use old codes. + model._centroids.add_(1000) + expected = torch.where( + (counts[shard] > 0)[:, None], + sums[shard] / counts[shard].clamp_min(1)[:, None], model._centroids, + ) + def no_search(*args, **kwargs): + raise AssertionError("saved closing must not run assignment") + model._prepare_assignment = model._local_assignment_batch = model._reduce_winners = no_search + result = model.final_closing_mean( + [local[:1], local[1:]], assignments=codes, chunk_rows=1, + ) + torch.testing.assert_close(result, expected, rtol=0, atol=0) + global_mean = sums / counts.clamp_min(1)[:, None] + mse = (rows - global_mean[labels]).square().sum().item() / len(rows) + check.assertAlmostEqual(model.closing_stats["assignment_mse"], mse, places=6) + assert model.closing_stats["rows"] == 6 and model.closing_stats["saved_assignments"] + # Rank 1 owns only empty clusters and must survive zero-length receives. + assert counts[2:].sum().item() == 0 + + del model._prepare_assignment, model._local_assignment_batch, model._reduce_winners + codes = train() + with check.assertRaisesRegex(ValueError, "counts differ"): + model.final_closing_mean([local], assignments=torch.zeros_like(codes), chunk_rows=1) + assert model._failed and model.centroids is None + + # A short final epoch leaves uncoded rows; all ranks still route empty blocks. + model = EmeansShardedCentroids( + 1, 4, group=group, nepochs=0.5, batch_size=4, alpha0=1, + capture_assignments=True, + quantizer=quantizer, assignment_backend=backend, + ) + local = torch.tensor([0., 4., 50., 60.], device=device)[:, None] + if quantizer is not None: + local = local + 2**-10 + if rank == 1: + local = quantizer.compute_codes(local) + model.begin(8, initial[shard]) + stats = model.accumulate(local[:2]) + codes = torch.full((4,), -1, dtype=torch.int32) + codes[:2] = stats["labels"].cpu().to(torch.int32) + model.update(stats) + model.end_epoch() + expected = model.current_centroids().clone() + model._prepare_assignment = model._local_assignment_batch = model._reduce_winners = no_search + torch.testing.assert_close( + model.final_closing_mean([local], assignments=codes, chunk_rows=1), + expected, rtol=0, atol=0, + ) + assert model.closing_stats["rows"] == 4 + + +def _all_gather_contracts(group, device): + from unittest.mock import patch + from faiss.contrib.e_means import EmeansShardedCentroids, EmeansShardedCentroidsIVF + + rank = dist.get_rank(group) + generator = torch.Generator(device=device).manual_seed(37) + # INT8 assignment needs an NVIDIA SM80, SM90 or SM100 GPU. + modes = ["float", "ivf", "spherical"] + if torch.cuda.get_device_capability(device) in ((8, 0), (9, 0), (10, 0)): + modes += ["int8", "uint8"] + for mode in modes: + data = torch.randn((34, 8), device=device, generator=generator) + if mode in ("int8", "uint8"): + data = (data * 3).round().to(torch.int8) + if mode == "uint8": + data = (data.int() + 128).to(torch.uint8) + initial = data[:8].float().clone() + initial[1] = initial[0] # Exact ties must retain lowest global-ID semantics. + local = data[rank * 17:(rank + 1) * 17] + model_type = EmeansShardedCentroidsIVF if mode == "ivf" else EmeansShardedCentroids + extra = dict(nlist=4, nprobe=2, coarse_niter=2) if mode == "ivf" else {} + models = [model_type( + 8, 8, group=group, nepochs=2, batch_size=12, alpha0=.3, + assignment_chunk_size=2, capture_assignments=True, + spherical=mode == "spherical", + assignment_backend="triton" if mode in ("int8", "uint8") else "native", + quantizer=None, + **extra, + ) for _ in range(2)] + if mode == "ivf": + # The oracle gathers first and lets every owner route the whole + # batch, as before. Compare that with routing each reader's rows. + models[1]._gather_assignment_rows = ( + EmeansShardedCentroids._gather_assignment_rows.__get__(models[1]) + ) + for model in models: + model.begin(34, initial[rank * 4:(rank + 1) * 4]) + model._prepare_input(local) + retained = [] + for epoch in range(2): + order = torch.randperm(17, device=device, generator=generator) + for begin in range(0, 17, 6): + index = order[begin:begin + 6] + outputs = [] + for i, model in enumerate(models): + # Compare partial with whole indexed accumulation, including tails. + partial = model._accumulate(local, index[:2]) if i == 0 else None + stats = model._accumulate(local, index[2:] if i == 0 else index) + outputs.append({key: stats[key].clone() for key in ("sums", "counts", "objective")}) + if epoch == 1: + labels = (torch.cat((partial["labels"], stats["labels"])) + if partial is not None else stats["labels"]) + outputs[-1]["labels"] = labels + retained.append((stats["labels"], stats["labels"].clone())) + model.update(stats) + for key in outputs[0]: + torch.testing.assert_close(outputs[0][key], outputs[1][key], rtol=2e-5, atol=2e-5) + torch.testing.assert_close(models[0].current_centroids(), models[1].current_centroids(), + rtol=2e-5, atol=2e-5) + for model in models: + model.end_epoch() + torch.testing.assert_close(models[0].finalize(), models[1].finalize(), rtol=2e-5, atol=2e-5) + for labels, expected in retained: + torch.testing.assert_close(labels, expected, rtol=0, atol=0) + + # Isolate top-1 row/winner collectives from setup and cost revival. + model = EmeansShardedCentroids( + 8, 8, group=group, nepochs=1, batch_size=12, alpha0=.3, assignment_chunk_size=2, + assignment_backend="native", quantizer=None, unused_threshold=.1, + ) + rows = torch.randn((6, 8), device=device, generator=generator) + model.begin(12, rows[rank:rank + 4].clone()) + # The coordinated score-hook preflight is setup once per run. Its own + # coverage lives in the sharded-cost tests, outside this transport spy. + model._prepare_input(rows) + model._prepare_assignment() + gather_name = "all_gather_single" if getattr(dist, "all_gather_single", None) else "all_gather_into_tensor" + real_gather, real_reduce = getattr(dist, gather_name), dist.all_reduce + calls = {"gather": 0, "reduce": 0} + + def gather(*args, **kwargs): + calls["gather"] += 1 + return real_gather(*args, **kwargs) + + def reduce(*args, **kwargs): + calls["reduce"] += 1 + return real_reduce(*args, **kwargs) + + def no_broadcast(*args, **kwargs): + raise AssertionError("batch broadcast in all-gather path") + + with patch.object(dist, gather_name, new=gather), \ + patch.object(dist, "all_reduce", new=reduce), \ + patch.object(dist, "broadcast", new=no_broadcast): + model.accumulate(rows) + assert calls["gather"] == 1 and calls["reduce"] == 2 + + # Default cost transport includes one extra second-candidate reduction + # per batch, and only the first batch includes the hook preflight gather. + cost = EmeansShardedCentroids( + 8, 8, group=group, nepochs=1, batch_size=12, alpha0=.3, assignment_chunk_size=2, + assignment_backend="native", quantizer=None, + ) + cost.begin(24, rows[rank:rank + 4].clone()) + for expected_gathers in (2, 1): + calls.update(gather=0, reduce=0) + with patch.object(dist, gather_name, new=gather), \ + patch.object(dist, "all_reduce", new=reduce), \ + patch.object(dist, "broadcast", new=no_broadcast): + stats = cost.accumulate(rows) + assert calls["gather"] == expected_gathers and calls["reduce"] == 3 + assert cost._unused_threshold is None and stats["n"] == 12 + assert stats["removal"] is cost._batch_removal + cost.update(stats) + + # Every reader queries only lists owned by the other centroid shard. + # Routing must use global occupancy, not discard locally empty lists. + from faiss.contrib.e_means.ivf_flat import IndexIVFFlat + + initial = torch.tensor( + [[0., 0.], [1., 0.], [10., 0.], [11., 0.], + [20., 0.], [21., 0.], [30., 0.], [31., 0.]], device=device, + ) + local = initial[(1 - rank) * 4:(2 - rank) * 4].clone() + model = EmeansShardedCentroidsIVF( + 2, 8, group=group, nepochs=1, batch_size=8, alpha0=.3, + nlist=4, nprobe=1, assignment_backend="native", unused_threshold=0, + ) + model.begin(8, initial[rank * 4:(rank + 1) * 4]) + model._ivf = IndexIVFFlat(initial[::2].clone(), nprobe=1) + model._prepare_input(local) + prepared = model._prepare_assignment() + full = model._gather_training_rows(local) + expected_routing = prepared.route(full).to(torch.int32) + distance, labels = prepared.search_1nn(full) + expected_winner = model._reduce_winners(distance, labels) + real_route, real_search = prepared.route, prepared.search_1nn + calls = {"gather": 0, "reduce": 0, "route": 0, "route_rows": 0} + routing = None + + def route(rows, *args, **kwargs): + calls["route"] += 1 + calls["route_rows"] = len(rows) + return real_route(rows, *args, **kwargs) + + def search(*args, **kwargs): + nonlocal routing + routing = kwargs["coarse_idx"].detach().clone() + return real_search(*args, **kwargs) + + with patch.object(prepared, "route", new=route), \ + patch.object(prepared, "search_1nn", new=search), \ + patch.object(dist, gather_name, new=gather), \ + patch.object(dist, "all_reduce", new=reduce): + stats = model.accumulate(local) + assert calls["route"] == 1 and calls["route_rows"] == len(local) + assert calls["gather"] == 2 and calls["reduce"] == 3 + assert routing.dtype == torch.int32 and routing.shape == (8, 1) + torch.testing.assert_close(routing, expected_routing, rtol=0, atol=0) + torch.testing.assert_close(stats["labels"], expected_winner[rank * 4:(rank + 1) * 4]) + torch.testing.assert_close(stats["counts"], torch.ones(4, device=device)) + torch.testing.assert_close(stats["sums"], initial[rank * 4:(rank + 1) * 4]) + + +def _auto_batch_error_worker(rank, world_size, rendezvous): + # 128 rows, d=8, k=4, 5 passes: batch_law="auto" picks the quality law and + # a batch of 1, which two processes cannot split. begin must say why and + # how to fix it; the throughput law gives a divisible batch. + torch.set_num_threads(1) + dist.init_process_group("gloo", init_method=rendezvous, rank=rank, + world_size=world_size, timeout=datetime.timedelta(seconds=60)) + try: + initial = torch.arange(32, dtype=torch.float32).reshape(4, 8) + model = DistributedEmeans(8, 4, nepochs=5, group=dist.group.WORLD) + try: + model.begin(128, initial) + except ValueError as error: + message = str(error) + else: + raise AssertionError("begin accepted a batch the processes cannot split") + for part in ('batch_law="auto"', "quality law", "d <= 16", "%d processes" % world_size, + 'batch_law="throughput"'): + assert part in message, (part, message) + explicit = DistributedEmeans(8, 4, nepochs=5, batch_law="throughput", group=dist.group.WORLD) + explicit.begin(128, initial) + assert explicit.recipe["batch_size"] % world_size == 0 + finally: + dist.destroy_process_group() + + +def _revival_worker(rank, world_size, rendezvous, backend): + from unittest import mock + from faiss.contrib.e_means import EmeansShardedCentroids + from faiss.contrib.e_means.torch_backend import TorchBackend, TritonBackend + + torch.set_num_threads(1) + if backend == "nccl": + torch.cuda.set_device(rank) + device = torch.device("cuda", rank) if backend == "nccl" else torch.device("cpu") + dist.init_process_group(backend, init_method=rendezvous, rank=rank, + world_size=world_size, timeout=datetime.timedelta(seconds=60)) + try: + # Unique sources/targets cross owners in both directions. The first + # and last chunks have empty senders and empty receivers; the middle + # chunk exercises mixed ownership and a partial tail for chunk_rows=4. + source = torch.tensor([0, 2, 3, 10, 11, 14], device=device) + target = torch.tensor([8, 9, 15, 1, 5, 6], device=device) + initial = torch.tensor([8., 0.001, -2., 1.], device=device).repeat(16, 1) + initial += torch.arange(16, device=device)[:, None] * 1e-5 + usage = torch.arange(1, 17, device=device, dtype=torch.float32) + shard = slice(rank * 8, (rank + 1) * 8) + cases = [(dtype, None, TorchBackend) for dtype in (None, torch.float16, torch.bfloat16)] + if backend == "nccl": + from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer + + q = Fp8Quantizer(4) + q.train(torch.cat((initial - 1, initial + 1))) + cases.append((q.dtype, q, TritonBackend)) + real_exchange = dist.all_to_all_single + for dtype, quantizer, owner in cases: + # An independent full-table split is the arithmetic oracle. In + # particular, low-precision collapsed pairs must stay separated. + oracle = QuantizedEmeans(4, 16, quantizer=quantizer, assignment_backend=owner.name) + oracle._execution_backend = owner(oracle.centroid_chunk_size) + oracle._centroids, oracle._usage = initial.clone(), usage.clone() + oracle._input_dtype = dtype + oracle._apply_splits(source, target) + for chunk_rows in ((1, 2, 4, 100) if quantizer is None else (2,)): + model = EmeansShardedCentroids(4, 16, group=dist.group.WORLD, + quantizer=quantizer, assignment_backend=owner.name) + model._execution_backend = owner(model.centroid_chunk_size) + model._centroids, model._usage = initial[shard].clone(), usage[shard].clone() + model._revival_dtype = dtype + exchanges = [0] + + def counted(output, rows, *args, chunk_rows=chunk_rows, exchanges=exchanges, **kwargs): + if rows.ndim == 2: + assert len(rows) <= chunk_rows and len(output) <= chunk_rows + exchanges[0] += 1 + return real_exchange(output, rows, *args, **kwargs) + + with mock.patch.object(model, "_choose_splits", return_value=(source, target)) as choose, \ + mock.patch.object(dist, "all_to_all_single", new=counted): + assert model._revive_unused(torch.Generator(), chunk_rows=chunk_rows) == len(source) + assert choose.call_count == (1 if rank == 0 else 0) + assert model.n_splits == len(source) + torch.testing.assert_close(model._centroids, oracle._centroids[shard], rtol=0, atol=0) + torch.testing.assert_close(model._usage, oracle._usage[shard], rtol=0, atol=0) + assert exchanges[0] == 3 * ((len(source) + chunk_rows - 1) // chunk_rows) + # A later empty revival must leave the completed split alone. + model._usage.fill_(1) + before = model._centroids.clone() + with mock.patch.object(dist, "all_to_all_single", new=counted): + assert model._revive_unused(torch.Generator(), chunk_rows=chunk_rows) == 0 + assert exchanges[0] == 3 * ((len(source) + chunk_rows - 1) // chunk_rows) + assert model.n_splits == len(source) + torch.testing.assert_close(model._centroids, before, rtol=0, atol=0) + finally: + dist.destroy_process_group() + + +def _shared_codec_route(check, device, name, backend, capabilities, rows, initial, codec): + """Agree numerical admission; unavailable local models must fail loudly.""" + def admitted(capability): + if backend == 'cute' and capability != (9, 0): + return False + if name in ('fp8', 'native_fp8'): + return capability in ((9, 0), (10, 0), (10, 3)) + if name in ('int8', 'raw_int8', 'raw_uint8'): + return capability in ((8, 0), (9, 0), (10, 0)) + return True + + if all(admitted(cap) for cap in capabilities): + return True + if not admitted(torch.cuda.get_device_capability(device)): + # Use a local model here: an unsupported peer must not strand a + # supported peer inside owner collectives. Both omit the same arm. + model = QuantizedEmeans(1, 4, quantizer=codec, assignment_backend=backend, + nepochs=1, batch_size=4, unused_threshold=.1) + message = ('exactly SM90' if backend == 'cute' else + 'SM80, SM90, or SM100' if name in ('int8', 'raw_int8', 'raw_uint8') else + 'SM90, SM100, or SM103') + with check.assertRaisesRegex(RuntimeError, message): + model.begin(4, initial) + model.accumulate(rows[:4]) + check.assertEqual(model.assignment_backend, backend) + return False + + +def _shared_codec_contracts(group, device): + """Exercise the new owned-code wire; local/replica codec laws live elsewhere.""" + from faiss.contrib.e_means import EmeansShardedCentroids + from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer + + check, rank = unittest.TestCase(), dist.get_rank(group) + base = torch.tensor([1+2**-10, 1+2**-9, 3+2**-10, 3+2**-9], device=device)[:, None].repeat(3, 1) + anchors = torch.tensor([1., 3., 4., 8.], device=device)[:, None] + capability = torch.tensor(torch.cuda.get_device_capability(device), dtype=torch.int64, device=device) + peers = [torch.empty_like(capability) for _ in range(dist.get_world_size(group))] + dist.all_gather(peers, capability, group=group) + capabilities = [tuple(peer.cpu().tolist()) for peer in peers] + cases = [('default', 'native'), ('default_mixed', 'native'), + ('fp32', 'native'), ('fp16', 'native'), ('bf16', 'native'), + ('cast_fp16', 'native'), ('cast_bf16', 'native'), + ('center_fp16', 'native'), ('center_bf16', 'native'), + ('fp8', 'triton'), ('fp8', 'cute'), ('native_fp8', 'triton'), + ('int8', 'triton'), ('raw_int8', 'triton'), ('raw_uint8', 'triton')] + for name, backend in cases: + with check.subTest(codec=name, backend=backend): + rows, initial, q = base.clone(), anchors.clone(), None + if name.startswith(('cast_', 'center_')): + dtype = torch.float16 if name.endswith('fp16') else torch.bfloat16 + q = CastQuantizer(1, dtype, center=name.startswith('center_')) + if q.center: + rows, initial = rows + 100, initial + 100 + q.train(torch.full((2, 1), 100., device=device)) + elif name in ('fp8', 'int8'): + q = Fp8Quantizer(1) if name == 'fp8' else Int8Quantizer(1) + q.train(torch.cat((rows, initial))) + if name == 'int8' or rank == 1: + rows = q.compute_codes(rows) + elif name in ('raw_int8', 'raw_uint8'): + dtype = torch.int8 if name == 'raw_int8' else torch.uint8 + offset = 0 if name == 'raw_int8' else 128 + rows, initial = (rows + offset).to(dtype), initial + offset + elif not name.startswith('default'): + rows = rows.to({'fp32': torch.float32, 'fp16': torch.float16, + 'bf16': torch.bfloat16, 'native_fp8': torch.float8_e4m3fn}[name]) + if not _shared_codec_route(check, device, name, backend, capabilities, rows, initial, q): + print('SHARED_CODEC_UNAVAILABLE', rank, name, backend, capabilities, flush=True) + continue + options = {} if name.startswith('default') else {'quantizer': q} + if name == 'default_mixed' and rank == 1: + rows = rows.bfloat16() + model = EmeansShardedCentroids(1, 4, group=group, nepochs=2, batch_size=8, + alpha0=.5, seed=7, assignment_chunk_size=6, + assignment_backend=backend, unused_threshold=0.1, + **options) + model.begin(24, initial[2*rank:2*rank+2]) + model.accumulate(rows[:0]) + values_seen = [] + original = model._add_owned + + def observed(values, winner, sums, counts, objective, *extra, **kwargs): + values_seen.append((values.clone(), winner.clone(), model._centroids.clone())) # noqa: B023 + return original(values, winner, sums, counts, objective, *extra, **kwargs) # noqa: B023 + + def totals(dtype): + sums = torch.zeros((2, 1), dtype=dtype, device=device) + counts = torch.zeros(2, dtype=dtype, device=device) + objective = torch.zeros((), dtype=torch.float64, device=device) + for values, winner, snapshot in values_seen: # noqa: B023 + check.assertTrue(bool(((winner >= 0) & (winner < 4)).all())) + for local in range(2): + selected = values[winner == 2*rank+local].to(dtype) + sums[local] += selected.sum(0) + counts[local] += len(selected) + objective += (selected.float()-snapshot[local]).square().sum(dtype=torch.float64) + return sums, counts, objective + + def represented(source): + if q is not None: # noqa: B023 + return q.decode(source if source.dtype == q.dtype else q.compute_codes(source)) # noqa: B023 + return source.bfloat16().float() if name.startswith('default') else source.float() # noqa: B023 + + with mock.patch.object(model, '_add_owned', new=observed): + for epoch in range(2): + for begin in (0, 4, 8): + values_seen.clear() + source = rows[begin:begin+4] + if name == 'default_mixed' and begin: + source = source.to(torch.float16 if rank == 0 else torch.float32) + partial = model.accumulate(source[:1]) + check.assertIsNone(partial['sums']) + stats = model.accumulate(source[1:]) + dtype = torch.int64 if name.startswith('raw_') else torch.float32 + check.assertEqual(stats['n'], 8) + check.assertEqual(stats['sums'].dtype, dtype) + expected = totals(dtype) + for field, wanted in zip(('sums', 'counts', 'objective'), expected): + torch.testing.assert_close(stats[field], wanted, rtol=0, atol=0) + # Widen native FP8 BEFORE sorting; Torch cannot sort FP8. + consumed = torch.cat([v for v, _, _ in values_seen]).to(dtype).flatten().sort().values + wanted = represented(source).to(dtype).repeat(2, 1).flatten().sort().values + torch.testing.assert_close(consumed, wanted, rtol=0, atol=0) + held = None if epoch == 0 else stats['labels'].clone() + model.update(stats) + if held is not None: + torch.testing.assert_close(stats['labels'], held, rtol=0, atol=0) + _detached(model) + model.end_epoch() + check.assertGreater(model.n_splits, 0) + frozen = model.current_centroids().clone() + values_seen.clear() + final = model.final_closing_mean([rows]) + sums, counts, _ = totals(dtype) + mean = (sums.double()/counts.clamp_min(1)[:, None]).float() if dtype is torch.int64 else sums/counts.clamp_min(1)[:, None] + wanted = torch.where((counts > 0)[:, None], mean, frozen) + torch.testing.assert_close(final, wanted, rtol=0, atol=0) + consumed = torch.cat([v for v, _, _ in values_seen]).to(dtype).flatten().sort().values + wanted = represented(rows).to(dtype).repeat(2, 1).flatten().sort().values + torch.testing.assert_close(consumed, wanted, rtol=0, atol=0) + check.assertEqual(model.closing_stats['rows'], 24) + if name == 'center_bf16': + saved_final, saved_closing = final.clone(), dict(model.closing_stats) + # Used-run rejection precedes any explicit-fit communication. + with mock.patch('faiss.contrib.e_means.sharded_centroids.check_codec_fit', + side_effect=AssertionError('repeat begin entered fit agreement')): + with check.assertRaises(RuntimeError): + model.begin(24, initial[2*rank:2*rank+2]) + check.assertFalse(model._failed) + check.assertIs(model.centroids, final) + check.assertEqual(model.closing_stats, saved_closing) + torch.testing.assert_close(final, saved_final, rtol=0, atol=0) + # Extend the existing no-search/-1/empty-receiver closing fixture, not a + # second private model simulator or full codec/replica Cartesian product. + centered = CastQuantizer(1, torch.bfloat16, center=True) + centered.train(torch.full((2, 1), 100., device=device)) + fp8 = Fp8Quantizer(1) + fp8.train(torch.tensor([[0.], [4.], [100.], [200.]], device=device)) + for codec, backend in ((CastQuantizer(1, torch.bfloat16), 'native'), + (centered, 'native'), (fp8, 'cute')): + name = 'fp8' if codec is fp8 else 'center_bf16' if codec is centered else 'cast_bf16' + if not _shared_codec_route(check, device, name, backend, capabilities, base, anchors, codec): + print('SAVED_CODEC_UNAVAILABLE', rank, name, backend, flush=True) + continue + _saved_closing_contracts(group, device, codec, backend) + unequal = CastQuantizer(1, torch.bfloat16, center=True) + unequal.train(torch.full((2, 1), float(rank), device=device)) + model = EmeansShardedCentroids(1, 4, group=group, quantizer=unequal, nepochs=1, batch_size=8) + with check.assertRaises(ValueError): + model.begin(24, anchors[2*rank:2*rank+2]) + check.assertTrue(model._failed) + # Generated seeds must not touch a bad local codec before fit agreement. + codec = Fp8Quantizer(1) if rank == 0 else fp8 + model = EmeansShardedCentroids(1, 4, group=group, quantizer=codec, + assignment_backend='triton', nepochs=1, batch_size=8) + with check.assertRaises(ValueError): + model.train(base) # Omitted initialization; same existing rows/fit. + check.assertTrue(model._failed) + model = EmeansShardedCentroids(1, 4, group=group, nepochs=1, batch_size=8) + model.begin(24, anchors[2*rank:2*rank+2]) + with check.assertRaises(ValueError): + model.accumulate(base[:0].to(torch.float16 if rank == 0 else torch.bfloat16)) + check.assertTrue(model._failed) + with mock.patch.object(model, '_gather_local', + side_effect=AssertionError('failed train entered first-input collective')): + with check.assertRaises(RuntimeError): + model.train(base, init_centroids=anchors[2*rank:2*rank+2]) + check.assertTrue(model._failed) + + +def _replica_default_contracts(group, device): + """Representative changed default; parent replica native/bytes laws remain.""" + rows = torch.tensor([1+2**-10, 1+2**-9, 3+2**-10, 3+2**-9], device=device)[:, None] + initial = torch.tensor([[1.], [3.]], device=device) + for options in ({}, {'quantizer': CastQuantizer(1, torch.bfloat16)}, {'quantizer': None}): + args = dict(nepochs=1, batch_size=8, alpha0=.5, assignment_backend='native', **options) + model = DistributedEmeans(1, 2, group=group, transport='dense', **args) + reference = QuantizedEmeans(1, 2, **args) + for candidate in (model, reference): + candidate.begin(8, initial) + partial = model.accumulate(rows[:1]) + assert partial['sums'] is None + model.update(model.accumulate(rows[1:])) + reference.update(reference.accumulate(torch.cat((rows, rows)))) + model.end_epoch() + reference.end_epoch() + final = model.finalize() + torch.testing.assert_close(final, reference.finalize(), rtol=2e-6, atol=2e-6) + native = 'quantizer' in options and options['quantizer'] is None + represented = rows if native else rows.bfloat16().float() + wanted = torch.stack((represented[:2].mean(0), represented[2:].mean(0))) + torch.testing.assert_close(final, wanted, rtol=0, atol=0) + torch.testing.assert_close(model.obj, reference.obj, rtol=1e-6, atol=1e-5) + centre = CastQuantizer(1, torch.bfloat16, center=True) + centre.train(initial) # Common semantic fit; existing provided GPU rows. + if dist.get_rank(group) == 0: + centre.shift.add_(0) # Same values, but this local frozen-fit token is stale. + model = DistributedEmeans(1, 2, group=group, transport='dense', quantizer=centre, + nepochs=1, batch_size=8, alpha0=.5, assignment_backend='native') + with unittest.TestCase().assertRaises(ValueError): + model.begin(8, initial) + assert model._failed and model.assignments is None + + +def _nccl_worker(rank, world_size, rendezvous, subgroup_only, sharder_only=False): + torch.set_num_threads(1) + torch.cuda.set_device(rank) + device = torch.device("cuda", rank) + subgroup = None + dist.init_process_group("nccl", init_method=rendezvous, rank=rank, + world_size=world_size, timeout=datetime.timedelta(seconds=60)) + try: + if sharder_only == 'codecs': + _shared_codec_contracts(dist.group.WORLD, device) + _replica_default_contracts(dist.group.WORLD, device) + return + if sharder_only == "transport": + _all_gather_contracts(dist.group.WORLD, device) + return + if sharder_only == "saved": + _saved_closing_contracts(dist.group.WORLD, device) + return + if sharder_only: + _sharder_contracts(dist.group.WORLD, device) + elif subgroup_only: + # Every world rank creates the group; global rank0 is not its root + # and never participates in any of its training collectives. + subgroup = dist.new_group([1, 2], timeout=datetime.timedelta(seconds=60)) + if rank in (1, 2): + for transport in ("dense", "sparse"): + _global_totals(subgroup, transport, device) + _training(subgroup, transport, device) + if torch.cuda.get_device_capability(device) in ((8, 0), (9, 0), (10, 0)): + _training(subgroup, "sparse", device, backend="triton", byte_dtype=torch.uint8) + else: + with unittest.TestCase().assertRaisesRegex(ValueError, "group must contain the caller"): + DistributedEmeans(1, 2, group=subgroup) + dist.barrier() + else: + for transport in ("dense", "sparse"): + _global_totals(dist.group.WORLD, transport, device) + _invalid_sizes(dist.group.WORLD, transport, device) + _training(dist.group.WORLD, transport, device) + _global_totals(dist.group.WORLD, "auto", device) + _training(dist.group.WORLD, "dense", device, alpha=1) + # One represented family through both packing/merge paths; avoid + # repeating the assignment-backend/dtype Cartesian product. + for transport in ("dense", "sparse"): + _training(dist.group.WORLD, transport, device, + quantizer=CastQuantizer(2, torch.bfloat16)) + _training(dist.group.WORLD, transport, device, backend="triton") + if torch.cuda.get_device_capability(device) in ((8, 0), (9, 0), (10, 0)): + _integer_external_totals(dist.group.WORLD, transport, device) + for dtype in (torch.int8, torch.uint8): + _training(dist.group.WORLD, transport, device, + backend="triton", byte_dtype=dtype) + q = Int8Quantizer(2) + q.train(_rows(0, 24, device)) + _training(dist.group.WORLD, transport, device, + backend="triton", quantizer=q) + finally: + if subgroup_only and rank in (1, 2) and subgroup is not None: + dist.destroy_process_group(subgroup) + dist.destroy_process_group() + + +class TestDistributedEmeans(unittest.TestCase): + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "Gloo required") + def test_two_cpu_auto_batch_error_names_the_law(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _auto_batch_error_worker, args=(2, "file://" + directory + "/group"), + nprocs=2, join=True, + ) + + @unittest.skipUnless(dist.is_available() and dist.is_gloo_available(), "Gloo required") + def test_two_cpu_sharded_revival(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _revival_worker, args=(2, "file://" + directory + "/group", "gloo"), + nprocs=2, join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_two_gpu_sharded_revival(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _revival_worker, args=(2, "file://" + directory + "/group", "nccl"), + nprocs=2, join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_two_gpu_shared_codec_values_and_closing(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn(_nccl_worker, + args=(2, 'file://' + directory + '/group', False, 'codecs'), nprocs=2, join=True) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_two_gpu_all_gather_batches(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _nccl_worker, + args=(2, "file://" + directory + "/group", False, "transport"), + nprocs=2, join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + def test_two_gpu_saved_closing_mean(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _nccl_worker, + args=(2, "file://" + directory + "/group", False, "saved"), + nprocs=2, join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_two_gpu_sharded_centroids(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _nccl_worker, + args=(2, "file://" + directory + "/group", False, True), + nprocs=2, + join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 2, + "NCCL and two NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_two_gpu_caller_owned_transports(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _nccl_worker, + args=(2, "file://" + directory + "/group", False), + nprocs=2, + join=True, + ) + + @unittest.skipUnless(NCCL_SM80 and torch.cuda.device_count() >= 3, + "NCCL and three NVIDIA SM80+ GPUs required") + @unittest.skipUnless(_nvidia_sm80_triton(), "NVIDIA SM80 or later GPU and Triton required") + def test_three_gpu_nonzero_global_root(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _nccl_worker, + args=(3, "file://" + directory + "/group", True), + nprocs=3, + join=True, + ) + + @unittest.skipUnless( + torch.cuda.is_available() + and (getattr(torch.version, "hip", None) is not None + or torch.cuda.get_device_capability() < (8, 0)), + "a GPU other than NVIDIA SM80 or later required", + ) + def test_bf16_without_sm80_names_the_cause(self): + with self.assertRaisesRegex(RuntimeError, "SM80"): + QuantizedEmeans(2, 1, quantizer=CastQuantizer(2, torch.bfloat16)).train( + torch.zeros((2, 2), device="cuda")) + + def test_auto_sharder_chunk_bound_is_independent_of_compute_backend(self): + from types import SimpleNamespace + from faiss.contrib.e_means import Emeans, EmeansShardedCentroids + from faiss.contrib.e_means.torch_backend import TorchBackend, TritonBackend, CuteBackend + + state = SimpleNamespace(device=torch.device("cuda"), is_cuda=True, shape=(4096, 128)) + native = Emeans(128, 4096, assignment_backend="native") + native._centroids = state + model = EmeansShardedCentroids.__new__(EmeansShardedCentroids) + model.d, model.k, model.centroid_chunk_size = native.d, native.k, native.centroid_chunk_size + model.assignment_chunk_size = native.assignment_chunk_size + model._centroids, model.centroids = state, None + model.assignment_backend = "auto" + expected_native_bound = native._get_assignment_chunk_size() + for cls in (TorchBackend, TritonBackend, CuteBackend): + model._execution_backend = cls(model.centroid_chunk_size) + self.assertEqual(model._get_assignment_chunk_size(), expected_native_bound) + for requested, cls in (("native", TorchBackend), ("triton", TritonBackend), ("cute", CuteBackend)): + control = Emeans(native.d, native.k, assignment_backend=requested, + centroid_chunk_size=native.centroid_chunk_size) + control._centroids = state + control._execution_backend = cls(control.centroid_chunk_size) + model.assignment_backend = requested + model._execution_backend = cls(model.centroid_chunk_size) + self.assertEqual(model._get_assignment_chunk_size(), control._get_assignment_chunk_size()) + model.assignment_backend, model.assignment_chunk_size = "auto", 37 + self.assertEqual(model._get_assignment_chunk_size(), 37) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_floating_revival.py b/thirdparty/faiss/tests/torch_test_e_means_floating_revival.py new file mode 100644 index 000000000..46578997a --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_floating_revival.py @@ -0,0 +1,562 @@ +# 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. + +"""Local floating revival, decoded statistics and caller batch contracts.""" + +import unittest +from unittest import mock + +import torch + +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.e_means_torch import Emeans +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer +from faiss.contrib.e_means.quantizer_fp8 import Fp8Quantizer +from faiss.contrib.e_means.torch_backend import CuteBackend, TritonBackend + + +def _reference(codes, values, centroids, axes, dtype, quantizer, spherical=False): + """Direct FP64 represented-distance and decoded Oja reference.""" + represented = quantizer.compute_codes(centroids) if quantizer is not None else ( + centroids.round().clamp(-128 if dtype == torch.int8 else 0, 127 if dtype == torch.int8 else 255) + if dtype in (torch.int8, torch.uint8) else centroids) + represented = represented.to(dtype).cpu().double() + rows = codes.cpu().double() + distance = (-2 * rows @ represented.T if spherical else + (rows[:, None] - represented[None]).square().sum(2)) + order = torch.argsort(distance, dim=1, stable=True) + labels = order[:, 0] + margin = distance.gather(1, order[:, 1:2]) - distance.gather(1, order[:, :1]) + if isinstance(quantizer, (Int8Quantizer, Fp8Quantizer)): + margin *= 2.**(-2 * quantizer.exponent) + y = values.cpu().double() - centroids.cpu().double()[labels] + p = (y * axes.cpu().double()[labels]).sum(1, keepdim=True) + sums = torch.zeros_like(centroids, device="cpu", dtype=torch.float64) + sums.index_add_(0, labels, values.cpu().double()) + counts = torch.bincount(labels, minlength=len(centroids)).double() + removal = torch.zeros((len(centroids), centroids.shape[1] + 1), dtype=torch.float64) + removal.index_add_(0, labels, torch.cat((p * y, margin), dim=1)) + return sums, counts, removal, labels + + +class _CodeOffset(CastQuantizer): + def compute_codes(self, rows): + return super().compute_codes(rows) + .25 + + +class _DecodedOffset(CastQuantizer): + def decode(self, codes): + return super().decode(codes) + codes.new_tensor([.5, -.25, .125], dtype=torch.float32) + + +def _check_host_split_closing(case, device, dtype): + rows = torch.tensor( + [0., 100., 1., 101., 2., 102., 3., 103., 4., 104., 2., 102.], + device=device, dtype=dtype, + )[:, None] + initial = torch.tensor([[0.], [100.], [110.]], device=device) + results = [] + for cls in (Emeans, QuantizedEmeans): + options = {"quantizer": None} if cls is QuantizedEmeans else {} + model = cls(1, 3, nepochs=1, batch_size=2, alpha0=.5, seed=7, + assignment_backend="native", **options) + # QuantizedEmeans uses the baseline search route; compare that same + # route in Emeans, with one controlled closing-pass split at step five. + model._second_labels_supported = lambda: False + model._choose_splits = lambda rng: ( + torch.tensor([0], device=device), torch.tensor([1], device=device)) + recorded = {} + finish = model._handover_finish + + def observe(order, n, *, model=model, finish=finish, recorded=recorded): + h = model._handover + recorded.update(moved_at=h["moved_at"].clone(), events=len(h["events"])) + result = finish(order, n) + recorded.update(sums=model._pass_sums.clone(), counts=model._pass_counts.clone()) + return result + + model._handover_finish = observe + centroids, labels = model.train(rows, initial) + case.assertEqual(model.recipe["closing_handover"], "search") + case.assertEqual(recorded["events"], 1) + torch.testing.assert_close(recorded["moved_at"], + torch.tensor([-1, 10, -1], device=device), rtol=0, atol=0) + case.assertEqual(model.closing_handover_stats, {"searched": 5}) + # Baseline final-pass counts are explicitly FP64, while this fixture's + # FP32 initial state keeps FP32 sum storage on both devices. + expected_counts = torch.bincount(labels, minlength=3).double() + expected_sums = torch.zeros_like(centroids).index_add_(0, labels, rows.float()) + case.assertEqual(recorded["sums"].dtype, torch.float32) + torch.testing.assert_close(recorded["counts"], expected_counts, rtol=0, atol=0) + torch.testing.assert_close(recorded["sums"], expected_sums, rtol=0, atol=0) + populated = expected_counts > 0 + torch.testing.assert_close(centroids[populated], + (expected_sums[populated] / expected_counts[populated, None]).float(), + rtol=0, atol=0) + results.append((centroids, labels)) + torch.testing.assert_close(results[0][0], results[1][0], rtol=0, atol=0) + torch.testing.assert_close(results[0][1], results[1][1], rtol=0, atol=0) + + +class TestFloatingRevivalCPU(unittest.TestCase): + def test_native_host_split_closing_matches_floating_search(self): + _check_host_split_closing(self, "cpu", torch.float32) + + def test_stock_cast_reuse_preserves_decoder_and_matrix_overrides(self): + for dtype in (torch.float16, torch.bfloat16): + with self.subTest(dtype=dtype): + codes = torch.tensor([[.25, .5], [1., 2.]], dtype=dtype) + q = CastQuantizer(2, dtype) + model = QuantizedEmeans(2, 2, quantizer=q) + reused = model._statistics_rows(codes) + torch.testing.assert_close(reused.float(), codes.float(), rtol=0, atol=0) + self.assertEqual(reused.data_ptr(), codes.data_ptr()) + seen = [] + + def custom_decode(values, *, seen=seen): + seen.append("decode") + return values.float() + 1 + + with mock.patch.object(q, "decode", custom_decode): + torch.testing.assert_close(model._statistics_rows(codes), codes.float() + 1, rtol=0, atol=0) + matrix = q._matrix + + def custom_matrix(values, *, matrix=matrix, seen=seen, **kwargs): + seen.append("matrix") + return matrix(values, **kwargs) + 1 + + with mock.patch.object(q, "_matrix", custom_matrix): + torch.testing.assert_close(model._statistics_rows(codes), codes.float() + 1, rtol=0, atol=0) + self.assertFalse(model._replay_representation_eligible()) + self.assertEqual(seen, ["decode", "matrix"]) + + def test_native_cpu_partial_batches_reference_and_natural_split(self): + # Torch CPU only: no native Faiss arithmetic or CUDA codec claim. + initial = torch.tensor([[0., 0., 0.], [4., 0., 0.], [8., 0., 0.], [12., 0., 0.]]) + ids = torch.arange(25) + rows = initial[2].expand(25, -1) + torch.stack((.125 + .125 * (ids % 3), + .125 * (ids % 2), -.125 * (ids % 3)), 1) + kwargs = dict(nepochs=1, batch_size=5, alpha0=.5, seed=7, assignment_backend="native", + assignment_chunk_size=3) + actual = QuantizedEmeans(3, 4, quantizer=None, **kwargs) + reference = Emeans(3, 4, **kwargs) + for model in (actual, reference): + model.begin(25, initial) + model.accumulate(rows[:0]) + self.assertEqual(model._input_dtype, torch.float32) + self.assertIsNotNone(model._removal_stats) + self.assertIsNone(model.recipe["unused_threshold"]) + observed = {} + apply = actual._apply_splits + + def observed_split(source, target): + observed.update(source=source.clone(), target=target.clone(), + centroids=actual._centroids.clone(), usage=actual._usage.clone(), + removal=actual._removal_stats.clone(), axes=actual._axes.clone()) + return apply(source, target) + + with mock.patch.object(actual, "_apply_splits", observed_split): + for step, begin in enumerate(range(0, 25, 5)): + batch = rows[begin:begin + 5] + previous = actual._removal_stats.clone() + c, a = actual._centroids.clone(), actual._axes.clone() + sums, counts, removal, _ = _reference(batch, batch, c, a, torch.float32, None) + partial = actual.accumulate(batch[:1]) + self.assertIsNone(partial["sums"]) + self.assertEqual(actual.accumulate(batch[:0])["n"], 1) + torch.testing.assert_close(actual._centroids, c, rtol=0, atol=0) + torch.testing.assert_close(actual._axes, a, rtol=0, atol=0) + stats = actual.accumulate(batch[1:]) + torch.testing.assert_close(stats["sums"].double(), sums, rtol=0, atol=0) + torch.testing.assert_close(stats["counts"].double(), counts, rtol=0, atol=0) + torch.testing.assert_close(stats["removal"].double(), removal, rtol=1e-5, atol=1e-5) + from faiss.contrib.e_means.base import _scheduled_alpha + alpha = _scheduled_alpha(actual.recipe["alpha0"], step, actual.recipe["total_steps"]) + expected = previous.double() * (1 - alpha) + removal * alpha + actual.update(stats) + reference.update(reference.accumulate(batch)) + # The fifth update performs the real standard revival check; + # compare the pre-split EMA before verifying its transfer. + checked = observed["removal"] if step == 4 else actual._removal_stats + torch.testing.assert_close(checked.double(), expected, rtol=1e-5, atol=1e-5) + self.assertEqual(actual._step, step + 1) + self.assertFalse(bool(actual._batch_removal.any())) + for name in ("_centroids", "_usage", "_removal_stats", "_axes", "_pass_sums", "_pass_counts"): + torch.testing.assert_close(getattr(actual, name), getattr(reference, name), rtol=1e-5, atol=1e-5) + self.assertTrue(observed) + self.assertGreater(actual.n_splits, 0) + source, target = observed["source"], observed["target"] + expected = observed["removal"].clone() + expected[source] /= 2 + expected[target] = expected[source] + torch.testing.assert_close(actual._removal_stats, expected, rtol=0, atol=0) + torch.testing.assert_close(actual._axes[target], observed["axes"][source], rtol=0, atol=0) + torch.testing.assert_close(actual._usage[target], observed["usage"][source] / 2, rtol=0, atol=0) + for model in (actual, reference): + model.end_epoch() + model.finalize() + torch.testing.assert_close(actual.centroids, reference.centroids, rtol=1e-5, atol=1e-5) + centered = CastQuantizer(3, torch.bfloat16, center=True) + centered.train(initial) + with self.assertRaisesRegex(ValueError, "CPU E-means requires quantizer=None"): + QuantizedEmeans(3, 4, quantizer=centered).begin(25, initial) + + +@unittest.skipUnless(torch.cuda.is_available() and not torch.version.hip, "NVIDIA CUDA required") +class TestFloatingRevivalCUDA(unittest.TestCase): + def test_fp16_host_split_closing_matches_floating_search(self): + _check_host_split_closing(self, "cuda", torch.float16) + + def test_decoded_logical_batches_match_independent_statistics(self): + initial = torch.tensor([[-4., 0., 0.], [0., 1., 0.], [4., -1., 0.], [12., 0., 1.]], device="cuda") + ids = torch.arange(13, device="cuda") + rows = initial[ids % 4] + torch.stack((.125 + .125 * (ids % 3), + .125 * (ids % 2), -.125 * (ids % 3)), 1) + cases = [("native", dtype, kind) for dtype, kind in + ((torch.float32, "native"), (torch.float16, "native"), (torch.bfloat16, "native"), + (torch.float16, "cast"), (torch.bfloat16, "cast"), + (torch.float16, "centered"), (torch.bfloat16, "centered"), + (torch.bfloat16, "custom"), (torch.bfloat16, "spherical"))] + cases += [("triton", dtype, kind) for _, dtype, kind in cases] + if torch.cuda.get_device_capability() == (9, 0): + cases += [("cute", torch.bfloat16, kind) for kind in ("cast", "centered", "custom", "spherical")] + cap = torch.cuda.get_device_capability() + encoded = [(torch.int8, "int8"), (torch.int8, "int8_cal")] if cap in ((8, 0), (9, 0), (10, 0)) else [] + if cap in ((9, 0), (10, 0), (10, 3)): + encoded += [(torch.float8_e4m3fn, "fp8"), (torch.float8_e4m3fn, "fp8_cal")] + cases += [(backend, dtype, kind) for dtype, kind in encoded + for backend in (("triton", "cute") if cap == (9, 0) else ("triton",))] + for backend, dtype, kind in cases: + with self.subTest(backend=backend, dtype=dtype, kind=kind): + if dtype == torch.bfloat16 and torch.cuda.get_device_capability() < (8, 0): + self.skipTest("BF16 requires NVIDIA SM80 or later") + q = None if kind in ("native", "int8", "fp8", "int8_cal", "fp8_cal") else ( + _DecodedOffset(3, dtype) if kind == "custom" else CastQuantizer(3, dtype, center=kind == "centered")) + source, seeds = (rows * 8, initial * 8) if kind == "int8" else (rows, initial) + if kind.endswith("_cal"): + q = (Int8Quantizer if kind == "int8_cal" else Fp8Quantizer)(3) + q.train(torch.cat((rows, initial))) + if kind == "centered": + shift = initial.new_tensor([100., -50., 30.]) + q.train(torch.stack((shift - 1, shift + 1))) + source, seeds = rows + shift, initial + shift + if kind == "spherical": + source = torch.nn.functional.normalize(source, dim=1) + seeds = torch.nn.functional.normalize(seeds, dim=1) + codes = source.to(dtype) if q is None else q.compute_codes(source) + values = codes.float() if q is None else q.decode(codes) + source = codes if kind == "int8_cal" else source + models = [QuantizedEmeans(3, 4, nepochs=1, batch_size=5, alpha0=.6, seed=7, + quantizer=q, assignment_backend=backend, assignment_chunk_size=3, + spherical=kind == "spherical") for _ in range(2)] + for model in models: + model.begin(13, seeds) + model.accumulate(codes[:0]) # Typed empty input resolves native policy too. + self.assertIsNotNone(model._removal_stats) + self.assertIsNone(model.recipe["unused_threshold"]) + self.assertEqual(model._input_dtype, dtype) + model._axes.zero_() + model._axes[:, 0] = 1 + model._removal_stats.fill_(.25) + for step, begin in enumerate((0, 5, 10)): + end = min(begin + 5, 13) + c, a = models[0]._readout().clone(), models[0]._axes.clone() + reference = _reference(codes[begin:end], values[begin:end], c, a, dtype, q, kind == "spherical") + previous = models[0]._removal_stats.clone() + stats = [] + for model, partial in zip(models, (False, True)): + unchanged = (model._centroids.clone(), model._axes.clone()) + if partial: + first = model.accumulate(source[begin:begin + 1] if q is not None else codes[begin:begin + 1]) + self.assertIsNone(first["sums"]) + self.assertEqual(model.accumulate(codes[begin:begin])["n"], 1) + for name, expected in zip(("_centroids", "_axes"), unchanged): + torch.testing.assert_close(getattr(model, name), expected, rtol=0, atol=0) + batch = model.accumulate(codes[begin + 1:end]) + else: + batch = model.accumulate(source[begin:end] if q is not None else codes[begin:end]) + sums, counts, removal, _ = reference + torch.testing.assert_close(batch["sums"].cpu().double(), sums, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(batch["counts"].cpu().double(), counts, rtol=0, atol=0) + torch.testing.assert_close(batch["removal"].cpu().double(), removal, rtol=1e-5, atol=1e-5) + stats.append(batch) + from faiss.contrib.e_means.base import _scheduled_alpha + alpha = _scheduled_alpha(models[0].recipe["alpha0"], step, models[0].recipe["total_steps"]) + expected = previous.cpu().double() * (1 - alpha) + alpha * reference[2] + for model, batch in zip(models, stats): + model.update(batch) + self.assertEqual(model._step, step + 1) + torch.testing.assert_close(model._removal_stats.cpu().double(), expected, rtol=1e-5, atol=1e-5) + direction = expected[:, :-1] + direction = direction / direction.norm(dim=1, keepdim=True) + torch.testing.assert_close(model._axes.cpu().double(), direction, rtol=1e-5, atol=1e-5) + self.assertFalse(bool(model._batch_removal.any())) + for name in ("_centroids", "_usage", "_removal_stats", "_axes", "_pass_sums", "_pass_counts"): + torch.testing.assert_close(getattr(models[0], name), getattr(models[1], name), rtol=1e-5, atol=1e-5) + for model in models: + model.end_epoch() + model.finalize() + + def test_live_split_hooks_are_honored_after_device_admission(self): + initial = torch.tensor([[-4., 0.], [0., 0.], [4., 0.], [12., 0.]], device="cuda") + for dtype in (torch.float32, torch.bfloat16): + with self.subTest(dtype=dtype): + if dtype == torch.bfloat16 and torch.cuda.get_device_capability() < (8, 0): + self.skipTest("BF16 requires NVIDIA SM80 or later") + model = QuantizedEmeans(2, 4, nepochs=1, batch_size=4, quantizer=None, + assignment_backend="triton") + model.begin(20, initial) + model.accumulate(initial[:0].to(dtype)) + self.assertTrue(model._device_check()) + model._removal_stats.copy_(initial.new_tensor([[0., 0., 0.], [3., 0., 10.], + [0., 0., 0.], [2., 0., 10.]])) + model._usage.fill_(1) + calls = [] + apply, separate = model._apply_splits, model._separate_split_values + state = model._execution_backend.removal_split + + def observed_apply(source, target, *, apply=apply, calls=calls): + calls.append("apply") + return apply(source, target) + + def observed_separate(donor, child, *, calls=calls, separate=separate): + calls.append("separate") + return separate(donor, child) + + def observed_state(*args, calls=calls, state=state): + calls.append("state") + return state(*args) + + with mock.patch.object(model, "_apply_splits", observed_apply), \ + mock.patch.object(model, "_separate_split_values", observed_separate), \ + mock.patch.object(model._execution_backend, "removal_split", observed_state): + self.assertFalse(model._device_check()) + self.assertEqual(model._revive_unused(model._split_rng), 2) + self.assertEqual(calls, ["apply", "separate", "state"]) + self.assertEqual(model.n_splits, 2) + torch.testing.assert_close(model._usage, initial.new_full((4,), .5), rtol=0, atol=0) + + @unittest.skipUnless(torch.cuda.is_available() and torch.cuda.get_device_capability() >= (8, 0), + "BF16 requires NVIDIA SM80 or later") + def test_old_owner_and_update_hooks_receive_decoded_statistics(self): + initial = torch.tensor([[100., -50.], [104., -50.], [112., -50.]], device="cuda") + rows = initial[[0, 1, 2, 0, 1]] + .25 + q = CastQuantizer(2, torch.bfloat16, center=True) + q.train(torch.tensor([[99., -51.], [101., -49.]], device="cuda")) + codes = q.compute_codes(rows) + seen = [] + + class OldOwner(TritonBackend): + def accumulate_removal(self, values, labels, stats, distance, second, axes, centroids, removal): + seen.append(values.clone()) + return super().accumulate_removal(values, labels, stats, distance, second, axes, centroids, removal) + + class UpdateObserved(QuantizedEmeans): + def _update_removal_statistics(self, alpha, decay): + self.updates += 1 + return super()._update_removal_statistics(alpha, decay) + + model = UpdateObserved(2, 3, nepochs=1, batch_size=5, alpha0=.5, quantizer=q, + assignment_backend="triton", assignment_chunk_size=5) + model.updates = 0 + model.begin(10, initial) + model.accumulate(codes[:0]) + model._execution_backend = OldOwner(model.centroid_chunk_size) + expected = _reference(codes, q.decode(codes), model._centroids, model._axes, q.dtype, q) + # This is the same fold-capable private call used by graph capture; + # the actual update hook must still run exactly once at update(). + batch = model._accumulate_core(codes, ema=(model._removal_stats, .5, .5)) + self.assertFalse(model._removal_folded) + self.assertFalse(model._capture_operations_match()) + self.assertEqual(len(seen), 1) + torch.testing.assert_close(seen[0], q.decode(codes), rtol=0, atol=0) + torch.testing.assert_close(batch["removal"].cpu().double(), expected[2], rtol=1e-5, atol=1e-5) + model.update(batch) + self.assertEqual(model.updates, 1) + torch.testing.assert_close(model._removal_stats.cpu().double(), expected[2] * .5, rtol=1e-5, atol=1e-5) + + @unittest.skipUnless(torch.cuda.is_available() and torch.cuda.get_device_capability() >= (8, 0), + "BF16 requires NVIDIA SM80 or later") + def test_ordinary_accumulation_owner_receives_decoded_rows(self): + initial = torch.tensor([[100., -50.], [104., -50.], [112., -50.]], device="cuda") + rows = initial[[0, 1, 2, 0, 1]] + .25 + q = CastQuantizer(2, torch.bfloat16, center=True) + q.train(torch.tensor([[99., -51.], [101., -49.]], device="cuda")) + codes = q.compute_codes(rows) + base = CuteBackend if torch.cuda.get_device_capability() == (9, 0) else TritonBackend + seen = [] + + class SumOwner(base): + def accumulate(self, values, labels, stats, batch_size, indexed=False): + seen.append(values.clone()) + return super().accumulate(values, labels, stats, batch_size, indexed) + + model = QuantizedEmeans(2, 3, nepochs=1, batch_size=5, quantizer=q, + assignment_backend=base.name, assignment_chunk_size=5) + model.begin(10, initial) + model.accumulate(codes[:0]) + model._execution_backend = SumOwner(model.centroid_chunk_size) + expected = _reference(codes, q.decode(codes), model._centroids, model._axes, q.dtype, q) + batch = model.accumulate(codes) + self.assertEqual(len(seen), 1) + torch.testing.assert_close(seen[0], q.decode(codes), rtol=0, atol=0) + torch.testing.assert_close(batch["sums"].cpu().double(), expected[0], rtol=0, atol=0) + torch.testing.assert_close(batch["removal"].cpu().double(), expected[2], rtol=1e-5, atol=1e-5) + + @unittest.skipUnless(torch.cuda.is_available() and torch.cuda.get_device_capability() == (9, 0), + "CuTe BF16 requires NVIDIA SM90") + def test_old_cute_owner_keeps_completed_second_on_decoded_rows(self): + # One represented coordinate isolates row-basis/completion ownership; + # the broader floating references cover norm-plus-dot rounding. + initial = torch.tensor([[100.], [104.], [112.]], device="cuda") + rows = initial[[0, 1, 2, 0, 1]] + .25 + q = CastQuantizer(1, torch.bfloat16, center=True) + q.train(torch.tensor([[99.], [101.]], device="cuda")) + codes = q.compute_codes(rows) + seen = [] + + class OldOwner(CuteBackend): + def accumulate_removal(self, values, labels, stats, distance, second, axes, centroids, removal): + seen.append((values.clone(), second.clone())) + return super().accumulate_removal(values, labels, stats, distance, second, axes, centroids, removal) + + model = QuantizedEmeans(1, 3, nepochs=1, batch_size=5, quantizer=q, + assignment_backend="cute", assignment_chunk_size=5) + model.begin(10, initial) + model.accumulate(codes[:0]) + model._execution_backend = OldOwner(model.centroid_chunk_size) + expected = _reference(codes, q.decode(codes), model._centroids, model._axes, q.dtype, q) + batch = model.accumulate(codes) + self.assertEqual(len(seen), 1) + torch.testing.assert_close(seen[0][0], q.decode(codes), rtol=0, atol=0) + direct = (codes.double()[:, None] - q.compute_codes(initial).double()[None]).square().sum(2) + second = direct.sort(dim=1, stable=True).values[:, 1] + torch.testing.assert_close(seen[0][1].double(), second, rtol=0, atol=0) + torch.testing.assert_close(batch["sums"].cpu().double(), expected[0], rtol=0, atol=0) + torch.testing.assert_close(batch["counts"].cpu().double(), expected[1], rtol=0, atol=0) + torch.testing.assert_close(batch["removal"].cpu().double(), expected[2], rtol=1e-5, atol=1e-5) + + def test_fp16_range_and_sums_only_external_update_remain_explicit(self): + initial = torch.full((2, 1), 65504., device="cuda") + for backend in ("native", "triton"): + for quantizer in (None, CastQuantizer(1, torch.float16)): + with self.subTest(backend=backend, quantizer=quantizer): + model = QuantizedEmeans(1, 2, nepochs=1, batch_size=2, quantizer=quantizer, + assignment_backend=backend) + model.begin(4, initial) + model.accumulate(initial[:0].half()) + self.assertIsNotNone(model._removal_stats) + self.assertFalse(model._device_check()) + # Landed Gaussian splits use Oja variance, not a fixed + # perturbation: supply nonzero variance to exercise overflow. + model._usage.fill_(1) + model._removal_stats[:, :-1].copy_(model._axes * 100) + before = model._centroids.clone(), model._usage.clone() + with self.assertRaisesRegex(ValueError, "65504"): + model._apply_splits(torch.tensor([0], device="cuda"), torch.tensor([1], device="cuda")) + torch.testing.assert_close(model._centroids, before[0], rtol=0, atol=0) + torch.testing.assert_close(model._usage, before[1], rtol=0, atol=0) + self.assertEqual(model.n_splits, 0) + with self.assertRaisesRegex(ValueError, "from this model's accumulate"): + model.update(dict(sums=torch.zeros_like(initial), counts=initial.new_zeros(2), + objective=initial.new_zeros((), dtype=torch.float64), n=2)) + + @unittest.skipUnless(torch.cuda.is_available() and torch.cuda.get_device_capability() >= (8, 0), + "BF16 requires NVIDIA SM80 or later") + def test_centered_closing_repairs_labels_and_rebuilds_decoded_means(self): + # The actual closing loop forces one physical split at the normal + # fifth update. This is a retention/row-basis witness, not a claim + # about which donors the revival algorithm should select. + initial = torch.tensor([[100.25, -49.5], [104.25, -49.5], [112.25, -49.5]], device="cuda") + original_labels = torch.arange(10, device="cuda") % 3 + rows = initial[original_labels] + class ForcedClosingMove(QuantizedEmeans): + def _revive_unused(self, rng): + return self._apply_splits( + torch.tensor([2], device="cuda"), torch.tensor([1], device="cuda")) + + def finalize(self): + self.before_sums = self._pass_sums.clone() + self.before_counts = self._pass_counts.clone() + self.split_positions = self._centroids.clone() + return super().finalize() + + backends = ("native", "triton", "cute") if torch.cuda.get_device_capability() == (9, 0) else ("native", "triton") + for backend in backends: + kinds = ("centered", "cast", "int8_cal", "int8", "custom") if backend != "native" else ("centered", "cast") + for kind in kinds: + with self.subTest(backend=backend, kind=kind): + q = (Int8Quantizer(2) if kind == "int8_cal" else None if kind == "int8" else + _CodeOffset(2, torch.bfloat16) if kind == "custom" else + CastQuantizer(2, torch.bfloat16, center=kind == "centered")) + source, seeds = (rows - initial.new_tensor([100., -50.]), initial - initial.new_tensor([100., -50.])) if kind == "int8" else (rows, initial) + if kind == "int8": + source = source.round().to(torch.int8) + elif kind == "cast": + source = rows + .03125 # Not exactly BF16-representable at this origin. + storage = source.new_empty((20, 2)) + storage[::2] = source + source = storage[::2] # Row-strided, unit inner stride. + if kind == "centered": + q.train(torch.tensor([[99., -51.], [101., -49.]], device="cuda")) + elif kind == "int8_cal": + q.train(torch.tensor([[36., -114.], [164., 14.]], device="cuda")) + elif q is not None: + q.train(torch.cat((source.float(), seeds))) + codes = source if q is None else q.compute_codes(source) + decoded = codes.float() if q is None else q.decode(codes) + model = ForcedClosingMove(2, 3, nepochs=1, batch_size=2, alpha0=.5, + assignment_chunk_size=2, assignment_backend=backend, + seed=7, quantizer=q) + with mock.patch("faiss.contrib.e_means.e_means_torch._HANDOVER_CHUNK", 4): + centroids, labels = model.train(codes if kind == "int8_cal" else source, seeds) + self.assertEqual(model.recipe["total_steps"], 5) + self.assertEqual(model.n_splits, 1) + repaired = model.closing_handover_stats + self.assertGreater(repaired.get("searched", 0) + repaired.get("second", 0), 0) + sums = torch.zeros_like(model.before_sums) + sums.index_add_(0, labels, decoded.to(sums.dtype)) + counts = torch.bincount(labels, minlength=3).to(model.before_counts) + torch.testing.assert_close(model.before_sums, sums, rtol=0, atol=0) + torch.testing.assert_close(model.before_counts, counts, rtol=0, atol=0) + self.assertEqual(model.before_counts.sum().item(), len(rows)) + expected = model.split_positions.clone() + populated = counts > 0 + expected[populated] = (sums[populated] / counts[populated, None]).float() + torch.testing.assert_close(centroids, expected, rtol=0, atol=0) + + def test_actual_cast_closing_rounds_twin_decisions(self): + for dtype, bits in ((torch.bfloat16, 7), (torch.float16, 10)): + centered = CastQuantizer(1, dtype, center=True) + centered.train(torch.zeros(2, 1, device="cuda")) + for q in (CastQuantizer(1, dtype), centered): + with self.subTest(dtype=dtype, centered=q.center): + ulp = 2.**(-bits-1) # Spacing immediately below one. + rows = torch.tensor([[0.], [1 - .375 * ulp]], device="cuda") + centers = torch.tensor([[1 - .5 * ulp], [1.]], device="cuda") + self.assertEqual((rows[1] - centers[:, 0]).abs().argmin().item(), 0) + self.assertEqual((rows.to(dtype)[1].float() - centers[:, 0]).abs().argmin().item(), 1) + model = QuantizedEmeans(1, 2, quantizer=q, assignment_backend="triton", + nepochs=1, batch_size=2) + model.begin(2, centers) + model._prepare_input(rows) + labels = torch.tensor([0, 1], device="cuda") + model._handover_start(labels, rows, second=False) + model._handover["moved_at"].copy_(torch.tensor([1, -1], device="cuda")) + model._handover["events"] = [(torch.tensor([0], device="cuda"), + torch.tensor([1], device="cuda"), None, 1)] + model._pass_sums.copy_(rows.new_tensor([[0.], [1.]])) + model._pass_counts.fill_(1) + # Staged order [1,0] maps local rows [0,1]; wrong indexing + # reads the zero decoy for the twin and changes its label. + model._handover_finish(torch.tensor([1, 0], device="cuda"), 2) + self.assertEqual(labels.tolist(), [0, 1]) + torch.testing.assert_close(model._pass_sums, rows.new_tensor([[0.], [1.]]), rtol=0, atol=0) + torch.testing.assert_close(model._pass_counts, model._pass_counts.new_ones(2), rtol=0, atol=0) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_grouping.py b/thirdparty/faiss/tests/torch_test_e_means_grouping.py new file mode 100644 index 000000000..6bb40fbb5 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_grouping.py @@ -0,0 +1,265 @@ +# 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. + +"""Focused optional-import, grouping, capture and storage-ownership checks.""" + +import gc +import importlib.util +import importlib.metadata +from pathlib import Path +import subprocess +import sys +import unittest +from unittest import mock +import weakref +import warnings + +import torch + +PATH = Path(importlib.util.find_spec( + 'faiss.contrib.e_means.e_means_grouping').origin).resolve() +spec = importlib.util.spec_from_file_location('owned_e_means_grouping', PATH) +grouping = importlib.util.module_from_spec(spec) +spec.loader.exec_module(grouping) + + +class TestGroupingCPU(unittest.TestCase): + def test_import_without_torch_numpy_or_cuda(self): + code = '''import builtins, importlib.util, sys, warnings +original = builtins.__import__ +def guarded(name, *args, **kwargs): + if name.split('.')[0] in ('torch', 'numpy', 'cuda'): + raise AssertionError('eager optional import: ' + name) + return original(name, *args, **kwargs) +builtins.__import__ = guarded +with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter('always') + spec = importlib.util.spec_from_file_location('isolated_grouping', sys.argv[1]) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) +assert not seen +''' + subprocess.run([sys.executable, '-c', code, str(PATH)], check=True) + + def test_provider_present_absent_warn_once_and_broken_propagates(self): + def reset(): + grouping._grouping_provider.cache_clear() + grouping._provider_warning_emitted = False + + try: + reset() + present = mock.Mock(CountingIterator=object(), SortOrder=object(), + make_lower_bound=object(), make_radix_sort=object()) + with mock.patch.object(grouping.importlib, 'import_module', return_value=present) as imported, \ + mock.patch.object(grouping.importlib.metadata, 'version') as version, \ + warnings.catch_warnings(record=True) as seen: + warnings.simplefilter('always') + self.assertEqual(grouping.selected_grouping_provider(warn=True), 'cuda.compute') + self.assertEqual(grouping.selected_grouping_provider(warn=True), 'cuda.compute') + imported.assert_called_once_with('cuda.compute') + version.assert_not_called() + self.assertFalse(seen) + + reset() + with mock.patch.object(grouping.importlib, 'import_module', return_value=object()), \ + self.assertRaisesRegex(ImportError, 'missing required grouping API.*tested 1.2.0'): + grouping.selected_grouping_provider(warn=True) + + reset() + missing = ModuleNotFoundError('no cuda.compute', name='cuda.compute') + with mock.patch.object(grouping.importlib, 'import_module', side_effect=missing), \ + mock.patch.object(grouping.importlib.metadata, 'version', + side_effect=importlib.metadata.PackageNotFoundError), \ + warnings.catch_warnings(record=True) as seen: + warnings.simplefilter('always') + self.assertEqual(grouping.selected_grouping_provider(warn=True), 'torch') + self.assertEqual(grouping.selected_grouping_provider(warn=True), 'torch') + self.assertEqual(len(seen), 1) + self.assertIs(seen[0].category, RuntimeWarning) + self.assertIn('~0.6–2.4%', str(seen[0].message)) + self.assertIn('Install cuda-cccl', str(seen[0].message)) + + reset() + with mock.patch.object(grouping.importlib, 'import_module', side_effect=missing), \ + mock.patch.object(grouping.importlib.metadata, 'version', return_value='1.2.0'), \ + self.assertRaisesRegex(ImportError, 'cuda-cccl 1.2.0.*tested 1.2.0') as caught: + grouping.selected_grouping_provider(warn=True) + self.assertIs(caught.exception.__cause__, missing) + + reset() + broken = ModuleNotFoundError('broken CCCL child import', name='cccl.bindings') + with mock.patch.object(grouping.importlib, 'import_module', side_effect=broken), \ + mock.patch.object(grouping.importlib.metadata, 'version') as version, \ + self.assertRaises(ModuleNotFoundError) as caught: + grouping.selected_grouping_provider(warn=True) + self.assertIs(caught.exception, broken) + version.assert_not_called() + + reset() + broken = ImportError('installed CCCL ABI failure') + with mock.patch.object(grouping.importlib, 'import_module', side_effect=broken), \ + self.assertRaises(ImportError) as caught: + grouping.selected_grouping_provider(warn=True) + self.assertIs(caught.exception, broken) + finally: + reset() + + def test_host_group_count_and_cpu_input_guards(self): + keys = torch.zeros(4, dtype=torch.int32) + with mock.patch.dict(sys.modules, {'cuda.compute': None}): + for count in (True, 1.5, torch.tensor(2)): + with self.assertRaises(TypeError): + grouping.prepare_grouping(keys, count) + for count in (0, -1, 2**31): + with self.assertRaises(ValueError): + grouping.prepare_grouping(keys, count) + for values in (keys, keys.long(), keys.reshape(2, 2), keys[:0]): + with self.assertRaises(ValueError): + grouping.prepare_grouping(values, 2) + # A cached descriptor must expose the live buffer without owning it. + tensor = torch.zeros(4, dtype=torch.int32) + owners = (tensor,) + ref = weakref.ref(tensor) + descriptor = grouping._array(tensor) + pointer = tensor.data_ptr() + self.assertEqual(descriptor.data_ptr(), pointer) + self.assertEqual(descriptor.__cuda_array_interface__['data'][0], pointer) + self.assertEqual(descriptor.__cuda_array_interface__['shape'], tuple(tensor.shape)) + del tensor + self.assertIsNotNone(ref()) + del owners + gc.collect() + self.assertIsNone(ref()) + + +@unittest.skipUnless(torch.cuda.is_available(), 'requires CUDA') +class TestGroupingCUDA(unittest.TestCase): + def check_reference(self, handle, values, groups, device): + order = handle.order.cpu().tolist() + expected_offsets = [sum(value < group for value in values) for group in range(groups + 1)] + self.assertEqual(sorted(order), list(range(len(values)))) + ordered_keys = [values[index] for index in order] + self.assertTrue(all(left <= right for left, right in zip(ordered_keys, ordered_keys[1:]))) + self.assertEqual(handle.offsets.cpu().tolist(), expected_offsets) + self.assertEqual(handle.order.dtype, torch.int32) + self.assertEqual(handle.offsets.dtype, torch.uint64) + self.assertEqual(tuple(handle.order.shape), (len(values),)) + self.assertEqual(tuple(handle.offsets.shape), (groups + 1,)) + self.assertEqual(handle.order.device, device) + self.assertEqual(handle.offsets.device, device) + self.assertTrue(handle.order.is_contiguous() and handle.offsets.is_contiguous()) + + def test_ties_empty_groups_current_stream_and_accounting(self): + values, groups = [2, 0, 2, 3, 0], 5 + backing = torch.tensor([99] + values + [99], dtype=torch.int32, device='cuda') + keys = backing[1:-1] + handle = grouping.prepare_grouping(keys, groups) + self.assertEqual(handle.provider, grouping.selected_grouping_provider()) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + order, offsets = grouping.launch_grouping(handle) + stream.synchronize() + for actual, expected in ((order, handle.order), (offsets, handle.offsets)): + self.assertEqual(actual.dtype, expected.dtype) + self.assertEqual(actual.device, keys.device) + self.assertEqual(tuple(actual.shape), tuple(expected.shape)) + self.assertTrue(actual.is_contiguous()) + self.assertEqual(actual.data_ptr(), expected.data_ptr()) + self.assertEqual(actual.untyped_storage().data_ptr(), expected.untyped_storage().data_ptr()) + self.check_reference(handle, values, groups, keys.device) + borrowed_storage = (keys.device, keys.untyped_storage().data_ptr()) + storages = {(storage.device, storage.data_ptr()): storage.nbytes() + for storage in (tensor.untyped_storage() for tensor in handle.tensors)} + owned_storages = {identity: size for identity, size in storages.items() + if identity != borrowed_storage} + self.assertEqual(handle.workspace_bytes, sum(owned_storages.values())) + for output in (handle.order, handle.offsets): + self.assertIn((output.device, output.untyped_storage().data_ptr()), owned_storages) + self.assertEqual(handle.retained_bytes, sum(storages.values())) + # Current UINT8 buffers are queried scratch; order/prefix roles are I32/U64. + scratch = {(tensor.device, tensor.untyped_storage().data_ptr()): tensor.numel() * tensor.element_size() + for tensor in handle.tensors if tensor.dtype is torch.uint8 + and (tensor.device, tensor.untyped_storage().data_ptr()) != borrowed_storage} + if handle.provider == 'cuda.compute': + self.assertEqual(handle.scratch_bytes, sum(scratch.values())) + else: + self.assertIsNone(handle.scratch_bytes) + self.assertFalse(scratch) + + def test_mutated_capture_fixed_pointers_and_retirement(self): + groups, count = 17, 257 + values = [i % groups for i in range(count)] + keys = torch.tensor(values, dtype=torch.int32, device='cuda') + handle = grouping.prepare_grouping(keys, groups) + pointers = {tensor.data_ptr() for tensor in handle.tensors} + grouping.launch_grouping(handle) + self.check_reference(handle, values, groups, keys.device) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + grouping.launch_grouping(handle) + for values in ([groups - 1] * count, [(3 * i + 2) % groups for i in range(count)]): + keys.copy_(torch.tensor(values, dtype=torch.int32, device='cuda')) + graph.replay() + self.check_reference(handle, values, groups, keys.device) + self.assertEqual(pointers, {tensor.data_ptr() for tensor in handle.tensors}) + refs = [weakref.ref(tensor) for tensor in handle.tensors] + graph.reset() + del graph, keys, handle + gc.collect() + self.assertTrue(all(ref() is None for ref in refs)) + + def test_torch_fallback_stable_stream_capture_failure_and_retirement(self): + groups, count = 17, 257 + values = [(3 * i + 2) % groups for i in range(count)] + keys = torch.empty(count, dtype=torch.int32, device='cuda') + producer, consumer = torch.cuda.Stream(), torch.cuda.Stream() + producer.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(producer): + keys.copy_(torch.tensor(values, dtype=torch.int32, device='cuda')) + consumer.wait_stream(producer) + with mock.patch.object(grouping, '_grouping_provider', return_value='torch'): + handle = grouping.prepare_grouping(keys, groups) + with torch.cuda.stream(consumer): + grouping.launch_grouping(handle) + consumer.synchronize() + self.assertEqual(handle.provider, 'torch') + self.assertEqual(handle.order.cpu().tolist(), + sorted(range(count), key=values.__getitem__)) + self.check_reference(handle, values, groups, keys.device) + pointers = [tensor.data_ptr() for tensor in handle.tensors] + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + grouping.launch_grouping(handle) + for values in ([groups - 1] * count, [(5 * i + 1) % groups for i in range(count)]): + keys.copy_(torch.tensor(values, dtype=torch.int32, device='cuda')) + graph.replay() + self.assertEqual(handle.order.cpu().tolist(), + sorted(range(count), key=values.__getitem__)) + self.check_reference(handle, values, groups, keys.device) + self.assertEqual(pointers, [tensor.data_ptr() for tensor in handle.tensors]) + refs = [weakref.ref(tensor) for tensor in handle.tensors] + graph.reset() + del graph, keys, handle + gc.collect() + self.assertTrue(all(ref() is None for ref in refs)) + + keys = torch.zeros(33, dtype=torch.int32, device='cuda') + with mock.patch.object(grouping, '_grouping_provider', return_value='torch'): + handle = grouping.prepare_grouping(keys, 3) + handle.order.resize_(34) + with self.assertRaisesRegex(ValueError, 'resized or rebound'): + grouping.launch_grouping(handle) + + broken = ImportError('installed CCCL failure at grouped preparation') + keys = torch.zeros(33, dtype=torch.int32, device='cuda') + with mock.patch.object(grouping, '_grouping_provider', side_effect=broken), \ + self.assertRaises(ImportError) as caught: + grouping.prepare_grouping(keys, 3) + self.assertIs(caught.exception, broken) + + +if __name__ == '__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_ivf.py b/thirdparty/faiss/tests/torch_test_e_means_ivf.py new file mode 100644 index 000000000..9a8fd8b54 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_ivf.py @@ -0,0 +1,642 @@ +# 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. + +"""Represented-score oracle and centroid-owner IVF lifecycle checks.""" + +import datetime +import importlib.util +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import numpy as np +import torch +import torch.distributed as dist + +from faiss.contrib.e_means.ivf_flat import IndexIVFFlat, _bucket_sort, _check_int32_count +from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids +from faiss.contrib.e_means.sharded_centroids_ivf import EmeansShardedCentroidsIVF + + +def represented_oracle(queries, candidates): + operands = candidates.half() + scores = (operands.float().square().sum(1)[None] + - 2 * (queries.half().float() @ operands.float().T)) + return scores.min(1) + + +def source_score_bound(test, scores, queries, candidates): + # Independent FP64 operands; bound norm, dot and epilogue FP32 rounding. + q, c = queries.double(), candidates.double() + reference = c.square().sum(1)[None] - 2 * (q @ c.T) + labels = reference.argmin(1) + envelope = c.square().sum(1)[None] + 2 * (q.abs() @ c.abs().T) + unit = torch.finfo(torch.float32).eps / 2 + operations = 2 * c.shape[1] + 3 + gamma = operations * unit / (1 - operations * unit) + row = torch.arange(len(q)) + error = (scores.double() - reference[row, labels]).abs() + test.assertTrue((error <= gamma * envelope[row, labels]).all(), + f'FP32 source bound violated: {error}') + + +class TestIVFFlat(unittest.TestCase): + def test_finite_1024d_inputs_do_not_overflow_dot_output(self): + finite_output_regression('cpu') + + def test_all_probes_split_tiles_empty_lists_and_ties(self): + gen = torch.Generator().manual_seed(4) + candidates = torch.randn((128, 8), generator=gen) + candidates[1] = candidates[0] + queries = torch.cat((candidates[:3], torch.randn((17, 8), generator=gen))) + index = IndexIVFFlat(torch.zeros((4, 8)), nprobe=4) + index.add(candidates) + self.assertEqual(int((index.list_sizes == 0).sum()), 3) + scores, ids = index.search_1nn(queries) + expected_scores, expected_ids = represented_oracle(queries, candidates) + torch.testing.assert_close(scores, expected_scores, rtol=0, atol=0) + torch.testing.assert_close(ids.long(), expected_ids) + self.assertEqual(ids[0].item(), 0) + self.assertEqual(ids[1].item(), 0) + + def test_representation_and_routing_can_change_winners(self): + candidates = torch.tensor([[1.0002, 0], [1.0, 0]]) + query = torch.tensor([[1.0, 0]]) + index = IndexIVFFlat(torch.zeros((2, 2)), nprobe=2) + index.add(candidates) + self.assertEqual(index.search_1nn(query)[1].item(), 0) + self.assertEqual((query[:, None] - candidates).square().sum(2).argmin(1).item(), 1) + index = IndexIVFFlat(torch.tensor([[0.0, 0], [100.0, 0]]), nprobe=1) + candidates = torch.tensor([[40.0, 0], [100.0, 0]]) + query = torch.tensor([[60.0, 0]]) + index.add(candidates) + self.assertEqual(index.search_1nn(query)[1].item(), 1) + self.assertEqual(represented_oracle(query, candidates)[1].item(), 0) + + def test_global_route_can_have_no_local_candidate(self): + index = IndexIVFFlat(torch.tensor([[0.0, 0], [100.0, 0]]), nprobe=1) + index.add(torch.tensor([[0.0, 0]])) + index.set_routing_nonempty(torch.ones(2, dtype=torch.bool)) + query = torch.tensor([[100.0, 0]]) + probes = index.route(query) + self.assertEqual(probes.item(), 1) + scores, ids = index.search_1nn(query, coarse_idx=probes) + self.assertTrue(torch.isinf(scores).all()) + self.assertEqual(ids.item(), -1) + + def test_original_alias_and_empty_queries(self): + # Reject unsupported composition before superclass/group work, even + # when no process group exists, in both accepted core call forms. + positional = ( + 1, + 1, + 1, + None, + None, + 'throughput', + 1234, + False, + None, + 4096, + ) + with patch.object( + EmeansShardedCentroids, + '__init__', + side_effect=AssertionError('entered group constructor'), + ) as base: + with self.assertRaisesRegex(ValueError, 'spherical=True'): + EmeansShardedCentroidsIVF(*positional, group=None, spherical=True) + base.assert_not_called() + controls = dict(assignment_backend='native', capture_assignments=False, spherical=False) + with patch.object(EmeansShardedCentroids, '__init__', + side_effect=RuntimeError('ordinary forwarding')) as base: + with self.assertRaisesRegex(RuntimeError, 'ordinary forwarding'): + EmeansShardedCentroidsIVF(*positional, group=None, **controls) + base.assert_called_once_with(*positional, group=None, quantizer=None, **controls) + from faiss.contrib.e_means.quantizer import CastQuantizer + with patch.object(EmeansShardedCentroids, '__init__', + side_effect=AssertionError('codec entered native IVF constructor')) as base: + with self.assertRaises(ValueError): + EmeansShardedCentroidsIVF(*positional, group=None, + quantizer=CastQuantizer(8, torch.bfloat16), **controls) + base.assert_not_called() + # The tensor constructor, rather than a compatibility validator, + # rejects old quantizer/backend/capture positions through every owner. + from faiss.contrib.e_means import QuantizedEmeans, Emeans, DistributedEmeans + legacy = positional + (None, 'native', False) + with patch('faiss.contrib.e_means.e_means_distributed._check_group', return_value=1), \ + patch('faiss.contrib.e_means.sharded_centroids._check_group', return_value=1), \ + patch.object(dist, 'get_rank', return_value=0): + for cls in (QuantizedEmeans, Emeans, DistributedEmeans, + EmeansShardedCentroids, EmeansShardedCentroidsIVF): + kwargs = {} if cls in (QuantizedEmeans, Emeans) else {'group': None} + with self.subTest(constructor=cls.__name__): + with self.assertRaises(TypeError): + cls(*legacy, **kwargs) + floating = Emeans(*positional, **controls) + self.assertEqual(floating.assignment_backend, 'native') + self.assertFalse(floating.capture_assignments) + self.assertFalse(floating.spherical) + coarse = torch.zeros((1, 2)) + index = IndexIVFFlat(coarse, nprobe=1) + coarse.fill_(100) + index.add(torch.tensor([[0.0, 0], [1.0, 0]], requires_grad=True)) + scores, ids = index.search_1nn(torch.tensor([[0.0, 0]], requires_grad=True)) + self.assertTrue(scores.requires_grad) + self.assertEqual(ids.item(), 0) + self.assertEqual(index.centroids.data_ptr(), coarse.data_ptr()) + self.assertEqual(index.centroids.sum().item(), 200) + self.assertEqual(len(index.search_1nn(torch.empty((0, 2)))[1]), 0) + index.add(torch.zeros((1, 2), dtype=torch.uint8)) + self.assertEqual(index.search_1nn(torch.zeros((1, 2)))[1].item(), 0) + + def test_all_original_precision_storage_and_entrypoint_branches(self): + gen = torch.Generator().manual_seed(18) + candidates = torch.randn((19, 8), generator=gen) + queries = torch.randn((7, 8), generator=gen) + for implem in (1, 2, 3, 4, 5): + for dtype_name, dtype in (('fp16', torch.float16), ('bf16', torch.bfloat16)): + for scope in ('all', 'fine'): + with self.subTest(implem=implem, dtype=dtype_name, scope=scope): + index = IndexIVFFlat(torch.zeros((2, 8)), nprobe=2, query_chunk=2) + index.implem, index.dtype, index.lowp_scope = implem, dtype_name, scope + fine = None if implem < 3 else dtype + coarse = None if implem < 3 or scope != 'all' else dtype + self.assertEqual(index._mm_dtype('fine'), fine) + self.assertEqual(index._mm_dtype('coarse'), coarse) + represented = candidates if fine is None else candidates.to(fine).float() + represented_q = queries if fine is None else queries.to(fine).float() + expected = (represented.double().square().sum(1)[None] + - 2 * (represented_q.double() @ represented.double().T)) + direct = index._exact_1nn(queries, candidates) + topk = index._exact_topk(queries, candidates, 2) + torch.testing.assert_close(direct[1], expected.argmin(1)) + source_score_bound(self, direct[0], represented_q, represented) + torch.testing.assert_close(topk[1], expected.topk(2, largest=False).indices) + coarse_c = candidates if coarse is None else candidates.to(coarse).float() + coarse_q = queries if coarse is None else queries.to(coarse).float() + coarse_expected = (coarse_c.double().square().sum(1)[None] + - 2 * (coarse_q.double() @ coarse_c.double().T)) + coarse_result = index._exact_1nn(queries, candidates, stage='coarse') + coarse_topk = index._exact_topk(queries, candidates, 2, stage='coarse') + torch.testing.assert_close(coarse_result[1], coarse_expected.argmin(1)) + source_score_bound(self, coarse_result[0], coarse_q, coarse_c) + torch.testing.assert_close(coarse_topk[1], coarse_expected.topk(2, largest=False).indices) + index.add(candidates) + self.assertEqual(index.vectors is None, implem >= 4 and fine is not None) + self.assertEqual(index.vectors_lowp is None, fine is None) + actual = index.search_1nn(queries) + torch.testing.assert_close(actual[1].long(), expected.argmin(1)) + source_score_bound(self, actual[0], represented_q, represented) + torch.testing.assert_close(index._sq_norms(candidates, 'fine').double(), represented.double().square().sum(1), rtol=2e-6, atol=3e-6) + + def test_precision_selectors_reject_unsupported_values(self): + index = IndexIVFFlat(torch.zeros((2, 2)), nprobe=2) + index.implem = np.int64(3) + self.assertIs(type(index.implem), int) + index.implem = 4 + invalid = { + 'implem': (0, 6, True, 3.0, '4', None), + 'dtype': ('native', 'float16', torch.float16, None, 1), + 'lowp_scope': ('coarse', 'both', '', None, 1), + } + for name, values in invalid.items(): + original = getattr(index, name) + for value in values: + with self.subTest(name=name, value=value): + with self.assertRaisesRegex(ValueError, name): + setattr(index, name, value) + self.assertEqual(getattr(index, name), original) + + def test_fp16_to_bf16_coarse_norm_counterexample(self): + coarse = torch.tensor([[1.001], [1.008]]) + query = torch.tensor([[1.]]) + index = IndexIVFFlat(coarse, nprobe=1) + fixed_membership_norms = index.centroids_norms.clone() + index.dtype = 'bf16' + index.set_routing_nonempty(torch.ones(2, dtype=torch.bool)) + + represented = coarse.bfloat16().float() + current_norms = represented.square().sum(1) + dot = query.bfloat16().float() @ represented.T + stale_scores = fixed_membership_norms[None] - 2 * dot + coherent_scores = current_norms[None] - 2 * dot + self.assertEqual(stale_scores.argmin(1).item(), 1) + self.assertEqual(coherent_scores.argmin(1).item(), 0) + self.assertEqual(index.route(query).item(), 0) + torch.testing.assert_close(index._query_centroids_norms, current_norms, + rtol=0, atol=0) + torch.testing.assert_close(index.centroids_norms, fixed_membership_norms, + rtol=0, atol=0) + + def test_cpu_add_policy_and_occupancy_survive_mutation(self): + coarse = torch.tensor([[1.001], [1.008]]) + index = IndexIVFFlat(coarse, nprobe=1) + index.dtype = 'bf16' + index.add(torch.tensor([[1.]])) + torch.testing.assert_close(index.list_sizes, + torch.tensor([1, 0], dtype=torch.int32)) + original_ids = index.ids.clone() + original_sizes = index.list_sizes.clone() + + index.dtype = 'fp16' + torch.testing.assert_close(index.ids, original_ids) + torch.testing.assert_close(index.list_sizes, original_sizes) + self.assertEqual(index.route(torch.tensor([[1.008]])).item(), 0) + self.assertTrue(torch.isinf(index.routing_norms[1])) + + def test_every_supported_precision_transition_and_rebuild(self): + states = [(implem, dtype, scope) + for implem in range(1, 6) + for dtype in ('fp16', 'bf16') + for scope in ('all', 'fine')] + coarse = torch.tensor([[0., 0.], [4., 0.]]) + candidates = torch.tensor([[0., 0.], [4., 0.], [2., 1.]]) + queries = torch.tensor([[.25, 0.], [3.75, 0.]]) + probes = torch.tensor([[0, 1], [0, 1]]) + + def policy_dtype(state, stage): + implem, dtype, scope = state + if implem < 3 or (stage == 'coarse' and scope != 'all'): + return None + return torch.float16 if dtype == 'fp16' else torch.bfloat16 + + def represented(value, dtype): + return value if dtype is None else value.to(dtype).float() + + for before in states: + for after in states: + with self.subTest(before=before, after=after): + index = IndexIVFFlat(coarse, nprobe=2, query_chunk=1) + index.implem, index.dtype, index.lowp_scope = before + index.add(candidates) + original_ids = index.ids.clone() + original_sizes = index.list_sizes.clone() + + index.implem, index.dtype, index.lowp_scope = after + torch.testing.assert_close(index.ids, original_ids) + torch.testing.assert_close(index.list_sizes, original_sizes) + coarse_dtype = policy_dtype(after, 'coarse') + cq = represented(queries, coarse_dtype) + cc = represented(coarse, coarse_dtype) + coarse_scores = (cc.double().square().sum(1)[None] + - 2 * (cq.double() @ cc.double().T)) + torch.testing.assert_close(index.route(queries), + coarse_scores.topk(2, largest=False).indices) + + fine_dtype = policy_dtype(after, 'fine') + fq = represented(queries, fine_dtype) + fc = represented(candidates, fine_dtype) + fine_scores = (fc.double().square().sum(1)[None] + - 2 * (fq.double() @ fc.double().T)) + compatible = (policy_dtype(before, 'fine') == fine_dtype) + if not compatible: + with self.assertRaisesRegex(RuntimeError, 'call add again'): + index.search_1nn(queries, coarse_idx=probes) + index.add(candidates) + scores, ids = index.search_1nn(queries, coarse_idx=probes) + torch.testing.assert_close(ids.long(), fine_scores.argmin(1)) + source_score_bound(self, scores, fq, fc) + + def test_original_stage_policy_supplied_norms_and_cache_timing(self): + coarse = torch.tensor([[1.003, .127], [2.009, -.211]]) + query = torch.tensor([[1.019, .193]]) + index = IndexIVFFlat(coarse, nprobe=2) + cached = index.centroids_norms.clone() + index.dtype, index.lowp_scope = 'bf16', 'fine' + torch.testing.assert_close(index.centroids_norms, cached, rtol=0, atol=0) + self.assertIs(index._as_computed(coarse, 'coarse'), coarse) + torch.testing.assert_close(index._as_computed(coarse, 'fine'), coarse.bfloat16().float(), rtol=0, atol=0) + index.lowp_scope = 'all' + supplied = torch.tensor([8., 1.]) + scores, ids = index._exact_1nn(query, coarse, supplied, 'coarse') + expected = (supplied.double() + - 2 * (query.bfloat16().double() + @ coarse.bfloat16().double().T)[0]) + self.assertEqual(ids.item(), expected.argmin().item()) + torch.testing.assert_close(scores.double(), expected.min()[None], rtol=2e-6, atol=3e-6) + + def test_original_floating_training_inputs_reach_inherited_preparation(self): + from faiss.contrib.e_means import QuantizedEmeans + + model = object.__new__(EmeansShardedCentroidsIVF) + QuantizedEmeans.__init__(model, 8, 2, quantizer=None, assignment_backend='native', unused_threshold=0) + model._centroids, model.centroids = torch.zeros((2, 8)), None + model._batch_stats = torch.zeros((2, 9)) + model._fp8_quantizer = model._int8_quantizer = model.spherical = False + model.recipe = {} + for dtype in (torch.float16, torch.bfloat16, torch.float32): + model._input_dtype = None + rows = torch.ones((3, 16), dtype=dtype)[:, ::2] + declared = model._prepare_input(rows) + self.assertIs(declared, rows) # Metadata does not copy the population. + self.assertEqual(declared.dtype, dtype) + self.assertEqual(model._input_dtype, torch.float32) + prepared = model._prepare_rows(declared[:2]) + self.assertTrue(prepared.is_contiguous()) + torch.testing.assert_close(prepared, torch.ones((2, 8)), rtol=0, atol=0) + + def test_original_hooks_and_full_vs_chunked_queries(self): + from contextlib import contextmanager + class Observed(IndexIVFFlat): + events = [] + @contextmanager + def _timed(self, name): + self.events.append(name) + yield + def _chunk_body(self, kind): + body = super()._chunk_body(kind) + def observed(rows, *args): + self.events.append((kind, len(rows))) + return body(rows, *args) + return observed + index = Observed(torch.zeros((2, 8)), nprobe=2, query_chunk=2) + rows = torch.zeros((5, 8)) + index.add(rows) + self.assertIn('add', index.events) + self.assertEqual(index.events.count(('assign', 2)), 2) + index.events.clear() + index.implem = 1 + index.route(rows) + self.assertEqual(index.events, ['coarse', ('topk', 5)]) + index.events.clear() + index.implem = 2 + index.route(rows) + self.assertEqual(index.events, ['coarse', ('topk', 2), ('topk', 2), ('topk', 1)]) + + def test_original_empty_add_and_conversions(self): + index = IndexIVFFlat(torch.zeros((2, 8), dtype=torch.bfloat16), nprobe=2) + self.assertEqual(index.centroids.dtype, torch.float32) + index.add(torch.empty((0, 8))) + score, labels = index.search_1nn(torch.zeros((3, 8), dtype=torch.float16)) + self.assertTrue(torch.isinf(score).all()) + self.assertEqual(labels.tolist(), [-1, -1, -1]) + self.assertEqual(index.coarse_ndis, 6) + index.add(torch.zeros((17, 8), dtype=torch.bfloat16)) + probes = torch.tensor([[0, 1]], dtype=torch.int32) + score, labels = index.search_1nn(torch.zeros((1, 8)), coarse_idx=probes) + self.assertEqual(labels.item(), 0) + self.assertEqual(index.coarse_ndis, 40) + self.assertEqual(index.ndis.item(), 17) + self.assertEqual(index.search_1nn(torch.zeros((1, 8)))[1].item(), 0) + self.assertEqual(index.coarse_ndis, 42) + + def test_int32_boundaries(self): + _check_int32_count(2**31 - 1, 'fixture') + with self.assertRaisesRegex(ValueError, 'INT32'): + _check_int32_count(2**31, 'fixture') + class TooMany: + ndim = 1 + def numel(self): + return 2**31 + with self.assertRaisesRegex(ValueError, 'INT32'): + _bucket_sort(TooMany(), 1) + + def test_global_occupancy_over_int32_keeps_a_live_list(self): + class Prepared: + list_sizes = torch.tensor([2**31 - 1, 0], dtype=torch.int32) + def add(self, rows): + pass + def set_routing_nonempty(self, nonempty): + self.nonempty = nonempty + model = object.__new__(EmeansShardedCentroidsIVF) + model._ivf, model._centroids, model._group = Prepared(), torch.zeros((1, 8)), None + observed = [] + def reduce(occupancy, group): + observed.append(occupancy.dtype) + occupancy.add_(torch.tensor([1, 0], dtype=torch.int64)) + with patch.object(dist, 'all_reduce', side_effect=reduce): + result = model._prepare_assignment() + self.assertEqual(observed, [torch.int64]) + self.assertEqual(result.nonempty.tolist(), [True, False]) + + def test_bf16_dot_rounding_and_native_float64_computation(self): + index = IndexIVFFlat(torch.zeros((1, 8)), nprobe=1) + index.dtype = 'bf16' + candidates = torch.full((2, 32), 1.0078125) + candidates[1, 0] = 1.015625 + query = torch.full((1, 32), 1.0078125) + expected = (candidates.double().square().sum(1) + - 2 * (query.double() @ candidates.double().T)[0]) + self.assertFalse(torch.equal((query.bfloat16() @ candidates.bfloat16().T).float(), + (query.double() @ candidates.double().T).float())) + scores, ids = index._exact_1nn(query, candidates) + self.assertEqual(ids.item(), expected.argmin().item()) + torch.testing.assert_close(scores.double(), expected.min()[None], rtol=0, atol=0) + index.implem = 1 + native_q = torch.tensor([[1. + 2**-30, 2.]], dtype=torch.float64) + native_c = torch.tensor([[3., 4.], [5., 6.]], dtype=torch.float64) + supplied = torch.tensor([.1, .2], dtype=torch.float64) + expected_native = supplied - 2 * (native_q @ native_c.T).float()[0] + scores, ids = index._exact_1nn(native_q, native_c, supplied) + self.assertEqual(scores.dtype, torch.float64) + self.assertEqual(ids.item(), expected_native.argmin().item()) + torch.testing.assert_close(scores, expected_native.min()[None], rtol=0, atol=0) + + def test_original_package_and_module_import_identity_optional_torch(self): + from pathlib import Path + import faiss.contrib + + source = Path(faiss.contrib.__file__).resolve().parent + script = """ +import importlib, sys +import faiss.contrib +faiss.contrib.__path__.insert(0, sys.argv[1]) +order = sys.argv[2].split(',') +modules = [importlib.import_module('faiss.contrib.e_means.' + name) for name in order] +from faiss.contrib.e_means import EmeansShardedCentroids, EmeansShardedCentroidsIVF +from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroidsIVF as old +from faiss.contrib.e_means.sharded_centroids_ivf import EmeansShardedCentroidsIVF as new +assert old is new is EmeansShardedCentroidsIVF +assert EmeansShardedCentroids is modules[order.index('sharded_centroids')].EmeansShardedCentroids +""" + for order in ('sharded_centroids,sharded_centroids_ivf', 'sharded_centroids_ivf,sharded_centroids'): + subprocess.run([sys.executable, '-c', script, str(source), order], check=True, timeout=30) + optional = """ +import importlib.abc, sys +import faiss.contrib +faiss.contrib.__path__.insert(0, sys.argv[1]) +class BlockTorch(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == 'torch' or fullname.startswith('torch.'): + raise ImportError('intentional optional-Torch fixture') +sys.meta_path.insert(0, BlockTorch()) +import faiss.contrib.e_means as package +assert 'torch' not in sys.modules +assert set(package.__all__) == { + 'Emeans', 'NumpyEmeans', 'QuantizedEmeans', 'DistributedNumpyEmeans', + 'DistributedEmeans', 'EmeansShardedCentroids', 'EmeansShardedCentroidsIVF', +} +assert not any(hasattr(package, name) for name in + ('TorchEmeans', 'QuantizedTorchEmeans', 'NumPyEmeans', 'DistributedNumPyEmeans')) +try: + package.EmeansShardedCentroidsIVF +except ImportError: + pass +else: + raise AssertionError('missing optional Torch was hidden') +""" + subprocess.run([sys.executable, '-c', optional, str(source)], check=True, timeout=30) + + def test_auto_keeps_ivf_auxiliary_backend_and_chunk_bound(self): + from unittest import mock + from faiss.contrib.e_means import Emeans, QuantizedEmeans + from faiss.contrib.e_means.torch_backend import TorchBackend, TritonBackend + + state = torch.empty((4096, 128), device="meta") + for requested, cls in (("auto", TorchBackend), ("native", TorchBackend), ("triton", TritonBackend)): + model = EmeansShardedCentroidsIVF.__new__(EmeansShardedCentroidsIVF) + control = Emeans(128, 4096, assignment_backend=cls.name) + QuantizedEmeans.__init__(model, 128, 4096, quantizer=None, + assignment_backend=requested) + model._centroids, model.centroids = state, None + control._centroids = state + control._execution_backend = cls(control.centroid_chunk_size) + model.assignment_backend = requested + model._resolved_assignment_backend = None + model._execution_backend = cls(model.centroid_chunk_size) + # This geometry fixture does not execute the selected GPU operation. + with mock.patch.object(TritonBackend, 'require_assignment'): + model._resolve_assignment_backend(state) + self.assertEqual(model.assignment_backend, requested) + self.assertEqual(model._assignment_backend, cls.name) + self.assertEqual(model._get_assignment_chunk_size(), control._get_assignment_chunk_size()) + model.assignment_chunk_size = 23 + self.assertEqual(model._get_assignment_chunk_size(), 23) + + +def finite_output_regression(device): + candidates = torch.stack((torch.full((1024,), 31.), torch.full((1024,), 32.))).to(device) + query = candidates[1:] + # One list reproduces Root's all-probe wrong-ID witness; two real coarse + # rows also exercise the 2D assignment/top-k call sites, not only BMM. + for coarse in (torch.zeros((1, 1024), device=device), candidates.clone()): + index = IndexIVFFlat(coarse, nprobe=len(coarse), query_chunk=1) + index.add(candidates) + scores, ids = index.search_1nn(query) + assert torch.isfinite(scores).all() + torch.testing.assert_close(ids.long(), torch.tensor([1], device=device)) + torch.testing.assert_close(scores, torch.tensor([-1048576.], device=device), rtol=0, atol=0) + direct = (query.double()[:, None] - candidates.double()).square().sum(2) + torch.testing.assert_close(ids.long(), direct.argmin(1)) + if len(coarse) == 2: + torch.testing.assert_close(index.list_sizes.long(), torch.ones(2, dtype=torch.int64, device=device)) + assert index.route(query)[0, 0].item() == 1 + + +class TestIVFFlatCUDA(unittest.TestCase): + @unittest.skipUnless(torch.cuda.is_available() and importlib.util.find_spec('triton'), + 'requires CUDA and Triton') + def test_cuda_fp32_mm_and_bmm_outputs(self): + finite_output_regression('cuda:0') + + @unittest.skipUnless(torch.cuda.is_available() and importlib.util.find_spec('triton'), + 'requires CUDA and Triton') + def test_original_benign_ragged_empty_and_ties(self): + # Exactly represented small coordinates: independent CPU FP64 oracle. + candidates_cpu = torch.zeros((5, 16)) + candidates_cpu[:, 0] = torch.tensor([0., 0., 8., 9., 16.]) + coarse_cpu = torch.zeros((4, 16)) + coarse_cpu[:, 0] = torch.tensor([0., 8., 16., 24.]) + queries_cpu = torch.zeros((7, 16)) + queries_cpu[:, 0] = torch.tensor([0., .25, -.25, 8., 9., 16., 24.]) + probes_cpu = torch.tensor([[0], [0], [0], [1], [1], [2], [3]]) + reference_scores = torch.full((7,), torch.inf, dtype=torch.float64) + reference_ids = torch.full((7,), -1, dtype=torch.int64) + candidate_lists = ((0, 1), (2, 3), (4,), ()) + for row, probe in enumerate(probes_cpu[:, 0].tolist()): + ids = candidate_lists[probe] + if ids: + c = candidates_cpu[list(ids)].double() + score = c.square().sum(1) - 2 * (c * queries_cpu[row].double()).sum(1) + winner = score.argmin().item() + reference_scores[row], reference_ids[row] = score[winner], ids[winner] + for label, dtype, implem in (('fp16', 'fp16', 4), + ('bf16', 'bf16', 4), + ('native', 'fp16', 2)): + if dtype == 'bf16' and torch.cuda.get_device_capability() < (8, 0): + continue + with self.subTest(dtype=label): + index = IndexIVFFlat(coarse_cpu.cuda(), nprobe=1, query_chunk=8) + index.dtype, index.implem = dtype, implem + index.add(candidates_cpu.cuda()) + self.assertEqual(index.list_sizes.tolist(), [2, 2, 1, 0]) + query, probes = queries_cpu.cuda(), probes_cpu.cuda() + scores, ids = index.search_1nn(query, coarse_idx=probes) + torch.testing.assert_close(scores.double().cpu(), reference_scores, + rtol=0, atol=0) + torch.testing.assert_close(ids.long().cpu(), reference_ids, + rtol=0, atol=0) + + +def sharded_contract(rank, rendezvous): + torch.cuda.set_device(rank) + dist.init_process_group('nccl', init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=90)) + try: + device = torch.device('cuda', rank) + initial = torch.tensor([[0., 0], [0., 0], [8., 0], [16., 0]], device=device) + rows = torch.tensor([[0., 0], [1., 0], [8., 0], [9., 0], [16., 0], + [0., 0], [2., 0], [7., 0], [15., 0], [16., 0]], device=device) + local = rows[rank * 5:(rank + 1) * 5] + model = EmeansShardedCentroidsIVF( + 2, 4, group=dist.group.WORLD, nepochs=1, batch_size=8, alpha0=.25, + nlist=3, nprobe=3, coarse_niter=1, assignment_chunk_size=2, + search_workspace_bytes=4096, capture_assignments=True, seed=7) + model.begin(10, initial[rank * 2:(rank + 1) * 2]) + for start, end in ((0, 4), (4, 5)): + before = model.current_centroids().clone() + shards = [torch.empty_like(before) for _ in range(2)] + dist.all_gather(shards, before) + full = torch.cat(shards) + all_rows = torch.cat((rows[start:end], rows[5 + start:5 + end])) + winners = represented_oracle(all_rows, full)[1] + expected_sums = torch.zeros_like(full) + expected_counts = torch.zeros(4, device=device) + expected_sums.index_add_(0, winners, all_rows) + expected_counts.index_add_(0, winners, torch.ones(len(winners), device=device)) + expected_objective = (all_rows - full[winners]).square().sum(dtype=torch.float64) + snapshot = None + for offset in range(start, end, 2): + stats = model.accumulate(local[offset:min(offset + 2, end)]) + if snapshot is None: + snapshot = model._ivf.vectors_lowp + assert model._ivf.vectors_lowp is snapshot + torch.testing.assert_close(model.current_centroids(), before, rtol=0, atol=0) + chunk_labels = winners[rank * (end - start) + offset - start: + rank * (end - start) + min(offset + 2, end) - start] + torch.testing.assert_close(stats['labels'], chunk_labels) + torch.testing.assert_close(stats['sums'], expected_sums[rank * 2:(rank + 1) * 2], rtol=0, atol=0) + torch.testing.assert_close(stats['counts'], expected_counts[rank * 2:(rank + 1) * 2], rtol=0, atol=0) + objective = stats['objective'].clone() + dist.all_reduce(objective) + torch.testing.assert_close(objective, expected_objective, rtol=0, atol=0) + model.update(stats) + model.end_epoch() + result = model.finalize() + assert torch.isfinite(result).all() and model._ivf is not None + model = EmeansShardedCentroidsIVF( + 2, 4, group=dist.group.WORLD, nepochs=1, batch_size=8, alpha0=.25, + nlist=3, nprobe=3, coarse_niter=1, assignment_chunk_size=2, + search_workspace_bytes=4096, capture_assignments=True, seed=7) + assert model._ivf is None + finally: + dist.destroy_process_group() + + +class TestIVFShardedCUDA(unittest.TestCase): + @unittest.skipUnless(torch.cuda.device_count() >= 2 and dist.is_nccl_available() + and importlib.util.find_spec('triton'), 'requires two CUDA GPUs, NCCL and Triton') + def test_original_fp32_statistics_and_frozen_transfer_snapshot(self): + import torch.multiprocessing as mp + with tempfile.TemporaryDirectory() as directory: + mp.spawn(sharded_contract, args=('file://' + directory + '/group',), + nprocs=2, join=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_ivf_fine.py b/thirdparty/faiss/tests/torch_test_e_means_ivf_fine.py new file mode 100644 index 000000000..8cccf47bf --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_ivf_fine.py @@ -0,0 +1,308 @@ +# 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. + +"""IVF fine search and exact probe selection. + +The fine search is checked against an exact FP64 top-3 over the probed lists of the represented operands. Scores +must lie within gamma_{2d+3} * (|c|^2 + 2 |q| . |c|) of the FP64 distance, the a-priori FP32 bound the IVF tests +also use; labels and second IDs must match wherever no other candidate's error interval reaches theirs. Probe +selection must return the nprobe smallest coarse scores, ordered by score, lower list IDs first among equal scores. +""" + +import unittest +from unittest import mock + +import torch + +from faiss.contrib.e_means import ivf_fine +from faiss.contrib.e_means.ivf_flat import IndexIVFFlat, _dot_fp32 + + +def _data(n, k, nlist, d, seed, ties=False, long_list=False): + g = torch.Generator().manual_seed(seed) + coarse = torch.randn(nlist, d, generator=g) + candidates = torch.randn(k, d, generator=g) + if long_list: # half of the candidates land in one list + candidates[: k // 2] = coarse[0] + 0.05 * torch.randn(k // 2, d, generator=g) + if ties: # duplicated candidates: exact score ties between distinct IDs + candidates[1::2] = candidates[::2] + rows = torch.randn(n, d, generator=g) + return coarse, candidates, rows + + +def _cuda_bf16_gemm_supported(device): + # NVIDIA's BF16-input/FP32-output GEMM requires SM80; HIP uses its own contract. + return torch.version.hip is not None or torch.cuda.get_device_capability(device) >= (8, 0) + + +def _index(coarse, candidates, nprobe, device="cuda", dtype=None, implem=4): + device = torch.device(device) + bf16 = device.type != "cuda" or _cuda_bf16_gemm_supported(device) + if dtype is None: + dtype = "bf16" if bf16 else "fp16" + if dtype == "bf16" and implem >= 3 and not bf16: + raise unittest.SkipTest("BF16 IVF GEMM requires NVIDIA SM80 or later") + index = IndexIVFFlat(coarse.to(device), nprobe=nprobe) + index.implem, index.dtype = implem, dtype + index.add(candidates.to(device)) + return index + + +def _topk_route(index, rows): + """The nprobe smallest coarse scores (route's scores, same query chunks), lower list IDs first among equals.""" + dt, xb_t = index._lowp_operands(index.centroids, "coarse") + chunk = index.query_chunk if index.implem >= 2 else len(rows) + out = [] + for i0 in range(0, len(rows), max(1, chunk)): + part = rows[i0:i0 + chunk] + dis = index._current_routing_norms() - 2 * _dot_fp32(part if dt is None else part.to(dt), xb_t) + out.append(torch.sort(dis, dim=1, stable=True).indices[:, :index.nprobe]) + return torch.cat(out) if out else torch.empty((0, index.nprobe), dtype=torch.int64, device=rows.device) + + +def _exact(index, rows, probes): + """FP64 distances to every stored candidate (inf outside the probed lists), their FP32 error bounds, and the IDs.""" + fine = index._mm_dtype("fine") + vecs = index.vectors_lowp if index.vectors_lowp is not None else index.vectors + c = vecs.double() + q = (rows if fine is None else rows.to(fine)).double() + lims = index.xb_lims.long() + owner = torch.repeat_interleave(torch.arange(index.nlist, device=c.device), lims[1:] - lims[:-1]) + probed = (owner[None, None, :] == probes.long()[:, :, None]).any(1) + norms = c.square().sum(1) + dis = torch.where(probed, norms[None] - 2 * q @ c.T, torch.inf) + envelope = norms[None] + 2 * q.abs() @ c.abs().T + unit = torch.finfo(torch.float32).eps / 2 + operations = 2 * c.shape[1] + 3 + # Relative FP32 rounding plus an absolute term for products that underflow below the normal range. + bound = operations * unit / (1 - operations * unit) * envelope + operations * 2.0 ** -149 + return dis, bound, index.ids.long() + + +class _Checks(unittest.TestCase): + def _assert_exact(self, index, rows, probes, result): + scores, ids = result + self.assertEqual(scores.dtype, torch.float32) + self.assertEqual(ids.dtype, torch.int32) + dis, bound, cid = _exact(index, rows, probes) + order = torch.argsort(cid) # columns by ID, then a stable sort by distance: ties go to the lower ID + dis, bound, cid = dis[:, order], bound[:, order], cid[order] + top = torch.sort(dis, dim=1, stable=True).indices[:, :3] + s, b, i = dis.gather(1, top), bound.gather(1, top), cid[top] + found = torch.isfinite(s) + # Missing entries: inf and -1 exactly where the probed lists hold fewer than one / two candidates. + for col in range(2): + self.assertTrue(torch.equal(ids[:, col] < 0, ~found[:, col])) + self.assertTrue(torch.isinf(scores[~found[:, col], col]).all()) + # Every returned score is within the FP32 bound of its own candidate's FP64 distance. + pos = torch.searchsorted(cid, ids.long().clamp(min=0)) + for col in range(2): + ok = found[:, col] + exact = dis.gather(1, pos[:, col:col + 1])[:, 0] + limit = bound.gather(1, pos[:, col:col + 1])[:, 0] + self.assertTrue(((scores[ok, col].double() - exact[ok]).abs() <= limit[ok]).all()) + both = (ids[:, 0] >= 0) & (ids[:, 1] >= 0) + self.assertTrue((ids[both, 0] != ids[both, 1]).all()) # two distinct candidates + # Labels and second IDs wherever no other candidate's interval [dis - bound, dis + bound] reaches theirs. + low = dis - bound + rest = low.scatter(1, top[:, :1], torch.inf).min(1).values + sure1 = found[:, 0] & (rest > s[:, 0] + b[:, 0]) + self.assertTrue(torch.equal(ids[sure1, 0].long(), i[sure1, 0])) + rest2 = low.scatter(1, top[:, :2], torch.inf).min(1).values + sure2 = sure1 & found[:, 1] & (rest2 > s[:, 1] + b[:, 1]) + self.assertTrue(torch.equal(ids[sure2, 1].long(), i[sure2, 1])) + return sure1.float().mean().item() + + def _case(self, n, k, nlist, d, nprobe, seed=0, device="cuda", dtype=None, implem=4, **kwargs): + coarse, candidates, rows = _data(n, k, nlist, d, seed, **kwargs) + index = _index(coarse, candidates, nprobe, device, dtype, implem) + rows = rows.to(device) + probes = _topk_route(index, rows) + return index, rows, probes, index.search_2nn(rows, coarse_idx=probes) + + +@unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") +class TestFineSearchCUDA(_Checks): + def test_selected_bf16_route_refuses_pre_sm80(self): + if _cuda_bf16_gemm_supported(torch.cuda.current_device()): + self.skipTest("requires NVIDIA CUDA before SM80") + coarse, candidates, rows = _data(4, 8, 2, 16, 7) + index = IndexIVFFlat(coarse.cuda(), nprobe=2) + index.dtype, index.implem = "bf16", 4 + index.add(candidates.cuda()) + with self.assertRaisesRegex(RuntimeError, r"BFloat16.*compute capability 8\.0"): + index.route(rows.cuda()) + + def test_exact_reference(self): + for dtype, implem, d in (("bf16", 4, 16), ("bf16", 4, 64), ("bf16", 4, 96), ("bf16", 4, 128), ("bf16", 4, 1024), + ("fp16", 4, 64), ("bf16", 2, 64), ("bf16", 4, 3), ("bf16", 4, 17), ("bf16", 4, 100)): + if dtype == "bf16" and implem >= 3 and not _cuda_bf16_gemm_supported(torch.cuda.current_device()): + continue + for nprobe in (1, 4, 16): + with self.subTest(dtype=dtype, implem=implem, d=d, nprobe=nprobe): + index, rows, probes, result = self._case(2048, 4096, 64, d, nprobe, seed=d + nprobe, + dtype=dtype, implem=implem) + # The bounds leave few rows undecided (about 2% at d 1024): the label check is not vacuous. + self.assertGreater(self._assert_exact(index, rows, probes, result), 0.95) + self.assertTrue(torch.equal(index.search_1nn(rows, coarse_idx=probes)[1], result[1][:, 0])) + + def test_kernel_paths(self): + # The Triton kernel and every CuTe candidate-tile width meet the exact reference. + for d in (64, 100): + with self.subTest(d=d): + index, rows, probes, _ = self._case(4096, 8192, 32, d, 4, seed=d) + xq, vecs = ivf_fine._operands(index, rows) + reference = ivf_fine._search_triton(index, xq, vecs, probes) + self._assert_exact(index, rows, probes, reference) + if ivf_fine._cute_ready(torch.cuda.current_device()): + for tile in (128, 256): + result = ivf_fine.search_2nn(index, rows, probes, tile=tile) + self._assert_exact(index, rows, probes, result) + for actual, expected in zip(result, reference): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + def test_ties_long_lists_missing_and_repeated_probes(self): + index, rows, probes, result = self._case(2048, 4096, 32, 64, 4, ties=True) + self._assert_exact(index, rows, probes, result) + twins = (result[1][:, 0] % 2 == 1) & (result[0][:, 0] == result[0][:, 1]) + self.assertFalse(twins.any()) # equal scores of duplicated candidates: the lower (even) ID first + index, rows, probes, result = self._case(2048, 8192, 16, 128, 2, long_list=True) + self._assert_exact(index, rows, probes, result) + index, rows, probes, result = self._case(512, 48, 32, 32, 1) # lists with fewer than two candidates + self._assert_exact(index, rows, probes, result) + self.assertTrue((result[1][:, 1] == -1).any()) + index, rows, probes, _ = self._case(1024, 2048, 16, 64, 4, seed=5) + probes[:, 1] = probes[:, 0] # a list probed twice + self._assert_exact(index, rows, probes, index.search_2nn(rows, coarse_idx=probes)) + index, rows, probes, result = self._case(2048, 20000, 9000, 32, 8, seed=9) # several routing tiles + self._assert_exact(index, rows, probes, result) + + @unittest.skipUnless(torch.cuda.device_count() >= 2, "requires 2 GPUs") + def test_second_device(self): + coarse, candidates, rows = _data(2048, 4096, 32, 64, 3) + index = _index(coarse, candidates, 4, device="cuda:1") + rows = rows.to("cuda:1") + probes = _topk_route(index, rows) + for current in (0, 1): # launched while either device is current + with torch.cuda.device(current): + self.assertTrue(torch.equal(index.route(rows), probes)) + self._assert_exact(index, rows, probes, index.search_2nn(rows)) + + def test_empty_inputs_alignment_and_shape_errors(self): + coarse, candidates, rows = _data(64, 512, 16, 32, 0) + index = _index(coarse, candidates, 4) + scores, ids = index.search_2nn(torch.empty((0, 32), device="cuda")) + self.assertEqual(tuple(scores.shape), (0, 2)) + with self.assertRaises(ValueError): + index.search_2nn(torch.randn(8, 32, device="cuda"), + coarse_idx=torch.zeros((8, 3), dtype=torch.int64, device="cuda")) + with self.assertRaises(ValueError): # query width differs from the index + index.search_2nn(torch.randn(8, 33, device="cuda"), + coarse_idx=torch.zeros((8, 4), dtype=torch.int64, device="cuda")) + # A represented-operand view starts mid-allocation (2-byte offset): + # BF16 on SM80+, FP16 on older NVIDIA devices. + buffer = torch.empty(64 * 32 + 1, dtype=index._mm_dtype("fine"), device="cuda") + shifted = buffer[1:].view(64, 32) + shifted.copy_(rows.cuda()) + probes = _topk_route(index, shifted.float()) + self._assert_exact(index, shifted.float(), probes, index.search_2nn(shifted, coarse_idx=probes)) + empty = _index(coarse, torch.empty((0, 32)), 4) # no candidates anywhere + scores, ids = empty.search_2nn(rows.cuda(), coarse_idx=probes) + self.assertTrue(torch.isinf(scores).all() and (ids == -1).all()) + + +class TestFineSearchCPU(_Checks): + def test_cpu_does_not_import_gpu_dependencies(self): + import builtins + import importlib + + original_import = builtins.__import__ + + def cpu_import(name, *args, **kwargs): + if name.split(".")[0] in ("triton", "cutlass", "quack"): + raise AssertionError("CPU path imported a GPU dependency: " + name) + return original_import(name, *args, **kwargs) + + with mock.patch.object(builtins, "__import__", side_effect=cpu_import): + importlib.reload(ivf_fine) + index, rows, probes, result = self._case(16, 32, 4, 8, 2, device="cpu") + self._assert_exact(index, rows, probes, result) + + def test_hip_does_not_select_nvidia_cute(self): + ivf_fine._cute_ready.cache_clear() + try: + with mock.patch.object(torch.version, "hip", "6.0"), \ + mock.patch.object(torch.cuda, "get_device_capability", return_value=(9, 0)) as capability: + self.assertFalse(ivf_fine._cute_ready(0)) + capability.assert_not_called() + finally: + ivf_fine._cute_ready.cache_clear() + + def test_selected_cuda_dependencies_fail_loud(self): + import builtins + + original_import = builtins.__import__ + + def missing_import(name, *args, **kwargs): + if name.split(".")[0] in ("triton", "cutlass", "quack"): + raise ImportError("deliberately missing " + name) + return original_import(name, *args, **kwargs) + + ivf_fine._triton_kernels.cache_clear() + ivf_fine._cute_ready.cache_clear() + try: + with mock.patch.object(builtins, "__import__", side_effect=missing_import): + with self.assertRaisesRegex(ImportError, "require Triton"): + ivf_fine._search_triton(None, None, None, None) + with mock.patch.object(torch.version, "hip", None), \ + mock.patch.object(torch.cuda, "get_device_capability", return_value=(9, 0)): + with self.assertRaisesRegex(ImportError, "requires CuTe and quack"): + ivf_fine._cute_ready(0) + finally: + ivf_fine._triton_kernels.cache_clear() + ivf_fine._cute_ready.cache_clear() + + def test_blocks(self): + # Small blocks split rows and candidates; the running top-2 meets the same exact reference (CPU matmuls of + # other shapes may round the last bit differently). + index, rows, probes, result = self._case(256, 2048, 4, 16, 2, device="cpu", seed=8) + xq, vecs = ivf_fine._operands(index, rows) + blocked = ivf_fine._search_torch(index, xq, vecs, probes, block=64) + self._assert_exact(index, rows, probes, blocked) + torch.testing.assert_close(blocked[0], result[0], rtol=1e-6, atol=1e-4) + + def test_exact_reference(self): + for dtype, implem in (("bf16", 4), ("fp16", 4), ("bf16", 2)): + with self.subTest(dtype=dtype, implem=implem): + index, rows, probes, result = self._case(512, 1024, 16, 24, 3, device="cpu", dtype=dtype, implem=implem) + self._assert_exact(index, rows, probes, result) + index, rows, probes, result = self._case(256, 512, 8, 16, 2, device="cpu", ties=True) + self._assert_exact(index, rows, probes, result) + probes[:, 1] = probes[:, 0] # a list probed twice: the second candidate is still another ID + self._assert_exact(index, rows, probes, index.search_2nn(rows, coarse_idx=probes)) + + +@unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") +class TestExactRouting(unittest.TestCase): + def test_any_nlist_and_nprobe(self): + for d, nlist, nprobe in ((64, 64, 1), (96, 512, 24), (128, 1024, 16), (1024, 256, 4), (32, 20000, 64), + (16, 70000, 7), (32, 2048, 16), (32, 2049, 16), (16, 4097, 2049), (16, 9000, 5000), + (16, 9000, 9000)): + with self.subTest(d=d, nlist=nlist, nprobe=nprobe): + coarse, candidates, rows = _data(8192 if nprobe < 1024 else 256, 4 * nlist, nlist, d, nlist) + index = _index(coarse, candidates, nprobe) + rows = rows.cuda() + self.assertTrue(torch.equal(index.route(rows), _topk_route(index, rows))) + + def test_boundary_ties_take_lower_ids(self): + coarse = torch.randn(64, 32) + coarse[32:] = coarse[:32] # every score appears twice + index = _index(coarse, torch.randn(256, 32), 5) + rows = torch.randn(1024, 32, device="cuda") + self.assertTrue(torch.equal(index.route(rows), _topk_route(index, rows))) # lower ID first among equals + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_precision_boundary.py b/thirdparty/faiss/tests/torch_test_e_means_precision_boundary.py new file mode 100644 index 000000000..99be31640 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_precision_boundary.py @@ -0,0 +1,342 @@ +# 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. + +"""Real-row precision regression and separately labelled small branch laws.""" +import copy +import datetime +import tempfile +import unittest +from contextlib import contextmanager +from unittest import mock + +import numpy as np +import torch +import torch.distributed as dist + +from faiss.contrib.e_means import DistributedEmeans, DistributedNumpyEmeans, NumpyEmeans +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means import e_means as numpy_engine +from faiss.contrib.e_means import e_means_torch as torch_engine +from faiss.contrib.e_means import e_means_quantized as quantized_engine + + +def _host(value): + return value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else value + + +@contextmanager +def _small_branch(): + # Branch proof ONLY: actual rows, recipe/share and integer bounds stay real. + with mock.patch.object(numpy_engine, '_FLOAT32_COUNT_LIMIT', 4), \ + mock.patch.object(torch_engine, '_FLOAT32_COUNT_LIMIT', 4), \ + mock.patch.object(quantized_engine, '_FLOAT32_COUNT_LIMIT', 4): + yield + + +@contextmanager +def _no_partial_comms(): + names = ('broadcast', 'all_reduce', 'all_gather', 'all_gather_object') + with mock.patch.multiple(dist, **{name: mock.Mock(side_effect=AssertionError('partial communication')) + for name in names}): + yield + + +class _PrepareWitness(DistributedEmeans): + def _prepare_statistics(self, stats, expected_n): + self.calls = getattr(self, 'calls', []) + ['prepare'] + return super()._prepare_statistics(stats, expected_n) + + def _apply_statistics(self, *args, **kwargs): + self.calls.append('apply') + return super()._apply_statistics(*args, **kwargs) + + +class _CostWitness(_PrepareWitness): + def _initial_removal_axes(self): + self.init_calls = getattr(self, 'init_calls', 0) + 1 + return torch.ones_like(self._centroids) + + +class _NumpyCostWitness(DistributedNumpyEmeans): + def _initial_removal_axes(self): + self.init_calls = getattr(self, 'init_calls', 0) + 1 + return np.ones_like(self._centroids) + + +def _models(numpy_state, *, group=None, cost=False, transport='dense', n=10, batch=8): + initial = np.array([[1e9], [0.], [-1e9], [5e8]], dtype='float32') + options = dict(nepochs=1, batch_size=batch, alpha0=1, seed=7, + unused_threshold=None if cost else 0, assignment_chunk_size=4) + if numpy_state: + cls = (_NumpyCostWitness if cost else DistributedNumpyEmeans) if group is not None else NumpyEmeans + model = cls(1, 4, **options, **({} if group is None else dict(group=group, transport=transport))) + caller = initial.copy() + else: + cls = (_CostWitness if cost else _PrepareWitness) if group is not None else QuantizedEmeans + model = cls(1, 4, quantizer=None, **options, + **({} if group is None else dict(group=group, transport=transport))) + caller = torch.from_numpy(initial.copy()) + model.begin(n, caller) + np.testing.assert_array_equal(_host(caller), initial) + return model, initial + + +def _branch_case(numpy_state, transport, mode='native', cost=False): + model, initial = _models(numpy_state, group=dist.group.WORLD, transport=transport, cost=cost) + rank = dist.get_rank() + rows = np.array([[2**24], [1.], [-2**24], [1.]], dtype='float32') + values = rows if numpy_state else torch.from_numpy(rows.copy()) + empty = values[:0] + with _small_branch(), _no_partial_comms(): + model.accumulate(empty) + cut = 1 if rank == 0 else 2 + partial = model.accumulate(values[:cut]) + assert partial['sums'] is None and partial['counts'] is None + model.accumulate(empty) + stats = model.accumulate(values[cut:]) + assert stats['n'] == 4 and _host(stats['sums']).dtype == np.float64 + if not numpy_state: + assert stats['stat_schema'] == torch.float32 + np.testing.assert_array_equal(_host(stats['sums'])[:, 0], [0., 2., 0., 0.]) + edit = mode in ('edit', 'replace') + independent = mode in ('deep', 'independent', 'edit', 'replace', 'fp64', 'unannotated') + if mode == 'dict': + stats = dict(stats) + elif independent: + removal = stats.get('removal') + stats = copy.deepcopy(stats) if mode == 'deep' else dict(stats) + stats['sums'] = stats['sums'].copy() if numpy_state else stats['sums'].clone() + stats['counts'] = stats['counts'].copy() if numpy_state else stats['counts'].clone() + if removal is not None: + stats['removal'] = removal # Required existing removal provenance. + if edit: + stats['sums'][1, 0] += .25 + if mode == 'replace': + stats['counts'] = stats['counts'].copy() if numpy_state else stats['counts'].clone() + if not numpy_state and mode == 'fp64': + stats['stat_schema'] = torch.float64 + if not numpy_state and mode == 'unannotated': + stats.pop('stat_schema') + saved = {key: _host(stats[key]).copy() for key in ('sums', 'counts')} + model.update(stats) + global_sum = 4.5 if edit else 4. + expected_dtype = np.float64 if not numpy_state and mode in ('fp64', 'unannotated') else np.float32 + assert _host(model._batch_stats).dtype == expected_dtype + np.testing.assert_array_equal(_host(model._pass_sums)[:, 0], [0., global_sum, 0., 0.]) + np.testing.assert_array_equal(_host(model._pass_counts), [0., 8., 0., 0.]) + np.testing.assert_array_equal(_host(model.current_centroids())[1], [global_sum / 8]) + if independent: + for key, value in saved.items(): + np.testing.assert_array_equal(_host(stats[key]), value) + if not numpy_state: + assert model.calls == ['prepare', 'apply'] + if cost: + assert model.init_calls == 1 + assert _host(model._removal_stats).dtype == np.float32 + # Independent D1 oracle: y=x at center0; all axes are +1. + all_rows = np.concatenate((rows, rows)).astype('float64')[:, 0] + distances = np.square(all_rows[:, None] - initial[:, 0].astype('float64')) + nearest_two = np.sort(distances, axis=1)[:, :2] + expected_u = np.square(all_rows).sum() + expected_r = np.diff(nearest_two, axis=1).sum() + np.testing.assert_allclose(_host(model._removal_stats)[1], [expected_u, expected_r], rtol=1e-5, atol=1e-5) + with _no_partial_comms(): + after = model.accumulate(empty) + assert _host(after['sums']).dtype == expected_dtype and 'stat_schema' not in after + # Actual next logical tail is2, below the lowered4 threshold. + tail = np.array([[2.]], dtype='float32') + stats = model.accumulate(tail if numpy_state else torch.from_numpy(tail)) + assert _host(stats['sums']).dtype == expected_dtype + model.update(stats) + model.end_epoch() + final = _host(model.finalize()) + np.testing.assert_allclose(final[1], [(global_sum + 4) / 10], rtol=0, atol=np.spacing(np.float32(.85))) + np.testing.assert_array_equal(final[[0, 2, 3]], initial[[0, 2, 3]]) + + +def _small_declared_raw(transport): + model, _ = _models(False, group=dist.group.WORLD, transport=transport, n=4, batch=4) + rank = dist.get_rank() + stats = dict(n=2, sums=torch.zeros((4, 1), dtype=torch.float64), + counts=torch.tensor([0, 2, 0, 0], dtype=torch.int64), + objective=torch.tensor(0., dtype=torch.float64), stat_schema=torch.float32) + stats['sums'][1, 0] = (1 + 2**-24) if rank == 0 else -1 + saved = stats['sums'].clone() + model.update(stats) + # Early per-rank FP32 narrowing erases the nonzero exact global sum. + np.testing.assert_array_equal(_host(model._pass_sums)[1], [2**-24]) + np.testing.assert_array_equal(_host(model.current_centroids())[1], [2**-26]) + torch.testing.assert_close(stats['sums'], saved, rtol=0, atol=0) + assert model.accumulate(torch.empty((0, 1)))['sums'].dtype == torch.float32 + + +def _real_case(numpy_state): + size, share = 2**24 + 2, 2**23 + 1 + initial = np.array([[0.], [1.]], dtype='float32') + options = dict(nepochs=1, batch_size=size, alpha0=1, seed=7, + unused_threshold=0, assignment_chunk_size=1 << 18) + cls = DistributedNumpyEmeans if numpy_state else DistributedEmeans + model = cls(1, 2, group=dist.group.WORLD, transport='dense', **options, + **({} if numpy_state else dict(quantizer=None))) + caller = initial.copy() if numpy_state else torch.from_numpy(initial.copy()) + model.begin(size, caller) + rows = np.full((share, 1), np.float32(.1), dtype='float32') + values = rows if numpy_state else torch.from_numpy(rows) + cut = share // 3 if dist.get_rank() == 0 else share // 2 + with _no_partial_comms(): + model.accumulate(values[:cut]) + model.accumulate(values[:0]) + stats = model.accumulate(values[cut:]) + assert stats['n'] == share and _host(stats['sums']).dtype == np.float64 + if not numpy_state: + assert stats['stat_schema'] == torch.float32 + model.update(stats) + exact_sum = size * float(np.float32(.1)) + np.testing.assert_array_equal(_host(stats['sums'])[:, 0], [exact_sum, 0.]) + np.testing.assert_array_equal(_host(stats['counts']), [size, 0.]) + np.testing.assert_array_equal(_host(model._pass_sums)[:, 0], [np.float32(exact_sum), 0.]) + np.testing.assert_array_equal(_host(model._pass_counts), [size, 0.]) + expected = torch.tensor([[np.float32(.1)], [1.]], dtype=torch.float32) + if dist.get_rank() == 0: + local_cls = NumpyEmeans if numpy_state else QuantizedEmeans + reference = local_cls(1, 2, **options, **({} if numpy_state else dict(quantizer=None))) + reference.begin(size, initial.copy() if numpy_state else torch.from_numpy(initial.copy())) + whole = np.full((size, 1), np.float32(.1), dtype='float32') + reference_stats = reference.accumulate(whole if numpy_state else torch.from_numpy(whole)) + assert _host(reference_stats['sums']).dtype == np.float32 and 'stat_schema' not in reference_stats + reference.update(reference_stats) + np.testing.assert_array_equal(_host(reference._pass_sums), _host(model._pass_sums)) + expected.copy_(torch.from_numpy(_host(reference.current_centroids()).copy())) + dist.broadcast(expected, src=0) + np.testing.assert_allclose(_host(model.current_centroids()), expected.numpy(), rtol=0, + atol=np.spacing(np.float32(.1))) + np.testing.assert_array_equal(_host(caller), initial) + np.testing.assert_array_equal(rows, np.full_like(rows, np.float32(.1))) + model.end_epoch() + assert model.n_splits == 0 + np.testing.assert_allclose(_host(model.finalize()), expected.numpy(), rtol=0, + atol=np.spacing(np.float32(.1))) + + +def _pending_schema_case(): + for tag in (torch.float64, 'invalid', None, torch.int64, 'removed'): + model, _ = _models(False, group=dist.group.WORLD, n=8) + values = torch.tensor([[1.], [2.], [3.], [4.]]) + with _small_branch(), _no_partial_comms(): + stats = model.accumulate(values) + assert stats['sums'].dtype == torch.float64 and stats['stat_schema'] == torch.float32 + if tag == 'removed': + stats.pop('stat_schema') + else: + stats['stat_schema'] = tag # Edit the actual published pending record. + after_empty = model.accumulate(values[:0]) + assert 'stat_schema' not in after_empty if tag == 'removed' else after_empty['stat_schema'] == tag + if tag in (torch.float64, 'removed'): + model.update(after_empty) + expected_dtype = torch.float64 + else: + with unittest.TestCase().assertRaisesRegex(ValueError, 'stat_schema'): + model.update(after_empty) + assert not model._failed and model._step == 0 + assert model._batch_stats.dtype == torch.float32 + # Retry using explicitly repaired metadata; original supplied values remain. + model.update(dict(after_empty, stat_schema=torch.float32)) + expected_dtype = torch.float32 + assert model._batch_stats.dtype == expected_dtype + np.testing.assert_array_equal(_host(model._pass_sums)[:, 0], [0., 20., 0., 0.]) + np.testing.assert_array_equal(_host(model.current_centroids())[1], [2.5]) + with _no_partial_comms(): + assert model.accumulate(values[:0])['sums'].dtype == expected_dtype + model.end_epoch() + np.testing.assert_array_equal(_host(model.finalize())[1], [2.5]) + + +def _worker(rank, init, kind): + torch.set_num_threads(1) + dist.init_process_group('gloo', rank=rank, world_size=2, init_method=init, + timeout=datetime.timedelta(seconds=240)) + try: + if kind.startswith('real'): + _real_case(kind == 'real_numpy') + elif kind == 'pending_schema': + _pending_schema_case() + else: + for transport in ('dense', 'sparse', 'auto'): + for numpy_state in (True, False): + for mode in ('native', 'dict', 'deep', 'independent', 'edit', 'replace'): + _branch_case(numpy_state, transport, mode) + _branch_case(numpy_state, transport, cost=True) + for mode in ('fp64', 'unannotated'): + _branch_case(False, transport, mode) + _small_declared_raw(transport) + finally: + dist.destroy_process_group() + + +class TestPrecisionBoundary(unittest.TestCase): + def spawn(self, kind): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn(_worker, args=('file://' + directory + '/group', kind), + nprocs=2, join=True) + + def test_real_numpy_rows(self): + self.spawn('real_numpy') + + def test_real_tensor_rows(self): + self.spawn('real_tensor') + + def test_reduced_threshold_authority_schema_and_transports(self): + self.spawn('branch') + + def test_pending_schema_survives_empty_accumulation(self): + self.spawn('pending_schema') + + def test_local_small_and_wide_completion_laws(self): + for numpy_state in (True, False): + for lowered in (False, True): + model, _ = _models(numpy_state, n=8) + raw = np.array([[2**24], [1.], [-2**24], [1.]] * 2, dtype='float32') + with _small_branch() if lowered else mock.patch.object(numpy_engine, '_FLOAT32_COUNT_LIMIT', 2**24): + stats = model.accumulate(raw if numpy_state else torch.from_numpy(raw)) + assert _host(stats['sums']).dtype == np.float32 and 'stat_schema' not in stats + # Lowered wide branch is exact; ordinary sequential FP32 law + # depends on backend addition order, so only its schema is fixed here. + if lowered: + np.testing.assert_array_equal(_host(stats['sums'])[1], [4.]) + model.update(stats) + + def test_invalid_metadata_and_running_priority(self): + model = QuantizedEmeans(1, 2, quantizer=None, unused_threshold=0, batch_size=4, nepochs=1) + invalid = dict(n=4, sums=torch.zeros((2, 1)), counts=torch.ones(2), + objective=torch.tensor(0., dtype=torch.float64), stat_schema='float32') + with self.assertRaises(TypeError): + model.update(invalid) + model.begin(4, torch.tensor([[0.], [1.]])) + saved = model.current_centroids().clone() + for schema, sums, counts in ( + (None, torch.float64, torch.float64), ('float32', torch.float64, torch.float64), + (True, torch.float64, torch.float64), (torch.int64, torch.float64, torch.float64), + (torch.complex64, torch.float64, torch.float64), (torch.float16, torch.float64, torch.float64), + (torch.float32, torch.int64, torch.int64), (torch.float64, torch.int32, torch.int64)): + stats = dict(invalid, stat_schema=schema, sums=torch.zeros((2, 1), dtype=sums), + counts=torch.ones(2, dtype=counts)) + with self.subTest(schema=schema, sums=sums): + with self.assertRaisesRegex(ValueError, 'stat_schema'): + model.update(stats) + assert not model._failed and model._batch_stats.dtype == torch.float32 + assert model._step == 0 + torch.testing.assert_close(model.current_centroids(), saved, rtol=0, atol=0) + for key in ('sums', 'counts'): + with self.assertRaisesRegex(ValueError, 'stat_schema'): + model.update(dict(invalid, stat_schema=torch.float32, **{key: None})) + assert not model._failed and model._step == 0 + model._failed = True + with self.assertRaises(RuntimeError): + model.update(invalid) + numpy = NumpyEmeans(1, 2, unused_threshold=0, batch_size=4, nepochs=1) + numpy.begin(4, np.array([[0.], [1.]], dtype='float32')) + with self.assertRaisesRegex(ValueError, 'Tensor'): + numpy.update(dict(n=4, sums=np.zeros((2, 1), dtype='float32'), counts=np.ones(2, dtype='float32'), + objective=np.float64(0), stat_schema=torch.float32)) diff --git a/thirdparty/faiss/tests/torch_test_e_means_replicated_revival.py b/thirdparty/faiss/tests/torch_test_e_means_replicated_revival.py new file mode 100644 index 000000000..114553d3f --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_replicated_revival.py @@ -0,0 +1,468 @@ +# 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. + +"""Small independent laws for caller-driven replicated floating revival.""" +import datetime +import gc +import tempfile +import types +import unittest +from unittest import mock + +import numpy as np +import torch +import torch.distributed as dist + +from faiss.contrib.e_means import DistributedEmeans, DistributedNumpyEmeans, NumpyEmeans +from faiss.contrib.e_means.e_means_quantized import QuantizedEmeans +from faiss.contrib.e_means.quantizer import CastQuantizer +from faiss.contrib.e_means.quantizer_int8 import Int8Quantizer +from faiss.contrib.e_means import e_means_distributed as replica + + +def _host(value): + return value.detach().cpu().numpy() if isinstance(value, torch.Tensor) else np.asarray(value) + + +def _pairs(model): + """Enumerate the law from readout/state; never call a production selector.""" + removal = _host(model._removal_stats).astype('float64') + usage = _host(model._usage) + gain = (np.linalg.norm(removal[:, :-1], axis=1) * getattr(model, '_axis_scale', 1.)).astype('float32') + candidates = np.flatnonzero((removal[:, -1] <= 0) | (removal[:, -1] < .3 * np.median(removal[:, -1]))) + kept = candidates[np.argsort(removal[candidates, -1], kind='stable')].tolist() + donors = [int(i) for i in np.argsort(-gain, kind='stable') if usage[i] > 0 and i not in kept] + n = min(len(donors), len(kept)) + if not n: + return None, None + source, target = np.array(donors[:n], dtype='int64'), np.array(kept[:n], dtype='int64') + if isinstance(model._centroids, np.ndarray): + return source, target + return torch.from_numpy(source).to(model._centroids.device), torch.from_numpy(target).to(model._centroids.device) + + +def _reference_revival(model, rng): + source, target = _pairs(model) + return 0 if source is None else model._apply_splits(source, target) + + +def _agree(value, group): + tensor = torch.from_numpy(value) if isinstance(value, np.ndarray) else value + copies = [torch.empty_like(tensor) for _ in range(dist.get_world_size(group))] + dist.all_gather(copies, tensor, group=group) + for other in copies: + torch.testing.assert_close(tensor, other, rtol=0, atol=0) + + +class _InitWitness(DistributedEmeans): + def _initialize_removal_statistics(self): + self.init_calls = getattr(self, 'init_calls', 0) + 1 + super()._initialize_removal_statistics() + + +class _DecodedCast(CastQuantizer): + def decode(self, codes): + self.decode_calls = getattr(self, 'decode_calls', 0) + 1 + return super().decode(codes) + .125 + + +class _CentroidInitWitness(_InitWitness): + def _initialize_removal_statistics(self): + super()._initialize_removal_statistics() + self.init_centroid_sign = float(self._centroids[0, 0]) + self._axes.mul_(1. if self.init_centroid_sign > 0 else -1.) + + +class _NumpyCentroidInitWitness(DistributedNumpyEmeans): + def _initial_removal_axes(self): + self.init_calls = getattr(self, 'init_calls', 0) + 1 + self.init_centroid_sign = float(self._centroids[0, 0]) + return super()._initial_removal_axes() * (1. if self.init_centroid_sign > 0 else -1.) + + +def _caller_case(group, device, transport, *, numpy_state=False, dtype=torch.float32, + centered=False, custom_decode=False, mixed=False, epochs=1, calibrated=False): + rank = dist.get_rank(group) + initial_cpu = np.array([[100.], [200.], [0.], [300.], [400.], [500.], [600.], [2.]], dtype='float32') + initial = initial_cpu.copy() if numpy_state else torch.from_numpy(initial_cpu).to(device) + options = dict(nepochs=epochs, batch_size=4, alpha0=.5, seed=7, assignment_chunk_size=1) + q = None + if centered or custom_decode: + q = (_DecodedCast if custom_decode else CastQuantizer)(1, torch.bfloat16, center=True) + q.train(torch.full((2, 1), 100., device=device)) + if calibrated: + q = Int8Quantizer(1) + q.train(initial) + input_dtype = torch.int8 if calibrated else torch.float32 if q is not None else dtype + if numpy_state: + model = DistributedNumpyEmeans(1, 8, group=group, transport=transport, **options) + reference = NumpyEmeans(1, 8, **options) + else: + model = _InitWitness(1, 8, group=group, transport=transport, quantizer=q, **options) + reference = QuantizedEmeans(1, 8, quantizer=q, **options) + caller_initial = initial + 1000 * rank + saved_initial = _host(caller_initial).copy() + population = 28 if epochs == 2.5 else 26 # Includes a real global tail. + model.begin(population, caller_initial) + reference.begin(population, initial) + np.testing.assert_array_equal(_host(caller_initial), saved_initial) + before_rng = None if numpy_state else model._split_rng.get_state().clone() + empty = np.empty((0, 1), dtype='float32') if numpy_state else torch.empty((0, 1), dtype=input_dtype, device=device) + # Initial binding and all subsequent caller partials communicate nothing. + methods = ('broadcast', 'all_reduce', 'all_gather', 'all_gather_object') + with mock.patch.multiple(dist, **{name: mock.Mock(side_effect=AssertionError('partial collective')) for name in methods}): + model.accumulate(empty) + reference.accumulate(empty) + if numpy_state: + reference._axes[:] = model._axes + else: + reference._axes.copy_(model._axes) + torch.testing.assert_close(model._split_rng.get_state(), before_rng, rtol=0, atol=0) + assert model.init_calls == 1 + _agree(model._axes, group) + reference._revive_unused = types.MethodType(_reference_revival, reference) + choice_calls = [0] + original_choice = model._choose_splits + + def checked_choice(rng): + saved = [_host(v).copy() for v in (model._centroids, model._usage, model._removal_stats, model._axes)] + old_count = model.n_splits + actual = original_choice(rng) + wanted = _pairs(model) + for a, b in zip(actual, wanted): + assert (a is None) == (b is None) + if a is not None: + np.testing.assert_array_equal(_host(a), _host(b)) + for value, old in zip((model._centroids, model._usage, model._removal_stats, model._axes), saved): + np.testing.assert_array_equal(_host(value), old) + assert model.n_splits == old_count + choice_calls[0] += 1 + return actual + + model._choose_splits = checked_choice + first_axes = _host(model._axes).copy() + for epoch, epoch_n in enumerate(model.recipe['epoch_rows']): + for step, begin in enumerate(range(0, epoch_n, 4)): + full_cpu = np.array([[0.], [.5], [2.], [2.5]], dtype='float32') + n = min(4, epoch_n - begin) + full = full_cpu[:n] if numpy_state else torch.from_numpy(full_cpu[:n]).to(device=device, dtype=torch.float32 if calibrated else input_dtype) + if calibrated: + full = q.compute_codes(full) + local = full[rank * (n // 2):(rank + 1) * (n // 2)] + with mock.patch.multiple(dist, **{name: mock.Mock(side_effect=AssertionError('partial collective')) for name in methods}): + if rank == 0 and len(local) > 1: + partial = model.accumulate(local[:1]) + assert partial['sums'] is None + model.accumulate(empty) + stats = model.accumulate(local[1:]) + else: + stats = model.accumulate(local) + reference_stats = reference.accumulate(full) + # S/N are caller-owned copies. Removal remains the documented + # borrowed model provenance object, consumed by the shared EMA. + stats = dict(stats, **{name: value.copy() if isinstance(value, np.ndarray) else value.clone() if isinstance(value, torch.Tensor) else value + for name, value in stats.items() if name in ('sums', 'counts', 'objective')}) + saved_sums, saved_counts = _host(stats['sums']).copy(), _host(stats['counts']).copy() + if mixed: + assert not numpy_state + stats = dict(stats, sums=stats['sums'].double().requires_grad_(), + counts=stats['counts'].double().requires_grad_(), + objective=stats['objective'].clone().requires_grad_()) + reference_stats = dict(reference_stats, sums=reference_stats['sums'].double(), + counts=reference_stats['counts'].double()) + model.update(stats) + reference.update(reference_stats) + np.testing.assert_array_equal(_host(stats['sums']), saved_sums) + np.testing.assert_array_equal(_host(stats['counts']), saved_counts) + for name in ('_centroids', '_usage', '_removal_stats', '_axes', '_pass_counts'): + actual, expected = _host(getattr(model, name)), _host(getattr(reference, name)) + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-5) + _agree(getattr(model, name), group) + if model._pass_sums is not None: + np.testing.assert_allclose(_host(model._pass_sums), _host(reference._pass_sums), rtol=1e-5, atol=1e-5) + if epoch == step == 0 and not calibrated: + wanted_r = np.zeros(8, dtype='float32') + wanted_r[[2, 7]] = [3., 5.] + offset = .125 if custom_decode else 0. + expected_gain = .5 * (offset**2 + (.5 + offset)**2) + wanted_u = np.zeros((8, 1), dtype='float32') + wanted_u[[2, 7]] = expected_gain * first_axes[[2, 7]] + np.testing.assert_array_equal(_host(model._removal_stats)[:, -1], wanted_r) + effective = _host(model._removal_stats)[:, :-1] * getattr(model, '_axis_scale', 1.) + np.testing.assert_array_equal(effective, wanted_u) + if mixed: + assert model._batch_stats.dtype == torch.float64 and model._batch_removal.dtype == torch.float32 + assert '_communication' not in vars(model) + assert model._epoch_rows == begin + n and model.n_splits == reference.n_splits + model.end_epoch() + reference.end_epoch() + np.testing.assert_allclose(_host(model._objective), _host(reference._objective), rtol=1e-5, atol=1e-5) + assert choice_calls[0] > 0 if rank == 0 else choice_calls[0] == 0 + assert model.n_splits == reference.n_splits and model.n_splits > 0 + if custom_decode: + assert q.decode_calls > 0 + np.testing.assert_allclose(_host(model.finalize()), _host(reference.finalize()), rtol=1e-5, atol=1e-5) + assert '_communication' not in vars(model) and model._axis_seed is None + + +def _typed_transport(group, device, transport): + rank = dist.get_rank(group) + sn = torch.zeros((8, 2), dtype=torch.int64, device=device) + ru = torch.zeros((8, 2), dtype=torch.float32, device=device) + sn[2] = torch.tensor([2**24 + 1, 1], device=device) + ru[2, 0] = .125 * (rank + 1) # Zero R cannot exclude this U record. + if rank: + sn[7] = torch.tensor([2**53 + 1, 1], device=device) + ru[7] = .5 + saved = sn.clone(), ru.clone() + ids, values = replica._combine_payloads((sn.clone(), ru.clone()), sn[:, -1], group, transport, 4) + expected_sn, expected_ru = sn.new_zeros((8, 2)), ru.new_zeros((8, 2)) + expected_sn[2] = torch.tensor([2**25 + 2, 2], device=device) + expected_sn[7] = torch.tensor([2**53 + 1, 1], device=device) + expected_ru[2, 0], expected_ru[7] = .375, .5 + for actual, expected in zip(values, (expected_sn, expected_ru)): + assert actual.dtype == expected.dtype + torch.testing.assert_close(actual, expected if ids is None else expected[ids], rtol=0, atol=0) + for actual, expected in zip((sn, ru), saved): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +def _analytical_batch(group, device, transport, numpy_state=False): + rank = dist.get_rank(group) + initial = np.array([[0.], [2.]], dtype='float32') + options = dict(group=group, transport=transport, seed=7, nepochs=1, batch_size=2, alpha0=.5) + if numpy_state: + model = DistributedNumpyEmeans(1, 2, **options) + else: + model = DistributedEmeans(1, 2, quantizer=None, **options) + initial = torch.from_numpy(initial).to(device) + model.begin(4, initial) + empty = np.empty((0, 1), dtype='float32') if numpy_state else torch.empty((0, 1), device=device) + model.accumulate(empty) + np.testing.assert_array_equal(_host(model._axes)[0], [1.]) + x = np.array([[.25 if rank == 0 else -.25]], dtype='float32') + stats = model.accumulate(x if numpy_state else torch.from_numpy(x).to(device)) + model.update(stats) + np.testing.assert_array_equal(_host(model._removal_stats)[:, -1], [4., 0.]) + effective = _host(model._removal_stats)[:, :-1] * getattr(model, '_axis_scale', 1.) + np.testing.assert_array_equal(effective[:, 0], [.0625, 0.]) + np.testing.assert_array_equal(_host(model._pass_counts), [2., 0.]) + np.testing.assert_array_equal(_host(model._pass_sums), [[0.], [0.]]) + _agree(model._removal_stats, group) + _agree(model._axes, group) + + +def _seed_and_legacy_contracts(group, device): + rank = dist.get_rank(group) + initial = torch.arange(12, device=device, dtype=torch.float32).reshape(4, 3) + for seed in (-1, 2**63 + 7): + model = _InitWitness(3, 4, group=group, quantizer=None, seed=seed, + batch_size=4, nepochs=1) + ambient = torch.random.get_rng_state().clone() + model.begin(4, initial) + assert model._axes is not None and model._axis_seed == torch.Generator().manual_seed(seed).initial_seed() + _agree(model._axes, group) + sums, counts = torch.zeros((4, 3), device=device), torch.zeros(4, device=device) + with mock.patch.object(dist, 'all_reduce', side_effect=AssertionError('invalid update communicated')): + with unittest.TestCase().assertRaisesRegex(ValueError, 'typed input statistics'): + model.update({}) # Typed validation precedes n access and communication. + with unittest.TestCase().assertRaisesRegex(ValueError, 'typed input statistics'): + model.update(dict(sums=sums, counts=counts, objective=torch.zeros((), device=device), n=2)) + model._split_rng.manual_seed(991 + rank) + saved = model._split_rng.get_state().clone() + with mock.patch.object(dist, 'broadcast', side_effect=AssertionError('partial broadcast')): + model.accumulate(torch.empty((0, 3), device=device)) + _agree(model._axes, group) + torch.testing.assert_close(model._split_rng.get_state(), saved, rtol=0, atol=0) + torch.testing.assert_close(torch.random.get_rng_state(), ambient, rtol=0, atol=0) + with mock.patch.object(dist, 'all_reduce', side_effect=AssertionError('missing R communicated')): + with unittest.TestCase().assertRaisesRegex(ValueError, "this model's accumulate"): + model.update(dict(sums=sums, counts=counts, objective=torch.zeros((), device=device), n=2)) + assert model.init_calls == 1 and '_communication' not in vars(model) + # Explicit mass keeps caller-owned staging/coercion and the model RNG; + # landed #5915 also retains its donor-axis/removal state. + for transport in ('dense', 'sparse', 'auto'): + legacy = DistributedEmeans(3, 4, group=group, transport=transport, quantizer=None, + unused_threshold=.1, batch_size=4, nepochs=1) + legacy.begin(4, initial) + legacy._split_rng.manual_seed(991 + rank) + before_rng = legacy._split_rng.get_state().clone() + assert legacy._axes is not None and legacy._axis_seed is None + sums = torch.zeros((4, 3), device=device, dtype=torch.float64, requires_grad=True) + counts = torch.tensor([2, 0, 0, 0], device=device, dtype=torch.int64) + before = sums.clone(), counts.clone() + legacy.update(dict(sums=sums, counts=counts, objective=torch.zeros((), device=device), n=2)) + for value, expected in zip((sums, counts), before): + torch.testing.assert_close(value, expected, rtol=0, atol=0) + torch.testing.assert_close(legacy._split_rng.get_state(), before_rng, rtol=0, atol=0) + assert '_communication' not in vars(legacy) and legacy._removal_stats is not None + legacy.end_epoch() + legacy.finalize() + + +def _canonical_init_hook(group, device, numpy_state=False): + rank = dist.get_rank(group) + canonical = np.array([[-1.], [2.]], dtype='float32') + placeholder = canonical if rank == 0 else -canonical + if numpy_state: + caller = placeholder.copy() + model = _NumpyCentroidInitWitness(1, 2, group=group, batch_size=2, alpha0=.5, nepochs=1, seed=7) + expected_rng = np.random.RandomState(7) + else: + caller = torch.from_numpy(placeholder).to(device) + q = CastQuantizer(1, torch.bfloat16) if device.type == 'cuda' else None + model = _CentroidInitWitness(1, 2, group=group, quantizer=q, + batch_size=2, alpha0=.5, nepochs=1, seed=7) + expected_rng = np.random.Generator(np.random.PCG64(7)) + saved = _host(caller).copy() + model.begin(4, caller) + if model._axes is None: + model.accumulate(torch.empty((0, 1), device=device)) + expected = expected_rng.standard_normal((2, 1)) + expected = -(expected / np.linalg.norm(expected, axis=1, keepdims=True)).astype('float32') + np.testing.assert_array_equal(_host(model._centroids), canonical) + np.testing.assert_array_equal(_host(caller), saved) + np.testing.assert_array_equal(_host(model._axes), expected) + assert model.init_calls == 1 and model.init_centroid_sign == -1. + _agree(model._axes, group) + x = np.array([[-.75 if rank == 0 else -1.25]], dtype='float32') + stats = model.accumulate(x if numpy_state else torch.from_numpy(x).to(device)) + model.update(stats) + np.testing.assert_array_equal(_host(model._removal_stats)[:, -1], [9., 0.]) + u = _host(model._removal_stats)[:, :-1] * getattr(model, '_axis_scale', 1.) + np.testing.assert_array_equal(u[0], expected[0] * .0625) + _agree(model._removal_stats, group) + + +def _worker(rank, world, rendezvous, cuda=False, subgroup=False): + torch.set_num_threads(1) + if cuda: + torch.cuda.set_device(rank) + device = torch.device('cuda', rank) if cuda else torch.device('cpu') + dist.init_process_group('nccl' if cuda else 'gloo', init_method=rendezvous, + rank=rank, world_size=world, timeout=datetime.timedelta(seconds=120)) + group = dist.new_group([1, 2]) if subgroup else dist.group.WORLD + try: + if not subgroup or rank in (1, 2): + _seed_and_legacy_contracts(group, device) + _canonical_init_hook(group, device) + if not cuda: + _canonical_init_hook(group, device, numpy_state=True) + for transport in ('dense', 'sparse', 'auto'): + _typed_transport(group, device, transport) + _analytical_batch(group, device, transport) + _caller_case(group, device, transport, epochs=2.5 if subgroup else 1) + if not cuda: + _analytical_batch(group, device, transport, numpy_state=True) + _caller_case(group, device, transport, numpy_state=True) + _caller_case(group, device, transport, mixed=True) + if cuda: + for dtype in (torch.float16, torch.bfloat16): + _caller_case(group, device, 'sparse', dtype=dtype) + _caller_case(group, device, 'dense', dtype=torch.bfloat16, centered=True) + _caller_case(group, device, 'dense', dtype=torch.bfloat16, custom_decode=True) + if torch.cuda.get_device_capability(device) in ((8, 0), (9, 0), (10, 0)): + _caller_case(group, device, 'sparse', calibrated=True, epochs=2.5) + dist.barrier() + finally: + # Release test-owned cycles before the caller-owned group joins Gloo work. + gc.collect() + if subgroup: + dist.destroy_process_group(group) + del group + dist.destroy_process_group() + + +class TestReplicatedFloating(unittest.TestCase): + def spawn(self, *, cuda=False, subgroup=False): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn(_worker, args=(3 if subgroup else 2, 'file://' + directory + '/group', cuda, subgroup), + nprocs=3 if subgroup else 2, join=True) + + def test_cpu_gloo_global_cost_and_typed_transports(self): + self.spawn() + + def test_cpu_gloo_nonzero_global_root_and_fractional_budget(self): + self.spawn(subgroup=True) + + @unittest.skipUnless(torch.cuda.is_available() and not torch.version.hip and dist.is_nccl_available() + and torch.cuda.device_count() >= 2 and torch.cuda.get_device_capability() >= (8, 0), + 'two NVIDIA SM80+ GPUs/NCCL required for BF16 arms') + def test_two_gpu_nccl_native_cast_and_centered_cost(self): + self.spawn(cuda=True) + + def test_initializer_bound_and_generator_position(self): + for numpy_rng in (False, True): + factory = (lambda: np.random.RandomState(7)) if numpy_rng else (lambda: np.random.Generator(np.random.PCG64(7))) + expected_rng = factory() + expected = expected_rng.standard_normal((3, 65)) + expected = (expected / np.linalg.norm(expected, axis=1, keepdims=True)).astype('float32') + for budget in (1 << 25, 512): + rng = factory() + actual = np.empty((3, 65), dtype='float32') + with mock.patch.object(replica, '_AXIS_HOST_BYTES', budget): + replica._fill_initial_axes(actual, rng) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(rng.standard_normal(7), expected_rng.standard_normal(7)) + expected_rng = factory() + expected_rng.standard_normal((3, 65)) + + def test_auto_accounts_for_complete_typed_payload(self): + self.assertEqual(replica._select_transport(4, 1 << 20, 126, 2), 'dense') + self.assertEqual(replica._select_transport(4, 1 << 20, 126, 2, record_bytes=1024), 'sparse') + + def test_local_initial_axis_draws_and_rng_are_unchanged(self): + initial = np.arange(12, dtype='float32').reshape(4, 3) + n = NumpyEmeans(3, 4, seed=7, batch_size=4, nepochs=1) + n.begin(8, initial) + rng = np.random.RandomState(7) + raw = rng.standard_normal((4, 3)) + np.testing.assert_array_equal(n._axes, (raw / np.linalg.norm(raw, axis=1, keepdims=True)).astype('float32')) + np.testing.assert_array_equal(n._split_rng.standard_normal(7), rng.standard_normal(7)) + tensor = QuantizedEmeans(3, 4, seed=7, quantizer=None, batch_size=4, nepochs=1) + tensor.begin(8, torch.from_numpy(initial)) + tensor.accumulate(torch.empty((0, 3))) + generator = torch.Generator().manual_seed(7) + raw = torch.randn(4, 3, generator=generator) + torch.testing.assert_close(tensor._axes, raw / raw.norm(dim=1, keepdim=True), rtol=0, atol=0) + torch.testing.assert_close(tensor._split_rng.get_state(), generator.get_state(), rtol=0, atol=0) + + @unittest.skipUnless(torch.cuda.is_available() and not torch.version.hip + and torch.cuda.get_device_capability() >= (8, 0), 'Triton NVIDIA SM80+ required') + def test_custom_apply_keeps_gpu_choice_and_parent_fp32_keys(self): + class Hooked(QuantizedEmeans): + def _apply_splits(self, source, target): + self.apply_calls = getattr(self, 'apply_calls', 0) + 1 + return super()._apply_splits(source, target) + + m = Hooked(2, 3, quantizer=None, assignment_backend='triton', batch_size=2, nepochs=1) + m.begin(4, torch.tensor([[0., 0.], [2., 0.], [4., 0.]], device='cuda')) + m.accumulate(torch.empty((0, 2), device='cuda')) + m._usage.fill_(1) + m._removal_stats.zero_() + m._removal_stats[:, -1] = torch.tensor([0., 100., 100.], device='cuda') + m._removal_stats[1, 0] = 1 + m._removal_stats[2, :2] = torch.tensor([1., 2**-13], device='cuda') + self.assertTrue(m._device_choice_eligible()) + self.assertFalse(m._device_check()) + before = m._centroids.clone(), m._removal_stats.clone(), m._usage.clone() + source, target = m._choose_splits(m._split_rng) + self.assertEqual((source.tolist(), target.tolist()), ([1], [0])) + for actual, expected in zip((source, target), _pairs(m)): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + # Parent host and fused rules both rank FP32 keys. The double norms + # differ, but their equal FP32 keys retain the lower donor ID. + host = m._choose_removal_splits(m._removal_stats[:, -1].double().cpu().numpy(), + m._usage.double().cpu().numpy(), + m._removal_stats[:, :-1].double().norm(dim=1).cpu().numpy()) + self.assertEqual((host[0].tolist(), host[1].tolist()), ([1], [0])) + for actual, expected in zip((m._centroids, m._removal_stats, m._usage), before): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + counter = torch.zeros((), dtype=torch.int64, device='cuda') + victims, donors, count = m._removal_pairs(counter) + self.assertEqual((donors[:int(count)].tolist(), victims[:int(count)].tolist()), ([1], [0])) + self.assertEqual(int(counter), 1) # Existing fused FP32 key order retained. + m._revive_unused(m._split_rng) + self.assertEqual((m.apply_calls, m.n_splits), (1, 1)) diff --git a/thirdparty/faiss/tests/torch_test_e_means_row_norms.py b/thirdparty/faiss/tests/torch_test_e_means_row_norms.py new file mode 100644 index 000000000..0e7b656e5 --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_row_norms.py @@ -0,0 +1,247 @@ +# 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. + +"""Bounded reductions for DINO query scoring and sharded revival.""" + +import datetime +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +import numpy as np +import torch +import torch.distributed as dist + +from faiss.contrib.e_means.sharded_centroids import _removal_scalar_stats + +# Bare pytest exposes tests/, while Buck already exposes the mapped namespace. +_SOURCE_ROOT = str(Path(__file__).absolute().parents[1]) +if _SOURCE_ROOT not in sys.path: + sys.path.append(_SOURCE_ROOT) +from benchs.e_means import dino_data as _DINO # noqa: E402 + + +def _check_query_mse(model, device): + from faiss.contrib.e_means import EmeansShardedCentroids + rank, ranks = dist.get_rank(), dist.get_world_size() + centroids = ( + model.centroids if model.centroids is not None else model._centroids + ) + shards = [torch.empty_like(centroids) for _ in range(ranks)] + dist.all_gather(shards, centroids) + full = torch.cat(shards) + state = { + key: value.clone() + for key, value in vars(model).items() + if isinstance(value, torch.Tensor) + } + ivf = getattr(model, "_ivf", None) + data = np.random.RandomState(27).randint( + 0, 8, (17, model.d), dtype=np.uint8 + ) + raw = np.empty((17, model.d + 4), dtype=np.uint8) + raw[:, :4] = np.frombuffer(np.int32(model.d).tobytes(), dtype=np.uint8) + raw[:, 4:] = data + mean = torch.full((model.d,), 3.0, device=device) + scale = 2.0 + test_indices = np.random.RandomState(1234).permutation(len(data))[ + round(0.5 * len(data)): + ] + original = torch.from_numpy(data[test_indices]).to(device).double() + expected = ( + (original[:, None, :] - (full.double() * scale + mean)[None, :, :]) + .square() + .sum(2) + .min(1) + .values.mean() + .item() + ) + represented = full.to(torch.bfloat16) + query_rows = ((original.float() - mean) / scale).to(torch.bfloat16) + scores = represented.float().square().sum(1)[None, :] - 2 * torch.mm( + query_rows, represented.t(), out_dtype=torch.float32 + ) + bf16_expected = ( + (original - (full.double() * scale + mean)[scores.argmin(1)]) + .square().sum(1).mean().item() + ) + with tempfile.TemporaryDirectory(prefix="dino-query-test-") as directory: + path = Path(directory) / "queries_clean.bvecs" + raw.tofile(path) + queries = _DINO.DinoQueries(directory, model.d, n=17) + assert queries.n == 9 + np.testing.assert_array_equal(queries.indices, test_indices) + for batch_size in (4, 17, 32): + for precision, oracle in (("fp32", expected), ("bf16", bf16_expected)): + actual = _DINO.compute_mse_per_batches( + model, queries.batches(mean, scale, batch_size), + precision=precision, + ) * scale**2 + np.testing.assert_allclose(actual, oracle, rtol=2e-5, atol=1e-5) + del queries + raw[-1, 0] = 0 + raw.tofile(path) + try: + _DINO.DinoQueries(directory, model.d, n=17) + except ValueError: + pass + else: + raise AssertionError("invalid query header must fail") + for key, value in state.items(): + torch.testing.assert_close(getattr(model, key), value, rtol=0, atol=0) + assert getattr(model, "_ivf", None) is ivf + # BF16 collapses these distinct FP32 centroids to the same value. Global + # ties must choose the lowest ID, even when another FP32 centroid is closer. + tied = EmeansShardedCentroids(17, 2 * ranks, group=dist.group.WORLD) + tied.centroids = torch.zeros((2, 17), device=device) + tied.centroids[:, 0] = 1.0001 + rank * 0.0001 + row = torch.zeros((1, 17), device=device) + row[:, 0] = 1.0001 + (ranks - 1) * 0.0001 + first = row.new_tensor(1.0001) + oracle = (row[:, 0] - first).square().item() + actual = _DINO.compute_mse_per_batches(tied, [row[:0], row]) + np.testing.assert_allclose(actual, oracle, rtol=1e-6, atol=1e-14) + with np.testing.assert_raises(ValueError): + _DINO.compute_mse_per_batches(tied, [row[:0]]) + if rank == 0: + print( + "PASS: FP32/BF16 held-out MSE, global BF16 ties, query tails, " + "scaling and unchanged state", + flush=True, + ) + + + +def _query_mse_worker(rank, rendezvous): + from faiss.contrib.e_means import EmeansShardedCentroids + torch.set_num_threads(1) + torch.cuda.set_device(rank) + device = torch.device("cuda", rank) + dist.init_process_group( + "nccl", init_method=rendezvous, rank=rank, world_size=2, + timeout=datetime.timedelta(seconds=120), + ) + try: + model = EmeansShardedCentroids( + 17, 8, group=dist.group.WORLD, assignment_backend="native", + quantizer=None, unused_threshold=0, + ) + generator = torch.Generator(device=device).manual_seed(19 + rank) + model.centroids = torch.randn((4, 17), device=device, generator=generator) + _check_query_mse(model, device) + finally: + dist.destroy_process_group() + + +class TestRowNorms(unittest.TestCase): + def _equivalence(self, device): + generator = torch.Generator(device=device).manual_seed(1234) + for d in (1, 7, 1024): + state = torch.randn((83, d + 1), generator=generator, device=device) + usage = torch.rand(83, generator=generator, device=device) + for dtype in (torch.float32, torch.bfloat16): + # Non-contiguous rows, ragged chunks and exact BF16 rounding. + rows = state[:, :-1].to(dtype) + before = rows.clone() + expected = rows.float().square().sum(1) + for chunk in (1, 13, 128, None): + result = _DINO._squared_row_norms(rows, chunk_rows=chunk) + self.assertEqual(result.dtype, torch.float32) + self.assertEqual(result.device, rows.device) + # CUDA changes its reduction tree for different row grids; + # chunking preserves FP32 arithmetic, not bitwise rounding. + rtol = 4 * torch.finfo(torch.float32).eps if rows.is_cuda else 0 + torch.testing.assert_close(result, expected, rtol=rtol, atol=0) + torch.testing.assert_close(rows, before, rtol=0, atol=0) + # Reproduce the strided axis slice of the packed (k, d+1) state. + before = state.clone() + expected = torch.stack(( + state[:, -1].double(), usage.double(), + torch.linalg.vector_norm(state[:, :-1], dim=1, dtype=torch.float64), + ), dim=1) + for chunk in (1, 13, 128, None): + result = _removal_scalar_stats(state, usage, chunk_rows=chunk) + self.assertEqual(result.dtype, torch.float64) + self.assertEqual(result.device, state.device) + rtol = 4 * torch.finfo(torch.float64).eps if state.is_cuda else 0 + torch.testing.assert_close(result, expected, rtol=rtol, atol=0) + torch.testing.assert_close(state, before, rtol=0, atol=0) + + def test_cpu_equivalence(self): + self._equivalence(torch.device("cpu")) + + @unittest.skipUnless(torch.cuda.is_available(), "requires CUDA") + def test_cuda_equivalence(self): + self._equivalence(torch.device("cuda")) + + @unittest.skipUnless(torch.cuda.device_count() >= 2 and dist.is_nccl_available(), + "requires two CUDA GPUs and NCCL") + def test_query_mse_global_ties_and_unchanged_state(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn( + _query_mse_worker, args=("file://" + directory + "/group",), + nprocs=2, join=True, + ) + + def test_empty_and_invalid_chunks(self): + self.assertEqual(_DINO._squared_row_norms(torch.empty(0, 7)).shape, (0,)) + self.assertEqual( + _removal_scalar_stats(torch.empty(0, 8), torch.empty(0)).shape, + (0, 3), + ) + for chunk in (0, -1): + with self.assertRaisesRegex(ValueError, "positive"): + _DINO._squared_row_norms(torch.empty(2, 7), chunk_rows=chunk) + with self.assertRaisesRegex(ValueError, "positive"): + _removal_scalar_stats( + torch.empty(2, 8), torch.empty(2), chunk_rows=chunk + ) + + def test_special_values(self): + rows = torch.tensor([[0., 0.], [float("inf"), 1.], + [float("nan"), 1.], [1e20, 1.]]) + torch.testing.assert_close( + _DINO._squared_row_norms(rows, chunk_rows=1), + rows.square().sum(1), equal_nan=True, rtol=0, atol=0, + ) + state = torch.cat((rows, torch.ones(4, 1)), dim=1) + torch.testing.assert_close( + _removal_scalar_stats(state, torch.ones(4), chunk_rows=1)[:, 2], + torch.linalg.vector_norm(rows, dim=1, dtype=torch.float64), + equal_nan=True, rtol=0, atol=0, + ) + + def test_default_workspace_is_bounded(self): + # Cross the default 8192-row boundary at DINO's d=1024. + state = torch.ones(8193, 1025) + squares, norms = [], [] + square = torch.Tensor.square + vector_norm = torch.linalg.vector_norm + + def bounded_square(rows, *args, **kwargs): + squares.append((rows.shape[0], rows.numel() * rows.element_size())) + return square(rows, *args, **kwargs) + + def bounded_norm(rows, *args, **kwargs): + norms.append((rows.shape[0], rows.numel() * 8, kwargs["dtype"])) + return vector_norm(rows, *args, **kwargs) + + with mock.patch.object(torch.Tensor, "square", bounded_square): + result = _DINO._squared_row_norms(state[:, :-1].bfloat16()) + self.assertEqual([n for n, _ in squares], [8192, 1]) + self.assertLessEqual(max(size for _, size in squares), 32 << 20) + torch.testing.assert_close(result, torch.full((8193,), 1024.)) + with mock.patch.object(torch.linalg, "vector_norm", bounded_norm): + result = _removal_scalar_stats(state, torch.ones(8193)) + self.assertEqual([n for n, _, _ in norms], [8192, 1]) + self.assertTrue(all(dtype == torch.float64 for _, _, dtype in norms)) + self.assertLessEqual(max(size for _, size, _ in norms), 64 << 20) + torch.testing.assert_close(result[:, 2], torch.full((8193,), 32., dtype=torch.float64)) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_row_owned.py b/thirdparty/faiss/tests/torch_test_e_means_row_owned.py new file mode 100644 index 000000000..88b0bf1ec --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_row_owned.py @@ -0,0 +1,163 @@ +# 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. + +"""BF16 row-owned second results, independent of empirical route selection.""" +import unittest +import torch +from torch_test_e_means_cute import _ready, _integer_second + + +@unittest.skipUnless(_ready(), "pinned CuTe stack on SM90 required") +class TestRowOwnedSecond(unittest.TestCase): + def fixture(self, b=17, k=128, second_id=1, second_value=1., first_id=0): + from faiss.contrib.e_means import cute, cute_row_owned as row + c=torch.zeros(k,96,device='cuda') + c[:,0]=100 + c[first_id,0]=0 + c[second_id,0]=second_value + x=cute._aligned_operand(b,96,c.device,torch.bfloat16) + x.zero_() + x[:,0]=.25 + prepared=cute._prepare_centroids(c) + plan=row.row_owned_plan(b,k,96,c.device) + self.assertIsNotNone(plan) + return cute,row,x,prepared,plan + + def test_distinct_second_same_slot_other_tile_and_ties(self): + cases=((17,128,0,1,1.),(129,256,0,128,1.),(17,128,0,1,0.), + (17,128,0,2,1.),(17,128,0,4,1.),(17,128,0,6,1.), + (17,128,0,10,1.), + (17,128,2,3,1.),(17,128,4,5,1.)) + for b,k,first_id,j,value in cases: + with self.subTest(b=b,k=k,first_id=first_id,second_id=j,tie=value==0): + _,row,x,p,plan=self.fixture(b,k,j,value,first_id) + first=torch.empty(b,device='cuda') + labels=torch.empty(b,device='cuda',dtype=torch.int64) + backing=torch.full((b+2,),-123.,device='cuda') + second=backing[1:-1] + top1=row.prepare_row_owned(x,p,first,labels,plan) + row.launch_row_owned(top1) + old=first.clone() + top2=row.prepare_row_owned(x,p,first,labels,plan,second_scores=second) + row.launch_row_owned(top2) + self.assertTrue(torch.equal(first,old)) + torch.testing.assert_close(labels,torch.full_like(labels,first_id),rtol=0,atol=0) + # Direct scores omit the row norm, exactly as the tiled epilogue. + norm=x.float().square().sum(1) + torch.testing.assert_close(first+norm,torch.full_like(first,.0625),rtol=0,atol=0) + truth=.5625 if value else .0625 + torch.testing.assert_close(second+norm,torch.full_like(second,truth),rtol=0,atol=0) + self.assertEqual(backing[[0,-1]].tolist(),[-123.,-123.]) + row.launch_row_owned(top1) + self.assertTrue(torch.equal(first,old)) + + def test_integer_second_across_blocks(self): + _integer_second(384) + + def test_normalized_random_represented_fp64_oracle(self): + from faiss.contrib.e_means import cute, cute_row_owned as row + generator=torch.Generator(device='cuda').manual_seed(20261114) + c=torch.nn.functional.normalize(torch.randn(128,96,device='cuda',generator=generator),dim=1) + original=torch.nn.functional.normalize(torch.randn(17,96,device='cuda',generator=generator),dim=1) + x=cute._aligned_operand(17,96,c.device,torch.bfloat16) + x.copy_(original) + for spherical in (False,True): + with self.subTest(spherical=spherical): + p=cute._prepare_centroids(c,spherical=spherical) + first=torch.empty(17,device='cuda') + second=torch.empty_like(first) + labels=torch.empty(17,device='cuda',dtype=torch.int64) + plan=row.row_owned_plan(17,128,96,c.device) + bound=row.prepare_row_owned(x,p,first,labels,plan,second_scores=second) + row.launch_row_owned(bound) + q,centroids=x.double(),p.centroids.double() + truth=-2*(q[:,None]*centroids[None]).sum(2) if spherical else ( + q[:,None]-centroids[None]).square().sum(2) + order=torch.argsort(truth,dim=1,stable=True) + norm=0 if spherical else x.float().square().sum(1) + torch.testing.assert_close(labels,order[:,0],rtol=0,atol=0) + # Existing complete BF16 second-distance precision bound. + torch.testing.assert_close((first+norm).double(),truth.gather(1,order[:,:1]).flatten(),rtol=0,atol=1e-5) + torch.testing.assert_close((second+norm).double(),truth.gather(1,order[:,1:2]).flatten(),rtol=0,atol=1e-5) + + def test_prepared_second_capture_and_changed_rows(self): + _,row,x,p,plan=self.fixture() + first=torch.empty(len(x),device='cuda') + second=torch.empty_like(first) + labels=torch.empty(len(x),device='cuda',dtype=torch.int64) + bound=row.prepare_row_owned(x,p,first,labels,plan,second_scores=second) + row.launch_row_owned(bound) + torch.cuda.synchronize() + graph=torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + row.launch_row_owned(bound) + pointers=tuple(t.data_ptr() for t in (first,labels,second)) + for value,label,raw_first,raw_second in ((.25,0,0.,.5),(.75,1,-.5,0.),(.25,0,0.,.5)): + x[:,0]=value + graph.replay() + torch.testing.assert_close(first,torch.full_like(first,raw_first),rtol=0,atol=0) + torch.testing.assert_close(second,torch.full_like(second,raw_second),rtol=0,atol=0) + torch.testing.assert_close(labels,torch.full_like(labels,label),rtol=0,atol=0) + self.assertEqual(pointers,tuple(t.data_ptr() for t in (first,labels,second))) + torch.cuda.synchronize() + graph.reset() + + def test_natural_dispatch_row_owned_complete_outputs(self): + cute,_,x,p,_=self.fixture() + distance=torch.empty(len(x),device='cuda') + second=torch.empty_like(distance) + for second_requested in (False,True): + with self.subTest(second=second_requested): + optional={'second_out':second} if second_requested else {} + actual,labels=cute._assign_rows(x,p,distance_out=distance,**optional) + self.assertIs(actual,distance) + key=(len(x),'second') if second_requested else len(x) + self.assertEqual(p.bindings[key].launcher.__name__,'launch_row_owned') + if not second_requested: + self.assertIsNone(p.bindings[key].second_scores) + torch.testing.assert_close(labels,torch.zeros_like(labels),rtol=0,atol=0) + torch.testing.assert_close(distance,torch.full_like(distance,.0625),rtol=0,atol=0) + if second_requested: + torch.testing.assert_close(second,torch.full_like(second,.5625),rtol=0,atol=0) + + def test_natural_spherical_second_uses_native_score_units(self): + from faiss.contrib.e_means import cute + c=torch.zeros(128,96,device='cuda') + c[:,1]=1 + c[0,:2]=torch.tensor([1.,0.],device='cuda') + c[1,:2]=torch.tensor([.5,.75**.5],device='cuda') + x=torch.zeros(17,96,device='cuda',dtype=torch.bfloat16) + x[:,0]=1 + p=cute._prepare_centroids(c,spherical=True) + second=torch.empty(17,device='cuda') + distance,labels=cute._assign_rows(x,p,second_out=second) + self.assertEqual(p.bindings[(17,'second')].launcher.__name__,'launch_row_owned') + torch.testing.assert_close(labels,torch.zeros_like(labels),rtol=0,atol=0) + torch.testing.assert_close(distance,torch.full_like(distance,-2.),rtol=0,atol=0) + torch.testing.assert_close(second,torch.full_like(second,-1.),rtol=0,atol=0) + + def test_baseline_tiled_when_row_owned_exceeds_shared_memory(self): + from faiss.contrib.e_means import cute, cute_row_owned as row + from faiss.contrib.e_means.torch_backend import CuteBackend + c=torch.zeros(128,256,device='cuda') + c[:,0]=100 + c[0,0]=0 + c[1,0]=1 + x=torch.zeros(17,256,device='cuda',dtype=torch.bfloat16) + x[:,0]=.25 + self.assertIsNone(row.row_owned_plan(17,128,256,x.device)) + backend=CuteBackend(4096) + p=backend.prepare_centroids(c,torch.bfloat16)[0] + second=torch.empty(17,device='cuda') + distance,labels=cute._assign_rows(x,p,second_out=second) + backend.complete_second(x,labels,second) + self.assertEqual(p.bindings[(17,'second')].launcher.__name__,'launch_tiled_gemm') + torch.testing.assert_close(labels,torch.zeros_like(labels),rtol=0,atol=0) + torch.testing.assert_close(distance,torch.full_like(distance,.0625),rtol=0,atol=0) + torch.testing.assert_close(second,torch.full_like(second,.5625),rtol=0,atol=0) + + +if __name__=='__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_e_means_tiled_second.py b/thirdparty/faiss/tests/torch_test_e_means_tiled_second.py new file mode 100644 index 000000000..0c7246a9a --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_e_means_tiled_second.py @@ -0,0 +1,110 @@ +# 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. + +"""Complete tiled SECOND, valid candidates, tails and consumer lifetime.""" +import unittest +import torch +from torch_test_e_means_cute import _ready, _integer_second + + +@unittest.skipUnless(_ready(), 'pinned CuTe stack on SM90 required') +class TestTiledCompleteSecond(unittest.TestCase): + def test_closed_form_lanes_tiles_ties_and_nan_exclusion(self): + from faiss.contrib.e_means.torch_backend import CuteBackend + cases=((0,1,1.,False),(0,2,1.,False),(0,4,1.,False),(2,3,1.,False), + (192,193,1.,False),(0,192,1.,False),(0,1,0.,False),(0,1,1.,True), + (192,193,1.,True)) + for first_id,second_id,value,nan in cases: + with self.subTest(first=first_id,second=second_id,tie=value==0,nan=nan): + k,d,b=385,96,17 + c=torch.zeros(k,d,device='cuda') + c[:,0]=100 + if nan: + c[:,0]=torch.nan + c[first_id,0]=0 + c[second_id,0]=value + x=torch.zeros(b,d,device='cuda',dtype=torch.bfloat16) + x[:,0]=.25 + backend=CuteBackend(4096) + p=backend.prepare_centroids(c,torch.bfloat16)[0] + backing=torch.full((2*b+3,),-123.,device='cuda') + distance=backing[1:b+1] + second=backing[b+2:2*b+2] + labels=torch.empty(b,device='cuda',dtype=torch.int64) + actual,ids=backend.assign(x,p,distance_out=distance,labels_out=labels,second_out=second) + self.assertIs(actual,distance) + self.assertIs(ids,labels) + self.assertEqual(p.bindings[(b,'second')].launcher.__name__,'launch_tiled_gemm') + self.assertIsNone(p.bindings[(b,'second')].row_norms) + torch.testing.assert_close(ids,torch.full_like(ids,first_id),rtol=0,atol=0) + torch.testing.assert_close(distance,torch.full_like(distance,.0625),rtol=0,atol=0) + truth=.0625 if value==0 else .5625 + torch.testing.assert_close(second,torch.full_like(second,truth),rtol=0,atol=0) + complete=second.clone() + backend.complete_second(x,ids,second) + self.assertTrue(torch.equal(second,complete)) + self.assertEqual(backing[[0,b+1,-1]].tolist(),[-123.,-123.,-123.]) + top1,top1_ids=backend.assign(x,p) + self.assertTrue(torch.equal(top1,distance)) + self.assertTrue(torch.equal(top1_ids,ids)) + + def test_integer_second_across_blocks(self): + _integer_second(385) + + def test_normalized_random_euclidean_and_spherical(self): + from faiss.contrib.e_means.torch_backend import CuteBackend + g=torch.Generator(device='cuda').manual_seed(20261114) + c=torch.nn.functional.normalize(torch.randn(385,96,device='cuda',generator=g),dim=1) + x=torch.nn.functional.normalize(torch.randn(17,96,device='cuda',generator=g),dim=1).bfloat16() + for spherical in (False,True): + with self.subTest(spherical=spherical): + backend=CuteBackend(4096) + p=backend.prepare_centroids(c,torch.bfloat16,spherical=spherical)[0] + second=torch.empty(17,device='cuda') + distance,labels=backend.assign(x,p,spherical=spherical,second_out=second) + q,z=x.double(),p.centroids.double() + truth=-2*(q[:,None]*z[None]).sum(2) if spherical else (q[:,None]-z[None]).square().sum(2) + order=torch.argsort(truth,dim=1,stable=True) + torch.testing.assert_close(labels,order[:,0],rtol=0,atol=0) + torch.testing.assert_close(distance.double(),truth.gather(1,order[:,:1]).flatten(),rtol=0,atol=1e-5) + torch.testing.assert_close(second.double(),truth.gather(1,order[:,1:2]).flatten(),rtol=0,atol=1e-5) + + def test_capture_refresh_and_complete_output_noop(self): + from faiss.contrib.e_means.torch_backend import CuteBackend + c=torch.zeros(385,96,device='cuda') + c[:,0]=100 + c[0,0]=0 + c[1,0]=1 + x=torch.zeros(17,96,device='cuda',dtype=torch.bfloat16) + x[:,0]=.25 + backend=CuteBackend(4096) + p=backend.prepare_centroids(c,torch.bfloat16)[0] + distance=torch.empty(17,device='cuda') + second=torch.empty_like(distance) + labels=torch.empty(17,device='cuda',dtype=torch.int64) + backend.assign(x,p,distance_out=distance,labels_out=labels,second_out=second) + torch.cuda.synchronize() + backend.capture_state() + graph=torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + + p=backend.prepare_centroids(c,torch.bfloat16)[0] + backend.assign(x,p,distance_out=distance,labels_out=labels,second_out=second) + backend.complete_second(x,labels,second) + pointers=tuple(v.data_ptr() for v in (distance,labels,second)) + for coordinate,other,winner,d1,d2 in ((.25,1.,0,.0625,.5625),(.75,1.,1,.0625,.5625),(.25,2.,0,.0625,3.0625),(.25,1.,0,.0625,.5625)): + x[:,0]=coordinate + c[1,0]=other + graph.replay() + torch.testing.assert_close(labels,torch.full_like(labels,winner),rtol=0,atol=0) + torch.testing.assert_close(distance,torch.full_like(distance,d1),rtol=0,atol=0) + torch.testing.assert_close(second,torch.full_like(second,d2),rtol=0,atol=0) + self.assertEqual(pointers,tuple(v.data_ptr() for v in (distance,labels,second))) + torch.cuda.synchronize() + graph.reset() + + +if __name__=='__main__': + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_lloyd_ssd.py b/thirdparty/faiss/tests/torch_test_lloyd_ssd.py new file mode 100644 index 000000000..7b14e045d --- /dev/null +++ b/thirdparty/faiss/tests/torch_test_lloyd_ssd.py @@ -0,0 +1,171 @@ +# 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. + +"""Lloyd epoch updates and the SSD demo's exact/IVF sharded integration.""" + +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +import torch +import torch.distributed as dist + +from faiss.contrib.e_means import QuantizedEmeans +from faiss.contrib.e_means.sharded_centroids import EmeansShardedCentroids +from faiss.contrib.e_means.sharded_centroids_ivf import EmeansShardedCentroidsIVF + +# Bare pytest exposes tests/, while Buck already exposes the mapped namespace. +_SOURCE_ROOT = str(Path(__file__).absolute().parents[1]) +if _SOURCE_ROOT not in sys.path: + sys.path.append(_SOURCE_ROOT) +from benchs.e_means import lloyd as _LLOYD # noqa: E402 + + +class _CpuLloyd(_LLOYD._LloydEpoch, QuantizedEmeans): + """Exercise the epoch policy with the native CPU assignment engine.""" + + def __init__(self, d, k, **kwargs): + super().__init__(d, k, **kwargs) + self.global_k = k + self._group_size = 1 + self._group = dist.group.WORLD + + +def _fixture(device): + centers = torch.arange(6, device=device)[:, None] * 20.0 + centers = centers + torch.arange(16, device=device)[None, :] / 32 + offsets = torch.arange(36, device=device).remainder(3) / 8 - 0.125 + rows = centers[torch.arange(36, device=device).remainder(6)] + offsets[:, None] + initial = torch.cat((centers, torch.full((2, 16), 10000.0, device=device))) + return rows, initial + + +def _check_epochs(model, rows, initial, rank=0, ranks=1): + n = len(rows) + local_n, local_k = n // ranks, len(initial) // ranks + model.begin(n, initial[rank * local_k:(rank + 1) * local_k].clone()) + expected = initial.clone() + for budget in model.recipe["epoch_rows"]: + local_rows = rows[rank * local_n:rank * local_n + budget // ranks] + frozen = model.current_centroids().clone() + for batch in local_rows.split(model.recipe["batch_size"] // ranks): + stats = model.accumulate(batch) + model.update(stats) + torch.testing.assert_close(model.current_centroids(), frozen, rtol=0, atol=0) + selected = torch.cat([ + rows[worker * local_n:worker * local_n + budget // ranks] + for worker in range(ranks) + ]) + if model.recipe.get("fine_dtype") == "bf16": + represented = expected.to(torch.bfloat16).float() + queries = selected.to(torch.bfloat16).float() + labels = (represented.square().sum(1)[None, :] + - 2 * queries @ represented.t()).argmin(1) + else: + labels = (selected[:, None, :] - expected[None, :, :]).square().sum(2).argmin(1) + for cluster in range(len(initial)): + assigned = selected[labels == cluster] + if len(assigned): + expected[cluster] = assigned.double().mean(0).float() + mse = (selected - expected[labels]).square().sum(1).mean().item() + model.end_epoch() + torch.testing.assert_close( + model.current_centroids(), expected[rank * local_k:(rank + 1) * local_k], + rtol=2e-6, atol=2e-5, + ) + assert abs(model.iteration_stats[-1]["assignment_mse"] - mse) < 2e-4 + assert model.n_splits == 0 + result = model.finalize() + assert model.finalize() is result + torch.testing.assert_close(result, expected[rank * local_k:(rank + 1) * local_k]) + assert "alpha0" not in model.recipe + + +def _gpu_worker(rank, rendezvous): + torch.cuda.set_device(rank) + dist.init_process_group("nccl", init_method=rendezvous, rank=rank, world_size=2) + try: + rows, initial = _fixture(torch.device("cuda", rank)) + for cls, parent, extra in ( + (_LLOYD.LloydShardedCentroids, EmeansShardedCentroids, {}), + (_LLOYD.LloydShardedCentroidsIVF, EmeansShardedCentroidsIVF, + {"nlist": 4, "nprobe": 4, "coarse_niter": 2}), + ): + for epochs in (0.5, 2.5): + model = cls(16, 8, nepochs=epochs, batch_size=10, alpha0=1, + assignment_backend="triton", group=dist.group.WORLD, **extra) + calls = [] + prepare = parent._prepare_assignment + + def counted(self, *, calls=calls, prepare=prepare): + calls.append(self._epoch) + return prepare(self) + + with mock.patch.object(parent, "_prepare_assignment", counted): + _check_epochs(model, rows, initial, rank, 2) + assert calls == list(range(len(model.recipe["epoch_rows"]))) + # BF16 merges two distinct centroids on different owners. Assignment + # must pick the lowest global ID; means must retain unrounded FP32 rows. + initial = torch.zeros((4, 17), device=rows.device) + initial[:, 0] = initial.new_tensor([1.0001, 4., 1.0021, 9.]) + rows = torch.zeros((8, 17), device=rows.device) + rows[:, 0] = rows.new_tensor([1.0021, 4.12345, 9.12345, 1.0021, + 4.12345, 9.12345, 1.0021, 4.12345]) + rows[:, 1] = 0.000123 + model = _LLOYD.LloydShardedCentroids( + 17, 4, nepochs=1, batch_size=4, alpha0=1, + assignment_backend="triton", group=dist.group.WORLD, + ) + _check_epochs(model, rows, initial, rank, 2) + assert model.recipe["representation"] == "float32" + assert model.recipe["fine_dtype"] == "bf16" + if rank == 0: + assert abs(model.centroids[0, 0].item() - 1.0021) < 1e-6 + finally: + dist.destroy_process_group() + + +class TestLloydSSD(unittest.TestCase): + def test_epoch_means_and_fractional_tail(self): + with tempfile.TemporaryDirectory() as directory: + dist.init_process_group("gloo", init_method="file://" + directory + "/group", + rank=0, world_size=1) + try: + rows, initial = _fixture(torch.device("cpu")) + for epochs in (0.5, 2.5): + model = _CpuLloyd(16, 8, nepochs=epochs, batch_size=10, alpha0=1) + _check_epochs(model, rows, initial) + self.assertEqual(model.recipe["epoch_rows"], + [18] if epochs == 0.5 else [36, 36, 18]) + finally: + dist.destroy_process_group() + + def test_incomplete_epoch_keeps_centroids(self): + with tempfile.TemporaryDirectory() as directory: + dist.init_process_group("gloo", init_method="file://" + directory + "/group", + rank=0, world_size=1) + try: + rows, initial = _fixture(torch.device("cpu")) + model = _CpuLloyd(16, 8, nepochs=1, batch_size=10, alpha0=1) + model.begin(len(rows), initial) + with self.assertRaisesRegex(RuntimeError, "incomplete"): + model.end_epoch() + torch.testing.assert_close(model.current_centroids(), initial) + with self.assertRaisesRegex(RuntimeError, "finish all epochs"): + model.finalize() + finally: + dist.destroy_process_group() + + @unittest.skipUnless(torch.cuda.device_count() >= 2, "requires two CUDA GPUs") + def test_sharded_exact_and_ivf(self): + with tempfile.TemporaryDirectory() as directory: + torch.multiprocessing.spawn(_gpu_worker, nprocs=2, + args=("file://" + directory + "/group",), join=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/thirdparty/faiss/tests/torch_test_neural_net.py b/thirdparty/faiss/tests/torch_test_neural_net.py index 2d0c285c5..e49da7d22 100644 --- a/thirdparty/faiss/tests/torch_test_neural_net.py +++ b/thirdparty/faiss/tests/torch_test_neural_net.py @@ -20,7 +20,6 @@ class TestLayer(unittest.TestCase): @torch.no_grad() def test_Embedding(self): - """verify that the Faiss Embedding works the same as in Pytorch""" torch.manual_seed(123) emb = nn.Embedding(40, 50) @@ -36,7 +35,6 @@ def test_Embedding(self): @torch.no_grad() def do_test_Linear(self, bias): - """verify that the Faiss Linear works the same as in Pytorch""" torch.manual_seed(123) linear = nn.Linear(50, 40, bias=bias) x = torch.randn(25, 50) @@ -93,36 +91,9 @@ def assign_batch_multiple(x, zqs): return idx.squeeze(1), quantized.squeeze(1) -def assign_to_codebook(x, c, bs=16384): - nq, d = x.shape - nb, d2 = c.shape - assert d == d2 - if nq * nb < bs * bs: - # small enough to represent the whole distance table - dis = pairwise_distances(x, c) - return dis.argmin(1) - - # otherwise tile computation to avoid OOM - res = torch.empty((nq,), dtype=torch.int64, device=x.device) - cnorms = (c**2).sum(1) - for i in range(0, nq, bs): - xnorms = (x[i : i + bs] ** 2).sum(1, keepdim=True) - for j in range(0, nb, bs): - dis = ( - xnorms - + cnorms[j : j + bs] - - 2 * x[i : i + bs] @ c[j : j + bs].T - ) - dmini, imini = dis.min(1) - if j == 0: - dmin = dmini - imin = imini - else: - (mask,) = torch.where(dmini < dmin) - dmin[mask] = dmini[mask] - imin[mask] = imini[mask] + j - res[i : i + bs] = imin - return res +def assign_to_codebook(x, c): + dis = pairwise_distances(x, c) + return dis.argmin(1) class QINCoStep(nn.Module): @@ -207,21 +178,12 @@ def decode(self, codes): xhat = xhat + step.decode(xhat, codes[:, i + 1]) return xhat - def encode(self, x, code0=None): - """ - Encode a batch of vectors x to codes of length M. - If this function is called from IVF-QINCo, codes are 1 index longer, - due to the first index being the IVF index, and codebook0 is the - IVF codebook. - """ + def encode(self, x): M = len(self.steps) + 1 bs, d = x.shape codes = torch.zeros(bs, M, dtype=int, device=x.device) - if code0 is None: - # at IVF training time, the code0 is fixed (and precomputed) - code0 = assign_to_codebook(x, self.codebook0.weight) - + code0 = assign_to_codebook(x, self.codebook0.weight) codes[:, 0] = code0 xhat = self.codebook0.weight[code0] @@ -232,51 +194,7 @@ def encode(self, x, code0=None): return codes, xhat -###################################################### -# QINCo tests -###################################################### - - -def copy_QINCoStep(step): - step2 = faiss.QINCoStep(step.d, step.K, step.L, step.h) - step2.codebook.from_torch(step.codebook) - step2.MLPconcat.from_torch(step.MLPconcat) - - for l in range(step.L): - src = step.residual_blocks[l] - dest = step2.get_residual_block(l) - dest.linear1.from_torch(src[0]) - dest.linear2.from_torch(src[2]) - return step2 - - class TestQINCoStep(unittest.TestCase): - @torch.no_grad() - def test_decode(self): - torch.manual_seed(123) - step = QINCoStep(d=16, K=20, L=2, h=8) - - codes = torch.randint(0, 20, (10,)) - xhat = torch.randn(10, 16) - ref_decode = step.decode(xhat, codes) - - # step2 = copy_QINCoStep(step) - step2 = faiss.QINCoStep(step) - codes2 = faiss.Int32Tensor2D(codes[:, None].to(dtype=torch.int32)) - - np.testing.assert_array_equal( - step.codebook(codes).numpy(), step2.codebook(codes2).numpy() - ) - - xhat2 = faiss.Tensor2D(xhat) - # xhat2 = faiss.Tensor2D(len(codes), step2.d) - - new_decode = step2.decode(xhat2, codes2) - - np.testing.assert_allclose( - ref_decode.numpy(), new_decode.numpy(), atol=2e-6 - ) - @torch.no_grad() def test_encode(self): torch.manual_seed(123) @@ -289,7 +207,7 @@ def test_encode(self): del codes ref_codes, toadd = step.encode(xhat, x) - step2 = copy_QINCoStep(step) + step2 = faiss.QINCoStep(step) xhat2 = faiss.Tensor2D(xhat) x2 = faiss.Tensor2D(x) toadd2 = faiss.Tensor2D(10, 16) @@ -337,11 +255,6 @@ def test_encode(self): ) -###################################################### -# Test index -###################################################### - - class TestIndexQINCo(unittest.TestCase): def test_search(self): @@ -355,13 +268,11 @@ def test_search(self): M = 5 index_ref = faiss.index_factory(ds.d, "RQ5x4") rq = index_ref.rq - # rq = faiss.ResidualQuantizer(ds.d, M, 4) rq.train_type = faiss.ResidualQuantizer.Train_default rq.max_beam_size = 1 # beam search not implemented for QINCo (yet) index_ref.train(ds.get_train()) codebooks = get_additive_quantizer_codebooks(rq) - # convert to QINCo index qinco_index = faiss.IndexQINCo(ds.d, M, 4, 0, ds.d) qinco = qinco_index.qinco qinco.codebook0.from_array(codebooks[0]) @@ -371,7 +282,6 @@ def test_search(self): # MLPConcat left at zero -- it's added to the backbone qinco_index.is_trained = True - # verify that the encoding gives the same results ref_codes = rq.compute_codes(ds.get_database()) ref_decoded = rq.decode(ref_codes) new_decoded = qinco_index.sa_decode(ref_codes) @@ -380,7 +290,6 @@ def test_search(self): new_codes = qinco_index.sa_encode(ds.get_database()) np.testing.assert_array_equal(ref_codes, new_codes) - # verify that search gives the same results Dref, Iref = index_ref.search(ds.get_queries(), 5) Dnew, Inew = qinco_index.search(ds.get_queries(), 5)