Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
- Errors in an HNSW routing graph name the graph rather than the sidecar: `Truncated HNSW centroid graph` and `HNSW centroid graph changed while loading` replace their `sidecar` forms.
- A missing sidecar of an earlier file still raises `Cannot open HNSW centroid sidecar`.
- A failed HNSW-RaBitQ write raises `HNSW index file cannot be written` instead of `HNSW failed to write index file`.
- `pickle.dumps(obj, protocol=0)` or `protocol=1` on a `rabitqlib` object no longer aborts the Python process. `quant.Rotator` and `quant.Query` now pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raise `TypeError: cannot pickle ...`, as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects ([pybind11#3745](https://github.com/pybind/pybind11/issues/3745)), so they now use the protocol-2 reduction.

## C++ changes

Expand Down
14 changes: 14 additions & 0 deletions python_bindings/bindings_common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,20 @@ class IndexAccess {
[[nodiscard]] Guard write() { return Guard(*this, true); }
};

// `__reduce_ex__` for every extension class and enum. Pickle protocols 0 and 1 reduce
// through copyreg._reduce_ex, which calls pybind11_object(self); that constructor throws a
// C++ exception through the C API and aborts the interpreter (pybind11 issue 3745).
// Reducing with protocol 2 instead pickles a class that defines py::pickle with any
// protocol and raises TypeError for the others, as protocol 2 already does.
inline py::object reduce_ex_with_protocol_2(const py::object& self, int protocol) {
const auto object_type =
py::reinterpret_borrow<py::object>(reinterpret_cast<PyObject*>(&PyBaseObject_Type));
return object_type.attr("__reduce_ex__")(self, std::max(protocol, 2));
}

inline constexpr const char* kReduceExDoc =
"Reduce for pickle; protocols 0 and 1 use the protocol-2 reduction.";

// Resolve Python callbacks before index guards and own bytes across GIL release.
inline std::string path_string(py::handle value) {
// The old std::string caster also accepted bytearray directly.
Expand Down
6 changes: 6 additions & 0 deletions python_bindings/hnsw_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,12 @@ link through the stored codes, so add most vectors in the first call. Capacity
grows geometrically when needed. Removed IDs are not reused.)doc";

py::class_<HnswIndex>(m, "HnswIndex", kIndexDoc)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(
py::init<
size_t,
Expand Down
6 changes: 6 additions & 0 deletions python_bindings/ivf_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,12 @@ untrained and empty. Batch additions to reduce repeated cluster copying;
reserve_cluster can preallocate room.)doc";

py::class_<IvfIndex>(m, "IvfIndex", kIndexDoc)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(
py::init<
size_t,
Expand Down
21 changes: 20 additions & 1 deletion python_bindings/kmeans_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,14 @@ py::tuple assign(const Clustering& clustering, py::handle x) {

template <typename Parameters>
void bind_training_parameters(py::class_<Parameters>& binding) {
binding.def(py::init<>(), "Create parameters with their documented defaults.")
binding
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(py::init<>(), "Create parameters with their documented defaults.")
.def_readwrite(
"niter",
&Parameters::niter,
Expand Down Expand Up @@ -138,6 +145,12 @@ void bind_training_parameters(py::class_<Parameters>& binding) {
template <typename Clustering, typename Parameters>
void bind_clustering(py::module_& m, const char* native_name, const char* public_name) {
py::class_<Clustering>(m, native_name)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(py::init<size_t, size_t, const Parameters&>())
.def("train", &train<Clustering>, py::arg("x"))
.def("assign", &assign<Clustering>, py::arg("x"))
Expand Down Expand Up @@ -240,6 +253,12 @@ on RaBitQKMeans.)doc"
"KMeansIterationStats",
R"doc(Read-only statistics for one completed clustering iteration.)doc"
)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def_readonly(
"iteration",
&KMeansIterationStats::iteration,
Expand Down
12 changes: 12 additions & 0 deletions python_bindings/quant_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2058,6 +2058,12 @@ Examples
(2, 128))doc";

py::class_<QuantRotator>(quant, "Rotator", kRotatorDoc)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(
py::init<size_t, const std::string&, const py::object&, const py::object&>(),
py::arg("dim"),
Expand Down Expand Up @@ -2276,6 +2282,12 @@ num_threads : int, optional
OMP_NUM_THREADS.)doc";

py::class_<QuantQuery>(quant, "Query", kQueryDoc)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(
py::init(&QuantQuery::create),
py::arg("rotated_query"),
Expand Down
13 changes: 13 additions & 0 deletions python_bindings/rabitq_bindings.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <pybind11/detail/common.h>
#include <pybind11/pybind11.h>

#include "bindings_common.hpp"
#include "rabitqlib/core/metric.hpp"
#include "rabitqlib/core/rotator.hpp"
#include "rabitqlib/index/format_error.hpp"
Expand Down Expand Up @@ -60,11 +61,23 @@ PYBIND11_MODULE(_rabitqlib, m) {

// Register shared enums once
py::enum_<rabitqlib::MetricType>(m, "MetricType")
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.value("L2", rabitqlib::METRIC_L2)
.value("IP", rabitqlib::METRIC_IP)
.export_values();

py::enum_<rabitqlib::RotatorType>(m, "RotatorType")
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.value("FhtKacRotator", rabitqlib::RotatorType::FhtKacRotator)
.value("MatrixRotator", rabitqlib::RotatorType::MatrixRotator)
.export_values();
Expand Down
6 changes: 6 additions & 0 deletions python_bindings/symqg_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,12 @@ np.isfinite(distances) to find them. Array shapes and value ranges are
checked at runtime, not by static type checkers.)doc";

py::class_<SymqgIndex>(m, "SymqgIndex", kIndexDoc)
.def(
"__reduce_ex__",
&rabitqlib::python_bindings::reduce_ex_with_protocol_2,
py::arg("protocol"),
rabitqlib::python_bindings::kReduceExDoc
)
.def(
py::init<
size_t,
Expand Down
112 changes: 112 additions & 0 deletions tests/python/test_pickle_protocols.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""Pickle protocols 0 and 1 raise or round-trip instead of aborting the interpreter.

Those protocols reduce through copyreg, which calls the constructor of pybind11's base
class; that throws through the C API and aborts the process (pybind11 issue 3745)
unless the class defines __reduce_ex__. The calls therefore run in a child process.
"""

import subprocess
import sys
import textwrap

import rabitqlib
from rabitqlib import _rabitqlib

CHILD = textwrap.dedent(
"""
import pickle
import sys

import numpy as np
import rabitqlib
from rabitqlib import _rabitqlib, quant

if rabitqlib.__file__ != sys.argv[1]:
raise SystemExit(f"child imported {rabitqlib.__file__}, not {sys.argv[1]}")
x = np.random.default_rng(0).normal(size=(64, 64)).astype(np.float32)
flat = rabitqlib.RaBitQKMeans(64, 2, niter=1, num_threads=1, seed=1)
flat.train(x)
graph = rabitqlib.QGKMeans(64, 33, niter=1, num_threads=1, seed=1)
graph.train(x)

def state(value):
return pickle.dumps(value, protocol=2)

picklable = {
"Rotator": quant.Rotator(64, seed=1),
"Query": quant.Query(x[0], metric="ip"),
"Query with centroid": quant.Query(x[0], metric="l2", centroid=x[1]),
"MetricType": _rabitqlib.MetricType.IP,
"RotatorType": _rabitqlib.RotatorType.FhtKacRotator,
}
unpicklable = {
"IvfIndex": rabitqlib.IvfIndex(64, 2, seed=1),
"HnswIndex": rabitqlib.HnswIndex(64, seed=1),
"SymqgIndex": rabitqlib.SymqgIndex(64, seed=1),
"QGKMeansParameters": rabitqlib.QGKMeansParameters(),
"RaBitQKMeansParameters": rabitqlib.RaBitQKMeansParameters(),
"KMeansIterationStats": flat.iteration_stats[0],
"_RaBitQKMeans": flat._impl,
"_QGKMeans": graph._impl,
"RaBitQKMeans": flat,
}
for protocol in (0, 1):
for name, value in picklable.items():
copy = pickle.loads(pickle.dumps(value, protocol=protocol))
if state(copy) != state(value):
raise SystemExit(f"{name} changed in a protocol {protocol} round trip")
print(name, protocol, "round-trip", flush=True)
for name, value in unpicklable.items():
try:
pickle.dumps(value, protocol=protocol)
except TypeError as error:
if "cannot pickle" not in str(error):
raise SystemExit(f"{name}: {error}")
print(name, protocol, "TypeError", flush=True)
else:
raise SystemExit(f"{name} pickled with protocol {protocol}")
print(len(picklable) + len(unpicklable), "cases", flush=True)
"""
)


def test_old_protocols_round_trip_or_raise_in_a_child_process():
result = subprocess.run(
[sys.executable, "-c", CHILD, rabitqlib.__file__],
capture_output=True,
text=True,
timeout=300,
)
assert result.returncode == 0, result.stdout + result.stderr
lines = result.stdout.splitlines()
cases = int(lines[-1].split()[0])
assert len(lines) == 1 + 2 * cases, lines
assert "Query with centroid 0 round-trip" in lines
assert "_QGKMeans 1 TypeError" in lines


def extension_classes():
"""Every pybind11 class that rabitqlib registered, found through the subclass tree."""
pending = [
base
for base in type(_rabitqlib.MetricType.IP).__mro__
if base.__name__ == "pybind11_object"
]
found = []
while pending:
cls = pending.pop()
pending.extend(cls.__subclasses__())
# quant.py renames its classes' module to rabitqlib.quant when imported.
if cls.__module__.split(".")[0] == "rabitqlib":
found.append(cls)
return found


def test_every_extension_class_defines_reduce_ex():
classes = extension_classes()
names = {cls.__name__ for cls in classes}
assert {"IvfIndex", "Query", "_QGKMeans", "MetricType"} <= names, names
assert (
sorted(cls.__name__ for cls in classes if "__reduce_ex__" not in vars(cls))
== []
)
Loading