FALCONN Library Documentation

repository·master·Indexed 22 days ago

https://github.com/falconn-lib/falconn

FALCONN is a high-performance library for nearest neighbor search using Locality-Sensitive Hashing (LSH), specifically optimized for cosine similarity in high-dimensional spaces.

Tokens
107K
Snippets
319
Records
430
Agent score
78%

What's inside FALCONN

  1. Overview of pybind11

    master

    pybind11 is a lightweight, header-only C++ library designed to expose C++ types to Python and vice versa. It is primarily used to create Python bindings for existing C++ code. It aims to minimize boilerplate by using compile-time introspection to infer type information, similar to Boost.Python but without the heavy dependency on the Boost suite.

    Key characteristics:

    • Header-only: No need to link against additional libraries; everything is contained in a few header files.
    • Lightweight: Core header files are approximately 4K lines of code.
    • Efficient: Uses C++11 features like move constructors, constexpr, and variadic templates to ensure small binaries and fast execution.
    • Python Support: Supports Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7).
  2. Overview of Google Mock

    master

    Google Mock is a C++ framework for creating mock classes to facilitate better system design and testing. It allows you to define mock classes using macros, control their behavior with an intuitive syntax, and validate function arguments using a rich set of matchers.

    Key capabilities include:

    • Declarative Syntax: Define mocks easily using macros.
    • Partial Mocks: Create hybrid objects that combine real and mock behavior.
    • Flexible Expectations: Handle unordered, partially ordered, or completely ordered function call expectations.
    • Automatic Verification: Expectations are verified automatically without requiring a manual record-and-replay cycle.
    • Extensibility: Users can define custom matchers and actions.
    • No Exceptions: The framework does not rely on C++ exceptions.
  3. Overview of FALCONN

    master

    FALCONN (FAst Lookups of Cosine and Other Nearest Neighbors) is a C++ library designed for efficient nearest neighbor search in high-dimensional spaces using Locality-Sensitive Hashing (LSH).

    Key features include:

    • Supported Similarity Metrics: Primarily optimized for cosine similarity using hyperplane LSH and cross polytope LSH families. It can also be used for Euclidean distance and maximum inner product search.
    • Efficiency: Uses multi-probe LSH to minimize memory usage and is optimized for both dense and sparse data.
    • Performance: On datasets with ~1 million points in ~100 dimensions, it typically achieves query times of a few milliseconds on modern desktop CPUs. It is particularly competitive in memory-constrained (low RAM) environments.
    • Implementation: Written in C++ using templates to avoid runtime overhead. It leverages Eigen and FFHT for vectorized mathematical operations.
  4. Overview of Google Test and Google Mock

    master

    Google Test is a C++ testing framework that provides an xUnit-style interface. It includes features such as test discovery, a rich set of assertions (both fatal and non-fatal), death tests, and support for both value-parameterized and type-parameterized tests. It also supports XML test report generation.

    Google Mock is an extension to Google Test specifically designed for writing and using C++ mock classes. The two projects are maintained together in a single repository.

  5. What is Pump and how does it work?

    master

    Pump is a meta-programming tool for C++ designed to automate the generation of repetitive code (like classes or functions that vary by argument count) without relying on complex variadic templates or external scripts.

    Users write .pump files containing standard C++ code interspersed with a concise meta-language. A Python-based compiler then processes these files to generate the final C++ source code.

    Key Features:

    • Portability: The implementation is a single Python script; no installation or build step is required.
    • Style Aware: It automatically breaks long generated lines to fit within 80 columns and handles indentation.
    • Non-intrusive: The syntax is designed to be compatible with standard C++ editors (like Emacs).
    • Logic Support: Supports iterations, nested loops, local variables, arithmetic, and conditionals.
  6. Key features and benefits of Google Test

    master

    Google Test (gtest) is a portable C++ testing framework designed to work across Linux, Mac OS X, Windows, and embedded systems without requiring exceptions or RTTI.

    Key advantages include:

    • Nonfatal assertions (EXPECT_*): Allows tests to continue reporting multiple failures in a single cycle.
    • Informative messages: Supports stream syntax for custom error messages, e.g., ASSERT_EQ(5, Foo(i)) << " where i = " << i;.
    • Automatic test detection: No need to manually enumerate tests.
    • Death tests: Verifies that production code triggers assertions under specific conditions.
    • SCOPED_TRACE: Provides context for failures occurring inside loops or sub-routines.
    • Test filtering: Allows running specific tests using name patterns.
    • Extensibility: Supports custom predicates, custom type printing, and intercepting test events via a Service Provider Interface (SPI).
  7. What is a Mock Object in Google Mock?

    master
    A mock object is a simulated implementation of an interface used during testing. Unlike fake objects (which have working but simplified implementations, like an in-memory file system), mocks are pre-programmed with expectations. These expectations specify how the object should be used: which methods should be called, in what order, how many times, with which arguments, and what they should return. Mocks allow you to verify the interaction between your code and its dependencies.
  8. Handle inheritance and automatic upcasting

    master

    There are two ways to indicate a C++ inheritance relationship in pybind11:

    1. Template Parameter: Specify the C++ base class as an extra template parameter in py::class_<Derived, Base>.
    2. Python Parent Object: Assign the previously bound base class to a variable and pass it as the third argument to py::class_<Derived>(m, "Derived", base_object).

    Polymorphism and Upcasting

    • Non-polymorphic types: If you return a base pointer to a derived instance (e.g., std::unique_ptr<Base>), Python will only see the Base type. It will not automatically upcast to the derived type, and derived methods will be inaccessible.
    • Polymorphic types: If the C++ class has at least one virtual function, pybind11 performs automatic upcasting. When a base pointer is returned, Python identifies the actual concrete derived type, providing access to all derived functions and attributes.
    // Polymorphic setup
    struct PolymorphicPet {
        virtual ~PolymorphicPet() = default;
    };
    
    struct PolymorphicDog : PolymorphicPet {
        std::string bark() const { return "woof!"; }
    };
    
    py::class_<PolymorphicPet>(m, "PolymorphicPet");
    py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
        .def(py::init<>())
        .def("bark", &PolymorphicDog::bark);
    // Method 1: Template parameter
    py::class_<Dog, Pet>(m, "Dog")
        .def(py::init<const std::string &>());
    
    // Method 2: Pass parent class_ object
    py::class_<Pet> pet(m, "Pet");
    py::class_<Dog>(m, "Dog", pet)
        .def(py::init<const std::string &>());
  9. Change mock behavior based on state using InSequence

    master

    You can simulate a state change in a mock object by using ::testing::InSequence. By wrapping multiple EXPECT_CALL statements in an InSequence scope, you can define a specific order of behaviors. For example, you can make a method return true initially, then call a Flush() method, and then have the same method return false.

    using ::testing::InSequence;
    using ::testing::Return;
    
    {
      InSequence seq;
      EXPECT_CALL(my_mock, IsDirty())
          .WillRepeatedly(Return(true));
      EXPECT_CALL(my_mock, Flush());
      EXPECT_CALL(my_mock, IsDirty())
          .WillRepeatedly(Return(false));
    }
    my_mock.FlushIfDirty();
  10. Mock non-virtual methods via hi-perf dependency injection

    master

    You can mock non-virtual methods by creating an unrelated mock class that has the same method signatures as the real class. This is used for 'hi-perf dependency injection' where you avoid the overhead of virtual functions.

    Because the classes are unrelated and methods are non-virtual, you must choose which class to use at compile time, typically by templatizing the consumer code.

    // Production class (no virtual methods)
    class ConcretePacketStream {
     public:
      void AppendPacket(Packet* new_packet);
    };
    
    // Mock class (unrelated to ConcretePacketStream)
    class MockPacketStream {
     public:
      MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
    };
    
    // Consumer code using templates to switch implementations
    template <class PacketStream>
    void CreateConnection(PacketStream* stream) { ... }
    
    // In tests:
    MockPacketStream mock_stream;
    CreateConnection<MockPacketStream>(&mock_stream);
  11. Use Module-Local bindings to avoid type conflicts

    master

    By default, pybind11 bindings are "global," meaning a type defined in one module can be returned from any other module as the same Python type. While useful for splitting libraries, this causes ImportError: generic_type: type "X" is already registered! if two different modules attempt to bind the same external C++ class differently.

    To resolve this, use the py::module_local() attribute in the py::class_ constructor. This makes the binding specific to that module, resulting in distinct Python classes (e.g., module1.Pet and module2.Pet) even if they represent the same C++ type.

    Key Behaviors of py::module_local():

    1. Directionality: Locality only applies to the C++ $\rightarrow$ Python direction. When passing a module-local type into a C++ function, the underlying C++ type is still recognized.
    2. Casting: Within the module where the local binding exists, C++ instances will be cast to the local Python type. In other modules, they will be converted to the global Python type if a global binding exists.
    3. Isolation: From the Python perspective, module1.Pet and module2.Pet are distinct classes.
    // In module A, bind an external class locally to avoid conflicts
    py::class<external_type>(m, "ExternalType", py::module_local())
        .def("method", &external_type::method);
  12. Handle immutable Python types when binding C++ reference arguments

    master

    In C++, functions often use mutable references (int &i) or pointers (int *i) to modify arguments. However, basic Python types like str, int, bool, and float are immutable. Binding a C++ function that modifies these types will result in a Python function that appears to do nothing to the input value.

    Workarounds:

    1. Encapsulation: Wrap the immutable types in a custom C++ type that allows modifications.
    2. Lambda Wrapper: Bind a small wrapper lambda that calls the C++ function and returns the modified values as a tuple.
    // C++ function to be bound
    int foo(int &i) { i++; return 123; }
    
    // Binding code using a lambda to return a tuple
    m.def("foo", [](int i) { 
        int rv = foo(i); 
        return std::make_tuple(rv, i); 
    });