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