Skip to content
Navigation Menu
{{ message }}
forked from ashvardanian/NumKong
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.c
More file actions
2086 lines (1873 loc) · 99.9 KB
/
Copy pathlib.c
File metadata and controls
2086 lines (1873 loc) · 99.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @brief Pure CPython bindings for SimSIMD.
* @file lib.c
* @author Ash Vardanian
* @date January 1, 2023
* @copyright Copyright (c) 2023
*
* @section Latency, Quality, and Arguments Parsing
*
* The complexity of implementing high-quality CPython bindings is often underestimated.
* You can't use high-level wrappers like PyBind11 and NanoBind, and you shouldn't use
* SWIG-like messy toolchains. Most of them use expensive dynamic data-structures to map
* your callbacks to object/module properties, not taking advantage of the CPython API.
* They are prohibitively slow for low-latency operations like checking the length of a
* container, handling vectors, or strings.
*
* Once you are down to the CPython API, there is a lot of boilerplate code to write and
* it's understandable that most people lazily use the `PyArg_ParseTupleAndKeywords` and
* `PyArg_ParseTuple` functions. Those, however, need to dynamically parse format specifier
* strings at runtime, which @b can't be fast by design! Moreover, they are not suitable
* for the Python's "Fast Calling Convention". In a typical scenario, a function is defined
* with `METH_VARARGS | METH_KEYWORDS` and has a signature like:
*
* @code {.c}
* static PyObject* cdist(
* PyObject * self,
* PyObject * positional_args_tuple,
* PyObject * named_args_dict) {
* PyObject * a_obj, b_obj, metric_obj, out_obj, dtype_obj, out_dtype_obj, threads_obj;
* static char* names[] = {"a", "b", "metric", "threads", "dtype", "out_dtype", NULL};
* if (!PyArg_ParseTupleAndKeywords(
* positional_args_tuple, named_args_dict, "OO|s$Kss", names,
* &a_obj, &b_obj, &metric_str, &threads, &dtype_str, &out_dtype_str))
* return NULL;
* ...
* @endcode
*
* This `cdist` example takes 2 positional, 1 postional or named, 3 named-only arguments.
* The alternative using the `METH_FASTCALL` is to use a function signature like:
*
* @code {.c}
* static PyObject* cdist(
* PyObject * self,
* PyObject * const * args_c_array, //! C array of `args_count` pointers
* Py_ssize_t const positional_args_count, //! The `args_c_array` may be larger than this
* PyObject * args_names_tuple) { //! May be smaller than `args_count`
* Py_ssize_t args_names_count = args_names_tuple ? PyTuple_Size(args_names_tuple) : 0;
* Py_ssize_t args_count = positional_args_count + args_names_count;
* ...
* @endcode
*
* The positional elements are easy to access in that C array, but parsing the named arguments is tricky.
* There may be a case, when the call is ill-formed and more positional arguments are provided than needed.
*
* @code {.py}
* cdist(a, b, "cos", "dos"): //! positional_args_count == 4, args_names_count == 0
* cdist(a, b, "cos", metric="dos"): //! positional_args_count == 3, args_names_count == 1
* cdist(a, b, metric="cos", metric="dos"): //! positional_args_count == 2, args_names_count == 2
* @endcode
*
* If the same argument is provided twice, a @b `TypeError` is raised.
* If the argument is not found, a @b `KeyError` is raised.
*
* https://ashvardanian.com/posts/discount-on-keyword-arguments-in-python/
*
* @section Buffer Protocol and NumPy Compatibility
*
* Most modern Machine Learning frameworks struggle with the buffer protocol compatibility.
* At best, they provide zero-copy NumPy views of the underlying data, introducing unnecessary
* dependency on NumPy, a memory allocation for the wrapper, and a constraint on the supported
* numeric types. The last is a noticeable limitation, as both PyTorch and TensorFlow have
* richer type systems than NumPy.
*
* You can't convert a PyTorch `Tensor` to a `memoryview` object.
* If you try to convert a `bf16` TensorFlow `Tensor` to a `memoryview` object, you will get an error:
*
* ! ValueError: cannot include dtype 'E' in a buffer
*
* Moreover, the CPython documentation and the NumPy documentation diverge on the format specificers
* for the `typestr` and `format` data-type descriptor strings, making the development error-prone.
* At this point, SimSIMD seems to be @b the_only_package that at least attempts to provide interoperability.
*
* https://numpy.org/doc/stable/reference/arrays.interface.html
* https://pearu.github.io/array_interface_pytorch.html
* https://github.com/pytorch/pytorch/issues/54138
* https://github.com/pybind/pybind11/issues/1908
*/
#include <math.h>
#if defined(__linux__)
#ifdef _OPENMP
#include <omp.h>
#endif
#endif
#include <simsimd/simsimd.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
typedef struct TensorArgument {
char *start;
size_t dimensions;
size_t count;
size_t stride;
int rank;
simsimd_datatype_t datatype;
} TensorArgument;
typedef struct DistancesTensor {
PyObject_HEAD //
simsimd_datatype_t datatype; // Double precision real or complex numbers
size_t dimensions; // Can be only 1 or 2 dimensions
Py_ssize_t shape[2]; // Dimensions of the tensor
Py_ssize_t strides[2]; // Strides for each dimension
simsimd_distance_t start[]; // Variable length data aligned to 64-bit scalars
} DistancesTensor;
static int DistancesTensor_getbuffer(PyObject *export_from, Py_buffer *view, int flags);
static void DistancesTensor_releasebuffer(PyObject *export_from, Py_buffer *view);
static PyBufferProcs DistancesTensor_as_buffer = {
.bf_getbuffer = DistancesTensor_getbuffer,
.bf_releasebuffer = DistancesTensor_releasebuffer,
};
static PyTypeObject DistancesTensorType = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "simsimd.DistancesTensor",
.tp_doc = "Zero-copy view of an internal tensor, compatible with NumPy",
.tp_basicsize = sizeof(DistancesTensor),
// Instead of using `simsimd_distance_t` for all the elements,
// we use `char` to allow user to specify the datatype on `cdist`-like functions.
.tp_itemsize = sizeof(char),
.tp_as_buffer = &DistancesTensor_as_buffer,
};
/// @brief Global variable that caches the CPU capabilities, and is computed just onc, when the module is loaded.
simsimd_capability_t static_capabilities = simsimd_cap_serial_k;
/// @brief Helper method to check for string equality.
/// @return 1 if the strings are equal, 0 otherwise.
int same_string(char const *a, char const *b) { return strcmp(a, b) == 0; }
/// @brief Helper method to check if a logical datatype is complex and should be represented as two scalars.
/// @return 1 if the datatype is complex, 0 otherwise.
int is_complex(simsimd_datatype_t datatype) {
return datatype == simsimd_datatype_f32c_k || datatype == simsimd_datatype_f64c_k ||
datatype == simsimd_datatype_f16c_k || datatype == simsimd_datatype_bf16c_k;
}
/// @brief Converts a Python-ic datatype string to a logical datatype, normalizing the format.
/// @return `simsimd_datatype_unknown_k` if the datatype is not supported, otherwise the logical datatype.
/// @see https://docs.python.org/3/library/struct.html#format-characters
/// @see https://numpy.org/doc/stable/reference/arrays.interface.html
/// @see https://github.com/pybind/pybind11/issues/1908
simsimd_datatype_t python_string_to_datatype(char const *name) {
// Floating-point numbers:
if (same_string(name, "float32") || same_string(name, "f32") || // SimSIMD-specific
same_string(name, "f4") || same_string(name, "<f4") || // Sized float
same_string(name, "f") || same_string(name, "<f")) // Named type
return simsimd_datatype_f32_k;
else if (same_string(name, "float16") || same_string(name, "f16") || // SimSIMD-specific
same_string(name, "f2") || same_string(name, "<f2") || // Sized float
same_string(name, "e") || same_string(name, "<e")) // Named type
return simsimd_datatype_f16_k;
else if (same_string(name, "float64") || same_string(name, "f64") || // SimSIMD-specific
same_string(name, "f8") || same_string(name, "<f8") || // Sized float
same_string(name, "d") || same_string(name, "<d")) // Named type
return simsimd_datatype_f64_k;
//? The exact format is not defined, but TensorFlow uses 'E' for `bf16`?!
else if (same_string(name, "bfloat16") || same_string(name, "bf16")) // SimSIMD-specific
return simsimd_datatype_bf16_k;
// Complex numbers:
else if (same_string(name, "complex64") || // SimSIMD-specific
same_string(name, "F4") || same_string(name, "<F4") || // Sized complex
same_string(name, "Zf") || same_string(name, "F") || same_string(name, "<F")) // Named type
return simsimd_datatype_f32c_k;
else if (same_string(name, "complex128") || // SimSIMD-specific
same_string(name, "F8") || same_string(name, "<F8") || // Sized complex
same_string(name, "Zd") || same_string(name, "D") || same_string(name, "<D")) // Named type
return simsimd_datatype_f64c_k;
else if (same_string(name, "complex32") || // SimSIMD-specific
same_string(name, "F2") || same_string(name, "<F2") || // Sized complex
same_string(name, "Ze") || same_string(name, "E") || same_string(name, "<E")) // Named type
return simsimd_datatype_f16c_k;
//? The exact format is not defined, but TensorFlow uses 'E' for `bf16`?!
else if (same_string(name, "bcomplex32")) // SimSIMD-specific
return simsimd_datatype_bf16c_k;
//! Boolean values:
else if (same_string(name, "bin8") || // SimSIMD-specific
same_string(name, "?")) // Named type
return simsimd_datatype_b8_k;
// Signed integers:
else if (same_string(name, "int8") || // SimSIMD-specific
same_string(name, "i1") || same_string(name, "|i1") || same_string(name, "<i1") || // Sized integer
same_string(name, "b") || same_string(name, "<b")) // Named type
return simsimd_datatype_i8_k;
else if (same_string(name, "int16") || // SimSIMD-specific
same_string(name, "i2") || same_string(name, "|i2") || same_string(name, "<i2") || // Sized integer
same_string(name, "h") || same_string(name, "<h")) // Named type
return simsimd_datatype_i16_k;
//! On Windows the 32-bit and 64-bit signed integers will have different specifiers:
//! https://github.com/pybind/pybind11/issues/1908
#if defined(_MSC_VER) || defined(__i386__)
else if (same_string(name, "int32") || // SimSIMD-specific
same_string(name, "i4") || same_string(name, "|i4") || same_string(name, "<i4") || // Sized integer
same_string(name, "l") || same_string(name, "<l")) // Named type
return simsimd_datatype_i32_k;
else if (same_string(name, "int64") || // SimSIMD-specific
same_string(name, "i8") || same_string(name, "|i8") || same_string(name, "<i8") || // Sized integer
same_string(name, "q") || same_string(name, "<q")) // Named type
return simsimd_datatype_i64_k;
#else // On Linux and macOS:
else if (same_string(name, "int32") || // SimSIMD-specific
same_string(name, "i4") || same_string(name, "|i4") || same_string(name, "<i4") || // Sized integer
same_string(name, "i") || same_string(name, "<i")) // Named type
return simsimd_datatype_i32_k;
else if (same_string(name, "int64") || // SimSIMD-specific
same_string(name, "i8") || same_string(name, "|i8") || same_string(name, "<i8") || // Sized integer
same_string(name, "l") || same_string(name, "<l")) // Named type
return simsimd_datatype_i64_k;
#endif
// Unsigned integers:
else if (same_string(name, "uint8") || // SimSIMD-specific
same_string(name, "u1") || same_string(name, "|u1") || same_string(name, "<u1") || // Sized integer
same_string(name, "B") || same_string(name, "<B")) // Named type
return simsimd_datatype_u8_k;
else if (same_string(name, "uint16") || // SimSIMD-specific
same_string(name, "u2") || same_string(name, "|u2") || same_string(name, "<u2") || // Sized integer
same_string(name, "H") || same_string(name, "<H")) // Named type
return simsimd_datatype_u16_k;
//! On Windows the 32-bit and 64-bit unsigned integers will have different specifiers:
//! https://github.com/pybind/pybind11/issues/1908
#if defined(_MSC_VER) || defined(__i386__)
else if (same_string(name, "uint32") || // SimSIMD-specific
same_string(name, "i4") || same_string(name, "|i4") || same_string(name, "<i4") || // Sized integer
same_string(name, "L") || same_string(name, "<L")) // Named type
return simsimd_datatype_u32_k;
else if (same_string(name, "uint64") || // SimSIMD-specific
same_string(name, "i8") || same_string(name, "|i8") || same_string(name, "<i8") || // Sized integer
same_string(name, "Q") || same_string(name, "<Q")) // Named type
return simsimd_datatype_u64_k;
#else // On Linux and macOS:
else if (same_string(name, "uint32") || // SimSIMD-specific
same_string(name, "u4") || same_string(name, "|u4") || same_string(name, "<u4") || // Sized integer
same_string(name, "I") || same_string(name, "<I")) // Named type
return simsimd_datatype_u32_k;
else if (same_string(name, "uint64") || // SimSIMD-specific
same_string(name, "u8") || same_string(name, "|u8") || same_string(name, "<u8") || // Sized integer
same_string(name, "L") || same_string(name, "<L")) // Named type
return simsimd_datatype_u64_k;
#endif
else
return simsimd_datatype_unknown_k;
}
/// @brief Returns the Python string representation of a datatype for the buffer protocol.
/// @param dtype Logical datatype, can be complex.
/// @return "unknown" if the datatype is not supported, otherwise a string.
/// @see https://docs.python.org/3/library/struct.html#format-characters
char const *datatype_to_python_string(simsimd_datatype_t dtype) {
switch (dtype) {
// Floating-point numbers:
case simsimd_datatype_f64_k: return "d";
case simsimd_datatype_f32_k: return "f";
case simsimd_datatype_f16_k: return "e";
// Complex numbers:
case simsimd_datatype_f64c_k: return "Zd";
case simsimd_datatype_f32c_k: return "Zf";
case simsimd_datatype_f16c_k: return "Ze";
// Boolean values:
case simsimd_datatype_b8_k: return "?";
// Signed integers:
case simsimd_datatype_i8_k: return "b";
case simsimd_datatype_i16_k: return "h";
case simsimd_datatype_i32_k: return "i";
case simsimd_datatype_i64_k: return "q";
// Unsigned integers:
case simsimd_datatype_u8_k: return "B";
case simsimd_datatype_u16_k: return "H";
case simsimd_datatype_u32_k: return "I";
case simsimd_datatype_u64_k: return "Q";
// Other:
default: return "unknown";
}
}
/// @brief Estimate the number of bytes per element for a given datatype.
/// @param dtype Logical datatype, can be complex.
/// @return Zero if the datatype is not supported, positive integer otherwise.
size_t bytes_per_datatype(simsimd_datatype_t dtype) {
switch (dtype) {
case simsimd_datatype_f64_k: return sizeof(simsimd_f64_t);
case simsimd_datatype_f32_k: return sizeof(simsimd_f32_t);
case simsimd_datatype_f16_k: return sizeof(simsimd_f16_t);
case simsimd_datatype_bf16_k: return sizeof(simsimd_bf16_t);
case simsimd_datatype_f64c_k: return sizeof(simsimd_f64_t) * 2;
case simsimd_datatype_f32c_k: return sizeof(simsimd_f32_t) * 2;
case simsimd_datatype_f16c_k: return sizeof(simsimd_f16_t) * 2;
case simsimd_datatype_bf16c_k: return sizeof(simsimd_bf16_t) * 2;
case simsimd_datatype_b8_k: return sizeof(simsimd_b8_t);
case simsimd_datatype_i8_k: return sizeof(simsimd_i8_t);
case simsimd_datatype_u8_k: return sizeof(simsimd_u8_t);
case simsimd_datatype_i16_k: return sizeof(simsimd_i16_t);
case simsimd_datatype_u16_k: return sizeof(simsimd_u16_t);
case simsimd_datatype_i32_k: return sizeof(simsimd_i32_t);
case simsimd_datatype_u32_k: return sizeof(simsimd_u32_t);
case simsimd_datatype_i64_k: return sizeof(simsimd_i64_t);
case simsimd_datatype_u64_k: return sizeof(simsimd_u64_t);
default: return 0;
}
}
/// @brief Copy a distance to a target datatype, downcasting if necessary.
/// @return 1 if the cast was successful, 0 if the target datatype is not supported.
int cast_distance(simsimd_distance_t distance, simsimd_datatype_t target_dtype, void *target_ptr, size_t offset) {
switch (target_dtype) {
case simsimd_datatype_f64c_k: ((simsimd_f64_t *)target_ptr)[offset] = (simsimd_f64_t)distance; return 1;
case simsimd_datatype_f64_k: ((simsimd_f64_t *)target_ptr)[offset] = (simsimd_f64_t)distance; return 1;
case simsimd_datatype_f32c_k: ((simsimd_f32_t *)target_ptr)[offset] = (simsimd_f32_t)distance; return 1;
case simsimd_datatype_f32_k: ((simsimd_f32_t *)target_ptr)[offset] = (simsimd_f32_t)distance; return 1;
case simsimd_datatype_f16c_k: simsimd_f32_to_f16(distance, (simsimd_f16_t *)target_ptr + offset); return 1;
case simsimd_datatype_f16_k: simsimd_f32_to_f16(distance, (simsimd_f16_t *)target_ptr + offset); return 1;
case simsimd_datatype_bf16c_k: simsimd_f32_to_bf16(distance, (simsimd_bf16_t *)target_ptr + offset); return 1;
case simsimd_datatype_bf16_k: simsimd_f32_to_bf16(distance, (simsimd_bf16_t *)target_ptr + offset); return 1;
case simsimd_datatype_i8_k: ((simsimd_i8_t *)target_ptr)[offset] = (simsimd_i8_t)distance; return 1;
case simsimd_datatype_u8_k: ((simsimd_u8_t *)target_ptr)[offset] = (simsimd_u8_t)distance; return 1;
case simsimd_datatype_i16_k: ((simsimd_i16_t *)target_ptr)[offset] = (simsimd_i16_t)distance; return 1;
case simsimd_datatype_u16_k: ((simsimd_u16_t *)target_ptr)[offset] = (simsimd_u16_t)distance; return 1;
case simsimd_datatype_i32_k: ((simsimd_i32_t *)target_ptr)[offset] = (simsimd_i32_t)distance; return 1;
case simsimd_datatype_u32_k: ((simsimd_u32_t *)target_ptr)[offset] = (simsimd_u32_t)distance; return 1;
case simsimd_datatype_i64_k: ((simsimd_i64_t *)target_ptr)[offset] = (simsimd_i64_t)distance; return 1;
case simsimd_datatype_u64_k: ((simsimd_u64_t *)target_ptr)[offset] = (simsimd_u64_t)distance; return 1;
default: return 0;
}
}
simsimd_metric_kind_t python_string_to_metric_kind(char const *name) {
if (same_string(name, "euclidean") || same_string(name, "l2")) return simsimd_metric_euclidean_k;
else if (same_string(name, "sqeuclidean") || same_string(name, "l2sq"))
return simsimd_metric_sqeuclidean_k;
else if (same_string(name, "dot") || same_string(name, "inner"))
return simsimd_metric_dot_k;
else if (same_string(name, "vdot"))
return simsimd_metric_vdot_k;
else if (same_string(name, "cosine") || same_string(name, "cos"))
return simsimd_metric_cosine_k;
else if (same_string(name, "jaccard"))
return simsimd_metric_jaccard_k;
else if (same_string(name, "kullbackleibler") || same_string(name, "kl"))
return simsimd_metric_kl_k;
else if (same_string(name, "jensenshannon") || same_string(name, "js"))
return simsimd_metric_js_k;
else if (same_string(name, "hamming"))
return simsimd_metric_hamming_k;
else if (same_string(name, "jaccard"))
return simsimd_metric_jaccard_k;
else if (same_string(name, "bilinear"))
return simsimd_metric_bilinear_k;
else if (same_string(name, "mahalanobis"))
return simsimd_metric_mahalanobis_k;
else
return simsimd_metric_unknown_k;
}
/// @brief Check if a metric is commutative, i.e., if `metric(a, b) == metric(b, a)`.
/// @return 1 if the metric is commutative, 0 otherwise.
int kernel_is_commutative(simsimd_metric_kind_t kind) {
switch (kind) {
case simsimd_metric_kl_k: return 0;
case simsimd_metric_bilinear_k: return 0; //? The kernel is commutative if only the matrix is symmetric
default: return 1;
}
}
static char const doc_enable_capability[] = //
"Enable a specific SIMD kernel family.\n\n"
"Args:\n"
" capability (str): The name of the SIMD feature to enable (e.g., 'haswell').";
static PyObject *api_enable_capability(PyObject *self, PyObject *cap_name_obj) {
char const *cap_name = PyUnicode_AsUTF8(cap_name_obj);
if (!cap_name) {
PyErr_SetString(PyExc_TypeError, "Capability name must be a string");
return NULL;
}
if (same_string(cap_name, "neon")) { static_capabilities |= simsimd_cap_neon_k; }
else if (same_string(cap_name, "neon_f16")) { static_capabilities |= simsimd_cap_neon_f16_k; }
else if (same_string(cap_name, "neon_bf16")) { static_capabilities |= simsimd_cap_neon_bf16_k; }
else if (same_string(cap_name, "neon_i8")) { static_capabilities |= simsimd_cap_neon_i8_k; }
else if (same_string(cap_name, "sve")) { static_capabilities |= simsimd_cap_sve_k; }
else if (same_string(cap_name, "sve_f16")) { static_capabilities |= simsimd_cap_sve_f16_k; }
else if (same_string(cap_name, "sve_bf16")) { static_capabilities |= simsimd_cap_sve_bf16_k; }
else if (same_string(cap_name, "sve_i8")) { static_capabilities |= simsimd_cap_sve_i8_k; }
else if (same_string(cap_name, "haswell")) { static_capabilities |= simsimd_cap_haswell_k; }
else if (same_string(cap_name, "skylake")) { static_capabilities |= simsimd_cap_skylake_k; }
else if (same_string(cap_name, "ice")) { static_capabilities |= simsimd_cap_ice_k; }
else if (same_string(cap_name, "genoa")) { static_capabilities |= simsimd_cap_genoa_k; }
else if (same_string(cap_name, "sapphire")) { static_capabilities |= simsimd_cap_sapphire_k; }
else if (same_string(cap_name, "turin")) { static_capabilities |= simsimd_cap_turin_k; }
else if (same_string(cap_name, "sierra")) { static_capabilities |= simsimd_cap_sierra_k; }
else if (same_string(cap_name, "serial")) {
PyErr_SetString(PyExc_ValueError, "Can't change the serial functionality");
return NULL;
}
else {
PyErr_SetString(PyExc_ValueError, "Unknown capability");
return NULL;
}
Py_RETURN_NONE;
}
static char const doc_disable_capability[] = //
"Disable a specific SIMD kernel family.\n\n"
"Args:\n"
" capability (str): The name of the SIMD feature to disable (e.g., 'haswell').";
static PyObject *api_disable_capability(PyObject *self, PyObject *cap_name_obj) {
char const *cap_name = PyUnicode_AsUTF8(cap_name_obj);
if (!cap_name) {
PyErr_SetString(PyExc_TypeError, "Capability name must be a string");
return NULL;
}
if (same_string(cap_name, "neon")) { static_capabilities &= ~simsimd_cap_neon_k; }
else if (same_string(cap_name, "neon_f16")) { static_capabilities &= ~simsimd_cap_neon_f16_k; }
else if (same_string(cap_name, "neon_bf16")) { static_capabilities &= ~simsimd_cap_neon_bf16_k; }
else if (same_string(cap_name, "neon_i8")) { static_capabilities &= ~simsimd_cap_neon_i8_k; }
else if (same_string(cap_name, "sve")) { static_capabilities &= ~simsimd_cap_sve_k; }
else if (same_string(cap_name, "sve_f16")) { static_capabilities &= ~simsimd_cap_sve_f16_k; }
else if (same_string(cap_name, "sve_bf16")) { static_capabilities &= ~simsimd_cap_sve_bf16_k; }
else if (same_string(cap_name, "sve_i8")) { static_capabilities &= ~simsimd_cap_sve_i8_k; }
else if (same_string(cap_name, "haswell")) { static_capabilities &= ~simsimd_cap_haswell_k; }
else if (same_string(cap_name, "skylake")) { static_capabilities &= ~simsimd_cap_skylake_k; }
else if (same_string(cap_name, "ice")) { static_capabilities &= ~simsimd_cap_ice_k; }
else if (same_string(cap_name, "genoa")) { static_capabilities &= ~simsimd_cap_genoa_k; }
else if (same_string(cap_name, "sapphire")) { static_capabilities &= ~simsimd_cap_sapphire_k; }
else if (same_string(cap_name, "turin")) { static_capabilities &= ~simsimd_cap_turin_k; }
else if (same_string(cap_name, "sierra")) { static_capabilities &= ~simsimd_cap_sierra_k; }
else if (same_string(cap_name, "serial")) {
PyErr_SetString(PyExc_ValueError, "Can't change the serial functionality");
return NULL;
}
else {
PyErr_SetString(PyExc_ValueError, "Unknown capability");
return NULL;
}
Py_RETURN_NONE;
}
static char const doc_get_capabilities[] = //
"Get the current hardware SIMD capabilities as a dictionary of feature flags.\n"
"On x86 includes: 'serial', 'haswell', 'skylake', 'ice', 'genoa', 'sapphire', 'turin'.\n"
"On Arm includes: 'serial', 'neon', 'sve', 'sve2', and their extensions.\n";
static PyObject *api_get_capabilities(PyObject *self) {
simsimd_capability_t caps = static_capabilities;
PyObject *cap_dict = PyDict_New();
if (!cap_dict) return NULL;
#define ADD_CAP(name) PyDict_SetItemString(cap_dict, #name, PyBool_FromLong((caps) & simsimd_cap_##name##_k))
ADD_CAP(serial);
ADD_CAP(neon);
ADD_CAP(sve);
ADD_CAP(neon_f16);
ADD_CAP(sve_f16);
ADD_CAP(neon_bf16);
ADD_CAP(sve_bf16);
ADD_CAP(neon_i8);
ADD_CAP(sve_i8);
ADD_CAP(haswell);
ADD_CAP(skylake);
ADD_CAP(ice);
ADD_CAP(genoa);
ADD_CAP(sapphire);
ADD_CAP(turin);
ADD_CAP(sierra);
#undef ADD_CAP
return cap_dict;
}
/// @brief Unpacks a Python tensor object into a C structure.
/// @return 1 on success, 0 otherwise.
int parse_tensor(PyObject *tensor, Py_buffer *buffer, TensorArgument *parsed) {
if (PyObject_GetBuffer(tensor, buffer, PyBUF_STRIDES | PyBUF_FORMAT) != 0) {
PyErr_SetString(PyExc_TypeError, "arguments must support buffer protocol");
return 0;
}
// In case you are debugging some new obscure format string :)
// printf("buffer format is %s\n", buffer->format);
// printf("buffer ndim is %d\n", buffer->ndim);
// printf("buffer shape is %d\n", buffer->shape[0]);
// printf("buffer shape is %d\n", buffer->shape[1]);
// printf("buffer itemsize is %d\n", buffer->itemsize);
parsed->start = buffer->buf;
parsed->datatype = python_string_to_datatype(buffer->format);
if (parsed->datatype == simsimd_datatype_unknown_k) {
PyErr_Format(PyExc_ValueError, "Unsupported '%s' datatype specifier", buffer->format);
PyBuffer_Release(buffer);
return 0;
}
parsed->rank = buffer->ndim;
if (buffer->ndim == 1) {
if (buffer->strides[0] > buffer->itemsize) {
PyErr_SetString(PyExc_ValueError, "Input vectors must be contiguous, check with `X.__array_interface__`");
PyBuffer_Release(buffer);
return 0;
}
parsed->dimensions = buffer->shape[0];
parsed->count = 1;
parsed->stride = 0;
}
else if (buffer->ndim == 2) {
if (buffer->strides[1] > buffer->itemsize) {
PyErr_SetString(PyExc_ValueError, "Input vectors must be contiguous, check with `X.__array_interface__`");
PyBuffer_Release(buffer);
return 0;
}
parsed->dimensions = buffer->shape[1];
parsed->count = buffer->shape[0];
parsed->stride = buffer->strides[0];
}
else {
PyErr_SetString(PyExc_ValueError, "Input tensors must be 1D or 2D");
PyBuffer_Release(buffer);
return 0;
}
return 1;
}
static int DistancesTensor_getbuffer(PyObject *export_from, Py_buffer *view, int flags) {
DistancesTensor *tensor = (DistancesTensor *)export_from;
size_t const total_items = tensor->shape[0] * tensor->shape[1];
size_t const item_size = bytes_per_datatype(tensor->datatype);
view->buf = &tensor->start[0];
view->obj = (PyObject *)tensor;
view->len = item_size * total_items;
view->readonly = 0;
view->itemsize = (Py_ssize_t)item_size;
view->format = datatype_to_python_string(tensor->datatype);
view->ndim = (int)tensor->dimensions;
view->shape = &tensor->shape[0];
view->strides = &tensor->strides[0];
view->suboffsets = NULL;
view->internal = NULL;
Py_INCREF(tensor);
return 0;
}
static void DistancesTensor_releasebuffer(PyObject *export_from, Py_buffer *view) {
// This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release().
// https://docs.python.org/3/c-api/typeobj.html#c.PyBufferProcs.bf_releasebuffer
}
static PyObject *implement_dense_metric( //
simsimd_metric_kind_t metric_kind, //
PyObject *const *args, Py_ssize_t const positional_args_count, PyObject *args_names_tuple) {
PyObject *return_obj = NULL;
// This function accepts up to 5 arguments:
PyObject *a_obj = NULL; // Required object, positional-only
PyObject *b_obj = NULL; // Required object, positional-only
PyObject *dtype_obj = NULL; // Optional object, "dtype" keyword or positional
PyObject *out_obj = NULL; // Optional object, "out" keyword-only
PyObject *out_dtype_obj = NULL; // Optional object, "out_dtype" keyword-only
// Once parsed, the arguments will be stored in these variables:
char const *dtype_str = NULL, *out_dtype_str = NULL;
simsimd_datatype_t dtype = simsimd_datatype_unknown_k, out_dtype = simsimd_datatype_unknown_k;
Py_buffer a_buffer, b_buffer, out_buffer;
TensorArgument a_parsed, b_parsed, out_parsed;
memset(&a_buffer, 0, sizeof(Py_buffer));
memset(&b_buffer, 0, sizeof(Py_buffer));
memset(&out_buffer, 0, sizeof(Py_buffer));
// Parse the arguments
Py_ssize_t const args_names_count = args_names_tuple ? PyTuple_Size(args_names_tuple) : 0;
Py_ssize_t const args_count = positional_args_count + args_names_count;
if (args_count < 2 || args_count > 5) {
PyErr_Format(PyExc_TypeError, "Function expects 2-5 arguments, got %zd", args_count);
return NULL;
}
if (positional_args_count > 3) {
PyErr_Format(PyExc_TypeError, "Only first 3 arguments can be positional, received %zd", positional_args_count);
return NULL;
}
// Positional-only arguments (first and second matrix)
a_obj = args[0];
b_obj = args[1];
// Positional or keyword arguments (dtype)
if (positional_args_count == 3) dtype_obj = args[2];
// The rest of the arguments must be checked in the keyword dictionary:
for (Py_ssize_t args_names_tuple_progress = 0, args_progress = positional_args_count;
args_names_tuple_progress < args_names_count; ++args_progress, ++args_names_tuple_progress) {
PyObject *const key = PyTuple_GetItem(args_names_tuple, args_names_tuple_progress);
PyObject *const value = args[args_progress];
if (PyUnicode_CompareWithASCIIString(key, "dtype") == 0 && !dtype_obj) { dtype_obj = value; }
else if (PyUnicode_CompareWithASCIIString(key, "out") == 0 && !out_obj) { out_obj = value; }
else if (PyUnicode_CompareWithASCIIString(key, "out_dtype") == 0 && !out_dtype_obj) { out_dtype_obj = value; }
else {
PyErr_Format(PyExc_TypeError, "Got unexpected keyword argument: %S", key);
return NULL;
}
}
// Convert `dtype_obj` to `dtype_str` and to `dtype`
if (dtype_obj) {
dtype_str = PyUnicode_AsUTF8(dtype_obj);
if (!dtype_str && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Expected 'dtype' to be a string");
return NULL;
}
dtype = python_string_to_datatype(dtype_str);
if (dtype == simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_ValueError, "Unsupported 'dtype'");
return NULL;
}
}
// Convert `out_dtype_obj` to `out_dtype_str` and to `out_dtype`
if (out_dtype_obj) {
out_dtype_str = PyUnicode_AsUTF8(out_dtype_obj);
if (!out_dtype_str && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Expected 'out_dtype' to be a string");
return NULL;
}
out_dtype = python_string_to_datatype(out_dtype_str);
if (out_dtype == simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_ValueError, "Unsupported 'out_dtype'");
return NULL;
}
}
// Convert `a_obj` to `a_buffer` and to `a_parsed`. Same for `b_obj` and `out_obj`.
if (!parse_tensor(a_obj, &a_buffer, &a_parsed) || !parse_tensor(b_obj, &b_buffer, &b_parsed)) return NULL;
if (out_obj && !parse_tensor(out_obj, &out_buffer, &out_parsed)) return NULL;
// Check dimensions
if (a_parsed.dimensions != b_parsed.dimensions) {
PyErr_SetString(PyExc_ValueError, "Vector dimensions don't match");
goto cleanup;
}
if (a_parsed.count == 0 || b_parsed.count == 0) {
PyErr_SetString(PyExc_ValueError, "Collections can't be empty");
goto cleanup;
}
if (a_parsed.count > 1 && b_parsed.count > 1 && a_parsed.count != b_parsed.count) {
PyErr_SetString(PyExc_ValueError, "Collections must have the same number of elements or just one element");
goto cleanup;
}
// Check data types
if (a_parsed.datatype != b_parsed.datatype || //
a_parsed.datatype == simsimd_datatype_unknown_k || b_parsed.datatype == simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_TypeError,
"Input tensors must have matching datatypes, check with `X.__array_interface__`");
goto cleanup;
}
if (dtype == simsimd_datatype_unknown_k) dtype = a_parsed.datatype;
// Inference order for the output type:
// 1. `out_dtype` named argument, if defined
// 2. `out.dtype` attribute, if `out` is passed
// 3. double precision float (or its complex variant)
if (out_dtype == simsimd_datatype_unknown_k) {
if (out_obj) { out_dtype = out_parsed.datatype; }
else { out_dtype = is_complex(dtype) ? simsimd_datatype_f64c_k : simsimd_datatype_f64_k; }
}
// Make sure the return datatype is complex if the input datatype is complex, and the same for real numbers
if (out_dtype != simsimd_datatype_unknown_k) {
if (is_complex(dtype) != is_complex(out_dtype)) {
PyErr_SetString(
PyExc_ValueError,
"If the input datatype is complex, the return datatype must be complex, and same for real.");
goto cleanup;
}
}
// Check if the downcasting to provided datatype is supported
{
char returned_buffer_example[8];
if (!cast_distance(0, out_dtype, &returned_buffer_example, 0)) {
PyErr_SetString(PyExc_ValueError, "Exporting to the provided datatype is not supported");
goto cleanup;
}
}
// Look up the metric and the capability
simsimd_metric_dense_punned_t metric = NULL;
simsimd_capability_t capability = simsimd_cap_serial_k;
simsimd_find_kernel_punned(metric_kind, dtype, static_capabilities, simsimd_cap_any_k,
(simsimd_kernel_punned_t *)&metric, &capability);
if (!metric) {
PyErr_Format( //
PyExc_LookupError,
"Unsupported metric '%c' and datatype combination across vectors ('%s'/'%s' and '%s'/'%s') and "
"`dtype` override ('%s'/'%s')",
metric_kind, //
a_buffer.format ? a_buffer.format : "nil", datatype_to_python_string(a_parsed.datatype), //
b_buffer.format ? b_buffer.format : "nil", datatype_to_python_string(b_parsed.datatype), //
dtype_str ? dtype_str : "nil", datatype_to_python_string(dtype));
goto cleanup;
}
// If the distance is computed between two vectors, rather than matrices, return a scalar
int const dtype_is_complex = is_complex(dtype);
if (a_parsed.rank == 1 && b_parsed.rank == 1) {
simsimd_distance_t distances[2];
metric(a_parsed.start, b_parsed.start, a_parsed.dimensions, distances);
return_obj = //
dtype_is_complex //
? PyComplex_FromDoubles(distances[0], distances[1])
: PyFloat_FromDouble(distances[0]);
goto cleanup;
}
// In some batch requests we may be computing the distance from multiple vectors to one,
// so the stride must be set to zero avoid illegal memory access
if (a_parsed.count == 1) a_parsed.stride = 0;
if (b_parsed.count == 1) b_parsed.stride = 0;
// We take the maximum of the two counts, because if only one entry is present in one of the arrays,
// all distances will be computed against that single entry.
size_t const count_pairs = a_parsed.count > b_parsed.count ? a_parsed.count : b_parsed.count;
size_t const components_per_pair = dtype_is_complex ? 2 : 1;
size_t const count_components = count_pairs * components_per_pair;
char *distances_start = NULL;
size_t distances_stride_bytes = 0;
// Allocate the output matrix if it wasn't provided
if (!out_obj) {
DistancesTensor *distances_obj =
PyObject_NewVar(DistancesTensor, &DistancesTensorType, count_components * bytes_per_datatype(out_dtype));
if (!distances_obj) {
PyErr_NoMemory();
goto cleanup;
}
// Initialize the object
distances_obj->datatype = out_dtype;
distances_obj->dimensions = 1;
distances_obj->shape[0] = count_pairs;
distances_obj->shape[1] = 1;
distances_obj->strides[0] = bytes_per_datatype(out_dtype);
distances_obj->strides[1] = 0;
return_obj = (PyObject *)distances_obj;
distances_start = (char *)&distances_obj->start[0];
distances_stride_bytes = distances_obj->strides[0];
}
else {
if (bytes_per_datatype(out_parsed.datatype) != bytes_per_datatype(out_dtype)) {
PyErr_Format( //
PyExc_LookupError,
"Output tensor scalar type must be compatible with the output type ('%s' and '%s'/'%s')",
datatype_to_python_string(out_dtype), out_buffer.format ? out_buffer.format : "nil",
datatype_to_python_string(out_parsed.datatype));
goto cleanup;
}
distances_start = (char *)&out_parsed.start[0];
distances_stride_bytes = out_buffer.strides[0];
//? Logic suggests to return `None` in in-place mode...
//? SciPy decided differently.
return_obj = Py_None;
}
// Compute the distances
for (size_t i = 0; i < count_pairs; ++i) {
simsimd_distance_t result[2];
metric( //
a_parsed.start + i * a_parsed.stride, //
b_parsed.start + i * b_parsed.stride, //
a_parsed.dimensions, //
(simsimd_distance_t *)&result);
// Export out:
cast_distance(result[0], out_dtype, distances_start + i * distances_stride_bytes, 0);
if (dtype_is_complex) cast_distance(result[1], out_dtype, distances_start + i * distances_stride_bytes, 1);
}
cleanup:
PyBuffer_Release(&a_buffer);
PyBuffer_Release(&b_buffer);
PyBuffer_Release(&out_buffer);
return return_obj;
}
static PyObject *implement_curved_metric( //
simsimd_metric_kind_t metric_kind, //
PyObject *const *args, Py_ssize_t const positional_args_count, PyObject *args_names_tuple) {
PyObject *return_obj = NULL;
// This function accepts up to 6 arguments:
PyObject *a_obj = NULL; // Required object, positional-only
PyObject *b_obj = NULL; // Required object, positional-only
PyObject *c_obj = NULL; // Required object, positional-only
PyObject *dtype_obj = NULL; // Optional object, "dtype" keyword or positional
// Once parsed, the arguments will be stored in these variables:
char const *dtype_str = NULL;
simsimd_datatype_t dtype = simsimd_datatype_unknown_k;
Py_buffer a_buffer, b_buffer, c_buffer;
TensorArgument a_parsed, b_parsed, c_parsed;
memset(&a_buffer, 0, sizeof(Py_buffer));
memset(&b_buffer, 0, sizeof(Py_buffer));
memset(&c_buffer, 0, sizeof(Py_buffer));
// Parse the arguments
Py_ssize_t const args_names_count = args_names_tuple ? PyTuple_Size(args_names_tuple) : 0;
Py_ssize_t const args_count = positional_args_count + args_names_count;
if (args_count < 3 || args_count > 6) {
PyErr_Format(PyExc_TypeError, "Function expects 2-6 arguments, got %zd", args_count);
return NULL;
}
if (positional_args_count > 4) {
PyErr_Format(PyExc_TypeError, "Only first 4 arguments can be positional, received %zd", positional_args_count);
return NULL;
}
// Positional-only arguments (first, second, and third matrix)
a_obj = args[0];
b_obj = args[1];
c_obj = args[2];
// Positional or keyword arguments (dtype)
if (positional_args_count == 4) dtype_obj = args[3];
// The rest of the arguments must be checked in the keyword dictionary:
for (Py_ssize_t args_names_tuple_progress = 0, args_progress = positional_args_count;
args_names_tuple_progress < args_names_count; ++args_progress, ++args_names_tuple_progress) {
PyObject *const key = PyTuple_GetItem(args_names_tuple, args_names_tuple_progress);
PyObject *const value = args[args_progress];
if (PyUnicode_CompareWithASCIIString(key, "dtype") == 0 && !dtype_obj) { dtype_obj = value; }
else {
PyErr_Format(PyExc_TypeError, "Got unexpected keyword argument: %S", key);
return NULL;
}
}
// Convert `dtype_obj` to `dtype_str` and to `dtype`
if (dtype_obj) {
dtype_str = PyUnicode_AsUTF8(dtype_obj);
if (!dtype_str && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Expected 'dtype' to be a string");
return NULL;
}
dtype = python_string_to_datatype(dtype_str);
if (dtype == simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_ValueError, "Unsupported 'dtype'");
return NULL;
}
}
// Convert `a_obj` to `a_buffer` and to `a_parsed`. Same for `b_obj` and `out_obj`.
if (!parse_tensor(a_obj, &a_buffer, &a_parsed) || !parse_tensor(b_obj, &b_buffer, &b_parsed) ||
!parse_tensor(c_obj, &c_buffer, &c_parsed))
return NULL;
// Check dimensions
if (a_parsed.rank != 1 || b_parsed.rank != 1) {
PyErr_SetString(PyExc_ValueError, "First and second argument must be vectors");
goto cleanup;
}
if (c_parsed.rank != 2) {
PyErr_SetString(PyExc_ValueError, "Third argument must be a matrix (rank-2 tensor)");
goto cleanup;
}
if (a_parsed.count == 0 || b_parsed.count == 0) {
PyErr_SetString(PyExc_ValueError, "Collections can't be empty");
goto cleanup;
}
if (a_parsed.count > 1 && b_parsed.count > 1 && a_parsed.count != b_parsed.count) {
PyErr_SetString(PyExc_ValueError, "Collections must have the same number of elements or just one element");
goto cleanup;
}
// Check data types
if (a_parsed.datatype != b_parsed.datatype || a_parsed.datatype != c_parsed.datatype ||
a_parsed.datatype == simsimd_datatype_unknown_k || b_parsed.datatype == simsimd_datatype_unknown_k ||
c_parsed.datatype == simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_TypeError,
"Input tensors must have matching datatypes, check with `X.__array_interface__`");
goto cleanup;
}
if (dtype == simsimd_datatype_unknown_k) dtype = a_parsed.datatype;
// Look up the metric and the capability
simsimd_metric_curved_punned_t metric = NULL;
simsimd_capability_t capability = simsimd_cap_serial_k;
simsimd_find_kernel_punned(metric_kind, dtype, static_capabilities, simsimd_cap_any_k,
(simsimd_kernel_punned_t *)&metric, &capability);
if (!metric) {
PyErr_Format( //
PyExc_LookupError,
"Unsupported metric '%c' and datatype combination across vectors ('%s'/'%s' and '%s'/'%s'), "
"tensor ('%s'/'%s'), and `dtype` override ('%s'/'%s')",
metric_kind, //
a_buffer.format ? a_buffer.format : "nil", datatype_to_python_string(a_parsed.datatype), //
b_buffer.format ? b_buffer.format : "nil", datatype_to_python_string(b_parsed.datatype), //
c_buffer.format ? c_buffer.format : "nil", datatype_to_python_string(c_parsed.datatype), //
dtype_str ? dtype_str : "nil", datatype_to_python_string(dtype));
goto cleanup;
}
// If the distance is computed between two vectors, rather than matrices, return a scalar
int const dtype_is_complex = is_complex(dtype);
simsimd_distance_t distances[2];
metric(a_parsed.start, b_parsed.start, c_parsed.start, a_parsed.dimensions, &distances[0]);
return_obj = //
dtype_is_complex //
? PyComplex_FromDoubles(distances[0], distances[1])
: PyFloat_FromDouble(distances[0]);
cleanup:
PyBuffer_Release(&a_buffer);
PyBuffer_Release(&b_buffer);
PyBuffer_Release(&c_buffer);
return return_obj;
}
static PyObject *implement_sparse_metric( //
simsimd_metric_kind_t metric_kind, //
PyObject *const *args, Py_ssize_t nargs) {
if (nargs != 2) {
PyErr_SetString(PyExc_TypeError, "Function expects only 2 arguments");
return NULL;
}
PyObject *return_obj = NULL;
PyObject *a_obj = args[0];
PyObject *b_obj = args[1];
Py_buffer a_buffer, b_buffer;
TensorArgument a_parsed, b_parsed;
if (!parse_tensor(a_obj, &a_buffer, &a_parsed) || !parse_tensor(b_obj, &b_buffer, &b_parsed)) return NULL;
// Check dimensions
if (a_parsed.rank != 1 || b_parsed.rank != 1) {
PyErr_SetString(PyExc_ValueError, "First and second argument must be vectors");
goto cleanup;
}
// Check data types
if (a_parsed.datatype != b_parsed.datatype && a_parsed.datatype != simsimd_datatype_unknown_k &&
b_parsed.datatype != simsimd_datatype_unknown_k) {
PyErr_SetString(PyExc_TypeError,
"Input tensors must have matching datatypes, check with `X.__array_interface__`");
goto cleanup;
}
simsimd_datatype_t dtype = a_parsed.datatype;
simsimd_metric_sparse_punned_t metric = NULL;
simsimd_capability_t capability = simsimd_cap_serial_k;
simsimd_find_kernel_punned(metric_kind, dtype, static_capabilities, simsimd_cap_any_k,
(simsimd_kernel_punned_t *)&metric, &capability);
if (!metric) {
PyErr_Format( //
PyExc_LookupError, "Unsupported metric '%c' and datatype combination ('%s'/'%s' and '%s'/'%s')",
metric_kind, //
a_buffer.format ? a_buffer.format : "nil", datatype_to_python_string(a_parsed.datatype), //
b_buffer.format ? b_buffer.format : "nil", datatype_to_python_string(b_parsed.datatype));
goto cleanup;
}
simsimd_distance_t distance;
metric(a_parsed.start, b_parsed.start, a_parsed.dimensions, b_parsed.dimensions, &distance);
return_obj = PyFloat_FromDouble(distance);
cleanup:
PyBuffer_Release(&a_buffer);
PyBuffer_Release(&b_buffer);
return return_obj;
}
static PyObject *implement_cdist( //
PyObject *a_obj, PyObject *b_obj, PyObject *out_obj, //
simsimd_metric_kind_t metric_kind, size_t threads, //
simsimd_datatype_t dtype, simsimd_datatype_t out_dtype) {
You can’t perform that action at this time.
