usearch 2.8.3 → 2.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vscode/settings.json +1 -0
- package/CITATION.cff +1 -1
- package/CONTRIBUTING.md +258 -6
- package/Cargo.toml +1 -1
- package/README.md +57 -53
- package/conanfile.py +1 -1
- package/cpp/README.md +89 -21
- package/csharp/DEV_SETUP.md +1 -1
- package/csharp/nuget/nuget-package.props +1 -1
- package/docs/{compilation.rst → contributing.rst} +2 -2
- package/docs/index.rst +1 -1
- package/include/usearch/index.hpp +1 -1
- package/include/usearch/index_dense.hpp +11 -7
- package/package.json +1 -1
- package/python/README.md +1 -1
- package/simsimd/CMakeLists.txt +1 -1
- package/simsimd/README.md +7 -1
- package/simsimd/include/simsimd/probability.h +24 -24
- package/simsimd/include/simsimd/types.h +8 -0
- package/simsimd/javascript/{test.js → test/simsimd.test.js} +15 -15
- package/simsimd/package.json +4 -8
- package/simsimd/setup.py +3 -0
- package/wasmer.toml +1 -1
- package/docs/compilation.md +0 -215
- package/simsimd/.clang-format +0 -10
- package/simsimd/.github/workflows/prerelease.yml +0 -89
- package/simsimd/.github/workflows/release.yml +0 -141
- package/simsimd/.github/workflows/update_version.sh +0 -5
- package/simsimd/.vscode/launch.json +0 -53
- package/simsimd/.vscode/settings.json +0 -114
- package/simsimd/.vscode/tasks.json +0 -23
- package/simsimd/go.mod +0 -3
- package/simsimd/golang/bench_test.go +0 -40
- package/simsimd/golang/simsimd.go +0 -47
- package/simsimd/golang/unit_test.go +0 -40
- package/simsimd/pyproject.toml +0 -42
- package/simsimd/python/bench.ipynb +0 -187
- package/simsimd/python/bench.py +0 -268
- package/simsimd/python/lib.c +0 -492
- package/simsimd/python/test.py +0 -195
package/simsimd/python/lib.c
DELETED
|
@@ -1,492 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @brief Pure CPython bindings for SimSIMD.
|
|
3
|
-
* @file lib.c
|
|
4
|
-
* @author Ash Vardanian
|
|
5
|
-
* @date January 1, 2023
|
|
6
|
-
* @copyright Copyright (c) 2023
|
|
7
|
-
*/
|
|
8
|
-
#if __linux__
|
|
9
|
-
#define SIMSIMD_TARGET_ARM_NEON 1
|
|
10
|
-
#define SIMSIMD_TARGET_ARM_SVE 1
|
|
11
|
-
#define SIMSIMD_TARGET_X86_AVX2 1
|
|
12
|
-
#define SIMSIMD_TARGET_X86_AVX512 1
|
|
13
|
-
#include <omp.h>
|
|
14
|
-
#elif defined(_MSC_VER)
|
|
15
|
-
#define SIMSIMD_TARGET_ARM_NEON 0
|
|
16
|
-
#define SIMSIMD_TARGET_ARM_SVE 0
|
|
17
|
-
#define SIMSIMD_TARGET_X86_AVX2 0
|
|
18
|
-
#define SIMSIMD_TARGET_X86_AVX512 0
|
|
19
|
-
#elif defined(__APPLE__)
|
|
20
|
-
#define SIMSIMD_TARGET_ARM_NEON 1
|
|
21
|
-
#define SIMSIMD_TARGET_ARM_SVE 0
|
|
22
|
-
#define SIMSIMD_TARGET_X86_AVX2 1
|
|
23
|
-
#define SIMSIMD_TARGET_X86_AVX512 0
|
|
24
|
-
#endif
|
|
25
|
-
|
|
26
|
-
#define SIMSIMD_RSQRT simsimd_approximate_inverse_square_root
|
|
27
|
-
#define SIMSIMD_LOG simsimd_approximate_log
|
|
28
|
-
#include "simsimd/simsimd.h"
|
|
29
|
-
|
|
30
|
-
#define PY_SSIZE_T_CLEAN
|
|
31
|
-
#include <Python.h>
|
|
32
|
-
#include <numpy/arrayobject.h>
|
|
33
|
-
|
|
34
|
-
typedef struct parsed_vector_or_matrix_t {
|
|
35
|
-
char* start;
|
|
36
|
-
size_t dimensions;
|
|
37
|
-
size_t count;
|
|
38
|
-
size_t stride;
|
|
39
|
-
int is_flat;
|
|
40
|
-
simsimd_datatype_t datatype;
|
|
41
|
-
} parsed_vector_or_matrix_t;
|
|
42
|
-
|
|
43
|
-
/// @brief Global variable that caches the CPU capabilities, and is computed just onc, when the module is loaded.
|
|
44
|
-
simsimd_capability_t static_capabilities = simsimd_cap_serial_k;
|
|
45
|
-
|
|
46
|
-
int same_string(char const* a, char const* b) { return strcmp(a, b) == 0; }
|
|
47
|
-
|
|
48
|
-
simsimd_datatype_t numpy_string_to_datatype(char const* name) {
|
|
49
|
-
// https://docs.python.org/3/library/struct.html#format-characters
|
|
50
|
-
if (same_string(name, "f") || same_string(name, "<f") || same_string(name, "f4") || same_string(name, "<f4"))
|
|
51
|
-
return simsimd_datatype_f32_k;
|
|
52
|
-
else if (same_string(name, "e") || same_string(name, "<e") || same_string(name, "f2") || same_string(name, "<f2"))
|
|
53
|
-
return simsimd_datatype_f16_k;
|
|
54
|
-
else if (same_string(name, "b") || same_string(name, "<b") || same_string(name, "i1") || same_string(name, "|i1"))
|
|
55
|
-
return simsimd_datatype_i8_k;
|
|
56
|
-
else if (same_string(name, "B") || same_string(name, "<B") || same_string(name, "u1") || same_string(name, "|u1"))
|
|
57
|
-
return simsimd_datatype_b8_k;
|
|
58
|
-
else if (same_string(name, "d") || same_string(name, "<d") || same_string(name, "i8") || same_string(name, "<i8"))
|
|
59
|
-
return simsimd_datatype_f64_k;
|
|
60
|
-
else
|
|
61
|
-
return simsimd_datatype_unknown_k;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
simsimd_datatype_t python_string_to_datatype(char const* name) {
|
|
65
|
-
if (same_string(name, "f") || same_string(name, "f32"))
|
|
66
|
-
return simsimd_datatype_f32_k;
|
|
67
|
-
else if (same_string(name, "h") || same_string(name, "f16"))
|
|
68
|
-
return simsimd_datatype_f16_k;
|
|
69
|
-
else if (same_string(name, "c") || same_string(name, "i8"))
|
|
70
|
-
return simsimd_datatype_i8_k;
|
|
71
|
-
else if (same_string(name, "b") || same_string(name, "b8"))
|
|
72
|
-
return simsimd_datatype_b8_k;
|
|
73
|
-
else if (same_string(name, "d") || same_string(name, "f64"))
|
|
74
|
-
return simsimd_datatype_f64_k;
|
|
75
|
-
else
|
|
76
|
-
return simsimd_datatype_unknown_k;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
simsimd_metric_kind_t python_string_to_metric_kind(char const* name) {
|
|
80
|
-
if (same_string(name, "sqeuclidean"))
|
|
81
|
-
return simsimd_metric_sqeuclidean_k;
|
|
82
|
-
else if (same_string(name, "inner"))
|
|
83
|
-
return simsimd_metric_inner_k;
|
|
84
|
-
else if (same_string(name, "cosine"))
|
|
85
|
-
return simsimd_metric_cosine_k;
|
|
86
|
-
else if (same_string(name, "hamming"))
|
|
87
|
-
return simsimd_metric_hamming_k;
|
|
88
|
-
else if (same_string(name, "jaccard"))
|
|
89
|
-
return simsimd_metric_jaccard_k;
|
|
90
|
-
else if (same_string(name, "kullbackleibler") || same_string(name, "kl"))
|
|
91
|
-
return simsimd_metric_kl_k;
|
|
92
|
-
else if (same_string(name, "jensenshannon") || same_string(name, "js"))
|
|
93
|
-
return simsimd_metric_js_k;
|
|
94
|
-
else if (same_string(name, "jaccard"))
|
|
95
|
-
return simsimd_metric_jaccard_k;
|
|
96
|
-
else
|
|
97
|
-
return simsimd_metric_unknown_k;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
static PyObject* api_get_capabilities(PyObject* self) {
|
|
101
|
-
simsimd_capability_t caps = static_capabilities;
|
|
102
|
-
PyObject* cap_dict = PyDict_New();
|
|
103
|
-
if (!cap_dict)
|
|
104
|
-
return NULL;
|
|
105
|
-
|
|
106
|
-
#define ADD_CAP(name) PyDict_SetItemString(cap_dict, #name, PyBool_FromLong(caps& simsimd_cap_##name##_k))
|
|
107
|
-
|
|
108
|
-
ADD_CAP(serial);
|
|
109
|
-
ADD_CAP(arm_neon);
|
|
110
|
-
ADD_CAP(arm_sve);
|
|
111
|
-
ADD_CAP(arm_sve2);
|
|
112
|
-
ADD_CAP(x86_avx2);
|
|
113
|
-
ADD_CAP(x86_avx512);
|
|
114
|
-
ADD_CAP(x86_avx2fp16);
|
|
115
|
-
ADD_CAP(x86_avx512fp16);
|
|
116
|
-
ADD_CAP(x86_avx512vpopcntdq);
|
|
117
|
-
ADD_CAP(x86_avx512vnni);
|
|
118
|
-
|
|
119
|
-
#undef ADD_CAP
|
|
120
|
-
|
|
121
|
-
return cap_dict;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
int parse_tensor(PyObject* tensor, Py_buffer* buffer, parsed_vector_or_matrix_t* parsed) {
|
|
125
|
-
if (PyObject_GetBuffer(tensor, buffer, PyBUF_STRIDES | PyBUF_FORMAT) != 0) {
|
|
126
|
-
PyErr_SetString(PyExc_TypeError, "arguments must support buffer protocol");
|
|
127
|
-
return -1;
|
|
128
|
-
}
|
|
129
|
-
parsed->start = buffer->buf;
|
|
130
|
-
parsed->datatype = numpy_string_to_datatype(buffer->format);
|
|
131
|
-
if (buffer->ndim == 1) {
|
|
132
|
-
if (buffer->strides[0] > buffer->itemsize) {
|
|
133
|
-
PyErr_SetString(PyExc_ValueError, "input vectors must be contiguous");
|
|
134
|
-
PyBuffer_Release(buffer);
|
|
135
|
-
return -1;
|
|
136
|
-
}
|
|
137
|
-
parsed->is_flat = 1;
|
|
138
|
-
parsed->dimensions = buffer->shape[0];
|
|
139
|
-
parsed->count = 1;
|
|
140
|
-
parsed->stride = 0;
|
|
141
|
-
} else if (buffer->ndim == 2) {
|
|
142
|
-
if (buffer->strides[1] > buffer->itemsize) {
|
|
143
|
-
PyErr_SetString(PyExc_ValueError, "input vectors must be contiguous");
|
|
144
|
-
PyBuffer_Release(buffer);
|
|
145
|
-
return -1;
|
|
146
|
-
}
|
|
147
|
-
parsed->is_flat = 0;
|
|
148
|
-
parsed->dimensions = buffer->shape[1];
|
|
149
|
-
parsed->count = buffer->shape[0];
|
|
150
|
-
parsed->stride = buffer->strides[0];
|
|
151
|
-
} else {
|
|
152
|
-
PyErr_SetString(PyExc_ValueError, "input tensors must be 1D or 2D");
|
|
153
|
-
PyBuffer_Release(buffer);
|
|
154
|
-
return -1;
|
|
155
|
-
}
|
|
156
|
-
return 0;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
static PyObject* impl_metric(simsimd_metric_kind_t metric_kind, PyObject* const* args, Py_ssize_t nargs) {
|
|
160
|
-
if (nargs != 2) {
|
|
161
|
-
PyErr_SetString(PyExc_TypeError, "function expects exactly 2 arguments");
|
|
162
|
-
return NULL;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
PyObject* output = NULL;
|
|
166
|
-
PyObject* input_tensor_a = args[0];
|
|
167
|
-
PyObject* input_tensor_b = args[1];
|
|
168
|
-
Py_buffer buffer_a, buffer_b;
|
|
169
|
-
parsed_vector_or_matrix_t parsed_a, parsed_b;
|
|
170
|
-
if (parse_tensor(input_tensor_a, &buffer_a, &parsed_a) != 0 ||
|
|
171
|
-
parse_tensor(input_tensor_b, &buffer_b, &parsed_b) != 0) {
|
|
172
|
-
return NULL; // Error already set by parse_tensor
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Check dimensions
|
|
176
|
-
if (parsed_a.dimensions != parsed_b.dimensions) {
|
|
177
|
-
PyErr_SetString(PyExc_ValueError, "vector dimensions don't match");
|
|
178
|
-
goto cleanup;
|
|
179
|
-
}
|
|
180
|
-
if (parsed_a.count == 0 || parsed_b.count == 0) {
|
|
181
|
-
PyErr_SetString(PyExc_ValueError, "collections can't be empty");
|
|
182
|
-
goto cleanup;
|
|
183
|
-
}
|
|
184
|
-
if (parsed_a.count > 1 && parsed_b.count > 1 && parsed_a.count != parsed_b.count) {
|
|
185
|
-
PyErr_SetString(PyExc_ValueError, "collections must have the same number of elements or just one element");
|
|
186
|
-
goto cleanup;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// Check data types
|
|
190
|
-
if (parsed_a.datatype != parsed_b.datatype && parsed_a.datatype != simsimd_datatype_unknown_k &&
|
|
191
|
-
parsed_b.datatype != simsimd_datatype_unknown_k) {
|
|
192
|
-
PyErr_SetString(PyExc_ValueError, "input tensors must have matching and supported datatypes");
|
|
193
|
-
goto cleanup;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
simsimd_metric_punned_t metric = NULL;
|
|
197
|
-
simsimd_capability_t capability = simsimd_cap_serial_k;
|
|
198
|
-
simsimd_datatype_t datatype = parsed_a.datatype;
|
|
199
|
-
simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
|
|
200
|
-
if (!metric) {
|
|
201
|
-
PyErr_SetString(PyExc_ValueError, "unsupported metric and datatype combination");
|
|
202
|
-
goto cleanup;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// If the distance is computed between two vectors, rather than matrices, return a scalar
|
|
206
|
-
if (parsed_a.is_flat && parsed_b.is_flat) {
|
|
207
|
-
output = PyFloat_FromDouble(metric(parsed_a.start, parsed_b.start, parsed_a.dimensions, parsed_b.dimensions));
|
|
208
|
-
} else {
|
|
209
|
-
|
|
210
|
-
// In some batch requests we may be computing the distance from multiple vectors to one,
|
|
211
|
-
// so the stride must be set to zero avoid illegal memory access
|
|
212
|
-
if (parsed_a.count == 1)
|
|
213
|
-
parsed_a.stride = 0;
|
|
214
|
-
if (parsed_b.count == 1)
|
|
215
|
-
parsed_b.stride = 0;
|
|
216
|
-
|
|
217
|
-
size_t count_max = parsed_a.count > parsed_b.count ? parsed_a.count : parsed_b.count;
|
|
218
|
-
|
|
219
|
-
// Compute the distances
|
|
220
|
-
float* distances = malloc(count_max * sizeof(float));
|
|
221
|
-
for (size_t i = 0; i < count_max; ++i)
|
|
222
|
-
distances[i] = metric( //
|
|
223
|
-
parsed_a.start + i * parsed_a.stride, //
|
|
224
|
-
parsed_b.start + i * parsed_b.stride, //
|
|
225
|
-
parsed_a.dimensions, //
|
|
226
|
-
parsed_b.dimensions);
|
|
227
|
-
|
|
228
|
-
// Create a new PyArray object for the output
|
|
229
|
-
npy_intp dims[1] = {count_max};
|
|
230
|
-
PyArray_Descr* descr = PyArray_DescrFromType(NPY_FLOAT32);
|
|
231
|
-
PyArrayObject* output_array = (PyArrayObject*)PyArray_NewFromDescr( //
|
|
232
|
-
&PyArray_Type, descr, 1, dims, NULL, distances, NPY_ARRAY_OWNDATA | NPY_ARRAY_C_CONTIGUOUS, NULL);
|
|
233
|
-
|
|
234
|
-
if (!output_array) {
|
|
235
|
-
free(distances);
|
|
236
|
-
goto cleanup;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
output = output_array;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
cleanup:
|
|
243
|
-
PyBuffer_Release(&buffer_a);
|
|
244
|
-
PyBuffer_Release(&buffer_b);
|
|
245
|
-
return output;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
static PyObject* impl_cdist( //
|
|
249
|
-
PyObject* input_tensor_a, PyObject* input_tensor_b, //
|
|
250
|
-
simsimd_metric_kind_t metric_kind, size_t threads) {
|
|
251
|
-
|
|
252
|
-
PyObject* output = NULL;
|
|
253
|
-
Py_buffer buffer_a, buffer_b;
|
|
254
|
-
parsed_vector_or_matrix_t parsed_a, parsed_b;
|
|
255
|
-
if (parse_tensor(input_tensor_a, &buffer_a, &parsed_a) != 0 ||
|
|
256
|
-
parse_tensor(input_tensor_b, &buffer_b, &parsed_b) != 0) {
|
|
257
|
-
return NULL; // Error already set by parse_tensor
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Check dimensions
|
|
261
|
-
if (parsed_a.dimensions != parsed_b.dimensions) {
|
|
262
|
-
PyErr_SetString(PyExc_ValueError, "vector dimensions don't match");
|
|
263
|
-
goto cleanup;
|
|
264
|
-
}
|
|
265
|
-
if (parsed_a.count == 0 || parsed_b.count == 0) {
|
|
266
|
-
PyErr_SetString(PyExc_ValueError, "collections can't be empty");
|
|
267
|
-
goto cleanup;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Check data types
|
|
271
|
-
if (parsed_a.datatype != parsed_b.datatype && parsed_a.datatype != simsimd_datatype_unknown_k &&
|
|
272
|
-
parsed_b.datatype != simsimd_datatype_unknown_k) {
|
|
273
|
-
PyErr_SetString(PyExc_ValueError, "input tensors must have matching and supported datatypes");
|
|
274
|
-
goto cleanup;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
simsimd_metric_punned_t metric = NULL;
|
|
278
|
-
simsimd_capability_t capability = simsimd_cap_serial_k;
|
|
279
|
-
simsimd_datatype_t datatype = parsed_a.datatype;
|
|
280
|
-
simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
|
|
281
|
-
if (!metric) {
|
|
282
|
-
PyErr_SetString(PyExc_ValueError, "unsupported metric and datatype combination");
|
|
283
|
-
goto cleanup;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
// If the distance is computed between two vectors, rather than matrices, return a scalar
|
|
287
|
-
if (parsed_a.is_flat && parsed_b.is_flat) {
|
|
288
|
-
output = PyFloat_FromDouble(metric(parsed_a.start, parsed_b.start, parsed_a.dimensions, parsed_b.dimensions));
|
|
289
|
-
} else {
|
|
290
|
-
|
|
291
|
-
#ifdef __linux__
|
|
292
|
-
#ifdef _OPENMP
|
|
293
|
-
if (threads == 0)
|
|
294
|
-
threads = omp_get_num_procs();
|
|
295
|
-
omp_set_num_threads(threads);
|
|
296
|
-
#endif
|
|
297
|
-
#endif
|
|
298
|
-
// Compute the distances
|
|
299
|
-
float* distances = malloc(parsed_a.count * parsed_b.count * sizeof(float));
|
|
300
|
-
#pragma omp parallel for collapse(2)
|
|
301
|
-
for (size_t i = 0; i < parsed_a.count; ++i)
|
|
302
|
-
for (size_t j = 0; j < parsed_b.count; ++j)
|
|
303
|
-
distances[i * parsed_b.count + j] = metric( //
|
|
304
|
-
parsed_a.start + i * parsed_a.stride, //
|
|
305
|
-
parsed_b.start + j * parsed_b.stride, //
|
|
306
|
-
parsed_a.dimensions, //
|
|
307
|
-
parsed_b.dimensions);
|
|
308
|
-
|
|
309
|
-
// Create a new PyArray object for the output
|
|
310
|
-
npy_intp dims[2] = {parsed_a.count, parsed_b.count};
|
|
311
|
-
PyArray_Descr* descr = PyArray_DescrFromType(NPY_FLOAT32);
|
|
312
|
-
PyArrayObject* output_array = (PyArrayObject*)PyArray_NewFromDescr( //
|
|
313
|
-
&PyArray_Type, descr, 2, dims, NULL, distances, NPY_ARRAY_OWNDATA | NPY_ARRAY_C_CONTIGUOUS, NULL);
|
|
314
|
-
|
|
315
|
-
if (!output_array) {
|
|
316
|
-
free(distances);
|
|
317
|
-
goto cleanup;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
output = output_array;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
cleanup:
|
|
324
|
-
PyBuffer_Release(&buffer_a);
|
|
325
|
-
PyBuffer_Release(&buffer_b);
|
|
326
|
-
return output;
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
static PyObject* impl_pointer(simsimd_metric_kind_t metric_kind, PyObject* args) {
|
|
330
|
-
char const* type_name = PyUnicode_AsUTF8(PyTuple_GetItem(args, 0));
|
|
331
|
-
if (!type_name) {
|
|
332
|
-
PyErr_SetString(PyExc_ValueError, "Invalid type name");
|
|
333
|
-
return NULL;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
simsimd_datatype_t datatype = python_string_to_datatype(type_name);
|
|
337
|
-
if (!type_name) {
|
|
338
|
-
PyErr_SetString(PyExc_ValueError, "Unsupported type");
|
|
339
|
-
return NULL;
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
simsimd_metric_punned_t metric = NULL;
|
|
343
|
-
simsimd_capability_t capability = simsimd_cap_serial_k;
|
|
344
|
-
simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
|
|
345
|
-
if (metric == NULL) {
|
|
346
|
-
PyErr_SetString(PyExc_ValueError, "No such metric");
|
|
347
|
-
return NULL;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
return PyLong_FromUnsignedLongLong((unsigned long long)metric);
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
static PyObject* api_cdist(PyObject* self, PyObject* args, PyObject* kwargs) {
|
|
354
|
-
PyObject *input_tensor_a, *input_tensor_b;
|
|
355
|
-
PyObject* metric_obj = NULL;
|
|
356
|
-
PyObject* threads_obj = NULL;
|
|
357
|
-
|
|
358
|
-
if (!PyTuple_Check(args) || PyTuple_Size(args) < 2) {
|
|
359
|
-
PyErr_SetString(PyExc_TypeError, "function expects at least 2 positional arguments");
|
|
360
|
-
return NULL;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
input_tensor_a = PyTuple_GetItem(args, 0);
|
|
364
|
-
input_tensor_b = PyTuple_GetItem(args, 1);
|
|
365
|
-
if (PyTuple_Size(args) > 2)
|
|
366
|
-
metric_obj = PyTuple_GetItem(args, 2);
|
|
367
|
-
if (PyTuple_Size(args) > 3)
|
|
368
|
-
threads_obj = PyTuple_GetItem(args, 3);
|
|
369
|
-
|
|
370
|
-
// Checking for named arguments in kwargs
|
|
371
|
-
if (kwargs) {
|
|
372
|
-
if (!metric_obj) {
|
|
373
|
-
metric_obj = PyDict_GetItemString(kwargs, "metric");
|
|
374
|
-
} else if (PyDict_GetItemString(kwargs, "metric")) {
|
|
375
|
-
PyErr_SetString(PyExc_TypeError, "Duplicate argument for 'metric'");
|
|
376
|
-
return NULL;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
if (!threads_obj) {
|
|
380
|
-
threads_obj = PyDict_GetItemString(kwargs, "threads");
|
|
381
|
-
} else if (PyDict_GetItemString(kwargs, "threads")) {
|
|
382
|
-
PyErr_SetString(PyExc_TypeError, "Duplicate argument for 'threads'");
|
|
383
|
-
return NULL;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// Process the PyObject values
|
|
388
|
-
simsimd_metric_kind_t metric_kind = simsimd_metric_l2sq_k;
|
|
389
|
-
if (metric_obj) {
|
|
390
|
-
char const* metric_str = PyUnicode_AsUTF8(metric_obj);
|
|
391
|
-
if (!metric_str && PyErr_Occurred()) {
|
|
392
|
-
PyErr_SetString(PyExc_TypeError, "Expected 'metric' to be a string");
|
|
393
|
-
return NULL;
|
|
394
|
-
}
|
|
395
|
-
metric_kind = python_string_to_metric_kind(metric_str);
|
|
396
|
-
if (metric_kind == simsimd_metric_unknown_k) {
|
|
397
|
-
PyErr_SetString(PyExc_ValueError, "Unsupported metric");
|
|
398
|
-
return NULL;
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
size_t threads = 1;
|
|
403
|
-
if (threads_obj)
|
|
404
|
-
threads = PyLong_AsSize_t(threads_obj);
|
|
405
|
-
if (PyErr_Occurred()) {
|
|
406
|
-
PyErr_SetString(PyExc_TypeError, "Expected 'threads' to be an unsigned integer");
|
|
407
|
-
return NULL;
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
return impl_cdist(input_tensor_a, input_tensor_b, metric_kind, threads);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
static PyObject* api_l2sq_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_l2sq_k, args); }
|
|
414
|
-
static PyObject* api_cos_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_cos_k, args); }
|
|
415
|
-
static PyObject* api_ip_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_ip_k, args); }
|
|
416
|
-
static PyObject* api_kl_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_kl_k, args); }
|
|
417
|
-
static PyObject* api_js_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_js_k, args); }
|
|
418
|
-
static PyObject* api_hamming_pointer(PyObject* self, PyObject* args) {
|
|
419
|
-
return impl_pointer(simsimd_metric_hamming_k, args);
|
|
420
|
-
}
|
|
421
|
-
static PyObject* api_jaccard_pointer(PyObject* self, PyObject* args) {
|
|
422
|
-
return impl_pointer(simsimd_metric_jaccard_k, args);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
static PyObject* api_l2sq(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
426
|
-
return impl_metric(simsimd_metric_l2sq_k, args, nargs);
|
|
427
|
-
}
|
|
428
|
-
static PyObject* api_cos(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
429
|
-
return impl_metric(simsimd_metric_cos_k, args, nargs);
|
|
430
|
-
}
|
|
431
|
-
static PyObject* api_ip(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
432
|
-
return impl_metric(simsimd_metric_ip_k, args, nargs);
|
|
433
|
-
}
|
|
434
|
-
static PyObject* api_kl(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
435
|
-
return impl_metric(simsimd_metric_kl_k, args, nargs);
|
|
436
|
-
}
|
|
437
|
-
static PyObject* api_js(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
438
|
-
return impl_metric(simsimd_metric_js_k, args, nargs);
|
|
439
|
-
}
|
|
440
|
-
static PyObject* api_hamming(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
441
|
-
return impl_metric(simsimd_metric_hamming_k, args, nargs);
|
|
442
|
-
}
|
|
443
|
-
static PyObject* api_jaccard(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
|
|
444
|
-
return impl_metric(simsimd_metric_jaccard_k, args, nargs);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
static PyMethodDef simsimd_methods[] = {
|
|
448
|
-
// Introspecting library and hardware capabilities
|
|
449
|
-
{"get_capabilities", api_get_capabilities, METH_NOARGS, "Get hardware capabilities"},
|
|
450
|
-
|
|
451
|
-
// NumPy and SciPy compatible interfaces (two matrix or vector arguments)
|
|
452
|
-
{"sqeuclidean", api_l2sq, METH_FASTCALL, "L2sq (Sq. Euclidean) distances between a pair of matrices"},
|
|
453
|
-
{"cosine", api_cos, METH_FASTCALL, "Cosine (Angular) distances between a pair of matrices"},
|
|
454
|
-
{"inner", api_ip, METH_FASTCALL, "Inner (Dot) Product distances between a pair of matrices"},
|
|
455
|
-
{"hamming", api_hamming, METH_FASTCALL, "Hamming distances between a pair of matrices"},
|
|
456
|
-
{"jaccard", api_jaccard, METH_FASTCALL, "Jaccard (Bitwise Tanimoto) distances between a pair of matrices"},
|
|
457
|
-
{"kullbackleibler", api_kl, METH_FASTCALL, "Kullback-Leibler divergence between probability distributions"},
|
|
458
|
-
{"jensenshannon", api_js, METH_FASTCALL, "Jensen-Shannon divergence between probability distributions"},
|
|
459
|
-
|
|
460
|
-
// Conventional `cdist` and `pdist` insterfaces with third string argument, and optional `threads` arg
|
|
461
|
-
{"cdist", api_cdist, METH_VARARGS | METH_KEYWORDS,
|
|
462
|
-
"Compute distance between each pair of the two collections of inputs"},
|
|
463
|
-
|
|
464
|
-
// Exposing underlying API for USearch
|
|
465
|
-
{"pointer_to_sqeuclidean", api_l2sq_pointer, METH_VARARGS, "L2sq (Sq. Euclidean) function pointer as `int`"},
|
|
466
|
-
{"pointer_to_cosine", api_cos_pointer, METH_VARARGS, "Cosine (Angular) function pointer as `int`"},
|
|
467
|
-
{"pointer_to_inner", api_ip_pointer, METH_VARARGS, "Inner (Dot) Product function pointer as `int`"},
|
|
468
|
-
{"pointer_to_kullbackleibler", api_ip_pointer, METH_VARARGS, "Kullback-Leibler function pointer as `int`"},
|
|
469
|
-
{"pointer_to_jensenshannon", api_ip_pointer, METH_VARARGS, "Jensen-Shannon function pointer as `int`"},
|
|
470
|
-
|
|
471
|
-
// Sentinel
|
|
472
|
-
{NULL, NULL, 0, NULL}};
|
|
473
|
-
|
|
474
|
-
static PyModuleDef simsimd_module = {
|
|
475
|
-
PyModuleDef_HEAD_INIT,
|
|
476
|
-
.m_name = "SimSIMD",
|
|
477
|
-
.m_doc = "Vector Similarity Functions 3x-200x Faster than SciPy and NumPy",
|
|
478
|
-
.m_size = -1,
|
|
479
|
-
.m_methods = simsimd_methods,
|
|
480
|
-
};
|
|
481
|
-
|
|
482
|
-
PyMODINIT_FUNC PyInit_simsimd(void) {
|
|
483
|
-
_import_array();
|
|
484
|
-
PyObject* module = PyModule_Create(&simsimd_module);
|
|
485
|
-
|
|
486
|
-
// Open the VERSION file to add the `simsimd.__version__` attribute
|
|
487
|
-
if (module)
|
|
488
|
-
PyModule_AddStringConstant(module, "__version__", "2.1.1");
|
|
489
|
-
|
|
490
|
-
static_capabilities = simsimd_capabilities();
|
|
491
|
-
return module;
|
|
492
|
-
}
|
package/simsimd/python/test.py
DELETED
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
import pytest
|
|
2
|
-
import numpy as np
|
|
3
|
-
import simsimd as simd
|
|
4
|
-
import scipy.spatial.distance as spd
|
|
5
|
-
|
|
6
|
-
# For normalized distances we use the absolute tolerance, because the result is close to zero.
|
|
7
|
-
# For unnormalized ones (like squared Euclidean or Jaccard), we use the relative.
|
|
8
|
-
SIMSIMD_RTOL = 0.2
|
|
9
|
-
SIMSIMD_ATOL = 0.1
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def test_pointers_availability():
|
|
13
|
-
"""Tests the availability of pre-compiled functions for compatibility with USearch."""
|
|
14
|
-
assert simd.pointer_to_sqeuclidean("f32") != 0
|
|
15
|
-
assert simd.pointer_to_cosine("f32") != 0
|
|
16
|
-
assert simd.pointer_to_inner("f32") != 0
|
|
17
|
-
|
|
18
|
-
assert simd.pointer_to_sqeuclidean("f16") != 0
|
|
19
|
-
assert simd.pointer_to_cosine("f16") != 0
|
|
20
|
-
assert simd.pointer_to_inner("f16") != 0
|
|
21
|
-
|
|
22
|
-
assert simd.pointer_to_sqeuclidean("i8") != 0
|
|
23
|
-
assert simd.pointer_to_cosine("i8") != 0
|
|
24
|
-
assert simd.pointer_to_inner("i8") != 0
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
@pytest.mark.repeat(50)
|
|
28
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
29
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
30
|
-
def test_dot(ndim, dtype):
|
|
31
|
-
"""Compares the simd.dot() function with numpy.dot(), measuring the accuracy error for f16, and f32 types."""
|
|
32
|
-
a = np.random.randn(ndim).astype(dtype)
|
|
33
|
-
b = np.random.randn(ndim).astype(dtype)
|
|
34
|
-
a /= np.linalg.norm(a)
|
|
35
|
-
b /= np.linalg.norm(b)
|
|
36
|
-
|
|
37
|
-
expected = 1 - np.inner(a, b)
|
|
38
|
-
result = simd.inner(a, b)
|
|
39
|
-
|
|
40
|
-
np.testing.assert_allclose(expected, result, atol=SIMSIMD_ATOL, rtol=0)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
@pytest.mark.repeat(50)
|
|
44
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
45
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
46
|
-
def test_sqeuclidean(ndim, dtype):
|
|
47
|
-
"""Compares the simd.sqeuclidean() function with scipy.spatial.distance.sqeuclidean(), measuring the accuracy error for f16, and f32 types."""
|
|
48
|
-
a = np.random.randn(ndim).astype(dtype)
|
|
49
|
-
b = np.random.randn(ndim).astype(dtype)
|
|
50
|
-
|
|
51
|
-
expected = spd.sqeuclidean(a, b)
|
|
52
|
-
result = simd.sqeuclidean(a, b)
|
|
53
|
-
|
|
54
|
-
np.testing.assert_allclose(expected, result, atol=0, rtol=SIMSIMD_RTOL)
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
@pytest.mark.repeat(50)
|
|
58
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
59
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
60
|
-
def test_cosine(ndim, dtype):
|
|
61
|
-
"""Compares the simd.cosine() function with scipy.spatial.distance.cosine(), measuring the accuracy error for f16, and f32 types."""
|
|
62
|
-
a = np.random.randn(ndim).astype(dtype)
|
|
63
|
-
b = np.random.randn(ndim).astype(dtype)
|
|
64
|
-
|
|
65
|
-
expected = spd.cosine(a, b)
|
|
66
|
-
result = simd.cosine(a, b)
|
|
67
|
-
|
|
68
|
-
np.testing.assert_allclose(expected, result, atol=SIMSIMD_ATOL, rtol=0)
|
|
69
|
-
|
|
70
|
-
@pytest.mark.repeat(50)
|
|
71
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
72
|
-
def test_cosine_i8(ndim):
|
|
73
|
-
"""Compares the simd.cosine() function with scipy.spatial.distance.cosine(), measuring the accuracy error for 8-bit int types."""
|
|
74
|
-
a = np.random.randint(0, 100, size=ndim, dtype=np.int8)
|
|
75
|
-
b = np.random.randint(0, 100, size=ndim, dtype=np.int8)
|
|
76
|
-
|
|
77
|
-
expected = spd.cosine(a.astype(np.float32), b.astype(np.float32))
|
|
78
|
-
result = simd.cosine(a, b)
|
|
79
|
-
|
|
80
|
-
np.testing.assert_allclose(expected, result, atol=SIMSIMD_ATOL, rtol=0)
|
|
81
|
-
|
|
82
|
-
@pytest.mark.repeat(50)
|
|
83
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
84
|
-
def test_sqeuclidean_i8(ndim):
|
|
85
|
-
"""Compares the simd.sqeuclidean() function with scipy.spatial.distance.sqeuclidean(), measuring the accuracy error for 8-bit int types."""
|
|
86
|
-
a = np.random.randint(0, 100, size=ndim, dtype=np.int8)
|
|
87
|
-
b = np.random.randint(0, 100, size=ndim, dtype=np.int8)
|
|
88
|
-
|
|
89
|
-
expected = spd.sqeuclidean(a.astype(np.float32), b.astype(np.float32))
|
|
90
|
-
result = simd.sqeuclidean(a, b)
|
|
91
|
-
|
|
92
|
-
np.testing.assert_allclose(expected, result, atol=0, rtol=SIMSIMD_RTOL)
|
|
93
|
-
|
|
94
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
95
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
96
|
-
def test_cosine_zero_vector(ndim, dtype):
|
|
97
|
-
"""Tests the simd.cosine() function with zero vectors, to catch division by zero errors."""
|
|
98
|
-
a = np.zeros(ndim, dtype=dtype)
|
|
99
|
-
b = np.random.randn(ndim).astype(dtype)
|
|
100
|
-
|
|
101
|
-
# SciPy raises: "RuntimeWarning: invalid value encountered in scalar divide"
|
|
102
|
-
with pytest.raises(RuntimeWarning):
|
|
103
|
-
expected = spd.cosine(a, b)
|
|
104
|
-
|
|
105
|
-
expected = 1
|
|
106
|
-
result = simd.cosine(a, b)
|
|
107
|
-
|
|
108
|
-
assert result == expected, f"Expected {expected}, but got {result}"
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
@pytest.mark.repeat(50)
|
|
112
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
113
|
-
def test_hamming(ndim):
|
|
114
|
-
"""Compares the simd.hamming() function with scipy.spatial.distance.hamming."""
|
|
115
|
-
a = np.random.randint(2, size=ndim).astype(np.uint8)
|
|
116
|
-
b = np.random.randint(2, size=ndim).astype(np.uint8)
|
|
117
|
-
|
|
118
|
-
expected = spd.hamming(a, b) * ndim
|
|
119
|
-
result = simd.hamming(np.packbits(a), np.packbits(b))
|
|
120
|
-
|
|
121
|
-
np.testing.assert_allclose(expected, result, atol=0, rtol=SIMSIMD_RTOL)
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
@pytest.mark.repeat(50)
|
|
125
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
126
|
-
def test_jaccard(ndim):
|
|
127
|
-
"""Compares the simd.jaccard() function with scipy.spatial.distance.jaccard."""
|
|
128
|
-
a = np.random.randint(2, size=ndim).astype(np.uint8)
|
|
129
|
-
b = np.random.randint(2, size=ndim).astype(np.uint8)
|
|
130
|
-
|
|
131
|
-
expected = spd.jaccard(a, b)
|
|
132
|
-
result = simd.jaccard(np.packbits(a), np.packbits(b))
|
|
133
|
-
|
|
134
|
-
np.testing.assert_allclose(expected, result, atol=SIMSIMD_ATOL, rtol=0)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
138
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
139
|
-
def test_batch(ndim, dtype):
|
|
140
|
-
"""Compares the simd.simd.sqeuclidean() function with scipy.spatial.distance.sqeuclidean() for a batch of vectors, measuring the accuracy error for f16, and f32 types."""
|
|
141
|
-
|
|
142
|
-
# Distance between matrixes A (N x D scalars) and B (N x D scalars) is an array with N floats.
|
|
143
|
-
A = np.random.randn(10, ndim).astype(dtype)
|
|
144
|
-
B = np.random.randn(10, ndim).astype(dtype)
|
|
145
|
-
result_np = [spd.sqeuclidean(A[i], B[i]) for i in range(10)]
|
|
146
|
-
result_simd = simd.sqeuclidean(A, B)
|
|
147
|
-
assert np.allclose(result_simd, result_np, atol=0, rtol=SIMSIMD_RTOL)
|
|
148
|
-
|
|
149
|
-
# Distance between matrixes A (N x D scalars) and B (1 x D scalars) is an array with N floats.
|
|
150
|
-
B = np.random.randn(1, ndim).astype(dtype)
|
|
151
|
-
result_np = [spd.sqeuclidean(A[i], B[0]) for i in range(10)]
|
|
152
|
-
result_simd = simd.sqeuclidean(A, B)
|
|
153
|
-
assert np.allclose(result_simd, result_np, atol=0, rtol=SIMSIMD_RTOL)
|
|
154
|
-
|
|
155
|
-
# Distance between matrixes A (1 x D scalars) and B (N x D scalars) is an array with N floats.
|
|
156
|
-
A = np.random.randn(1, ndim).astype(dtype)
|
|
157
|
-
B = np.random.randn(10, ndim).astype(dtype)
|
|
158
|
-
result_np = [spd.sqeuclidean(A[0], B[i]) for i in range(10)]
|
|
159
|
-
result_simd = simd.sqeuclidean(A, B)
|
|
160
|
-
assert np.allclose(result_simd, result_np, atol=0, rtol=SIMSIMD_RTOL)
|
|
161
|
-
|
|
162
|
-
# Distance between matrix A (N x D scalars) and array B (D scalars) is an array with N floats.
|
|
163
|
-
A = np.random.randn(10, ndim).astype(dtype)
|
|
164
|
-
B = np.random.randn(ndim).astype(dtype)
|
|
165
|
-
result_np = [spd.sqeuclidean(A[i], B) for i in range(10)]
|
|
166
|
-
result_simd = simd.sqeuclidean(A, B)
|
|
167
|
-
assert np.allclose(result_simd, result_np, atol=0, rtol=SIMSIMD_RTOL)
|
|
168
|
-
|
|
169
|
-
# Distance between matrix B (N x D scalars) and array A (D scalars) is an array with N floats.
|
|
170
|
-
B = np.random.randn(10, ndim).astype(dtype)
|
|
171
|
-
A = np.random.randn(ndim).astype(dtype)
|
|
172
|
-
result_np = [spd.sqeuclidean(B[i], A) for i in range(10)]
|
|
173
|
-
result_simd = simd.sqeuclidean(B, A)
|
|
174
|
-
assert np.allclose(result_simd, result_np, atol=0, rtol=SIMSIMD_RTOL)
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
@pytest.mark.parametrize("ndim", [3, 97, 1536])
|
|
178
|
-
@pytest.mark.parametrize("dtype", [np.float32, np.float16])
|
|
179
|
-
@pytest.mark.parametrize("metric", ["cosine"])
|
|
180
|
-
def test_cdist(ndim, dtype, metric):
|
|
181
|
-
"""Compares the simd.cdist() function with scipy.spatial.distance.cdist(), measuring the accuracy error for f16, and f32 types using sqeuclidean and cosine metrics."""
|
|
182
|
-
|
|
183
|
-
# Create random matrices A (M x D) and B (N x D).
|
|
184
|
-
M, N = 10, 15 # or any other sizes you deem appropriate
|
|
185
|
-
A = np.random.randn(M, ndim).astype(dtype)
|
|
186
|
-
B = np.random.randn(N, ndim).astype(dtype)
|
|
187
|
-
|
|
188
|
-
# Compute cdist using scipy.
|
|
189
|
-
expected = spd.cdist(A, B, metric)
|
|
190
|
-
|
|
191
|
-
# Compute cdist using simd.
|
|
192
|
-
result = simd.cdist(A, B, metric=metric)
|
|
193
|
-
|
|
194
|
-
# Assert they're close.
|
|
195
|
-
np.testing.assert_allclose(expected, result, atol=SIMSIMD_ATOL, rtol=0)
|