usearch 2.15.3 → 2.16.0

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 (48) hide show
  1. package/README.md +1 -1
  2. package/cpp/test.cpp +16 -0
  3. package/include/usearch/index.hpp +21 -5
  4. package/include/usearch/index_dense.hpp +6 -1
  5. package/include/usearch/index_plugins.hpp +345 -8
  6. package/javascript/lib.cpp +17 -5
  7. package/javascript/usearch.test.js +190 -21
  8. package/package.json +1 -1
  9. package/prebuilds/darwin-arm64+x64/usearch.node +0 -0
  10. package/prebuilds/linux-arm64/usearch.node +0 -0
  11. package/prebuilds/linux-x64/usearch.node +0 -0
  12. package/simsimd/.git-blame-ignore-revs +2 -0
  13. package/simsimd/CONTRIBUTING.md +71 -23
  14. package/simsimd/Cargo.lock +1 -1
  15. package/simsimd/Cargo.toml +4 -4
  16. package/simsimd/MANIFEST.in +2 -1
  17. package/simsimd/Package.swift +15 -3
  18. package/simsimd/README.md +104 -35
  19. package/simsimd/binding.gyp +6 -2
  20. package/simsimd/build.rs +2 -0
  21. package/simsimd/c/lib.c +180 -99
  22. package/simsimd/include/simsimd/binary.h +311 -102
  23. package/simsimd/include/simsimd/curved.h +134 -135
  24. package/simsimd/include/simsimd/dot.h +448 -274
  25. package/simsimd/include/simsimd/elementwise.h +1437 -0
  26. package/simsimd/include/simsimd/geospatial.h +2 -2
  27. package/simsimd/include/simsimd/mesh.h +2 -2
  28. package/simsimd/include/simsimd/probability.h +88 -88
  29. package/simsimd/include/simsimd/simsimd.h +1157 -772
  30. package/simsimd/include/simsimd/sparse.h +768 -147
  31. package/simsimd/include/simsimd/spatial.h +955 -376
  32. package/simsimd/include/simsimd/types.h +145 -71
  33. package/simsimd/javascript/lib.c +1 -2
  34. package/simsimd/package.json +4 -4
  35. package/simsimd/rust/lib.rs +14 -1
  36. package/simsimd/scripts/bench.cxx +1070 -0
  37. package/simsimd/scripts/bench.ipynb +187 -0
  38. package/simsimd/{javascript → scripts}/bench.js +1 -1
  39. package/simsimd/{rust/benches/sqeuclidean.rs → scripts/bench_sqeuclidean.rs} +6 -6
  40. package/simsimd/scripts/bench_vectors.py +700 -0
  41. package/simsimd/scripts/bench_vectors_live.py +213 -0
  42. package/simsimd/scripts/test.c +155 -0
  43. package/simsimd/{javascript → scripts}/test.mjs +2 -2
  44. package/simsimd/scripts/test.py +1410 -0
  45. package/simsimd/swift/{source/SimSIMD.swift → SimSIMD.swift} +6 -2
  46. package/simsimd/swift/{tests/SimSIMDTests.swift → Test.swift} +1 -1
  47. /package/simsimd/{rust/benches/cosine.rs → scripts/bench_cosine.rs} +0 -0
  48. /package/simsimd/{rust/benches/native.rs → scripts/bench_native.rs} +0 -0
@@ -0,0 +1,1410 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Module: test.py
5
+
6
+ This module contains a suite of tests for the `simsimd` package.
7
+ It compares various SIMD kernels (like Dot-products, squared Euclidean, and Cosine distances)
8
+ with their NumPy or baseline counterparts, testing accuracy for different data types including
9
+ floating-point, integer, and complex numbers.
10
+
11
+ The tests cover:
12
+
13
+ - **Dense Vector Operations**: Tests for `float64`, `float32`, `float16` data types using metrics like `inner`, `sqeuclidean`, and `cosine`.
14
+ - **Brain Floating-Point Format (bfloat16)**: Tests for operations with the brain floating-point format not natively supported by NumPy.
15
+ - **Integer Operations**: Tests for `int8` data type, ensuring accuracy without overflow.
16
+ - **Bitwise Operations**: Tests for Hamming and Jaccard distances using bit arrays.
17
+ - **Complex Numbers**: Tests for complex dot products and vector dot products.
18
+ - **Batch Operations and Cross-Distance Computations**: Tests for batch processing and cross-distance computations using `cdist`.
19
+ - **Hardware Capabilities Verification**: Checks the availability of hardware capabilities and function pointers.
20
+
21
+ **Dependencies**:
22
+
23
+ - Python 3.x
24
+ - `numpy`
25
+ - `scipy`
26
+ - `pytest`
27
+ - `tabulate`
28
+ - `simsimd` package
29
+
30
+ **Usage**:
31
+
32
+ Run the tests using pytest:
33
+
34
+ pytest test.py
35
+
36
+ Or run the script directly:
37
+
38
+ python test.py
39
+
40
+ """
41
+
42
+ import os
43
+ import math
44
+ import time
45
+ import platform
46
+ import collections
47
+ from typing import Dict, List
48
+
49
+ import tabulate
50
+ import pytest
51
+ import simsimd as simd
52
+
53
+
54
+ # NumPy is available on most platforms and is required for most tests.
55
+ # When using PyPy on some platforms NumPy has internal issues, that will
56
+ # raise a weird error, not an `ImportError`. That's why we intentionally
57
+ # use a naked `except:`. Necessary evil!
58
+ try:
59
+ import numpy as np
60
+
61
+ numpy_available = True
62
+
63
+ baseline_inner = np.inner
64
+ baseline_intersect = lambda x, y: len(np.intersect1d(x, y))
65
+ baseline_bilinear = lambda x, y, z: x @ z @ y
66
+
67
+ def baseline_fma(x, y, z, alpha, beta):
68
+ xy_scaled = np.multiply((alpha * x), y)
69
+ z_scaled = beta * z
70
+ r = xy_scaled + z_scaled
71
+ if np.issubdtype(x.dtype, np.integer):
72
+ r = np.round(r)
73
+ #! We need non-overflowing saturating addition for small integers, that NumPy lacks:
74
+ #! https://stackoverflow.com/questions/29611185/avoid-overflow-when-adding-numpy-arrays
75
+ if x.dtype == np.uint8:
76
+ r = np.clip(r, 0, 255, out=r)
77
+ elif x.dtype == np.int8:
78
+ r = np.clip(r, -128, 127, out=r)
79
+ return r.astype(x.dtype)
80
+
81
+ def baseline_wsum(x, y, alpha, beta):
82
+ x_scaled = alpha * x
83
+ y_scaled = beta * y
84
+ r = x_scaled + y_scaled
85
+ if np.issubdtype(x.dtype, np.integer):
86
+ r = np.round(r)
87
+ #! We need non-overflowing saturating addition for small integers, that NumPy lacks:
88
+ #! https://stackoverflow.com/questions/29611185/avoid-overflow-when-adding-numpy-arrays
89
+ if x.dtype == np.uint8:
90
+ r = np.clip(r, 0, 255, out=r)
91
+ elif x.dtype == np.int8:
92
+ r = np.clip(r, -128, 127, out=r)
93
+ return r.astype(x.dtype)
94
+
95
+ except:
96
+ # NumPy is not installed, most tests will be skipped
97
+ numpy_available = False
98
+
99
+ baseline_inner = lambda x, y: sum(x[i] * y[i] for i in range(len(x)))
100
+ baseline_intersect = lambda x, y: len(set(x).intersection(y))
101
+
102
+ def baseline_bilinear(x, y, z):
103
+ result = 0
104
+ for i in range(len(x)):
105
+ for j in range(len(y)):
106
+ result += x[i] * z[i][j] * y[j]
107
+ return result
108
+
109
+ def baseline_fma(x, y, z, alpha, beta):
110
+ return [(alpha * xi) * yi + beta * zi for xi, yi, zi in zip(x, y, z)]
111
+
112
+ def baseline_wsum(x, y, alpha, beta):
113
+ return [(alpha * xi) + beta * yi for xi, yi in zip(x, y)]
114
+
115
+
116
+ # At the time of Python 3.12, SciPy doesn't support 32-bit Windows on any CPU,
117
+ # or 64-bit Windows on Arm. It also doesn't support `musllinux` distributions,
118
+ # like CentOS, RedHat OS, and many others.
119
+ try:
120
+ import scipy.spatial.distance as spd
121
+
122
+ scipy_available = True
123
+
124
+ baseline_euclidean = lambda x, y: np.array(spd.euclidean(x, y)) #! SciPy returns a scalar
125
+ baseline_sqeuclidean = spd.sqeuclidean
126
+ baseline_cosine = spd.cosine
127
+ baseline_jensenshannon = lambda x, y: spd.jensenshannon(x, y) ** 2
128
+ baseline_hamming = lambda x, y: spd.hamming(x, y) * len(x)
129
+ baseline_jaccard = spd.jaccard
130
+
131
+ def baseline_mahalanobis(x, y, z):
132
+ # If there was an error, or the value is NaN, we skip the test.
133
+ try:
134
+ result = spd.mahalanobis(x, y, z).astype(np.float64)
135
+ if not np.isnan(result):
136
+ return result
137
+ except:
138
+ pass
139
+ pytest.skip(f"SciPy Mahalanobis distance returned {result} due to `sqrt` of a negative number")
140
+
141
+ except:
142
+ # SciPy is not installed, some tests will be skipped
143
+ scipy_available = False
144
+
145
+ baseline_cosine = lambda x, y: 1.0 - np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))
146
+ baseline_euclidean = lambda x, y: np.array([np.sqrt(np.sum((x - y) ** 2))])
147
+ baseline_sqeuclidean = lambda x, y: np.sum((x - y) ** 2)
148
+ baseline_jensenshannon = lambda p, q: (np.sum((np.sqrt(p) - np.sqrt(q)) ** 2)) / 2
149
+ baseline_hamming = lambda x, y: np.logical_xor(x, y).sum()
150
+
151
+ def baseline_mahalanobis(x, y, z):
152
+ diff = x - y
153
+ return np.sqrt(diff @ z @ diff)
154
+
155
+ def baseline_jaccard(x, y):
156
+ intersection = np.logical_and(x, y).sum()
157
+ union = np.logical_or(x, y).sum()
158
+ return 0.0 if union == 0 else 1.0 - float(intersection) / float(union)
159
+
160
+ def baseline_intersect(arr1, arr2):
161
+ i, j, intersection = 0, 0, 0
162
+ while i < len(arr1) and j < len(arr2):
163
+ if arr1[i] == arr2[j]:
164
+ intersection += 1
165
+ i += 1
166
+ j += 1
167
+ elif arr1[i] < arr2[j]:
168
+ i += 1
169
+ else:
170
+ j += 1
171
+ return intersection
172
+
173
+
174
+ def is_running_under_qemu():
175
+ return "SIMSIMD_IN_QEMU" in os.environ
176
+
177
+
178
+ def profile(callable, *args, **kwargs) -> tuple:
179
+ before = time.perf_counter_ns()
180
+ result = callable(*args, **kwargs)
181
+ after = time.perf_counter_ns()
182
+ return after - before, result
183
+
184
+
185
+ @pytest.fixture(scope="session")
186
+ def stats_fixture():
187
+ """Session-scoped fixture that collects errors during tests."""
188
+ results = dict()
189
+ results["metric"] = []
190
+ results["ndim"] = []
191
+ results["dtype"] = []
192
+ results["absolute_baseline_error"] = []
193
+ results["relative_baseline_error"] = []
194
+ results["absolute_simsimd_error"] = []
195
+ results["relative_simsimd_error"] = []
196
+ results["accurate_duration"] = []
197
+ results["baseline_duration"] = []
198
+ results["simsimd_duration"] = []
199
+ results["warnings"] = []
200
+ yield results
201
+
202
+ # Group the errors by (metric, ndim, dtype) to calculate the mean and std error.
203
+ grouped_errors = collections.defaultdict(
204
+ lambda: {
205
+ "absolute_baseline_error": [],
206
+ "relative_baseline_error": [],
207
+ "absolute_simsimd_error": [],
208
+ "relative_simsimd_error": [],
209
+ "accurate_duration": [],
210
+ "baseline_duration": [],
211
+ "simsimd_duration": [],
212
+ }
213
+ )
214
+ for (
215
+ metric,
216
+ ndim,
217
+ dtype,
218
+ absolute_baseline_error,
219
+ relative_baseline_error,
220
+ absolute_simsimd_error,
221
+ relative_simsimd_error,
222
+ accurate_duration,
223
+ baseline_duration,
224
+ simsimd_duration,
225
+ ) in zip(
226
+ results["metric"],
227
+ results["ndim"],
228
+ results["dtype"],
229
+ results["absolute_baseline_error"],
230
+ results["relative_baseline_error"],
231
+ results["absolute_simsimd_error"],
232
+ results["relative_simsimd_error"],
233
+ results["accurate_duration"],
234
+ results["baseline_duration"],
235
+ results["simsimd_duration"],
236
+ ):
237
+ key = (metric, ndim, dtype)
238
+ grouped_errors[key]["absolute_baseline_error"].append(absolute_baseline_error)
239
+ grouped_errors[key]["relative_baseline_error"].append(relative_baseline_error)
240
+ grouped_errors[key]["absolute_simsimd_error"].append(absolute_simsimd_error)
241
+ grouped_errors[key]["relative_simsimd_error"].append(relative_simsimd_error)
242
+ grouped_errors[key]["accurate_duration"].append(accurate_duration)
243
+ grouped_errors[key]["baseline_duration"].append(baseline_duration)
244
+ grouped_errors[key]["simsimd_duration"].append(simsimd_duration)
245
+
246
+ # Compute mean and the standard deviation for each task error
247
+ final_results = []
248
+ for key, errors in grouped_errors.items():
249
+ n = len(errors["simsimd_duration"])
250
+
251
+ # Mean and the standard deviation for errors
252
+ baseline_errors = errors["relative_baseline_error"]
253
+ simsimd_errors = errors["relative_simsimd_error"]
254
+ #! On some platforms (like `cp312-musllinux_aarch64`) without casting via `float(x)`
255
+ #! the subsequent `:.2e` string formatting code will fail due to:
256
+ #! `TypeError: unsupported format string passed to numpy.ndarray.__format__`.
257
+ baseline_mean = float(sum(baseline_errors)) / n
258
+ simsimd_mean = float(sum(simsimd_errors)) / n
259
+ baseline_std = math.sqrt(sum((x - baseline_mean) ** 2 for x in baseline_errors) / n)
260
+ simsimd_std = math.sqrt(sum((x - simsimd_mean) ** 2 for x in simsimd_errors) / n)
261
+ baseline_error_formatted = f"{baseline_mean:.2e} ± {baseline_std:.2e}"
262
+ simsimd_error_formatted = f"{simsimd_mean:.2e} ± {simsimd_std:.2e}"
263
+
264
+ # Log durations
265
+ accurate_durations = errors["accurate_duration"]
266
+ baseline_durations = errors["baseline_duration"]
267
+ simsimd_durations = errors["simsimd_duration"]
268
+ accurate_mean_duration = sum(accurate_durations) / n
269
+ baseline_mean_duration = sum(baseline_durations) / n
270
+ simsimd_mean_duration = sum(simsimd_durations) / n
271
+ accurate_std_duration = math.sqrt(sum((x - accurate_mean_duration) ** 2 for x in accurate_durations) / n)
272
+ baseline_std_duration = math.sqrt(sum((x - baseline_mean_duration) ** 2 for x in baseline_durations) / n)
273
+ simsimd_std_duration = math.sqrt(sum((x - simsimd_mean_duration) ** 2 for x in simsimd_durations) / n)
274
+ accurate_duration = f"{accurate_mean_duration:.2e} ± {accurate_std_duration:.2e}"
275
+ baseline_duration = f"{baseline_mean_duration:.2e} ± {baseline_std_duration:.2e}"
276
+ simsimd_duration = f"{simsimd_mean_duration:.2e} ± {simsimd_std_duration:.2e}"
277
+
278
+ # Measure time improvement
279
+ improvements = [baseline / simsimd for baseline, simsimd in zip(baseline_durations, simsimd_durations)]
280
+ improvements_mean = sum(improvements) / n
281
+ improvements_std = math.sqrt(sum((x - improvements_mean) ** 2 for x in improvements) / n)
282
+ simsimd_speedup = f"{improvements_mean:.2f}x ± {improvements_std:.2f}x"
283
+
284
+ # Calculate Improvement
285
+ # improvement = abs(baseline_mean - simsimd_mean) / min(simsimd_mean, baseline_mean)
286
+ # if baseline_mean < simsimd_mean:
287
+ # improvement *= -1
288
+ # improvement_formatted = f"{improvement:+.2}x" if improvement != float("inf") else "N/A"
289
+
290
+ final_results.append(
291
+ (
292
+ *key,
293
+ baseline_error_formatted,
294
+ simsimd_error_formatted,
295
+ accurate_duration,
296
+ baseline_duration,
297
+ simsimd_duration,
298
+ simsimd_speedup,
299
+ )
300
+ )
301
+
302
+ # Sort results for consistent presentation
303
+ final_results.sort(key=lambda x: (x[0], x[1], x[2]))
304
+
305
+ # Output the final table after all tests are completed
306
+ print("\n")
307
+ print("Numerical Error Aggregation Report:")
308
+ headers = [
309
+ "Metric",
310
+ "NDim",
311
+ "DType",
312
+ "Baseline Error", # Printed as mean ± std deviation
313
+ "SimSIMD Error", # Printed as mean ± std deviation
314
+ "Accurate Duration", # Printed as mean ± std deviation
315
+ "Baseline Duration", # Printed as mean ± std deviation
316
+ "SimSIMD Duration", # Printed as mean ± std deviation
317
+ "SimSIMD Speedup",
318
+ ]
319
+ print(tabulate.tabulate(final_results, headers=headers, tablefmt="pretty", showindex=True))
320
+
321
+ # Show the additional grouped warnings
322
+ warnings = results.get("warnings", [])
323
+ warnings = sorted(warnings)
324
+ warnings = [f"{name}: {message}" for name, message in warnings]
325
+ if len(warnings) != 0:
326
+ print("\nWarnings:")
327
+ unique_warnings, warning_counts = np.unique(warnings, return_counts=True)
328
+ for warning, count in zip(unique_warnings, warning_counts):
329
+ print(f"- {count}x times: {warning}")
330
+
331
+
332
+ @pytest.hookimpl(tryfirst=True)
333
+ def pytest_runtest_makereport(item, call):
334
+ """Custom hook to ensure that the error aggregator runs even for failed tests."""
335
+ if call.when == "call":
336
+ item.test_result = call.excinfo is None
337
+
338
+
339
+ def collect_errors(
340
+ metric: str,
341
+ ndim: int,
342
+ dtype: str,
343
+ accurate_result: float,
344
+ accurate_duration: float,
345
+ baseline_result: float,
346
+ baseline_duration: float,
347
+ simsimd_result: float,
348
+ simsimd_duration: float,
349
+ stats,
350
+ ):
351
+ """Calculates and aggregates errors for a given test.
352
+
353
+ What we want to know in the end of the day is:
354
+
355
+ - How much SimSIMD implementation is more/less accurate than baseline,
356
+ when compared against the accurate result?
357
+ - TODO: How much faster is SimSIMD than the baseline kernel?
358
+ - TODO: How much faster is SimSIMD than the accurate kernel?
359
+ """
360
+ eps = np.finfo(accurate_result.dtype).resolution
361
+ absolute_baseline_error = np.max(np.abs(baseline_result - accurate_result))
362
+ relative_baseline_error = np.max(np.abs(baseline_result - accurate_result) / (np.abs(accurate_result) + eps))
363
+ absolute_simsimd_error = np.max(np.abs(simsimd_result - accurate_result))
364
+ relative_simsimd_error = np.max(np.abs(simsimd_result - accurate_result) / (np.abs(accurate_result) + eps))
365
+
366
+ stats["metric"].append(metric)
367
+ stats["ndim"].append(ndim)
368
+ stats["dtype"].append(dtype)
369
+ stats["absolute_baseline_error"].append(absolute_baseline_error)
370
+ stats["relative_baseline_error"].append(relative_baseline_error)
371
+ stats["absolute_simsimd_error"].append(absolute_simsimd_error)
372
+ stats["relative_simsimd_error"].append(relative_simsimd_error)
373
+ stats["accurate_duration"].append(accurate_duration)
374
+ stats["baseline_duration"].append(baseline_duration)
375
+ stats["simsimd_duration"].append(simsimd_duration)
376
+
377
+
378
+ def get_current_test():
379
+ """Get's the current test filename, test name, and function name.
380
+ Similar metadata can be obtained from the `request` fixture, but this
381
+ solution uses environment variables."""
382
+ full_name = os.environ.get("PYTEST_CURRENT_TEST").split(" ")[0]
383
+ test_file = full_name.split("::")[0].split("/")[-1].split(".py")[0]
384
+ test_name = full_name.split("::")[1]
385
+ # The `test_name` may look like: "test_dense_i8[cosine-1536-24-50]"
386
+ function_name = test_name.split("[")[0]
387
+ return test_file, test_name, function_name
388
+
389
+
390
+ def collect_warnings(message: str, stats: dict):
391
+ """Collects warnings for the final report."""
392
+ _, _, function_name = get_current_test()
393
+ stats["warnings"].append((function_name, message))
394
+
395
+
396
+ # For normalized distances we use the absolute tolerance, because the result is close to zero.
397
+ # For unnormalized ones (like squared Euclidean or Jaccard), we use the relative.
398
+ SIMSIMD_RTOL = 0.1
399
+ SIMSIMD_ATOL = 0.1
400
+
401
+ # We will run all the tests many times using different instruction sets under the hood.
402
+ available_capabilities: Dict[str, str] = simd.get_capabilities()
403
+ possible_x86_capabilities: List[str] = ["haswell", "ice", "skylake", "sapphire", "turin", "genoa", "sierra"]
404
+ possible_arm_capabilities: List[str] = [
405
+ "neon",
406
+ "neon_f16",
407
+ "neon_bf16",
408
+ "neon_i8",
409
+ "sve",
410
+ "sve_f16",
411
+ "sve_bf16",
412
+ "sve_i8",
413
+ ]
414
+ possible_x86_capabilities: List[str] = [c for c in possible_x86_capabilities if available_capabilities[c]]
415
+ possible_arm_capabilities: List[str] = [c for c in possible_arm_capabilities if available_capabilities[c]]
416
+ possible_capabilities: List[str] = (
417
+ possible_x86_capabilities if platform.machine() == "x86_64" else possible_arm_capabilities
418
+ )
419
+
420
+
421
+ def keep_one_capability(cap: str):
422
+ assert cap in possible_capabilities
423
+ for c in possible_capabilities:
424
+ if c != cap:
425
+ simd.disable_capability(c)
426
+ simd.enable_capability(c)
427
+
428
+
429
+ def name_to_kernels(name: str):
430
+ """
431
+ Having a separate "helper" function to convert the kernel name is handy for PyTest decorators,
432
+ that can't generally print non-trivial object (like function pointers) well.
433
+ """
434
+ if name == "inner":
435
+ return baseline_inner, simd.inner
436
+ elif name == "euclidean":
437
+ return baseline_euclidean, simd.euclidean
438
+ elif name == "sqeuclidean":
439
+ return baseline_sqeuclidean, simd.sqeuclidean
440
+ elif name == "cosine":
441
+ return baseline_cosine, simd.cosine
442
+ elif name == "bilinear":
443
+ return baseline_bilinear, simd.bilinear
444
+ elif name == "mahalanobis":
445
+ return baseline_mahalanobis, simd.mahalanobis
446
+ elif name == "jaccard":
447
+ return baseline_jaccard, simd.jaccard
448
+ elif name == "hamming":
449
+ return baseline_hamming, simd.hamming
450
+ elif name == "intersect":
451
+ return baseline_intersect, simd.intersect
452
+ elif name == "fma":
453
+ return baseline_fma, simd.fma
454
+ elif name == "wsum":
455
+ return baseline_wsum, simd.wsum
456
+ else:
457
+ raise ValueError(f"Unknown kernel name: {name}")
458
+
459
+
460
+ def f32_downcast_to_bf16(array):
461
+ """Converts an array of 32-bit floats into 16-bit brain-floats."""
462
+ array = np.asarray(array, dtype=np.float32)
463
+ # NumPy doesn't natively support brain-float, so we need a trick!
464
+ # Luckily, it's very easy to reduce the representation accuracy
465
+ # by simply masking the low 16-bits of our 32-bit single-precision
466
+ # numbers. We can also add `0x8000` to round the numbers.
467
+ array_f32_rounded = ((array.view(np.uint32) + 0x8000) & 0xFFFF0000).view(np.float32)
468
+ # To represent them as brain-floats, we need to drop the second halves.
469
+ array_bf16 = np.right_shift(array_f32_rounded.view(np.uint32), 16).astype(np.uint16)
470
+ return array_f32_rounded, array_bf16
471
+
472
+
473
+ def i8_downcast_to_i4(array):
474
+ """Converts an array of 8-bit integers into 4-bit integers, packing 2 per byte."""
475
+ array = np.asarray(array, dtype=np.int8)
476
+ assert np.all(array >= -8) and np.all(array <= 7), "Input array must be in the range [-8, 7]"
477
+
478
+
479
+ def hex_array(arr):
480
+ """Converts numerical array into a string of comma-separated hexadecimal values for debugging.
481
+ Supports 1D and 2D arrays.
482
+ """
483
+ printer = np.vectorize(hex)
484
+ strings = printer(arr)
485
+
486
+ if strings.ndim == 1:
487
+ return ", ".join(strings)
488
+ else:
489
+ return "\n".join(", ".join(row) for row in strings)
490
+
491
+
492
+ def test_pointers_availability():
493
+ """Tests the availability of pre-compiled functions for compatibility with USearch."""
494
+ assert simd.pointer_to_sqeuclidean("f64") != 0
495
+ assert simd.pointer_to_cosine("f64") != 0
496
+ assert simd.pointer_to_inner("f64") != 0
497
+
498
+ assert simd.pointer_to_sqeuclidean("f32") != 0
499
+ assert simd.pointer_to_cosine("f32") != 0
500
+ assert simd.pointer_to_inner("f32") != 0
501
+
502
+ assert simd.pointer_to_sqeuclidean("f16") != 0
503
+ assert simd.pointer_to_cosine("f16") != 0
504
+ assert simd.pointer_to_inner("f16") != 0
505
+
506
+ assert simd.pointer_to_sqeuclidean("i8") != 0
507
+ assert simd.pointer_to_cosine("i8") != 0
508
+ assert simd.pointer_to_inner("i8") != 0
509
+
510
+ assert simd.pointer_to_sqeuclidean("u8") != 0
511
+ assert simd.pointer_to_cosine("u8") != 0
512
+ assert simd.pointer_to_inner("u8") != 0
513
+
514
+
515
+ def test_capabilities_list():
516
+ """Tests the visibility of hardware capabilities."""
517
+ assert "serial" in simd.get_capabilities()
518
+ assert "neon" in simd.get_capabilities()
519
+ assert "neon_f16" in simd.get_capabilities()
520
+ assert "neon_bf16" in simd.get_capabilities()
521
+ assert "neon_i8" in simd.get_capabilities()
522
+ assert "sve" in simd.get_capabilities()
523
+ assert "sve_f16" in simd.get_capabilities()
524
+ assert "sve_bf16" in simd.get_capabilities()
525
+ assert "sve_i8" in simd.get_capabilities()
526
+ assert "haswell" in simd.get_capabilities()
527
+ assert "ice" in simd.get_capabilities()
528
+ assert "skylake" in simd.get_capabilities()
529
+ assert "genoa" in simd.get_capabilities()
530
+ assert "sapphire" in simd.get_capabilities()
531
+ assert "turin" in simd.get_capabilities()
532
+ assert simd.get_capabilities().get("serial") == 1
533
+
534
+ # Check the toggle:
535
+ previous_value = simd.get_capabilities().get("neon")
536
+ simd.enable_capability("neon")
537
+ assert simd.get_capabilities().get("neon") == 1
538
+ if not previous_value:
539
+ simd.disable_capability("neon")
540
+
541
+
542
+ def to_array(x, dtype=None):
543
+ if numpy_available:
544
+ y = np.array(x)
545
+ if dtype is not None:
546
+ y = y.astype(dtype)
547
+ return y
548
+
549
+
550
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
551
+ @pytest.mark.parametrize(
552
+ "function, expected_error, args, kwargs",
553
+ [
554
+ # Test missing positional arguments
555
+ (simd.sqeuclidean, TypeError, (), {}), # No arguments provided
556
+ (simd.sqeuclidean, TypeError, (to_array([1.0]),), {}), # Only one positional argument
557
+ # Try missing type name
558
+ (simd.sqeuclidean, ValueError, (to_array([1.0]), to_array([1.0]), "missing_dtype"), {}),
559
+ # Test incorrect argument type
560
+ (simd.sqeuclidean, TypeError, (to_array([1.0]), "invalid"), {}), # Wrong type for second argument
561
+ # Test invalid keyword argument name
562
+ (simd.sqeuclidean, TypeError, (to_array([1.0]), to_array([1.0])), {"invalid_kwarg": "value"}),
563
+ # Test wrong argument type for SIMD capability toggle
564
+ (simd.enable_capability, TypeError, (123,), {}), # Should expect a string
565
+ (simd.disable_capability, TypeError, ([],), {}), # Should expect a string
566
+ # Test missing required argument for Mahalanobis
567
+ (simd.mahalanobis, TypeError, (to_array([1.0]), to_array([1.0])), {}), # Missing covariance matrix
568
+ # Test missing required arguments for bilinear
569
+ (simd.bilinear, TypeError, (to_array([1.0]),), {}), # Missing second vector and metric tensor
570
+ # Test passing too many arguments to a method
571
+ (simd.cosine, TypeError, (to_array([1.0]), to_array([1.0]), to_array([1.0])), {}), # Too many arguments
572
+ (simd.cdist, TypeError, (to_array([[1.0]]), to_array([[1.0]]), "cos", "dos"), {}), # Too many arguments
573
+ # Same argument as both positional and keyword
574
+ (simd.cdist, TypeError, (to_array([[1.0]]), to_array([[1.0]]), "cos"), {"metric": "cos"}),
575
+ # Applying real metric to complex numbers - missing kernel
576
+ (simd.cosine, LookupError, (to_array([1 + 2j]), to_array([1 + 2j])), {}),
577
+ # Test incompatible vectors for cosine
578
+ (simd.cosine, ValueError, (to_array([1.0]), to_array([1.0, 2.0])), {}), # Different number of dimensions
579
+ (simd.cosine, TypeError, (to_array([1.0]), to_array([1], "uint32")), {}), # Floats and integers
580
+ (simd.cosine, TypeError, (to_array([1]), to_array([1], "float16")), {}), # Different floats
581
+ ],
582
+ )
583
+ def test_invalid_argument_handling(function, expected_error, args, kwargs):
584
+ """Test that functions raise TypeError when called with invalid arguments."""
585
+ with pytest.raises(expected_error):
586
+ function(*args, **kwargs)
587
+
588
+
589
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
590
+ @pytest.mark.repeat(50)
591
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
592
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "float16"])
593
+ @pytest.mark.parametrize("metric", ["inner", "euclidean", "sqeuclidean", "cosine"])
594
+ @pytest.mark.parametrize("capability", possible_capabilities)
595
+ def test_dense(ndim, dtype, metric, capability, stats_fixture):
596
+ """Compares various SIMD kernels (like Dot-products, squared Euclidean, and Cosine distances)
597
+ with their NumPy or baseline counterparts, testing accuracy for IEEE standard floating-point types."""
598
+
599
+ if dtype == "float16" and is_running_under_qemu():
600
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
601
+
602
+ np.random.seed()
603
+ a = np.random.randn(ndim).astype(dtype)
604
+ b = np.random.randn(ndim).astype(dtype)
605
+
606
+ keep_one_capability(capability)
607
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
608
+
609
+ accurate_dt, accurate = profile(baseline_kernel, a.astype(np.float64), b.astype(np.float64))
610
+ expected_dt, expected = profile(baseline_kernel, a, b)
611
+ result_dt, result = profile(simd_kernel, a, b)
612
+ result = np.array(result)
613
+
614
+ np.testing.assert_allclose(result, expected.astype(np.float64), atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
615
+ collect_errors(metric, ndim, dtype, accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture)
616
+
617
+
618
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
619
+ @pytest.mark.repeat(50)
620
+ @pytest.mark.parametrize("ndim", [11, 97])
621
+ @pytest.mark.parametrize(
622
+ "dtypes", # representation datatype and compute precision
623
+ [
624
+ ("float64", "float64"),
625
+ ("float32", "float32"),
626
+ ("float16", "float32"), # otherwise NumPy keeps aggregating too much error
627
+ ],
628
+ )
629
+ @pytest.mark.parametrize("metric", ["bilinear", "mahalanobis"])
630
+ @pytest.mark.parametrize("capability", possible_capabilities)
631
+ def test_curved(ndim, dtypes, metric, capability, stats_fixture):
632
+ """Compares various SIMD kernels (like Bilinear Forms and Mahalanobis distances) for curved spaces
633
+ with their NumPy or baseline counterparts, testing accuracy for IEEE standard floating-point types."""
634
+
635
+ dtype, compute_dtype = dtypes
636
+ if dtype == "float16" and is_running_under_qemu():
637
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
638
+
639
+ np.random.seed()
640
+
641
+ # Let's generate some non-negative probability distributions
642
+ a = np.abs(np.random.randn(ndim).astype(dtype))
643
+ b = np.abs(np.random.randn(ndim).astype(dtype))
644
+ a /= np.sum(a)
645
+ b /= np.sum(b)
646
+
647
+ # Let's compute the inverse of the covariance matrix, otherwise in the SciPy
648
+ # implementation of the Mahalanobis we may face `sqrt` of a negative number.
649
+ # We multiply the matrix by its transpose to get a positive-semi-definite matrix.
650
+ c = np.abs(np.random.randn(ndim, ndim).astype(dtype))
651
+ c = np.dot(c, c.T)
652
+
653
+ keep_one_capability(capability)
654
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
655
+ accurate_dt, accurate = profile(
656
+ baseline_kernel,
657
+ a.astype(np.float64),
658
+ b.astype(np.float64),
659
+ c.astype(np.float64),
660
+ )
661
+ expected_dt, expected = profile(
662
+ baseline_kernel,
663
+ a.astype(compute_dtype),
664
+ b.astype(compute_dtype),
665
+ c.astype(compute_dtype),
666
+ )
667
+ result_dt, result = profile(simd_kernel, a, b, c)
668
+ result = np.array(result)
669
+
670
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
671
+ collect_errors(metric, ndim, dtype, accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture)
672
+
673
+
674
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
675
+ @pytest.mark.repeat(50)
676
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
677
+ @pytest.mark.parametrize("metric", ["inner", "euclidean", "sqeuclidean", "cosine"])
678
+ @pytest.mark.parametrize("capability", possible_capabilities)
679
+ def test_dense_bf16(ndim, metric, capability, stats_fixture):
680
+ """Compares various SIMD kernels (like Dot-products, squared Euclidean, and Cosine distances)
681
+ with their NumPy or baseline counterparts, testing accuracy for the Brain-float format not
682
+ natively supported by NumPy."""
683
+ np.random.seed()
684
+ a = np.random.randn(ndim).astype(np.float32)
685
+ b = np.random.randn(ndim).astype(np.float32)
686
+
687
+ a_f32_rounded, a_bf16 = f32_downcast_to_bf16(a)
688
+ b_f32_rounded, b_bf16 = f32_downcast_to_bf16(b)
689
+
690
+ keep_one_capability(capability)
691
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
692
+ accurate_dt, accurate = profile(baseline_kernel, a_f32_rounded.astype(np.float64), b_f32_rounded.astype(np.float64))
693
+ expected_dt, expected = profile(baseline_kernel, a_f32_rounded, b_f32_rounded)
694
+ result_dt, result = profile(simd_kernel, a_bf16, b_bf16, "bf16")
695
+ result = np.array(result)
696
+
697
+ np.testing.assert_allclose(
698
+ result,
699
+ expected,
700
+ atol=SIMSIMD_ATOL,
701
+ rtol=SIMSIMD_RTOL,
702
+ err_msg=f"""
703
+ First `f32` operand in hex: {hex_array(a_f32_rounded.view(np.uint32))}
704
+ Second `f32` operand in hex: {hex_array(b_f32_rounded.view(np.uint32))}
705
+ First `bf16` operand in hex: {hex_array(a_bf16)}
706
+ Second `bf16` operand in hex: {hex_array(b_bf16)}
707
+ """,
708
+ )
709
+ collect_errors(
710
+ metric, ndim, "bfloat16", accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture
711
+ )
712
+
713
+
714
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
715
+ @pytest.mark.repeat(50)
716
+ @pytest.mark.parametrize("ndim", [11, 16, 33])
717
+ @pytest.mark.parametrize("metric", ["bilinear", "mahalanobis"])
718
+ @pytest.mark.parametrize("capability", possible_capabilities)
719
+ def test_curved_bf16(ndim, metric, capability, stats_fixture):
720
+ """Compares various SIMD kernels (like Bilinear Forms and Mahalanobis distances) for curved spaces
721
+ with their NumPy or baseline counterparts, testing accuracy for the Brain-float format not
722
+ natively supported by NumPy."""
723
+
724
+ np.random.seed()
725
+
726
+ # Let's generate some non-negative probability distributions
727
+ a = np.abs(np.random.randn(ndim).astype(np.float32))
728
+ b = np.abs(np.random.randn(ndim).astype(np.float32))
729
+ a /= np.sum(a)
730
+ b /= np.sum(b)
731
+
732
+ # Let's compute the inverse of the covariance matrix, otherwise in the SciPy
733
+ # implementation of the Mahalanobis we may face `sqrt` of a negative number.
734
+ # We multiply the matrix by its transpose to get a positive-semi-definite matrix.
735
+ c = np.abs(np.random.randn(ndim, ndim).astype(np.float32))
736
+ c = np.dot(c, c.T)
737
+
738
+ a_f32_rounded, a_bf16 = f32_downcast_to_bf16(a)
739
+ b_f32_rounded, b_bf16 = f32_downcast_to_bf16(b)
740
+ c_f32_rounded, c_bf16 = f32_downcast_to_bf16(c)
741
+
742
+ keep_one_capability(capability)
743
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
744
+ accurate_dt, accurate = profile(
745
+ baseline_kernel,
746
+ a_f32_rounded.astype(np.float64),
747
+ b_f32_rounded.astype(np.float64),
748
+ c_f32_rounded.astype(np.float64),
749
+ )
750
+ expected_dt, expected = profile(baseline_kernel, a_f32_rounded, b_f32_rounded, c_f32_rounded)
751
+ result_dt, result = profile(simd_kernel, a_bf16, b_bf16, c_bf16, "bf16")
752
+ result = np.array(result)
753
+
754
+ np.testing.assert_allclose(
755
+ result,
756
+ expected,
757
+ atol=SIMSIMD_ATOL,
758
+ rtol=SIMSIMD_RTOL,
759
+ err_msg=f"""
760
+ First `f32` operand in hex: {hex_array(a_f32_rounded.view(np.uint32))}
761
+ Second `f32` operand in hex: {hex_array(b_f32_rounded.view(np.uint32))}
762
+ First `bf16` operand in hex: {hex_array(a_bf16)}
763
+ Second `bf16` operand in hex: {hex_array(b_bf16)}
764
+ Matrix `bf16` operand in hex: {hex_array(c_bf16)}
765
+ Matrix `bf16` operand in hex: {hex_array(c_bf16)}
766
+ """,
767
+ )
768
+ collect_errors(
769
+ metric, ndim, "bfloat16", accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture
770
+ )
771
+
772
+
773
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
774
+ @pytest.mark.repeat(50)
775
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
776
+ @pytest.mark.parametrize("dtype", ["int8", "uint8"])
777
+ @pytest.mark.parametrize("metric", ["inner", "euclidean", "sqeuclidean", "cosine"])
778
+ @pytest.mark.parametrize("capability", possible_capabilities)
779
+ def test_dense_i8(ndim, dtype, metric, capability, stats_fixture):
780
+ """Compares various SIMD kernels (like Dot-products, squared Euclidean, and Cosine distances)
781
+ with their NumPy or baseline counterparts, testing accuracy for small integer types, that can't
782
+ be directly processed with other tools without overflowing."""
783
+
784
+ np.random.seed()
785
+ if dtype == "int8":
786
+ a = np.random.randint(-128, 127, size=(ndim), dtype=np.int8)
787
+ b = np.random.randint(-128, 127, size=(ndim), dtype=np.int8)
788
+ else:
789
+ a = np.random.randint(0, 255, size=(ndim), dtype=np.uint8)
790
+ b = np.random.randint(0, 255, size=(ndim), dtype=np.uint8)
791
+
792
+ keep_one_capability(capability)
793
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
794
+
795
+ accurate_dt, accurate = profile(baseline_kernel, a.astype(np.float64), b.astype(np.float64))
796
+ expected_dt, expected = profile(baseline_kernel, a.astype(np.int64), b.astype(np.int64))
797
+ result_dt, result = profile(simd_kernel, a, b)
798
+ result = np.array(result)
799
+
800
+ if metric == "inner":
801
+ assert round(float(result)) == round(float(expected)), f"Expected {expected}, but got {result}"
802
+ else:
803
+ np.testing.assert_allclose(
804
+ result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL
805
+ ), f"Expected {expected}, but got {result}"
806
+ collect_errors(metric, ndim, dtype, accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture)
807
+
808
+ #! Fun fact: SciPy doesn't actually raise an `OverflowError` when overflow happens
809
+ #! here, instead it raises `ValueError: math domain error` during the `sqrt` operation.
810
+ try:
811
+ expected_overflow = baseline_kernel(a, b)
812
+ if np.isinf(expected_overflow):
813
+ collect_warnings("Couldn't avoid overflow in SciPy", stats_fixture)
814
+ except Exception as e:
815
+ collect_warnings(f"Arbitrary error raised in SciPy: {e}", stats_fixture)
816
+
817
+
818
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
819
+ @pytest.mark.skipif(not scipy_available, reason="SciPy is not installed")
820
+ @pytest.mark.repeat(50)
821
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
822
+ @pytest.mark.parametrize("metric", ["jaccard", "hamming"])
823
+ @pytest.mark.parametrize("capability", possible_capabilities)
824
+ def test_dense_bits(ndim, metric, capability, stats_fixture):
825
+ """Compares various SIMD kernels (like Hamming and Jaccard/Tanimoto distances) for dense bit arrays
826
+ with their NumPy or baseline counterparts, even though, they can't process sub-byte-sized scalars."""
827
+ np.random.seed()
828
+ a = np.random.randint(2, size=ndim).astype(np.uint8)
829
+ b = np.random.randint(2, size=ndim).astype(np.uint8)
830
+
831
+ keep_one_capability(capability)
832
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
833
+ accurate_dt, accurate = profile(baseline_kernel, a.astype(np.uint64), b.astype(np.uint64))
834
+ expected_dt, expected = profile(baseline_kernel, a, b)
835
+ result_dt, result = profile(simd_kernel, np.packbits(a), np.packbits(b), "b8")
836
+ result = np.array(result)
837
+
838
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
839
+ collect_errors(metric, ndim, "bits", accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture)
840
+
841
+
842
+ @pytest.mark.skip(reason="Problems inferring the tolerance bounds for numerical errors")
843
+ @pytest.mark.repeat(50)
844
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
845
+ @pytest.mark.parametrize("dtype", ["float32", "float16"])
846
+ @pytest.mark.parametrize("capability", possible_capabilities)
847
+ def test_jensen_shannon(ndim, dtype, capability):
848
+ """Compares the simd.jensenshannon() function with scipy.spatial.distance.jensenshannon(), measuring the accuracy error for f16, and f32 types."""
849
+ np.random.seed()
850
+ a = np.abs(np.random.randn(ndim)).astype(dtype)
851
+ b = np.abs(np.random.randn(ndim)).astype(dtype)
852
+ a /= np.sum(a)
853
+ b /= np.sum(b)
854
+
855
+ keep_one_capability(capability)
856
+ baseline_kernel, simd_kernel = name_to_kernels("jensenshannon")
857
+ accurate_dt, accurate = profile(baseline_kernel, a.astype(np.float64), b.astype(np.float64))
858
+ expected_dt, expected = profile(baseline_kernel, a, b)
859
+ result_dt, result = profile(simd_kernel, a, b)
860
+ result = np.array(result)
861
+
862
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
863
+ collect_errors(
864
+ "jensenshannon", ndim, dtype, accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture
865
+ )
866
+
867
+
868
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
869
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
870
+ @pytest.mark.parametrize("dtype", ["float32", "float16"])
871
+ @pytest.mark.parametrize("capability", possible_capabilities)
872
+ def test_cosine_zero_vector(ndim, dtype, capability):
873
+ """Tests the simd.cosine() function with zero vectors, to catch division by zero errors."""
874
+ a = np.zeros(ndim, dtype=dtype)
875
+ b = (np.random.randn(ndim) + 1).astype(dtype)
876
+ keep_one_capability(capability)
877
+
878
+ result = simd.cosine(a, b)
879
+ assert result == 1, f"Expected 1, but got {result}"
880
+
881
+ result = simd.cosine(a, a)
882
+ assert result == 0, f"Expected 0 distance from itself, but got {result}"
883
+
884
+ result = simd.cosine(b, b)
885
+ assert abs(result) < SIMSIMD_ATOL, f"Expected 0 distance from itself, but got {result}"
886
+
887
+ # For the cosine, the output must not be negative!
888
+ assert np.all(result >= 0), f"Negative result for cosine distance"
889
+
890
+
891
+ @pytest.mark.skip(reason="Lacks overflow protection: https://github.com/ashvardanian/SimSIMD/issues/206") # TODO
892
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
893
+ @pytest.mark.repeat(50)
894
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
895
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "float16"])
896
+ @pytest.mark.parametrize("metric", ["inner", "euclidean", "sqeuclidean", "cosine"])
897
+ @pytest.mark.parametrize("capability", possible_capabilities)
898
+ def test_overflow(ndim, dtype, metric, capability):
899
+ """Tests if the floating-point kernels are capable of detecting overflow yield the same ±inf result."""
900
+
901
+ np.random.seed()
902
+ a = np.random.randn(ndim)
903
+ b = np.random.randn(ndim)
904
+
905
+ # Replace scalar at random position with infinity
906
+ a[np.random.randint(ndim)] = np.inf
907
+ a = a.astype(dtype)
908
+ b = b.astype(dtype)
909
+
910
+ keep_one_capability(capability)
911
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
912
+ result = simd_kernel(a, b)
913
+ assert np.isinf(result), f"Expected ±inf, but got {result}"
914
+
915
+ #! In the Euclidean (L2) distance, SciPy raises a `ValueError` from the underlying
916
+ #! NumPy function: `ValueError: array must not contain infs or NaNs`.
917
+ try:
918
+ expected_overflow = baseline_kernel(a, b)
919
+ if not np.isinf(expected_overflow):
920
+ collect_warnings("Overflow not detected in SciPy", stats_fixture)
921
+ except Exception as e:
922
+ collect_warnings(f"Arbitrary error raised in SciPy: {e}", stats_fixture)
923
+
924
+
925
+ @pytest.mark.skip(reason="Lacks overflow protection: https://github.com/ashvardanian/SimSIMD/issues/206") # TODO
926
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
927
+ @pytest.mark.repeat(50)
928
+ @pytest.mark.parametrize("ndim", [131072, 262144])
929
+ @pytest.mark.parametrize("metric", ["inner", "euclidean", "sqeuclidean", "cosine"])
930
+ @pytest.mark.parametrize("capability", possible_capabilities)
931
+ def test_overflow_i8(ndim, metric, capability):
932
+ """Tests if the integral kernels are capable of detecting overflow yield the same ±inf result,
933
+ as with 2^16 elements accumulating "u32(u16(u8)*u16(u8))+u32" products should overflow and the
934
+ same is true for 2^17 elements with "i32(i15(i8))*i32(i15(i8))" products.
935
+ """
936
+
937
+ np.random.seed()
938
+ a = np.full(ndim, fill_value=-128, dtype=np.int8)
939
+ b = np.full(ndim, fill_value=-128, dtype=np.int8)
940
+
941
+ keep_one_capability(capability)
942
+ baseline_kernel, simd_kernel = name_to_kernels(metric)
943
+ expected = baseline_kernel(a, b)
944
+ result = simd_kernel(a, b)
945
+ assert np.isinf(result), f"Expected ±inf, but got {result}"
946
+
947
+ try:
948
+ expected_overflow = baseline_kernel(a, b)
949
+ if not np.isinf(expected_overflow):
950
+ collect_warnings("Overflow not detected in SciPy", stats_fixture)
951
+ except Exception as e:
952
+ collect_warnings(f"Arbitrary error raised in SciPy: {e}", stats_fixture)
953
+
954
+
955
+ @pytest.mark.skipif(is_running_under_qemu(), reason="Complex math in QEMU fails")
956
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
957
+ @pytest.mark.repeat(50)
958
+ @pytest.mark.parametrize("ndim", [22, 66, 1536])
959
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
960
+ @pytest.mark.parametrize("capability", possible_capabilities)
961
+ def test_dot_complex(ndim, dtype, capability, stats_fixture):
962
+ """Compares the simd.dot() and simd.vdot() against NumPy for complex numbers."""
963
+ np.random.seed()
964
+ dtype_view = np.complex64 if dtype == "float32" else np.complex128
965
+ a = np.random.randn(ndim).astype(dtype=dtype).view(dtype_view)
966
+ b = np.random.randn(ndim).astype(dtype=dtype).view(dtype_view)
967
+
968
+ keep_one_capability(capability)
969
+ accurate_dt, accurate = profile(np.dot, a.astype(np.complex128), b.astype(np.complex128))
970
+ expected_dt, expected = profile(np.dot, a, b)
971
+ result_dt, result = profile(simd.dot, a, b)
972
+ result = np.array(result)
973
+
974
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
975
+ collect_errors(
976
+ "dot", ndim, dtype + "c", accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture
977
+ )
978
+
979
+ accurate_dt, accurate = profile(np.vdot, a.astype(np.complex128), b.astype(np.complex128))
980
+ expected_dt, expected = profile(np.vdot, a, b)
981
+ result_dt, result = profile(simd.vdot, a, b)
982
+ result = np.array(result)
983
+
984
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
985
+ collect_errors(
986
+ "vdot", ndim, dtype + "c", accurate, accurate_dt, expected, expected_dt, result, result_dt, stats_fixture
987
+ )
988
+
989
+
990
+ @pytest.mark.skipif(is_running_under_qemu(), reason="Complex math in QEMU fails")
991
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
992
+ @pytest.mark.repeat(50)
993
+ @pytest.mark.parametrize("ndim", [22, 66, 1536])
994
+ @pytest.mark.parametrize("capability", possible_capabilities)
995
+ def test_dot_complex_explicit(ndim, capability):
996
+ """Compares the simd.dot() and simd.vdot() against NumPy for complex numbers."""
997
+ np.random.seed()
998
+ a = np.random.randn(ndim).astype(dtype=np.float32)
999
+ b = np.random.randn(ndim).astype(dtype=np.float32)
1000
+
1001
+ keep_one_capability(capability)
1002
+ expected = np.dot(a.view(np.complex64), b.view(np.complex64))
1003
+ result = simd.dot(a, b, "complex64")
1004
+
1005
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1006
+
1007
+ expected = np.vdot(a.view(np.complex64), b.view(np.complex64))
1008
+ result = simd.vdot(a, b, "complex64")
1009
+
1010
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1011
+
1012
+
1013
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1014
+ @pytest.mark.repeat(100)
1015
+ @pytest.mark.parametrize("dtype", ["uint16", "uint32"])
1016
+ @pytest.mark.parametrize("first_length_bound", [10, 100, 1000])
1017
+ @pytest.mark.parametrize("second_length_bound", [10, 100, 1000])
1018
+ @pytest.mark.parametrize("capability", possible_capabilities)
1019
+ def test_intersect(dtype, first_length_bound, second_length_bound, capability):
1020
+ """Compares the simd.intersect() function with numpy.intersect1d."""
1021
+
1022
+ if is_running_under_qemu() and (platform.machine() == "aarch64" or platform.machine() == "arm64"):
1023
+ pytest.skip("In QEMU `aarch64` emulation on `x86_64` the `intersect` function is not reliable")
1024
+
1025
+ np.random.seed()
1026
+
1027
+ a_length = np.random.randint(1, first_length_bound)
1028
+ b_length = np.random.randint(1, second_length_bound)
1029
+ a = np.random.randint(first_length_bound * 2, size=a_length, dtype=dtype)
1030
+ b = np.random.randint(second_length_bound * 2, size=b_length, dtype=dtype)
1031
+
1032
+ # Remove duplicates, converting into sorted arrays
1033
+ a = np.unique(a)
1034
+ b = np.unique(b)
1035
+
1036
+ keep_one_capability(capability)
1037
+ expected = baseline_intersect(a, b)
1038
+ result = simd.intersect(a, b)
1039
+
1040
+ assert round(float(expected)) == round(float(result)), f"Missing {np.intersect1d(a, b)} from {a} and {b}"
1041
+
1042
+
1043
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1044
+ @pytest.mark.repeat(50)
1045
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1046
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "float16", "int8", "uint8"])
1047
+ @pytest.mark.parametrize("kernel", ["fma"])
1048
+ @pytest.mark.parametrize("capability", possible_capabilities)
1049
+ def test_fma(ndim, dtype, kernel, capability, stats_fixture):
1050
+ """"""
1051
+
1052
+ if dtype == "float16" and is_running_under_qemu():
1053
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
1054
+
1055
+ np.random.seed()
1056
+ if np.issubdtype(np.dtype(dtype), np.integer):
1057
+ dtype_info = np.iinfo(np.dtype(dtype))
1058
+ a = np.random.randint(dtype_info.min, dtype_info.max, size=ndim, dtype=dtype)
1059
+ b = np.random.randint(dtype_info.min, dtype_info.max, size=ndim, dtype=dtype)
1060
+ c = np.random.randint(dtype_info.min, dtype_info.max, size=ndim, dtype=dtype)
1061
+ alpha = abs(np.random.randn(1).astype(np.float64).item()) / 512
1062
+ beta = abs(np.random.randn(1).astype(np.float64).item()) / 3
1063
+ atol = 1 # ? Allow at most one rounding error per vector
1064
+ rtol = 0
1065
+ else:
1066
+ a = np.random.randn(ndim).astype(dtype)
1067
+ b = np.random.randn(ndim).astype(dtype)
1068
+ c = np.random.randn(ndim).astype(dtype)
1069
+ alpha = np.random.randn(1).astype(np.float64).item()
1070
+ beta = np.random.randn(1).astype(np.float64).item()
1071
+ atol = SIMSIMD_ATOL
1072
+ rtol = SIMSIMD_RTOL
1073
+
1074
+ keep_one_capability(capability)
1075
+ baseline_kernel, simd_kernel = name_to_kernels(kernel)
1076
+
1077
+ accurate_dt, accurate = profile(
1078
+ baseline_kernel,
1079
+ a.astype(np.float64),
1080
+ b.astype(np.float64),
1081
+ c.astype(np.float64),
1082
+ alpha=alpha,
1083
+ beta=beta,
1084
+ )
1085
+ expected_dt, expected = profile(baseline_kernel, a, b, c, alpha=alpha, beta=beta)
1086
+ result_dt, result = profile(simd_kernel, a, b, c, alpha=alpha, beta=beta)
1087
+ result = np.array(result)
1088
+
1089
+ np.testing.assert_allclose(result, expected.astype(np.float64), atol=atol, rtol=rtol)
1090
+ collect_errors(
1091
+ kernel,
1092
+ ndim,
1093
+ dtype,
1094
+ accurate,
1095
+ accurate_dt,
1096
+ expected,
1097
+ expected_dt,
1098
+ result,
1099
+ result_dt,
1100
+ stats_fixture,
1101
+ )
1102
+
1103
+
1104
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1105
+ @pytest.mark.repeat(50)
1106
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1107
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "float16", "int8", "uint8"])
1108
+ @pytest.mark.parametrize("kernel", ["wsum"])
1109
+ @pytest.mark.parametrize("capability", possible_capabilities)
1110
+ def test_wsum(ndim, dtype, kernel, capability, stats_fixture):
1111
+ """"""
1112
+
1113
+ if dtype == "float16" and is_running_under_qemu():
1114
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
1115
+
1116
+ np.random.seed()
1117
+ if np.issubdtype(np.dtype(dtype), np.integer):
1118
+ dtype_info = np.iinfo(np.dtype(dtype))
1119
+ a = np.random.randint(dtype_info.min, dtype_info.max, size=ndim, dtype=dtype)
1120
+ b = np.random.randint(dtype_info.min, dtype_info.max, size=ndim, dtype=dtype)
1121
+ alpha = abs(np.random.randn(1).astype(np.float64).item()) / 2
1122
+ beta = abs(np.random.randn(1).astype(np.float64).item()) / 2
1123
+ atol = 1 # ? Allow at most one rounding error per vector
1124
+ rtol = 0
1125
+ else:
1126
+ a = np.random.randn(ndim).astype(dtype)
1127
+ b = np.random.randn(ndim).astype(dtype)
1128
+ alpha = np.random.randn(1).astype(np.float64).item()
1129
+ beta = np.random.randn(1).astype(np.float64).item()
1130
+ atol = SIMSIMD_ATOL
1131
+ rtol = SIMSIMD_RTOL
1132
+
1133
+ keep_one_capability(capability)
1134
+ baseline_kernel, simd_kernel = name_to_kernels(kernel)
1135
+
1136
+ accurate_dt, accurate = profile(
1137
+ baseline_kernel,
1138
+ a.astype(np.float64),
1139
+ b.astype(np.float64),
1140
+ alpha=alpha,
1141
+ beta=beta,
1142
+ )
1143
+ expected_dt, expected = profile(baseline_kernel, a, b, alpha=alpha, beta=beta)
1144
+ result_dt, result = profile(simd_kernel, a, b, alpha=alpha, beta=beta)
1145
+ result = np.array(result)
1146
+
1147
+ np.testing.assert_allclose(result, expected.astype(np.float64), atol=atol, rtol=rtol)
1148
+ collect_errors(
1149
+ kernel,
1150
+ ndim,
1151
+ dtype,
1152
+ accurate,
1153
+ accurate_dt,
1154
+ expected,
1155
+ expected_dt,
1156
+ result,
1157
+ result_dt,
1158
+ stats_fixture,
1159
+ )
1160
+
1161
+
1162
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1163
+ @pytest.mark.skipif(not scipy_available, reason="SciPy is not installed")
1164
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1165
+ @pytest.mark.parametrize("dtype", ["float64", "float32", "float16"])
1166
+ @pytest.mark.parametrize("capability", possible_capabilities)
1167
+ def test_batch(ndim, dtype, capability):
1168
+ """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."""
1169
+
1170
+ if dtype == "float16" and is_running_under_qemu():
1171
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
1172
+
1173
+ np.random.seed()
1174
+ keep_one_capability(capability)
1175
+
1176
+ # Distance between matrixes A (N x D scalars) and B (N x D scalars) is an array with N floats.
1177
+ A = np.random.randn(10, ndim).astype(dtype)
1178
+ B = np.random.randn(10, ndim).astype(dtype)
1179
+ result_np = [spd.sqeuclidean(A[i], B[i]) for i in range(10)]
1180
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1181
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1182
+
1183
+ # Distance between matrixes A (N x D scalars) and B (1 x D scalars) is an array with N floats.
1184
+ B = np.random.randn(1, ndim).astype(dtype)
1185
+ result_np = [spd.sqeuclidean(A[i], B[0]) for i in range(10)]
1186
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1187
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1188
+
1189
+ # Distance between matrixes A (1 x D scalars) and B (N x D scalars) is an array with N floats.
1190
+ A = np.random.randn(1, ndim).astype(dtype)
1191
+ B = np.random.randn(10, ndim).astype(dtype)
1192
+ result_np = [spd.sqeuclidean(A[0], B[i]) for i in range(10)]
1193
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1194
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1195
+
1196
+ # Distance between matrix A (N x D scalars) and array B (D scalars) is an array with N floats.
1197
+ A = np.random.randn(10, ndim).astype(dtype)
1198
+ B = np.random.randn(ndim).astype(dtype)
1199
+ result_np = [spd.sqeuclidean(A[i], B) for i in range(10)]
1200
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1201
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1202
+
1203
+ # Distance between matrix B (N x D scalars) and array A (D scalars) is an array with N floats.
1204
+ B = np.random.randn(10, ndim).astype(dtype)
1205
+ A = np.random.randn(ndim).astype(dtype)
1206
+ result_np = [spd.sqeuclidean(B[i], A) for i in range(10)]
1207
+ result_simd = np.array(simd.sqeuclidean(B, A)).astype(np.float64)
1208
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1209
+
1210
+ # Distance between matrixes A (N x D scalars) and B (N x D scalars) in slices of bigger matrices.
1211
+ A_extended = np.random.randn(10, ndim + 11).astype(dtype)
1212
+ B_extended = np.random.randn(10, ndim + 13).astype(dtype)
1213
+ A = A_extended[:, 1 : 1 + ndim]
1214
+ B = B_extended[:, 3 : 3 + ndim]
1215
+ assert A.base is A_extended and B.base is B_extended
1216
+ assert A.__array_interface__["strides"] is not None and B.__array_interface__["strides"] is not None
1217
+ result_np = [spd.sqeuclidean(A[i], B[i]) for i in range(10)]
1218
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1219
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1220
+
1221
+ # Distance between matrixes A (N x D scalars) and B (N x D scalars) in a transposed matrix.
1222
+ #! This requires calling `np.ascontiguousarray()` to ensure the matrix is in the right format.
1223
+ A = np.random.randn(10, ndim).astype(dtype)
1224
+ B = np.ascontiguousarray(np.random.randn(ndim, 10).astype(dtype).T)
1225
+ result_np = [spd.sqeuclidean(A[i], B[i]) for i in range(10)]
1226
+ result_simd = np.array(simd.sqeuclidean(A, B)).astype(np.float64)
1227
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1228
+
1229
+ # Distance between matrixes A (N x D scalars) and B (N x D scalars) with a differnt output type.
1230
+ A = np.random.randn(10, ndim).astype(dtype)
1231
+ B = np.random.randn(10, ndim).astype(dtype)
1232
+ result_np = np.array([spd.sqeuclidean(A[i], B[i]) for i in range(10)]).astype(np.float32)
1233
+ result_simd = np.array(simd.sqeuclidean(A, B, out_dtype="float32"))
1234
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1235
+ assert result_simd.dtype == result_np.dtype
1236
+
1237
+ # Distance between matrixes A (N x D scalars) and B (N x D scalars) with a supplied output buffer.
1238
+ A = np.random.randn(10, ndim).astype(dtype)
1239
+ B = np.random.randn(10, ndim).astype(dtype)
1240
+ result_np = np.array([spd.sqeuclidean(A[i], B[i]) for i in range(10)]).astype(np.float32)
1241
+ result_simd = np.zeros(10, dtype=np.float32)
1242
+ assert simd.sqeuclidean(A, B, out=result_simd) is None
1243
+ assert np.allclose(result_simd, result_np, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1244
+ assert result_simd.dtype == result_np.dtype
1245
+
1246
+
1247
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1248
+ @pytest.mark.skipif(not scipy_available, reason="SciPy is not installed")
1249
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1250
+ @pytest.mark.parametrize("input_dtype", ["float32", "float16"])
1251
+ @pytest.mark.parametrize("out_dtype", [None, "float32", "int32"])
1252
+ @pytest.mark.parametrize("metric", ["cosine", "sqeuclidean"])
1253
+ @pytest.mark.parametrize("capability", possible_capabilities)
1254
+ def test_cdist(ndim, input_dtype, out_dtype, metric, capability):
1255
+ """Compares the simd.cdist() function with scipy.spatial.distance.cdist(), measuring the accuracy error for f16, and f32 types using sqeuclidean and cosine metrics."""
1256
+
1257
+ if input_dtype == "float16" and is_running_under_qemu():
1258
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
1259
+
1260
+ np.random.seed()
1261
+ keep_one_capability(capability)
1262
+
1263
+ # We will work with random matrices A (M x D) and B (N x D).
1264
+ # To test their ability to handle strided inputs, we are going to add one extra dimension.
1265
+ M, N = 10, 15
1266
+ A_extended = np.random.randn(M, ndim + 1).astype(input_dtype)
1267
+ B_extended = np.random.randn(N, ndim + 3).astype(input_dtype)
1268
+ A = A_extended[:, :ndim]
1269
+ B = B_extended[:, :ndim]
1270
+
1271
+ if out_dtype is None:
1272
+ expected = spd.cdist(A, B, metric)
1273
+ result = simd.cdist(A, B, metric)
1274
+ #! Same functions can be used in-place, but SciPy doesn't support misaligned outputs
1275
+ expected_out = np.zeros((M, N))
1276
+ result_out_extended = np.zeros((M, N + 7))
1277
+ result_out = result_out_extended[:, :N]
1278
+ assert spd.cdist(A, B, metric, out=expected_out) is not None
1279
+ assert simd.cdist(A, B, metric, out=result_out) is None
1280
+ else:
1281
+ expected = spd.cdist(A, B, metric).astype(out_dtype)
1282
+ result = simd.cdist(A, B, metric, out_dtype=out_dtype)
1283
+
1284
+ #! Same functions can be used in-place, but SciPy doesn't support misaligned outputs
1285
+ expected_out = np.zeros((M, N), dtype=np.float64)
1286
+ result_out_extended = np.zeros((M, N + 7), dtype=out_dtype)
1287
+ result_out = result_out_extended[:, :N]
1288
+ assert spd.cdist(A, B, metric, out=expected_out) is not None
1289
+ assert simd.cdist(A, B, metric, out=result_out) is None
1290
+ #! Moreover, SciPy supports only double-precision outputs, so we need to downcast afterwards.
1291
+ expected_out = expected_out.astype(out_dtype)
1292
+
1293
+ # Assert they're close.
1294
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1295
+ np.testing.assert_allclose(result_out, expected_out, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1296
+
1297
+
1298
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1299
+ @pytest.mark.skipif(not scipy_available, reason="SciPy is not installed")
1300
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1301
+ @pytest.mark.parametrize("input_dtype", ["float32", "float16"])
1302
+ @pytest.mark.parametrize("out_dtype", [None, "float32", "int32"])
1303
+ @pytest.mark.parametrize("metric", ["cosine", "sqeuclidean"])
1304
+ def test_cdist_itself(ndim, input_dtype, out_dtype, metric):
1305
+ """Compares the simd.cdist(A, A) function with scipy.spatial.distance.cdist(A, A), measuring the accuracy error for f16, and f32 types using sqeuclidean and cosine metrics."""
1306
+
1307
+ if input_dtype == "float16" and is_running_under_qemu():
1308
+ pytest.skip("Testing low-precision math isn't reliable in QEMU")
1309
+
1310
+ np.random.seed()
1311
+
1312
+ A = np.random.randn(10, ndim + 1).astype(input_dtype)
1313
+ if out_dtype is None:
1314
+ expected = spd.cdist(A, A, metric)
1315
+ result = simd.cdist(A, A, metric=metric)
1316
+ else:
1317
+ expected = spd.cdist(A, A, metric).astype(out_dtype)
1318
+ result = simd.cdist(A, A, metric=metric, out_dtype=out_dtype)
1319
+
1320
+ # Assert they're close.
1321
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1322
+
1323
+
1324
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1325
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1326
+ @pytest.mark.parametrize("input_dtype", ["complex128", "complex64"])
1327
+ @pytest.mark.parametrize("out_dtype", [None, "complex128", "complex64"])
1328
+ @pytest.mark.parametrize("metric", ["dot", "vdot"])
1329
+ @pytest.mark.parametrize("capability", possible_capabilities)
1330
+ def test_cdist_complex(ndim, input_dtype, out_dtype, metric, capability):
1331
+ """Compares the simd.cdist() for complex numbers to pure NumPy complex dot-products, as SciPy has no such functionality.
1332
+ The goal is to make sure that addressing multi-component numbers is done properly in both real and imaginary parts.
1333
+ """
1334
+
1335
+ np.random.seed()
1336
+ keep_one_capability(capability)
1337
+
1338
+ # We will work with random matrices A (M x D) and B (N x D).
1339
+ # To test their ability to handle strided inputs, we are going to add one extra dimension.
1340
+ M, N = 10, 15
1341
+ A_extended = np.random.randn(M, ndim + 1).astype(input_dtype)
1342
+ B_extended = np.random.randn(N, ndim + 3).astype(input_dtype)
1343
+ A = A_extended[:, :ndim]
1344
+ B = B_extended[:, :ndim]
1345
+ C_extended = np.random.randn(M, N + 7).astype(out_dtype if out_dtype else np.complex128)
1346
+ C = C_extended[:, :N]
1347
+
1348
+ #! Unlike the `np.dot`, the `np.vdot` flattens multi-dimensional inputs into 1D arrays.
1349
+ #! So to compreare the results we need to manually compute all the dot-products.
1350
+ expected = np.zeros((M, N), dtype=out_dtype if out_dtype else np.complex128)
1351
+ baseline_kernel = np.dot if metric == "dot" else np.vdot
1352
+ for i in range(M):
1353
+ for j in range(N):
1354
+ expected[i, j] = baseline_kernel(A[i], B[j])
1355
+
1356
+ # Compute with SimSIMD:
1357
+ if out_dtype is None:
1358
+ result1d = simd.cdist(A[0], B[0], metric=metric)
1359
+ result2d = simd.cdist(A, B, metric=metric)
1360
+ assert simd.cdist(A, B, metric=metric, out=C) is None
1361
+ else:
1362
+ expected = expected.astype(out_dtype)
1363
+ result1d = simd.cdist(A[0], B[0], metric=metric, out_dtype=out_dtype)
1364
+ result2d = simd.cdist(A, B, metric=metric, out_dtype=out_dtype)
1365
+ assert simd.cdist(A, B, metric=metric, out_dtype=out_dtype, out=C) is None
1366
+
1367
+ # Assert they're close.
1368
+ np.testing.assert_allclose(result1d, expected[0, 0], atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1369
+ np.testing.assert_allclose(result2d, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1370
+ np.testing.assert_allclose(C, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1371
+
1372
+
1373
+ @pytest.mark.skipif(not numpy_available, reason="NumPy is not installed")
1374
+ @pytest.mark.skipif(not scipy_available, reason="SciPy is not installed")
1375
+ @pytest.mark.repeat(50)
1376
+ @pytest.mark.parametrize("ndim", [11, 97, 1536])
1377
+ @pytest.mark.parametrize("out_dtype", [None, "float32", "float16", "int8"])
1378
+ @pytest.mark.parametrize("capability", possible_capabilities)
1379
+ def test_cdist_hamming(ndim, out_dtype, capability):
1380
+ """Compares various SIMD kernels (like Hamming and Jaccard/Tanimoto distances) for dense bit arrays
1381
+ with their NumPy or baseline counterparts, even though, they can't process sub-byte-sized scalars."""
1382
+ np.random.seed()
1383
+ keep_one_capability(capability)
1384
+
1385
+ # Create random matrices A (M x D) and B (N x D).
1386
+ M, N = 10, 15
1387
+ A = np.random.randint(2, size=(M, ndim)).astype(np.uint8)
1388
+ B = np.random.randint(2, size=(N, ndim)).astype(np.uint8)
1389
+ A_bits, B_bits = np.packbits(A, axis=1), np.packbits(B, axis=1)
1390
+
1391
+ if out_dtype is None:
1392
+ # SciPy divides the Hamming distance by the number of dimensions, so we need to multiply it back.
1393
+ expected = spd.cdist(A, B, "hamming") * ndim
1394
+ result = simd.cdist(A_bits, B_bits, metric="hamming", dtype="b8")
1395
+ else:
1396
+ expected = (spd.cdist(A, B, "hamming") * ndim).astype(out_dtype)
1397
+ result = simd.cdist(A_bits, B_bits, metric="hamming", dtype="b8", out_dtype=out_dtype)
1398
+
1399
+ np.testing.assert_allclose(result, expected, atol=SIMSIMD_ATOL, rtol=SIMSIMD_RTOL)
1400
+
1401
+
1402
+ if __name__ == "__main__":
1403
+ pytest.main(
1404
+ [
1405
+ "-s", # Print stdout
1406
+ "-x", # Stop on first failure
1407
+ "-v", # Verbose output
1408
+ "--tb=short", # Short traceback format
1409
+ ]
1410
+ )