usearch 2.7.3 → 2.7.6

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.
Files changed (55) hide show
  1. package/.github/workflows/Dockerfile.libs +4 -6
  2. package/.github/workflows/prerelease.yml +4 -1
  3. package/.github/workflows/release.yml +8 -28
  4. package/.github/workflows/update_version.sh +1 -0
  5. package/CITATION.cff +2 -2
  6. package/CMakeLists.txt +1 -1
  7. package/Cargo.toml +1 -1
  8. package/README.md +4 -4
  9. package/binding.gyp +1 -1
  10. package/build.gradle +20 -5
  11. package/conanfile.py +1 -1
  12. package/csharp/nuget/nuget-package.props +1 -1
  13. package/docs/compilation.md +0 -2
  14. package/golang/README.md +0 -1
  15. package/include/usearch/index.hpp +1 -1
  16. package/include/usearch/index_plugins.hpp +119 -243
  17. package/package.json +1 -1
  18. package/simsimd/.github/workflows/prerelease.yml +33 -58
  19. package/simsimd/.github/workflows/release.yml +22 -9
  20. package/simsimd/.github/workflows/update_version.sh +3 -1
  21. package/simsimd/.releaserc +9 -1
  22. package/simsimd/.vscode/launch.json +3 -0
  23. package/simsimd/.vscode/settings.json +15 -2
  24. package/simsimd/.vscode/tasks.json +2 -2
  25. package/simsimd/CMakeLists.txt +36 -55
  26. package/simsimd/README.md +163 -109
  27. package/simsimd/binding.gyp +18 -0
  28. package/simsimd/cpp/bench.cxx +187 -0
  29. package/simsimd/go.mod +3 -0
  30. package/simsimd/golang/bench_test.go +40 -0
  31. package/simsimd/golang/simsimd.go +47 -0
  32. package/simsimd/golang/unit_test.go +40 -0
  33. package/simsimd/include/simsimd/binary.h +186 -0
  34. package/simsimd/include/simsimd/probability.h +645 -0
  35. package/simsimd/include/simsimd/simsimd.h +335 -575
  36. package/simsimd/include/simsimd/spatial.h +924 -0
  37. package/simsimd/include/simsimd/types.h +196 -0
  38. package/simsimd/javascript/bench.js +117 -0
  39. package/simsimd/javascript/lib.c +102 -0
  40. package/simsimd/javascript/simsimd.js +45 -0
  41. package/simsimd/javascript/test.js +29 -0
  42. package/simsimd/package.json +31 -2
  43. package/simsimd/pyproject.toml +5 -6
  44. package/simsimd/python/bench.ipynb +187 -0
  45. package/simsimd/python/bench.py +268 -0
  46. package/simsimd/python/lib.c +453 -72
  47. package/simsimd/python/test.py +167 -35
  48. package/simsimd/setup.py +51 -8
  49. package/wasmer.toml +1 -1
  50. package/simsimd/bench.cxx +0 -137
  51. package/simsimd/include/simsimd/simsimd_bio.h +0 -54
  52. package/simsimd/include/simsimd/simsimd_chem.h +0 -167
  53. package/simsimd/include/simsimd/simsimd_text.h +0 -92
  54. package/simsimd/python/run.sh +0 -1
  55. package/simsimd/python/test.c +0 -109
@@ -1,110 +1,491 @@
1
1
  /**
2
- * @file python.c
3
- * @author Ash Vardanian
4
- * @date 2023-01-30
5
- * @copyright Copyright (c) 2023
6
- *
7
- * @brief Pure CPython bindings for SimSIMD.
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
8
7
  */
9
- #define SIMSIMD_TARGET_ARM_NEON 1
10
- #define SIMSIMD_TARGET_X86_AVX2 1
11
8
  #if __linux__
9
+ #define SIMSIMD_TARGET_ARM_NEON 1
12
10
  #define SIMSIMD_TARGET_ARM_SVE 1
11
+ #define SIMSIMD_TARGET_X86_AVX2 1
13
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
14
24
  #endif
15
25
 
26
+ #define SIMSIMD_RSQRT simsimd_approximate_inverse_square_root
27
+ #define SIMSIMD_LOG simsimd_approximate_log
16
28
  #include "simsimd/simsimd.h"
17
- #include "simsimd/simsimd_chem.h"
18
29
 
19
30
  #define PY_SSIZE_T_CLEAN
20
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;
21
42
 
22
- static void pseudo_destroy(PyObject* obj) { (void)obj; }
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;
23
45
 
24
- PyObject* distance(void* func) { return PyCapsule_New(func, NULL, pseudo_destroy); }
46
+ int same_string(char const* a, char const* b) { return strcmp(a, b) == 0; }
25
47
 
26
- static PyObject* to_int(PyObject* self, PyObject* args) {
27
- PyObject* capsule;
28
- if (!PyArg_ParseTuple(args, "O", &capsule)) {
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)
29
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
+
118
+ #undef ADD_CAP
119
+
120
+ return cap_dict;
121
+ }
122
+
123
+ int parse_tensor(PyObject* tensor, Py_buffer* buffer, parsed_vector_or_matrix_t* parsed) {
124
+ if (PyObject_GetBuffer(tensor, buffer, PyBUF_STRIDES | PyBUF_FORMAT) != 0) {
125
+ PyErr_SetString(PyExc_TypeError, "arguments must support buffer protocol");
126
+ return -1;
127
+ }
128
+ parsed->start = buffer->buf;
129
+ parsed->datatype = numpy_string_to_datatype(buffer->format);
130
+ if (buffer->ndim == 1) {
131
+ if (buffer->strides[0] > buffer->itemsize) {
132
+ PyErr_SetString(PyExc_ValueError, "input vectors must be contiguous");
133
+ PyBuffer_Release(buffer);
134
+ return -1;
135
+ }
136
+ parsed->is_flat = 1;
137
+ parsed->dimensions = buffer->shape[0];
138
+ parsed->count = 1;
139
+ parsed->stride = 0;
140
+ } else if (buffer->ndim == 2) {
141
+ if (buffer->strides[1] > buffer->itemsize) {
142
+ PyErr_SetString(PyExc_ValueError, "input vectors must be contiguous");
143
+ PyBuffer_Release(buffer);
144
+ return -1;
145
+ }
146
+ parsed->is_flat = 0;
147
+ parsed->dimensions = buffer->shape[1];
148
+ parsed->count = buffer->shape[0];
149
+ parsed->stride = buffer->strides[0];
150
+ } else {
151
+ PyErr_SetString(PyExc_ValueError, "input tensors must be 1D or 2D");
152
+ PyBuffer_Release(buffer);
153
+ return -1;
30
154
  }
155
+ return 0;
156
+ }
31
157
 
32
- if (!PyCapsule_IsValid(capsule, NULL)) {
33
- PyErr_SetString(PyExc_ValueError, "Object is not a valid capsule");
158
+ static PyObject* impl_metric(simsimd_metric_kind_t metric_kind, PyObject* const* args, Py_ssize_t nargs) {
159
+ if (nargs != 2) {
160
+ PyErr_SetString(PyExc_TypeError, "function expects exactly 2 arguments");
34
161
  return NULL;
35
162
  }
36
163
 
37
- void* pointer = PyCapsule_GetPointer(capsule, NULL);
164
+ PyObject* output = NULL;
165
+ PyObject* input_tensor_a = args[0];
166
+ PyObject* input_tensor_b = args[1];
167
+ Py_buffer buffer_a, buffer_b;
168
+ parsed_vector_or_matrix_t parsed_a, parsed_b;
169
+ if (parse_tensor(input_tensor_a, &buffer_a, &parsed_a) != 0 ||
170
+ parse_tensor(input_tensor_b, &buffer_b, &parsed_b) != 0) {
171
+ return NULL; // Error already set by parse_tensor
172
+ }
38
173
 
39
- return PyLong_FromVoidPtr(pointer);
40
- }
174
+ // Check dimensions
175
+ if (parsed_a.dimensions != parsed_b.dimensions) {
176
+ PyErr_SetString(PyExc_ValueError, "vector dimensions don't match");
177
+ goto cleanup;
178
+ }
179
+ if (parsed_a.count == 0 || parsed_b.count == 0) {
180
+ PyErr_SetString(PyExc_ValueError, "collections can't be empty");
181
+ goto cleanup;
182
+ }
183
+ if (parsed_a.count > 1 && parsed_b.count > 1 && parsed_a.count != parsed_b.count) {
184
+ PyErr_SetString(PyExc_ValueError, "collections must have the same number of elements or just one element");
185
+ goto cleanup;
186
+ }
41
187
 
42
- static PyMethodDef simsimd_methods[] = {
43
- {"to_int", (PyCFunction)to_int, METH_VARARGS, "Converts CPython capsule to `int`"},
44
- {NULL, NULL, 0, NULL} /* Sentinel */
45
- };
188
+ // Check data types
189
+ if (parsed_a.datatype != parsed_b.datatype && parsed_a.datatype != simsimd_datatype_unknown_k &&
190
+ parsed_b.datatype != simsimd_datatype_unknown_k) {
191
+ PyErr_SetString(PyExc_ValueError, "input tensors must have matching and supported datatypes");
192
+ goto cleanup;
193
+ }
46
194
 
47
- static PyModuleDef simsimd_module = {
48
- PyModuleDef_HEAD_INIT,
49
- .m_name = "SimSIMD",
50
- .m_doc = "SIMD-accelerated similarity measures for x86 and Arm: AVX2, AVX512, NEON, SVE",
51
- .m_size = -1,
52
- .m_methods = simsimd_methods,
53
- };
195
+ simsimd_metric_punned_t metric = NULL;
196
+ simsimd_capability_t capability = simsimd_cap_serial_k;
197
+ simsimd_datatype_t datatype = parsed_a.datatype;
198
+ simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
199
+ if (!metric) {
200
+ PyErr_SetString(PyExc_ValueError, "unsupported metric and datatype combination");
201
+ goto cleanup;
202
+ }
54
203
 
55
- PyMODINIT_FUNC PyInit_simsimd(void) {
56
- PyObject* m = PyModule_Create(&simsimd_module);
57
- if (m == NULL)
58
- return NULL;
204
+ // If the distance is computed between two vectors, rather than matrices, return a scalar
205
+ if (parsed_a.is_flat && parsed_b.is_flat) {
206
+ output = PyFloat_FromDouble(metric(parsed_a.start, parsed_b.start, parsed_a.dimensions, parsed_b.dimensions));
207
+ } else {
59
208
 
60
- PyModule_AddObject(m, "tanimoto_b1x8_naive", distance(&simsimd_tanimoto_b1x8_naive));
209
+ // In some batch requests we may be computing the distance from multiple vectors to one,
210
+ // so the stride must be set to zero avoid illegal memory access
211
+ if (parsed_a.count == 1)
212
+ parsed_a.stride = 0;
213
+ if (parsed_b.count == 1)
214
+ parsed_b.stride = 0;
61
215
 
62
- // Specialized:
63
- PyModule_AddObject(m, "tanimoto_maccs_naive", distance(&simsimd_tanimoto_maccs_naive));
64
- PyModule_AddObject(m, "tanimoto_conditional_naive", distance(&simsimd_tanimoto_conditional_naive));
216
+ size_t count_max = parsed_a.count > parsed_b.count ? parsed_a.count : parsed_b.count;
65
217
 
66
- #if SIMSIMD_TARGET_ARM
67
- PyModule_AddObject(m, "dot_f32x4_neon", distance(&simsimd_dot_f32x4_neon));
68
- PyModule_AddObject(m, "cos_f16x4_neon", distance(&simsimd_cos_f16x4_neon));
69
- PyModule_AddObject(m, "cos_i8x16_neon", distance(&simsimd_cos_i8x16_neon));
70
- PyModule_AddObject(m, "cos_f32x4_neon", distance(&simsimd_cos_f32x4_neon));
218
+ // Compute the distances
219
+ float* distances = malloc(count_max * sizeof(float));
220
+ for (size_t i = 0; i < count_max; ++i)
221
+ distances[i] = metric( //
222
+ parsed_a.start + i * parsed_a.stride, //
223
+ parsed_b.start + i * parsed_b.stride, //
224
+ parsed_a.dimensions, //
225
+ parsed_b.dimensions);
71
226
 
72
- // Specialized:
73
- PyModule_AddObject(m, "tanimoto_maccs_neon", distance(&simsimd_tanimoto_maccs_neon));
227
+ // Create a new PyArray object for the output
228
+ npy_intp dims[1] = {count_max};
229
+ PyArray_Descr* descr = PyArray_DescrFromType(NPY_FLOAT32);
230
+ PyArrayObject* output_array = (PyArrayObject*)PyArray_NewFromDescr( //
231
+ &PyArray_Type, descr, 1, dims, NULL, distances, NPY_ARRAY_OWNDATA | NPY_ARRAY_C_CONTIGUOUS, NULL);
74
232
 
75
- #if SIMSIMD_TARGET_ARM_SVE
76
- PyModule_AddObject(m, "dot_f32_sve", distance(&simsimd_dot_f32_sve));
77
- PyModule_AddObject(m, "cos_f32_sve", distance(&simsimd_cos_f32_sve));
78
- PyModule_AddObject(m, "cos_f16_sve", distance(&simsimd_cos_f16_sve));
79
- PyModule_AddObject(m, "l2sq_f32_sve", distance(&simsimd_l2sq_f32_sve));
80
- PyModule_AddObject(m, "l2sq_f16_sve", distance(&simsimd_l2sq_f16_sve));
81
- PyModule_AddObject(m, "hamming_b1x8_sve", distance(&simsimd_hamming_b1x8_sve));
82
- PyModule_AddObject(m, "hamming_b1x128_sve", distance(&simsimd_hamming_b1x128_sve));
233
+ if (!output_array) {
234
+ free(distances);
235
+ goto cleanup;
236
+ }
83
237
 
84
- // Specialized:
85
- PyModule_AddObject(m, "tanimoto_maccs_sve", distance(&simsimd_tanimoto_maccs_sve));
86
- #endif
87
- #endif
238
+ output = output_array;
239
+ }
88
240
 
89
- #if SIMSIMD_TARGET_X86
90
- PyModule_AddObject(m, "dot_f32x4_avx2", distance(&simsimd_dot_f32x4_avx2));
91
- PyModule_AddObject(m, "cos_f32x4_avx2", distance(&simsimd_cos_f32x4_avx2));
92
- PyModule_AddObject(m, "l2sq_f32x4_avx2", distance(&simsimd_l2sq_f32x4_avx2));
93
- PyModule_AddObject(m, "dot_f16x8_avx2", distance(&simsimd_dot_f16x8_avx2));
94
- PyModule_AddObject(m, "cos_f16x8_avx2", distance(&simsimd_cos_f16x8_avx2));
95
- PyModule_AddObject(m, "l2sq_f16x8_avx2", distance(&simsimd_l2sq_f16x8_avx2));
241
+ cleanup:
242
+ PyBuffer_Release(&buffer_a);
243
+ PyBuffer_Release(&buffer_b);
244
+ return output;
245
+ }
96
246
 
97
- #if SIMSIMD_TARGET_X86_AVX512
98
- PyModule_AddObject(m, "dot_f16x16_avx512", distance(&simsimd_dot_f16x16_avx512));
99
- PyModule_AddObject(m, "cos_f16x16_avx512", distance(&simsimd_cos_f16x16_avx512));
100
- PyModule_AddObject(m, "l2sq_f16x16_avx512", distance(&simsimd_l2sq_f16x16_avx512));
247
+ static PyObject* impl_cdist( //
248
+ PyObject* input_tensor_a, PyObject* input_tensor_b, //
249
+ simsimd_metric_kind_t metric_kind, size_t threads) {
101
250
 
102
- PyModule_AddObject(m, "hamming_b1x128_avx512", distance(&simsimd_hamming_b1x128_avx512));
251
+ PyObject* output = NULL;
252
+ Py_buffer buffer_a, buffer_b;
253
+ parsed_vector_or_matrix_t parsed_a, parsed_b;
254
+ if (parse_tensor(input_tensor_a, &buffer_a, &parsed_a) != 0 ||
255
+ parse_tensor(input_tensor_b, &buffer_b, &parsed_b) != 0) {
256
+ return NULL; // Error already set by parse_tensor
257
+ }
258
+
259
+ // Check dimensions
260
+ if (parsed_a.dimensions != parsed_b.dimensions) {
261
+ PyErr_SetString(PyExc_ValueError, "vector dimensions don't match");
262
+ goto cleanup;
263
+ }
264
+ if (parsed_a.count == 0 || parsed_b.count == 0) {
265
+ PyErr_SetString(PyExc_ValueError, "collections can't be empty");
266
+ goto cleanup;
267
+ }
103
268
 
104
- // Specialized:
105
- PyModule_AddObject(m, "tanimoto_maccs_avx512", distance(&simsimd_tanimoto_maccs_avx512));
269
+ // Check data types
270
+ if (parsed_a.datatype != parsed_b.datatype && parsed_a.datatype != simsimd_datatype_unknown_k &&
271
+ parsed_b.datatype != simsimd_datatype_unknown_k) {
272
+ PyErr_SetString(PyExc_ValueError, "input tensors must have matching and supported datatypes");
273
+ goto cleanup;
274
+ }
275
+
276
+ simsimd_metric_punned_t metric = NULL;
277
+ simsimd_capability_t capability = simsimd_cap_serial_k;
278
+ simsimd_datatype_t datatype = parsed_a.datatype;
279
+ simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
280
+ if (!metric) {
281
+ PyErr_SetString(PyExc_ValueError, "unsupported metric and datatype combination");
282
+ goto cleanup;
283
+ }
284
+
285
+ // If the distance is computed between two vectors, rather than matrices, return a scalar
286
+ if (parsed_a.is_flat && parsed_b.is_flat) {
287
+ output = PyFloat_FromDouble(metric(parsed_a.start, parsed_b.start, parsed_a.dimensions, parsed_b.dimensions));
288
+ } else {
289
+
290
+ #ifdef __linux__
291
+ #ifdef _OPENMP
292
+ if (threads == 0)
293
+ threads = omp_get_num_procs();
294
+ omp_set_num_threads(threads);
106
295
  #endif
107
296
  #endif
297
+ // Compute the distances
298
+ float* distances = malloc(parsed_a.count * parsed_b.count * sizeof(float));
299
+ #pragma omp parallel for collapse(2)
300
+ for (size_t i = 0; i < parsed_a.count; ++i)
301
+ for (size_t j = 0; j < parsed_b.count; ++j)
302
+ distances[i * parsed_b.count + j] = metric( //
303
+ parsed_a.start + i * parsed_a.stride, //
304
+ parsed_b.start + j * parsed_b.stride, //
305
+ parsed_a.dimensions, //
306
+ parsed_b.dimensions);
307
+
308
+ // Create a new PyArray object for the output
309
+ npy_intp dims[2] = {parsed_a.count, parsed_b.count};
310
+ PyArray_Descr* descr = PyArray_DescrFromType(NPY_FLOAT32);
311
+ PyArrayObject* output_array = (PyArrayObject*)PyArray_NewFromDescr( //
312
+ &PyArray_Type, descr, 2, dims, NULL, distances, NPY_ARRAY_OWNDATA | NPY_ARRAY_C_CONTIGUOUS, NULL);
313
+
314
+ if (!output_array) {
315
+ free(distances);
316
+ goto cleanup;
317
+ }
318
+
319
+ output = output_array;
320
+ }
321
+
322
+ cleanup:
323
+ PyBuffer_Release(&buffer_a);
324
+ PyBuffer_Release(&buffer_b);
325
+ return output;
326
+ }
327
+
328
+ static PyObject* impl_pointer(simsimd_metric_kind_t metric_kind, PyObject* args) {
329
+ char const* type_name = PyUnicode_AsUTF8(PyTuple_GetItem(args, 0));
330
+ if (!type_name) {
331
+ PyErr_SetString(PyExc_ValueError, "Invalid type name");
332
+ return NULL;
333
+ }
334
+
335
+ simsimd_datatype_t datatype = python_string_to_datatype(type_name);
336
+ if (!type_name) {
337
+ PyErr_SetString(PyExc_ValueError, "Unsupported type");
338
+ return NULL;
339
+ }
340
+
341
+ simsimd_metric_punned_t metric = NULL;
342
+ simsimd_capability_t capability = simsimd_cap_serial_k;
343
+ simsimd_find_metric_punned(metric_kind, datatype, static_capabilities, simsimd_cap_any_k, &metric, &capability);
344
+ if (metric == NULL) {
345
+ PyErr_SetString(PyExc_ValueError, "No such metric");
346
+ return NULL;
347
+ }
348
+
349
+ return PyLong_FromUnsignedLongLong((unsigned long long)metric);
350
+ }
351
+
352
+ static PyObject* api_cdist(PyObject* self, PyObject* args, PyObject* kwargs) {
353
+ PyObject *input_tensor_a, *input_tensor_b;
354
+ PyObject* metric_obj = NULL;
355
+ PyObject* threads_obj = NULL;
356
+
357
+ if (!PyTuple_Check(args) || PyTuple_Size(args) < 2) {
358
+ PyErr_SetString(PyExc_TypeError, "function expects at least 2 positional arguments");
359
+ return NULL;
360
+ }
361
+
362
+ input_tensor_a = PyTuple_GetItem(args, 0);
363
+ input_tensor_b = PyTuple_GetItem(args, 1);
364
+ if (PyTuple_Size(args) > 2)
365
+ metric_obj = PyTuple_GetItem(args, 2);
366
+ if (PyTuple_Size(args) > 3)
367
+ threads_obj = PyTuple_GetItem(args, 3);
368
+
369
+ // Checking for named arguments in kwargs
370
+ if (kwargs) {
371
+ if (!metric_obj) {
372
+ metric_obj = PyDict_GetItemString(kwargs, "metric");
373
+ } else if (PyDict_GetItemString(kwargs, "metric")) {
374
+ PyErr_SetString(PyExc_TypeError, "Duplicate argument for 'metric'");
375
+ return NULL;
376
+ }
377
+
378
+ if (!threads_obj) {
379
+ threads_obj = PyDict_GetItemString(kwargs, "threads");
380
+ } else if (PyDict_GetItemString(kwargs, "threads")) {
381
+ PyErr_SetString(PyExc_TypeError, "Duplicate argument for 'threads'");
382
+ return NULL;
383
+ }
384
+ }
385
+
386
+ // Process the PyObject values
387
+ simsimd_metric_kind_t metric_kind = simsimd_metric_l2sq_k;
388
+ if (metric_obj) {
389
+ char const* metric_str = PyUnicode_AsUTF8(metric_obj);
390
+ if (!metric_str && PyErr_Occurred()) {
391
+ PyErr_SetString(PyExc_TypeError, "Expected 'metric' to be a string");
392
+ return NULL;
393
+ }
394
+ metric_kind = python_string_to_metric_kind(metric_str);
395
+ if (metric_kind == simsimd_metric_unknown_k) {
396
+ PyErr_SetString(PyExc_ValueError, "Unsupported metric");
397
+ return NULL;
398
+ }
399
+ }
400
+
401
+ size_t threads = 1;
402
+ if (threads_obj)
403
+ threads = PyLong_AsSize_t(threads_obj);
404
+ if (PyErr_Occurred()) {
405
+ PyErr_SetString(PyExc_TypeError, "Expected 'threads' to be an unsigned integer");
406
+ return NULL;
407
+ }
408
+
409
+ return impl_cdist(input_tensor_a, input_tensor_b, metric_kind, threads);
410
+ }
411
+
412
+ static PyObject* api_l2sq_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_l2sq_k, args); }
413
+ static PyObject* api_cos_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_cos_k, args); }
414
+ static PyObject* api_ip_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_ip_k, args); }
415
+ static PyObject* api_kl_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_kl_k, args); }
416
+ static PyObject* api_js_pointer(PyObject* self, PyObject* args) { return impl_pointer(simsimd_metric_js_k, args); }
417
+ static PyObject* api_hamming_pointer(PyObject* self, PyObject* args) {
418
+ return impl_pointer(simsimd_metric_hamming_k, args);
419
+ }
420
+ static PyObject* api_jaccard_pointer(PyObject* self, PyObject* args) {
421
+ return impl_pointer(simsimd_metric_jaccard_k, args);
422
+ }
423
+
424
+ static PyObject* api_l2sq(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
425
+ return impl_metric(simsimd_metric_l2sq_k, args, nargs);
426
+ }
427
+ static PyObject* api_cos(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
428
+ return impl_metric(simsimd_metric_cos_k, args, nargs);
429
+ }
430
+ static PyObject* api_ip(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
431
+ return impl_metric(simsimd_metric_ip_k, args, nargs);
432
+ }
433
+ static PyObject* api_kl(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
434
+ return impl_metric(simsimd_metric_kl_k, args, nargs);
435
+ }
436
+ static PyObject* api_js(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
437
+ return impl_metric(simsimd_metric_js_k, args, nargs);
438
+ }
439
+ static PyObject* api_hamming(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
440
+ return impl_metric(simsimd_metric_hamming_k, args, nargs);
441
+ }
442
+ static PyObject* api_jaccard(PyObject* self, PyObject* const* args, Py_ssize_t nargs) {
443
+ return impl_metric(simsimd_metric_jaccard_k, args, nargs);
444
+ }
445
+
446
+ static PyMethodDef simsimd_methods[] = {
447
+ // Introspecting library and hardware capabilities
448
+ {"get_capabilities", api_get_capabilities, METH_NOARGS, "Get hardware capabilities"},
449
+
450
+ // NumPy and SciPy compatible interfaces (two matrix or vector arguments)
451
+ {"sqeuclidean", api_l2sq, METH_FASTCALL, "L2sq (Sq. Euclidean) distances between a pair of matrices"},
452
+ {"cosine", api_cos, METH_FASTCALL, "Cosine (Angular) distances between a pair of matrices"},
453
+ {"inner", api_ip, METH_FASTCALL, "Inner (Dot) Product distances between a pair of matrices"},
454
+ {"hamming", api_hamming, METH_FASTCALL, "Hamming distances between a pair of matrices"},
455
+ {"jaccard", api_jaccard, METH_FASTCALL, "Jaccard (Bitwise Tanimoto) distances between a pair of matrices"},
456
+ {"kullbackleibler", api_kl, METH_FASTCALL, "Kullback-Leibler divergence between probability distributions"},
457
+ {"jensenshannon", api_js, METH_FASTCALL, "Jensen-Shannon divergence between probability distributions"},
458
+
459
+ // Conventional `cdist` and `pdist` insterfaces with third string argument, and optional `threads` arg
460
+ {"cdist", api_cdist, METH_VARARGS | METH_KEYWORDS,
461
+ "Compute distance between each pair of the two collections of inputs"},
462
+
463
+ // Exposing underlying API for USearch
464
+ {"pointer_to_sqeuclidean", api_l2sq_pointer, METH_VARARGS, "L2sq (Sq. Euclidean) function pointer as `int`"},
465
+ {"pointer_to_cosine", api_cos_pointer, METH_VARARGS, "Cosine (Angular) function pointer as `int`"},
466
+ {"pointer_to_inner", api_ip_pointer, METH_VARARGS, "Inner (Dot) Product function pointer as `int`"},
467
+ {"pointer_to_kullbackleibler", api_ip_pointer, METH_VARARGS, "Kullback-Leibler function pointer as `int`"},
468
+ {"pointer_to_jensenshannon", api_ip_pointer, METH_VARARGS, "Jensen-Shannon function pointer as `int`"},
469
+
470
+ // Sentinel
471
+ {NULL, NULL, 0, NULL}};
472
+
473
+ static PyModuleDef simsimd_module = {
474
+ PyModuleDef_HEAD_INIT,
475
+ .m_name = "SimSIMD",
476
+ .m_doc = "Vector Similarity Functions 3x-200x Faster than SciPy and NumPy",
477
+ .m_size = -1,
478
+ .m_methods = simsimd_methods,
479
+ };
480
+
481
+ PyMODINIT_FUNC PyInit_simsimd(void) {
482
+ _import_array();
483
+ PyObject* module = PyModule_Create(&simsimd_module);
484
+
485
+ // Open the VERSION file to add the `simsimd.__version__` attribute
486
+ if (module)
487
+ PyModule_AddStringConstant(module, "__version__", "2.1.1");
108
488
 
109
- return m;
489
+ static_capabilities = simsimd_capabilities();
490
+ return module;
110
491
  }