Skip to content

Commit 657c563

Browse files
bshethmetafacebook-github-bot
authored andcommitted
Add bounds checking to hnsw nb_neighbors (#4185)
Summary: Pull Request resolved: #4185 Based on this users comment it seems like we should do bound checking: #4177 Reviewed By: mnorris11 Differential Revision: D69497295 fbshipit-source-id: 97025cf29c464afb0f85aa98f4b303489b7fc989
1 parent f0e3832 commit 657c563

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

faiss/impl/HNSW.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ namespace faiss {
3232
**************************************************************/
3333

3434
int HNSW::nb_neighbors(int layer_no) const {
35+
FAISS_THROW_IF_NOT(layer_no + 1 < cum_nneighbor_per_level.size());
3536
return cum_nneighbor_per_level[layer_no + 1] -
3637
cum_nneighbor_per_level[layer_no];
3738
}

tests/test_hnsw.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,16 @@ TEST_F(HNSWTest, TEST_search_neighbors_to_add) {
582582
}
583583
}
584584

585+
TEST_F(HNSWTest, TEST_nb_neighbors_bound) {
586+
omp_set_num_threads(1);
587+
EXPECT_EQ(index->hnsw.nb_neighbors(0), 8);
588+
EXPECT_EQ(index->hnsw.nb_neighbors(1), 4);
589+
EXPECT_EQ(index->hnsw.nb_neighbors(2), 4);
590+
EXPECT_EQ(index->hnsw.nb_neighbors(3), 4);
591+
// picking a large number to trigger an exception based on checking bounds
592+
EXPECT_THROW(index->hnsw.nb_neighbors(100), faiss::FaissException);
593+
}
594+
585595
TEST_F(HNSWTest, TEST_search_level_0) {
586596
omp_set_num_threads(1);
587597
std::vector<faiss::idx_t> I(k * nq);

0 commit comments

Comments
 (0)