From df4eaa543d5662ea752f0ff015c4cc5d5aa0a9d5 Mon Sep 17 00:00:00 2001 From: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:57:40 +0000 Subject: [PATCH] fix: stabilize exact cosine distances for extreme float32 vectors --- Cargo.lock | 159 +- Cargo.toml | 5 + python/Cargo.toml | 2 + python/python/tests/test_query.py | 62 + rust/lancedb/vendor/lance-linalg/Cargo.toml | 71 + rust/lancedb/vendor/lance-linalg/LICENSE | 255 ++ .../vendor/lance-linalg/README.lancedb.md | 14 + rust/lancedb/vendor/lance-linalg/README.md | 4 + .../vendor/lance-linalg/benches/argmin.rs | 65 + .../lance-linalg/benches/batch_distance.rs | 76 + .../vendor/lance-linalg/benches/cosine.rs | 153 + .../vendor/lance-linalg/benches/dist_table.rs | 66 + .../vendor/lance-linalg/benches/dot.rs | 190 + .../lancedb/vendor/lance-linalg/benches/l2.rs | 194 + .../vendor/lance-linalg/benches/norm_l2.rs | 133 + rust/lancedb/vendor/lance-linalg/build.rs | 327 ++ .../proptest-regressions/distance/cosine.txt | 8 + .../vendor/lance-linalg/src/clustering.rs | 41 + .../vendor/lance-linalg/src/distance.rs | 1147 ++++++ .../vendor/lance-linalg/src/distance/arrow.rs | 260 ++ .../lance-linalg/src/distance/cosine.rs | 1646 +++++++++ .../lance-linalg/src/distance/cosine_u8.rs | 357 ++ .../vendor/lance-linalg/src/distance/dot.rs | 1265 +++++++ .../lance-linalg/src/distance/dot_f16.rs | 1299 +++++++ .../lance-linalg/src/distance/dot_u8.rs | 292 ++ .../lance-linalg/src/distance/hamming.rs | 2098 +++++++++++ .../vendor/lance-linalg/src/distance/l2.rs | 1722 +++++++++ .../vendor/lance-linalg/src/distance/l2_u8.rs | 311 ++ .../lance-linalg/src/distance/norm_l2.rs | 787 ++++ .../vendor/lance-linalg/src/kernels.rs | 919 +++++ rust/lancedb/vendor/lance-linalg/src/lib.rs | 22 + rust/lancedb/vendor/lance-linalg/src/simd.rs | 121 + .../vendor/lance-linalg/src/simd/amx_fp16.c | 727 ++++ .../vendor/lance-linalg/src/simd/amx_fp16.rs | 454 +++ .../vendor/lance-linalg/src/simd/bf16.c | 74 + .../vendor/lance-linalg/src/simd/dist_table.c | 60 + .../lance-linalg/src/simd/dist_table.rs | 3154 +++++++++++++++++ .../vendor/lance-linalg/src/simd/f16.c | 145 + .../vendor/lance-linalg/src/simd/f32.rs | 1363 +++++++ .../vendor/lance-linalg/src/simd/f64.rs | 1058 ++++++ .../vendor/lance-linalg/src/simd/i32.rs | 467 +++ .../vendor/lance-linalg/src/simd/u8.rs | 464 +++ .../vendor/lance-linalg/src/simd/x86.rs | 89 + .../vendor/lance-linalg/src/test_utils.rs | 183 + .../lance-linalg/tests/panic_location.rs | 72 + 45 files changed, 22375 insertions(+), 6 deletions(-) create mode 100644 rust/lancedb/vendor/lance-linalg/Cargo.toml create mode 100644 rust/lancedb/vendor/lance-linalg/LICENSE create mode 100644 rust/lancedb/vendor/lance-linalg/README.lancedb.md create mode 100644 rust/lancedb/vendor/lance-linalg/README.md create mode 100644 rust/lancedb/vendor/lance-linalg/benches/argmin.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/batch_distance.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/cosine.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/dist_table.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/dot.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/l2.rs create mode 100644 rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs create mode 100644 rust/lancedb/vendor/lance-linalg/build.rs create mode 100644 rust/lancedb/vendor/lance-linalg/proptest-regressions/distance/cosine.txt create mode 100644 rust/lancedb/vendor/lance-linalg/src/clustering.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/cosine_u8.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/dot.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/dot_f16.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/dot_u8.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/l2.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/l2_u8.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/kernels.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/lib.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.c create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/bf16.c create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/dist_table.c create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/dist_table.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/f16.c create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/f32.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/f64.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/i32.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/u8.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/simd/x86.rs create mode 100644 rust/lancedb/vendor/lance-linalg/src/test_utils.rs create mode 100644 rust/lancedb/vendor/lance-linalg/tests/panic_location.rs diff --git a/Cargo.lock b/Cargo.lock index 11968b42c..baaa7f564 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1380,7 +1380,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ - "bit-vec", + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", ] [[package]] @@ -1389,6 +1398,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -1463,6 +1482,30 @@ dependencies = [ "generic-array", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases 0.2.1", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "brotli" version = "3.5.0" @@ -2048,6 +2091,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "countio" version = "0.3.0" @@ -3517,7 +3566,7 @@ version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8" dependencies = [ - "bit-set", + "bit-set 0.8.0", "regex-automata", "regex-syntax", ] @@ -3528,7 +3577,7 @@ version = "0.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912" dependencies = [ - "bit-set", + "bit-set 0.8.0", "regex-automata", "regex-syntax", ] @@ -5760,17 +5809,23 @@ dependencies = [ [[package]] name = "lance-linalg" version = "15.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.13#6eef95cf4552e3f904f9222cbd3719504dede0cf" dependencies = [ + "approx", "argminmax 0.7.1", "arrow-array", + "arrow-buffer", "arrow-schema", "cc", + "criterion", "half", "lance-arrow", "lance-core", + "lance-testing", "num-traits", + "proptest", + "rand 0.9.5", "rayon", + "rstest 0.26.1", ] [[package]] @@ -6005,7 +6060,7 @@ dependencies = [ "regex", "reqwest 0.13.5", "roaring", - "rstest", + "rstest 0.23.0", "semver", "serde", "serde_json", @@ -6122,6 +6177,7 @@ dependencies = [ "lance-arrow", "lance-core", "lance-io", + "lance-linalg", "lance-namespace", "lance-namespace-impls", "lancedb", @@ -8501,6 +8557,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.1", + "bitflags 2.11.1", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.1", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "prost" version = "0.14.4" @@ -8686,6 +8762,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-xml" version = "0.26.0" @@ -8934,6 +9016,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rand_xoshiro" version = "0.7.0" @@ -9564,10 +9655,21 @@ checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035" dependencies = [ "futures", "futures-timer", - "rstest_macros", + "rstest_macros 0.23.0", "rustc_version", ] +[[package]] +name = "rstest" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49" +dependencies = [ + "futures-timer", + "futures-util", + "rstest_macros 0.26.1", +] + [[package]] name = "rstest_macros" version = "0.23.0" @@ -9586,6 +9688,24 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "rstest_macros" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" +dependencies = [ + "cfg-if 1.0.4", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.117", + "unicode-ident", +] + [[package]] name = "rust-ini" version = "0.21.3" @@ -9726,6 +9846,18 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "rustyline" version = "14.0.0" @@ -11414,6 +11546,12 @@ version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "214ca0b2191785cbc06209b9ca1861e048e39b5ba33574b3cedd58363d5bb5f6" +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicase" version = "2.9.0" @@ -11600,6 +11738,15 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index 468eb04d3..d042a78cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "rust/lancedb/cli", "rust/lancedb", + "rust/lancedb/vendor/lance-linalg", "nodejs", "python", "docs/web-tests/blob-v2/rs", @@ -98,6 +99,10 @@ chrono = { version = "0.4", default-features = false, features = ["clock"] } # Lance v14.0.0-beta.18 requires multipart write modes from this upstream revision. object_store = { git = "https://github.com/apache/arrow-rs-object-store.git", rev = "c10758c207c0103355f940f0c736fb8ecb157b04" } +# Keep the pinned Lance release and patch only FLOAT32 cosine range handling. +[patch."https://github.com/lance-format/lance.git"] +lance-linalg = { path = "rust/lancedb/vendor/lance-linalg" } + [profile.ci] debug = "line-tables-only" inherits = "dev" diff --git a/python/Cargo.toml b/python/Cargo.toml index 2118ab6e7..df3ce65bf 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -22,6 +22,8 @@ bytes.workspace = true lancedb.workspace = true datafusion-common.workspace = true lance-core.workspace = true +# Maturin includes path dependencies in source distributions; retain the cosine patch. +lance-linalg = { path = "../rust/lancedb/vendor/lance-linalg" } lance-arrow.workspace = true lance-namespace.workspace = true lance-namespace-impls.workspace = true diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 95148dcf9..40cfb9cdc 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1383,6 +1383,68 @@ def test_query_builder_with_metric(table): assert 0 <= df_cosine._distance[0] <= 1 +@pytest.mark.parametrize("dimension", [2, 8, 16, 33]) +@pytest.mark.parametrize( + "candidate_scale,query_scale", + [ + (1e20, 1.0), + (1e-30, 1e-30), + (1e-20, 1e-20), + (np.finfo(np.float32).max, 1.0), + (np.nextafter(np.float32(0), np.float32(1)), 1e-30), + (1.0, np.finfo(np.float32).max), + ], +) +@pytest.mark.asyncio +async def test_exact_cosine_extreme_float32( + tmp_path, dimension, candidate_scale, query_scale +): + vectors = np.zeros((2, dimension), dtype=np.float32) + vectors[0, 0] = candidate_scale + vectors[1, :2] = [0.5, 0.8660254] + query = np.zeros(dimension, dtype=np.float32) + query[0] = query_scale + data = pa.table( + { + "id": [0, 1], + "vector": pa.array( + vectors.tolist(), type=pa.list_(pa.float32(), dimension) + ), + } + ) + table = lancedb.connect(tmp_path).create_table("vectors", data) + # Compute the reference from the actual FLOAT32 inputs using FLOAT64 arithmetic. + wide_vectors = vectors.astype(np.float64) + wide_query = query.astype(np.float64) + expected = 1 - (wide_vectors @ wide_query) / ( + np.linalg.norm(wide_vectors, axis=1) * np.linalg.norm(wide_query) + ) + + def check(result): + assert result["id"].to_pylist() == [0, 1] + distances = result["_distance"].to_numpy() + assert np.isfinite(distances).all() + np.testing.assert_allclose(distances, expected, atol=1e-6) + assert result["vector"].combine_chunks().equals(data["vector"].combine_chunks()) + + check( + table.search(query) + .distance_type("cosine") + .bypass_vector_index() + .limit(2) + .to_arrow() + ) + async_db = await lancedb.connect_async(tmp_path) + async_table = await async_db.open_table("vectors") + check( + await async_table.vector_search(query) + .distance_type("cosine") + .bypass_vector_index() + .limit(2) + .to_arrow() + ) + + def test_query_builder_with_different_vector_column(): table = mock.MagicMock(spec=LanceTable) query = [4, 8] diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml new file mode 100644 index 000000000..e951fbf11 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -0,0 +1,71 @@ +[package] +name = "lance-linalg" +version = "15.0.0-beta.13" +publish = false +edition = { workspace = true } +license = { workspace = true } +repository = "https://github.com/lance-format/lance" +description = "Arrow native linear algebra algorithms for Lance" +readme = "README.md" +keywords = { workspace = true } +categories = { workspace = true } + +[dependencies] +argminmax = "0.7.1" +arrow-array = { workspace = true } +arrow-schema = { workspace = true } +half = { workspace = true } +lance-arrow = { workspace = true } +lance-core = { workspace = true } +num-traits = { workspace = true } +rayon = "1.10" + +[dev-dependencies] +approx = "0.5.1" +arrow-buffer = { workspace = true } +criterion = { version = "0.8.2", features = ["async", "async_tokio", "html_reports"] } +lance-testing = { workspace = true } +proptest = "1.3.1" +rand = { workspace = true } +rstest = "0.26.1" + +[build-dependencies] +cc = "1.0.83" + +[features] +# Enable compiling multiple C kernels for fp16 SIMD computations. +# This requires GCC 12 / Clang 6 or later. (To get AVX-512 support, +# you need Clang 11 or later.) +fp16kernels = [] + +[[bench]] +name = "l2" +harness = false + +[[bench]] +name = "dot" +harness = false + +[[bench]] +name = "argmin" +harness = false + +[[bench]] +name = "cosine" +harness = false + +[[bench]] +name = "norm_l2" +harness = false + +[[bench]] +name = "dist_table" +harness = false + +[[bench]] +name = "batch_distance" +harness = false + +[lints.rust] +unsafe_op_in_unsafe_fn = "allow" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage,coverage_nightly)"] } diff --git a/rust/lancedb/vendor/lance-linalg/LICENSE b/rust/lancedb/vendor/lance-linalg/LICENSE new file mode 100644 index 000000000..cd4c38213 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/LICENSE @@ -0,0 +1,255 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- + +This project includes code from Ritchie Vink's Polars project, which is licensed +under the MIT license: + + Copyright (c) 2020 Ritchie Vink + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +https://github.com/pola-rs/polars/blob/main/LICENSE + +-------------------------------------------------------------------------------- + +This project includes code adapted from the quickwit-oss/bitpacking crate, which +is licensed under the MIT license: + + Copyright (c) 2016 Paul Masurel + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + +https://github.com/quickwit-oss/bitpacking/blob/main/LICENSE diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md new file mode 100644 index 000000000..af8ea6451 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -0,0 +1,14 @@ +This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.13` +(commit `6eef95cf4552e3f904f9222cbd3719504dede0cf`), licensed under Apache-2.0. + +LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances +in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary +vectors retain the existing SIMD kernels. The root Cargo patch applies to all +Lance callers, including exact scans and cached-norm distance calculations. The +private Python binding crate also references the local path so Maturin includes +the patch in source distributions. The public Rust workspace dependency keeps +its Git pin to preserve type identity for downstream Cargo consumers. + +The manifest resolves dependencies in the LanceDB workspace, disables +publication, and preserves the upstream Rust lint configuration. Other source files are unchanged. Remove +this copy and the Cargo patch once the pinned Lance release includes the fix. diff --git a/rust/lancedb/vendor/lance-linalg/README.md b/rust/lancedb/vendor/lance-linalg/README.md new file mode 100644 index 000000000..62b2d1954 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/README.md @@ -0,0 +1,4 @@ +# Lance Linear Algebra Library + +`lance-linalg` is an internal sub-crate, containing [Apache-Arrow](https://github.com/apache/arrow-rs) +native linear algebra algorithms used by [Lance](https://github.com/lance-format/lance). diff --git a/rust/lancedb/vendor/lance-linalg/benches/argmin.rs b/rust/lancedb/vendor/lance-linalg/benches/argmin.rs new file mode 100644 index 000000000..f80ad668a --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/argmin.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::{sync::Arc, time::Duration}; + +use arrow_array::types::Float32Type; +use arrow_array::{Float32Array, UInt32Array}; +use criterion::{Criterion, criterion_group, criterion_main}; +use lance_linalg::kernels::argmin_opt; +use lance_testing::datagen::generate_random_array_with_seed; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +#[inline] +fn argmin_arrow(x: &Float32Array) -> u32 { + argmin_opt(x.iter()).unwrap() +} + +fn argmin_arrow_batch(x: &Float32Array, dimension: usize) -> Arc { + assert_eq!(x.len() % dimension, 0); + + let idxs = unsafe { + UInt32Array::from_trusted_len_iter( + (0..x.len()) + .step_by(dimension) + .map(|start| Some(argmin_arrow(&x.slice(start, dimension)))), + ) + }; + Arc::new(idxs) +} + +fn bench_argmin(c: &mut Criterion) { + const DIMENSION: usize = 1024 * 8; + const TOTAL: usize = 1024; + const SEED: [u8; 32] = [42; 32]; + + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, SEED); + + c.bench_function("argmin(arrow)", |b| { + b.iter(|| { + argmin_arrow_batch(&target, DIMENSION); + }) + }); +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default() + .measurement_time(Duration::from_secs(10)) + .sample_size(32) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_argmin); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default() + .measurement_time(Duration::from_secs(10)) + .sample_size(32); + targets = bench_argmin); + +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/batch_distance.rs b/rust/lancedb/vendor/lance-linalg/benches/batch_distance.rs new file mode 100644 index 000000000..a49d7cab3 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/batch_distance.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::hint::black_box; +use std::time::Duration; + +use criterion::{Criterion, criterion_group, criterion_main}; +use lance_linalg::distance::{Cosine, Dot, L2}; + +const DIMENSION: usize = 8; +const TOTAL_VALUES: usize = 1024 * 1024; + +fn bench_batch_distance(c: &mut Criterion) { + let key = (0..DIMENSION) + .map(|index| index as f32 * 0.125 + 0.25) + .collect::>(); + let batch = (0..TOTAL_VALUES) + .map(|index| (index % 31) as f32 * 0.03125 - 0.5) + .collect::>(); + let mut output = vec![0.0; TOTAL_VALUES / DIMENSION]; + + // Callers pass the dimension at runtime. A constant would let LLVM unroll + // the dim-8 loop only where the kernel inlines into this closure, so the + // comparison would measure inlining rather than the kernel. + c.bench_function("Batch distance dot f32 dim 8", |b| { + b.iter(|| { + ::dot_batch_into( + black_box(&key), + black_box(&batch), + black_box(DIMENSION), + &mut output, + ); + black_box(&mut output); + }) + }); + c.bench_function("Batch distance l2 f32 dim 8", |b| { + b.iter(|| { + ::l2_batch_into( + black_box(&key), + black_box(&batch), + black_box(DIMENSION), + &mut output, + ); + black_box(&mut output); + }) + }); + c.bench_function("Batch distance cosine f32 dim 8", |b| { + b.iter(|| { + ::cosine_batch_into( + black_box(&key), + black_box(&batch), + black_box(DIMENSION), + &mut output, + ); + black_box(&mut output); + }) + }); +} + +fn bench_time() -> Duration { + let seconds = option_env!("TARGET_TIME") + .unwrap_or("5") + .parse() + .expect("TARGET_TIME must be an integer number of seconds"); + Duration::from_secs(seconds) +} + +criterion_group!( + name = benches; + config = Criterion::default() + .significance_level(0.1) + .sample_size(10) + .measurement_time(bench_time()); + targets = bench_batch_distance +); +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/cosine.rs b/rust/lancedb/vendor/lance-linalg/benches/cosine.rs new file mode 100644 index 000000000..ef754d713 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/cosine.rs @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use arrow_array::{ + FixedSizeListArray, Float32Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use lance_arrow::{ArrowFloatType, FixedSizeListArrayExt, FloatArray, bfloat16::BFloat16Type}; +use lance_linalg::distance::DistanceType; +use lance_linalg::distance::cosine::{Cosine, cosine_distance_batch_into}; +use lance_linalg::distance::cosine_u8::{cosine_u8, cosine_u8_scalar}; +use num_traits::Float; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +use lance_testing::datagen::generate_random_array_with_seed; + +fn cosine_scalar(x: &[T], y: &[T], dim: usize) -> Vec { + y.chunks_exact(dim) + .map(|vec| { + let mut dot = T::zero(); + let mut x_norm = T::zero(); + let mut y_norm = T::zero(); + + for (&xi, &yi) in x.iter().zip(vec.iter()) { + dot = dot + xi * yi; + x_norm = x_norm + xi * xi; + y_norm = y_norm + yi * yi; + } + dot / (x_norm * y_norm).sqrt() + }) + .collect() +} + +fn run_bench(c: &mut Criterion) +where + T::Native: Cosine, +{ + const DIMENSION: usize = 1024; + const TOTAL: usize = 512 * 1024; + + let type_name = std::any::type_name::(); + let key = generate_random_array_with_seed::(DIMENSION, [0; 32]); + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + + c.bench_function(format!("Cosine({}, scalar)", type_name).as_str(), |b| { + b.iter(|| { + black_box(cosine_scalar(key.as_slice(), target.as_slice(), DIMENSION)); + }) + }); + + c.bench_function( + format!("Cosine({}, auto-vectorized)", type_name).as_str(), + |b| { + let mut distances = vec![0.0; TOTAL]; + b.iter(|| { + cosine_distance_batch_into( + key.as_slice(), + target.as_slice(), + DIMENSION, + &mut distances, + ); + black_box(&mut distances); + }) + }, + ); +} + +fn bench_distance(c: &mut Criterion) { + run_bench::(c); + run_bench::(c); + run_bench::(c); + run_bench::(c); + + let key: Float32Array = generate_random_array_with_seed::(8, [0; 32]); + let target = generate_random_array_with_seed::(1024 * 1024 * 8, [42; 32]); + + c.bench_function("Cosine(simd,f32x8) rng seed", |b| { + let mut distances = vec![0.0; target.len() / 8]; + b.iter(|| { + cosine_distance_batch_into(key.values(), target.values(), 8, &mut distances); + black_box(&mut distances); + }) + }); + + let target = FixedSizeListArray::try_new_from_values(target, 8).unwrap(); + c.bench_function("Cosine(f32x8, arrow) rng seed", |b| { + b.iter(|| black_box(DistanceType::Cosine.batch(&key, &target).unwrap())) + }); + + // u8 cosine benchmarks + { + use rand::Rng; + use std::iter::repeat_with; + + const DIMENSION: usize = 1024; + const TOTAL: usize = 1024 * 1024; + let mut rng = rand::rng(); + // Slice 64-byte-aligned views out of padded buffers: zmm loads split cache + // lines on misaligned inputs, so results depended on heap placement. + let key_buf: Vec = repeat_with(|| rng.random()).take(DIMENSION + 63).collect(); + let key_u8 = &key_buf[key_buf.as_ptr().align_offset(64)..][..DIMENSION]; + let target_buf: Vec = repeat_with(|| rng.random()) + .take(TOTAL * DIMENSION + 63) + .collect(); + let target_u8 = &target_buf[target_buf.as_ptr().align_offset(64)..][..TOTAL * DIMENSION]; + + c.bench_function("Cosine(u8, scalar)", |b| { + b.iter(|| { + black_box( + target_u8 + .as_chunks::() + .0 + .iter() + .map(|tgt| cosine_u8_scalar(key_u8, tgt)) + .fold(0.0, |acc: f32, v| acc + v), + ); + }); + }); + + c.bench_function("Cosine(u8, SIMD)", |b| { + b.iter(|| { + black_box( + target_u8 + .as_chunks::() + .0 + .iter() + .map(|tgt| cosine_u8(key_u8, tgt)) + .fold(0.0, |acc: f32, v| acc + v), + ); + }); + }); + } +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_distance); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10); + targets = bench_distance); +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/dist_table.rs b/rust/lancedb/vendor/lance-linalg/benches/dist_table.rs new file mode 100644 index 000000000..954d9b02f --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/dist_table.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Benchmark of 4-bit LUT distance table summation (RaBitQ inner loop). +//! +//! Measures both the dispatched path (NEON on ARM, AVX2 on x86) and the +//! scalar fallback, so the speedup is visible in a single benchmark run. + +use std::iter::repeat_with; + +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use lance_linalg::simd::dist_table::{BATCH_SIZE, sum_4bit_dist_table, sum_4bit_dist_table_scalar}; +use rand::Rng; + +fn bench_sum_4bit_dist_table(c: &mut Criterion) { + let mut rng = rand::rng(); + + // code_len = dim / 8 for 1-bit quantization + for (label, n_vectors, code_len) in [ + ("32vec_dim128", 32_usize, 16_usize), + ("32vec_dim1536", 32, 192), + ("32vec_dim4096", 32, 512), + ("32vec_dim65536", 32, 8192), + ("16Kvec_dim128", 16_000, 16), + ("16Kvec_dim1536", 16_000, 192), + ] { + let n = n_vectors.div_ceil(BATCH_SIZE) * BATCH_SIZE; + + let codes: Vec = repeat_with(|| rng.random::()) + .take(n * code_len) + .collect(); + + let dist_table: Vec = repeat_with(|| rng.random::()) + .take(BATCH_SIZE * code_len) + .collect(); + + let mut dists = vec![0u16; n]; + + // Dispatched path (NEON on ARM, AVX2 on x86) + c.bench_function(&format!("sum_4bit_dist_table/simd/{}", label), |b| { + b.iter(|| { + dists.fill(0); + sum_4bit_dist_table(n, code_len, &codes, &dist_table, &mut dists); + black_box(&dists); + }) + }); + + // Scalar reference path + c.bench_function(&format!("sum_4bit_dist_table/scalar/{}", label), |b| { + b.iter(|| { + dists.fill(0); + sum_4bit_dist_table_scalar(code_len, &codes, &dist_table, &mut dists); + black_box(&dists); + }) + }); + } +} + +criterion_group!( + name = benches; + config = Criterion::default().significance_level(0.1).sample_size(10); + targets = bench_sum_4bit_dist_table +); +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/dot.rs b/rust/lancedb/vendor/lance-linalg/benches/dot.rs new file mode 100644 index 000000000..81e1374d5 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/dot.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::iter::{Sum, repeat_with}; +use std::time::Duration; + +use arrow_array::{ + Float32Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use half::bf16; +use lance_arrow::{ArrowFloatType, FloatArray}; +use num_traits::Float; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +use lance_linalg::distance::dot::{Dot, dot, dot_distance}; +use lance_testing::datagen::generate_random_array_with_seed; +use rand::Rng; + +#[inline] +fn dot_scalar(x: &[T], y: &[T]) -> T { + x.iter().zip(y.iter()).map(|(&xi, &yi)| xi * yi).sum::() +} + +fn run_bench(c: &mut Criterion) +where + T::Native: Dot, +{ + const DIMENSION: usize = 1024; + const TOTAL: usize = 1024 * 1024; // 1M vectors + + let key = generate_random_array_with_seed::(DIMENSION, [0; 32]); + // 1M of 1024 D vectors + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + + let type_name = std::any::type_name::(); + c.bench_function(format!("Dot({type_name}, arrow_artiy)").as_str(), |b| { + b.iter(|| { + >::from_values( + target + .as_slice() + .chunks(DIMENSION) + .map(|arr| dot_scalar(key.as_slice(), arr)) + .collect::>(), + ) + }); + }); + + c.bench_function( + format!("Dot({type_name}, auto-vectorization)").as_str(), + |b| { + let x = key.as_slice(); + b.iter(|| { + Float32Array::from( + target + .as_slice() + .chunks(DIMENSION) + .map(|y| black_box(dot(x, y))) + .collect::>(), + ) + }); + }, + ); + + // TODO: SIMD needs generic specialization +} + +fn bench_distance(c: &mut Criterion) { + const DIMENSION: usize = 1024; + const TOTAL: usize = 1024 * 1024; // 1M vectors + + run_bench::(c); + c.bench_function("Dot(f16, SIMD)", |b| { + let key = generate_random_array_with_seed::(DIMENSION, [0; 32]); + // 1M of 1024 D vectors + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + b.iter(|| unsafe { + let x = key.values().as_ref(); + Float32Array::from_trusted_len_iter((0..target.len() / DIMENSION).map(|idx| { + let y = target.values()[idx * DIMENSION..(idx + 1) * DIMENSION].as_ref(); + Some(dot_distance(x, y)) + })) + }); + }); + + let mut rng = rand::rng(); + let key = repeat_with(|| rng.random::()) + .map(bf16::from_bits) + .take(DIMENSION) + .collect::>(); + let target = repeat_with(|| rng.random::()) + .map(bf16::from_bits) + .take(TOTAL * DIMENSION) + .collect::>(); + c.bench_function("Dot(bf16, auto-vectorization)", |b| { + b.iter(|| { + let x = key.as_slice(); + black_box( + target + .chunks(DIMENSION) + .map(|y| dot_distance(x, y)) + .collect::>(), + ) + }); + }); + + // u8 dot product benchmarks: scalar baseline vs SIMD dispatch + { + use lance_linalg::distance::dot_u8::{dot_u8, dot_u8_scalar}; + + for &dim in &[128, 256, 512, 1024] { + let num_vectors = 1024 * 1024 / dim; // ~1M elements total + let mut rng = rand::rng(); + // Slice 64-byte-aligned views out of padded buffers: zmm loads split cache + // lines on misaligned inputs, so results depended on heap placement. + let key_buf: Vec = (0..dim + 63).map(|_| rng.random()).collect(); + let key_u8 = &key_buf[key_buf.as_ptr().align_offset(64)..][..dim]; + let target_buf: Vec = (0..num_vectors * dim + 63).map(|_| rng.random()).collect(); + let target_u8 = + &target_buf[target_buf.as_ptr().align_offset(64)..][..num_vectors * dim]; + + c.bench_function(&format!("Dot(u8, scalar, dim={dim})"), |b| { + b.iter(|| { + black_box( + target_u8 + .chunks(dim) + .map(|y| dot_u8_scalar(key_u8, y)) + .collect::>(), + ) + }); + }); + + c.bench_function(&format!("Dot(u8, dispatch, dim={dim})"), |b| { + b.iter(|| { + black_box( + target_u8 + .chunks(dim) + .map(|y| dot_u8(key_u8, y)) + .collect::>(), + ) + }); + }); + } + } + + run_bench::(c); + c.bench_function("Dot(f32, SIMD)", |b| { + let key = generate_random_array_with_seed::(DIMENSION, [0; 32]); + // 1M of 1024 D vectors + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + b.iter(|| unsafe { + let x = key.values().as_ref(); + Float32Array::from_trusted_len_iter((0..target.len() / DIMENSION).map(|idx| { + let y = target.values()[idx * DIMENSION..(idx + 1) * DIMENSION].as_ref(); + Some(f32::dot(x, y)) + })) + }); + }); + + run_bench::(c); +} + +fn bench_time() -> Duration { + let secs: u64 = option_env!("TARGET_TIME").unwrap_or("5").parse().unwrap(); + Duration::from_secs(secs) +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default() + .significance_level(0.1) + .sample_size(10) + .measurement_time(bench_time()) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_distance); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10).measurement_time(bench_time()); + targets = bench_distance); + +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/l2.rs b/rust/lancedb/vendor/lance-linalg/benches/l2.rs new file mode 100644 index 000000000..e4fa7ec6f --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/l2.rs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::iter::repeat_with; + +use arrow_array::{ + Float32Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use num_traits::{AsPrimitive, Float}; +use rand::Rng; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +use lance_arrow::{ArrowFloatType, FloatArray}; +use lance_linalg::distance::l2_u8::l2_u8; +use lance_linalg::distance::{L2, l2::l2, l2_distance_batch_into, l2_distance_uint_scalar}; +use lance_testing::datagen::generate_random_array_with_seed; + +const DIMENSION: usize = 1024; +const TOTAL: usize = 1024 * 1024; // 1M vectors + +/// Naive scalar implementation of L2 distance. +fn l2_scalar>(x: &[T], y: &[T]) -> T { + let mut sum = T::zero(); + for (&xi, &yi) in x.iter().zip(y.iter()) { + sum = sum + (xi - yi).powi(2); + } + sum.sqrt() +} + +fn run_bench(c: &mut Criterion) +where + T::Native: L2, +{ + const DIMENSION: usize = 1024; + const TOTAL: usize = 1024 * 1024; // 1M vectors + + let key = generate_random_array_with_seed::(DIMENSION, [0; 32]); + // 1M of 1024 D vectors + let target = generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + + let type_name = std::any::type_name::(); + + c.bench_function(format!("L2({type_name}, scalar)").as_str(), |b| { + b.iter(|| { + black_box( + target + .as_slice() + .chunks(DIMENSION) + .map(|arr| l2_scalar(key.as_slice(), arr).as_()) + .fold(0.0, |acc: f32, v: f32| acc + v), + ) + }); + }); + + c.bench_function( + format!("L2({type_name}, auto-vectorization)").as_str(), + |b| { + b.iter(|| { + black_box( + target + .as_slice() + .chunks(DIMENSION) + .map(|y| black_box(l2(key.as_slice(), y))) + .fold(0.0, |acc: f32, v: f32| acc + v), + ); + }); + }, + ); +} + +fn bench_distance(c: &mut Criterion) { + run_bench::(c); + run_bench::(c); + let key: Float32Array = generate_random_array_with_seed::(DIMENSION, [0; 32]); + let target: Float32Array = + generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + c.bench_function("L2(f32, simd)", |b| { + let mut distances = vec![0.0; TOTAL]; + b.iter(|| { + l2_distance_batch_into(key.values(), target.values(), DIMENSION, &mut distances); + black_box(&mut distances); + }) + }); + + run_bench::(c); +} + +fn bench_small_distance(c: &mut Criterion) { + let key = generate_random_array_with_seed::(8, [5; 32]); + // 1M of 1024 D vectors. 4GB in memory. + let target = generate_random_array_with_seed::(TOTAL * 8, [7; 32]); + c.bench_function("L2(simd,f32x8)", |b| { + let mut distances = vec![0.0; TOTAL]; + b.iter(|| { + l2_distance_batch_into(key.values(), target.values(), 8, &mut distances); + black_box(&mut distances); + }) + }); +} + +fn l2_distance_uint_scalar_auto_vectorized(key: &[u8], target: &[u8]) -> f32 { + let mut sum = 0; + const LANE: usize = 16; + let (x_chunks, x_reminder) = key.as_chunks::(); + let (y_chunks, y_reminder) = target.as_chunks::(); + + for (x, y) in x_chunks.iter().zip(y_chunks) { + let mut s: u32 = 0; + for i in 0..LANE { + s += (x[i].abs_diff(y[i]) as u32).pow(2); + } + sum += s; + } + sum += x_reminder + .iter() + .zip(y_reminder) + .map(|(&x, &y)| (x.abs_diff(y) as u32).pow(2)) + .sum::(); + sum as f32 +} + +fn bench_uint_distance(c: &mut Criterion) { + let mut rng = rand::rng(); + // Slice 64-byte-aligned views out of padded buffers: zmm loads split cache + // lines on misaligned inputs, so results depended on heap placement. + let key_buf = repeat_with(|| rng.random::()) + .take(DIMENSION + 63) + .collect::>(); + let key = &key_buf[key_buf.as_ptr().align_offset(64)..][..DIMENSION]; + let target_buf = repeat_with(|| rng.random::()) + .take(TOTAL * DIMENSION + 63) + .collect::>(); + let target = &target_buf[target_buf.as_ptr().align_offset(64)..][..TOTAL * DIMENSION]; + + c.bench_function("L2(uint8, scalar)", |b| { + b.iter(|| { + black_box( + target + .as_chunks::() + .0 + .iter() + .map(|tgt| l2_distance_uint_scalar(key, tgt)) + .fold(0.0, |acc, v| acc + v), + ); + }); + }); + + c.bench_function("L2(uint8, auto-vectorization)", |b| { + b.iter(|| { + black_box( + target + .as_chunks::() + .0 + .iter() + .map(|tgt| l2_distance_uint_scalar_auto_vectorized(key, tgt)) + .fold(0.0, |acc, v| acc + v), + ); + }); + }); + + c.bench_function("L2(u8, SIMD)", |b| { + b.iter(|| { + black_box( + target + .as_chunks::() + .0 + .iter() + .map(|tgt| l2_u8(key, tgt) as f32) + .fold(0.0, |acc, v| acc + v), + ); + }); + }); +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_distance, bench_small_distance, bench_uint_distance); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10); + targets = bench_distance, bench_small_distance, bench_uint_distance); +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs b/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs new file mode 100644 index 000000000..73b8e5d52 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::iter::repeat_with; + +use arrow_array::{ + Float16Array, Float32Array, Float64Array, + types::{Float16Type, Float32Type, Float64Type}, +}; +use std::hint::black_box; + +use criterion::{Criterion, criterion_group, criterion_main}; +use half::{bf16, f16}; +use num_traits::Float; +use rand::Rng; + +use lance_arrow::{ArrowFloatType, FloatArray, bfloat16::BFloat16Type}; +use lance_linalg::distance::{norm_l2, norm_l2_f64_simd, norm_l2_impl}; +use lance_testing::datagen::generate_random_array_with_seed; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +const DIMENSION: usize = 1024; +const TOTAL: usize = 1024 * 1024; // 1M vectors + +#[allow(clippy::type_complexity)] +fn run_bench( + c: &mut Criterion, + target: &[T::Native], + auto_vec_impl: fn(&[T::Native]) -> f32, + simd_impl: Option f32>, +) where + T::Native: Float, +{ + let type_name = std::any::type_name::(); + + c.bench_function(format!("NormL2({type_name}, scalar)").as_str(), |b| { + b.iter(|| { + target + .chunks(DIMENSION) + .map(|arr| arr.iter().map(|&x| x * x).sum::().sqrt()) + .collect::>() + }); + }); + + c.bench_function( + format!("NormL2({type_name}, auto-vectorization)").as_str(), + |b| { + b.iter(|| { + black_box( + target + .as_chunks::() + .0 + .iter() + .map(|v| auto_vec_impl(v)) + .collect::>(), + ); + }); + }, + ); + + if let Some(simd_impl) = simd_impl { + c.bench_function( + format!("NormL2({type_name}, SIMD)", type_name = type_name).as_str(), + |b| { + b.iter(|| { + black_box( + target + .as_chunks::() + .0 + .iter() + .map(|v| simd_impl(v)) + .collect::>(), + ); + }); + }, + ); + } +} + +fn bench_distance(c: &mut Criterion) { + let mut rng = rand::rng(); + let target = repeat_with(|| rng.random::()) + .map(bf16::from_bits) + .take(TOTAL * DIMENSION) + .collect::>(); + // We currently don't have a SIMD implementation for bf16. + run_bench::(c, &target, norm_l2, None); + + let target: Float16Array = + generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + run_bench::( + c, + target.as_slice(), + norm_l2_impl::, + Some(norm_l2), + ); + + let target: Float32Array = + generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + run_bench::( + c, + target.as_slice(), + norm_l2_impl::, + Some(norm_l2), + ); + + let target: Float64Array = + generate_random_array_with_seed::(TOTAL * DIMENSION, [42; 32]); + run_bench::( + c, + target.as_slice(), + norm_l2_impl::, + Some(norm_l2_f64_simd), + ); +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_distance); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(10); + targets = bench_distance); + +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/build.rs b/rust/lancedb/vendor/lance-linalg/build.rs new file mode 100644 index 000000000..ce1eda75f --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/build.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::env; + +fn main() -> Result<(), String> { + let rust_toolchain = env::var("RUSTUP_TOOLCHAIN") + .or_else(|e| match e { + env::VarError::NotPresent => Ok("stable".into()), + e => Err(e), + }) + .unwrap(); + if rust_toolchain.starts_with("nightly") { + // enable the 'nightly' feature flag + println!("cargo:rustc-cfg=feature=\"nightly\""); + } + + // Let clippy know about our custom cfg attribute + println!( + "cargo::rustc-check-cfg=cfg(kernel_support, values(\"avx512_f16\", \"avx512_bf16\", \"avx512_dist_table\", \"amx_fp16\"))" + ); + println!("cargo::rustc-check-cfg=cfg(simd_fallback)"); + + println!("cargo:rerun-if-changed=src/simd/f16.c"); + println!("cargo:rerun-if-changed=src/simd/bf16.c"); + println!("cargo:rerun-if-changed=src/simd/dist_table.c"); + println!("cargo:rerun-if-changed=src/simd/amx_fp16.c"); + println!("cargo:rerun-if-env-changed=LANCE_AMX_FP16_CC"); + + // Important: we don't use `cfg!(target_arch)` here because that is the target_arch + // for the build script, not the target_arch for the library. Similar story for + // target_os. + let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap(); + let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); + + // Architectures without SIMD kernels back the vector types with plain arrays. + if !matches!(target_arch.as_str(), "x86_64" | "aarch64" | "loongarch64") { + println!("cargo:rustc-cfg=simd_fallback"); + } + + if target_os == "windows" { + println!( + "cargo:warning=fp16 kernels are not supported on Windows. Skipping compilation of kernels." + ); + return Ok(()); + } + + if target_arch == "aarch64" && target_os == "macos" { + // Build a version with NEON + build_f16_with_flags("neon", &["-mtune=apple-m1"]).unwrap(); + build_bf16_with_flags("neon", &["-mtune=apple-m1"]).unwrap(); + } else if target_arch == "aarch64" && target_os == "ios" { + // Build version with NEON + // A13 bionic is the earliest supported iOS SOC + build_f16_with_flags("neon", &["-mtune=apple-a13"]).unwrap(); + build_bf16_with_flags("neon", &["-mtune=apple-a13"]).unwrap(); + } else if target_arch == "aarch64" && (target_os == "linux" || target_os == "android") { + // Build a version with NEON + build_f16_with_flags("neon", &["-march=armv8.2-a+fp16"]).unwrap(); + build_bf16_with_flags("neon", &["-march=armv8.2-a+fp16"]).unwrap(); + } else if target_arch == "x86_64" { + // Build a version with AVX512 + if let Err(err) = build_f16_with_flags("avx512", &["-march=sapphirerapids", "-mavx512fp16"]) + { + // It's likely the compiler doesn't support the sapphirerapids architecture + // Clang 12 and GCC 11 are the first versions with sapphire rapids support + println!( + "cargo:warning=Skipping build of AVX-512 fp16 kernels. Error: {}", + err + ); + } else if cfg!(feature = "fp16kernels") { + // We create a special cfg so that we can detect we have in fact + // generated the AVX512 version of the f16 kernels. + println!("cargo:rustc-cfg=kernel_support=\"avx512_f16\""); + }; + // Build AVX-512 bf16 kernels (sapphirerapids has native vdpbf16ps) + if let Err(err) = + build_bf16_with_flags("avx512", &["-march=sapphirerapids", "-mavx512fp16"]) + { + println!( + "cargo:warning=Skipping build of AVX-512 bf16 kernels. Error: {}", + err + ); + } else if cfg!(feature = "fp16kernels") { + println!("cargo:rustc-cfg=kernel_support=\"avx512_bf16\""); + }; + // Only the ISA the intrinsics need, so the Rust candidate can require + // exactly these features and also run on AVX-512 CPUs without FP16. + if let Err(err) = build_dist_table_with_flags("avx512", &["-mavx512f", "-mavx512bw"]) { + println!( + "cargo:warning=Skipping build of AVX-512 dist_table. Error: {}", + err + ); + } else { + println!("cargo:rustc-cfg=kernel_support=\"avx512_dist_table\""); + }; + // Build the AMX-FP16 batched f16 dot-product kernel (Granite Rapids+). + // + // No cargo feature of its own: whether it can be built is a property of + // the toolchain, not a choice the user makes. `-mamx-fp16` needs clang + // >= 16 or gcc >= 13, so a capable compiler is probed for below; if none + // is found we warn, skip the kernel, and leave `kernel_support` unset. + // + // Linux only: every Rust-side cfg gate on this kernel also demands + // `target_os = "linux"`, and entering it needs XTILEDATA from + // `arch_prctl(ARCH_REQ_XCOMP_PERM)`, which is Linux-specific. + if target_os == "linux" { + if let Err(err) = + build_amx_fp16_with_flags(&["-march=sapphirerapids", "-mamx-fp16", "-mamx-tile"]) + { + println!( + "cargo:warning=Skipping build of AMX-FP16 kernels. Error: {}", + err + ); + } else { + println!("cargo:rustc-cfg=kernel_support=\"amx_fp16\""); + }; + } + // Build a version with AVX + // While GCC doesn't have support for _Float16 until GCC 12, clang + // has support for __fp16 going back to at least clang 6. + // We use haswell since it's the oldest CPUs on AWS. + // Keep the AVX2 L2 reductions lane-partitioned. A single reassociated + // float accumulator can exceed the public 1e-6 relative-error contract + // for long f16 vectors. + if let Err(err) = + build_f16_with_flags("avx2", &["-march=haswell", "-DPRECISE_F16_REDUCTION"]) + { + return Err(format!( + "Unable to build AVX2 f16 kernels. Please use Clang >= 6 or GCC >= 12 or remove the fp16kernels feature. Received error: {}", + err + )); + }; + // Build AVX2 bf16 kernels (bf16-to-f32 is just a shift, auto-vectorizes well) + if let Err(err) = build_bf16_with_flags("avx2", &["-march=haswell"]) { + return Err(format!( + "Unable to build AVX2 bf16 kernels. Received error: {}", + err + )); + }; + // There is no SSE instruction set for f16 -> f32 float conversion + } else if target_arch == "loongarch64" { + // Build a version with LSX and LASX + build_f16_with_flags("lsx", &["-mlsx"]).unwrap(); + build_f16_with_flags("lasx", &["-mlasx"]).unwrap(); + build_bf16_with_flags("lsx", &["-mlsx"]).unwrap(); + build_bf16_with_flags("lasx", &["-mlasx"]).unwrap(); + } else { + // Only error if fp16kernels was explicitly requested on unsupported platform. + // This allows builds on iOS, Android, etc. when the feature is disabled. + // + // Note: We use CARGO_FEATURE_* env var instead of cfg!() because cfg!() + // checks the build script's features, not the library's features. + if env::var("CARGO_FEATURE_FP16KERNELS").is_ok() { + return Err("Unable to build f16 kernels on given target_arch. Please use x86_64 or aarch64 or remove the fp16kernels feature".to_string()); + } + } + Ok(()) +} + +fn build_f16_with_flags(suffix: &str, flags: &[&str]) -> Result<(), cc::Error> { + if cfg!(not(feature = "fp16kernels")) { + println!( + "cargo:warning=fp16kernels feature is not enabled, skipping build of fp16 kernels" + ); + return Ok(()); + } + + let mut builder = cc::Build::new(); + builder + // We use clang #pragma to yields better vectorization + // See https://github.com/lance-format/lance/pull/2885 + // .compiler("clang") + .std("c17") + .file("src/simd/f16.c") + .flag("-ffast-math") + .flag("-funroll-loops") + .flag("-O3") + .flag("-Wall") + // .flag("-Werror") + .flag("-Wextra") + // Pedantic will complain about _Float16 in some versions of GCC + // .flag("-Wpedantic") + // We pass in the suffix to make sure the symbol names are unique + .flag(format!("-DSUFFIX=_{}", suffix).as_str()); + + for flag in flags { + builder.flag(flag); + } + + builder.try_compile(&format!("f16_{}", suffix)) +} + +fn build_bf16_with_flags(suffix: &str, flags: &[&str]) -> Result<(), cc::Error> { + if cfg!(not(feature = "fp16kernels")) { + println!( + "cargo:warning=fp16kernels feature is not enabled, skipping build of bf16 kernels" + ); + return Ok(()); + } + + let mut builder = cc::Build::new(); + builder + .std("c17") + .file("src/simd/bf16.c") + .flag("-ffast-math") + .flag("-funroll-loops") + .flag("-O3") + .flag("-Wall") + .flag("-Wextra") + .flag(format!("-DSUFFIX=_{}", suffix).as_str()); + + for flag in flags { + builder.flag(flag); + } + + builder.try_compile(&format!("bf16_{}", suffix)) +} + +fn build_dist_table_with_flags(suffix: &str, flags: &[&str]) -> Result<(), cc::Error> { + let mut builder = cc::Build::new(); + builder + .std("c17") + .file("src/simd/dist_table.c") + .flag("-funroll-loops") + .flag("-O3") + .flag("-Wall") + .flag("-Wextra") + .flag(format!("-DSUFFIX=_{}", suffix).as_str()); + for flag in flags { + builder.flag(flag); + } + builder.try_compile(&format!("dist_table_{}", suffix)) +} + +/// Compile the AMX-FP16 kernel. Unlike the other kernels this may need a +/// different C compiler: `_tile_dpfp16ps` / `-mamx-fp16` require clang >= 16 or +/// gcc >= 13, which is often newer than the platform default `cc`. We probe for +/// a capable compiler (respecting a `LANCE_AMX_FP16_CC` override) and use it +/// only for this one file; everything else keeps using the default toolchain. +fn build_amx_fp16_with_flags(flags: &[&str]) -> Result<(), String> { + let compiler = find_amx_fp16_compiler(flags).ok_or_else(|| { + "no C compiler supporting -mamx-fp16 found (need clang>=16 or gcc>=13; \ + set LANCE_AMX_FP16_CC to override)" + .to_string() + })?; + let mut builder = cc::Build::new(); + builder + .compiler(&compiler) + .std("c17") + .file("src/simd/amx_fp16.c") + .flag("-funroll-loops") + .flag("-O3") + .flag("-Wall") + .flag("-Wextra"); + for flag in flags { + builder.flag(flag); + } + builder.try_compile("amx_fp16").map_err(|e| e.to_string()) +} + +/// Find a C compiler that can build the AMX-FP16 kernel with `flags`, in order: +/// the `LANCE_AMX_FP16_CC` override, the default toolchain `cc`, then common +/// modern clang names. Returns the first that compiles a `_tile_dpfp16ps` probe. +fn find_amx_fp16_compiler(flags: &[&str]) -> Option { + let mut candidates: Vec = Vec::new(); + if let Ok(cc) = env::var("LANCE_AMX_FP16_CC") { + candidates.push(cc); + } + if let Ok(default_cc) = cc::Build::new() + .get_compiler() + .path() + .to_str() + .ok_or(()) + .map(str::to_string) + { + candidates.push(default_cc); + } + for c in ["clang-18", "clang-17", "clang-16", "clang"] { + candidates.push(c.to_string()); + } + candidates + .into_iter() + .find(|cc| cc_supports_amx_fp16(cc, flags)) +} + +/// True iff invoking `cc` with `flags` can compile a translation unit that uses +/// `_tile_dpfp16ps`. `-Werror=implicit-function-declaration` turns gcc's +/// "intrinsic not declared" *warning* (which otherwise still exits 0 on the +/// too-old gcc that lacks amx-fp16) into a hard failure. +fn cc_supports_amx_fp16(cc: &str, flags: &[&str]) -> bool { + use std::io::Write; + use std::process::{Command, Stdio}; + + let src = b"#include \n\ + void t(const void* a, const void* b) {\n\ + _tile_loadd(1, a, 64); _tile_loadd(2, b, 4);\n\ + _tile_dpfp16ps(0, 1, 2); _tile_release(); }\n"; + let out = env::var("OUT_DIR") + .map(|d| format!("{d}/amx_fp16_probe.o")) + .unwrap_or_else(|_| "/dev/null".to_string()); + + let mut cmd = Command::new(cc); + cmd.args(flags) + .args([ + "-Werror=implicit-function-declaration", + "-x", + "c", + "-c", + "-", + "-o", + ]) + .arg(&out) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + + let Ok(mut child) = cmd.spawn() else { + return false; + }; + if let Some(mut stdin) = child.stdin.take() + && stdin.write_all(src).is_err() + { + return false; + } + child.wait().map(|s| s.success()).unwrap_or(false) +} diff --git a/rust/lancedb/vendor/lance-linalg/proptest-regressions/distance/cosine.txt b/rust/lancedb/vendor/lance-linalg/proptest-regressions/distance/cosine.txt new file mode 100644 index 000000000..5cc427771 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/proptest-regressions/distance/cosine.txt @@ -0,0 +1,8 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 72cbff0852d1bef1842803e6fd343b2b85b6f6d786d39bf68683f17c7077f580 # nearly parallel vectors in test_cosine_once_16_scalar_vs_avx_fma_parity +cc 679c764b02e2726ec2d943b3abdc7d7d3565e168d4081b155860c1e69b616fce # shrinks to (x, y) = ([-1.2933521e-15, -1.1194652e-8, 7.447341e-32, -0.0, -14247490.0, -8.55e-43, -4576.872, 0.009181444], [4.926e-42, -9.267065e-15, -0.0, 7e-45, -0.00036999694, -0.0, -5.7810876e-8, 1.9273644e-21]) diff --git a/rust/lancedb/vendor/lance-linalg/src/clustering.rs b/rust/lancedb/vendor/lance-linalg/src/clustering.rs new file mode 100644 index 000000000..99a166f8d --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/clustering.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Clustering algorithms. +//! + +use arrow_array::UInt32Array; +use num_traits::Num; + +use crate::Result; + +/// Clustering Trait. +pub trait Clustering { + /// The dimension of the vectors. + fn dimension(&self) -> u32; + + /// The number of clusters. + fn num_clusters(&self) -> u32; + + /// Find n-nearest partitions for the given query. + /// + /// ## Parameters + /// * `query`: a `D`-dimensional query vector. + /// * `nprobes`: The number of probes to return. + /// + /// ## Returns + /// + /// `n` of nearest partitions. + fn find_partitions(&self, query: &[T], nprobes: usize) -> Result; + + /// Get the n nearest partitions for an array of vectors. + /// + /// ## Parameters: + /// * `data`: an `N * D` of D-dimensional vectors. + /// * `nprobes`: If provided, the number of partitions per vector to return. + /// If not provided, return 1 partition per vector. + /// + /// ## Returns: + /// * An `N * nprobes` matrix of partition IDs. + fn compute_membership(&self, data: &[T], nprobes: Option) -> Vec>; +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance.rs b/rust/lancedb/vendor/lance-linalg/src/distance.rs new file mode 100644 index 000000000..78f0b22ba --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance.rs @@ -0,0 +1,1147 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Distance metrics +//! +//! This module provides distance metrics for vectors. +//! +//! - `bf16, f16, f32, f64` types are supported. +//! - SIMD is used when available, on `x86_64`, `aarch64` and `loongarch64` +//! architectures. + +use std::sync::Arc; + +use arrow_array::cast::AsArray; +use arrow_array::{Array, FixedSizeListArray, Float32Array, ListArray}; +use arrow_schema::ArrowError; +use lance_core::utils::cpu::SimdSupport; + +mod arrow; + +pub mod cosine; +pub mod cosine_u8; +pub mod dot; +pub mod dot_f16; +pub mod dot_u8; +pub mod hamming; +pub mod l2; +pub mod l2_u8; +pub mod norm_l2; + +// `#[track_caller]` on these helpers is load-bearing: without it a length-contract +// panic reports this file rather than the distance function the caller reached. +// See #8863. +#[inline] +#[track_caller] +fn assert_equal_lengths(left_len: usize, right_len: usize) { + assert_eq!( + left_len, right_len, + "distance inputs must have equal lengths: left={left_len}, right={right_len}" + ); +} + +#[inline] +#[track_caller] +fn assert_batch_layout(vector_len: usize, batch_len: usize, dimension: usize) { + assert!( + dimension > 0, + "distance dimension must be greater than zero" + ); + assert_eq!( + vector_len, dimension, + "distance vector length must match dimension: vector={vector_len}, dimension={dimension}" + ); + assert_eq!( + batch_len % dimension, + 0, + "distance batch length must be divisible by dimension: batch={batch_len}, dimension={dimension}" + ); +} + +/// [`assert_batch_layout`], plus one output slot per vector in the batch. +#[inline] +#[track_caller] +fn assert_batch_output_layout( + vector_len: usize, + batch_len: usize, + dimension: usize, + output_len: usize, +) { + assert_batch_layout(vector_len, batch_len, dimension); + assert_eq!( + output_len, + batch_len / dimension, + "distance output length must match the number of vectors in the batch: output={output_len}, batch={batch_len}, dimension={dimension}" + ); +} + +/// Runtime backend shared by the f16 and bf16 C kernels. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HalfBackend { + Avx512, + Avx2, + Neon, + Lsx, + Lasx, + Scalar, +} + +/// Half-precision element type whose fallback kernel is being selected. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HalfType { + F16, + Bf16, +} + +/// CPU features required by the x86 fallback objects. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct X86HalfFeatures { + has_avx2: bool, + has_f16c: bool, + has_fma: bool, +} + +/// Whether this target links the optional half-precision C objects. +const HALF_KERNELS_COMPILED: bool = cfg!(all( + feature = "fp16kernels", + not(target_os = "windows"), + any( + target_arch = "aarch64", + target_arch = "x86_64", + target_arch = "loongarch64" + ) +)); + +/// Selects a half-precision backend without reading host or build state so the +/// exclusive SIMD tier ladder can be tested on any machine. +fn half_backend( + support: SimdSupport, + half_type: HalfType, + has_kernels: bool, + has_avx512_kernel: bool, + x86_features: X86HalfFeatures, +) -> HalfBackend { + if !has_kernels { + return HalfBackend::Scalar; + } + + match support { + SimdSupport::Avx512FP16 if has_avx512_kernel => HalfBackend::Avx512, + // SIMD_SUPPORT reports one exclusive tier. An AVX-512 host that cannot + // use the optional AVX-512 C object must therefore be named here to + // reach the always-built x86 fallback object. + SimdSupport::Avx512 | SimdSupport::Avx512FP16 | SimdSupport::Avx2 + if x86_features.has_fma + && match half_type { + HalfType::F16 => x86_features.has_f16c, + HalfType::Bf16 => x86_features.has_avx2, + } => + { + HalfBackend::Avx2 + } + SimdSupport::Neon => HalfBackend::Neon, + SimdSupport::Lsx => HalfBackend::Lsx, + SimdSupport::Lasx => HalfBackend::Lasx, + _ => HalfBackend::Scalar, + } +} + +/// Detects every feature emitted by the x86 fallback objects. +#[inline] +fn x86_half_features() -> X86HalfFeatures { + #[cfg(target_arch = "x86_64")] + { + X86HalfFeatures { + has_avx2: std::is_x86_feature_detected!("avx2"), + has_f16c: std::is_x86_feature_detected!("f16c"), + has_fma: std::is_x86_feature_detected!("fma"), + } + } + #[cfg(not(target_arch = "x86_64"))] + { + X86HalfFeatures::default() + } +} + +/// Largest number of maximal u8 product terms whose sum fits in a u32. +const U8_U32_ACCUMULATOR_MAX_LEN: usize = u32::MAX as usize / (u8::MAX as usize * u8::MAX as usize); + +/// Distance between two vectors of equal length. +pub(crate) type PairKernel = unsafe fn(&[f32], &[f32]) -> f32; + +/// Writes the distance from `key` to each `dimension`-sized vector of `batch` +/// into the matching element of `output`. +pub(crate) type BatchKernel = unsafe fn(&[f32], &[f32], usize, &mut [f32]); + +pub use cosine::*; +pub use dot::*; +#[allow(deprecated)] +pub use hamming::{ + BinaryHashValues, Cluster, ClusteringResult, PairwiseResult, UnionFind, cluster_edges, + cluster_pairwise_result, extract_binary_hashes_from_fixed_list, extract_hashes_from_fixed_list, + hamming_distance_arrow_batch, hamming_u64, pairwise_hamming_distance, + pairwise_hamming_distance_binary, pairwise_hamming_distance_binary_parallel, + pairwise_hamming_distance_parallel, +}; +pub use l2::*; +use lance_core::deepsize::DeepSizeOf; +pub use norm_l2::*; + +use crate::Result; + +/// Distance metrics type. +#[derive(Debug, Copy, Clone, PartialEq, DeepSizeOf)] +pub enum DistanceType { + L2, + Cosine, + /// Dot Product + Dot, + /// Hamming Distance + Hamming, +} + +/// For backwards compatibility. +pub type MetricType = DistanceType; + +pub type DistanceFunc = fn(&[T], &[T]) -> f32; +pub type BatchDistanceFunc = fn(&[f32], &[f32], usize) -> Arc; +pub type ArrowBatchDistanceFunc = fn(&dyn Array, &FixedSizeListArray) -> Result>; + +impl DistanceType { + /// Compute distances from `query` to each row of `vectors`, propagating row nulls. + /// + /// L2, cosine and dot accept Float16/Float32/Float64 queries and Int8 queries. + /// An Int8 query also accepts Float32, Int16, or Int32 stored vectors; both + /// sides are widened to Float32, preserving the legacy mixed-type behavior. + /// Other query and stored element types must match. Hamming accepts UInt8. + /// The query must be non-null and have the same positive dimension as the rows. + /// Unsupported types and invalid queries return an [`ArrowError::InvalidArgumentError`]. + /// + /// ``` + /// use arrow_array::{FixedSizeListArray, Float32Array, types::Float32Type}; + /// use lance_linalg::distance::DistanceType; + /// let query = Float32Array::from(vec![1.0, 2.0]); + /// let vectors = FixedSizeListArray::from_iter_primitive::( + /// [Some(vec![Some(3.0), Some(4.0)])], 2); + /// assert_eq!(DistanceType::L2.batch(&query, &vectors)?.value(0), 8.0); + /// # Ok::<(), arrow_schema::ArrowError>(()) + /// ``` + pub fn batch(&self, query: &dyn Array, vectors: &FixedSizeListArray) -> Result { + let values = arrow::dispatch(arrow::Operation::Batch(*self), Some(query), vectors)?; + Ok(Float32Array::new(values.into(), vectors.nulls().cloned())) + } + + /// Compute additive late-interaction distances for a flattened multivector query. + /// + /// Each query sub-vector contributes its minimum distance to any stored + /// sub-vector in the row. Null or empty stored rows produce `NaN`. + /// Float16/Float32/Float64 support L2, cosine and dot; UInt8 supports Hamming. + /// Int8 multivectors remain unsupported. Query and stored element types must + /// match, and the non-null query length must be a positive multiple of the + /// stored vector dimension. Invalid inputs return [`ArrowError::InvalidArgumentError`]. + /// + /// ``` + /// use arrow_array::ListArray; + /// use lance_linalg::distance::DistanceType; + /// # fn example(query: &dyn arrow_array::Array, vectors: &ListArray) + /// # -> Result, arrow_schema::ArrowError> { + /// DistanceType::Cosine.multivec(query, vectors) + /// # } + /// ``` + pub fn multivec(&self, query: &dyn Array, vectors: &ListArray) -> Result> { + let values = vectors.values().as_fixed_size_list_opt().ok_or_else(|| { + ArrowError::InvalidArgumentError(format!( + "{self} multivec: vectors must be a list of fixed size list, got {}", + vectors.data_type() + )) + })?; + arrow::dispatch( + arrow::Operation::Multivec(*self, vectors), + Some(query), + values, + ) + } + + /// Return a typed numeric kernel, or an error for Hamming. + /// + /// Use [`Self::batch`] for UInt8 Hamming distances. + /// + /// ``` + /// use lance_linalg::distance::DistanceType; + /// let distance = DistanceType::L2.try_func::()?; + /// assert_eq!(distance(&[1.0], &[3.0]), 4.0); + /// assert!(DistanceType::Hamming.try_func::().is_err()); + /// # Ok::<(), arrow_schema::ArrowError>(()) + /// ``` + pub fn try_func(&self) -> Result> { + match self { + Self::L2 => Ok(l2), + Self::Cosine => Ok(cosine_distance), + Self::Dot => Ok(dot_distance), + Self::Hamming => Err(ArrowError::InvalidArgumentError( + "hamming: typed numeric kernels do not support Hamming; use DistanceType::batch with UInt8 vectors".to_string(), + )), + } + } + + /// Compute distances through the legacy function-pointer API. + #[deprecated(note = "Use DistanceType::batch")] + pub fn arrow_batch_func(&self) -> ArrowBatchDistanceFunc { + match self { + Self::L2 => |query, vectors| Self::L2.batch(query, vectors).map(Arc::new), + Self::Cosine => |query, vectors| Self::Cosine.batch(query, vectors).map(Arc::new), + Self::Dot => |query, vectors| Self::Dot.batch(query, vectors).map(Arc::new), + Self::Hamming => |query, vectors| Self::Hamming.batch(query, vectors).map(Arc::new), + } + } + + /// Return a typed numeric kernel through the legacy infallible API. + /// + /// # Panics + /// Panics for Hamming. Use [`Self::try_func`] to receive an error instead. + #[deprecated(note = "Use DistanceType::try_func or DistanceType::batch")] + pub fn func(&self) -> DistanceFunc { + // This deprecated signature cannot return an error without breaking callers. + self.try_func() + .expect("Hamming requires UInt8 Arrow vectors") + } +} + +impl std::fmt::Display for DistanceType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + match self { + Self::L2 => "l2", + Self::Cosine => "cosine", + Self::Dot => "dot", + Self::Hamming => "hamming", + } + ) + } +} + +impl TryFrom<&str> for DistanceType { + type Error = ArrowError; + + fn try_from(s: &str) -> std::result::Result { + match s.to_lowercase().as_str() { + "l2" | "euclidean" => Ok(Self::L2), + "cosine" => Ok(Self::Cosine), + "dot" => Ok(Self::Dot), + "hamming" => Ok(Self::Hamming), + _ => Err(ArrowError::InvalidArgumentError(format!( + "Metric type '{s}' is not supported" + ))), + } + } +} + +/// Computes the additive late-interaction distance from a multivector query. +/// +/// For each query sub-vector, this finds the minimum distance to any stored +/// sub-vector in the row, then sums those minimum distances. Null or empty +/// stored rows produce `NaN`. +#[deprecated(note = "Use DistanceType::multivec")] +pub fn multivec_distance( + query: &dyn Array, + vectors: &ListArray, + distance_type: DistanceType, +) -> Result> { + distance_type.multivec(query, vectors) +} + +#[cfg(test)] +#[allow(deprecated)] +mod tests { + use super::*; + + #[cfg(target_arch = "x86_64")] + use std::io::Write; + use std::sync::Arc; + + use arrow_array::ArrowPrimitiveType; + use arrow_array::types::{Float16Type, Float32Type, Int8Type, UInt8Type}; + use arrow_array::{ + Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, ListArray, PrimitiveArray, + UInt8Array, + }; + use arrow_buffer::{OffsetBuffer, ScalarBuffer}; + use arrow_schema::{DataType, Field}; + use half::f16; + use lance_arrow::FixedSizeListArrayExt; + + const NO_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures { + has_avx2: false, + has_f16c: false, + has_fma: false, + }; + const F16_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures { + has_avx2: false, + has_f16c: true, + has_fma: true, + }; + const BF16_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures { + has_avx2: true, + has_f16c: false, + has_fma: true, + }; + const ALL_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures { + has_avx2: true, + has_f16c: true, + has_fma: true, + }; + const X86_HALF_FEATURES_WITHOUT_FMA: X86HalfFeatures = X86HalfFeatures { + has_avx2: true, + has_f16c: true, + has_fma: false, + }; + + #[rstest::rstest] + #[case::kernels_disabled( + SimdSupport::Avx512FP16, + HalfType::F16, + false, + false, + ALL_X86_HALF_FEATURES, + HalfBackend::Scalar + )] + #[case::avx512_kernel_ready( + SimdSupport::Avx512FP16, + HalfType::F16, + true, + true, + NO_X86_HALF_FEATURES, + HalfBackend::Avx512 + )] + #[case::f16_fallback_from_avx512fp16( + SimdSupport::Avx512FP16, + HalfType::F16, + true, + false, + F16_X86_HALF_FEATURES, + HalfBackend::Avx2 + )] + #[case::bf16_fallback_from_avx512fp16( + SimdSupport::Avx512FP16, + HalfType::Bf16, + true, + false, + BF16_X86_HALF_FEATURES, + HalfBackend::Avx2 + )] + #[case::fallback_from_avx512( + SimdSupport::Avx512, + HalfType::Bf16, + true, + false, + BF16_X86_HALF_FEATURES, + HalfBackend::Avx2 + )] + #[case::f16_missing_f16c( + SimdSupport::Avx512FP16, + HalfType::F16, + true, + false, + BF16_X86_HALF_FEATURES, + HalfBackend::Scalar + )] + #[case::bf16_missing_avx2( + SimdSupport::Avx512FP16, + HalfType::Bf16, + true, + false, + F16_X86_HALF_FEATURES, + HalfBackend::Scalar + )] + #[case::fallback_missing_fma( + SimdSupport::Avx512FP16, + HalfType::F16, + true, + false, + X86_HALF_FEATURES_WITHOUT_FMA, + HalfBackend::Scalar + )] + #[case::avx2_tier( + SimdSupport::Avx2, + HalfType::Bf16, + true, + false, + BF16_X86_HALF_FEATURES, + HalfBackend::Avx2 + )] + #[case::neon( + SimdSupport::Neon, + HalfType::F16, + true, + false, + NO_X86_HALF_FEATURES, + HalfBackend::Neon + )] + #[case::lsx( + SimdSupport::Lsx, + HalfType::Bf16, + true, + false, + NO_X86_HALF_FEATURES, + HalfBackend::Lsx + )] + #[case::lasx( + SimdSupport::Lasx, + HalfType::Bf16, + true, + false, + NO_X86_HALF_FEATURES, + HalfBackend::Lasx + )] + fn half_backend_follows_exclusive_tier_and_feature_requirements( + #[case] support: SimdSupport, + #[case] half_type: HalfType, + #[case] has_kernels: bool, + #[case] has_avx512_kernel: bool, + #[case] features: X86HalfFeatures, + #[case] expected: HalfBackend, + ) { + assert_eq!( + half_backend(support, half_type, has_kernels, has_avx512_kernel, features), + expected + ); + } + + #[cfg(target_arch = "x86_64")] + #[test] + fn test_x86_runtime_feature_report() { + // Write directly to stderr so this remains visible when libtest captures + // ordinary output from passing tests. + writeln!( + std::io::stderr().lock(), + "lance-linalg x86 runtime features: avx={}, fma={}, avx2={}, avx512f={}, avx512bw={}, avx512vnni={}, avx512vpopcntdq={}", + std::is_x86_feature_detected!("avx"), + std::is_x86_feature_detected!("fma"), + std::is_x86_feature_detected!("avx2"), + std::is_x86_feature_detected!("avx512f"), + std::is_x86_feature_detected!("avx512bw"), + std::is_x86_feature_detected!("avx512vnni"), + std::is_x86_feature_detected!("avx512vpopcntdq"), + ) + .expect("write x86 runtime feature report"); + } + + #[test] + fn test_arrow_batch_type_errors_identify_the_argument() { + let float32_targets = + FixedSizeListArray::try_new_from_values(Float32Array::from(vec![1.0, 2.0]), 2).unwrap(); + let unsupported_query = Int32Array::from(vec![1, 2]); + + for distance_type in [DistanceType::L2, DistanceType::Cosine, DistanceType::Dot] { + let error = distance_type + .batch(&unsupported_query, &float32_targets) + .unwrap_err(); + assert!( + matches!(error, ArrowError::InvalidArgumentError(_)), + "{distance_type} returned a different error variant: {error}" + ); + } + + let unsupported_from_error = DistanceType::Cosine + .batch(&unsupported_query, &float32_targets) + .unwrap_err(); + assert!( + matches!(&unsupported_from_error, ArrowError::InvalidArgumentError(message) + if message == "cosine batch: query type Int32 does not match the stored vector type Float32"), + "unexpected unsupported `from` error: {unsupported_from_error}" + ); + + let float32_query = Float32Array::from(vec![1.0, 2.0]); + let float64_targets = + FixedSizeListArray::try_new_from_values(Float64Array::from(vec![1.0, 2.0]), 2).unwrap(); + let mismatched_to_error = DistanceType::Cosine + .batch(&float32_query, &float64_targets) + .unwrap_err(); + assert!( + matches!(&mismatched_to_error, ArrowError::InvalidArgumentError(message) + if message == "cosine batch: query type Float32 does not match the stored vector type Float64"), + "unexpected mismatched `to` error: {mismatched_to_error}" + ); + } + + /// Build `List>` rows from flattened sub-vector values. + fn multivecs_of(rows: Vec>, dim: i32) -> ListArray { + let lengths = rows + .iter() + .map(|row| { + assert_eq!(row.len() % dim as usize, 0); + row.len() / dim as usize + }) + .collect::>(); + let values = ScalarBuffer::from(rows.into_iter().flatten().collect::>()); + let inner = PrimitiveArray::::new(values, None); + let fsl = FixedSizeListArray::try_new( + Arc::new(Field::new("item", T::DATA_TYPE, true)), + dim, + Arc::new(inner), + None, + ) + .unwrap(); + let offsets = OffsetBuffer::from_lengths(lengths); + let field = Arc::new(Field::new("item", fsl.data_type().clone(), true)); + ListArray::try_new(field, offsets, Arc::new(fsl), None).unwrap() + } + + /// Build one `List>` row. + fn multivec_of(values: Vec, dim: i32) -> ListArray { + multivecs_of::(vec![values], dim) + } + + /// The `(query dtype, distance type)` pre-check and the dispatch must agree. + /// `UInt8` is only valid with Hamming, and the float types only with the + /// float metrics; a mismatch must be an error rather than a panic in the + /// dispatch arm or inside an arrow downcast. + #[test] + fn test_multivec_distance_rejects_dtype_metric_mismatch() { + let f32_vectors = multivec_of::(vec![1.0, 2.0], 2); + let u8_vectors = multivec_of::(vec![1, 2], 2); + + let u8_query: Arc = Arc::new(UInt8Array::from(vec![1_u8, 2])); + let f32_query: Arc = Arc::new(Float32Array::from(vec![1.0_f32, 2.0])); + + // Query and stored types MATCH in each case, so only the metric is wrong + // — otherwise the element-type check would reject these first and this + // test would pass with the metric guard deleted. + for dt in [DistanceType::L2, DistanceType::Cosine, DistanceType::Dot] { + let err = multivec_distance(u8_query.as_ref(), &u8_vectors, dt).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("unsupported vector element type")), + "UInt8 query with {dt} must be rejected for the metric, got: {err}" + ); + } + + let err = + multivec_distance(f32_query.as_ref(), &f32_vectors, DistanceType::Hamming).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("unsupported vector element type")), + "Float32 query with hamming must be rejected for the metric, got: {err}" + ); + } + + /// The `_arrow_batch` entry points that accept `Int8` widen the query element + /// by element. + /// A null there used to reach an `unwrap`, so a query column with a null in + /// its values panicked instead of returning an error, on the metrics that + /// accept `Int8`. + #[test] + fn test_arrow_batch_rejects_null_int8_query() { + let targets = + FixedSizeListArray::try_new_from_values(Int8Array::from(vec![1_i8, 2, 3, 4]), 2) + .unwrap(); + let query: Arc = Arc::new(Int8Array::from(vec![Some(1_i8), None])); + + for dt in [DistanceType::L2, DistanceType::Cosine, DistanceType::Dot] { + let err = dt.batch(query.as_ref(), &targets).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) + if m.contains("query must not contain nulls") && m.contains("found 1 in 2 values")), + "{dt} accepted a null Int8 query element, got: {err}" + ); + } + + // The same query without nulls goes through, so the guard is not + // rejecting every `Int8` query. + let query: Arc = Arc::new(Int8Array::from(vec![1_i8, 2])); + for dt in [DistanceType::L2, DistanceType::Cosine, DistanceType::Dot] { + assert_eq!( + dt.batch(query.as_ref(), &targets).unwrap().len(), + 2, + "{dt} rejected a well-formed Int8 query" + ); + } + + // A sliced query reads through `values()`, which has to follow the slice: + // the window here holds no nulls while the full buffer does. The L2 + // distances are asserted literally rather than against a second call, + // since computing the expected values by the same route would hide a bug + // that transformed both alike. Query [3, 4] against [[1, 2], [3, 4]] + // gives (3-1)^2 + (4-2)^2 = 8 and 0. + let sliced = Int8Array::from(vec![None, Some(3_i8), Some(4), None]).slice(1, 2); + let query: Arc = Arc::new(sliced); + let got = DistanceType::L2.batch(query.as_ref(), &targets).unwrap(); + assert_eq!( + got.values(), + &[8.0_f32, 0.0], + "L2 did not follow the query slice" + ); + for dt in [DistanceType::Cosine, DistanceType::Dot] { + let got = dt.batch(query.as_ref(), &targets).unwrap(); + let want = dt + .batch(Arc::new(Int8Array::from(vec![3_i8, 4])).as_ref(), &targets) + .unwrap(); + assert_eq!(got, want, "{dt} did not follow the query slice"); + } + } + + /// An input that is both a length mismatch and a null query must reach the + /// null error on all three metrics. `dot` used to carry a second + /// `debug_assert_eq!` on the dimension in its public entry point, ahead of + /// the `Int8` arm's null guard. + #[test] + fn test_arrow_batch_null_and_length_mismatch_agree() { + let targets = + FixedSizeListArray::try_new_from_values(Int8Array::from(vec![1_i8, 2, 3, 4]), 2) + .unwrap(); + let query: Arc = Arc::new(Int8Array::from(vec![Some(1_i8), None, Some(2)])); + + for dt in [DistanceType::L2, DistanceType::Cosine, DistanceType::Dot] { + let err = dt.batch(query.as_ref(), &targets).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("must not contain nulls")), + "{dt} did not report the null query, got: {err}" + ); + } + } + + /// `Int8` is a valid vector element type elsewhere in the crate but has no + /// multivector kernel, so it must be rejected for the type, not the metric. + #[test] + fn test_multivec_distance_rejects_unsupported_element_type() { + let i8_vectors = multivec_of::(vec![1, 2], 2); + let i8_query: Arc = Arc::new(Int8Array::from(vec![1_i8, 2])); + + let err = multivec_distance(i8_query.as_ref(), &i8_vectors, DistanceType::L2).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("unsupported vector element type")), + "Int8 must be rejected for the element type, got: {err}" + ); + } + + /// Query and stored vector element types must match before dispatch. + #[test] + fn test_multivec_distance_rejects_element_type_mismatch() { + let f16_vectors = + multivec_of::(vec![f16::from_f32(1.0), f16::from_f32(2.0)], 2); + let f32_query: Arc = Arc::new(Float32Array::from(vec![1.0_f32, 2.0])); + + let err = + multivec_distance(f32_query.as_ref(), &f16_vectors, DistanceType::L2).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("does not match the stored vector type")), + "Float32 query against a Float16 column must be rejected, got: {err}" + ); + } + + /// A query length that is not a positive multiple of `dim` is structurally + /// invalid: `chunks_exact` would silently drop the tail, and a query shorter + /// than `dim` would yield no sub-vectors at all and score every row `0.0`. + #[test] + fn test_multivec_distance_rejects_bad_query_length() { + let vectors = multivec_of::(vec![1.0, 2.0], 2); + + for bad in [vec![7.0_f32], vec![7.0, 7.0, 999.0], vec![]] { + let len = bad.len(); + let query: Arc = Arc::new(Float32Array::from(bad)); + let err = multivec_distance(query.as_ref(), &vectors, DistanceType::L2).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("must be a positive multiple")), + "query of length {len} against dim 2 must be rejected, got: {err}" + ); + } + } + + /// A zero-dimension column would panic in `chunks_exact(0)`; it gets its own + /// message rather than blaming the query's length. + #[test] + fn test_multivec_distance_rejects_zero_dim() { + let values = Float32Array::from(Vec::::new()); + let fsl = FixedSizeListArray::try_new_with_length( + Arc::new(Field::new("item", DataType::Float32, true)), + 0, + Arc::new(values), + None, + 1, + ) + .unwrap(); + let field = Arc::new(Field::new("item", fsl.data_type().clone(), true)); + let vectors = ListArray::try_new( + field, + OffsetBuffer::from_lengths([1_usize]), + Arc::new(fsl), + None, + ) + .unwrap(); + let query: Arc = Arc::new(Float32Array::from(vec![1.0_f32, 2.0])); + + let err = multivec_distance(query.as_ref(), &vectors, DistanceType::L2).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) + if m.contains("stored vectors have dimension 0") + && !m.contains("positive multiple")), + "a zero-dim column must be rejected on its own terms, got: {err}" + ); + } + + /// A null query slot is read from the raw values buffer, so it would be + /// silently scored as whatever the buffer holds. + #[test] + fn test_multivec_distance_rejects_null_query() { + let vectors = multivec_of::(vec![1.0, 2.0], 2); + let query: Arc = Arc::new(Float32Array::from(vec![Some(1.0_f32), None])); + + let err = multivec_distance(query.as_ref(), &vectors, DistanceType::L2).unwrap_err(); + assert!( + matches!(&err, ArrowError::InvalidArgumentError(m) if m.contains("must not contain nulls")), + "a query with nulls must be rejected, got: {err}" + ); + } + + /// Each query sub-vector contributes its minimum Hamming distance to the + /// row total. + #[test] + fn test_multivec_distance_hamming() { + let vectors = + multivecs_of::(vec![vec![0b0000_0000, 0b0000_1111], vec![0b0000_0011]], 1); + let query: Arc = Arc::new(UInt8Array::from(vec![0b0000_0000_u8, 0b0000_1111])); + + let dists = multivec_distance(query.as_ref(), &vectors, DistanceType::Hamming).unwrap(); + + assert_eq!(dists, vec![0.0, 4.0]); + } + + #[rstest::rstest] + #[case::l2_perfect( + DistanceType::L2, + vec![1.0, 0.0, 0.0, 1.0], + vec![1.0, 0.0, 0.0, 1.0], + 0.0 + )] + #[case::cosine_perfect( + DistanceType::Cosine, + vec![1.0, 0.0, 0.0, 1.0], + vec![1.0, 0.0, 0.0, 1.0], + 0.0 + )] + #[case::dot_perfect( + DistanceType::Dot, + vec![1.0, 0.0, 0.0, 1.0], + vec![1.0, 0.0, 0.0, 1.0], + 0.0 + )] + #[case::cosine_repeated_query( + DistanceType::Cosine, + vec![0.6, 0.8], + vec![1.0, 0.0, 1.0, 0.0], + 0.8 + )] + #[case::cosine_single_query( + DistanceType::Cosine, + vec![0.0, 1.0], + vec![1.0, 0.0], + 1.0 + )] + fn test_multivec_distance_float( + #[case] distance_type: DistanceType, + #[case] vectors: Vec, + #[case] query: Vec, + #[case] expected: f32, + ) { + let vectors = multivec_of::(vectors, 2); + let query: Arc = Arc::new(Float32Array::from(query)); + + let dists = multivec_distance(query.as_ref(), &vectors, distance_type).unwrap(); + + assert!((dists[0] - expected).abs() < 1e-6); + } + + #[test] + fn test_multivec_distance_empty_row_is_nan() { + let query: Arc = Arc::new(Float32Array::from_iter_values([1.0_f32, 2.0])); + + let dim = 2; + let values = FixedSizeListArray::from_iter_primitive::( + vec![Some(vec![Some(1.0_f32), Some(2.0)])], + dim, + ); + + // Two rows: first is empty list, second has one sub-vector. + let offsets = OffsetBuffer::from_lengths([0_usize, 1]); + let field = Arc::new(Field::new("item", values.data_type().clone(), true)); + let vectors = ListArray::try_new(field, offsets, Arc::new(values), None).unwrap(); + + let dists = multivec_distance(query.as_ref(), &vectors, DistanceType::Dot).unwrap(); + assert_eq!(dists.len(), 2); + assert!(dists[0].is_nan()); + assert_eq!(dists[1], -4.0); + } + + #[cfg_attr(coverage, coverage(off))] + pub(super) fn arrow_values(dtype: &DataType, values: Vec) -> Arc { + match dtype { + DataType::Float16 => Arc::new(PrimitiveArray::::from( + values + .into_iter() + .map(|v| f16::from_f32(v as f32)) + .collect::>(), + )), + DataType::Float32 => Arc::new(Float32Array::from( + values.into_iter().map(|v| v as f32).collect::>(), + )), + DataType::Float64 => Arc::new(Float64Array::from( + values.into_iter().map(|v| v as f64).collect::>(), + )), + DataType::Int8 => Arc::new(Int8Array::from( + values.into_iter().map(|v| v as i8).collect::>(), + )), + DataType::Int16 => Arc::new(Int16Array::from( + values.into_iter().map(|v| v as i16).collect::>(), + )), + DataType::UInt8 => Arc::new(UInt8Array::from( + values.into_iter().map(|v| v as u8).collect::>(), + )), + DataType::Int32 => Arc::new(Int32Array::from(values)), + _ => panic!("unsupported test dtype {dtype}"), + } + } + + #[rstest::rstest] + #[case::l2(DistanceType::L2, [0.0, 8.0])] + #[case::dot(DistanceType::Dot, [-4.0, -10.0])] + #[case::cosine(DistanceType::Cosine, [0.0, 1.0 - 11.0 / (5.0_f32.sqrt() * 5.0)])] + #[case::hamming(DistanceType::Hamming, [0.0, 3.0])] + fn test_arrow_support_table( + #[case] metric: DistanceType, + #[case] expected: [f32; 2], + #[values( + DataType::Float16, + DataType::Float32, + DataType::Float64, + DataType::Int8, + DataType::UInt8, + DataType::Int32 + )] + dtype: DataType, + ) { + let query = arrow_values(&dtype, vec![1, 2]); + let vectors = + FixedSizeListArray::try_new_from_values(arrow_values(&dtype, vec![1, 2, 3, 4]), 2) + .unwrap(); + let rows = ListArray::new( + Arc::new(Field::new("item", vectors.data_type().clone(), true)), + OffsetBuffer::from_lengths([1, 1]), + Arc::new(vectors.clone()), + None, + ); + let supports_batch = if metric == DistanceType::Hamming { + dtype == DataType::UInt8 + } else { + matches!( + dtype, + DataType::Float16 | DataType::Float32 | DataType::Float64 | DataType::Int8 + ) + }; + let supports_multivec = supports_batch && dtype != DataType::Int8; + let batch = metric.batch(query.as_ref(), &vectors); + let legacy: ArrowBatchDistanceFunc = match metric { + DistanceType::L2 => l2_distance_arrow_batch, + DistanceType::Cosine => cosine_distance_arrow_batch, + DistanceType::Dot => dot_distance_arrow_batch, + DistanceType::Hamming => hamming_distance_arrow_batch, + }; + for legacy in [legacy, metric.arrow_batch_func()] { + match (&batch, legacy(query.as_ref(), &vectors)) { + (Ok(batch), Ok(legacy)) => assert_eq!(batch, legacy.as_ref()), + (Err(batch), Err(legacy)) => assert_eq!(batch.to_string(), legacy.to_string()), + (batch, legacy) => panic!("legacy dispatch differs: {batch:?}, {legacy:?}"), + } + } + let multivec = metric.multivec(query.as_ref(), &rows); + for (result, supported) in [ + (batch.map(|a| a.values().to_vec()), supports_batch), + (multivec, supports_multivec), + ] { + if supported { + let got = result.unwrap(); + assert_eq!(got.len(), expected.len()); + for (got, want) in got.iter().zip(expected) { + approx::assert_abs_diff_eq!(*got, want, epsilon = 1e-6); + } + } else { + let error = result.unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("unsupported vector element type") && message.contains(&dtype.to_string())), + "{metric} {dtype}: {error}" + ); + } + } + } + + #[rstest::rstest] + #[case::l2(DistanceType::L2, [0.0, 8.0])] + #[case::dot(DistanceType::Dot, [-4.0, -10.0])] + #[case::cosine(DistanceType::Cosine, [0.0, 1.0 - 11.0 / (5.0_f32.sqrt() * 5.0)])] + fn test_int8_query_with_legacy_stored_types( + #[case] metric: DistanceType, + #[case] expected: [f32; 2], + #[values(DataType::Float32, DataType::Int16, DataType::Int32)] dtype: DataType, + ) { + let query = arrow_values(&DataType::Int8, vec![1, 2]); + let vectors = + FixedSizeListArray::try_new_from_values(arrow_values(&dtype, vec![1, 2, 3, 4]), 2) + .unwrap(); + + let got = metric.batch(query.as_ref(), &vectors).unwrap(); + for (got, want) in got.values().iter().zip(expected) { + approx::assert_abs_diff_eq!(*got, want, epsilon = 1e-6); + } + + let legacy: ArrowBatchDistanceFunc = match metric { + DistanceType::L2 => l2_distance_arrow_batch, + DistanceType::Cosine => cosine_distance_arrow_batch, + DistanceType::Dot => dot_distance_arrow_batch, + DistanceType::Hamming => hamming_distance_arrow_batch, + }; + assert_eq!(&got, legacy(query.as_ref(), &vectors).unwrap().as_ref()); + } + + #[test] + fn test_int8_query_does_not_broaden_past_legacy_stored_types() { + let query = arrow_values(&DataType::Int8, vec![1, 2]); + for dtype in [DataType::Float16, DataType::Float64, DataType::UInt8] { + let vectors = + FixedSizeListArray::try_new_from_values(arrow_values(&dtype, vec![1, 2, 3, 4]), 2) + .unwrap(); + assert!( + DistanceType::L2.batch(query.as_ref(), &vectors).is_err(), + "Int8 query unexpectedly accepted stored {dtype}" + ); + } + } + + #[rstest::rstest] + #[case::l2(DistanceType::L2, DataType::Float32)] + #[case::dot(DistanceType::Dot, DataType::Float32)] + #[case::cosine(DistanceType::Cosine, DataType::Float32)] + #[case::hamming(DistanceType::Hamming, DataType::UInt8)] + fn test_arrow_batch_dimension_errors( + #[case] metric: DistanceType, + #[case] dtype: DataType, + #[values(0, 1, 3)] query_len: usize, + ) { + let vectors = + FixedSizeListArray::try_new_from_values(arrow_values(&dtype, vec![1, 2, 3, 4]), 2) + .unwrap(); + let query = arrow_values(&dtype, vec![1; query_len]); + let error = metric.batch(query.as_ref(), &vectors).unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains(&format!("query length {query_len}")) && message.contains("dimension 2")), + "{error}" + ); + } + + #[test] + fn test_hamming_validation_and_legacy_wrapper() { + let targets = + FixedSizeListArray::try_new_from_values(Float32Array::from(vec![1.0, 2.0]), 2).unwrap(); + let query = UInt8Array::from(vec![1, 2]); + let error = hamming_distance_arrow_batch(&query, &targets).unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("hamming batch") && message.contains("Float32")), + "{error}" + ); + + let targets = + FixedSizeListArray::try_new_from_values(UInt8Array::from(vec![1, 2]), 2).unwrap(); + let query = UInt8Array::from(vec![Some(1), None]); + let error = DistanceType::Hamming.batch(&query, &targets).unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("query must not contain nulls")), + "{error}" + ); + let query = UInt8Array::from(vec![1, 2]); + assert_eq!( + hamming_distance_arrow_batch(&query, &targets) + .unwrap() + .as_ref(), + &DistanceType::Hamming.batch(&query, &targets).unwrap() + ); + let error = DistanceType::Hamming.try_func::().unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("Hamming") && message.contains("UInt8")), + "{error}" + ); + } + + #[rstest::rstest] + #[case::l2(DistanceType::L2, DataType::Float32, 0.0)] + #[case::dot(DistanceType::Dot, DataType::Float32, -24.0)] + #[case::cosine(DistanceType::Cosine, DataType::Float32, 0.0)] + #[case::hamming(DistanceType::Hamming, DataType::UInt8, 0.0)] + fn test_arrow_batch_slices_and_null_rows( + #[case] metric: DistanceType, + #[case] dtype: DataType, + #[case] expected: f32, + ) { + let values = arrow_values(&dtype, vec![99, 99, 3, 4, 0, 0, 99, 99]); + let vectors = FixedSizeListArray::new( + Arc::new(Field::new("item", dtype.clone(), true)), + 2, + values, + Some(arrow_buffer::NullBuffer::from(vec![ + true, true, false, true, + ])), + ) + .slice(1, 2); + let query = arrow_values(&dtype, vec![99, 3, 4, 99]).slice(1, 2); + let got = metric.batch(query.as_ref(), &vectors).unwrap(); + assert_eq!(got.len(), 2); + approx::assert_abs_diff_eq!(got.value(0), expected, epsilon = 1e-6); + assert!(got.is_null(1)); + + let empty = vectors.slice(0, 0); + assert_eq!(metric.batch(query.as_ref(), &empty).unwrap().len(), 0); + let zero_dim = FixedSizeListArray::try_new_with_length( + Arc::new(Field::new("item", dtype.clone(), true)), + 0, + arrow_values(&dtype, vec![]), + None, + 1, + ) + .unwrap(); + let error = metric.batch(query.as_ref(), &zero_dim).unwrap_err(); + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("dimension 0")), + "{error}" + ); + } + + #[test] + fn test_multivec_sliced_null_and_empty_rows() { + let rows = multivecs_of::( + vec![ + vec![99.0, 99.0], + vec![1.0, 2.0, 3.0, 4.0], + vec![], + vec![5.0, 6.0], + ], + 2, + ); + let rows = ListArray::new( + Arc::new(Field::new("item", rows.value_type(), true)), + rows.offsets().clone(), + rows.values().clone(), + Some(arrow_buffer::NullBuffer::from(vec![ + true, true, true, false, + ])), + ) + .slice(1, 3); + let query = Float32Array::from(vec![99.0, 3.0, 4.0, 99.0]).slice(1, 2); + let got = DistanceType::L2.multivec(&query, &rows).unwrap(); + assert_eq!(got[0], 0.0); + assert!(got[1].is_nan()); + assert!(got[2].is_nan()); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs b/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs new file mode 100644 index 000000000..86d397a4c --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Shared validation, support table, and dtype dispatch for Arrow vectors. + +use arrow_array::cast::AsArray; +use arrow_array::types::{Float16Type, Float32Type, Float64Type, Int8Type, UInt8Type}; +use arrow_array::{Array, ArrowPrimitiveType, FixedSizeListArray, Float32Array, ListArray}; +use arrow_schema::{ArrowError, DataType}; +use lance_arrow::FixedSizeListArrayExt; +use num_traits::AsPrimitive; + +use super::{ + Cosine, DistanceFunc, DistanceType, Dot, L2, Normalize, cosine_distance_batch_into, + dot_distance_batch_into, hamming, l2_distance_batch_into, norm_l2, +}; +use crate::Result; + +#[derive(Clone, Copy)] +pub(super) enum Norm { + L2, + Squared, +} + +#[derive(Clone, Copy)] +pub(super) enum Operation<'a> { + Batch(DistanceType), + Multivec(DistanceType, &'a ListArray), + Norm(Norm), +} + +impl Operation<'_> { + // Keep the accepted metric × dtype pairs here, including the deliberate + // distinction between Int8 batches and multivectors. + fn supports(self, dtype: &DataType) -> bool { + matches!( + (self, dtype), + ( + Self::Batch(DistanceType::L2 | DistanceType::Cosine | DistanceType::Dot) + | Self::Multivec( + DistanceType::L2 | DistanceType::Cosine | DistanceType::Dot, + _ + ) + | Self::Norm(_), + DataType::Float16 | DataType::Float32 | DataType::Float64, + ) | ( + Self::Batch(DistanceType::L2 | DistanceType::Cosine | DistanceType::Dot), + DataType::Int8 + ) | ( + Self::Batch(DistanceType::Hamming) | Self::Multivec(DistanceType::Hamming, _), + DataType::UInt8 + ) + ) + } + + fn supports_int8_query(self, dtype: &DataType) -> bool { + matches!( + (self, dtype), + ( + Self::Batch(DistanceType::L2 | DistanceType::Cosine | DistanceType::Dot), + DataType::Float32 | DataType::Int8 | DataType::Int16 | DataType::Int32, + ) + ) + } + + fn error(self, message: impl std::fmt::Display) -> ArrowError { + let name = match self { + Self::Batch(metric) => format!("{metric} batch"), + Self::Multivec(metric, _) => format!("{metric} multivec"), + Self::Norm(Norm::L2) => "L2 norm".to_string(), + Self::Norm(Norm::Squared) => "squared L2 norm".to_string(), + }; + ArrowError::InvalidArgumentError(format!("{name}: {message}")) + } + + fn numeric(self, query: &[T], values: &[T], dim: usize) -> Result> + where + T: L2 + Dot + Cosine + Normalize + AsPrimitive + AsPrimitive, + { + match self { + Self::Batch(metric) => { + let mut distances = vec![0.0; values.len() / dim]; + match metric { + DistanceType::L2 => l2_distance_batch_into(query, values, dim, &mut distances), + DistanceType::Cosine => { + cosine_distance_batch_into(query, values, dim, &mut distances) + } + DistanceType::Dot => { + dot_distance_batch_into(query, values, dim, &mut distances) + } + _ => return Err(self.error("Hamming requires UInt8 values")), + } + Ok(distances) + } + Self::Multivec(metric, rows) => { + Ok(multivec(query, values, dim, rows, metric.try_func()?)) + } + Self::Norm(Norm::L2) => Ok(values.chunks_exact(dim).map(norm_l2).collect()), + Self::Norm(Norm::Squared) => Ok(values + .chunks_exact(dim) + .map(|v| { + // Preserve f64 accumulation for f64, and widen f16 before + // squaring so large and small half values remain finite. + if std::mem::size_of::() > std::mem::size_of::() { + v.iter() + .map(|&v| { + let v: f64 = v.as_(); + v * v + }) + .sum::() as f32 + } else { + v.iter() + .map(|&v| { + let v: f32 = v.as_(); + v * v + }) + .sum() + } + }) + .collect()), + } + } + + fn binary(self, query: &[u8], values: &[u8], dim: usize) -> Result> { + match self { + Self::Batch(DistanceType::Hamming) => { + Ok(hamming::hamming_distance_batch(query, values, dim).collect()) + } + Self::Multivec(DistanceType::Hamming, rows) => { + Ok(multivec(query, values, dim, rows, hamming::hamming)) + } + _ => Err(self.error("UInt8 values require Hamming distance")), + } + } +} + +/// Validate before the only Arrow dtype dispatch used by distances and norms. +pub(super) fn dispatch( + operation: Operation<'_>, + query: Option<&dyn Array>, + vectors: &FixedSizeListArray, +) -> Result> { + let dtype = vectors.value_type(); + let int8_query = query.is_some_and(|query| query.data_type() == &DataType::Int8) + && operation.supports_int8_query(&dtype); + if !operation.supports(&dtype) && !int8_query { + return Err(operation.error(format!("unsupported vector element type {dtype}"))); + } + if let Some(query) = query { + if !int8_query && query.data_type() != &dtype { + return Err(operation.error(format!( + "query type {} does not match the stored vector type {dtype}", + query.data_type() + ))); + } + if query.null_count() > 0 { + return Err(operation.error(format!( + "query must not contain nulls, found {} in {} values", + query.null_count(), + query.len() + ))); + } + } + let dim = vectors.value_length() as usize; + if dim == 0 { + return Err(operation.error("stored vectors have dimension 0")); + } + if let Some(query) = query { + match operation { + Operation::Batch(_) if query.len() != dim => { + return Err(operation.error(format!( + "query length {} must equal the vector dimension {dim}", + query.len() + ))); + } + Operation::Multivec(_, _) if query.is_empty() || !query.len().is_multiple_of(dim) => { + return Err(operation.error(format!( + "query length {} must be a positive multiple of the vector dimension {dim}", + query.len() + ))); + } + _ => {} + } + } + + match dtype { + DataType::Float16 => numeric::(operation, query, vectors, dim), + DataType::Float32 if int8_query => numeric_int8_query(operation, query, vectors, dim), + DataType::Float32 => numeric::(operation, query, vectors, dim), + DataType::Float64 => numeric::(operation, query, vectors, dim), + DataType::Int8 | DataType::Int16 | DataType::Int32 => { + numeric_int8_query(operation, query, vectors, dim) + } + DataType::UInt8 => operation.binary( + query.map_or(&[], |q| q.as_primitive::().values().as_ref()), + vectors.values().as_primitive::().values(), + dim, + ), + _ => Err(operation.error(format!("unsupported vector element type {dtype}"))), + } +} + +fn numeric_int8_query( + operation: Operation<'_>, + query: Option<&dyn Array>, + vectors: &FixedSizeListArray, + dim: usize, +) -> Result> { + let query = query.ok_or_else(|| operation.error("Int8 values require a query"))?; + let query = query.as_primitive::(); + let query = Float32Array::from(query.values().iter().map(|&v| v as f32).collect::>()); + let vectors = vectors.convert_to_floating_point()?; + numeric::(operation, Some(&query), &vectors, dim) +} + +fn numeric( + operation: Operation<'_>, + query: Option<&dyn Array>, + vectors: &FixedSizeListArray, + dim: usize, +) -> Result> +where + T: ArrowPrimitiveType, + T::Native: L2 + Dot + Cosine + Normalize + AsPrimitive + AsPrimitive, +{ + operation.numeric( + query.map_or(&[], |q| q.as_primitive::().values().as_ref()), + vectors.values().as_primitive::().values(), + dim, + ) +} + +fn multivec( + query: &[T], + values: &[T], + dim: usize, + rows: &ListArray, + distance: DistanceFunc, +) -> Vec { + rows.value_offsets() + .windows(2) + .enumerate() + .map(|(row, offsets)| { + if rows.is_null(row) || offsets[0] == offsets[1] { + return f32::NAN; + } + let values = &values[offsets[0] as usize * dim..offsets[1] as usize * dim]; + query + .chunks_exact(dim) + .map(|q| { + values + .chunks_exact(dim) + .map(|v| distance(q, v)) + .min_by(f32::total_cmp) + .unwrap_or(f32::NAN) + }) + .sum() + }) + .collect() +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs b/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs new file mode 100644 index 000000000..032c51b93 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs @@ -0,0 +1,1646 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Cosine distance +//! +//! +//! +//! `bf16, f16, f32, f64` types are supported. + +use std::sync::Arc; + +use arrow_array::{Array, FixedSizeListArray, Float32Array}; +use half::{bf16, f16}; +use lance_core::utils::cpu::SIMD_SUPPORT; + +#[cfg(feature = "fp16kernels")] +use super::HalfBackend; +use super::{ + BatchKernel, Dot, HALF_KERNELS_COMPILED, HalfType, Normalize, assert_batch_output_layout, + assert_equal_lengths, dot::dot, half_backend, norm_l2::norm_l2, x86_half_features, +}; +use crate::Result; +#[cfg(not(target_arch = "x86_64"))] +use crate::simd::{ + FloatSimd, SIMD, + f32::{f32x8, f32x16}, +}; + +/// Cosine Distance +pub trait Cosine: Dot + Normalize { + /// Cosine distance between two vectors. + #[inline] + fn cosine(x: &[Self], other: &[Self]) -> f32 { + let x_norm = norm_l2(x); + Self::cosine_fast(x, x_norm, other) + } + + /// Fast cosine function, that assumes that the norm of the first vector is already known. + #[inline] + fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 { + cosine_scalar(x, x_norm, y) + } + + /// Cosine between two vectors, with the L2 norms of both vectors already known. + #[inline] + fn cosine_with_norms(x: &[Self], x_norm: f32, y_norm: f32, y: &[Self]) -> f32 { + cosine_scalar_fast(x, x_norm, y, y_norm) + } + + /// Writes the cosine distance from `x` to each `dimension`-sized vector + /// in `batch` into the matching element of `output`. + /// + /// The default computes the norm of `x` once and calls + /// [`Cosine::cosine_fast`] per vector. `f32` overrides it with one batch + /// kernel call. + /// + /// # Panics + /// + /// Panics if `x.len() != dimension`, if `batch.len()` is not a multiple of + /// `dimension`, or if `output.len() != batch.len() / dimension`. + fn cosine_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + let x_norm = norm_l2(x); + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = Self::cosine_fast(x, x_norm, y); + } + } +} + +impl Cosine for u8 { + #[inline] + fn cosine(x: &[Self], other: &[Self]) -> f32 { + super::cosine_u8::cosine_u8(x, other) + } +} + +#[cfg(feature = "fp16kernels")] +mod bf16_kernel { + use half::bf16; + + // These are the `cosine_bf16` function in bf16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn cosine_bf16_neon(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32) + -> f32; + #[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))] + pub fn cosine_bf16_avx512( + x: *const bf16, + x_norm: f32, + y: *const bf16, + dimension: u32, + ) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn cosine_bf16_avx2(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32) + -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn cosine_bf16_lsx(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn cosine_bf16_lasx(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32) + -> f32; + } +} + +impl Cosine for bf16 { + fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + match half_backend( + *SIMD_SUPPORT, + HalfType::Bf16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + bf16_kernel::cosine_bf16_neon(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_bf16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + bf16_kernel::cosine_bf16_avx512(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + bf16_kernel::cosine_bf16_avx2(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + bf16_kernel::cosine_bf16_lasx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + bf16_kernel::cosine_bf16_lsx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx fall through here: + // the bf16 C kernels in `bf16_kernel::*` are compiled with + // `-march=haswell` minimum (which requires AVX2), so they cannot + // run on AVX-only or AVX+FMA hosts. Scalar is the correct route. + _ => cosine_scalar(x, x_norm, y), + } + } +} + +#[cfg(feature = "fp16kernels")] +mod kernel { + use super::*; + + // These are the `cosine_f16` function in f16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn cosine_f16_neon(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32; + #[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))] + pub fn cosine_f16_avx512(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn cosine_f16_avx2(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn cosine_f16_lsx(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn cosine_f16_lasx(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32; + } +} + +impl Cosine for f16 { + fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + match half_backend( + *SIMD_SUPPORT, + HalfType::F16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + kernel::cosine_f16_neon(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_f16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + kernel::cosine_f16_avx512(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + kernel::cosine_f16_avx2(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + kernel::cosine_f16_lasx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + kernel::cosine_f16_lsx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx retain their scalar + // route; this fallback only extends the tiers the C kernel already + // served to Avx512FP16 after checking F16C and FMA. + _ => cosine_scalar(x, x_norm, y), + } + } +} + +/// Cosine distance from `x`, whose L2 norm is `x_norm`, to `y`. +type CosineKernel = unsafe fn(&[T], f32, &[T]) -> f32; + +/// Cosine distance between `x` and `y` given both L2 norms, in the argument +/// order of [`Cosine::cosine_with_norms`]. +type CosineWithNormsKernel = unsafe fn(&[f32], f32, f32, &[f32]) -> f32; + +impl Cosine for f32 { + #[inline] + fn cosine_fast(x: &[Self], x_norm: Self, other: &[Self]) -> f32 { + assert_equal_lengths(x.len(), other.len()); + COSINE_F32.get().call(x, x_norm, other) + } + + #[inline] + fn cosine_with_norms(x: &[Self], x_norm: Self, y_norm: Self, y: &[Self]) -> Self { + assert_equal_lengths(x.len(), y.len()); + COSINE_WITH_NORMS_F32.get().call(x, x_norm, y_norm, y) + } + + fn cosine_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + COSINE_F32_BATCH.get().call(x, batch, dimension, output); + } +} + +impl Cosine for f64 { + #[inline] + fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + COSINE_F64.get().call(x, x_norm, y) + } +} + +lance_core::dispatch! { + static COSINE_F32: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::COSINE_F32_AVX512, + x86::COSINE_F32_AVX_FMA, + x86::COSINE_F32_AVX, + COSINE_F32_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[COSINE_F32_PORTABLE] + } + }; +} + +lance_core::dispatch! { + static COSINE_WITH_NORMS_F32: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::COSINE_WITH_NORMS_F32_AVX512, + x86::COSINE_WITH_NORMS_F32_AVX_FMA, + x86::COSINE_WITH_NORMS_F32_AVX, + COSINE_WITH_NORMS_F32_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[COSINE_WITH_NORMS_F32_PORTABLE] + } + }; +} + +lance_core::dispatch! { + /// Unlike `L2_F32_BATCH`, this has an AVX-512 candidate: Haswell builds + /// have always used the AVX-512 kernel on AVX-512 hosts outside the 8- and + /// 16-dimension paths. Keeping those results means Haswell builds select + /// at runtime, at one indirect call per batch. + static COSINE_F32_BATCH: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::COSINE_F32_BATCH_AVX512, + x86::COSINE_F32_BATCH_AVX_FMA, + x86::COSINE_F32_BATCH_AVX, + COSINE_F32_BATCH_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[COSINE_F32_BATCH_PORTABLE] + } + }; +} + +lance_core::dispatch! { + static COSINE_F64: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::COSINE_F64_AVX512, + x86::COSINE_F64_AVX_FMA, + x86::COSINE_F64_AVX, + COSINE_F64_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[COSINE_F64_PORTABLE] + } + }; +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F32_PORTABLE: CosineKernel)] + #[inline] + fn cosine_f32_portable(x: &[f32], x_norm: f32, y: &[f32]) -> f32 { + cosine_f32_from_sums(x, x_norm, y, dot(x, y), dot(y, y)) + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_WITH_NORMS_F32_PORTABLE: CosineWithNormsKernel)] + #[inline] + fn cosine_with_norms_f32_portable(x: &[f32], x_norm: f32, y_norm: f32, y: &[f32]) -> f32 { + cosine_f32_with_norms(x, x_norm, y, dot(x, y), y_norm) + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F32_BATCH_PORTABLE: BatchKernel)] + fn cosine_batch_f32_portable(x: &[f32], batch: &[f32], dimension: usize, output: &mut [f32]) { + let x_norm = norm_l2(x); + // Dim 8 uses the AVX candidates' SSE path so results stay bit-identical + // across candidates. Dim 16 can't use their `f32x16` without AVX, so + // it folds in scalar instead. + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + let key = x86::Sse8::new(key); + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + *distance = key.cosine(x_norm, y); + } + } else if dimension == 16 + && let Ok(key) = <&[f32; 16]>::try_from(x) + { + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<16>().0) { + let (xy, y2) = key + .iter() + .zip(y) + .fold((0.0f32, 0.0f32), |(xy, y2), (&a, &b)| (xy + a * b, y2 + b * b)); + *distance = cosine_f32_from_sums(x, x_norm, y, xy, y2); + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = cosine_f32_from_sums(x, x_norm, y, dot(x, y), dot(y, y)); + } + } + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F64_PORTABLE: CosineKernel)] + #[inline] + fn cosine_f64_portable(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + cosine_scalar(x, x_norm, y) + } +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use super::{ + CosineKernel, CosineWithNormsKernel, cosine_f32_from_sums, cosine_f32_with_norms, dot, + norm_l2, + }; + use crate::distance::BatchKernel; + use crate::simd::f32::{f32x8, f32x16}; + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::x86::{hsum256_pd, hsum256_ps}; + use crate::simd::{FloatSimd, SIMD}; + + /// A preloaded 8-dimension key for every x86 batch kernel. SSE is part of + /// the x86_64 baseline, so this needs no runtime selection. Its reduction + /// order matches `f32x8::reduce_sum`. + pub(super) struct Sse8<'a> { + key: &'a [f32; 8], + lo: __m128, + hi: __m128, + } + + impl<'a> Sse8<'a> { + #[inline] + pub(super) fn new(key: &'a [f32; 8]) -> Self { + // SAFETY: both loads read within the eight-element array, and + // x86_64 guarantees SSE. + unsafe { + Self { + key, + lo: _mm_loadu_ps(key.as_ptr()), + hi: _mm_loadu_ps(key.as_ptr().add(4)), + } + } + } + + #[inline] + pub(super) fn cosine(&self, key_norm: f32, y: &[f32; 8]) -> f32 { + // SAFETY: both loads read within the eight-element array, and + // x86_64 guarantees SSE. + unsafe { + let (lo, hi) = (_mm_loadu_ps(y.as_ptr()), _mm_loadu_ps(y.as_ptr().add(4))); + let xy = _mm_add_ps(_mm_mul_ps(self.lo, lo), _mm_mul_ps(self.hi, hi)); + let y2 = _mm_add_ps(_mm_mul_ps(lo, lo), _mm_mul_ps(hi, hi)); + cosine_f32_from_sums(self.key, key_norm, y, hsum128_ps(xy), hsum128_ps(y2)) + } + } + } + + /// # Safety + /// + /// None beyond SSE, which x86_64 guarantees; `unsafe` only because the + /// intrinsics are `#[target_feature(enable = "sse")]`. + #[inline] + unsafe fn hsum128_ps(values: __m128) -> f32 { + unsafe { + let sum64 = _mm_add_ps(values, _mm_movehl_ps(values, values)); + let sum32 = _mm_add_ss(sum64, _mm_shuffle_ps(sum64, sum64, 0x55)); + _mm_cvtss_f32(sum32) + } + } + + /// Fills `output` for the 8- and 16-dimension PQ widths shared by every + /// AVX batch kernel, returning `false` for any other layout. + #[target_feature(enable = "avx")] + #[inline] + fn cosine_batch_f32_narrow( + x: &[f32], + x_norm: f32, + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) -> bool { + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + // The SSE path benchmarks faster than `f32x8` at this width and + // keeps every candidate bit-identical. + let key = Sse8::new(key); + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + *distance = key.cosine(x_norm, y); + } + true + } else if dimension == 16 + && let Ok(key) = <&[f32; 16]>::try_from(x) + { + // SAFETY: the load reads within the sixteen-element array. + let key = unsafe { f32x16::load_unaligned(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<16>().0) { + // SAFETY: the load reads within the sixteen-element array. + let yv = unsafe { f32x16::load_unaligned(y.as_ptr()) }; + let xy = key * yv; + let y2 = yv * yv; + *distance = cosine_f32_from_sums(x, x_norm, y, xy.reduce_sum(), y2.reduce_sum()); + } + true + } else { + false + } + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) COSINE_F32_BATCH_AVX512: BatchKernel)] + pub(super) fn cosine_batch_f32_avx512( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + let x_norm = norm_l2(x); + if !cosine_batch_f32_narrow(x, x_norm, batch, dimension, output) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = cosine_f32_avx512(x, x_norm, y); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) COSINE_F32_BATCH_AVX_FMA: BatchKernel)] + pub(super) fn cosine_batch_f32_avx_fma( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + let x_norm = norm_l2(x); + if !cosine_batch_f32_narrow(x, x_norm, batch, dimension, output) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = cosine_f32_avx_fma(x, x_norm, y); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) COSINE_F32_BATCH_AVX: BatchKernel)] + pub(super) fn cosine_batch_f32_avx( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + let x_norm = norm_l2(x); + if !cosine_batch_f32_narrow(x, x_norm, batch, dimension, output) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = cosine_f32_avx(x, x_norm, y); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) COSINE_F32_AVX512: CosineKernel)] + /// 16-wide `__m512` xy/yy with `vfmadd231ps` per iteration. + #[inline] + pub(super) fn cosine_f32_avx512(x: &[f32], x_norm: f32, other: &[f32]) -> f32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(other.len()); + let unrolled_len = dim / 16 * 16; + + let mut acc_xy = _mm512_setzero_ps(); + let mut acc_yy = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm512_loadu_ps(x.as_ptr().add(i)), + _mm512_loadu_ps(other.as_ptr().add(i)), + ) + }; + acc_xy = _mm512_fmadd_ps(xv, yv, acc_xy); + acc_yy = _mm512_fmadd_ps(yv, yv, acc_yy); + } + + let mut xy = _mm512_reduce_add_ps(acc_xy); + let mut yy = _mm512_reduce_add_ps(acc_yy); + for i in unrolled_len..dim { + xy += x[i] * other[i]; + yy += other[i] * other[i]; + } + + cosine_f32_from_sums(x, x_norm, other, xy, yy) + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) COSINE_F32_AVX_FMA: CosineKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn cosine_f32_avx_fma(x: &[f32], x_norm: f32, other: &[f32]) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(other.len()); + let unrolled_len = dim / 16 * 16; + let mut y_norm16 = f32x16::zeros(); + let mut xy16 = f32x16::zeros(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x16::load_unaligned(x.as_ptr().add(i)), + f32x16::load_unaligned(other.as_ptr().add(i)), + ) + }; + xy16.multiply_add(xv, yv); + y_norm16.multiply_add(yv, yv); + } + let aligned_len = dim / 8 * 8; + let mut y_norm8 = f32x8::zeros(); + let mut xy8 = f32x8::zeros(); + for i in (unrolled_len..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x8::load_unaligned(x.as_ptr().add(i)), + f32x8::load_unaligned(other.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + y_norm8.multiply_add(yv, yv); + } + let y_norm = + y_norm16.reduce_sum() + y_norm8.reduce_sum() + norm_l2(&other[aligned_len..]).powi(2); + let xy = + xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &other[aligned_len..]); + cosine_f32_from_sums(x, x_norm, other, xy, y_norm) + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) COSINE_F32_AVX: CosineKernel)] + /// AVX-only path (no FMA) for Sandy/Ivy Bridge. + #[inline] + pub(super) fn cosine_f32_avx(x: &[f32], x_norm: f32, other: &[f32]) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(other.len()); + let aligned_len = dim / 8 * 8; + + let mut acc_xy = _mm256_setzero_ps(); + let mut acc_yy = _mm256_setzero_ps(); + for i in (0..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(other.as_ptr().add(i)), + ) + }; + acc_xy = _mm256_add_ps(acc_xy, _mm256_mul_ps(xv, yv)); + acc_yy = _mm256_add_ps(acc_yy, _mm256_mul_ps(yv, yv)); + } + + // SAFETY: AVX is enabled for this function. + let (xy_main, yy_main) = unsafe { (hsum256_ps(acc_xy), hsum256_ps(acc_yy)) }; + + let y_norm = yy_main + norm_l2(&other[aligned_len..]).powi(2); + let xy = xy_main + dot(&x[aligned_len..], &other[aligned_len..]); + cosine_f32_from_sums(x, x_norm, other, xy, y_norm) + } + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) COSINE_WITH_NORMS_F32_AVX512: CosineWithNormsKernel)] + /// 16-wide `__m512` with `vfmadd231ps` per iteration. + #[inline] + pub(super) fn cosine_with_norms_f32_avx512( + x: &[f32], + x_norm: f32, + y_norm: f32, + y: &[f32], + ) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 16 * 16; + + let mut acc = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm512_loadu_ps(x.as_ptr().add(i)), + _mm512_loadu_ps(y.as_ptr().add(i)), + ) + }; + acc = _mm512_fmadd_ps(xv, yv, acc); + } + + let mut xy = _mm512_reduce_add_ps(acc); + for i in unrolled_len..dim { + xy += x[i] * y[i]; + } + + cosine_f32_with_norms(x, x_norm, y, xy, y_norm) + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) COSINE_WITH_NORMS_F32_AVX_FMA: CosineWithNormsKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn cosine_with_norms_f32_avx_fma( + x: &[f32], + x_norm: f32, + y_norm: f32, + y: &[f32], + ) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 16 * 16; + let mut xy16 = f32x16::zeros(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x16::load_unaligned(x.as_ptr().add(i)), + f32x16::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy16.multiply_add(xv, yv); + } + let aligned_len = dim / 8 * 8; + let mut xy8 = f32x8::zeros(); + for i in (unrolled_len..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x8::load_unaligned(x.as_ptr().add(i)), + f32x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + } + let xy = + xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &y[aligned_len..]); + cosine_f32_with_norms(x, x_norm, y, xy, y_norm) + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) COSINE_WITH_NORMS_F32_AVX: CosineWithNormsKernel)] + /// AVX-only path (no FMA) for Sandy/Ivy Bridge. + #[inline] + pub(super) fn cosine_with_norms_f32_avx( + x: &[f32], + x_norm: f32, + y_norm: f32, + y: &[f32], + ) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let aligned_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(y.as_ptr().add(i)), + ) + }; + acc = _mm256_add_ps(acc, _mm256_mul_ps(xv, yv)); + } + + // SAFETY: AVX is enabled for this function. + let xy_main = unsafe { hsum256_ps(acc) }; + let xy = xy_main + dot(&x[aligned_len..], &y[aligned_len..]); + cosine_f32_with_norms(x, x_norm, y, xy, y_norm) + } + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) COSINE_F64_AVX512: CosineKernel)] + /// 8-wide `__m512d` xy/yy with `vfmadd231pd` per iteration. + #[inline] + pub(super) fn cosine_f64_avx512(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc_xy = _mm512_setzero_pd(); + let mut acc_yy = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm512_loadu_pd(x.as_ptr().add(i)), + _mm512_loadu_pd(y.as_ptr().add(i)), + ) + }; + acc_xy = _mm512_fmadd_pd(xv, yv, acc_xy); + acc_yy = _mm512_fmadd_pd(yv, yv, acc_yy); + } + + let mut xy = _mm512_reduce_add_pd(acc_xy); + let mut yy = _mm512_reduce_add_pd(acc_yy); + for i in unrolled_len..dim { + xy += x[i] * y[i]; + yy += y[i] * y[i]; + } + + let y_norm_sq = yy as f32; + let xy_f32 = xy as f32; + 1.0 - xy_f32 / x_norm / y_norm_sq.sqrt() + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) COSINE_F64_AVX_FMA: CosineKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn cosine_f64_avx_fma(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + let mut y_norm8 = f64x8::zeros(); + let mut xy8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + y_norm8.multiply_add(yv, yv); + } + let aligned_len = dim / 4 * 4; + let mut y_norm4 = f64x4::zeros(); + let mut xy4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy4.multiply_add(xv, yv); + y_norm4.multiply_add(yv, yv); + } + let tail_y_norm: f64 = y[aligned_len..].iter().map(|&v| v * v).sum(); + let tail_xy: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + let y_norm_sq = (y_norm8.reduce_sum() + y_norm4.reduce_sum() + tail_y_norm) as f32; + let xy = (xy8.reduce_sum() + xy4.reduce_sum() + tail_xy) as f32; + 1.0 - xy / x_norm / y_norm_sq.sqrt() + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) COSINE_F64_AVX: CosineKernel)] + /// AVX-only path (no FMA) for Sandy/Ivy Bridge. + #[inline] + pub(super) fn cosine_f64_avx(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + // See `cosine_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let aligned_len = dim / 4 * 4; + + let mut acc_xy = _mm256_setzero_pd(); + let mut acc_yy = _mm256_setzero_pd(); + for i in (0..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + _mm256_loadu_pd(x.as_ptr().add(i)), + _mm256_loadu_pd(y.as_ptr().add(i)), + ) + }; + acc_xy = _mm256_add_pd(acc_xy, _mm256_mul_pd(xv, yv)); + acc_yy = _mm256_add_pd(acc_yy, _mm256_mul_pd(yv, yv)); + } + + // SAFETY: AVX is enabled for this function. + let (xy_main, yy_main) = unsafe { (hsum256_pd(acc_xy), hsum256_pd(acc_yy)) }; + + let tail_y_norm: f64 = y[aligned_len..].iter().map(|&v| v * v).sum(); + let tail_xy: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + let y_norm_sq = (yy_main + tail_y_norm) as f32; + let xy = (xy_main + tail_xy) as f32; + 1.0 - xy / x_norm / y_norm_sq.sqrt() + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F32_PORTABLE: CosineKernel)] + /// `simd::f32` is backed by the baseline NEON or LSX on these architectures. + #[inline] + fn cosine_f32_portable(x: &[f32], x_norm: f32, other: &[f32]) -> f32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(other.len()); + let unrolled_len = dim / 16 * 16; + let mut y_norm16 = f32x16::zeros(); + let mut xy16 = f32x16::zeros(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x16::load_unaligned(x.as_ptr().add(i)), + f32x16::load_unaligned(other.as_ptr().add(i)), + ) + }; + xy16.multiply_add(xv, yv); + y_norm16.multiply_add(yv, yv); + } + let aligned_len = dim / 8 * 8; + let mut y_norm8 = f32x8::zeros(); + let mut xy8 = f32x8::zeros(); + for i in (unrolled_len..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x8::load_unaligned(x.as_ptr().add(i)), + f32x8::load_unaligned(other.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + y_norm8.multiply_add(yv, yv); + } + let y_norm = + y_norm16.reduce_sum() + y_norm8.reduce_sum() + norm_l2(&other[aligned_len..]).powi(2); + let xy = xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &other[aligned_len..]); + cosine_f32_from_sums(x, x_norm, other, xy, y_norm) + } +} + +#[cfg(not(target_arch = "x86_64"))] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_WITH_NORMS_F32_PORTABLE: CosineWithNormsKernel)] + /// See `cosine_f32_portable` for the SIMD backends. + #[inline] + fn cosine_with_norms_f32_portable(x: &[f32], x_norm: f32, y_norm: f32, y: &[f32]) -> f32 { + // See `cosine_f32_portable` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 16 * 16; + let mut xy16 = f32x16::zeros(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x16::load_unaligned(x.as_ptr().add(i)), + f32x16::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy16.multiply_add(xv, yv); + } + let aligned_len = dim / 8 * 8; + let mut xy8 = f32x8::zeros(); + for i in (unrolled_len..aligned_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f32x8::load_unaligned(x.as_ptr().add(i)), + f32x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + } + let xy = xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &y[aligned_len..]); + cosine_f32_with_norms(x, x_norm, y, xy, y_norm) + } +} + +#[cfg(not(target_arch = "x86_64"))] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F32_BATCH_PORTABLE: BatchKernel)] + /// See `cosine_f32_portable` for the SIMD backends. + fn cosine_batch_f32_portable(x: &[f32], batch: &[f32], dimension: usize, output: &mut [f32]) { + let x_norm = norm_l2(x); + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + // SAFETY: the load reads within the eight-element array. + let key = unsafe { f32x8::load_unaligned(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + // SAFETY: the load reads within the eight-element array. + let yv = unsafe { f32x8::load_unaligned(y.as_ptr()) }; + let xy = key * yv; + let y2 = yv * yv; + *distance = cosine_f32_from_sums(x, x_norm, y, xy.reduce_sum(), y2.reduce_sum()); + } + } else if dimension == 16 + && let Ok(key) = <&[f32; 16]>::try_from(x) + { + // SAFETY: the load reads within the sixteen-element array. + let key = unsafe { f32x16::load_unaligned(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<16>().0) { + // SAFETY: the load reads within the sixteen-element array. + let yv = unsafe { f32x16::load_unaligned(y.as_ptr()) }; + let xy = key * yv; + let y2 = yv * yv; + *distance = cosine_f32_from_sums(x, x_norm, y, xy.reduce_sum(), y2.reduce_sum()); + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = cosine_f32_portable(x, x_norm, y); + } + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_F64_PORTABLE: CosineKernel)] + /// `simd::f64` is backed by the baseline NEON or LSX on these architectures. + #[inline] + fn cosine_f64_portable(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + use crate::simd::f64::{f64x4, f64x8}; + + // See `cosine_f32_portable` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + let mut y_norm8 = f64x8::zeros(); + let mut xy8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy8.multiply_add(xv, yv); + y_norm8.multiply_add(yv, yv); + } + let aligned_len = dim / 4 * 4; + let mut y_norm4 = f64x4::zeros(); + let mut xy4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (xv, yv) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + xy4.multiply_add(xv, yv); + y_norm4.multiply_add(yv, yv); + } + let tail_y_norm: f64 = y[aligned_len..].iter().map(|&v| v * v).sum(); + let tail_xy: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + let y_norm_sq = (y_norm8.reduce_sum() + y_norm4.reduce_sum() + tail_y_norm) as f32; + let xy = (xy8.reduce_sum() + xy4.reduce_sum() + tail_xy) as f32; + 1.0 - xy / x_norm / y_norm_sq.sqrt() + } +} + +/// Keep ordinary vectors on the SIMD path. If squared norms approach the +/// underflow boundary or overflow, recompute from the original coordinates. +#[inline] +fn cosine_f32_from_sums(x: &[f32], x_norm: f32, y: &[f32], xy: f32, yy: f32) -> f32 { + if cosine_f32_norm_in_range(x_norm * x_norm, x.len()) + && cosine_f32_norm_in_range(yy, y.len()) + && xy.is_finite() + { + 1.0 - xy / x_norm / yy.sqrt() + } else { + cosine_f32_wide(x, y) + } +} + +#[inline] +fn cosine_f32_with_norms(x: &[f32], x_norm: f32, y: &[f32], xy: f32, y_norm: f32) -> f32 { + if cosine_f32_norm_in_range(x_norm * x_norm, x.len()) + && cosine_f32_norm_in_range(y_norm * y_norm, y.len()) + && xy.is_finite() + { + 1.0 - xy / x_norm / y_norm + } else { + cosine_f32_wide(x, y) + } +} + +#[inline] +fn cosine_f32_norm_in_range(squared_norm: f32, dimension: usize) -> bool { + // A sum of many subnormal squares can itself be normal. Allow room for + // their accumulated rounding error instead of checking only is_normal(). + squared_norm.is_normal() && squared_norm >= f32::MIN_POSITIVE * dimension as f32 +} + +/// Every finite f32 coordinate product and sum fits in f64, even for subnormal +/// coordinates. Widen before multiplication, and narrow only the final distance. +#[cold] +fn cosine_f32_wide(x: &[f32], y: &[f32]) -> f32 { + let (mut xx, mut xy, mut yy) = (0.0_f64, 0.0_f64, 0.0_f64); + for (&a, &b) in x.iter().zip(y) { + let (a, b) = (f64::from(a), f64::from(b)); + xx += a * a; + xy += a * b; + yy += b * b; + } + // Limit roundoff for self matches; zero vectors still produce NaN. + (1.0 - (xy / xx.sqrt() / yy.sqrt()).clamp(-1.0, 1.0)) as f32 +} + +/// Fallback non-SIMD implementation +#[inline] +fn cosine_scalar(x: &[T], x_norm: f32, y: &[T]) -> f32 { + let y_sq = dot(y, y); + let xy = dot(x, y); + // 1 - xy / (sqrt(x_sq) * sqrt(y_sq)) + 1.0 - xy / (x_norm * y_sq.sqrt()) +} + +#[inline] +pub(crate) fn cosine_scalar_fast(x: &[T], x_norm: f32, y: &[T], y_norm: f32) -> f32 { + let xy = dot(x, y); + // 1 - xy / (sqrt(x_sq) * sqrt(y_sq)) + // use f64 for overflow protection. + 1.0 - (xy / (x_norm * y_norm)) +} + +/// Cosine distance function between two vectors. +pub fn cosine_distance(from: &[T], to: &[T]) -> f32 { + T::cosine(from, to) +} + +/// Writes the [cosine distance](https://en.wikipedia.org/wiki/Cosine_similarity) +/// from `from` to each `dimension`-sized vector in `batch` into the matching +/// element of `output`. +/// +/// # Panics +/// +/// Panics if `from.len() != dimension`, if `batch.len()` is not a multiple of +/// `dimension`, or if `output.len() != batch.len() / dimension`. +/// +/// ``` +/// # use lance_linalg::distance::cosine_distance_batch_into; +/// let mut distances = [0.0; 2]; +/// cosine_distance_batch_into(&[1.0_f32, 0.0], &[2.0, 0.0, 0.0, 3.0], 2, &mut distances); +/// assert_eq!(distances, [0.0, 1.0]); +/// ``` +#[inline] +pub fn cosine_distance_batch_into( + from: &[T], + batch: &[T], + dimension: usize, + output: &mut [f32], +) { + T::cosine_batch_into(from, batch, dimension, output); +} + +/// Compute cosine distances, propagating the null buffer of `to`. +/// +/// See [`super::DistanceType::batch`] for supported types and input validation. +#[deprecated(note = "Use DistanceType::Cosine.batch")] +pub fn cosine_distance_arrow_batch( + from: &dyn Array, + to: &FixedSizeListArray, +) -> Result> { + super::DistanceType::Cosine.batch(from, to).map(Arc::new) +} + +/// Portable scalar reference cosine over f64 inputs. Used by tests to compare +/// against every cosine kernel candidate. Computes +/// `1 - xy / (x_norm * y_norm_sq.sqrt())` in f64 then casts to f32, matching +/// the reduction order of the dispatched kernels. +#[cfg(test)] +fn cosine_fast_scalar(x: &[f64], x_norm: f32, y: &[f64]) -> f32 { + let xy: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum(); + let y_norm_sq: f64 = y.iter().map(|&v| v * v).sum(); + 1.0 - (xy as f32) / x_norm / (y_norm_sq as f32).sqrt() +} + +/// Portable scalar reference cosine when both norms are known. Mirrors +/// `Cosine::cosine_with_norms` for testing. +#[cfg(test)] +fn cosine_with_norms_scalar(x: &[f64], x_norm: f32, y_norm: f32, y: &[f64]) -> f32 { + let xy: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum(); + 1.0 - (xy as f32) / x_norm / y_norm +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::test_utils::{ + arbitrary_bf16, arbitrary_f16, arbitrary_f32, arbitrary_f64, arbitrary_vector_pair, + dimension_shard, run_vector_pair_proptest, + }; + use approx::assert_relative_eq; + use num_traits::AsPrimitive; + use proptest::prelude::*; + + fn cosine_dist_brute_force(x: &[f32], y: &[f32]) -> f32 { + let xy = x + .iter() + .zip(y.iter()) + .map(|(&xi, &yi)| xi * yi) + .sum::(); + let x_sq = x.iter().map(|&xi| xi * xi).sum::().sqrt(); + let y_sq = y.iter().map(|&yi| yi * yi).sum::().sqrt(); + 1.0 - xy / x_sq / y_sq + } + + #[test] + fn half_cosine_rejects_mismatched_lengths_before_ffi() { + let f16_x = [f16::from_f32(1.0)]; + let f16_y = [f16::from_f32(1.0), f16::from_f32(2.0)]; + assert!( + std::panic::catch_unwind(|| ::cosine_fast(&f16_x, 1.0, &f16_y)).is_err() + ); + + let bf16_x = [bf16::from_f32(1.0)]; + let bf16_y = [bf16::from_f32(1.0), bf16::from_f32(2.0)]; + assert!( + std::panic::catch_unwind(|| ::cosine_fast(&bf16_x, 1.0, &bf16_y)) + .is_err() + ); + } + + #[test] + fn float_cosine_rejects_mismatched_lengths() { + let f32_x = [1.0_f32]; + let f32_y = [1.0_f32, 2.0]; + assert!( + std::panic::catch_unwind(|| ::cosine_fast(&f32_x, 1.0, &f32_y)).is_err() + ); + assert!( + std::panic::catch_unwind(|| ::cosine_with_norms( + &f32_x, 1.0, 1.0, &f32_y + )) + .is_err() + ); + + let f64_x = [1.0_f64]; + let f64_y = [1.0_f64, 2.0]; + assert!( + std::panic::catch_unwind(|| ::cosine_fast(&f64_x, 1.0, &f64_y)).is_err() + ); + } + + #[test] + fn test_cosine() { + let x: Float32Array = (1..9).map(|v| v as f32).collect(); + let y: Float32Array = (100..108).map(|v| v as f32).collect(); + let d = cosine_distance_batch_vec(x.values(), y.values(), 8); + // from scipy.spatial.distance.cosine + assert_relative_eq!(d[0], 1.0 - 0.900_957); + + let x = Float32Array::from_iter_values([3.0, 45.0, 7.0, 2.0, 5.0, 20.0, 13.0, 12.0]); + let y = Float32Array::from_iter_values([2.0, 54.0, 13.0, 15.0, 22.0, 34.0, 50.0, 1.0]); + let d = cosine_distance_batch_vec(x.values(), y.values(), 8); + // from sklearn.metrics.pairwise import cosine_similarity + assert_relative_eq!(d[0], 1.0 - 0.873_580_63); + } + + #[test] + fn test_cosine_large() { + let total = 1024; + let x = (0..total).map(|v| v as f32).collect::>(); + let y = (1024..1024 + total).map(|v| v as f32).collect::>(); + let d = cosine_distance_batch_vec(&x, &y, total); + assert_relative_eq!(d[0], cosine_dist_brute_force(&x, &y)); + } + + #[test] + fn test_cosine_not_aligned() { + let x: Float32Array = vec![16_f32, 32_f32].into(); + let y: Float32Array = vec![1_f32, 2_f32, 4_f32, 8_f32].into(); + let d = cosine_distance_batch_vec(x.values(), y.values(), 2); + assert_relative_eq!(d[0], 0.0); + assert_relative_eq!(d[0], 0.0); + } + + /// Reference implementation of cosine distance, plus error propagation. + /// + /// Pass `rel_err` to provide the allowed relative error in the dot product + /// results. This function will then compute the expected absolute error. + fn cosine_ref(x: &[f64], y: &[f64], rel_err: f64) -> (f32, f32) { + let xy = x + .iter() + .zip(y.iter()) + .map(|(&xi, &yi)| xi * yi) + .sum::(); + let x_sq = x.iter().map(|&xi| xi * xi).sum::().sqrt(); + let y_sq = y.iter().map(|&yi| yi * yi).sum::().sqrt(); + let expected = (1.0 - xy / x_sq / y_sq) as f32; + + let factor = 1.0 + rel_err; + let low = (1.0 - (xy * factor) / (x_sq / factor) / (y_sq / factor)) as f32; + let high = (1.0 - (xy / factor) / (x_sq * factor) / (y_sq * factor)) as f32; + let low = (expected - low).abs(); + let high = (expected - high).abs(); + let error = low.max(high); + + (expected, error) + } + + fn do_cosine_test>( + x: &[T], + y: &[T], + ) -> std::result::Result<(), TestCaseError> { + let x_f64 = x.iter().map(|&v| v.as_()).collect::>(); + let y_f64 = y.iter().map(|&v| v.as_()).collect::>(); + + let (expected, max_error) = cosine_ref(&x_f64, &y_f64, 1e-6); + let result = T::cosine(x, y); + + prop_assert!(approx::relative_eq!(result, expected, epsilon = max_error)); + Ok(()) + } + + #[rstest::rstest] + fn test_cosine_f32( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + prop_assume!(norm_l2(&x) > 1e-10); + prop_assume!(norm_l2(&y) > 1e-10); + do_cosine_test(&x, &y) + }); + } + + #[rstest::rstest] + fn test_cosine_f64( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + prop_assume!(norm_l2(&x) > 1e-20); + prop_assume!(norm_l2(&y) > 1e-20); + do_cosine_test(&x, &y) + }); + } + + fn assert_extreme_cosine_kernels(x: &[f32], vectors: &[Vec]) { + let expected: Vec = vectors + .iter() + .map(|y| { + let xy: f64 = x + .iter() + .zip(y) + .map(|(&a, &b)| f64::from(a) * f64::from(b)) + .sum(); + let xx: f64 = x.iter().map(|&a| f64::from(a).powi(2)).sum(); + let yy: f64 = y.iter().map(|&b| f64::from(b).powi(2)).sum(); + (1.0 - xy / (xx * yy).sqrt()) as f32 + }) + .collect(); + let x_norm = norm_l2(x); + for (y, &want) in vectors.iter().zip(&expected) { + assert_relative_eq!(f32::cosine(x, y), want, epsilon = 1e-6); + assert_relative_eq!( + f32::cosine_with_norms(x, x_norm, norm_l2(y), y), + want, + epsilon = 1e-6 + ); + for candidate in COSINE_F32.candidates() { + if let Some(kernel) = candidate.kernel() { + let got = kernel.call(x, x_norm, y); + assert_relative_eq!(got, want, epsilon = 1e-6); + } + } + for candidate in COSINE_WITH_NORMS_F32.candidates() { + if let Some(kernel) = candidate.kernel() { + let got = kernel.call(x, x_norm, norm_l2(y), y); + assert_relative_eq!(got, want, epsilon = 1e-6); + } + } + } + let batch: Vec<_> = vectors.iter().flat_map(|y| y.iter().copied()).collect(); + for candidate in COSINE_F32_BATCH.candidates() { + if let Some(kernel) = candidate.kernel() { + let mut got = vec![f32::NAN; vectors.len()]; + kernel.call(x, &batch, x.len(), &mut got); + for (&got, &want) in got.iter().zip(&expected) { + assert_relative_eq!(got, want, epsilon = 1e-6); + } + } + } + } + + #[rstest::rstest] + fn test_cosine_f32_extreme_magnitudes(#[values(2, 8, 16, 33, 1024)] dimension: usize) { + let scales = [ + f32::from_bits(1), + f32::MIN_POSITIVE, + 1e-30, + 1e-20, + 1.0, + 1e20, + f32::MAX, + ]; + for x_scale in scales { + for y_scale in scales { + let mut x = vec![0.0; dimension]; + x[0] = x_scale; + let mut y = vec![0.0; dimension]; + y[0] = y_scale; + let mut angled = vec![0.0; dimension]; + angled[0] = 0.5 * y_scale; + angled[1] = 0.8660254 * y_scale; + let opposite = y.iter().map(|v| -v).collect(); + let mut orthogonal = vec![0.0; dimension]; + orthogonal[1] = y_scale; + assert_extreme_cosine_kernels(&x, &[y, angled, opposite, orthogonal]); + } + } + } + + #[rstest::rstest] + fn test_cosine_f32_dense_extreme_magnitudes(#[values(8, 16, 33, 1024)] dimension: usize) { + for scale in [1e-22, 1e-21, 1e-20, 1e18, 1e19, 1e20] { + let x = vec![scale; dimension]; + let y = (0..dimension) + .map(|i| { + if i % 2 == 0 { + scale * 0.5 + } else { + -scale * 0.75 + } + }) + .collect(); + assert_extreme_cosine_kernels(&x, &[x.clone(), y]); + } + } + + /// Checks one cosine distance against an f64 reference. The absolute + /// `epsilon` covers inputs with extreme dynamic range, where a near-zero + /// result differs between f32 and f64 accumulation by more than + /// `max_relative` of itself. + fn check_cosine( + got: f32, + want: f32, + kernel: &str, + dimension: usize, + ) -> std::result::Result<(), TestCaseError> { + prop_assert!( + approx::relative_eq!(got, want, max_relative = 1e-3, epsilon = 1e-6), + "{kernel} at dim {dimension}: {got} != {want}" + ); + Ok(()) + } + + /// Every host-supported f32 kernel, single-pair and batch, must agree with + /// an f64 reference. Prefixes of length 8 and 16 pin the batch kernels' + /// PQ-width fast paths regardless of the generated dimension. + #[rstest::rstest] + fn test_cosine_f32_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + for dimension in [8, 16, x.len()].into_iter().filter(|&d| d <= x.len()) { + let (x, y) = (&x[..dimension], &y[..dimension]); + let (x_norm, y_norm) = (norm_l2(x), norm_l2(y)); + if x_norm <= 1e-10 || y_norm <= 1e-10 { + continue; + } + let x_f64: Vec = x.iter().map(|&v| v as f64).collect(); + let y_f64: Vec = y.iter().map(|&v| v as f64).collect(); + let want = cosine_fast_scalar(&x_f64, x_norm, &y_f64); + let want_with_norms = cosine_with_norms_scalar(&x_f64, x_norm, y_norm, &y_f64); + let want_self = cosine_fast_scalar(&x_f64, x_norm, &x_f64); + + for candidate in COSINE_F32.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + check_cosine(kernel.call(x, x_norm, y), want, candidate.name(), dimension)?; + } + + for candidate in COSINE_WITH_NORMS_F32.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(x, x_norm, y_norm, y); + check_cosine(got, want_with_norms, candidate.name(), dimension)?; + } + + let batch = [y, x].concat(); + let mut pq_width_result = None; + for candidate in COSINE_F32_BATCH.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut got = [f32::NAN; 2]; + kernel.call(x, &batch, dimension, &mut got); + check_cosine(got[0], want, candidate.name(), dimension)?; + check_cosine(got[1], want_self, candidate.name(), dimension)?; + + // At the PQ widths every candidate shares one reduction + // order, except the x86 portable kernel at 16 dimensions, + // which cannot use the AVX `f32x16`. + let shares_pq_path = dimension == 8 + || (dimension == 16 + && (cfg!(not(target_arch = "x86_64")) + || !candidate.features().is_empty())); + if shares_pq_path { + let bits = got.map(f32::to_bits); + let (first, first_bits) = + *pq_width_result.get_or_insert((candidate.name(), bits)); + prop_assert_eq!( + bits, + first_bits, + "{} and {} differ at dim {}", + candidate.name(), + first, + dimension + ); + } + } + } + Ok(()) + }); + } + + /// Every host-supported f64 kernel must agree with an f64 reference. + #[rstest::rstest] + fn test_cosine_f64_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + prop_assume!(norm_l2(&x) > 1e-20); + prop_assume!(norm_l2(&y) > 1e-20); + let x_norm = norm_l2(&x); + let want = cosine_fast_scalar(&x, x_norm, &y); + for candidate in COSINE_F64.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + check_cosine(kernel.call(&x, x_norm, &y), want, candidate.name(), x.len())?; + } + Ok(()) + }); + } + + proptest::proptest! { + #[test] + fn test_cosine_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) { + // Cosine requires non-zero vectors + prop_assume!(norm_l2(&x) > 1e-6); + prop_assume!(norm_l2(&y) > 1e-6); + do_cosine_test(&x, &y)?; + } + + #[test] + fn test_cosine_bf16((x, y) in arbitrary_vector_pair(arbitrary_bf16, 4..4048)){ + prop_assume!(norm_l2(&x) > 1e-6); + prop_assume!(norm_l2(&y) > 1e-6); + do_cosine_test(&x, &y)?; + } + } + + /// The f32 arrow path fills every distance with one batch kernel call; it + /// must match the per-vector `cosine` and keep the targets' nulls. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_40(40)] + fn test_cosine_arrow_batch_f32_matches_per_vector(#[case] dimension: usize) { + let num_vectors = 70; + let x: Vec = (0..dimension) + .map(|index| (index % 13) as f32 * 0.25 + 1.0) + .collect(); + let batch: Vec = (0..dimension * num_vectors) + .map(|index| (index % 11) as f32 * 0.5 - 2.0) + .collect(); + let nulls = arrow_buffer::NullBuffer::from_iter((0..num_vectors).map(|i| i % 3 != 0)); + let to = FixedSizeListArray::try_new( + Arc::new(arrow_schema::Field::new( + "item", + arrow_schema::DataType::Float32, + true, + )), + dimension as i32, + Arc::new(Float32Array::from(batch.clone())), + Some(nulls.clone()), + ) + .unwrap(); + + let got = crate::distance::DistanceType::Cosine + .batch(&Float32Array::from(x.clone()), &to) + .unwrap(); + + assert_eq!(got.nulls(), Some(&nulls)); + for (got, vector) in got.values().iter().zip(batch.chunks_exact(dimension)) { + assert_relative_eq!(*got, f32::cosine(&x, vector), max_relative = 1e-5); + } + } + + fn cosine_distance_batch_vec(from: &[T], to: &[T], dimension: usize) -> Vec { + let mut distances = vec![0.0; to.len() / dimension]; + cosine_distance_batch_into(from, to, dimension, &mut distances); + distances + } + + /// `cosine_batch_into` must agree with the per-vector `cosine`, both for + /// the f32 batch kernel and for the per-vector default that f64 uses. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_12(12)] + #[case::dim_16(16)] + #[case::dim_40(40)] + #[case::dim_1024(1024)] + fn test_cosine_batch_into_matches_per_vector(#[case] dimension: usize) { + fn check(dimension: usize) { + let num_vectors = 130; + let x: Vec = (0..dimension) + .map(|index| T::from_f32((index % 13) as f32 * 0.25 + 1.0).unwrap()) + .collect(); + let batch: Vec = (0..dimension * num_vectors) + .map(|index| T::from_f32((index % 11) as f32 * 0.5 - 2.0).unwrap()) + .collect(); + + let mut got = vec![f32::NAN; num_vectors]; + T::cosine_batch_into(&x, &batch, dimension, &mut got); + + for (distance, vector) in got.iter().zip(batch.chunks_exact(dimension)) { + let expected = T::cosine(&x, vector); + assert_relative_eq!(*distance, expected, max_relative = 1e-5, epsilon = 1e-6); + } + } + check::(dimension); + check::(dimension); + } + + #[rstest::rstest] + #[case::short(1)] + #[case::long(3)] + fn test_cosine_batch_into_rejects_wrong_output_len(#[case] output_len: usize) { + let batch = [1.0_f32; 4]; + let mut output = vec![0.0; output_len]; + let result = std::panic::catch_unwind(move || { + cosine_distance_batch_into(&[1.0_f32, 2.0], &batch, 2, &mut output) + }); + assert!(result.is_err()); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/cosine_u8.rs b/rust/lancedb/vendor/lance-linalg/src/distance/cosine_u8.rs new file mode 100644 index 000000000..182442b58 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/cosine_u8.rs @@ -0,0 +1,357 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Unsigned int8 cosine distance with runtime-dispatched SIMD backends. +//! +//! Computes `1 - dot(a,b) / (‖a‖ × ‖b‖)` for u8 slices in a single +//! pass over the data. The fused kernel maintains three accumulators +//! simultaneously — `Σ(a·b)`, `Σ(a²)`, `Σ(b²)` — so memory is only +//! traversed once instead of 2-3 times (norm + dot). +//! +//! Backends (selected at runtime, best available wins): +//! 1. scalar — portable reference, also used for tails +//! 2. avx2 — zero-extend u8→i16, triple VPMADDWD, 32 elements/iter +//! 3. avx512vnni — same with VPDPWSSD accumulation, 64 elements/iter + +use super::assert_equal_lengths; + +/// Intermediate results from the fused u8 cosine kernel: (dot_ab, norm_a², norm_b²). +/// +/// Separated from the final normalization so SIMD backends can be tested +/// for exact integer equality before the f32 division. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CosineAccumulators { + pub dot_ab: u32, + pub norm_a_sq: u32, + pub norm_b_sq: u32, +} + +type CosineU8AccumKernel = unsafe fn(&[u8], &[u8]) -> CosineAccumulators; + +lance_core::dispatch! { + /// There are no AVX or AVX+FMA candidates: the SIMD kernels need AVX2 + /// integer ops, so those hosts use the scalar kernel. + static COSINE_U8_ACCUM: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::COSINE_U8_ACCUM_AVX512_VNNI, + x86::COSINE_U8_ACCUM_AVX2, + COSINE_U8_ACCUM_SCALAR, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[COSINE_U8_ACCUM_SCALAR] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(COSINE_U8_ACCUM_SCALAR: CosineU8AccumKernel)] + /// Portable scalar fused cosine accumulation. + #[inline] + pub fn cosine_u8_accum_scalar(a: &[u8], b: &[u8]) -> CosineAccumulators { + assert_equal_lengths(a.len(), b.len()); + let (mut dot_ab, mut norm_a_sq, mut norm_b_sq) = (0u32, 0u32, 0u32); + for (&x, &y) in a.iter().zip(b.iter()) { + let (xu, yu) = (x as u32, y as u32); + dot_ab += xu * yu; + norm_a_sq += xu * xu; + norm_b_sq += yu * yu; + } + CosineAccumulators { + dot_ab, + norm_a_sq, + norm_b_sq, + } + } +} + +/// Convert accumulators to cosine distance: `1 - dot / (‖a‖ × ‖b‖)`. +#[inline] +fn normalize(acc: CosineAccumulators) -> f32 { + let na = (acc.norm_a_sq as f32).sqrt(); + let nb = (acc.norm_b_sq as f32).sqrt(); + let denom = na * nb; + if denom == 0.0 { + // Both zero-norm → identical → distance 0. + // One zero-norm → undefined, but 0 is a safe sentinel. + return 0.0; + } + 1.0 - acc.dot_ab as f32 / denom +} + +/// Portable scalar u8 cosine distance. +#[inline] +pub fn cosine_u8_scalar(a: &[u8], b: &[u8]) -> f32 { + normalize(cosine_u8_accum_scalar(a, b)) +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use super::{CosineAccumulators, CosineU8AccumKernel}; + + /// Horizontal sum of all 8 × i32 lanes in a __m256i. + #[target_feature(enable = "avx2")] + #[inline] + fn hsum_epi32_avx2(v: __m256i) -> u32 { + let lo128 = _mm256_castsi256_si128(v); + let hi128 = _mm256_extracti128_si256(v, 1); + let mut sum128 = _mm_add_epi32(lo128, hi128); + sum128 = _mm_hadd_epi32(sum128, sum128); + sum128 = _mm_hadd_epi32(sum128, sum128); + _mm_cvtsi128_si32(sum128) as u32 + } + + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) COSINE_U8_ACCUM_AVX2: CosineU8AccumKernel)] + /// AVX2 fused cosine: three VPMADDWD products per half, 32 elements/iter. + pub(super) fn cosine_u8_accum_avx2(a: &[u8], b: &[u8]) -> CosineAccumulators { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let n = a.len().min(b.len()); + let mut acc_dot = _mm256_setzero_si256(); + let mut acc_na = _mm256_setzero_si256(); + let mut acc_nb = _mm256_setzero_si256(); + let mut i = 0usize; + + while i + 32 <= n { + let (av, bv) = unsafe { + ( + _mm256_loadu_si256(a.as_ptr().add(i) as *const __m256i), + _mm256_loadu_si256(b.as_ptr().add(i) as *const __m256i), + ) + }; + + // Zero-extend each 128-bit half to 16 × i16. + let a_lo = _mm256_cvtepu8_epi16(_mm256_castsi256_si128(av)); + let a_hi = _mm256_cvtepu8_epi16(_mm256_extracti128_si256(av, 1)); + let b_lo = _mm256_cvtepu8_epi16(_mm256_castsi256_si128(bv)); + let b_hi = _mm256_cvtepu8_epi16(_mm256_extracti128_si256(bv, 1)); + + // VPMADDWD: pairwise multiply i16 and accumulate pairs into i32. + acc_dot = _mm256_add_epi32(acc_dot, _mm256_madd_epi16(a_lo, b_lo)); + acc_dot = _mm256_add_epi32(acc_dot, _mm256_madd_epi16(a_hi, b_hi)); + acc_na = _mm256_add_epi32(acc_na, _mm256_madd_epi16(a_lo, a_lo)); + acc_na = _mm256_add_epi32(acc_na, _mm256_madd_epi16(a_hi, a_hi)); + acc_nb = _mm256_add_epi32(acc_nb, _mm256_madd_epi16(b_lo, b_lo)); + acc_nb = _mm256_add_epi32(acc_nb, _mm256_madd_epi16(b_hi, b_hi)); + i += 32; + } + + let mut dot_ab = hsum_epi32_avx2(acc_dot); + let mut norm_a_sq = hsum_epi32_avx2(acc_na); + let mut norm_b_sq = hsum_epi32_avx2(acc_nb); + + // Scalar tail + while i < n { + let (xu, yu) = (a[i] as u32, b[i] as u32); + dot_ab += xu * yu; + norm_a_sq += xu * xu; + norm_b_sq += yu * yu; + i += 1; + } + + CosineAccumulators { + dot_ab, + norm_a_sq, + norm_b_sq, + } + } + } + + lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw", "avx512vnni")] + #[candidate(pub(super) COSINE_U8_ACCUM_AVX512_VNNI: CosineU8AccumKernel)] + /// AVX-512 VNNI fused cosine: VPDPWSSD for each product, 64 elements/iter. + pub(super) fn cosine_u8_accum_avx512_vnni(a: &[u8], b: &[u8]) -> CosineAccumulators { + // See `cosine_u8_accum_avx2`. + let n = a.len().min(b.len()); + let zeros = _mm512_setzero_si512(); + let mut acc_dot = _mm512_setzero_si512(); + let mut acc_na = _mm512_setzero_si512(); + let mut acc_nb = _mm512_setzero_si512(); + let mut i = 0usize; + + while i + 64 <= n { + let (av, bv) = unsafe { + ( + _mm512_loadu_si512(a.as_ptr().add(i) as *const __m512i), + _mm512_loadu_si512(b.as_ptr().add(i) as *const __m512i), + ) + }; + + // Zero-extend u8→i16 via interleave with zeros. + let a_lo = _mm512_unpacklo_epi8(av, zeros); + let a_hi = _mm512_unpackhi_epi8(av, zeros); + let b_lo = _mm512_unpacklo_epi8(bv, zeros); + let b_hi = _mm512_unpackhi_epi8(bv, zeros); + + // VPDPWSSD: signed i16 multiply-add into i32 accumulator. + acc_dot = _mm512_dpwssd_epi32(acc_dot, a_lo, b_lo); + acc_dot = _mm512_dpwssd_epi32(acc_dot, a_hi, b_hi); + acc_na = _mm512_dpwssd_epi32(acc_na, a_lo, a_lo); + acc_na = _mm512_dpwssd_epi32(acc_na, a_hi, a_hi); + acc_nb = _mm512_dpwssd_epi32(acc_nb, b_lo, b_lo); + acc_nb = _mm512_dpwssd_epi32(acc_nb, b_hi, b_hi); + i += 64; + } + + let mut dot_ab = _mm512_reduce_add_epi32(acc_dot) as u32; + let mut norm_a_sq = _mm512_reduce_add_epi32(acc_na) as u32; + let mut norm_b_sq = _mm512_reduce_add_epi32(acc_nb) as u32; + + // Scalar tail + while i < n { + let (xu, yu) = (a[i] as u32, b[i] as u32); + dot_ab += xu * yu; + norm_a_sq += xu * xu; + norm_b_sq += yu * yu; + i += 1; + } + + CosineAccumulators { + dot_ab, + norm_a_sq, + norm_b_sq, + } + } + } +} + +/// Dispatched fused u8 cosine accumulation. +#[inline] +fn cosine_u8_accum(a: &[u8], b: &[u8]) -> CosineAccumulators { + assert_equal_lengths(a.len(), b.len()); + COSINE_U8_ACCUM.get().call(a, b) +} + +/// Dispatched u8 cosine distance, selecting the best available SIMD backend. +/// +/// Returns `1 - dot(a,b) / (‖a‖ × ‖b‖)` computed in a single pass. +#[inline] +pub fn cosine_u8(a: &[u8], b: &[u8]) -> f32 { + normalize(cosine_u8_accum(a, b)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::u8_inputs::{LENGTHS, Pattern, random}; + + #[rstest::rstest] + #[case::shorter_right(64, 1)] + #[case::longer_right(1, 64)] + fn rejects_mismatched_lengths(#[case] a_len: usize, #[case] b_len: usize) { + let a = vec![1; a_len]; + let b = vec![1; b_len]; + + assert!(std::panic::catch_unwind(|| cosine_u8_accum_scalar(&a, &b)).is_err()); + assert!(std::panic::catch_unwind(|| cosine_u8_scalar(&a, &b)).is_err()); + assert!(std::panic::catch_unwind(|| cosine_u8(&a, &b)).is_err()); + } + + /// Every host-supported kernel, and the dispatched entry point, must + /// produce exactly the reference integer accumulators. + fn assert_kernels_match_reference(a: &[u8], b: &[u8], label: &str) { + let (mut dot_ab, mut norm_a_sq, mut norm_b_sq) = (0u64, 0u64, 0u64); + for (&x, &y) in a.iter().zip(b) { + let (x, y) = (x as u64, y as u64); + dot_ab += x * y; + norm_a_sq += x * x; + norm_b_sq += y * y; + } + let want = CosineAccumulators { + dot_ab: dot_ab.try_into().unwrap(), + norm_a_sq: norm_a_sq.try_into().unwrap(), + norm_b_sq: norm_b_sq.try_into().unwrap(), + }; + for candidate in COSINE_U8_ACCUM.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(a, b); + assert_eq!(got, want, "{} [{label}] n={}", candidate.name(), a.len()); + } + let got = cosine_u8_accum(a, b); + assert_eq!(got, want, "cosine_u8_accum [{label}] n={}", a.len()); + } + + #[rstest::rstest] + #[case::random(Pattern::Random)] + #[case::extremes(Pattern::Extremes)] + #[case::one_sided_zeros(Pattern::OneSidedZeros)] + fn test_cosine_u8_kernels_match_reference(#[case] pattern: Pattern) { + for &len in LENGTHS { + for (label, a, b) in pattern.pairs(len) { + assert_kernels_match_reference(&a, &b, label); + } + } + } + + /// The SIMD kernels are safe functions, so unequal lengths must stay in + /// bounds and use the common prefix. The lengths cross both SIMD strides. + #[rstest::rstest] + #[case::shorter_right(129, 65)] + #[case::longer_right(65, 129)] + fn simd_kernels_use_common_prefix_of_unequal_lengths( + #[case] a_len: usize, + #[case] b_len: usize, + ) { + let a = random(a_len, 0); + let b = random(b_len, 1); + let n = a_len.min(b_len); + let want = cosine_u8_accum_scalar(&a[..n], &b[..n]); + for candidate in COSINE_U8_ACCUM.candidates() { + // The scalar kernel asserts equal lengths instead. + if candidate.features().is_empty() { + continue; + } + let Some(kernel) = candidate.kernel() else { + continue; + }; + assert_eq!(kernel.call(&a, &b), want, "{}", candidate.name()); + } + } + + #[test] + fn cosine_known_values() { + // Identical vectors → distance 0 + let v = [10u8, 20, 30, 40]; + assert_eq!(cosine_u8(&v, &v), 0.0); + + // Orthogonal-ish: one vector all in first half, other in second half + let a = [255u8, 255, 0, 0]; + let b = [0u8, 0, 255, 255]; + assert_eq!(cosine_u8(&a, &b), 1.0); // dot=0 → distance=1 + + // Zero vectors → distance 0 (by convention) + assert_eq!(cosine_u8(&[0, 0], &[0, 0]), 0.0); + assert_eq!(cosine_u8(&[0, 0], &[1, 2]), 0.0); + } + + #[test] + fn cosine_distance_symmetry() { + let a = random(256, 0); + let b = random(256, 1); + assert_eq!(cosine_u8(&a, &b), cosine_u8(&b, &a)); + } + + #[test] + fn cosine_distance_range() { + // Cosine distance should be in [0, 1] for non-negative u8 inputs + // (all u8 values are ≥ 0, so dot product is always ≥ 0). + for seed in 0..8 { + let d = cosine_u8(&random(1024, 2 * seed), &random(1024, 2 * seed + 1)); + assert!( + (0.0..=1.0).contains(&d), + "cosine distance {d} out of [0,1] range" + ); + } + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs b/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs new file mode 100644 index 000000000..90cd533d2 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs @@ -0,0 +1,1265 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Dot product. + +use std::iter::Sum; +use std::ops::AddAssign; +use std::sync::Arc; + +use arrow_array::{Array, FixedSizeListArray, Float32Array}; +use half::{bf16, f16}; +#[allow(unused_imports)] +use lance_core::{ + deepsize::DeepSizeOf, + utils::cpu::{SIMD_SUPPORT, SimdSupport}, +}; +use num_traits::{AsPrimitive, Num, real::Real}; + +use crate::Result; +#[cfg(feature = "fp16kernels")] +use crate::distance::HalfBackend; +use crate::distance::{ + BatchKernel, HALF_KERNELS_COMPILED, HalfType, PairKernel, assert_batch_output_layout, + assert_equal_lengths, half_backend, x86_half_features, +}; + +/// Default implementation of dot product. +/// +// The following code has been tuned for auto-vectorization. +// Please make sure run `cargo bench --bench dot` with and without AVX-512 before any change. +// Tested `target-features`: avx512f,avx512vl,f16c +#[inline(always)] +fn dot_scalar< + T: AsPrimitive, + Output: Real + Sum + AddAssign + 'static, + const LANES: usize, +>( + from: &[T], + to: &[T], +) -> Output { + let (x_chunks, x_remainder) = to.as_chunks::(); + let (y_chunks, y_remainder) = from.as_chunks::(); + let sum = if x_remainder.is_empty() { + Output::zero() + } else { + x_remainder + .iter() + .zip(y_remainder.iter()) + .map(|(&x, &y)| x.as_() * y.as_()) + .sum::() + }; + // Use known size to allow LLVM to kick in auto-vectorization. + let mut sums = [Output::zero(); LANES]; + for (x, y) in x_chunks.iter().zip(y_chunks) { + for i in 0..LANES { + sums[i] += x[i].as_() * y[i].as_(); + } + } + sum + sums.iter().copied().sum::() +} + +/// Dot product. +/// +/// # Panics +/// +/// The implementations in this crate panic if `from` and `to` have different +/// lengths. A downstream [`Dot`] implementation may define different behavior. +#[inline] +pub fn dot(from: &[T], to: &[T]) -> f32 { + T::dot(from, to) +} + +/// Dot product between two f32 slices, dispatched to the widest SIMD backend +/// available at runtime. See [`crate::distance::l2::l2_f32`] for why this is +/// needed on top of the generic [`dot`]. +/// +/// # Panics +/// +/// Panics if `x` and `y` have different lengths. +#[inline] +pub fn dot_f32(x: &[f32], y: &[f32]) -> f32 { + f32::dot(x, y) +} + +/// Negative [Dot] distance. +/// +/// # Panics +/// +/// The implementations in this crate panic if `from` and `to` have different +/// lengths. A downstream [`Dot`] implementation may define different behavior. +#[inline] +pub fn dot_distance(from: &[T], to: &[T]) -> f32 { + 1.0 - T::dot(from, to) +} + +/// Accumulate one query dimension into the Dot distances for all targets. +/// +/// Keeping this in a separate function tells LLVM that `row` and `distances` +/// do not alias, allowing it to vectorize across targets on every architecture. +#[inline(never)] +fn accumulate_dot_dimension(q: f32, row: &[f32], distances: &mut [f32]) { + for (distance, &target) in distances.iter_mut().zip(row) { + *distance -= q * target; + } +} + +/// Pre-transposed target vectors for batched Dot distance computation. +/// +/// Stores targets in SoA layout `[dimension][num_targets]`, allowing one query +/// dimension to be multiplied with many contiguous target values. Construction +/// performs the AoS-to-SoA transpose once, so callers should reuse this across +/// queries. This is intended for small target sets whose transposed values fit +/// in cache, such as PQ sub-vector codebooks. +/// +/// # Example +/// +/// ``` +/// use lance_linalg::distance::dot::DotPrepared; +/// +/// let targets = [1.0, 0.0, 0.0, 1.0]; +/// let prepared = DotPrepared::new(&targets, 2); +/// assert_eq!(prepared.distances(&[1.0, 0.0]), [0.0, 1.0]); +/// ``` +#[derive(Debug, Clone, DeepSizeOf)] +pub struct DotPrepared { + transposed: Vec, + dimension: usize, + num_targets: usize, +} + +impl DotPrepared { + /// Transpose `targets` from AoS `[num_targets][dimension]` to SoA layout. + pub fn new(targets: &[f32], dimension: usize) -> Self { + let num_targets = targets.len() / dimension; + debug_assert_eq!(targets.len(), num_targets * dimension); + + let mut transposed = vec![0.0; targets.len()]; + for target in 0..num_targets { + for dim in 0..dimension { + transposed[dim * num_targets + target] = targets[target * dimension + dim]; + } + } + + Self { + transposed, + dimension, + num_targets, + } + } + + /// Compute Dot distances from `query` to every target, writing into `out`. + pub fn distances_into(&self, query: &[f32], out: &mut [f32]) { + debug_assert_eq!(query.len(), self.dimension); + debug_assert_eq!(out.len(), self.num_targets); + + out.fill(1.0); + for (dim, &q) in query.iter().enumerate() { + let row = &self.transposed[dim * self.num_targets..][..self.num_targets]; + accumulate_dot_dimension(q, row, out); + } + } + + /// Compute Dot distances from `query` to every target. + pub fn distances(&self, query: &[f32]) -> Vec { + let mut result = vec![0.0; self.num_targets]; + self.distances_into(query, &mut result); + result + } + + /// Number of targets in this set. + pub fn num_targets(&self) -> usize { + self.num_targets + } + + /// Dimension of each target vector. + pub fn dimension(&self) -> usize { + self.dimension + } + + /// Size of the transposed values in bytes. + pub fn size_bytes(&self) -> usize { + self.transposed.len() * std::mem::size_of::() + } +} + +/// Dot product +pub trait Dot: Num { + /// Dot product. + /// + /// # Panics + /// + /// The implementations in this crate panic if `x` and `y` have different + /// lengths. A downstream implementation may define different behavior. + fn dot(x: &[Self], y: &[Self]) -> f32; + + /// Writes the dot product of `x` with each `dimension`-sized vector in + /// `batch` into the matching element of `output`. + /// + /// The default calls [`Dot::dot`] per vector. `f32` overrides it with one + /// batch kernel call, so the SIMD tier is chosen once for the whole batch + /// instead of once per vector. `f64` overrides it off x86_64 to specialize + /// the loop for the common PQ sub-vector lengths. + /// + /// # Panics + /// + /// The default implementation panics if `dimension == 0`, if + /// `x.len() != dimension`, if `batch.len()` is not a multiple of + /// `dimension`, or if `output.len() != batch.len() / dimension`. + fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *product = Self::dot(x, y); + } + } +} + +#[cfg(feature = "fp16kernels")] +mod bf16_kernel { + use half::bf16; + + // These are the `dot_bf16` function in bf16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn dot_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))] + pub fn dot_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn dot_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn dot_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn dot_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + } +} + +impl Dot for bf16 { + #[inline] + fn dot(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + match half_backend( + *SIMD_SUPPORT, + HalfType::Bf16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + bf16_kernel::dot_bf16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_bf16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + bf16_kernel::dot_bf16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + bf16_kernel::dot_bf16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + bf16_kernel::dot_bf16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + bf16_kernel::dot_bf16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx fall through here: + // the bf16 C kernels are compiled with `-march=haswell` minimum + // (AVX2), so they cannot run on AVX-only or AVX+FMA hosts. + _ => dot_scalar::(x, y), + } + } +} + +#[cfg(feature = "fp16kernels")] +mod kernel { + use super::*; + + // These are the `dot_f16` function in f16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn dot_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))] + pub fn dot_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn dot_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn dot_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn dot_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + } +} + +impl Dot for f16 { + #[inline] + fn dot(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + match half_backend( + *SIMD_SUPPORT, + HalfType::F16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + kernel::dot_f16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_f16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + kernel::dot_f16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + kernel::dot_f16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + kernel::dot_f16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + kernel::dot_f16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx retain their scalar + // route; this fallback only extends the tiers the C kernel already + // served to Avx512FP16 after checking F16C and FMA. + _ => dot_scalar::(x, y), + } + } +} + +impl Dot for f32 { + #[inline] + fn dot(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + DOT_F32.get().call(x, y) + } + + fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + DOT_F32_BATCH.get().call(x, batch, dimension, output); + } +} + +lance_core::dispatch! { + static DOT_F32: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::DOT_F32_AVX512, + x86::DOT_F32_AVX_FMA, + x86::DOT_F32_AVX, + DOT_F32_SCALAR, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[DOT_F32_SCALAR] + } + }; +} + +lance_core::dispatch! { + /// See `L2_F32_BATCH` for why there is no AVX-512 candidate. + static DOT_F32_BATCH: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::DOT_F32_BATCH_AVX_FMA, + x86::DOT_F32_BATCH_AVX, + DOT_F32_BATCH_SCALAR, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[DOT_F32_BATCH_SCALAR] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(DOT_F32_SCALAR: PairKernel)] + /// Portable dot product for f32, relying on LLVM to auto-vectorize it. + #[inline] + fn dot_f32_scalar(x: &[f32], y: &[f32]) -> f32 { + dot_scalar::(x, y) + } +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(DOT_F32_BATCH_SCALAR: BatchKernel)] + #[inline] + fn dot_batch_f32_scalar(x: &[f32], batch: &[f32], dimension: usize, output: &mut [f32]) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = dot_f32_scalar(x, y); + } + } +} + +impl Dot for f64 { + #[inline] + fn dot(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + dot_f64_simd(x, y) + } + + fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + // Interim: on x86_64 f64 keeps the per-vector loop, since its PQ dot + // tables already beat the pre-`Dispatch` code; f64 moves onto + // `Dispatch` batch candidates later in #10083. + #[cfg(target_arch = "x86_64")] + for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *product = dot_f64_simd(x, y); + } + // Fixed query lengths and the pointer walk below are for the same + // reasons as in `L2::l2_batch_into` for f64. + #[cfg(not(target_arch = "x86_64"))] + if let Ok(x) = <&[Self; 8]>::try_from(x) { + dot_batch_f64_fixed(x, batch, output); + } else if let Ok(x) = <&[Self; 16]>::try_from(x) { + dot_batch_f64_fixed(x, batch, output); + } else { + let mut y = batch.as_ptr(); + for product in output.iter_mut() { + // SAFETY: the layout assert guarantees `batch.len() == output.len() * dimension`. + unsafe { + *product = dot_f64_simd_other(x, std::slice::from_raw_parts(y, dimension)); + y = y.add(dimension); + } + } + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline(always)] +fn dot_batch_f64_fixed(x: &[f64; N], batch: &[f64], output: &mut [f32]) { + for (product, y) in output.iter_mut().zip(batch.as_chunks::().0) { + *product = dot_f64_simd_other(x, y); + } +} + +/// Dot product for f64, runtime-dispatched via `SIMD_SUPPORT` on x86_64 +/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the SIMD +/// primitives in `crate::simd::f64`, unconditionally backed by NEON / LSX-LASX. +#[inline] +fn dot_f64_simd(x: &[f64], y: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + match *SIMD_SUPPORT { + SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { x86::dot_f64_avx512(x, y) }, + SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::dot_f64_avx_fma(x, y) }, + SimdSupport::Avx => unsafe { x86::dot_f64_avx(x, y) }, + _ => dot_f64_scalar(x, y), + } + } + #[cfg(not(target_arch = "x86_64"))] + { + dot_f64_simd_other(x, y) + } +} + +/// Portable scalar dot product for f64. Used as the x86_64 fallback when no +/// AVX2 is detected, and exposed for cross-backend parity testing. +#[cfg(target_arch = "x86_64")] +#[inline] +fn dot_f64_scalar(x: &[f64], y: &[f64]) -> f32 { + x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum::() as f32 +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use crate::distance::{BatchKernel, PairKernel}; + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::x86::hsum256_ps; + use crate::simd::{FloatSimd, SIMD}; + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) DOT_F32_BATCH_AVX_FMA: BatchKernel)] + /// Up to 16 dimensions the scalar kernel's 16-lane chunking degenerates + /// to its remainder loop, so the explicit AVX kernel wins; above that + /// the auto-vectorized scalar kernel is as good or better. + /// + /// Unlike `l2_batch_f32_avx_fma` there is no dimension-16 fast path: + /// that one closed a Haswell regression in PQ L2 tables, while dot at + /// dimension 16 was already faster than before `Dispatch`. + pub(super) fn dot_batch_f32_avx_fma( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + let key = unsafe { _mm256_loadu_ps(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + let product = _mm256_mul_ps(key, unsafe { _mm256_loadu_ps(y.as_ptr()) }); + *distance = unsafe { hsum256_ps(product) }; + } + } else if dimension <= 16 { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = dot_f32_avx_fma(x, y); + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = super::dot_f32_scalar(x, y); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) DOT_F32_BATCH_AVX: BatchKernel)] + pub(super) fn dot_batch_f32_avx( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + let key = unsafe { _mm256_loadu_ps(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + let product = _mm256_mul_ps(key, unsafe { _mm256_loadu_ps(y.as_ptr()) }); + *distance = unsafe { hsum256_ps(product) }; + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = dot_f32_avx(x, y); + } + } + } + } + + /// AVX-512 path for f64: 8-wide `__m512d` with `vfmadd231pd` per iteration. + #[target_feature(enable = "avx512f")] + pub unsafe fn dot_f64_avx512(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + let a = _mm512_loadu_pd(x.as_ptr().add(i)); + let b = _mm512_loadu_pd(y.as_ptr().add(i)); + acc = _mm512_fmadd_pd(a, b, acc); + } + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (_mm512_reduce_add_pd(acc) + tail) as f32 + } + + /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). + #[target_feature(enable = "avx,fma")] + pub unsafe fn dot_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + let a = f64x8::load_unaligned(x.as_ptr().add(i)); + let b = f64x8::load_unaligned(y.as_ptr().add(i)); + acc8.multiply_add(a, b); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + let a = f64x4::load_unaligned(x.as_ptr().add(i)); + let b = f64x4::load_unaligned(y.as_ptr().add(i)); + acc4.multiply_add(a, b); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 + } + + /// AVX-only path for f64 (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. + #[target_feature(enable = "avx")] + pub unsafe fn dot_f64_avx(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 4 * 4; + + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + let a = _mm256_loadu_pd(x.as_ptr().add(i)); + let b = _mm256_loadu_pd(y.as_ptr().add(i)); + acc = _mm256_add_pd(acc, _mm256_mul_pd(a, b)); + } + + // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc_sum + tail) as f32 + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) DOT_F32_AVX512: PairKernel)] + /// AVX-512 path for f32: 16-wide `__m512` with `vfmadd231ps` per iteration. + #[inline] + pub(super) fn dot_f32_avx512(x: &[f32], y: &[f32]) -> f32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 16 * 16; + + let mut acc = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + let (a, b) = unsafe { + ( + _mm512_loadu_ps(x.as_ptr().add(i)), + _mm512_loadu_ps(y.as_ptr().add(i)), + ) + }; + acc = _mm512_fmadd_ps(a, b, acc); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + _mm512_reduce_add_ps(acc) + tail + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) DOT_F32_AVX_FMA: PairKernel)] + /// AVX + FMA path for f32. Covers both AvxFma and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn dot_f32_avx_fma(x: &[f32], y: &[f32]) -> f32 { + // See `dot_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let (a, b) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(y.as_ptr().add(i)), + ) + }; + acc = _mm256_fmadd_ps(a, b, acc); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + let sum = unsafe { hsum256_ps(acc) }; + sum + tail + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) DOT_F32_AVX: PairKernel)] + /// AVX-only path for f32 (no FMA): `_mm256_mul_ps` + `_mm256_add_ps` per iteration for Sandy/Ivy Bridge. + #[inline] + pub(super) fn dot_f32_avx(x: &[f32], y: &[f32]) -> f32 { + // See `dot_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let (a, b) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(y.as_ptr().add(i)), + ) + }; + acc = _mm256_add_ps(acc, _mm256_mul_ps(a, b)); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + let sum = unsafe { hsum256_ps(acc) }; + sum + tail + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline] +fn dot_f64_simd_other(x: &[f64], y: &[f64]) -> f32 { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + unsafe { + let a = f64x8::load_unaligned(x.as_ptr().add(i)); + let b = f64x8::load_unaligned(y.as_ptr().add(i)); + acc8.multiply_add(a, b); + } + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + unsafe { + let a = f64x4::load_unaligned(x.as_ptr().add(i)); + let b = f64x4::load_unaligned(y.as_ptr().add(i)); + acc4.multiply_add(a, b); + } + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 +} + +impl Dot for u8 { + #[inline] + fn dot(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + super::dot_u8::dot_u8_u64(x, y) as f32 + } +} + +/// Writes the dot distance, `1 - dot`, from `from` to each `dimension`-sized +/// vector in `to` into the matching element of `output`. +/// +/// # Panics +/// +/// The implementations in this crate panic if `dimension == 0`, if +/// `from.len() != dimension`, if `to.len()` is not a multiple of `dimension`, +/// or if `output.len() != to.len() / dimension`. +/// +/// ``` +/// # use lance_linalg::distance::dot_distance_batch_into; +/// let mut distances = [0.0; 2]; +/// dot_distance_batch_into(&[1.0_f32, 2.0], &[1.0, 0.0, 0.0, 1.0], 2, &mut distances); +/// assert_eq!(distances, [0.0, -1.0]); +/// ``` +#[inline] +pub fn dot_distance_batch_into(from: &[T], to: &[T], dimension: usize, output: &mut [f32]) { + T::dot_batch_into(from, to, dimension, output); + for distance in output.iter_mut() { + *distance = 1.0 - *distance; + } +} + +/// Compute dot distances, propagating the null buffer of `to`. +/// +/// See [`super::DistanceType::batch`] for supported types and input validation. +#[deprecated(note = "Use DistanceType::Dot.batch")] +pub fn dot_distance_arrow_batch( + from: &dyn Array, + to: &FixedSizeListArray, +) -> Result> { + super::DistanceType::Dot.batch(from, to).map(Arc::new) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::{ + arbitrary_bf16, arbitrary_f16, arbitrary_f32, arbitrary_f64, arbitrary_vector_pair, + dimension_shard, run_vector_pair_proptest, + }; + use num_traits::{Float, FromPrimitive}; + use proptest::prelude::*; + + /// PQ distance tables call this per sub-vector, so Haswell-baseline + /// builds must reach the kernel without a runtime dispatch. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_dot_f32_batch_is_static_on_haswell() { + use lance_core::utils::cpu::CpuFeatures; + let haswell = + CpuFeatures::from_target_features(&["avx2", "fma", "f16c", "bmi1", "bmi2", "popcnt"]); + assert!(haswell.contains(DOT_F32_BATCH.candidates()[0].features())); + } + + #[test] + fn test_dot_rejects_mismatched_lengths() { + let short = [1.0_f32]; + let long = [1.0_f32, 2.0]; + + assert!(std::panic::catch_unwind(|| dot(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| dot_f32(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| f32::dot(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| dot_distance(&short, &long)).is_err()); + assert!( + std::panic::catch_unwind(|| dot_distance_batch_into(&short, &long, 2, &mut [0.0])) + .is_err() + ); + assert!( + std::panic::catch_unwind(|| dot_distance_batch_into( + &long, + &[1.0_f32; 3], + 2, + &mut [0.0] + )) + .is_err() + ); + // The f64 batch loops off x86 walk `batch` by pointer, sized by + // `output`, so a wrong `output` length must be rejected for f64 too. + for output_len in [1, 3] { + assert!( + std::panic::catch_unwind(|| dot_distance_batch_into( + &[1.0_f64, 2.0], + &[1.0_f64; 4], + 2, + &mut vec![0.0; output_len] + )) + .is_err(), + "f64 accepted output length {output_len}" + ); + } + assert!( + std::panic::catch_unwind(|| dot_distance_batch_into::(&[], &[], 0, &mut [])) + .is_err() + ); + assert!( + std::panic::catch_unwind(|| dot_distance_batch_into(&long, &long, 2, &mut [0.0; 2])) + .is_err() + ); + } + + #[test] + fn test_dot_f32_dispatch_matches_scalar() { + use approx::assert_relative_eq; + // Covers tail handling for lengths around the 16-lane AVX-512 stride. + for dim in [1usize, 7, 15, 16, 17, 31, 33, 64, 100, 1024] { + let x: Vec = (0..dim).map(|i| (i as f32) * 0.5 - 3.0).collect(); + let y: Vec = (0..dim).map(|i| (i as f32) * -0.25 + 1.5).collect(); + assert_relative_eq!(dot_f32(&x, &y), dot(&x, &y), max_relative = 1e-5); + } + } + + #[test] + fn test_dot_prepared_matches_per_target_distance() { + for (dimension, num_targets) in + [(1_usize, 32_usize), (3, 20), (8, 256), (16, 17), (128, 64)] + { + let query = (0..dimension) + .map(|idx| idx as f32 * 0.125 - 1.5) + .collect::>(); + let targets = (0..dimension * num_targets) + .map(|idx| ((idx * 7) % 101) as f32 * 0.02 - 1.0) + .collect::>(); + let expected = targets + .chunks_exact(dimension) + .map(|target| dot_distance(&query, target)) + .collect::>(); + + let prepared = DotPrepared::new(&targets, dimension); + let actual = prepared.distances(&query); + + assert_eq!(prepared.dimension(), dimension); + assert_eq!(prepared.num_targets(), num_targets); + assert_eq!( + prepared.size_bytes(), + targets.len() * std::mem::size_of::() + ); + for (target, (actual, expected)) in actual.iter().zip(expected.iter()).enumerate() { + assert!( + approx::relative_eq!(actual, expected, epsilon = 1e-4, max_relative = 1e-5), + "target {target}, dimension {dimension}: prepared={actual}, expected={expected}" + ); + } + } + } + + #[test] + fn test_dot_prepared_reuses_output() { + let prepared = DotPrepared::new(&[1.0, 0.0, 0.0, 1.0], 2); + let mut distances = vec![f32::NAN; 2]; + + prepared.distances_into(&[1.0, 0.0], &mut distances); + assert_eq!(distances, [0.0, 1.0]); + prepared.distances_into(&[0.0, 1.0], &mut distances); + assert_eq!(distances, [1.0, 0.0]); + } + + #[test] + fn test_dot() { + let x: Vec = (0..20).map(|v| v as f32).collect(); + let y: Vec = (100..120).map(|v| v as f32).collect(); + + assert_eq!(f32::dot(&x, &y), dot(&x, &y)); + + let x: Vec = (0..512).map(|v| v as f32).collect(); + let y: Vec = (100..612).map(|v| v as f32).collect(); + + assert_eq!(f32::dot(&x, &y), dot(&x, &y)); + + let x: Vec = (0..20).map(|v| f16::from_i32(v).unwrap()).collect(); + let y: Vec = (100..120).map(|v| f16::from_i32(v).unwrap()).collect(); + assert_eq!(f16::dot(&x, &y), dot(&x, &y)); + + let x: Vec = (20..40).map(|v| f64::from_i32(v).unwrap()).collect(); + let y: Vec = (120..140).map(|v| f64::from_i32(v).unwrap()).collect(); + assert_eq!(f64::dot(&x, &y), dot(&x, &y)); + } + + /// Reference implementation of dot product. + fn dot_scalar_ref(x: &[f64], y: &[f64]) -> f32 { + x.iter().zip(y.iter()).map(|(&x, &y)| x * y).sum::() as f32 + } + + /// Error bound for vector dot product + /// http://ftp.demec.ufpr.br/CFD/bibliografia/Higham_2002_Accuracy%20and%20Stability%20of%20Numerical%20Algorithms.pdf + /// Chapter 3 (page 61) equation 3.5 + /// A float point calculation error is bounded by: + /// (kє/(1-kє)) Sum_i(|x_i||y_i|) if kє < 1 + /// We are currently using a SIMD version of naive product and summation. + /// Therefore, k = 2n-1 (n multiplications, n-1 additions). + /// For f16 and bf16, kє can be >=1. + /// When that happens, we will use a simpler estimation method: + /// Imagine that each `x_i` can vary by `є * |x_i|`, similarly for `y_i`. + /// (Basically, it's accurate to ±(1 + є) * |x_i|). + /// Error for `sum(x, y)` is `є_x + є_y`. + /// Error for multiple is `є_x * x + є_y * y + є_x * є_y`, + /// which simplifies to `є_x * x + є_y * y` + /// See: https://www.geol.lsu.edu/jlorenzo/geophysics/uncertainties/Uncertaintiespart2.html + /// The multiplication of `x_i` and `y_i` can vary by `є|x_i||y_i| + є|y_i||x_i|`. + /// This simplifies to `2є|x_i||y_i|`. + /// So the error for the sum of all the multiplications is `2є Sum_i(|x_i||y_i|)`. + fn max_error>(x: &[f64], y: &[f64]) -> f32 { + let dot = x + .iter() + .cloned() + .zip(y.iter().cloned()) + .map(|(x, y)| x.abs() * y.abs()) + .sum::(); + let k = ((2 * x.len()) - 1) as f64; + let k_epsilon = k * T::epsilon().as_(); + + let error = if k_epsilon < 1.0 { + k_epsilon * dot + } else { + 2.0 * T::epsilon().as_() * dot + }; + + // Near the subnormal range the analytical error can underflow to zero, + // but f32 accumulation can still differ by a few subnormal ULPs. + let subnormal_rounding_floor = x.len() as f64 * f64::from(f32::from_bits(1)); + error.max(subnormal_rounding_floor) as f32 + } + + fn do_dot_test + Float>( + x: &[T], + y: &[T], + ) -> std::result::Result<(), TestCaseError> { + let f64_x = x.iter().map(|&v| v.as_()).collect::>(); + let f64_y = y.iter().map(|&v| v.as_()).collect::>(); + + let expected = dot_scalar_ref(&f64_x, &f64_y); + let result = dot(x, y); + + let max_error = max_error::(&f64_x, &f64_y); + + prop_assert!(approx::relative_eq!(expected, result, epsilon = max_error)); + Ok(()) + } + + #[rstest::rstest] + fn test_dot_f32(#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + do_dot_test(&x, &y) + }); + } + + #[rstest::rstest] + fn test_dot_f64(#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + do_dot_test(&x, &y) + }); + } + + /// Every host-supported f32 kernel, single-pair and batch, must agree with + /// an f64 reference. Prefixes of length 8 and 16 pin the batch kernels' + /// PQ-width fast paths regardless of the generated dimension. + #[rstest::rstest] + fn test_dot_f32_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + for dimension in [8, 16, x.len()].into_iter().filter(|&d| d <= x.len()) { + let (x, y) = (&x[..dimension], &y[..dimension]); + let x_f64: Vec = x.iter().map(|&v| v as f64).collect(); + let y_f64: Vec = y.iter().map(|&v| v as f64).collect(); + let want = dot_scalar_ref(&x_f64, &y_f64); + let max_error = max_error::(&x_f64, &y_f64); + + for candidate in DOT_F32.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(x, y); + prop_assert!( + approx::relative_eq!(got, want, epsilon = max_error), + "{} at dim {dimension}: {got} != {want}", + candidate.name() + ); + } + + // Where an x86 batch kernel reuses its tier's pair kernel or a + // fast path for it, the two must agree bit for bit: up to 16 + // dimensions for AVX+FMA (above that it uses the scalar + // kernel), and at every dimension for AVX. The one allowed + // difference is the sign of a zero result: the pair kernels + // add products to a +0.0 accumulator, which turns -0.0 into + // +0.0, while the dimension-8 fast paths sum the products + // directly. + #[cfg(target_arch = "x86_64")] + for (pair, batch, max_dimension) in [ + (x86::DOT_F32_AVX_FMA, x86::DOT_F32_BATCH_AVX_FMA, 16), + (x86::DOT_F32_AVX, x86::DOT_F32_BATCH_AVX, usize::MAX), + ] { + if dimension > max_dimension { + continue; + } + let (Some(pair_kernel), Some(batch_kernel)) = (pair.kernel(), batch.kernel()) + else { + continue; + }; + let mut got = [f32::NAN]; + batch_kernel.call(x, y, dimension, &mut got); + let want = pair_kernel.call(x, y); + prop_assert!( + got[0].to_bits() == want.to_bits() || (got[0] == 0.0 && want == 0.0), + "{} at dim {dimension}: {} != {want}", + batch.name(), + got[0] + ); + } + + // The zero vector pins the second output to exactly 0. + let batch = [y, &vec![0.0; dimension]].concat(); + for candidate in DOT_F32_BATCH.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut got = [f32::NAN; 2]; + kernel.call(x, &batch, dimension, &mut got); + prop_assert!( + approx::relative_eq!(got[0], want, epsilon = max_error) && got[1] == 0.0, + "{} at dim {dimension}: {got:?} != [{want}, 0]", + candidate.name() + ); + } + } + Ok(()) + }); + } + + proptest::proptest! { + #[test] + fn test_dot_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) { + do_dot_test(&x, &y)?; + } + + #[test] + fn test_dot_bf16((x, y) in arbitrary_vector_pair(arbitrary_bf16, 4..4048)){ + do_dot_test(&x, &y)?; + } + + /// Cross-backend parity: scalar fallback must match the dispatched + /// SIMD path within numerical tolerance. Exercises `dot_f64_scalar` + /// directly so the runtime fallback is exercised even on AVX2-capable + /// CI hosts. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_dot_f64_scalar_simd_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + let scalar = dot_f64_scalar(&x, &y); + let simd = dot_f64_simd(&x, &y); + let max_error = max_error::(&x, &y); + prop_assert!(approx::relative_eq!(scalar, simd, epsilon = max_error)); + } + + /// AVX-512-direct parity: explicitly compares the scalar fallback + /// against the native AVX-512 inner kernel on AVX-512F-capable hosts + /// (Skylake-X+, Ice Lake, Sapphire Rapids, Zen 4). Early-returns on + /// hosts without AVX-512F. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_dot_f64_scalar_vs_avx512_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !std::is_x86_feature_detected!("avx512f") { + return Ok(()); + } + let scalar = dot_f64_scalar(&x, &y); + let avx512 = unsafe { x86::dot_f64_avx512(&x, &y) }; + let max_error = max_error::(&x, &y); + prop_assert!(approx::relative_eq!(scalar, avx512, epsilon = max_error)); + } + + /// AVX + FMA-direct parity for the f64 dot kernel. Covers the AMD + /// Piledriver / Steamroller / FX-7500 tier. Early-returns on hosts + /// without both AVX and FMA. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_dot_f64_scalar_vs_avx_fma_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !(std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma")) { + return Ok(()); + } + let scalar = dot_f64_scalar(&x, &y); + let avx_fma = unsafe { x86::dot_f64_avx_fma(&x, &y) }; + let max_error = max_error::(&x, &y); + prop_assert!(approx::relative_eq!(scalar, avx_fma, epsilon = max_error)); + } + + /// AVX-only-direct parity for the f64 dot kernel. Covers the Intel + /// Sandy Bridge / Ivy Bridge tier (AVX without FMA). Early-returns + /// on hosts without AVX. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_dot_f64_scalar_vs_avx_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !std::is_x86_feature_detected!("avx") { + return Ok(()); + } + let scalar = dot_f64_scalar(&x, &y); + let avx = unsafe { x86::dot_f64_avx(&x, &y) }; + let max_error = max_error::(&x, &y); + prop_assert!(approx::relative_eq!(scalar, avx, epsilon = max_error)); + } + } + + /// An empty batch with a valid dimension, e.g. no centroids, writes + /// nothing and does not panic. 8 and 16 take the fixed-length paths. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_16(16)] + #[case::dim_13(13)] + fn test_dot_batch_into_accepts_empty_batch(#[case] dimension: usize) { + fn accepts(dimension: usize) { + let x = vec![T::from_f32(1.0).unwrap(); dimension]; + dot_distance_batch_into::(&x, &[], dimension, &mut []); + } + accepts::(dimension); + accepts::(dimension); + accepts::(dimension); + } + + /// `dot_batch_into` must agree with the per-vector `dot`. The f32 batch + /// kernel may differ in rounding; the f64 batch loops run the pair + /// kernel's arithmetic, so f64 must match bit for bit. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_12(12)] + #[case::dim_13(13)] + #[case::dim_16(16)] + #[case::dim_32(32)] + #[case::dim_1024(1024)] + fn test_dot_batch_into_matches_per_vector_dot(#[case] dimension: usize) { + fn check(dimension: usize, bit_exact: bool) { + let num_vectors = 130; + // Values that are not multiples of a power of two, so the sums + // round and a different summation order changes the result. + let x: Vec = (0..dimension) + .map(|i| T::from_f32((i as f32 * 0.37).sin()).unwrap()) + .collect(); + let batch: Vec = (0..dimension * num_vectors) + .map(|i| T::from_f32((i as f32 * 0.73).cos() * 2.0).unwrap()) + .collect(); + + let mut got = vec![f32::NAN; num_vectors]; + T::dot_batch_into(&x, &batch, dimension, &mut got); + + for (g, y) in got.iter().zip(batch.chunks_exact(dimension)) { + let w = T::dot(&x, y); + if bit_exact { + assert_eq!( + g.to_bits(), + w.to_bits(), + "dim {dimension}: batch {g} != per-vector {w}" + ); + } else { + assert!( + approx::relative_eq!(*g, w, epsilon = 1e-4, max_relative = 1e-5), + "dim {dimension}: batch {g} != per-vector {w}" + ); + } + } + } + check::(dimension, false); + check::(dimension, true); + } + + /// `dot_distance_batch_into` writes `1.0 - dot`. + #[test] + fn test_dot_distance_batch_into_preserves_distance_semantics() { + let dimension = 32; + let x: Vec = (0..dimension).map(|i| (i as f32) * 0.1).collect(); + let batch: Vec = (0..dimension * 3).map(|i| (i as f32) * 0.05).collect(); + + let mut got = vec![f32::NAN; 3]; + dot_distance_batch_into(&x, &batch, dimension, &mut got); + for (chunk, &g) in batch.chunks_exact(dimension).zip(got.iter()) { + assert!(approx::relative_eq!( + g, + 1.0 - f32::dot(&x, chunk), + epsilon = 1e-5 + )); + } + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/dot_f16.rs b/rust/lancedb/vendor/lance-linalg/src/distance/dot_f16.rs new file mode 100644 index 000000000..4c3c69464 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/dot_f16.rs @@ -0,0 +1,1299 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Batched f16 dot product with an optional AMX-FP16 tile backend. +//! +//! Used by IVF over an fp16 column under dot distance: [`dot_f16_batch_16`] +//! scores one query against 16 centroids when choosing the partitions to probe, +//! and the GEMM behind [`PackedCentroidsF16`] assigns vectors to partitions +//! while an index is built. +//! +//! [`dot_f16_batch_16`] returns the 16 raw dot products `Σ query·candidate` +//! (same value convention as [`crate::distance::dot()`]); the caller applies the +//! `1.0 - dot` distance wrapping. On Linux/x86_64 hosts with AMX-FP16 it +//! dispatches to a single tile pass; everywhere else (and on any AMX +//! unavailability) it falls back to 16 independent [`crate::distance::dot()`] +//! calls, which are bit-identical to the per-vector scalar path. +//! +//! Two gates cover all of this, and they are deliberately separate: +//! [`amx_fp16_supported`] answers whether the tile instructions can run here at +//! all, and [`amx_fp16_available`] adds the `LANCE_DISABLE_AMX` kill switch on +//! top. The kernels here are guarded by the former so tests can always reach +//! them; callers routing production work consult the latter. AMX is on by +//! default — the switch exists for A/B measurement and for getting the previous +//! path back without a rebuild. +//! +//! Unlike integer AMX kernels this is floating point: the AMX and fallback paths +//! are **not** bit-for-bit identical (tile accumulation order rounds +//! differently), but both accumulate products in f32 and agree to within fp16 +//! precision — a relative error on the order of 1e-4, far below fp16's own +//! representational error, so recall is unaffected. + +use half::f16; + +use crate::distance::dot::dot; + +/// Batched f16 dot product: the raw dot products of one `query` against the +/// first `len` of 16 `candidates`, in order. Every candidate slice must have the +/// same length as `query`, and `len` must be in `1..=16`. +/// +/// A batch is shorter than 16 only in the last group of a sweep, when the +/// centroid count is not a multiple of 16. `len` keeps the `16 - len` padding +/// rows out of the kernel's staging copy; with at most one short group per +/// sweep that saves much less than it would for a caller whose batches were +/// usually partial. Lanes `len..16` are returned as `0` rather than left +/// unspecified, so both the AMX and fallback paths agree exactly on what a +/// caller that reads past `len` sees. +/// +/// Safe to call unconditionally: the caller never needs to know whether AMX is +/// present. The function panics if any candidate has a different length from +/// `query`, or if `len` is out of range, rather than allowing a malformed batch +/// to reach the FFI kernel. See the module docs for the accuracy contract. +#[inline] +pub fn dot_f16_batch_16(query: &[f16], candidates: &[&[f16]; 16], len: usize) -> [f32; 16] { + assert!( + candidates + .iter() + .all(|candidate| candidate.len() == query.len()), + "all candidate vectors must have the same length as query" + ); + assert!( + (1..=16).contains(&len), + "batch length must be in 1..=16, got {len}" + ); + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + { + // AMX only earns its tile-config overhead once there is at least one + // full 32-wide pass; for tiny dims the fallback is cheaper anyway. + if query.len() >= 32 && crate::simd::amx_fp16::amx_supported() { + return unsafe { crate::simd::amx_fp16::dot_f16_batch_16_amx(query, candidates, len) }; + } + } + dot_f16_batch_16_fallback(query, candidates, len) +} + +/// Fallback for [`dot_f16_batch_16`]: `len` independent [`crate::distance::dot()`] +/// calls — bit-identical to the per-vector scalar path (both go through +/// `f16::dot`) — and `0` for the remaining lanes, matching what the kernel +/// leaves there. Exposed separately so tests can exercise it regardless of host. +#[inline] +pub(crate) fn dot_f16_batch_16_fallback( + query: &[f16], + candidates: &[&[f16]; 16], + len: usize, +) -> [f32; 16] { + std::array::from_fn(|i| { + if i < len { + dot(query, candidates[i]) + } else { + 0.0 + } + }) +} + +/// Centroids pre-packed into the layout the AMX-FP16 GEMM reads its B operand +/// in, together with the scoring entry point that consumes them. +/// +/// This type exists unconditionally, and construction is the only gate: +/// [`PackedCentroidsF16::new`] returns `None` on a build or host without the +/// kernel. Callers in other crates cannot see lance-linalg's `kernel_support` +/// cfg, so an `Option` at run time is the only form of the gate they can branch +/// on to keep their own fallback path. +/// +/// Packing costs `O(k * dim)` and is done once here rather than per block of +/// vectors, where it would outweigh the GEMM it feeds. +pub struct PackedCentroidsF16(Packed); + +/// [`PackedCentroidsF16`]'s payload — and the reason that type needs no `cfg` +/// of its own: without the kernel this is uninhabited, so `PackedCentroidsF16` +/// is too. `new` provably cannot return `Some`, which is what lets the methods +/// discharge their bodies against a value that cannot exist instead of carrying +/// a fallback implementation that could never run. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +struct Packed { + /// Zero-padded `[n_padded, dim]` centroids, row-major and tight. Held + /// because the kernel reads the unpacked centroids directly for the + /// `dim % 32` tail dims, which are not part of the packed layout. + centroids: Vec, + /// `centroids` in the kernel's VNNI B-tile order. + packed: Vec, + n_padded: usize, + dim: usize, +} + +#[cfg(not(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +)))] +enum Packed {} + +/// How many elements a buffer must hold for `m` rows of `row_len`, `stride` +/// apart — `(m - 1) * stride + row_len` — or `None` if that overflows `usize`. +/// +/// The checked arithmetic is the point. Written inline, the expression wraps +/// silently in release builds, and a wrapped requirement is *small*, so it +/// satisfies the very length check it was computed for: `m = 32`, +/// `stride = 595_056_260_442_243_601`, `row_len = 32` wraps to 47, admitting a +/// 47-element slice into a kernel that then strides `data + i * stride` past its +/// end. Every caller here is a safe function guarding an FFI boundary, so an +/// overflow has to be rejected rather than folded into a comparison. +/// +/// Zero rows need zero elements. Handling that here rather than leaving it to +/// the caller keeps the function total: `m - 1` would underflow, which panics in +/// debug builds and wraps to `usize::MAX` in release ones — the same class of +/// silent wrap this function exists to prevent. +pub(crate) fn strided_len(m: usize, stride: usize, row_len: usize) -> Option { + let Some(last_row) = m.checked_sub(1) else { + return Some(0); + }; + last_row.checked_mul(stride)?.checked_add(row_len) +} + +impl PackedCentroidsF16 { + /// Packs `n` row-major `dim`-dimensional `centroids` for repeated scoring. + /// + /// `None` means the GEMM is unavailable — this build has no kernel, this + /// host cannot run it (both are [`amx_fp16_supported`]), or the shape is + /// empty — and the caller must keep using its own path. There is no partial + /// mode. Whether an operator has taken the AMX paths out of service is a + /// separate question, answered by [`amx_fp16_available`] at the caller's + /// routing decision, so that tests can build one of these regardless. + /// + /// `n` is rounded up to a multiple of 32 with zero centroids, since the + /// kernel blocks its `n` loop by 32 and has no partial-tile path. The + /// padding is visible to [`score`](Self::score)'s output and callers must + /// account for it; see [`num_centroids_padded`](Self::num_centroids_padded). + /// + /// # Panics + /// If `centroids` does not hold exactly `n * dim` values. + pub fn new(centroids: &[f16], n: usize, dim: usize) -> Option { + let expected = n + .checked_mul(dim) + .unwrap_or_else(|| panic!("centroid shape n = {n} x dim = {dim} overflows usize")); + assert_eq!( + centroids.len(), + expected, + "centroids must hold n*dim = {expected} values, got {}", + centroids.len() + ); + if n == 0 || dim == 0 || !amx_fp16_supported() { + return None; + } + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + { + // Same checked-size contract as the length guards below: this + // allocation is what the kernel later reads through a raw pointer, + // so a shape whose padded size is not representable is rejected + // here rather than wrapped into an allocation smaller than the rows + // the kernel will address. `packed_centroids_len` needs no separate + // check -- `(dim / 32) * (n_padded / 16) * 512 <= n_padded * dim` + // for every input, so it cannot overflow once this one holds. + let n_padded = n.checked_next_multiple_of(32).unwrap_or_else(|| { + panic!("padding n = {n} up to a multiple of 32 overflows usize") + }); + let padded_len = n_padded.checked_mul(dim).unwrap_or_else(|| { + panic!("padded centroid shape {n_padded} x dim = {dim} overflows usize") + }); + let mut padded = vec![f16::ZERO; padded_len]; + padded[..centroids.len()].copy_from_slice(centroids); + let mut packed = + Vec::with_capacity(crate::simd::amx_fp16::packed_centroids_len(n_padded, dim)); + crate::simd::amx_fp16::pack_centroids_vnni(&padded, n_padded, dim, &mut packed); + return Some(Self(Packed { + centroids: padded, + packed, + n_padded, + dim, + })); + } + #[allow(unreachable_code)] + None + } + + /// The centroid count [`score`](Self::score) actually writes per row: the + /// `n` given to [`new`](Self::new) rounded up to a multiple of 32. + pub fn num_centroids_padded(&self) -> usize { + self.shape().0 + } + + /// `(padded centroid count, dim)`. The single place the uninhabited-payload + /// build is discharged, so the methods above it read as ordinary code. + fn shape(&self) -> (usize, usize) { + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + { + (self.0.n_padded, self.0.dim) + } + #[cfg(not(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + )))] + { + match self.0 {} + } + } + + /// Scores `m` vectors against every centroid: `out[i * out_stride + j]` is + /// the raw dot product `Σ data_i·centroid_j` — the same value convention as + /// [`crate::distance::dot()`], with no `1.0 - d` distance wrapping. + /// + /// Row `i` of `data` starts at `i * data_stride`, so both buffers may be + /// windows of larger ones. Columns `n..num_centroids_padded()` are the zero + /// padding centroids' scores; they are `0.0` for any finite input, which + /// *beats* a real centroid whose dot product is negative. A caller reducing + /// across a row must therefore stop at its own centroid count. + /// + /// See the module docs for the accuracy contract against the scalar path. + /// + /// # Panics + /// If `m` is not a multiple of 32 (the kernel blocks its `m` loop by 32 and + /// has no partial-tile path), if either stride is too small, or if either + /// slice is too short for the last row its stride reaches. + pub fn score( + &self, + data: &[f16], + m: usize, + data_stride: usize, + out: &mut [f32], + out_stride: usize, + ) { + let (n_padded, dim) = self.shape(); + assert_eq!(m % 32, 0, "m ({m}) must be a multiple of 32"); + assert!( + data_stride >= dim, + "data_stride ({data_stride}) is below dim ({dim})" + ); + assert!( + out_stride >= n_padded, + "out_stride ({out_stride}) is below the padded centroid count ({n_padded})" + ); + if m == 0 { + return; + } + let data_needed = strided_len(m, data_stride, dim).unwrap_or_else(|| { + panic!("m = {m} rows of dim {dim} at stride {data_stride} overflow usize") + }); + assert!( + data.len() >= data_needed, + "data ({}) holds fewer than m = {m} rows of dim {dim} at stride {data_stride}", + data.len() + ); + let out_needed = strided_len(m, out_stride, n_padded).unwrap_or_else(|| { + panic!("m = {m} rows of {n_padded} at stride {out_stride} overflow usize") + }); + assert!( + out.len() >= out_needed, + "out ({}) holds fewer than m = {m} rows of {n_padded} at stride {out_stride}", + out.len() + ); + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + // SAFETY: the kernel's preconditions are exactly the asserts above plus + // AMX availability. `n_padded % 32 == 0` and the packing / length + // agreement between `packed`, `centroids`, `n_padded` and `dim` hold by + // construction in `new`, which also proved `amx_fp16_supported()` — a + // process-wide, monotonic property (CPUID plus a one-time, idempotent + // XTILEDATA grant), so it cannot have lapsed since. + unsafe { + crate::simd::amx_fp16::dot_f16_gemm_amx( + data, + m, + data_stride, + &self.0.packed, + &self.0.centroids, + n_padded, + dim, + out, + out_stride, + ); + } + } +} + +/// Whether this process *can* execute the AMX-FP16 kernels at all. True when +/// all of the following hold: +/// +/// - the kernel was compiled in, i.e. `build.rs` found a C compiler accepting +/// `-mamx-fp16` (clang >= 16 or gcc >= 13) and set `kernel_support`; +/// - the target is Linux/x86_64; +/// - the CPU reports both the amx-tile and the amx-fp16 CPUID bits; +/// - the one-time XTILEDATA `arch_prctl` grant succeeded. +/// +/// This is the safety question — without the `arch_prctl` grant the first tile +/// instruction would SIGILL — so no tile instruction in this module runs until +/// it holds. It deliberately ignores [`LANCE_DISABLE_AMX`][amx_fp16_available], +/// so kernel-level tests can exercise the kernels on any host that can run them +/// even when an operator has turned the production paths off. +/// +/// Callers choosing between the AMX path and their fallback want +/// [`amx_fp16_available`] instead. +/// +/// Evaluated once and cached by the hardware probe underneath; nothing is +/// recomputed per call. +pub fn amx_fp16_supported() -> bool { + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + { + return crate::simd::amx_fp16::amx_supported(); + } + #[allow(unreachable_code)] + false +} + +/// Whether production work should be routed onto the AMX-FP16 kernels: this +/// host can run them ([`amx_fp16_supported`]) and no operator has turned them +/// off. +/// +/// **AMX is on by default.** Dispatch is a run-time decision made from CPU +/// capability alone, so a host with the silicon uses it with nothing to enable — +/// there is no Cargo feature and no opt-in variable. `LANCE_DISABLE_AMX` is the +/// escape hatch for the cases where a capability probe is not the whole story: +/// A/B measurement, and an operator who needs the previous code path back +/// without rebuilding. Set it to `1`, `true` or `on` (case-insensitive, +/// surrounding whitespace ignored) to take the AMX paths out of service; every +/// other value, and an unset variable, leave them in. +/// +/// Note this changes *which algorithm* an index build uses, not just how fast it +/// runs: without the GEMM, partition assignment falls back to an approximate +/// graph lookup (see `lance_index`'s `prefers_flat_amx_assignment`). Two indexes +/// built on either side of this variable are not interchangeable. +pub fn amx_fp16_available() -> bool { + !amx_fp16_disabled() && amx_fp16_supported() +} + +/// The `LANCE_DISABLE_AMX` kill switch on its own, read once and cached. Cached +/// because the routing decisions that consult it run per block of vectors, and +/// because a build that flipped behaviour halfway through would be far harder to +/// reason about than one that reads the environment at startup. +fn amx_fp16_disabled() -> bool { + static DISABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *DISABLED.get_or_init(|| { + std::env::var("LANCE_DISABLE_AMX").is_ok_and(|value| is_amx_disable_value(&value)) + }) +} + +/// The accepted spellings of "off". Anything else — including `0`, `false` and +/// the empty string — leaves AMX enabled, because an unrecognised value must not +/// silently disable a path the operator did not clearly ask to disable. +fn is_amx_disable_value(value: &str) -> bool { + matches!( + value.trim().to_ascii_lowercase().as_str(), + "1" | "true" | "on" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use rand::rngs::StdRng; + use rand::{Rng, SeedableRng}; + + /// Dims covering: < 32 (no tile pass, pure fallback), exactly 32 (one pass, + /// no tail), non-multiples of 32 (exercise the AMX tail), and larger dims + /// (multiple passes). + const BATCH_DIMS: &[usize] = &[ + 1, 7, 31, 32, 33, 47, 64, 96, 100, 127, 128, 200, 256, 384, 768, 1000, 1536, + ]; + + fn make_batch(dim: usize, rng: &mut StdRng) -> (Vec, Vec>) { + let gen_vec = |rng: &mut StdRng| -> Vec { + (0..dim) + .map(|_| f16::from_f32(rng.random_range(-1.0f32..1.0))) + .collect() + }; + let query = gen_vec(rng); + let candidates = (0..16).map(|_| gen_vec(rng)).collect(); + (query, candidates) + } + + /// f32-accumulated reference dot product — the semantic contract both the + /// AMX and fallback paths approximate. `f16::dot` itself accumulates in f32. + fn ref_dot_f32(query: &[f16], cand: &[f16]) -> f32 { + query + .iter() + .zip(cand.iter()) + .map(|(&q, &c)| q.to_f32() * c.to_f32()) + .sum() + } + + /// Relative-error tolerance justification: fp16 carries ~11 bits of mantissa + /// (~3 decimal digits). The AMX path and the f32 reference differ only in + /// summation order of f32-widened products, so the error is many orders + /// tighter than fp16's own representational error; 5e-3 relative is a very + /// safe bound (observed worst case is ~2e-4). + const REL_TOL: f32 = 5e-3; + + fn assert_close(got: f32, want: f32, ctx: &str) { + let rel = (got - want).abs() / (want.abs() + 1e-6); + assert!( + rel <= REL_TOL || (got - want).abs() <= 1e-3, + "{ctx}: got {got} want {want} rel_err {rel}" + ); + } + + #[test] + fn fallback_matches_reference() { + let mut rng = StdRng::seed_from_u64(0xF16); + for &dim in BATCH_DIMS { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + let got = dot_f16_batch_16_fallback(&query, &candidates, 16); + for i in 0..16 { + assert_close( + got[i], + ref_dot_f32(&query, &cands[i]), + &format!("fb dim={dim} i={i}"), + ); + } + } + } + + #[test] + fn dispatch_matches_reference() { + let mut rng = StdRng::seed_from_u64(0xBEEF); + for &dim in BATCH_DIMS { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + let got = dot_f16_batch_16(&query, &candidates, 16); + for i in 0..16 { + assert_close( + got[i], + ref_dot_f32(&query, &cands[i]), + &format!("disp dim={dim} i={i}"), + ); + } + } + } + + #[test] + #[should_panic(expected = "all candidate vectors must have the same length")] + fn rejects_mismatched_candidate_length() { + let query = vec![f16::from_f32(1.0); 32]; + let short = vec![f16::from_f32(1.0); 31]; + let candidates: [&[f16]; 16] = std::array::from_fn(|i| { + if i == 0 { + short.as_slice() + } else { + query.as_slice() + } + }); + let _ = dot_f16_batch_16(&query, &candidates, 16); + } + + /// A live lane must be bit-identical whatever `len` the batch was issued at. + /// Shortening the batch changes only how many rows are gathered, never a + /// row's contents nor the order the tile passes accumulate them, so anything + /// less than bit-exact here would mean a staging offset moved with `len` — + /// exactly the bug a tolerance would hide. Lanes past `len` must read 0 on + /// both paths: dispatch is host-dependent, so a caller must not be able to + /// tell which one ran. + #[test] + fn partial_len_matches_full_batch_and_zeroes_the_rest() { + let mut rng = StdRng::seed_from_u64(0x1EE); + for &dim in BATCH_DIMS { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + let full = dot_f16_batch_16(&query, &candidates, 16); + let full_fb = dot_f16_batch_16_fallback(&query, &candidates, 16); + for len in 1..=16 { + let got = dot_f16_batch_16(&query, &candidates, len); + let got_fb = dot_f16_batch_16_fallback(&query, &candidates, len); + for i in 0..len { + assert_eq!( + got[i].to_bits(), + full[i].to_bits(), + "dim={dim} len={len} i={i}: {} vs {}", + got[i], + full[i] + ); + assert_eq!( + got_fb[i].to_bits(), + full_fb[i].to_bits(), + "fb dim={dim} i={i}" + ); + } + for i in len..16 { + assert_eq!(got[i], 0.0, "dim={dim} len={len}: lane {i} must be 0"); + assert_eq!(got_fb[i], 0.0, "fb dim={dim} len={len}: lane {i} must be 0"); + } + } + } + } + + /// `len` is rejected, never clamped: the kernel indexes its staging buffer + /// by it, and a caller that meant 16 and passed 17 should hear about it. + #[rstest::rstest] + #[case::zero(0)] + #[case::seventeen(17)] + #[should_panic(expected = "batch length must be in 1..=16")] + fn rejects_out_of_range_len(#[case] len: usize) { + let query = vec![f16::from_f32(1.0); 32]; + let candidates: [&[f16]; 16] = std::array::from_fn(|_| query.as_slice()); + let _ = dot_f16_batch_16(&query, &candidates, len); + } + + /// The `LANCE_DISABLE_AMX` truth table, pinned in one place. + /// + /// Which spellings mean "off" is an operator-facing contract, and both ways + /// of getting it wrong are silent. A typo accepted as a kill switch — + /// `LANCE_DISABLE_AMX=disable` — would quietly change which algorithm an + /// index build uses, and the only visible trace would be a recall number + /// nobody was comparing. A deliberate `1` rejected would leave an operator + /// who needs the old path back believing they have it. + /// + /// The asymmetry with the enable direction is deliberate: an unrecognised + /// value leaves AMX **on**, because the default is on and an unparsable + /// request to deviate from it should not be honoured by halves. + #[test] + fn amx_disable_flag_accepts_only_explicit_on() { + for value in ["1", "true", "on", "TRUE", "On", " 1 ", "true\n"] { + assert!(is_amx_disable_value(value), "{value:?} should disable AMX"); + } + for value in ["", " ", "0", "false", "off", "no", "yes", "2", "disable"] { + assert!( + !is_amx_disable_value(value), + "{value:?} should not disable AMX" + ); + } + } + + /// With the kill switch unset, availability is exactly hardware support. + /// + /// This is the "on by default" contract itself: the assertion that would + /// fail if a Cargo feature or an opt-in variable ever crept back in front of + /// the dispatch decision. It is derived rather than hardcoded so it holds + /// identically on a host without AMX and in a build whose toolchain could + /// not compile the kernel. + #[test] + fn amx_is_available_by_default_wherever_it_is_supported() { + if std::env::var_os("LANCE_DISABLE_AMX").is_some() { + return; // the switch is under test elsewhere; respect it here + } + assert_eq!(amx_fp16_available(), amx_fp16_supported()); + } + + /// The length arithmetic guarding the GEMM's FFI boundary must reject a + /// shape it cannot represent, not wrap it into a small number. + /// + /// The first case is the one that made this necessary: unchecked, + /// `(32 - 1) * 595_056_260_442_243_601 + 32` wraps to **47**, so a + /// 47-element slice satisfied a check that meant to demand ~1.8e19 + /// elements — and the kernel then strode `data + i * stride` far past the + /// end of it. A wrapped requirement is dangerous precisely because it comes + /// out *small* enough to pass. + /// + /// Deliberately a plain-function test: it runs on every host, including + /// those where `PackedCentroidsF16` cannot be constructed at all. + #[test] + fn strided_len_rejects_shapes_it_cannot_represent() { + assert_eq!(strided_len(32, 595_056_260_442_243_601, 32), None); + assert_eq!(strided_len(2, usize::MAX, 1), None); + assert_eq!(strided_len(usize::MAX, 2, 0), None); + // Representable shapes still come through, including the degenerate + // single-row case where the stride is never applied. + assert_eq!(strided_len(32, 768, 768), Some(31 * 768 + 768)); + assert_eq!(strided_len(1, usize::MAX, 5), Some(5)); + // Zero rows need zero elements, and must not underflow `m - 1`. + assert_eq!(strided_len(0, usize::MAX, usize::MAX), Some(0)); + } + + /// End to end: the safe `score` wrapper must panic on the overflowing + /// shape rather than hand the undersized slice to the C kernel. + /// + /// `strided_len_rejects_shapes_it_cannot_represent` pins the arithmetic; + /// this pins that `score` actually consults it before the `unsafe` block. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn score_rejects_overflowing_stride_before_ffi() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + + let centroids = vec![f16::ONE; 32 * 32]; + let Some(packed) = PackedCentroidsF16::new(¢roids, 32, 32) else { + return; // no AMX on this host; the arithmetic test above still ran + }; + let data = vec![f16::ZERO; 47]; + let mut out = vec![0f32; 32 * 32]; + + let hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); // the panic is the expected result + let result = catch_unwind(AssertUnwindSafe(|| { + packed.score(&data, 32, 595_056_260_442_243_601, &mut out, 32); + })); + std::panic::set_hook(hook); + + assert!( + result.is_err(), + "score accepted a 47-element slice for a stride whose row count overflows usize" + ); + } + + /// On AMX-FP16 hardware, assert the AMX branch is actually selected (not a + /// silent fallback) and agrees with the f32 reference within tolerance. + /// Reaching the end without a SIGILL is itself proof the tile path executed. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn amx_path_is_active_and_close() { + if !crate::simd::amx_fp16::amx_supported() { + return; + } + let mut rng = StdRng::seed_from_u64(0xA11); + let mut worst = 0f32; + for &dim in BATCH_DIMS.iter().filter(|&&d| d >= 32) { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + let amx = + unsafe { crate::simd::amx_fp16::dot_f16_batch_16_amx(&query, &candidates, 16) }; + for i in 0..16 { + let want = ref_dot_f32(&query, &cands[i]); + assert_close(amx[i], want, &format!("amx dim={dim} i={i}")); + let rel = (amx[i] - want).abs() / (want.abs() + 1e-6); + worst = worst.max(rel); + } + } + assert!(worst <= REL_TOL, "worst AMX relative error: {worst:.2e}"); + } + + /// Another AMX user on this thread retiring the tile configuration must not + /// break the next kernel call. + /// + /// Regression for a stale-cache bug: the kernels used to remember which + /// configuration they had loaded and skip LDTILECFG when it matched, but that + /// record was private to Lance while LDTILECFG and TILERELEASE are + /// architectural per-logical-processor state. After a foreign TILERELEASE the + /// record still said "SEARCH is live" and the hardware was back in INIT, so + /// the kernel skipped the load and its first tile op raised #UD. Reloading on + /// every entry is the fix; this is what would fail if a cache came back. + /// + /// Both halves of that design are checked here, and only one of them has any + /// other symptom. The reload shows up as the kernel surviving a clobber; the + /// release on exit shows up nowhere but in the tile unit itself, read back at + /// the end. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn kernel_reconfigures_after_foreign_tile_release() { + use crate::simd::amx_fp16::{ + amx_supported, clobber_tile_state_for_test, dot_f16_batch_16_amx, + tile_config_is_live_for_test, + }; + + if !amx_supported() { + return; + } + let mut rng = StdRng::seed_from_u64(0xC10B); + let (query, cands) = make_batch(256, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + + let before = unsafe { dot_f16_batch_16_amx(&query, &candidates, 16) }; + // SAFETY: the `amx_supported()` check above granted XTILEDATA, so + // TILERELEASE is legal here. + unsafe { clobber_tile_state_for_test() }; + // Reaching the end of this call at all is the assertion that matters: + // under the bug it raised #UD and killed the test process. Comparing the + // results additionally catches the quieter variant, where a foreign + // configuration supplies the wrong shapes instead of none. + let after = unsafe { dot_f16_batch_16_amx(&query, &candidates, 16) }; + assert_eq!( + before, after, + "kernel output changed after a foreign TILERELEASE" + ); + + // Everything above only asks "did it crash". That is too weak on its own: + // `lance_amx_tile_ensure` reloading on entry is by itself enough to keep + // results right, so deleting `lance_amx_tile_done`'s TILERELEASE would + // leave every assertion so far green while the tile unit stayed held + // against the next AMX user on this thread. Reading the hardware is what + // catches that. + assert!( + !tile_config_is_live_for_test(), + "a kernel left its tile configuration loaded after returning" + ); + } + + /// The batch-16 kernel's tile shape, pinned byte for byte. + /// + /// The shape is the one thing a refactor of `amx_fp16.c` can change with no + /// visible symptom until it runs on AMX hardware, where a wrong shape is a + /// #UD or wrong results rather than a clean failure. Reading the + /// configuration image back is a way to check it without executing a single + /// tile instruction. + /// + /// It still needs the `amx_supported()` guard, which is easy to mistake for + /// redundant: `lance_amx_tilecfg_image` only fills a 64-byte struct. But + /// `amx_fp16.c` is compiled as one translation unit with + /// `-march=sapphirerapids`, so the compiler may use instructions from that + /// baseline anywhere in the file — entering *any* function in it faults on + /// an older CPU. Under `qemu -cpu Nehalem` that is a SIGILL, which is + /// exactly what the `qemu-pre-haswell` CI job runs. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn search_tile_config_image_is_pinned() { + use crate::simd::amx_fp16::{AMX_CFG_SEARCH, amx_supported, tilecfg_image}; + + if !amx_supported() { + return; + } + + // Image layout per Intel SDM: palette_id, start_row, 14 reserved bytes, + // a u16 colsb[16] array, then a u8 rows[16] array. + const COLSB: usize = 16; + const ROWS: usize = 48; + + let mut want = [0u8; 64]; + want[0] = 1; // palette_id + // C = tmm0: 16 x 1 fp32, fed by three independent (A, B) pairs so three + // TDPFP16PS can be in flight at once: A = tmm1/3/5, each 16 x 32 fp16; + // B = tmm2/4/6, each 16 x 2 fp16. tmm7 is left unconfigured. + for (tmm, colsb) in [ + (0usize, 4u16), + (1, 64), + (2, 4), + (3, 64), + (4, 4), + (5, 64), + (6, 4), + ] { + want[COLSB + tmm * 2..COLSB + tmm * 2 + 2].copy_from_slice(&colsb.to_le_bytes()); + want[ROWS + tmm] = 16; + } + + let got = tilecfg_image(AMX_CFG_SEARCH).expect("search config kind must be known"); + assert_eq!(got, want, "batch-16 tile configuration changed"); + } + + /// An unknown config kind must be rejected rather than answered with a + /// zeroed image: an all-zero (unconfigured) shape #UDs on the first tile op. + /// + /// Guarded for the same reason as the test above: reaching the C side at + /// all requires a CPU that can run its `-march=sapphirerapids` code. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn unknown_tile_config_kind_is_rejected() { + if !crate::simd::amx_fp16::amx_supported() { + return; + } + assert!(crate::simd::amx_fp16::tilecfg_image(-1).is_none()); + } + + // ----------------------------------------------------------------------- + // AMX-FP16 m x n GEMM + // ----------------------------------------------------------------------- + + /// `[m, dim]` vectors and `[n, dim]` centroids, both row-major and tightly + /// packed. Separate rngs per role would make a transposition bug harder to + /// spot, so both come off one stream. + fn make_gemm(m: usize, n: usize, dim: usize, rng: &mut StdRng) -> (Vec, Vec) { + let mut sample = |count: usize| -> Vec { + (0..count) + .map(|_| f16::from_f32(rng.random_range(-1.0f32..1.0))) + .collect() + }; + (sample(m * dim), sample(n * dim)) + } + + /// f32-accumulated reference GEMM — the same semantic contract as + /// [`ref_dot_f32`], extended to every (vector, centroid) pair. + fn ref_gemm( + data: &[f16], + m: usize, + data_stride: usize, + centroids: &[f16], + n: usize, + dim: usize, + ) -> Vec { + let mut out = vec![0f32; m * n]; + for i in 0..m { + let row = &data[i * data_stride..i * data_stride + dim]; + for j in 0..n { + out[i * n + j] = ref_dot_f32(row, ¢roids[j * dim..j * dim + dim]); + } + } + out + } + + /// Pack + run the GEMM kernel, returning an `[m, out_stride]` buffer. + /// + /// The destination starts as NaN rather than 0 so a tile store that never + /// lands (wrong stride, wrong tile index) fails the comparison instead of + /// passing on a coincidentally-correct zero. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + fn run_gemm( + data: &[f16], + m: usize, + data_stride: usize, + centroids: &[f16], + n: usize, + dim: usize, + out_stride: usize, + ) -> Vec { + use crate::simd::amx_fp16::{dot_f16_gemm_amx, pack_centroids_vnni}; + let mut packed = Vec::new(); + pack_centroids_vnni(centroids, n, dim, &mut packed); + let mut out = vec![f32::NAN; m * out_stride]; + unsafe { + dot_f16_gemm_amx( + data, + m, + data_stride, + &packed, + centroids, + n, + dim, + &mut out, + out_stride, + ); + } + out + } + + /// Compare a `[m, out_stride]` kernel result against a tightly-packed + /// `[m, n]` reference. + fn assert_gemm_close( + got: &[f32], + want: &[f32], + m: usize, + n: usize, + out_stride: usize, + ctx: &str, + ) { + for i in 0..m { + for j in 0..n { + assert_close( + got[i * out_stride + j], + want[i * n + j], + &format!("{ctx} [{i}][{j}]"), + ); + } + } + } + + /// The VNNI interleave, checked against the identity it exists to satisfy. + /// + /// This is the one part of the GEMM with no cheap sanity signal: a wrong + /// permutation still produces plausible-looking finite numbers, and on a + /// host without AMX nothing else here can run at all. Asserting the + /// element-for-element mapping keeps the layout pinned everywhere. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn packed_centroid_layout_matches_tile_operand_order() { + use crate::simd::amx_fp16::{pack_centroids_vnni, packed_centroids_len}; + + // Reused across shapes to also pin that packing clears rather than + // appends — a stale prefix would silently offset every B tile. + let mut packed = Vec::new(); + let mut rng = StdRng::seed_from_u64(0x9EC7); + for (n, dim) in [(16usize, 32usize), (32, 64), (48, 100), (32, 31), (32, 768)] { + let centroids: Vec = (0..n * dim) + .map(|_| f16::from_f32(rng.random_range(-1.0f32..1.0))) + .collect(); + pack_centroids_vnni(¢roids, n, dim, &mut packed); + assert_eq!( + packed.len(), + packed_centroids_len(n, dim), + "n={n} dim={dim}" + ); + + for kb in 0..dim / 32 { + for jb in 0..n / 16 { + for k in 0..16 { + for nn in 0..16 { + for p in 0..2 { + let at = ((kb * (n / 16)) + jb) * 512 + k * 32 + nn * 2 + p; + let from = (jb * 16 + nn) * dim + kb * 32 + 2 * k + p; + assert_eq!( + packed[at], centroids[from], + "n={n} dim={dim} kb={kb} jb={jb} k={k} nn={nn} p={p}" + ); + } + } + } + } + } + } + } + + /// GEMM results against the f32 reference across the shapes that exercise + /// each loop boundary: one vs. several 32-row/32-column register blocks, + /// one vs. many k-passes, dims with and without a scalar tail, dims too + /// short for any tile pass at all, and a case with padded row strides on + /// both the input and the output. + /// + /// Dims below 32 matter disproportionately: the kernel skips the tile loop + /// entirely, so `out` is never written by a tile store and the scalar tail + /// has to zero it first. Accumulating onto uninitialized memory instead + /// would still look plausible on a freshly-allocated buffer. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn gemm_matches_reference() { + if !crate::simd::amx_fp16::amx_supported() { + return; + } + let mut rng = StdRng::seed_from_u64(0x6E33); + for &m in &[32usize, 64] { + for &n in &[32usize, 64] { + for &dim in &[1usize, 16, 31, 32, 33, 64, 100, 768, 1000, 1536] { + let (data, centroids) = make_gemm(m, n, dim, &mut rng); + let want = ref_gemm(&data, m, dim, ¢roids, n, dim); + let got = run_gemm(&data, m, dim, ¢roids, n, dim, n); + assert_gemm_close(&got, &want, m, n, n, &format!("gemm m={m} n={n} dim={dim}")); + } + } + } + + // Padded strides: the kernel must address rows by the caller's stride, + // not by `dim` / `n`, so it can score a window of a larger buffer. + let (m, n, dim) = (64usize, 32usize, 100usize); + let (data_stride, out_stride) = (dim + 7, n + 5); + let mut data: Vec = vec![f16::from_f32(f32::MAX); m * data_stride]; + let (tight, centroids) = make_gemm(m, n, dim, &mut rng); + for i in 0..m { + data[i * data_stride..i * data_stride + dim] + .copy_from_slice(&tight[i * dim..(i + 1) * dim]); + } + let want = ref_gemm(&data, m, data_stride, ¢roids, n, dim); + let got = run_gemm(&data, m, data_stride, ¢roids, n, dim, out_stride); + assert_gemm_close(&got, &want, m, n, out_stride, "gemm padded strides"); + } + + /// The safe wrapper, over centroid counts that do and do not divide 32. + /// + /// Padding is the part a caller cannot see and must still reason about: the + /// real centroids have to score exactly as they would unpadded, and the + /// columns beyond them have to be the zeros that make a caller's argmin + /// bound (`< n`) load-bearing rather than decorative. + #[test] + fn packed_centroids_pad_to_the_kernel_block() { + let mut rng = StdRng::seed_from_u64(0x9AD); + for (n, dim) in [(32usize, 64usize), (100, 100), (48, 768)] { + let m = 64; + let (data, centroids) = make_gemm(m, n, dim, &mut rng); + let Some(packed) = PackedCentroidsF16::new(¢roids, n, dim) else { + return; // no AMX-FP16 on this build or host + }; + let n_padded = packed.num_centroids_padded(); + assert_eq!(n_padded, n.next_multiple_of(32), "n={n}"); + + // A wider output stride than the padded width, so a row's tail is + // untouched memory rather than the next row's scores. + let out_stride = n_padded + 3; + let mut out = vec![f32::NAN; m * out_stride]; + packed.score(&data, m, dim, &mut out, out_stride); + + let want = ref_gemm(&data, m, dim, ¢roids, n, dim); + assert_gemm_close(&out, &want, m, n, out_stride, &format!("packed n={n}")); + for i in 0..m { + for j in n..n_padded { + assert_eq!(out[i * out_stride + j], 0.0, "padding n={n} [{i}][{j}]"); + } + } + } + } + + /// The GEMM kernel's tile shape, pinned byte for byte, for the same reason + /// as [`search_tile_config_image_is_pinned`]. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn gemm_tile_config_image_is_pinned() { + use crate::simd::amx_fp16::{AMX_CFG_GEMM, amx_supported, tilecfg_image}; + + if !amx_supported() { + return; + } + + const COLSB: usize = 16; + const ROWS: usize = 48; + + let mut want = [0u8; 64]; + want[0] = 1; // palette_id + // All eight tiles at the architectural maximum 16 x 64 B: four fp32 + // accumulators, two A panels, two VNNI-packed B panels. + for tmm in 0..8usize { + want[COLSB + tmm * 2..COLSB + tmm * 2 + 2].copy_from_slice(&64u16.to_le_bytes()); + want[ROWS + tmm] = 16; + } + + let got = tilecfg_image(AMX_CFG_GEMM).expect("gemm config kind must be known"); + assert_eq!(got, want, "gemm tile configuration changed"); + } + + /// Alternate the two kernels on one thread and check both stay correct. + /// + /// They ask for incompatible tile shapes (7 tiles, four of them 16x4, vs. 8 + /// tiles all 16x64), so each call has to install its own shape over the one + /// the previous call left. That is what this pins: a kernel running against + /// the other one's tile shape reads garbage or #UDs, and only alternating + /// the two shapes can expose it. It says nothing about how the configuration + /// got there — `kernel_reconfigures_after_foreign_tile_release` is the test + /// that pins the reload itself. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn interleaved_search_and_gemm_stay_correct() { + if !crate::simd::amx_fp16::amx_supported() { + return; + } + let mut rng = StdRng::seed_from_u64(0x11E12EA5); + let (m, n, dim) = (32usize, 32usize, 96usize); + for round in 0..20 { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = std::array::from_fn(|i| cands[i].as_slice()); + let batch = + unsafe { crate::simd::amx_fp16::dot_f16_batch_16_amx(&query, &candidates, 16) }; + for i in 0..16 { + assert_close( + batch[i], + ref_dot_f32(&query, &cands[i]), + &format!("interleaved batch round={round} i={i}"), + ); + } + + let (data, centroids) = make_gemm(m, n, dim, &mut rng); + let want = ref_gemm(&data, m, dim, ¢roids, n, dim); + let got = run_gemm(&data, m, dim, ¢roids, n, dim, n); + assert_gemm_close( + &got, + &want, + m, + n, + n, + &format!("interleaved gemm round={round}"), + ); + } + } + + /// Both kernels running concurrently on different threads. + /// + /// LDTILECFG is per-logical-processor state, so correctness here rests on + /// each call building its configuration image on its own stack. A shared or + /// `static` image would let one thread's shape reach another's tile ops, + /// which this catches and a single-threaded test cannot. + #[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" + ))] + #[test] + fn concurrent_search_and_gemm_stay_correct() { + if !crate::simd::amx_fp16::amx_supported() { + return; + } + const THREADS: u64 = 8; + std::thread::scope(|scope| { + for t in 0..THREADS { + scope.spawn(move || { + let mut rng = StdRng::seed_from_u64(0xC0FFEE + t); + let dim = 128; + for round in 0..25 { + if t % 2 == 0 { + let (query, cands) = make_batch(dim, &mut rng); + let candidates: [&[f16]; 16] = + std::array::from_fn(|i| cands[i].as_slice()); + let batch = unsafe { + crate::simd::amx_fp16::dot_f16_batch_16_amx(&query, &candidates, 16) + }; + for i in 0..16 { + assert_close( + batch[i], + ref_dot_f32(&query, &cands[i]), + &format!("concurrent batch t={t} round={round} i={i}"), + ); + } + } else { + let (m, n) = (32usize, 32usize); + let (data, centroids) = make_gemm(m, n, dim, &mut rng); + let want = ref_gemm(&data, m, dim, ¢roids, n, dim); + let got = run_gemm(&data, m, dim, ¢roids, n, dim, n); + assert_gemm_close( + &got, + &want, + m, + n, + n, + &format!("concurrent gemm t={t} round={round}"), + ); + } + } + }); + } + }); + } + + /// The two costs a membership-level benchmark cannot separate: packing the + /// centroids, which happens once per call and is amortized over every block + /// of vectors, and the GEMM's throughput as a function of the block height + /// `m` its caller chooses. + /// + /// `m` sets how much f32 scratch one block writes (`m * n_padded * 4` bytes, + /// reported per row), which is what decides whether the reduction that + /// follows reads it out of L2 or out of memory. A caller sizing its blocks + /// from a scratch budget is making exactly this trade, so sweeping `m` here + /// says whether it lands on the right side of it. No knob is needed in the + /// production path for that — `score` takes `m` directly. + /// + /// `#[ignore]` -- run: + /// cargo test -p lance-linalg --release \ + /// packed_centroids_gemm_shape_bench -- --ignored --nocapture + /// Tune with `BENCH_DIMS` / `BENCH_KS` (comma-separated) and `BENCH_SECONDS` + /// (the wall-clock budget each measured point gets). + #[test] + #[ignore] + #[allow(clippy::print_stderr)] + // Without the kernel `PackedCentroidsF16` is uninhabited, so the first + // `expect` below has type `!` and everything after it is provably dead. That + // is the property the type is designed to have; it is not a sign the bench is + // wrong. + #[allow(unreachable_code, unused_variables)] + fn packed_centroids_gemm_shape_bench() { + use std::time::{Duration, Instant}; + + // Multiples of 32 (the kernel's `m` granularity) spanning scratch that + // fits a private L2 up to scratch that cannot. + const BLOCK_ROWS: &[usize] = &[32, 64, 128, 256, 512, 1024, 2048]; + + if !amx_fp16_supported() { + eprintln!("[gemm_shape_bench] skipped: amx_fp16_supported=false on this build or host"); + return; + } + + let env_list = |key: &str, default: &[usize]| -> Vec { + std::env::var(key) + .ok() + .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect()) + .unwrap_or_else(|| default.to_vec()) + }; + let dims = env_list("BENCH_DIMS", &[768]); + let ks = env_list("BENCH_KS", &[256, 4096]); + let budget = Duration::from_secs_f64( + std::env::var("BENCH_SECONDS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(3.0), + ); + + let mut rng = StdRng::seed_from_u64(0x6E33); + let mut random_f16 = |count: usize| -> Vec { + (0..count) + .map(|_| f16::from_f32(rng.random_range(-1.0f32..1.0))) + .collect() + }; + + eprintln!( + "[gemm_shape_bench] budget={:.1}s amx_fp16_supported=true", + budget.as_secs_f64() + ); + for &dim in &dims { + for &k in &ks { + let centroids = random_f16(k * dim); + + let mut packs = 0usize; + let t0 = Instant::now(); + while t0.elapsed() < budget { + let packed = PackedCentroidsF16::new(¢roids, k, dim); + std::hint::black_box(&packed); + packs += 1; + } + let pack_us = t0.elapsed().as_secs_f64() * 1e6 / packs as f64; + + let packed = PackedCentroidsF16::new(¢roids, k, dim) + .expect("availability was just checked"); + let n_padded = packed.num_centroids_padded(); + eprintln!( + "[gemm_shape_bench] dim={dim} k={k} n_padded={n_padded} pack_calls={packs} pack_us={pack_us:.1}" + ); + + let mut best_vec_per_s = 0f64; + for &m in BLOCK_ROWS { + let data = random_f16(m * dim); + let mut out = vec![0f32; m * n_padded]; + packed.score(&data, m, dim, &mut out, n_padded); // untimed warm-up + + let t1 = Instant::now(); + let mut iters = 0usize; + while t1.elapsed() < budget { + packed.score(&data, m, dim, &mut out, n_padded); + iters += 1; + } + let elapsed = t1.elapsed().as_secs_f64(); + std::hint::black_box(&out); + + let vec_per_s = (iters * m) as f64 / elapsed; + best_vec_per_s = best_vec_per_s.max(vec_per_s); + eprintln!( + // Pairs count the padding columns, since the kernel does + // the work either way — this is its true rate, not the + // caller's useful fraction of it. + "[gemm_shape_bench] m={m:>5} scratch_kb={:>7} iters={iters:>8} vec_per_s={vec_per_s:>12.0} us_per_vec={:>8.4} Gpair_per_s={:>8.2}", + m * n_padded * 4 / 1024, + 1e6 / vec_per_s, + vec_per_s * n_padded as f64 / 1e9, + ); + } + eprintln!( + "[gemm_shape_bench] pack_us={pack_us:.1} buys {:.0} vectors of scoring at the best m: packing is amortized above that", + pack_us * 1e-6 * best_vec_per_s, + ); + } + } + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/dot_u8.rs b/rust/lancedb/vendor/lance-linalg/src/distance/dot_u8.rs new file mode 100644 index 000000000..8a57b48e6 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/dot_u8.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Unsigned int8 dot product with runtime-dispatched SIMD backends. +//! +//! Used by Scalar Quantization (SQ) distance computation. SQ stores each +//! vector dimension as a u8 after linearly mapping [min, max] → [0, 255]. +//! Distance computation between SQ-encoded vectors reduces to a u8 × u8 +//! dot product plus precomputed per-vector scalar terms. +//! The u32 entry points return the low 32 bits, while [`dot_u8_u64`] chunks +//! those kernels to produce the full result used by SQ. +//! +//! Backends (selected at runtime, best available wins): +//! 1. scalar — portable reference, also used for tails +//! 2. avx2 — VPMADDWD on u16-widened halves, 32 elements/iter +//! 3. avx512vnni — VPDPBUSD with XOR-0x80 bias trick, 64 elements/iter +//! +//! ## The VNNI bias trick +//! +//! VPDPBUSD expects one unsigned and one signed operand, but SQ vectors +//! are u8 × u8. We bias `b` into the signed domain via XOR 0x80 (equivalent +//! to subtracting 128 when reinterpreted as i8), feed `a` directly as +//! unsigned, and correct by adding 128·Σa at the end: +//! +//! DPBUSD(a, b ⊕ 0x80) = Σ a·(b − 128) = Σ a·b − 128·Σa +//! +//! The Σa term uses VPSADBW, which dispatches to port 5 while VPDPBUSD +//! runs on port 0 on Intel. The two instructions execute in parallel, +//! making the correction effectively free. + +use super::{U8_U32_ACCUMULATOR_MAX_LEN, assert_equal_lengths}; + +type DotU8Kernel = unsafe fn(&[u8], &[u8]) -> u32; + +lance_core::dispatch! { + /// There are no AVX or AVX+FMA candidates: the SIMD kernels need AVX2 + /// integer ops, so those hosts use the scalar kernel. + static DOT_U8: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[x86::DOT_U8_AVX512_VNNI, x86::DOT_U8_AVX2, DOT_U8_SCALAR] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[DOT_U8_SCALAR] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(DOT_U8_SCALAR: DotU8Kernel)] + /// Portable scalar u8 dot product, also used for SIMD tail elements. + /// + /// The result is the low 32 bits of the exact dot product. Use + /// [`dot_u8_u64`] when the full result is required. + /// + /// # Panics + /// + /// Panics if `a` and `b` have different lengths. + #[inline] + pub fn dot_u8_scalar(a: &[u8], b: &[u8]) -> u32 { + assert_equal_lengths(a.len(), b.len()); + a.iter() + .zip(b.iter()) + .fold(0, |sum, (&x, &y)| sum.wrapping_add(x as u32 * y as u32)) + } +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use super::DotU8Kernel; + + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) DOT_U8_AVX2: DotU8Kernel)] + /// AVX2 path: zero-extend u8→u16, then VPMADDWD. 32 elements/iter. + pub(super) fn dot_u8_avx2(a: &[u8], b: &[u8]) -> u32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let n = a.len().min(b.len()); + let mut acc = _mm256_setzero_si256(); + let mut i = 0usize; + + while i + 32 <= n { + let (av, bv) = unsafe { + ( + _mm256_loadu_si256(a.as_ptr().add(i) as *const __m256i), + _mm256_loadu_si256(b.as_ptr().add(i) as *const __m256i), + ) + }; + + // Zero-extend each 128-bit half to 16 × u16. Values ≤ 255 fit + // in i16 as positive, so VPMADDWD gives correct results. + let a_lo = _mm256_cvtepu8_epi16(_mm256_castsi256_si128(av)); + let a_hi = _mm256_cvtepu8_epi16(_mm256_extracti128_si256(av, 1)); + let b_lo = _mm256_cvtepu8_epi16(_mm256_castsi256_si128(bv)); + let b_hi = _mm256_cvtepu8_epi16(_mm256_extracti128_si256(bv, 1)); + + acc = _mm256_add_epi32(acc, _mm256_madd_epi16(a_lo, b_lo)); + acc = _mm256_add_epi32(acc, _mm256_madd_epi16(a_hi, b_hi)); + i += 32; + } + + let lo128 = _mm256_castsi256_si128(acc); + let hi128 = _mm256_extracti128_si256(acc, 1); + let mut sum128 = _mm_add_epi32(lo128, hi128); + sum128 = _mm_hadd_epi32(sum128, sum128); + sum128 = _mm_hadd_epi32(sum128, sum128); + let mut result = _mm_cvtsi128_si32(sum128) as u32; + + while i < n { + result = result.wrapping_add(a[i] as u32 * b[i] as u32); + i += 1; + } + result + } + } + + lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw", "avx512vnni")] + #[candidate(pub(super) DOT_U8_AVX512_VNNI: DotU8Kernel)] + /// AVX-512 VNNI path (Ice Lake+, Zen 4+). 64 elements/iter. + /// + /// VPDPBUSD expects (unsigned, signed) operands but SQ stores u8×u8. + /// We XOR b with 0x80 to map it to i8, then correct: result + 128·Σa. + /// The Σa term (VPSADBW, port 5) runs in parallel with VPDPBUSD (port 0). + pub(super) fn dot_u8_avx512_vnni(a: &[u8], b: &[u8]) -> u32 { + // See `dot_u8_avx2`. + let n = a.len().min(b.len()); + + let mut acc_dot = _mm512_setzero_si512(); + let mut acc_suma = _mm512_setzero_si512(); + let sign_flip = _mm512_set1_epi8(0x80u8 as i8); + let zeros = _mm512_setzero_si512(); + let mut i = 0usize; + + while i + 64 <= n { + let (av, bv) = unsafe { + ( + _mm512_loadu_si512(a.as_ptr().add(i) as *const __m512i), + _mm512_loadu_si512(b.as_ptr().add(i) as *const __m512i), + ) + }; + let b_biased = _mm512_xor_si512(bv, sign_flip); + acc_dot = _mm512_dpbusd_epi32(acc_dot, av, b_biased); + acc_suma = _mm512_add_epi32(acc_suma, _mm512_sad_epu8(av, zeros)); + i += 64; + } + + // VPSADBW leaves the high 32 bits of each u64 lane zero, so Σa + // can be summed in 32-bit lanes and folded into `acc_dot` for a + // single reduction; the result is only kept mod 2^32 anyway. + let acc = _mm512_add_epi32(acc_dot, _mm512_slli_epi32(acc_suma, 7)); + let mut result = _mm512_reduce_add_epi32(acc) as u32; + + while i < n { + result = result.wrapping_add(a[i] as u32 * b[i] as u32); + i += 1; + } + result + } + } +} + +/// Dispatched u8 dot product, selecting the best available SIMD backend. +/// +/// The result is the low 32 bits of the exact dot product. Use +/// [`dot_u8_u64`] when the full result is required. +/// +/// # Panics +/// +/// Panics if `a` and `b` have different lengths. +#[inline] +pub fn dot_u8(a: &[u8], b: &[u8]) -> u32 { + assert_equal_lengths(a.len(), b.len()); + DOT_U8.get().call(a, b) +} + +/// Calculates the exact u8 dot product with a u64 accumulator. +/// +/// This retains the runtime-selected SIMD kernel and widens its result between +/// chunks that are guaranteed to fit in a u32. +/// +/// # Panics +/// +/// Panics if `a` and `b` have different lengths. +/// +/// # Example +/// +/// ``` +/// use lance_linalg::distance::dot_u8::dot_u8_u64; +/// +/// assert_eq!(dot_u8_u64(&[2, 3], &[4, 5]), 23); +/// ``` +#[inline] +pub fn dot_u8_u64(a: &[u8], b: &[u8]) -> u64 { + assert_equal_lengths(a.len(), b.len()); + if a.len() <= U8_U32_ACCUMULATOR_MAX_LEN { + return dot_u8(a, b) as u64; + } + a.chunks(U8_U32_ACCUMULATOR_MAX_LEN) + .zip(b.chunks(U8_U32_ACCUMULATOR_MAX_LEN)) + .map(|(a, b)| dot_u8(a, b) as u64) + .sum() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::u8_inputs::{LENGTHS, Pattern, random}; + + #[test] + fn rejects_mismatched_lengths() { + assert!(std::panic::catch_unwind(|| dot_u8_scalar(&[1, 2], &[1])).is_err()); + assert!(std::panic::catch_unwind(|| dot_u8(&[1, 2], &[1])).is_err()); + } + + /// Every host-supported kernel, and the dispatched entry point, must equal + /// the low 32 bits of the exact dot product. + fn assert_kernels_match_reference(a: &[u8], b: &[u8], label: &str) { + let exact: u64 = a.iter().zip(b).map(|(&x, &y)| x as u64 * y as u64).sum(); + let want = exact as u32; + for candidate in DOT_U8.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(a, b); + assert_eq!(got, want, "{} [{label}] n={}", candidate.name(), a.len()); + } + assert_eq!(dot_u8(a, b), want, "dot_u8 [{label}] n={}", a.len()); + } + + #[rstest::rstest] + #[case::random(Pattern::Random)] + #[case::extremes(Pattern::Extremes)] + #[case::one_sided_zeros(Pattern::OneSidedZeros)] + fn test_dot_u8_kernels_match_reference(#[case] pattern: Pattern) { + for &len in LENGTHS { + for (label, a, b) in pattern.pairs(len) { + assert_kernels_match_reference(&a, &b, label); + } + } + } + + /// The SIMD kernels are safe functions, so unequal lengths must stay in + /// bounds and use the common prefix. The lengths cross both SIMD strides. + #[rstest::rstest] + #[case::shorter_right(129, 65)] + #[case::longer_right(65, 129)] + fn simd_kernels_use_common_prefix_of_unequal_lengths( + #[case] a_len: usize, + #[case] b_len: usize, + ) { + let a = random(a_len, 0); + let b = random(b_len, 1); + let n = a_len.min(b_len); + let want = dot_u8_scalar(&a[..n], &b[..n]); + for candidate in DOT_U8.candidates() { + // The scalar kernel asserts equal lengths instead. + if candidate.features().is_empty() { + continue; + } + let Some(kernel) = candidate.kernel() else { + continue; + }; + assert_eq!(kernel.call(&a, &b), want, "{}", candidate.name()); + } + } + + #[test] + fn known_values() { + assert_eq!(dot_u8_scalar(&[2, 3], &[4, 5]), 23); + assert_eq!(dot_u8(&[2, 3], &[4, 5]), 23); + assert_eq!(dot_u8(&[1; 4097], &[1; 4097]), 4097); + } + + #[test] + fn overflow_is_backend_independent_and_wide_result_is_exact() { + let len = U8_U32_ACCUMULATOR_MAX_LEN + 1; + let a = vec![u8::MAX; len]; + let b = vec![u8::MAX; len]; + let exact = u8::MAX as u64 * u8::MAX as u64 * len as u64; + + assert_kernels_match_reference(&a, &b, "u32 overflow"); + assert_eq!(dot_u8_scalar(&a, &b), exact as u32); + assert_eq!(dot_u8_u64(&a, &b), exact); + assert_eq!(crate::distance::dot::dot::(&a, &b), exact as f32); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs b/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs new file mode 100644 index 000000000..0b711658b --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs @@ -0,0 +1,2098 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Hamming distance. +//! +//! This module provides hamming distance computation for binary vectors, +//! including SIMD-accelerated pairwise hamming distance for binary hashes. + +use std::collections::HashMap; +use std::sync::{Arc, LazyLock}; + +use arrow_array::builder::{ListBuilder, UInt64Builder}; +use arrow_array::{ + Array, ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, RecordBatchIterator, + RecordBatchReader, UInt32Array, UInt64Array, +}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use rayon::prelude::*; + +use crate::distance::assert_batch_layout; +use crate::{Error, Result}; + +/// Schema of a Hamming distance-pair batch. +static DISTANCE_PAIR_SCHEMA: LazyLock = LazyLock::new(|| { + Arc::new(Schema::new(vec![ + Field::new("row_id_a", DataType::UInt64, false), + Field::new("row_id_b", DataType::UInt64, false), + Field::new("distance", DataType::UInt32, false), + ])) +}); + +/// Schema of a Hamming clustering-result batch. +static CLUSTER_SCHEMA: LazyLock = LazyLock::new(|| { + Arc::new(Schema::new(vec![ + Field::new("representative", DataType::UInt64, false), + Field::new( + "duplicates", + DataType::List(Arc::new(Field::new("item", DataType::UInt64, true))), + false, + ), + ])) +}); + +pub trait Hamming { + /// Hamming distance between two vectors. + fn hamming(x: &[u8], y: &[u8]) -> f32; +} + +/// Hamming distance between two vectors. +#[inline] +pub fn hamming(x: &[u8], y: &[u8]) -> f32 { + hamming_autovec::<64>(x, y) +} + +#[inline] +fn hamming_autovec(x: &[u8], y: &[u8]) -> f32 { + let (x_chunks, x_remainder) = x.as_chunks::(); + let (y_chunks, y_remainder) = y.as_chunks::(); + let sum = x_remainder + .iter() + .zip(y_remainder) + .map(|(&a, &b)| (a ^ b).count_ones()) + .sum::(); + (sum + x_chunks + .iter() + .zip(y_chunks) + .map(|(x, y)| { + x.iter() + .zip(y.iter()) + .map(|(&a, &b)| (a ^ b).count_ones()) + .sum::() + }) + .sum::()) as f32 +} + +/// Scalar version of hamming distance. Used for benchmarks. +#[inline] +pub fn hamming_scalar(x: &[u8], y: &[u8]) -> f32 { + x.iter() + .zip(y.iter()) + .map(|(xi, yi)| (xi ^ yi).count_ones()) + .sum::() as f32 +} + +/// Compute Hamming distances from one vector to a batch of vectors. +/// +/// # Examples +/// +/// ``` +/// use lance_linalg::distance::hamming::hamming_distance_batch; +/// +/// let query = [0, u8::MAX]; +/// let targets = [0, u8::MAX, 1, u8::MAX - 1]; +/// let distances = hamming_distance_batch(&query, &targets, query.len()).collect::>(); +/// assert_eq!(distances, [0.0, 2.0]); +/// ``` +/// +/// # Panics +/// +/// Panics if `dimension` is zero, `from.len()` differs from `dimension`, or +/// `to` does not contain a whole number of vectors with that dimension. +pub fn hamming_distance_batch<'a>( + from: &'a [u8], + to: &'a [u8], + dimension: usize, +) -> Box + 'a> { + assert_batch_layout(from.len(), to.len(), dimension); + Box::new(to.chunks_exact(dimension).map(|v| hamming(from, v))) +} + +/// Compute Hamming distances with the validation of [`super::DistanceType::batch`]. +#[deprecated(note = "Use DistanceType::Hamming.batch")] +pub fn hamming_distance_arrow_batch( + from: &dyn Array, + to: &FixedSizeListArray, +) -> Result> { + super::DistanceType::Hamming.batch(from, to).map(Arc::new) +} + +/// Compute hamming distance between two 64-bit values using POPCNT. +#[inline(always)] +pub fn hamming_u64(a: u64, b: u64) -> u32 { + (a ^ b).count_ones() +} + +/// Binary hash values stored as 64-bit lanes in lane-major order. +/// +/// For a hash width of `N` bytes, `N` must be a positive multiple of 8 and the +/// number of lanes is `N / 8`. Lane-major layout keeps each lane contiguous for +/// all rows, which allows the pairwise path to reuse the SIMD `u64` batch +/// implementation for wider hashes. +#[derive(Debug, Clone)] +pub struct BinaryHashValues { + lane_values: Vec, + num_rows: usize, + byte_width: usize, +} + +impl BinaryHashValues { + /// Create hash values from lane-major `u64` values. + pub fn try_new(lane_values: Vec, num_rows: usize, byte_width: usize) -> Result { + let num_lanes = validate_hash_byte_width(byte_width)?; + let expected_values = checked_lane_value_count(num_rows, num_lanes)?; + if lane_values.len() != expected_values { + return Err(Error::InvalidArgumentError(format!( + "Expected {} lane values for {} rows and {} byte hashes, got {}", + expected_values, + num_rows, + byte_width, + lane_values.len() + ))); + } + Ok(Self { + lane_values, + num_rows, + byte_width, + }) + } + + /// Extract binary hash values from a `FixedSizeList` Arrow array. + pub fn from_fixed_size_list(array: &FixedSizeListArray) -> Result { + let byte_width = usize::try_from(array.value_length()).map_err(|_| { + Error::InvalidArgumentError(format!( + "Expected FixedSizeList with a positive size that is a multiple of 8 bytes, got size {}", + array.value_length() + )) + })?; + let num_lanes = validate_hash_byte_width(byte_width)?; + + let values = array + .values() + .as_any() + .downcast_ref::() + .ok_or_else(|| { + Error::InvalidArgumentError( + "Expected UInt8Array values in FixedSizeList".to_string(), + ) + })?; + + let num_rows = array.len(); + let value_count = checked_lane_value_count(num_rows, num_lanes)?; + let expected_bytes = checked_hash_byte_count(num_rows, byte_width)?; + let bytes = values.values(); + if bytes.len() != expected_bytes { + return Err(Error::InvalidArgumentError(format!( + "Expected {} bytes for {} rows and {} byte hashes, got {}", + expected_bytes, + num_rows, + byte_width, + bytes.len() + ))); + } + + let mut lane_values = vec![0u64; value_count]; + for row in 0..num_rows { + let row_start = row * byte_width; + for lane in 0..num_lanes { + let start = row_start + lane * 8; + let mut arr = [0u8; 8]; + arr.copy_from_slice(&bytes[start..start + 8]); + lane_values[lane * num_rows + row] = u64::from_le_bytes(arr); + } + } + + Ok(Self { + lane_values, + num_rows, + byte_width, + }) + } + + /// Concatenate chunks with the same hash width into a single lane-major set. + pub fn concat(chunks: &[Self]) -> Result { + let Some(first) = chunks.first() else { + return Err(Error::InvalidArgumentError( + "Cannot concatenate zero binary hash chunks".to_string(), + )); + }; + + let byte_width = first.byte_width; + let num_lanes = first.num_lanes(); + let mut num_rows = 0usize; + for chunk in chunks { + if chunk.byte_width != byte_width { + return Err(Error::InvalidArgumentError(format!( + "Cannot concatenate binary hash chunks with different widths: {} and {} bytes", + byte_width, chunk.byte_width + ))); + } + num_rows = num_rows.checked_add(chunk.num_rows).ok_or_else(|| { + Error::InvalidArgumentError( + "Binary hash row count overflowed while concatenating chunks".to_string(), + ) + })?; + } + + let value_count = checked_lane_value_count(num_rows, num_lanes)?; + let mut lane_values = vec![0u64; value_count]; + let mut row_offset = 0; + for chunk in chunks { + for lane in 0..num_lanes { + let dest_start = lane * num_rows + row_offset; + let dest_end = dest_start + chunk.num_rows; + lane_values[dest_start..dest_end].copy_from_slice(chunk.lane(lane)); + } + row_offset += chunk.num_rows; + } + + Ok(Self { + lane_values, + num_rows, + byte_width, + }) + } + + pub fn len(&self) -> usize { + self.num_rows + } + + pub fn is_empty(&self) -> bool { + self.num_rows == 0 + } + + pub fn byte_width(&self) -> usize { + self.byte_width + } + + pub fn num_lanes(&self) -> usize { + self.byte_width / 8 + } + + pub fn lane(&self, lane: usize) -> &[u64] { + let start = lane * self.num_rows; + &self.lane_values[start..start + self.num_rows] + } + + pub fn into_u64_values(self) -> Result> { + if self.num_lanes() != 1 { + return Err(Error::InvalidArgumentError(format!( + "Expected 8-byte binary hashes, got {} byte hashes", + self.byte_width + ))); + } + Ok(self.lane_values) + } +} + +fn checked_lane_value_count(num_rows: usize, num_lanes: usize) -> Result { + num_rows.checked_mul(num_lanes).ok_or_else(|| { + Error::InvalidArgumentError(format!( + "Binary hash lane value count overflowed for {} rows and {} lanes", + num_rows, num_lanes + )) + }) +} + +fn checked_hash_byte_count(num_rows: usize, byte_width: usize) -> Result { + num_rows.checked_mul(byte_width).ok_or_else(|| { + Error::InvalidArgumentError(format!( + "Binary hash byte count overflowed for {} rows and {} byte hashes", + num_rows, byte_width + )) + }) +} + +fn validate_hash_byte_width(byte_width: usize) -> Result { + if byte_width == 0 || !byte_width.is_multiple_of(8) { + return Err(Error::InvalidArgumentError(format!( + "Expected FixedSizeList with a positive size that is a multiple of 8 bytes, got size {}", + byte_width + ))); + } + Ok(byte_width / 8) +} + +/// Result of pairwise hamming distance computation. +#[derive(Debug, Clone)] +pub struct PairwiseResult { + pub row_id_a: Vec, + pub row_id_b: Vec, + pub distances: Vec, +} + +impl PairwiseResult { + pub fn new() -> Self { + Self { + row_id_a: Vec::new(), + row_id_b: Vec::new(), + distances: Vec::new(), + } + } + + pub fn with_capacity(capacity: usize) -> Self { + Self { + row_id_a: Vec::with_capacity(capacity), + row_id_b: Vec::with_capacity(capacity), + distances: Vec::with_capacity(capacity), + } + } + + pub fn push(&mut self, a: u64, b: u64, dist: u32) { + self.row_id_a.push(a); + self.row_id_b.push(b); + self.distances.push(dist); + } + + pub fn len(&self) -> usize { + self.row_id_a.len() + } + + pub fn is_empty(&self) -> bool { + self.row_id_a.is_empty() + } + + pub fn extend(&mut self, other: Self) { + self.row_id_a.extend(other.row_id_a); + self.row_id_b.extend(other.row_id_b); + self.distances.extend(other.distances); + } + + /// Convert to Arrow RecordBatch, consuming self. + pub fn into_record_batch(self) -> RecordBatch { + let schema = DISTANCE_PAIR_SCHEMA.clone(); + + let row_id_a = Arc::new(UInt64Array::from(self.row_id_a)); + let row_id_b = Arc::new(UInt64Array::from(self.row_id_b)); + let distances = Arc::new(UInt32Array::from(self.distances)); + + RecordBatch::try_new(schema, vec![row_id_a, row_id_b, distances]) + .expect("Failed to create RecordBatch") + } +} + +impl Default for PairwiseResult { + fn default() -> Self { + Self::new() + } +} + +/// Compute hamming distances for a query against multiple targets. +/// Uses SIMD acceleration when available. +/// +/// # Panics +/// +/// Panics if `results` is not the same length as `targets`. +#[inline] +pub fn hamming_batch_u64(query: u64, targets: &[u64], results: &mut [u32]) { + // Rejected in either direction, and before the dispatch. A shorter `results` the + // dispatcher's reslice would refuse on its own, and that reslice is what keeps the + // kernels' raw stores in bounds; this check just gets there first, with a message + // that names both lengths. An over-long one the reslice would instead truncate, + // handing the surplus tail back unwritten for the caller to read as distances. + // That is wrong output rather than a crash, which is why this is an `assert_eq!` + // and not a `debug_assert_eq!`. + let num_targets = targets.len(); + let num_slots = results.len(); + assert_eq!( + num_targets, num_slots, + "hamming_batch_u64 needs one result slot per target, \ + got {num_targets} target(s) and {num_slots} slot(s)" + ); + hamming_batch_simd(query, targets, results); +} + +/// SIMD-accelerated batch hamming distance computation. +/// +/// # Panics +/// +/// Panics if `results` is shorter than `targets`. `results.len()` is required to equal +/// `targets.len()`: an over-long `results` is truncated here rather than rejected, and +/// the surplus tail goes back to the caller unwritten. `hamming_batch_u64` asserts the +/// equality before dispatching. +#[inline] +fn hamming_batch_simd(query: u64, targets: &[u64], results: &mut [u32]) { + // Both x86 kernels store through raw pointers over a range bounded by + // `targets.len()`, and this reslice makes `results` exactly that long, so it has to + // stay above the dispatch. + let results = &mut results[..targets.len()]; + + #[cfg(target_arch = "x86_64")] + { + if is_x86_feature_detected!("avx512vpopcntdq") && is_x86_feature_detected!("avx512f") { + // SAFETY: both required features were just detected, and the reslice + // above makes `results.len() == targets.len()`. + unsafe { + hamming_batch_avx512(query, targets, results); + } + return; + } + if is_x86_feature_detected!("avx2") { + // SAFETY: AVX2 was just detected, and the reslice above makes + // `results.len() == targets.len()`. + unsafe { + hamming_batch_avx2(query, targets, results); + } + return; + } + } + + // Scalar fallback (LLVM auto-vectorizes well on Apple Silicon) + hamming_batch_scalar(query, targets, results); +} + +/// Scalar fallback using count_ones() which compiles to POPCNT. +#[inline] +fn hamming_batch_scalar(query: u64, targets: &[u64], results: &mut [u32]) { + // Unroll for better auto-vectorization + let n = targets.len(); + let chunks = n / 8; + let mut i = 0; + + for _ in 0..chunks { + results[i] = (query ^ targets[i]).count_ones(); + results[i + 1] = (query ^ targets[i + 1]).count_ones(); + results[i + 2] = (query ^ targets[i + 2]).count_ones(); + results[i + 3] = (query ^ targets[i + 3]).count_ones(); + results[i + 4] = (query ^ targets[i + 4]).count_ones(); + results[i + 5] = (query ^ targets[i + 5]).count_ones(); + results[i + 6] = (query ^ targets[i + 6]).count_ones(); + results[i + 7] = (query ^ targets[i + 7]).count_ones(); + i += 8; + } + + // Handle remainder + while i < n { + results[i] = (query ^ targets[i]).count_ones(); + i += 1; + } +} + +/// AVX-512 VPOPCNTDQ: Process 8 x 64-bit values at once. +/// +/// The chunk loop reaches only the first `targets.len() / 8 * 8` slots through a +/// raw pointer, 8 x u32 per chunk with no bounds check; the trailing slots go +/// through bounds-checked indexing. +/// +/// # Safety +/// +/// The host must support AVX-512F and AVX512VPOPCNTDQ, and `results.len()` must +/// be at least `targets.len()`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f", enable = "avx512vpopcntdq")] +unsafe fn hamming_batch_avx512(query: u64, targets: &[u64], results: &mut [u32]) { + use std::arch::x86_64::*; + + let n = targets.len(); + let query_vec = _mm512_set1_epi64(query as i64); + + let chunks = n / 8; + let remainder = n % 8; + + for i in 0..chunks { + let offset = i * 8; + let targets_ptr = targets.as_ptr().add(offset) as *const __m512i; + let target_vec = _mm512_loadu_si512(targets_ptr); + + let xor_result = _mm512_xor_si512(query_vec, target_vec); + let popcount = _mm512_popcnt_epi64(xor_result); + let popcount_32 = _mm512_cvtepi64_epi32(popcount); + + _mm256_storeu_si256( + results.as_mut_ptr().add(offset) as *mut __m256i, + popcount_32, + ); + } + + if remainder > 0 { + let offset = chunks * 8; + for j in 0..remainder { + results[offset + j] = (query ^ targets[offset + j]).count_ones(); + } + } +} + +/// AVX2 popcount using a PSHUFB nibble lookup table. +/// +/// The chunk loop reaches only the first `targets.len() / 4 * 4` slots through a +/// raw pointer, 4 x u32 per chunk with no bounds check; the trailing slots go +/// through bounds-checked indexing. +/// +/// # Safety +/// +/// The host must support AVX2, and `results.len()` must be at least +/// `targets.len()`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn hamming_batch_avx2(query: u64, targets: &[u64], results: &mut [u32]) { + use std::arch::x86_64::*; + + let n = targets.len(); + + let lookup = _mm256_setr_epi8( + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, + 3, 4, + ); + let low_mask = _mm256_set1_epi8(0x0f); + let query_vec = _mm256_set1_epi64x(query as i64); + + let chunks = n / 4; + let remainder = n % 4; + + for i in 0..chunks { + let offset = i * 4; + let targets_ptr = targets.as_ptr().add(offset) as *const __m256i; + let target_vec = _mm256_loadu_si256(targets_ptr); + + let xor_result = _mm256_xor_si256(query_vec, target_vec); + + // Popcount using nibble lookup + let lo = _mm256_and_si256(xor_result, low_mask); + let hi = _mm256_and_si256(_mm256_srli_epi16(xor_result, 4), low_mask); + let popcnt_lo = _mm256_shuffle_epi8(lookup, lo); + let popcnt_hi = _mm256_shuffle_epi8(lookup, hi); + let popcnt_bytes = _mm256_add_epi8(popcnt_lo, popcnt_hi); + let popcount = _mm256_sad_epu8(popcnt_bytes, _mm256_setzero_si256()); + + let results_ptr = results.as_mut_ptr().add(offset); + *results_ptr = _mm256_extract_epi32::<0>(popcount) as u32; + *results_ptr.add(1) = _mm256_extract_epi32::<2>(popcount) as u32; + *results_ptr.add(2) = _mm256_extract_epi32::<4>(popcount) as u32; + *results_ptr.add(3) = _mm256_extract_epi32::<6>(popcount) as u32; + } + + if remainder > 0 { + let offset = chunks * 4; + for j in 0..remainder { + results[offset + j] = (query ^ targets[offset + j]).count_ones(); + } + } +} + +/// Compute pairwise hamming distances for all pairs of hashes. +/// +/// Returns pairs where distance <= threshold (if provided). +/// +/// # Arguments +/// * `hashes` - Vector of 64-bit hash values +/// * `row_ids` - Optional row IDs (defaults to indices if None) +/// * `threshold` - Optional maximum distance to include in results +pub fn pairwise_hamming_distance( + hashes: &[u64], + row_ids: Option<&[u64]>, + threshold: Option, +) -> PairwiseResult { + let n = hashes.len(); + if n < 2 { + return PairwiseResult::new(); + } + + let threshold = threshold.unwrap_or(u32::MAX); + let num_pairs = n * (n - 1) / 2; + let mut result = PairwiseResult::with_capacity(num_pairs.min(1_000_000)); + + for i in 0..n { + for j in (i + 1)..n { + let dist = hamming_u64(hashes[i], hashes[j]); + if dist <= threshold { + let id_a = row_ids.map_or(i as u64, |ids| ids[i]); + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + } + } + } + + result +} + +/// Compute pairwise hamming distances in parallel using rayon + SIMD. +/// +/// Uses chunked parallelization for balanced workload distribution. +pub fn pairwise_hamming_distance_parallel( + hashes: &[u64], + row_ids: Option<&[u64]>, + threshold: Option, +) -> PairwiseResult { + let n = hashes.len(); + if n < 2 { + return PairwiseResult::new(); + } + + let threshold = threshold.unwrap_or(u32::MAX); + let total_pairs = n * (n - 1) / 2; + + // For small datasets, use sequential to avoid thread overhead + if total_pairs < 10_000 { + return pairwise_hamming_distance(hashes, row_ids, Some(threshold)); + } + + let threads = rayon::current_num_threads(); + let pairs_per_chunk = total_pairs.div_ceil(threads); + let chunks = compute_balanced_chunks(n, pairs_per_chunk); + + let results: Vec = chunks + .into_par_iter() + .map(|(start_row, end_row)| { + process_row_range(hashes, row_ids, threshold, start_row, end_row) + }) + .collect(); + + let mut combined = PairwiseResult::new(); + for r in results { + combined.extend(r); + } + combined +} + +/// Compute pairwise hamming distances for all pairs of fixed-width binary hashes. +/// +/// This supports any hash width that is a positive multiple of 8 bytes. For +/// 8-byte hashes this delegates to the existing `u64` implementation. +pub fn pairwise_hamming_distance_binary( + hashes: &BinaryHashValues, + row_ids: Option<&[u64]>, + threshold: Option, +) -> PairwiseResult { + let n = hashes.len(); + if n < 2 { + return PairwiseResult::new(); + } + + if hashes.num_lanes() == 1 { + return pairwise_hamming_distance(hashes.lane(0), row_ids, threshold); + } + + let threshold = threshold.unwrap_or(u32::MAX); + let num_pairs = n * (n - 1) / 2; + let mut result = PairwiseResult::with_capacity(num_pairs.min(1_000_000)); + + for i in 0..n { + for j in (i + 1)..n { + let mut dist = 0; + for lane in 0..hashes.num_lanes() { + let lane_values = hashes.lane(lane); + dist += hamming_u64(lane_values[i], lane_values[j]); + } + if dist <= threshold { + let id_a = row_ids.map_or(i as u64, |ids| ids[i]); + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + } + } + } + + result +} + +/// Compute pairwise hamming distances in parallel for fixed-width binary hashes. +/// +/// Wider hashes reuse the SIMD `u64` batch implementation lane-by-lane. +pub fn pairwise_hamming_distance_binary_parallel( + hashes: &BinaryHashValues, + row_ids: Option<&[u64]>, + threshold: Option, +) -> PairwiseResult { + let n = hashes.len(); + if n < 2 { + return PairwiseResult::new(); + } + + if hashes.num_lanes() == 1 { + return pairwise_hamming_distance_parallel(hashes.lane(0), row_ids, threshold); + } + + let threshold = threshold.unwrap_or(u32::MAX); + let total_pairs = n * (n - 1) / 2; + + if total_pairs < 10_000 { + return pairwise_hamming_distance_binary(hashes, row_ids, Some(threshold)); + } + + let threads = rayon::current_num_threads(); + let pairs_per_chunk = total_pairs.div_ceil(threads); + let chunks = compute_balanced_chunks(n, pairs_per_chunk); + + let results: Vec = chunks + .into_par_iter() + .map(|(start_row, end_row)| { + process_row_range_binary(hashes, row_ids, threshold, start_row, end_row) + }) + .collect(); + + let mut combined = PairwiseResult::new(); + for r in results { + combined.extend(r); + } + combined +} + +/// Compute balanced chunks for parallel processing. +fn compute_balanced_chunks(n: usize, target_pairs_per_chunk: usize) -> Vec<(usize, usize)> { + let mut chunks = Vec::new(); + let mut current_start = 0; + let mut current_pairs = 0; + + for i in 0..n { + let pairs_for_row = n - i - 1; + current_pairs += pairs_for_row; + + if current_pairs >= target_pairs_per_chunk || i == n - 1 { + chunks.push((current_start, i + 1)); + current_start = i + 1; + current_pairs = 0; + } + } + + chunks +} + +/// Process a range of rows for pairwise comparison using SIMD. +fn process_row_range( + hashes: &[u64], + row_ids: Option<&[u64]>, + threshold: u32, + start_row: usize, + end_row: usize, +) -> PairwiseResult { + let n = hashes.len(); + let mut result = PairwiseResult::new(); + + for i in start_row..end_row { + let remaining = n - i - 1; + if remaining == 0 { + continue; + } + + let mut distances = vec![0u32; remaining]; + hamming_batch_u64(hashes[i], &hashes[i + 1..], &mut distances); + + let id_a = row_ids.map_or(i as u64, |ids| ids[i]); + for (j_offset, &dist) in distances.iter().enumerate() { + if dist <= threshold { + let j = i + 1 + j_offset; + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + } + } + } + + result +} + +/// Process a range of rows for pairwise comparison of wider binary hashes. +fn process_row_range_binary( + hashes: &BinaryHashValues, + row_ids: Option<&[u64]>, + threshold: u32, + start_row: usize, + end_row: usize, +) -> PairwiseResult { + let n = hashes.len(); + let mut result = PairwiseResult::new(); + let mut distances = Vec::new(); + let mut lane_distances = Vec::new(); + + for i in start_row..end_row { + let remaining = n - i - 1; + if remaining == 0 { + continue; + } + + distances.clear(); + distances.resize(remaining, 0); + + let first_lane = hashes.lane(0); + hamming_batch_u64( + first_lane[i], + &first_lane[i + 1..], + distances.as_mut_slice(), + ); + + for lane in 1..hashes.num_lanes() { + lane_distances.clear(); + lane_distances.resize(remaining, 0); + let lane_values = hashes.lane(lane); + hamming_batch_u64( + lane_values[i], + &lane_values[i + 1..], + lane_distances.as_mut_slice(), + ); + for (distance, lane_distance) in distances.iter_mut().zip(&lane_distances) { + *distance += *lane_distance; + } + } + + let id_a = row_ids.map_or(i as u64, |ids| ids[i]); + for (j_offset, &dist) in distances.iter().enumerate() { + if dist <= threshold { + let j = i + 1 + j_offset; + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + } + } + } + + result +} + +/// Extract u64 hashes from a FixedSizeList Arrow array. +pub fn extract_hashes_from_fixed_list(array: &FixedSizeListArray) -> Result> { + let hashes = extract_binary_hashes_from_fixed_list(array)?; + if hashes.byte_width() != 8 { + return Err(Error::InvalidArgumentError(format!( + "Expected FixedSizeList with size 8, got size {}", + hashes.byte_width() + ))); + } + hashes.into_u64_values() +} + +/// Extract binary hashes from a `FixedSizeList` Arrow array where +/// `N` is a positive multiple of 8 bytes. +pub fn extract_binary_hashes_from_fixed_list( + array: &FixedSizeListArray, +) -> Result { + BinaryHashValues::from_fixed_size_list(array) +} + +/// Union-Find data structure with path compression for clustering. +pub struct UnionFind { + parent: HashMap, + rank: HashMap, +} + +impl UnionFind { + pub fn new() -> Self { + Self { + parent: HashMap::new(), + rank: HashMap::new(), + } + } + + pub fn with_capacity(capacity: usize) -> Self { + Self { + parent: HashMap::with_capacity(capacity), + rank: HashMap::with_capacity(capacity), + } + } + + /// Find the root of a node with path compression. + pub fn find(&mut self, x: u64) -> u64 { + if let std::collections::hash_map::Entry::Vacant(e) = self.parent.entry(x) { + e.insert(x); + self.rank.insert(x, 0); + return x; + } + + let mut current = x; + let mut path = Vec::new(); + + while self.parent[¤t] != current { + path.push(current); + current = self.parent[¤t]; + } + let root = current; + + for node in path { + self.parent.insert(node, root); + } + + root + } + + /// Union two nodes, using union by rank. + pub fn union(&mut self, a: u64, b: u64) -> bool { + let root_a = self.find(a); + let root_b = self.find(b); + + if root_a == root_b { + return false; + } + + let rank_a = self.rank[&root_a]; + let rank_b = self.rank[&root_b]; + + if rank_a < rank_b { + self.parent.insert(root_a, root_b); + } else if rank_a > rank_b { + self.parent.insert(root_b, root_a); + } else if root_a < root_b { + self.parent.insert(root_b, root_a); + *self.rank.get_mut(&root_a).unwrap() += 1; + } else { + self.parent.insert(root_a, root_b); + *self.rank.get_mut(&root_b).unwrap() += 1; + } + + true + } + + pub fn nodes(&self) -> impl Iterator { + self.parent.keys() + } + + pub fn len(&self) -> usize { + self.parent.len() + } + + pub fn is_empty(&self) -> bool { + self.parent.is_empty() + } +} + +impl Default for UnionFind { + fn default() -> Self { + Self::new() + } +} + +/// A cluster with representative and duplicates. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cluster { + /// The representative row ID (smallest in the cluster). + pub representative: u64, + /// List of duplicate row IDs (excludes the representative). + pub duplicates: Vec, +} + +impl Cluster { + pub fn size(&self) -> usize { + 1 + self.duplicates.len() + } +} + +/// Result of the clustering operation. +#[derive(Debug, Clone)] +pub struct ClusteringResult { + /// List of clusters, each with a representative and duplicates. + pub clusters: Vec, +} + +impl ClusteringResult { + pub fn num_clusters(&self) -> usize { + self.clusters.len() + } + + pub fn num_duplicates(&self) -> usize { + self.clusters.iter().map(|c| c.duplicates.len()).sum() + } + + pub fn num_unique(&self) -> usize { + self.clusters.len() + } + + /// Get the schema for clustering result batches. + pub fn schema() -> SchemaRef { + CLUSTER_SCHEMA.clone() + } + + /// Convert to Arrow RecordBatch with columns: + /// - `representative`: `UInt64` + /// - `duplicates`: `List` + pub fn to_record_batch(&self) -> RecordBatch { + let schema = Self::schema(); + + let mut representatives = Vec::with_capacity(self.clusters.len()); + let mut duplicates_builder = ListBuilder::new(UInt64Builder::new()); + + for cluster in &self.clusters { + representatives.push(cluster.representative); + for &dup in &cluster.duplicates { + duplicates_builder.values().append_value(dup); + } + duplicates_builder.append(true); + } + + let representative_array: ArrayRef = Arc::new(UInt64Array::from(representatives)); + let duplicates_array: ArrayRef = Arc::new(duplicates_builder.finish()); + + RecordBatch::try_new(schema, vec![representative_array, duplicates_array]) + .expect("Failed to create RecordBatch") + } + + /// Convert to a RecordBatchReader that yields batches of the specified size. + /// + /// # Arguments + /// * `batch_size` - Number of clusters per batch (default: 10000) + pub fn into_reader(self, batch_size: Option) -> Box { + let batch_size = batch_size.unwrap_or(10_000); + let schema = Self::schema(); + + if self.clusters.is_empty() { + // Return empty reader + let batches: Vec> = vec![]; + return Box::new(RecordBatchIterator::new(batches, schema)); + } + + let batches: Vec> = self + .clusters + .chunks(batch_size) + .map(|chunk| { + let mut representatives = Vec::with_capacity(chunk.len()); + let mut duplicates_builder = ListBuilder::new(UInt64Builder::new()); + + for cluster in chunk { + representatives.push(cluster.representative); + for &dup in &cluster.duplicates { + duplicates_builder.values().append_value(dup); + } + duplicates_builder.append(true); + } + + let representative_array: ArrayRef = Arc::new(UInt64Array::from(representatives)); + let duplicates_array: ArrayRef = Arc::new(duplicates_builder.finish()); + + RecordBatch::try_new(Self::schema(), vec![representative_array, duplicates_array]) + }) + .collect(); + + Box::new(RecordBatchIterator::new(batches, schema)) + } +} + +/// Cluster edges using union-find algorithm. +/// +/// Takes a list of edges (row_id_a, row_id_b) and groups connected nodes +/// into clusters. Each cluster has a representative (smallest row ID) +/// and a list of duplicates. +pub fn cluster_edges(edges: I) -> ClusteringResult +where + I: IntoIterator, +{ + let mut uf = UnionFind::new(); + + for (a, b) in edges { + uf.union(a, b); + } + + let mut clusters_map: HashMap> = HashMap::new(); + let nodes: Vec = uf.nodes().copied().collect(); + + for node in nodes { + let root = uf.find(node); + clusters_map.entry(root).or_default().push(node); + } + + let mut clusters = Vec::new(); + for (_root, mut members) in clusters_map { + members.sort_unstable(); + + if members.len() > 1 { + let representative = *members.iter().min().unwrap(); + let duplicates: Vec = members + .into_iter() + .filter(|&m| m != representative) + .collect(); + + clusters.push(Cluster { + representative, + duplicates, + }); + } + } + + clusters.sort_by_key(|c| c.representative); + + ClusteringResult { clusters } +} + +/// Cluster edges from PairwiseResult. +pub fn cluster_pairwise_result(result: &PairwiseResult) -> ClusteringResult { + let edges = result + .row_id_a + .iter() + .zip(result.row_id_b.iter()) + .map(|(&a, &b)| (a, b)); + + cluster_edges(edges) +} + +#[cfg(test)] +mod tests { + use super::*; + use lance_arrow::FixedSizeListArrayExt; + use rstest::rstest; + + #[test] + fn test_result_schemas_are_initialized_once() { + // These schemas are handed out per call and per batch, so they are + // shared rather than rebuilt. Pointer equality is what distinguishes a + // shared schema from an equal-but-freshly-allocated one. + assert!(Arc::ptr_eq( + &ClusteringResult::schema(), + &ClusteringResult::schema() + )); + + let batch = PairwiseResult::default().into_record_batch(); + assert!(Arc::ptr_eq(&batch.schema(), &DISTANCE_PAIR_SCHEMA)); + } + + #[test] + fn test_hamming() { + let x = vec![0b1101_1010, 0b1010_1010, 0b1010_1010]; + let y = vec![0b1101_1010, 0b1010_1010, 0b1010_1010]; + assert_eq!(hamming(&x, &y), 0.0); + + let y = vec![0b1101_1010, 0b1010_1010, 0b1010_1000]; + assert_eq!(hamming(&x, &y), 1.0); + + let y = vec![0b1101_1010, 0b1010_1010, 0b1010_1001]; + assert_eq!(hamming(&x, &y), 2.0); + } + + #[test] + #[should_panic( + expected = "distance batch length must be divisible by dimension: batch=5, dimension=2" + )] + fn test_hamming_distance_batch_rejects_partial_vector() { + let query = [0, 0]; + let targets = [u8::MAX, u8::MAX, 0, 1, 0]; + + let _ = hamming_distance_batch(&query, &targets, query.len()); + } + + #[test] + fn test_hamming_u64() { + assert_eq!(hamming_u64(0, 0), 0); + assert_eq!(hamming_u64(0, 1), 1); + assert_eq!(hamming_u64(0b1111, 0b0000), 4); + assert_eq!(hamming_u64(u64::MAX, 0), 64); + assert_eq!(hamming_u64(0xAAAAAAAAAAAAAAAA, 0x5555555555555555), 64); + } + + /// Runs `kernel` over `n` targets, with 8 guard slots past the output it is + /// handed, then checks every value and every guard. + /// + /// 8 is the widest unchecked chunk store in the file, so an unchecked chunk + /// store that overruns by one chunk lands inside this allocation instead of + /// past it. The remainder loops cannot trip the guards at all: all three + /// index through bounds-checked `results[..]` and would panic instead. + fn check_kernel_tail(n: usize, kernel: impl FnOnce(u64, &[u64], &mut [u32])) { + const GUARD: u32 = u32::MAX; + const GUARD_SLOTS: usize = 8; + let query = 0xDEAD_BEEF_CAFE_F00D_u64; + let targets: Vec = (0..n as u64) + .map(|i| i.wrapping_mul(0x9E37_79B9_7F4A_7C15)) + .collect(); + let mut results = vec![GUARD; n + GUARD_SLOTS]; + + kernel(query, &targets, &mut results[..n]); + + for (slot, &target) in targets.iter().enumerate() { + assert_eq!( + results[slot], + (query ^ target).count_ones(), + "n={n}, slot {slot}" + ); + } + for (slot, &guard) in results.iter().enumerate().skip(n) { + assert_eq!(guard, GUARD, "n={n}: wrote past results, at {slot}"); + } + } + + /// Each kernel behind `hamming_batch_u64` takes a fixed number of targets per + /// chunk and finishes the rest in a remainder loop: 4 for + /// `hamming_batch_avx2`, 8 for `hamming_batch_avx512` and for the unrolled + /// scalar fallback. + /// + /// The pairwise tests reach a remainder loop only when they are large enough + /// to take a parallel path. There the row ranges together pass every width + /// from one below the row count down to 1, so whichever kernel the host + /// dispatches has every residue covered incidentally, and a dropped or + /// out-of-bounds tail write surfaces somewhere in thousands of pairs, as a + /// mismatch or a panic. This asserts every slot at each width instead. + #[rstest] + #[case::one(1)] + #[case::two(2)] + #[case::three(3)] + #[case::four(4)] + #[case::five(5)] + #[case::six(6)] + #[case::seven(7)] + #[case::eight(8)] + #[case::nine(9)] + #[case::fifteen(15)] + #[case::sixteen(16)] + #[case::seventeen(17)] + #[case::one_hundred_twenty_eight(128)] + fn test_hamming_batch_u64(#[case] n: usize) { + check_kernel_tail(n, hamming_batch_u64); + // Also directly, because an x86_64 host with AVX2 takes an earlier branch + // and never reaches the scalar kernel through the dispatcher. + check_kernel_tail(n, hamming_batch_scalar); + } + + #[rstest] + // Fewer slots than targets is the case that used to write out of bounds: on a + // host that takes the AVX2 path, `hamming_batch_avx2` wrote 28 bytes past a + // one-slot `results`. + #[case::eight_targets_one_slot(8, 1)] + // On the same path this one overran by 4 bytes instead of 28. + #[case::eight_targets_seven_slots(8, 7)] + // More slots than targets left the tail unwritten rather than overrunning, but + // the contract is one slot per target either way. This and the zero-target case + // below are the two that catch a guard weakened to a one-sided + // `results.len() >= targets.len()`. + #[case::eight_targets_nine_slots(8, 9)] + // The target count varies too, so that the two shortcuts most likely to appear + // here cannot slip past every case: an `if targets.is_empty() { return; }` above + // the check, or a `targets.len() < 8` fast path, would otherwise leave every + // eight-target case green. Four is the smallest target count that still reaches + // the AVX2 chunk loop. + #[case::four_targets_one_slot(4, 1)] + #[case::no_targets_one_slot(0, 1)] + // Zero slots is the case with no in-bounds slot at all, and the only one here + // that a `results.is_empty()` early return above the check would not survive. + // Its sentinel assertion is vacuous, so it pins the message and nothing else. + #[case::eight_targets_no_slots(8, 0)] + fn test_hamming_batch_u64_rejects_mismatched_lengths( + #[case] num_targets: usize, + #[case] num_slots: usize, + ) { + // No CPU feature gate: the length check precedes every kernel, so the panic + // happens on each host and no case reaches a kernel at all. Every case here is + // a mismatch; matching lengths are covered by `test_hamming_batch_u64` above, + // which calls `hamming_batch_u64` directly, and by + // `test_pairwise_correctness_1000_deterministic` below, which reaches it + // through `pairwise_hamming_distance_parallel`'s chunked path and checks the + // result against `reference_pairwise`. + // + // `catch_unwind` rather than `#[should_panic]`, because the property worth + // protecting is that the check runs before the dispatch, and + // `#[should_panic]` cannot observe order: a check moved below it can still + // panic with this same message, after a kernel has already written through + // `results`. The sentinel assertion at the end is what rules that out. It is + // also why the nine-slot case is here: a kernel's writes all land in bounds + // there, so nothing else would notice that it ran. + // + // A `debug_assert_eq!` carrying the same message still passes here when + // debug assertions are on, which is the profile `--profile ci` gives this + // crate; `cargo test --release -p lance-linalg --lib` (rust.yml) is what + // catches that revert. + const SENTINEL: u32 = 0xDEAD_BEEF; + let targets = vec![u64::MAX; num_targets]; + let mut results = vec![SENTINEL; num_slots]; + + let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + hamming_batch_u64(0, &targets, &mut results); + })) + .expect_err("a length mismatch must panic"); + + let message = payload + .downcast_ref::() + .map(String::as_str) + .or_else(|| payload.downcast_ref::<&'static str>().copied()) + .expect("panic payload should be a string"); + // Matching the whole message, not the two numbers separately, is deliberate: + // it pins the function name and the order the two lengths are reported in, + // which is what a message copied from a sibling guard would get wrong. + let expected = format!( + "hamming_batch_u64 needs one result slot per target, \ + got {num_targets} target(s) and {num_slots} slot(s)" + ); + assert!( + message.contains(&expected), + "expected {expected:?} in panic message, got {message:?}" + ); + assert_eq!( + results.iter().position(|&slot| slot != SENTINEL), + None, + "a kernel reached `results`, so the length check no longer precedes it" + ); + } + + #[test] + fn test_pairwise_basic() { + let hashes = vec![0b0000u64, 0b0001, 0b0011, 0b0111]; + let result = pairwise_hamming_distance(&hashes, None, None); + + assert_eq!(result.len(), 6); // C(4,2) = 6 pairs + assert!(result.distances.iter().all(|&d| d <= 3)); + } + + #[test] + fn test_pairwise_with_threshold() { + let hashes = vec![0b0000u64, 0b0001, 0b1111]; + let result = pairwise_hamming_distance(&hashes, None, Some(1)); + + assert_eq!(result.len(), 1); + assert_eq!(result.row_id_a[0], 0); + assert_eq!(result.row_id_b[0], 1); + assert_eq!(result.distances[0], 1); + } + + #[test] + fn test_pairwise_with_row_ids() { + let hashes = vec![0b0000u64, 0b0001]; + let row_ids = vec![100u64, 200u64]; + let result = pairwise_hamming_distance(&hashes, Some(&row_ids), None); + + assert_eq!(result.len(), 1); + assert_eq!(result.row_id_a[0], 100); + assert_eq!(result.row_id_b[0], 200); + } + + #[test] + fn test_pairwise_parallel() { + let hashes: Vec = (0..100).collect(); + let result_seq = pairwise_hamming_distance(&hashes, None, None); + let result_par = pairwise_hamming_distance_parallel(&hashes, None, None); + + assert_eq!(result_seq.len(), result_par.len()); + } + + #[test] + fn test_union_find_basic() { + let mut uf = UnionFind::new(); + + assert_eq!(uf.find(1), 1); + assert_eq!(uf.find(2), 2); + assert_eq!(uf.find(3), 3); + + assert!(uf.union(1, 2)); + assert_eq!(uf.find(1), uf.find(2)); + + assert!(uf.union(2, 3)); + assert_eq!(uf.find(1), uf.find(3)); + + assert!(!uf.union(1, 3)); + } + + #[test] + fn test_cluster_edges_simple() { + let edges = vec![(1, 2), (2, 3), (4, 5)]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 2); + + let c1 = result + .clusters + .iter() + .find(|c| c.representative == 1) + .unwrap(); + assert_eq!(c1.duplicates.len(), 2); + assert!(c1.duplicates.contains(&2)); + assert!(c1.duplicates.contains(&3)); + + let c2 = result + .clusters + .iter() + .find(|c| c.representative == 4) + .unwrap(); + assert_eq!(c2.duplicates.len(), 1); + assert!(c2.duplicates.contains(&5)); + } + + #[test] + fn test_cluster_pairwise_result() { + let hashes = vec![0b0000u64, 0b0001, 0b0011]; // distances: (0,1)=1, (0,2)=2, (1,2)=1 + let pairwise = pairwise_hamming_distance(&hashes, None, Some(1)); // threshold 1 + + // Only pairs with distance <= 1: (0,1) and (1,2) + assert_eq!(pairwise.len(), 2); + + let clustering = cluster_pairwise_result(&pairwise); + // All three should be in one cluster since 0-1-2 are connected + assert_eq!(clustering.num_clusters(), 1); + assert_eq!(clustering.clusters[0].representative, 0); + assert_eq!(clustering.clusters[0].duplicates.len(), 2); + } + + #[test] + fn test_into_record_batch() { + let hashes = vec![0b0000u64, 0b0001, 0b0011]; + let result = pairwise_hamming_distance(&hashes, None, None); + let batch = result.into_record_batch(); + + assert_eq!(batch.num_rows(), 3); + assert_eq!(batch.num_columns(), 3); + assert_eq!(batch.schema().field(0).name(), "row_id_a"); + assert_eq!(batch.schema().field(1).name(), "row_id_b"); + assert_eq!(batch.schema().field(2).name(), "distance"); + } + + // ========================================================================= + // Additional tests from pairwise-hamming reference implementation + // ========================================================================= + + /// Reference implementation for validation - simple O(n²) nested loop + fn reference_pairwise(hashes: &[u64], threshold: Option) -> Vec<(usize, usize, u32)> { + let threshold = threshold.unwrap_or(u32::MAX); + let mut results = Vec::new(); + for i in 0..hashes.len() { + for j in (i + 1)..hashes.len() { + let dist = (hashes[i] ^ hashes[j]).count_ones(); + if dist <= threshold { + results.push((i, j, dist)); + } + } + } + results + } + + /// Convert PairwiseResult to sorted vec for comparison + fn result_to_sorted_vec(result: &PairwiseResult) -> Vec<(u64, u64, u32)> { + let mut v: Vec<_> = result + .row_id_a + .iter() + .zip(result.row_id_b.iter()) + .zip(result.distances.iter()) + .map(|((&a, &b), &d)| (a, b, d)) + .collect(); + v.sort(); + v + } + + #[test] + fn test_extract_binary_hashes_from_fixed_list_128() { + use arrow_array::UInt8Array; + + let rows = [ + (0x0102_0304_0506_0708u64, 0x1112_1314_1516_1718u64), + (0x2122_2324_2526_2728u64, 0x3132_3334_3536_3738u64), + ]; + let bytes: Vec = rows + .iter() + .flat_map(|(lo, hi)| lo.to_le_bytes().into_iter().chain(hi.to_le_bytes())) + .collect(); + let array = FixedSizeListArray::try_new_from_values(UInt8Array::from(bytes), 16).unwrap(); + + let hashes = extract_binary_hashes_from_fixed_list(&array).unwrap(); + assert_eq!(hashes.len(), 2); + assert_eq!(hashes.byte_width(), 16); + assert_eq!(hashes.num_lanes(), 2); + assert_eq!(hashes.lane(0), &[rows[0].0, rows[1].0]); + assert_eq!(hashes.lane(1), &[rows[0].1, rows[1].1]); + } + + #[test] + fn test_extract_binary_hashes_rejects_non_u64_multiple() { + use arrow_array::UInt8Array; + + let array = + FixedSizeListArray::try_new_from_values(UInt8Array::from(vec![0u8; 24]), 12).unwrap(); + let err = extract_binary_hashes_from_fixed_list(&array).unwrap_err(); + assert!(err.to_string().contains("multiple of 8 bytes"), "{}", err); + } + + #[test] + fn test_binary_hash_values_rejects_width_not_divisible_by_8() { + let err = BinaryHashValues::try_new(Vec::new(), 0, 12).unwrap_err(); + assert!(err.to_string().contains("multiple of 8 bytes"), "{}", err); + } + + #[test] + fn test_pairwise_binary_hashes_128() { + let hashes = BinaryHashValues::try_new( + vec![ + 0, + 0, + 1, + u64::MAX, // lane 0 + 0, + 1, + 1, + u64::MAX, // lane 1 + ], + 4, + 16, + ) + .unwrap(); + + let seq = pairwise_hamming_distance_binary(&hashes, None, Some(1)); + let par = pairwise_hamming_distance_binary_parallel(&hashes, None, Some(1)); + let expected = vec![(0, 1, 1), (1, 2, 1)]; + assert_eq!(result_to_sorted_vec(&seq), expected); + assert_eq!(result_to_sorted_vec(&par), expected); + } + + #[test] + fn test_pairwise_binary_hashes_parallel_128_matches_sequential() { + let rows: Vec<(u64, u64)> = (0..80) + .flat_map(|i| { + let lo = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); + let hi = !lo.rotate_left(17); + [(lo, hi), (lo ^ 1, hi)] + }) + .collect(); + let mut lane_values = Vec::with_capacity(rows.len() * 2); + lane_values.extend(rows.iter().map(|(lo, _)| *lo)); + lane_values.extend(rows.iter().map(|(_, hi)| *hi)); + let hashes = BinaryHashValues::try_new(lane_values, rows.len(), 16).unwrap(); + let row_ids: Vec = (0..rows.len()).map(|i| 10_000 + i as u64).collect(); + + let seq = pairwise_hamming_distance_binary(&hashes, Some(&row_ids), Some(1)); + let par = pairwise_hamming_distance_binary_parallel(&hashes, Some(&row_ids), Some(1)); + + assert_eq!(result_to_sorted_vec(&par), result_to_sorted_vec(&seq)); + assert!(par.len() >= 80); + } + + #[test] + fn test_pairwise_binary_hashes_32_with_row_ids() { + let hashes = BinaryHashValues::try_new( + vec![ + 0, + 0, + 1, // lane 0 + 0, + 1, + 1, // lane 1 + 7, + 7, + 7, // lane 2 + u64::MAX, + u64::MAX, + u64::MAX - 1, // lane 3 + ], + 3, + 32, + ) + .unwrap(); + let row_ids = [10, 20, 30]; + + let result = pairwise_hamming_distance_binary_parallel(&hashes, Some(&row_ids), Some(2)); + assert_eq!( + result_to_sorted_vec(&result), + vec![(10, 20, 1), (20, 30, 2)] + ); + } + + #[test] + fn test_pairwise_correctness_small() { + // Deterministic hashes with known distances + let hashes = vec![ + 0b0000_0000u64, // 0 + 0b0000_0001u64, // 1 bit from 0 + 0b0000_0011u64, // 2 bits from 0, 1 bit from 1 + 0b0000_0111u64, // 3 bits from 0, 2 bits from 1, 1 bit from 2 + 0b0000_1111u64, // 4 bits from 0, 3 bits from 1, 2 bits from 2, 1 bit from 3 + ]; + + let result = pairwise_hamming_distance(&hashes, None, None); + let reference = reference_pairwise(&hashes, None); + + assert_eq!(result.len(), reference.len()); + assert_eq!(result.len(), 10); // C(5,2) = 10 pairs + + // Verify specific distances + let result_vec = result_to_sorted_vec(&result); + for (i, j, expected_dist) in &reference { + let found = result_vec + .iter() + .find(|(a, b, _)| *a == *i as u64 && *b == *j as u64); + assert!(found.is_some(), "Missing pair ({}, {})", i, j); + assert_eq!( + found.unwrap().2, + *expected_dist, + "Wrong distance for pair ({}, {})", + i, + j + ); + } + } + + #[test] + fn test_pairwise_correctness_1000_deterministic() { + // Generate deterministic hashes using simple linear pattern + let hashes: Vec = (0u64..1000) + .map(|i| i.wrapping_mul(0x123456789ABCDEF)) + .collect(); + + let result_seq = pairwise_hamming_distance(&hashes, None, Some(10)); + let result_par = pairwise_hamming_distance_parallel(&hashes, None, Some(10)); + let reference = reference_pairwise(&hashes, Some(10)); + + // Both implementations should match reference + assert_eq!( + result_seq.len(), + reference.len(), + "Sequential result count mismatch" + ); + assert_eq!( + result_par.len(), + reference.len(), + "Parallel result count mismatch" + ); + + // Verify all pairs match + let seq_sorted = result_to_sorted_vec(&result_seq); + let par_sorted = result_to_sorted_vec(&result_par); + + for (i, j, dist) in &reference { + let seq_found = seq_sorted + .iter() + .find(|(a, b, _)| *a == *i as u64 && *b == *j as u64); + let par_found = par_sorted + .iter() + .find(|(a, b, _)| *a == *i as u64 && *b == *j as u64); + + assert!( + seq_found.is_some(), + "Sequential missing pair ({}, {})", + i, + j + ); + assert!(par_found.is_some(), "Parallel missing pair ({}, {})", i, j); + assert_eq!(seq_found.unwrap().2, *dist); + assert_eq!(par_found.unwrap().2, *dist); + } + } + + #[test] + fn test_pairwise_correctness_10000_deterministic() { + // Larger test with 10K hashes + let hashes: Vec = (0u64..10_000) + .map(|i| { + // Mix bits using a simple hash-like transformation + let x = i.wrapping_mul(0xDEADBEEFCAFEBABE); + x ^ (x >> 17) ^ (x << 13) + }) + .collect(); + + let result_seq = pairwise_hamming_distance(&hashes, None, Some(5)); + let result_par = pairwise_hamming_distance_parallel(&hashes, None, Some(5)); + + // Both should find the same number of pairs + assert_eq!( + result_seq.len(), + result_par.len(), + "10K test: sequential found {} pairs, parallel found {} pairs", + result_seq.len(), + result_par.len() + ); + + // Verify they contain the same pairs (sorted comparison) + let seq_sorted = result_to_sorted_vec(&result_seq); + let par_sorted = result_to_sorted_vec(&result_par); + assert_eq!(seq_sorted, par_sorted, "10K test: pair contents differ"); + } + + #[test] + fn test_pairwise_total_pairs_count() { + // Without threshold, should return exactly n*(n-1)/2 pairs + for n in [10, 50, 100, 500] { + let hashes: Vec = (0..n).map(|i| i as u64).collect(); + let result = pairwise_hamming_distance_parallel(&hashes, None, None); + let expected = n * (n - 1) / 2; + assert_eq!( + result.len(), + expected, + "n={}: expected {} pairs, got {}", + n, + expected, + result.len() + ); + } + } + + #[test] + fn test_pairwise_threshold_filtering() { + // All identical hashes should have distance 0 + let hashes = vec![0xABCDEF0123456789u64; 100]; + let result = pairwise_hamming_distance_parallel(&hashes, None, Some(0)); + + // All pairs should be included (distance 0) + assert_eq!(result.len(), 100 * 99 / 2); + assert!(result.distances.iter().all(|&d| d == 0)); + + // With threshold 0 and all different hashes, should find fewer pairs + let different_hashes: Vec = (0u64..100).collect(); + let result2 = pairwise_hamming_distance_parallel(&different_hashes, None, Some(0)); + // Only pairs with identical values should match (none in this case except 0^0) + assert!(result2.len() < 100 * 99 / 2); + } + + #[test] + fn test_pairwise_row_ids_preserved() { + let hashes: Vec = (0u64..100).collect(); + let row_ids: Vec = (1000u64..1100).collect(); // offset row IDs + + let result = pairwise_hamming_distance_parallel(&hashes, Some(&row_ids), Some(5)); + + // All row IDs should be in range [1000, 1100) + for &id in &result.row_id_a { + assert!((1000..1100).contains(&id), "row_id_a {} out of range", id); + } + for &id in &result.row_id_b { + assert!((1000..1100).contains(&id), "row_id_b {} out of range", id); + } + // row_id_a should always be less than row_id_b (upper triangular) + for (&a, &b) in result.row_id_a.iter().zip(result.row_id_b.iter()) { + assert!(a < b, "Expected row_id_a < row_id_b, got {} >= {}", a, b); + } + } + + #[test] + fn test_pairwise_distance_bounds() { + // All distances should be in [0, 64] for u64 hashes + let hashes: Vec = (0u64..1000).map(|i| i.wrapping_mul(0x123456789)).collect(); + + let result = pairwise_hamming_distance_parallel(&hashes, None, None); + + for &d in &result.distances { + assert!(d <= 64, "Distance {} exceeds maximum 64", d); + } + } + + #[test] + fn test_pairwise_symmetry() { + // Hamming distance is symmetric: d(a,b) = d(b,a) + let hashes: Vec = vec![ + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0xAAAAAAAAAAAAAAAA, + 0x5555555555555555, + 0x123456789ABCDEF0, + ]; + + let result = pairwise_hamming_distance(&hashes, None, None); + + // For each pair (i,j), verify distance matches manual calculation + for idx in 0..result.len() { + let i = result.row_id_a[idx] as usize; + let j = result.row_id_b[idx] as usize; + let dist = result.distances[idx]; + + let expected = (hashes[i] ^ hashes[j]).count_ones(); + assert_eq!(dist, expected, "Distance mismatch for pair ({}, {})", i, j); + } + } + + #[test] + fn test_balanced_chunks() { + // Verify chunks are reasonably balanced + let n = 10000; + let total_pairs = n * (n - 1) / 2; + let target_per_chunk = total_pairs / 16; + + let chunks = compute_balanced_chunks(n, target_per_chunk); + + // Should have roughly 16 chunks + assert!( + chunks.len() >= 14 && chunks.len() <= 18, + "Expected ~16 chunks, got {}", + chunks.len() + ); + + // Each chunk should have roughly equal work + for (start, end) in &chunks { + let mut chunk_pairs = 0usize; + for i in *start..*end { + chunk_pairs += n - i - 1; + } + // Allow 20% deviation from target + let lower = target_per_chunk * 80 / 100; + // last chunk may be smaller + assert!( + chunk_pairs >= lower || *end == n, + "Chunk [{}, {}) has {} pairs, expected ~{}", + start, + end, + chunk_pairs, + target_per_chunk + ); + } + + // Chunks should cover all rows without gaps + assert_eq!(chunks[0].0, 0); + assert_eq!(chunks.last().unwrap().1, n); + for i in 1..chunks.len() { + assert_eq!(chunks[i].0, chunks[i - 1].1, "Gap between chunks"); + } + } + + // ========================================================================= + // SIMD-specific tests + // ========================================================================= + + // `hamming_batch_simd` returns early on the AVX-512 branch when + // `avx512vpopcntdq` and `avx512f` are both present, so on a host with both + // nothing reaches `hamming_batch_avx2` through `hamming_batch_u64`. This + // calls it directly. The AVX-512 kernel needs no such test: it only runs + // where the dispatched test already drives it. + + /// `hamming_batch_avx2` consumes 4 targets per chunk, so `n % 4` covers its + /// remainder loop. + #[rstest] + #[cfg(target_arch = "x86_64")] + #[case::one(1)] + #[case::two(2)] + #[case::three(3)] + #[case::four(4)] + // Five, six and seven repeat remainders 1 through 3 with a chunk ahead of + // them, which one, two and three alone do not reach. + #[case::five(5)] + #[case::six(6)] + #[case::seven(7)] + fn test_avx2_covers_tail(#[case] n: usize) { + if !is_x86_feature_detected!("avx2") { + return; + } + check_kernel_tail(n, |query, targets, results| { + // SAFETY: AVX2 was just detected, and `check_kernel_tail` passes a + // `results` of exactly `targets.len()`. + unsafe { hamming_batch_avx2(query, targets, results) } + }); + } + + #[test] + #[cfg(target_arch = "x86_64")] + fn test_avx2_popcount() { + if !is_x86_feature_detected!("avx2") { + return; + } + + let query = 0u64; + let targets = vec![0u64, 1, 3, 7, 15, 31, 63, 127]; + let mut results = vec![0u32; 8]; + + unsafe { + hamming_batch_avx2(query, &targets, &mut results); + } + + assert_eq!(results[0], 0); // 0 ^ 0 = 0 bits + assert_eq!(results[1], 1); // 0 ^ 1 = 1 bit + assert_eq!(results[2], 2); // 0 ^ 3 = 2 bits + assert_eq!(results[3], 3); // 0 ^ 7 = 3 bits + assert_eq!(results[4], 4); // 0 ^ 15 = 4 bits + assert_eq!(results[5], 5); // 0 ^ 31 = 5 bits + assert_eq!(results[6], 6); // 0 ^ 63 = 6 bits + assert_eq!(results[7], 7); // 0 ^ 127 = 7 bits + } + + #[test] + #[cfg(target_arch = "x86_64")] + fn test_avx2_max_distance() { + if !is_x86_feature_detected!("avx2") { + return; + } + + let query = 0u64; + let targets = vec![u64::MAX; 4]; + let mut results = vec![0u32; 4]; + + unsafe { + hamming_batch_avx2(query, &targets, &mut results); + } + + for &r in &results { + assert_eq!(r, 64); + } + } + + #[test] + #[cfg(target_arch = "x86_64")] + fn test_avx512_popcount() { + if !is_x86_feature_detected!("avx512vpopcntdq") || !is_x86_feature_detected!("avx512f") { + return; + } + + let query = 0u64; + let targets = vec![0u64, 1, 3, 7, 15, 31, 63, 127]; + let mut results = vec![0u32; 8]; + + unsafe { + hamming_batch_avx512(query, &targets, &mut results); + } + + assert_eq!(results[0], 0); + assert_eq!(results[1], 1); + assert_eq!(results[2], 2); + assert_eq!(results[3], 3); + assert_eq!(results[4], 4); + assert_eq!(results[5], 5); + assert_eq!(results[6], 6); + assert_eq!(results[7], 7); + } + + // ========================================================================= + // Additional clustering tests + // ========================================================================= + + #[test] + fn test_union_find_path_compression() { + let mut uf = UnionFind::new(); + + // Create a chain: 1 -> 2 -> 3 -> 4 -> 5 + uf.union(4, 5); + uf.union(3, 4); + uf.union(2, 3); + uf.union(1, 2); + + // All should have the same root + let root = uf.find(1); + assert_eq!(uf.find(2), root); + assert_eq!(uf.find(3), root); + assert_eq!(uf.find(4), root); + assert_eq!(uf.find(5), root); + } + + #[test] + fn test_cluster_edges_single_cluster() { + // All connected: 1-2-3-4-5 + let edges = vec![(1, 2), (2, 3), (3, 4), (4, 5)]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 1); + let cluster = &result.clusters[0]; + assert_eq!(cluster.representative, 1); + assert_eq!(cluster.duplicates.len(), 4); + assert_eq!(cluster.size(), 5); + } + + #[test] + fn test_cluster_edges_no_duplicates() { + // No edges means no clusters + let edges: Vec<(u64, u64)> = vec![]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 0); + assert_eq!(result.num_duplicates(), 0); + } + + #[test] + fn test_cluster_edges_self_loop() { + // Self-loop shouldn't create a cluster (size 1) + let edges = vec![(1, 1), (2, 3)]; + let result = cluster_edges(edges); + + // Only {2,3} should be a cluster + assert_eq!(result.num_clusters(), 1); + assert_eq!(result.clusters[0].representative, 2); + } + + #[test] + fn test_cluster_edges_duplicate_edges() { + // Duplicate edges should be handled correctly + let edges = vec![(1, 2), (1, 2), (2, 3), (2, 3), (3, 1)]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 1); + assert_eq!(result.clusters[0].size(), 3); + } + + #[test] + fn test_cluster_edges_large() { + // Create 100 clusters of size 10 each + let mut edges = Vec::new(); + for cluster_id in 0..100u64 { + let base = cluster_id * 10; + for i in 0..9 { + edges.push((base + i, base + i + 1)); + } + } + + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 100); + for cluster in &result.clusters { + assert_eq!(cluster.size(), 10); + assert_eq!(cluster.duplicates.len(), 9); + } + } + + #[test] + fn test_cluster_edges_random_order() { + // Same edges in different order should produce same result + let edges1 = vec![(1, 2), (2, 3), (4, 5), (3, 4)]; + let edges2 = vec![(4, 5), (1, 2), (3, 4), (2, 3)]; + let edges3 = vec![(3, 4), (4, 5), (2, 3), (1, 2)]; + + let r1 = cluster_edges(edges1); + let r2 = cluster_edges(edges2); + let r3 = cluster_edges(edges3); + + // All should produce the same single cluster + assert_eq!(r1.num_clusters(), 1); + assert_eq!(r2.num_clusters(), 1); + assert_eq!(r3.num_clusters(), 1); + + assert_eq!(r1.clusters[0].representative, 1); + assert_eq!(r2.clusters[0].representative, 1); + assert_eq!(r3.clusters[0].representative, 1); + + assert_eq!(r1.clusters[0].size(), 5); + assert_eq!(r2.clusters[0].size(), 5); + assert_eq!(r3.clusters[0].size(), 5); + } + + #[test] + fn test_cluster_edges_non_contiguous_ids() { + // Row IDs don't need to be contiguous + let edges = vec![(100, 200), (200, 500), (1000, 2000)]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 2); + + let c1 = result + .clusters + .iter() + .find(|c| c.representative == 100) + .unwrap(); + assert_eq!(c1.duplicates, vec![200, 500]); + + let c2 = result + .clusters + .iter() + .find(|c| c.representative == 1000) + .unwrap(); + assert_eq!(c2.duplicates, vec![2000]); + } + + #[test] + fn test_cluster_representative_is_minimum() { + // Representative should always be the minimum row ID in cluster + let edges = vec![ + (5, 3), + (3, 7), + (7, 1), // 1 is minimum + (100, 50), + (50, 75), // 50 is minimum + ]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 2); + + let c1 = result + .clusters + .iter() + .find(|c| c.duplicates.contains(&7)) + .unwrap(); + assert_eq!(c1.representative, 1); + + let c2 = result + .clusters + .iter() + .find(|c| c.duplicates.contains(&100)) + .unwrap(); + assert_eq!(c2.representative, 50); + } + + #[test] + fn test_cluster_duplicates_sorted() { + // Duplicates should be sorted + let edges = vec![(1, 5), (1, 3), (1, 7), (1, 2)]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 1); + assert_eq!(result.clusters[0].representative, 1); + assert_eq!(result.clusters[0].duplicates, vec![2, 3, 5, 7]); + } + + #[test] + fn test_clustering_result_stats() { + let edges = vec![ + (1, 2), + (2, 3), // cluster of 3 + (10, 20), + (20, 30), + (30, 40), // cluster of 4 + ]; + let result = cluster_edges(edges); + + assert_eq!(result.num_clusters(), 2); + assert_eq!(result.num_duplicates(), 5); // 2 + 3 + assert_eq!(result.num_unique(), 2); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs new file mode 100644 index 000000000..750524ec5 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs @@ -0,0 +1,1722 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! L2 (Euclidean) distance. +//! + +use std::iter::Sum; +use std::ops::AddAssign; +use std::sync::Arc; + +use crate::Result; +use argminmax::ArgMinMax; +use arrow_array::{Array, FixedSizeListArray, Float32Array}; +use half::{bf16, f16}; +use lance_core::deepsize::DeepSizeOf; +use lance_core::utils::cpu::SIMD_SUPPORT; +#[cfg(target_arch = "x86_64")] +use lance_core::utils::cpu::SimdSupport; +use num_traits::{AsPrimitive, Num}; + +use crate::distance::{ + BatchKernel, HALF_KERNELS_COMPILED, HalfBackend, HalfType, PairKernel, + U8_U32_ACCUMULATOR_MAX_LEN, assert_batch_output_layout, assert_equal_lengths, half_backend, + x86_half_features, +}; + +/// Calculate the L2 distance between two vectors. +/// +pub trait L2: Num { + /// Calculate the L2 distance between two vectors. + /// + /// # Panics + /// + /// The implementations in this crate panic if `x` and `y` have different + /// lengths. A downstream implementation may define different behavior. + fn l2(x: &[Self], y: &[Self]) -> f32; + + /// Writes the L2 distance from `x` to each `dimension`-sized vector in + /// `batch` into the matching element of `output`. + /// + /// The default calls [`L2::l2`] per vector. `f32` overrides it with one + /// batch kernel call and `f16` selects its backend once per batch, so + /// neither chooses a kernel per vector. `f64` picks its x86_64 SIMD tier + /// once per batch, and on other targets specializes the loop for the + /// common PQ sub-vector lengths. + /// + /// # Panics + /// + /// The default implementation panics if `dimension == 0`, if + /// `x.len() != dimension`, if `batch.len()` is not a multiple of + /// `dimension`, or if `output.len() != batch.len() / dimension`. + fn l2_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = Self::l2(x, y); + } + } +} + +/// Squared L2 distance between two vectors of any [`L2`] element type. +/// +/// # Panics +/// +/// The implementations in this crate panic if `from` and `to` have different +/// lengths. A downstream [`L2`] implementation may define different behavior. +#[inline] +pub fn l2(from: &[T], to: &[T]) -> f32 { + T::l2(from, to) +} + +/// L2 distance between two f32 slices, dispatched to the widest SIMD backend +/// available at runtime. +/// +/// On x86_64 with AVX-512 this uses 16-wide f32 lanes; otherwise it falls back +/// to [`l2`], whose x86_64 implementation selects the best runtime-supported +/// kernel. This entry point gives hot-path callers such as the in-memory HNSW +/// index an explicit f32 API. +/// +/// # Panics +/// +/// Panics if `x` and `y` have different lengths. +#[inline] +pub fn l2_f32(x: &[f32], y: &[f32]) -> f32 { + f32::l2(x, y) +} + +/// Calculate L2 distance between two uint8 slices. +/// +/// # Panics +/// +/// Panics if `key` and `target` have different lengths. +#[inline] +pub fn l2_distance_uint_scalar(key: &[u8], target: &[u8]) -> f32 { + assert_equal_lengths(key.len(), target.len()); + // Keep the common path on a u32 accumulator so LLVM can auto-vectorize it + // efficiently. Longer inputs are widened between overflow-safe chunks. + if key.len() <= U8_U32_ACCUMULATOR_MAX_LEN { + return key + .iter() + .zip(target.iter()) + .map(|(&x, &y)| (x.abs_diff(y) as u32).pow(2)) + .sum::() as f32; + } + + key.chunks(U8_U32_ACCUMULATOR_MAX_LEN) + .zip(target.chunks(U8_U32_ACCUMULATOR_MAX_LEN)) + .map(|(key, target)| { + key.iter() + .zip(target.iter()) + .map(|(&x, &y)| (x.abs_diff(y) as u32).pow(2)) + .sum::() as u64 + }) + .sum::() as f32 +} + +/// Calculate the L2 distance between two vectors, using scalar operations. +/// +/// It relies on LLVM for auto-vectorization and unrolling. +/// +/// This is pub for test/benchmark only. use [l2] instead. +/// +/// # Panics +/// +/// Panics if `from` and `to` have different lengths, and separately if `LANES` +/// is zero, which `as_chunks` rejects. +#[inline(always)] +pub fn l2_scalar< + T: AsPrimitive, + Output: Num + Copy + Sum + AddAssign + 'static, + const LANES: usize, +>( + from: &[T], + to: &[T], +) -> Output { + l2_scalar_mixed::(from, to) +} + +/// [`l2_scalar`] with differently typed inputs, so a caller can convert a +/// query once and reuse it across a batch. Converting to `Output` up front +/// gives the same values as converting inside the loop, so results match +/// [`l2_scalar`] on the unconverted inputs bit for bit. +#[inline(always)] +fn l2_scalar_mixed< + X: AsPrimitive, + Y: AsPrimitive, + Output: Num + Copy + Sum + AddAssign + 'static, + const LANES: usize, +>( + from: &[X], + to: &[Y], +) -> Output { + assert_equal_lengths(from.len(), to.len()); + let (x_chunks, x_remainder) = from.as_chunks::(); + let (y_chunks, y_remainder) = to.as_chunks::(); + + let s = if !x_remainder.is_empty() { + x_remainder + .iter() + .zip(y_remainder) + .map(|(&x, &y)| { + let diff = x.as_() - y.as_(); + diff * diff + }) + .sum::() + } else { + Output::zero() + }; + + let mut sums = [Output::zero(); LANES]; + for (x, y) in x_chunks.iter().zip(y_chunks) { + for i in 0..LANES { + let diff = x[i].as_() - y[i].as_(); + sums[i] += diff * diff; + } + } + + s + sums.iter().copied().sum() +} + +impl L2 for u8 { + #[inline] + fn l2(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + super::l2_u8::l2_u8_u64(x, y) as f32 + } +} + +#[cfg(feature = "fp16kernels")] +mod bf16_kernel { + use half::bf16; + + // These are the `l2_bf16` function in bf16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn l2_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))] + pub fn l2_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn l2_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn l2_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn l2_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32; + } +} + +impl L2 for bf16 { + #[inline] + fn l2(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + match half_backend( + *SIMD_SUPPORT, + HalfType::Bf16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + bf16_kernel::l2_bf16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_bf16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + bf16_kernel::l2_bf16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + bf16_kernel::l2_bf16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + bf16_kernel::l2_bf16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + bf16_kernel::l2_bf16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx fall through here: + // the bf16 C kernels are compiled with `-march=haswell` minimum + // (AVX2), so they cannot run on AVX-only or AVX+FMA hosts. + _ => l2_scalar::(x, y), + } + } +} + +#[cfg(feature = "fp16kernels")] +mod kernel { + use super::*; + + // These are the `l2_f16` function in f16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn l2_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))] + pub fn l2_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn l2_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn l2_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn l2_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32; + } +} + +fn f16_backend() -> HalfBackend { + half_backend( + *SIMD_SUPPORT, + HalfType::F16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")), + x86_half_features(), + ) +} + +impl L2 for f16 { + #[inline] + fn l2(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + l2_f16_with(f16_backend(), x, y) + } + + fn l2_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + // Selecting the backend reads several runtime feature flags, which + // costs as much as a dimension-8 distance, so select it once per batch. + // The scalar backend converts the query to f32 once, instead of once + // per vector, and gets its own loop so the scalar kernel inlines. + // Interim: f16 still selects through `half_backend`, not `Dispatch`; + // it moves onto `Dispatch` batch candidates later in #10083, which + // must keep the convert-the-query-once step. + let backend = f16_backend(); + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + if backend == HalfBackend::Neon { + return l2_f16_batch_neon(x, batch, dimension, output); + } + if backend == HalfBackend::Scalar { + let x: Vec = x.iter().map(|v| v.to_f32()).collect(); + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_scalar_mixed::(&x, y); + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f16_with(backend, x, y); + } + } + } +} + +/// Out of line so the loop gets registers of its own: inlined into +/// `l2_batch_into`, LLVM spilled the batch pointer to the stack, which put a +/// store-to-load round trip on every dimension-8 distance. +#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] +#[inline(never)] +fn l2_f16_batch_neon(x: &[f16], batch: &[f16], dimension: usize, output: &mut [f32]) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f16_with(HalfBackend::Neon, x, y); + } +} + +#[inline(always)] +fn l2_f16_with(backend: HalfBackend, x: &[f16], y: &[f16]) -> f32 { + match backend { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { kernel::l2_f16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32) }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_f16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + kernel::l2_f16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { kernel::l2_f16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32) }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { kernel::l2_f16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32) }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { kernel::l2_f16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32) }, + // SimdSupport::AvxFma and SimdSupport::Avx retain their scalar + // route; this fallback only extends the tiers the C kernel already + // served to Avx512FP16 after checking F16C and FMA. + _ => l2_scalar::(x, y), + } +} + +impl L2 for f32 { + #[inline] + fn l2(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + L2_F32.get().call(x, y) + } + + fn l2_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + L2_F32_BATCH.get().call(x, batch, dimension, output); + } +} + +lance_core::dispatch! { + static L2_F32: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::L2_F32_AVX512, + x86::L2_F32_AVX_FMA, + x86::L2_F32_AVX, + L2_F32_SCALAR, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_F32_SCALAR] + } + }; +} + +lance_core::dispatch! { + /// There is no AVX-512 candidate: the AVX+FMA kernel is the best one so + /// that Haswell-baseline builds select it at compile time, with no + /// per-batch dispatch at the 8-wide PQ dimension. Its dimension-dependent + /// choice mirrors what those builds have always computed. + static L2_F32_BATCH: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::L2_F32_BATCH_AVX_FMA, + x86::L2_F32_BATCH_AVX, + L2_F32_BATCH_SCALAR, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_F32_BATCH_SCALAR] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_F32_SCALAR: PairKernel)] + /// Portable L2 distance for f32, relying on LLVM to auto-vectorize it. + #[inline] + fn l2_f32_scalar(x: &[f32], y: &[f32]) -> f32 { + // Below one 16-lane chunk (e.g. dimension-8 PQ sub-vectors) the + // 16-lane kernel is all scalar remainder: a serial add chain whose + // speed swings with code layout. 8 lanes vectorizes it. + if x.len() < 16 { + return l2_scalar::(x, y); + } + // 16 = 512 (avx512) / 8 bits / 4 (sizeof(f32)) + // See https://github.com/lance-format/lance/pull/2450. + l2_scalar::(x, y) + } +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_F32_BATCH_SCALAR: BatchKernel)] + #[inline] + fn l2_batch_f32_scalar(x: &[f32], batch: &[f32], dimension: usize, output: &mut [f32]) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f32_scalar(x, y); + } + } +} + +impl L2 for f64 { + #[inline] + fn l2(x: &[Self], y: &[Self]) -> f32 { + assert_equal_lengths(x.len(), y.len()); + l2_f64_simd(x, y) + } + + fn l2_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); + // Reading `SIMD_SUPPORT` per vector costs a large share of a + // dimension-8 distance, so pick the tier once per batch. Each tier's + // loop carries that tier's target features, so its kernel inlines. + // Interim: f64 still selects through `SIMD_SUPPORT`, not `Dispatch`; + // these per-tier loops become its `Dispatch` batch candidates later + // in #10083. + // + // SAFETY (all three calls): `SIMD_SUPPORT` reports a tier only when + // the host has its features: avx512f for the AVX-512 tiers, avx and + // fma for `Avx2`/`AvxFma`, and avx for `Avx`. + #[cfg(target_arch = "x86_64")] + match *SIMD_SUPPORT { + SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { + x86::l2_batch_f64_avx512(x, batch, dimension, output) + }, + SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { + x86::l2_batch_f64_avx_fma(x, batch, dimension, output) + }, + SimdSupport::Avx => unsafe { x86::l2_batch_f64_avx(x, batch, dimension, output) }, + _ => { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f64_scalar(x, y); + } + } + } + // A compile-time query length lets LLVM keep the query in registers + // and drop the kernel's 4-lane and scalar tail stages, which it + // otherwise doesn't reliably unswitch out of the loop. 8 and 16 are + // the PQ sub-vector lengths of 128-dimension vectors. + #[cfg(not(target_arch = "x86_64"))] + if let Ok(x) = <&[Self; 8]>::try_from(x) { + l2_batch_f64_fixed(x, batch, output); + } else if let Ok(x) = <&[Self; 16]>::try_from(x) { + l2_batch_f64_fixed(x, batch, output); + } else { + // A pointer walk rather than `zip` with `chunks_exact`: on aarch64 + // the zip indexed each vector with a multiply, which measurably + // slowed short vectors. + let mut y = batch.as_ptr(); + for distance in output.iter_mut() { + // SAFETY: the layout assert guarantees `batch.len() == output.len() * dimension`. + unsafe { + *distance = l2_f64_simd_other(x, std::slice::from_raw_parts(y, dimension)); + y = y.add(dimension); + } + } + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline(always)] +fn l2_batch_f64_fixed(x: &[f64; N], batch: &[f64], output: &mut [f32]) { + for (distance, y) in output.iter_mut().zip(batch.as_chunks::().0) { + *distance = l2_f64_simd_other(x, y); + } +} + +/// L2 distance for f64, runtime-dispatched via `SIMD_SUPPORT` on x86_64 +/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the SIMD +/// primitives in `crate::simd::f64`, unconditionally backed by NEON / LSX-LASX. +#[inline] +fn l2_f64_simd(x: &[f64], y: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + match *SIMD_SUPPORT { + SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { x86::l2_f64_avx512(x, y) }, + SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::l2_f64_avx_fma(x, y) }, + SimdSupport::Avx => unsafe { x86::l2_f64_avx(x, y) }, + _ => l2_f64_scalar(x, y), + } + } + #[cfg(not(target_arch = "x86_64"))] + { + l2_f64_simd_other(x, y) + } +} + +/// Portable scalar L2 distance for f64. Used as the x86_64 fallback when no +/// AVX2 is detected, and exposed for cross-backend parity testing. +#[cfg(target_arch = "x86_64")] +#[inline] +fn l2_f64_scalar(x: &[f64], y: &[f64]) -> f32 { + x.iter() + .zip(y.iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum::() as f32 +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use crate::distance::{BatchKernel, PairKernel}; + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::x86::hsum256_ps; + use crate::simd::{FloatSimd, SIMD}; + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) L2_F32_BATCH_AVX_FMA: BatchKernel)] + /// Up to 16 dimensions the scalar kernel's 16-lane chunking degenerates + /// to its remainder loop, so the explicit AVX kernel wins; above that + /// the auto-vectorized scalar kernel is as good or better. + pub(super) fn l2_batch_f32_avx_fma( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + let key = unsafe { _mm256_loadu_ps(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + let diff = _mm256_sub_ps(key, unsafe { _mm256_loadu_ps(y.as_ptr()) }); + *distance = unsafe { hsum256_ps(_mm256_mul_ps(diff, diff)) }; + } + } else if dimension == 16 + && let Ok(key) = <&[f32; 16]>::try_from(x) + { + // Same sums as `l2_f32_avx_fma`, whose first FMA adds to zero, + // with the key loaded once per batch. + let (key_lo, key_hi) = + unsafe { (_mm256_loadu_ps(key.as_ptr()), _mm256_loadu_ps(key.as_ptr().add(8))) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<16>().0) { + let (y_lo, y_hi) = + unsafe { (_mm256_loadu_ps(y.as_ptr()), _mm256_loadu_ps(y.as_ptr().add(8))) }; + let (diff_lo, diff_hi) = (_mm256_sub_ps(key_lo, y_lo), _mm256_sub_ps(key_hi, y_hi)); + let sum = _mm256_fmadd_ps(diff_hi, diff_hi, _mm256_mul_ps(diff_lo, diff_lo)); + *distance = unsafe { hsum256_ps(sum) }; + } + } else if dimension <= 16 { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f32_avx_fma(x, y); + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = super::l2_f32_scalar(x, y); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) L2_F32_BATCH_AVX: BatchKernel)] + pub(super) fn l2_batch_f32_avx( + x: &[f32], + batch: &[f32], + dimension: usize, + output: &mut [f32], + ) { + if dimension == 8 + && let Ok(key) = <&[f32; 8]>::try_from(x) + { + let key = unsafe { _mm256_loadu_ps(key.as_ptr()) }; + for (distance, y) in output.iter_mut().zip(batch.as_chunks::<8>().0) { + let diff = _mm256_sub_ps(key, unsafe { _mm256_loadu_ps(y.as_ptr()) }); + *distance = unsafe { hsum256_ps(_mm256_mul_ps(diff, diff)) }; + } + } else { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f32_avx(x, y); + } + } + } + } + + /// # Safety + /// + /// The host must support AVX-512F. + #[target_feature(enable = "avx512f")] + pub(super) unsafe fn l2_batch_f64_avx512( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = unsafe { l2_f64_avx512(x, y) }; + } + } + + /// # Safety + /// + /// The host must support AVX and FMA. + #[target_feature(enable = "avx,fma")] + pub(super) unsafe fn l2_batch_f64_avx_fma( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = unsafe { l2_f64_avx_fma(x, y) }; + } + } + + /// # Safety + /// + /// The host must support AVX. + #[target_feature(enable = "avx")] + pub(super) unsafe fn l2_batch_f64_avx( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = unsafe { l2_f64_avx(x, y) }; + } + } + + /// AVX-512 path for f64: 8-wide `__m512d` with `vsubpd` + `vfmadd231pd` per iteration. + #[target_feature(enable = "avx512f")] + #[inline] + pub unsafe fn l2_f64_avx512(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + let a = _mm512_loadu_pd(x.as_ptr().add(i)); + let b = _mm512_loadu_pd(y.as_ptr().add(i)); + let diff = _mm512_sub_pd(a, b); + acc = _mm512_fmadd_pd(diff, diff, acc); + } + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (_mm512_reduce_add_pd(acc) + tail) as f32 + } + + /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). + #[target_feature(enable = "avx,fma")] + #[inline] + pub unsafe fn l2_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + let a = f64x8::load_unaligned(x.as_ptr().add(i)); + let b = f64x8::load_unaligned(y.as_ptr().add(i)); + let diff = a - b; + acc8.multiply_add(diff, diff); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + let a = f64x4::load_unaligned(x.as_ptr().add(i)); + let b = f64x4::load_unaligned(y.as_ptr().add(i)); + let diff = a - b; + acc4.multiply_add(diff, diff); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 + } + + /// AVX-only path for f64 (no FMA): squared diff via `_mm256_mul_pd` + `_mm256_add_pd` for Sandy/Ivy Bridge. + #[target_feature(enable = "avx")] + #[inline] + pub unsafe fn l2_f64_avx(x: &[f64], y: &[f64]) -> f32 { + let dim = x.len(); + let unrolled_len = dim / 4 * 4; + + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + let a = _mm256_loadu_pd(x.as_ptr().add(i)); + let b = _mm256_loadu_pd(y.as_ptr().add(i)); + let diff = _mm256_sub_pd(a, b); + acc = _mm256_add_pd(acc, _mm256_mul_pd(diff, diff)); + } + + // Horizontal sum of __m256d -> f64. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc_sum + tail) as f32 + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) L2_F32_AVX512: PairKernel)] + /// AVX-512 path for f32: 16-wide `__m512` with `vsubps` + `vfmadd231ps` per iteration. + #[inline] + pub(super) fn l2_f32_avx512(x: &[f32], y: &[f32]) -> f32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 16 * 16; + + let mut acc = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + let (a, b) = unsafe { + ( + _mm512_loadu_ps(x.as_ptr().add(i)), + _mm512_loadu_ps(y.as_ptr().add(i)), + ) + }; + let diff = _mm512_sub_ps(a, b); + acc = _mm512_fmadd_ps(diff, diff, acc); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + _mm512_reduce_add_ps(acc) + tail + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) L2_F32_AVX_FMA: PairKernel)] + /// AVX + FMA path for f32. Covers both AvxFma and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn l2_f32_avx_fma(x: &[f32], y: &[f32]) -> f32 { + // See `l2_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let (a, b) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(y.as_ptr().add(i)), + ) + }; + let diff = _mm256_sub_ps(a, b); + acc = _mm256_fmadd_ps(diff, diff, acc); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + let sum = unsafe { hsum256_ps(acc) }; + sum + tail + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) L2_F32_AVX: PairKernel)] + /// AVX-only path for f32 (no FMA): squared diff via `_mm256_mul_ps` + `_mm256_add_ps` for Sandy/Ivy Bridge. + #[inline] + pub(super) fn l2_f32_avx(x: &[f32], y: &[f32]) -> f32 { + // See `l2_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let (a, b) = unsafe { + ( + _mm256_loadu_ps(x.as_ptr().add(i)), + _mm256_loadu_ps(y.as_ptr().add(i)), + ) + }; + let diff = _mm256_sub_ps(a, b); + acc = _mm256_add_ps(acc, _mm256_mul_ps(diff, diff)); + } + + let tail: f32 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + let sum = unsafe { hsum256_ps(acc) }; + sum + tail + } + } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline] +fn l2_f64_simd_other(x: &[f64], y: &[f64]) -> f32 { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + let dim = x.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + unsafe { + let a = f64x8::load_unaligned(x.as_ptr().add(i)); + let b = f64x8::load_unaligned(y.as_ptr().add(i)); + let diff = a - b; + acc8.multiply_add(diff, diff); + } + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + unsafe { + let a = f64x4::load_unaligned(x.as_ptr().add(i)); + let b = f64x4::load_unaligned(y.as_ptr().add(i)); + let diff = a - b; + acc4.multiply_add(diff, diff); + } + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 +} + +/// Accumulate squared differences for one dimension into per-target results. +/// +/// Separated into its own function so that LLVM sees `row` and `result` +/// as non-aliasing via the function signature (`&[f32]` vs `&mut [f32]`), +/// enabling packed SIMD vectorization (vbroadcastss + vsubps + vfmadd231ps). +#[inline(never)] +fn accumulate_l2_dimension(q: f32, row: &[f32], result: &mut [f32]) { + for (dist, &target) in result.iter_mut().zip(row.iter()) { + let diff = q - target; + *dist += diff * diff; + } +} + +/// Pre-transposed target vectors for batched L2 distance computation. +/// +/// Stores targets in SoA layout `[dimension][num_targets]` so the inner +/// distance loop iterates over targets contiguously. The AoS-to-SoA +/// transpose is done once at construction; callers should reuse the +/// struct across many queries to amortize that cost. +/// +/// **Cache constraint**: this is designed for cases where +/// `num_targets × dimension × 4` fits in L1 cache (~32 KB), such as PQ +/// sub-vector codebooks (e.g. 256 centroids × 16 dims = 16 KB). +/// For large target sets the SoA layout causes L1 thrashing and +/// [`l2_distance_batch_into`] with its AoS per-target locality is faster. +#[derive(Debug, Clone, DeepSizeOf)] +pub struct L2Prepared { + transposed: Vec, + dimension: usize, + num_targets: usize, +} + +impl L2Prepared { + /// Transpose `targets` from AoS `[num_targets][dimension]` to SoA layout. + /// + /// `targets.len()` must be a multiple of `dimension`. + /// + /// # Panics + /// + /// Panics if `dimension` is zero. With debug assertions on, also panics if + /// `targets.len()` is not a multiple of `dimension`; without them the + /// trailing partial vector is dropped. + pub fn new(targets: &[f32], dimension: usize) -> Self { + let num_targets = targets.len() / dimension; + debug_assert_eq!(targets.len(), num_targets * dimension); + + let mut transposed = vec![0.0f32; targets.len()]; + for t in 0..num_targets { + for d in 0..dimension { + transposed[d * num_targets + t] = targets[t * dimension + d]; + } + } + + Self { + transposed, + dimension, + num_targets, + } + } + + /// Compute L2 distances from `query` to every target, writing into `out`. + /// + /// `query` must have length `dimension` and `out` must have length + /// `num_targets`. `out` will be zeroed before accumulation. + /// + /// # Panics + /// + /// With debug assertions on, panics unless both lengths match. A `query` + /// longer than `dimension` can also panic on a slice range without them. + pub fn distances_into(&self, query: &[f32], out: &mut [f32]) { + debug_assert_eq!(query.len(), self.dimension); + debug_assert_eq!(out.len(), self.num_targets); + + out.fill(0.0); + for (d, &q) in query.iter().enumerate() { + let row = &self.transposed[d * self.num_targets..][..self.num_targets]; + accumulate_l2_dimension(q, row, out); + } + } + + /// Compute L2 distances from `query` to every target. + /// + /// `query` must have length `dimension`. + /// + /// # Panics + /// + /// Panics under the conditions [`Self::distances_into`] documents, with the + /// same debug/release behavior. + pub fn distances(&self, query: &[f32]) -> Vec { + let mut result = vec![0.0f32; self.num_targets]; + self.distances_into(query, &mut result); + result + } + + /// Return the index of the nearest target to `query`, using `buf` as scratch space. + /// + /// `query` must have length `dimension`, and `buf` must have length + /// `num_targets`. NaN distances are ignored; on ties the lowest index wins. + /// Returns `None` if there are no targets or no distance is finite. + /// + /// # Panics + /// + /// Panics under the conditions [`Self::distances_into`] documents, with the + /// same debug/release behavior. + pub fn nearest_into(&self, query: &[f32], buf: &mut [f32]) -> Option { + self.distances_into(query, buf); + let distances: &[f32] = buf; + // `argmin` panics on an empty slice, and returns an index even when no + // distance is finite (all NaN or infinite). + if distances.is_empty() { + return None; + } + let idx = distances.argmin(); + (distances[idx] < f32::INFINITY).then_some(idx as u32) + } + + /// Return the index of the nearest target to `query`. + /// + /// `query` must have length `dimension`. + /// + /// # Panics + /// + /// Panics under the conditions [`Self::distances_into`] documents, with the + /// same debug/release behavior. + pub fn nearest(&self, query: &[f32]) -> Option { + self.nearest_into(query, &mut vec![0.0f32; self.num_targets]) + } + + /// Number of targets in this set. + pub fn num_targets(&self) -> usize { + self.num_targets + } + + /// Dimension of each target vector. + pub fn dimension(&self) -> usize { + self.dimension + } + + /// Size of the internal buffer in bytes. + pub fn size_bytes(&self) -> usize { + self.transposed.len() * std::mem::size_of::() + } +} + +/// Compute L2 distance between two vectors. +/// +/// # Panics +/// +/// Panics if `from` and `to` have different lengths. +#[inline] +pub fn l2_distance(from: &[f32], to: &[f32]) -> f32 { + l2(from, to) +} + +/// Writes the L2 distance from `from` to each `dimension`-sized vector in `to` +/// into the matching element of `output`. +/// +/// # Panics +/// +/// The implementations in this crate panic if `dimension == 0`, if +/// `from.len() != dimension`, if `to.len()` is not a multiple of `dimension`, +/// or if `output.len() != to.len() / dimension`. +/// +/// ``` +/// # use lance_linalg::distance::l2_distance_batch_into; +/// let mut distances = [0.0; 2]; +/// l2_distance_batch_into(&[1.0_f32, 2.0], &[1.0, 2.0, 3.0, 4.0], 2, &mut distances); +/// assert_eq!(distances, [0.0, 8.0]); +/// ``` +#[inline] +pub fn l2_distance_batch_into(from: &[T], to: &[T], dimension: usize, output: &mut [f32]) { + T::l2_batch_into(from, to, dimension, output); +} + +/// Compute l2 distances, propagating the null buffer of `to`. +/// +/// See [`super::DistanceType::batch`] for supported types and input validation. +#[deprecated(note = "Use DistanceType::L2.batch")] +pub fn l2_distance_arrow_batch( + from: &dyn Array, + to: &FixedSizeListArray, +) -> Result> { + super::DistanceType::L2.batch(from, to).map(Arc::new) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow_array::{cast::AsArray, types::Float32Type}; + + use approx::assert_relative_eq; + use num_traits::ToPrimitive; + use proptest::prelude::*; + + #[test] + fn test_l2_rejects_mismatched_lengths() { + let short = [1.0_f32]; + let long = [1.0_f32, 2.0]; + + assert!(std::panic::catch_unwind(|| l2(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| l2_f32(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| f32::l2(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| l2_distance(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| l2_distance_batch_vec(&short, &long, 2)).is_err()); + assert!( + std::panic::catch_unwind(|| l2_distance_batch_vec(&long, &[1.0_f32; 3], 2)).is_err() + ); + assert!( + std::panic::catch_unwind(|| l2_distance_batch_into::(&[], &[], 0, &mut [])) + .is_err() + ); + assert!(std::panic::catch_unwind(|| l2_distance_uint_scalar(&[1, 2], &[1])).is_err()); + assert!(std::panic::catch_unwind(|| l2_scalar::(&[1, 2], &[1])).is_err()); + } + + use crate::test_utils::{ + arbitrary_bf16, arbitrary_f16, arbitrary_f32, arbitrary_f64, arbitrary_vector_pair, + dimension_shard, run_vector_pair_proptest, + }; + + fn l2_distance_batch_vec(from: &[T], to: &[T], dimension: usize) -> Vec { + let mut distances = vec![0.0; to.len() / dimension]; + l2_distance_batch_into(from, to, dimension, &mut distances); + distances + } + + #[test] + fn test_l2_f32_dispatch_matches_scalar() { + // Covers tail handling for lengths around the 16-lane AVX-512 stride. + for dim in [1usize, 7, 15, 16, 17, 31, 33, 64, 100, 1024] { + let x: Vec = (0..dim).map(|i| (i as f32) * 0.5 - 3.0).collect(); + let y: Vec = (0..dim).map(|i| (i as f32) * -0.25 + 1.5).collect(); + assert_relative_eq!(l2_f32(&x, &y), l2(&x, &y), max_relative = 1e-5); + } + } + + /// PQ distance tables call this per sub-vector, so Haswell-baseline + /// builds must reach the kernel without a runtime dispatch. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_f32_batch_is_static_on_haswell() { + use lance_core::utils::cpu::CpuFeatures; + let haswell = + CpuFeatures::from_target_features(&["avx2", "fma", "f16c", "bmi1", "bmi2", "popcnt"]); + assert!(haswell.contains(L2_F32_BATCH.candidates()[0].features())); + } + + #[test] + fn test_euclidean_distance() { + let mat = FixedSizeListArray::from_iter_primitive::( + vec![ + Some((0..8).map(|v| Some(v as f32)).collect::>()), + Some((1..9).map(|v| Some(v as f32)).collect::>()), + Some((2..10).map(|v| Some(v as f32)).collect::>()), + Some((3..11).map(|v| Some(v as f32)).collect::>()), + ], + 8, + ); + let point = Float32Array::from((2..10).map(|v| Some(v as f32)).collect::>()); + let distances = l2_distance_batch_vec( + point.values(), + mat.values().as_primitive::().values(), + 8, + ); + + assert_eq!(distances, vec![32.0, 8.0, 0.0, 8.0]); + } + + #[test] + fn test_not_aligned() { + let mat = (0..6) + .chain(0..8) + .chain(1..9) + .chain(2..10) + .chain(3..11) + .map(|v| v as f32) + .collect::>(); + let point = Float32Array::from((0..10).map(|v| Some(v as f32)).collect::>()); + let distances = l2_distance_batch_vec(&point.values()[2..], &mat[6..], 8); + + assert_eq!(distances, vec![32.0, 8.0, 0.0, 8.0]); + } + + #[test] + fn test_odd_length_vector() { + let mat = Float32Array::from_iter((0..5).map(|v| Some(v as f32))); + let point = Float32Array::from((2..7).map(|v| Some(v as f32)).collect::>()); + let distances = l2_distance_batch_vec(point.values(), mat.values(), 5); + + assert_eq!(distances, vec![20.0]); + } + + #[test] + fn test_l2_distance_cases() { + let values: Float32Array = vec![ + 0.25335717, 0.24663818, 0.26330215, 0.14988247, 0.06042378, 0.21077952, 0.26687378, + 0.22145681, 0.18319066, 0.18688454, 0.05216244, 0.11470364, 0.10554603, 0.19964123, + 0.06387895, 0.18992095, 0.00123718, 0.13500804, 0.09516747, 0.19508345, 0.2582458, + 0.1211653, 0.21121833, 0.24809816, 0.04078768, 0.19586588, 0.16496408, 0.14766085, + 0.04898421, 0.14728612, 0.21263947, 0.16763233, + ] + .into(); + + let q: Float32Array = vec![ + 0.18549609, + 0.29954708, + 0.28318876, + 0.05424477, + 0.093134984, + 0.21580857, + 0.2951282, + 0.19866848, + 0.13868214, + 0.19819534, + 0.23271298, + 0.047727287, + 0.14394054, + 0.023316395, + 0.18589257, + 0.037315924, + 0.07037327, + 0.32609823, + 0.07344752, + 0.020155912, + 0.18485495, + 0.32763934, + 0.14296658, + 0.04498596, + 0.06254237, + 0.24348071, + 0.16009757, + 0.053892266, + 0.05918874, + 0.040363103, + 0.19913352, + 0.14545348, + ] + .into(); + + let d = l2_distance_batch_vec(q.values(), values.values(), 32); + assert_relative_eq!(0.319_357_84, d[0]); + } + + /// Reference implementation of L2 distance. + /// + /// Note that we skip the final square root step for performance reasons. + fn l2_distance_reference(x: &[f64], y: &[f64]) -> f64 { + x.iter() + .zip(y.iter()) + .map(|(x, y)| (*x - *y).powi(2)) + .sum::() + } + + fn do_l2_test(x: &[T], y: &[T]) -> std::result::Result<(), TestCaseError> { + let x_f64 = x.iter().map(|v| v.to_f64().unwrap()).collect::>(); + let y_f64 = y.iter().map(|v| v.to_f64().unwrap()).collect::>(); + + let result = l2(x, y); + let reference = l2_distance_reference(&x_f64, &y_f64) as f32; + + prop_assert!(approx::relative_eq!(result, reference, max_relative = 1e-6)); + Ok(()) + } + + #[test] + fn test_l2_distance_f16_max() { + let x = vec![f16::MAX; 4048]; + let y = vec![-f16::MAX; 4048]; + do_l2_test(&x, &y).unwrap(); + } + + #[rstest::rstest] + fn test_l2_distance_f32( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + do_l2_test(&x, &y) + }); + } + + #[rstest::rstest] + fn test_l2_distance_f64( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + do_l2_test(&x, &y) + }); + } + + /// Every host-supported f32 kernel, single-pair and batch, must agree with + /// an f64 reference. Prefixes of length 8 and 16 pin the batch kernels' + /// PQ-width fast paths regardless of the generated dimension. + #[rstest::rstest] + fn test_l2_f32_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f32, dimension_shard(shard), |x, y| { + for dimension in [8, 16, x.len()].into_iter().filter(|&d| d <= x.len()) { + let (x, y) = (&x[..dimension], &y[..dimension]); + let x_f64 = x.iter().map(|&v| v as f64).collect::>(); + let y_f64 = y.iter().map(|&v| v as f64).collect::>(); + let want = l2_distance_reference(&x_f64, &y_f64) as f32; + + for candidate in L2_F32.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(x, y); + prop_assert!( + approx::relative_eq!(got, want, max_relative = 1e-3), + "{} at dim {dimension}: {got} != {want}", + candidate.name() + ); + } + + // Where an x86 batch kernel reuses its tier's pair kernel or a + // fast path for it, the two must match bit for bit: up to 16 + // dimensions for AVX+FMA (above that it uses the scalar + // kernel), and at every dimension for AVX. + #[cfg(target_arch = "x86_64")] + for (pair, batch, max_dimension) in [ + (x86::L2_F32_AVX_FMA, x86::L2_F32_BATCH_AVX_FMA, 16), + (x86::L2_F32_AVX, x86::L2_F32_BATCH_AVX, usize::MAX), + ] { + if dimension > max_dimension { + continue; + } + let (Some(pair_kernel), Some(batch_kernel)) = (pair.kernel(), batch.kernel()) + else { + continue; + }; + let mut got = [f32::NAN]; + batch_kernel.call(x, y, dimension, &mut got); + prop_assert_eq!( + got[0].to_bits(), + pair_kernel.call(x, y).to_bits(), + "{} at dim {}", + batch.name(), + dimension + ); + } + + // The second vector equals the key, so its distance is exactly 0. + let batch = [y, x].concat(); + for candidate in L2_F32_BATCH.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut got = [f32::NAN; 2]; + kernel.call(x, &batch, dimension, &mut got); + prop_assert!( + approx::relative_eq!(got[0], want, max_relative = 1e-3) && got[1] == 0.0, + "{} at dim {dimension}: {got:?} != [{want}, 0]", + candidate.name() + ); + } + } + Ok(()) + }); + } + + // Test L2 distance over different types. + // * L2 is valid over the entire range of f16. + // * L2 is valid over f32 and bf16 in the range of +-1e12. + // * L2 for f64 should match the reference implementation. + proptest::proptest! { + #[test] + fn test_l2_distance_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) { + do_l2_test(&x, &y)?; + } + + #[test] + fn test_l2_distance_bf16((x, y) in arbitrary_vector_pair(arbitrary_bf16, 4..4048)){ + do_l2_test(&x, &y)?; + } + + /// Cross-backend parity: scalar fallback must match the dispatched + /// SIMD path within numerical tolerance. Exercises `l2_f64_scalar` + /// directly so the runtime fallback is exercised even on AVX2-capable + /// CI hosts. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_f64_scalar_simd_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + let scalar = l2_f64_scalar(&x, &y); + let simd = l2_f64_simd(&x, &y); + prop_assert!(approx::relative_eq!(scalar, simd, max_relative = 1e-6)); + } + + /// AVX-512-direct parity: explicitly compares the scalar fallback + /// against the native AVX-512 inner kernel on AVX-512F-capable hosts + /// (Skylake-X+, Ice Lake, Sapphire Rapids, Zen 4). Early-returns on + /// hosts without AVX-512F. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_f64_scalar_vs_avx512_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !std::is_x86_feature_detected!("avx512f") { + return Ok(()); + } + let scalar = l2_f64_scalar(&x, &y); + let avx512 = unsafe { x86::l2_f64_avx512(&x, &y) }; + prop_assert!(approx::relative_eq!(scalar, avx512, max_relative = 1e-6)); + } + + /// AVX + FMA-direct parity for the f64 L2 kernel. Covers the AMD + /// Piledriver / Steamroller / FX-7500 tier. Early-returns on hosts + /// without both AVX and FMA. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_f64_scalar_vs_avx_fma_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !(std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma")) { + return Ok(()); + } + let scalar = l2_f64_scalar(&x, &y); + let avx_fma = unsafe { x86::l2_f64_avx_fma(&x, &y) }; + prop_assert!(approx::relative_eq!(scalar, avx_fma, max_relative = 1e-6)); + } + + /// AVX-only-direct parity for the f64 L2 kernel. Covers the Intel + /// Sandy Bridge / Ivy Bridge tier. Early-returns on hosts without + /// AVX. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_f64_scalar_vs_avx_parity( + (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) + ) { + if !std::is_x86_feature_detected!("avx") { + return Ok(()); + } + let scalar = l2_f64_scalar(&x, &y); + let avx = unsafe { x86::l2_f64_avx(&x, &y) }; + prop_assert!(approx::relative_eq!(scalar, avx, max_relative = 1e-6)); + } + } + + #[test] + fn test_uint8_l2_edge_cases() { + let q = vec![0_u8; 2048]; + let v = vec![0_u8; 2048]; + assert_eq!(l2_distance_uint_scalar(&q, &v), 0.0); + + let q = vec![0_u8; 2048]; + let v = vec![255_u8; 2048]; + assert_eq!( + l2_distance_uint_scalar(&q, &v), + (255_u32.pow(2) * 2048) as f32 + ); + assert_eq!( + l2_distance_uint_scalar(&v, &q), + (255_u32.pow(2) * 2048) as f32 + ); + } + + #[test] + fn test_l2_targets_matches_scalar() { + let cases = vec![ + (16, 8), // small target count + (16, 16), // exact SIMD width + (16, 256), // PQ-like: 256 centroids, 16-dim sub-vectors + (16, 17), // one remainder + (16, 31), // 15 remainder + (1, 32), // dim=1 + (3, 20), // odd dimension + (128, 64), // larger dimension + ]; + + for (dim, num_targets) in cases { + let query: Vec = (0..dim).map(|i| (i as f32) * 0.1 + 0.05).collect(); + let targets: Vec = (0..dim * num_targets) + .map(|i| ((i * 7 + 3) % 100) as f32 * 0.01) + .collect(); + + let expected: Vec = targets + .chunks_exact(dim) + .map(|v| l2_scalar::(&query, v)) + .collect(); + + let prepared = L2Prepared::new(&targets, dim); + let actual = prepared.distances(&query); + + assert_eq!( + actual.len(), + expected.len(), + "length mismatch for dim={dim}, num_targets={num_targets}" + ); + for (i, (a, e)) in actual.iter().zip(expected.iter()).enumerate() { + assert!( + approx::relative_eq!(a, e, max_relative = 1e-6), + "mismatch at index {i} for dim={dim}, num_targets={num_targets}: \ + prepared={a}, scalar={e}" + ); + } + } + } + + #[test] + fn test_l2_targets_zeros() { + let dim = 16; + let num_targets = 32; + let query = vec![0.0f32; dim]; + let targets = vec![0.0f32; dim * num_targets]; + + let prepared = L2Prepared::new(&targets, dim); + let distances = prepared.distances(&query); + assert_eq!(distances.len(), num_targets); + for d in &distances { + assert_eq!(*d, 0.0); + } + } + + #[test] + fn test_l2_targets_known_values() { + let dim = 2; + let query = vec![1.0f32, 0.0]; + + // 16 targets: [1,0], [0,1], [2,0], [0,0], then 12x [0,0] + let mut targets = vec![1.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 0.0]; + for _ in 4..16 { + targets.extend_from_slice(&[0.0, 0.0]); + } + + let prepared = L2Prepared::new(&targets, dim); + let distances = prepared.distances(&query); + assert_eq!(distances.len(), 16); + assert_relative_eq!(distances[0], 0.0); + assert_relative_eq!(distances[1], 2.0); + assert_relative_eq!(distances[2], 1.0); + assert_relative_eq!(distances[3], 1.0); + for d in &distances[4..] { + assert_relative_eq!(*d, 1.0); + } + } + + #[test] + fn test_l2_targets_reuse() { + // Verify that the same L2Prepared can be queried multiple times + let dim = 4; + let targets = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + let prepared = L2Prepared::new(&targets, dim); + + let q1 = vec![1.0, 2.0, 3.0, 4.0]; + let q2 = vec![5.0, 6.0, 7.0, 8.0]; + + let d1 = prepared.distances(&q1); + let d2 = prepared.distances(&q2); + + assert_relative_eq!(d1[0], 0.0); // q1 == target[0] + assert_relative_eq!(d2[1], 0.0); // q2 == target[1] + } + + /// With dimension 1 and a zero query, the distance to target `t` is `t * t`. + /// PQ uses 16 (4-bit) or 256 (8-bit) targets. The 258 targets of `first_of_equal` + /// put 2 targets after the last full SIMD vector, so the tie spans both parts. + #[rstest::rstest] + #[case::last_of_16([vec![3.0; 15], vec![2.0]].concat(), Some(15))] + #[case::first_of_equal([3.0, 1.0, -1.0].repeat(86), Some(1))] + #[case::skips_nan([vec![f32::NAN; 255], vec![2.0]].concat(), Some(255))] + #[case::all_nan(vec![f32::NAN; 16], None)] + #[case::all_infinite(vec![f32::INFINITY; 256], None)] + #[case::nan_and_infinite([f32::NAN, f32::INFINITY].repeat(8), None)] + #[case::no_targets(vec![], None)] + fn test_l2_targets_nearest(#[case] targets: Vec, #[case] expected: Option) { + let prepared = L2Prepared::new(&targets, 1); + assert_eq!(prepared.nearest(&[0.0]), expected); + } + + /// `l2_batch_into` must agree with the per-vector `l2` for the f32 batch + /// kernel and for the f64 and f16 loops that select their backend once + /// per batch. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_12(12)] + #[case::dim_13(13)] + #[case::dim_16(16)] + #[case::dim_32(32)] + #[case::dim_1024(1024)] + fn test_l2_batch_into_matches_per_vector_l2(#[case] dimension: usize) { + fn check(dimension: usize, bit_exact: bool) { + let num_vectors = 130; + // Values that are not multiples of a power of two, so the sums + // round and a different summation order changes the result. + let x: Vec = (0..dimension) + .map(|i| T::from_f32((i as f32 * 0.37).sin()).unwrap()) + .collect(); + let batch: Vec = (0..dimension * num_vectors) + .map(|i| T::from_f32((i as f32 * 0.73).cos() * 2.0).unwrap()) + .collect(); + + let mut got = vec![f32::NAN; num_vectors]; + T::l2_batch_into(&x, &batch, dimension, &mut got); + + for (g, y) in got.iter().zip(batch.chunks_exact(dimension)) { + let w = T::l2(&x, y); + if bit_exact { + assert_eq!( + g.to_bits(), + w.to_bits(), + "dim {dimension}: batch {g} != per-vector {w}" + ); + } else { + assert!( + approx::relative_eq!(*g, w, epsilon = 1e-4, max_relative = 1e-5), + "dim {dimension}: batch {g} != per-vector {w}" + ); + } + } + } + // Above dimension 16 the f32 batch kernel is a different kernel from + // the pair kernel, so only f32 is compared with a tolerance. The f64 + // and f16 batch loops run the pair kernel's arithmetic. + check::(dimension, false); + check::(dimension, true); + check::(dimension, true); + } + + /// Each x86 f64 batch loop must match its pair kernel bit for bit, + /// including the tiers this host's `SIMD_SUPPORT` doesn't select. + #[cfg(target_arch = "x86_64")] + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_13(13)] + #[case::dim_1024(1024)] + fn test_l2_batch_f64_tiers_match_pair_kernels(#[case] dimension: usize) { + type BatchFn = unsafe fn(&[f64], &[f64], usize, &mut [f32]); + type PairFn = unsafe fn(&[f64], &[f64]) -> f32; + + let num_vectors = 37; + let x: Vec = (0..dimension).map(|i| (i as f64 * 0.37).sin()).collect(); + let batch: Vec = (0..dimension * num_vectors) + .map(|i| (i as f64 * 0.73).cos() * 2.0) + .collect(); + + let tiers: [(&str, bool, BatchFn, PairFn); 3] = [ + ( + "avx512", + std::is_x86_feature_detected!("avx512f"), + x86::l2_batch_f64_avx512, + x86::l2_f64_avx512, + ), + ( + "avx_fma", + std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma"), + x86::l2_batch_f64_avx_fma, + x86::l2_f64_avx_fma, + ), + ( + "avx", + std::is_x86_feature_detected!("avx"), + x86::l2_batch_f64_avx, + x86::l2_f64_avx, + ), + ]; + for (name, is_supported, batch_fn, pair_fn) in tiers { + if !is_supported { + continue; + } + let mut got = vec![f32::NAN; num_vectors]; + // SAFETY: the host supports this tier's target features. + unsafe { batch_fn(&x, &batch, dimension, &mut got) }; + for (g, y) in got.iter().zip(batch.chunks_exact(dimension)) { + // SAFETY: as above. + let want = unsafe { pair_fn(&x, y) }; + assert_eq!( + g.to_bits(), + want.to_bits(), + "{name} dim {dimension}: batch {g} != pair {want}" + ); + } + } + } + + /// The f64 batch loops off x86 walk `batch` by pointer, sized by `output`, + /// so the layout check must reject a wrong `output` length for every type. + #[rstest::rstest] + #[case::short(1)] + #[case::long(3)] + fn test_l2_batch_into_rejects_wrong_output_len(#[case] output_len: usize) { + fn rejects(output_len: usize) { + let x = [T::from_f32(1.0).unwrap(), T::from_f32(2.0).unwrap()]; + let batch = [T::from_f32(1.0).unwrap(); 4]; + let mut output = vec![0.0; output_len]; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + l2_distance_batch_into(&x, &batch, 2, &mut output) + })); + assert!( + result.is_err(), + "{} accepted output length {output_len}", + std::any::type_name::() + ); + } + rejects::(output_len); + rejects::(output_len); + rejects::(output_len); + } + + /// An empty batch with a valid dimension, e.g. no centroids, writes + /// nothing and does not panic. 8 and 16 take the fixed-length paths. + #[rstest::rstest] + #[case::dim_8(8)] + #[case::dim_16(16)] + #[case::dim_13(13)] + fn test_l2_batch_into_accepts_empty_batch(#[case] dimension: usize) { + fn accepts(dimension: usize) { + let x = vec![T::from_f32(1.0).unwrap(); dimension]; + l2_distance_batch_into::(&x, &[], dimension, &mut []); + } + accepts::(dimension); + accepts::(dimension); + accepts::(dimension); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/l2_u8.rs b/rust/lancedb/vendor/lance-linalg/src/distance/l2_u8.rs new file mode 100644 index 000000000..46f1a50d2 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/l2_u8.rs @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Unsigned int8 squared L2 distance with runtime-dispatched SIMD backends. +//! +//! Computes `Σ(a[i] - b[i])²` for u8 slices. The u32 entry points return the +//! low 32 bits, while [`l2_u8_u64`] chunks those kernels to produce the full +//! result used by Scalar Quantization (SQ), where both L2 and Cosine metric +//! types operate on quantized u8 codes. +//! +//! Backends (selected at runtime, best available wins): +//! 1. scalar — portable reference, also used for tails +//! 2. avx2 — VPSADBW-style abs diff + VPMADDWD squaring, 32 elements/iter +//! 3. avx512vnni — same approach with VPDPWSSD accumulation, 64 elements/iter +//! +//! ## Algorithm +//! +//! Each SIMD backend computes |a - b| per element using saturating +//! subtraction: `max(a,b) - min(a,b) = (a ⊖ b) | (b ⊖ a)` where ⊖ +//! is unsigned saturating subtraction. The absolute differences are then +//! zero-extended to i16 and squared via VPMADDWD (which also pairwise- +//! accumulates adjacent products into i32). + +use super::{U8_U32_ACCUMULATOR_MAX_LEN, assert_equal_lengths}; + +type L2U8Kernel = unsafe fn(&[u8], &[u8]) -> u32; + +lance_core::dispatch! { + /// There are no AVX or AVX+FMA candidates: the SIMD kernels need AVX2 + /// integer ops, so those hosts use the scalar kernel. + static L2_U8: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[x86::L2_U8_AVX512_VNNI, x86::L2_U8_AVX2, L2_U8_SCALAR] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_U8_SCALAR] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_U8_SCALAR: L2U8Kernel)] + /// Portable scalar u8 squared L2 distance, also used for SIMD tail elements. + /// + /// The result is the low 32 bits of the exact squared distance. Use + /// [`l2_u8_u64`] when the full result is required. + /// + /// # Panics + /// + /// Panics if `a` and `b` have different lengths. + #[inline] + pub fn l2_u8_scalar(a: &[u8], b: &[u8]) -> u32 { + assert_equal_lengths(a.len(), b.len()); + a.iter().zip(b.iter()).fold(0, |sum, (&x, &y)| { + sum.wrapping_add((x.abs_diff(y) as u32).pow(2)) + }) + } +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use super::L2U8Kernel; + + /// Horizontal sum of all 8 × i32 lanes in a __m256i. + #[target_feature(enable = "avx2")] + #[inline] + fn hsum_epi32_avx2(v: __m256i) -> u32 { + let lo128 = _mm256_castsi256_si128(v); + let hi128 = _mm256_extracti128_si256(v, 1); + let mut sum128 = _mm_add_epi32(lo128, hi128); + sum128 = _mm_hadd_epi32(sum128, sum128); + sum128 = _mm_hadd_epi32(sum128, sum128); + _mm_cvtsi128_si32(sum128) as u32 + } + + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) L2_U8_AVX2: L2U8Kernel)] + /// AVX2 path: saturating-sub abs diff, unpack to i16, VPMADDWD to square. + /// 32 elements/iter. + pub(super) fn l2_u8_avx2(a: &[u8], b: &[u8]) -> u32 { + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let n = a.len().min(b.len()); + let zeros = _mm256_setzero_si256(); + let mut acc = _mm256_setzero_si256(); + let mut i = 0usize; + + while i + 32 <= n { + let (av, bv) = unsafe { + ( + _mm256_loadu_si256(a.as_ptr().add(i) as *const __m256i), + _mm256_loadu_si256(b.as_ptr().add(i) as *const __m256i), + ) + }; + + // |a - b| via saturating subtraction: max(a-b, 0) | max(b-a, 0) + let abs_diff = _mm256_or_si256(_mm256_subs_epu8(av, bv), _mm256_subs_epu8(bv, av)); + + // Zero-extend u8→i16 via interleave with zeros. + // unpacklo/hi within each 128-bit lane. + let diff_lo = _mm256_unpacklo_epi8(abs_diff, zeros); + let diff_hi = _mm256_unpackhi_epi8(abs_diff, zeros); + + // VPMADDWD squares adjacent i16 pairs and sums into i32. + acc = _mm256_add_epi32(acc, _mm256_madd_epi16(diff_lo, diff_lo)); + acc = _mm256_add_epi32(acc, _mm256_madd_epi16(diff_hi, diff_hi)); + i += 32; + } + + let mut result = hsum_epi32_avx2(acc); + + // Scalar tail + while i < n { + let d = a[i].abs_diff(b[i]) as u32; + result = result.wrapping_add(d * d); + i += 1; + } + result + } + } + + lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw", "avx512vnni")] + #[candidate(pub(super) L2_U8_AVX512_VNNI: L2U8Kernel)] + /// AVX-512 VNNI path: abs diff + VPDPWSSD for fused square-accumulate. + /// 64 elements/iter. + pub(super) fn l2_u8_avx512_vnni(a: &[u8], b: &[u8]) -> u32 { + // See `l2_u8_avx2`. + let n = a.len().min(b.len()); + let zeros = _mm512_setzero_si512(); + let mut acc = _mm512_setzero_si512(); + let mut i = 0usize; + + while i + 64 <= n { + let (av, bv) = unsafe { + ( + _mm512_loadu_si512(a.as_ptr().add(i) as *const __m512i), + _mm512_loadu_si512(b.as_ptr().add(i) as *const __m512i), + ) + }; + + // |a - b| via saturating subtraction + let abs_diff = _mm512_or_si512(_mm512_subs_epu8(av, bv), _mm512_subs_epu8(bv, av)); + + // Zero-extend u8→i16 via interleave with zeros + let diff_lo = _mm512_unpacklo_epi8(abs_diff, zeros); + let diff_hi = _mm512_unpackhi_epi8(abs_diff, zeros); + + // VPDPWSSD: signed i16 pairwise multiply-add into i32 accumulator. + // diff values are 0..255, fitting in i16 as positive, so signed is fine. + acc = _mm512_dpwssd_epi32(acc, diff_lo, diff_lo); + acc = _mm512_dpwssd_epi32(acc, diff_hi, diff_hi); + i += 64; + } + + let mut result = _mm512_reduce_add_epi32(acc) as u32; + + // Scalar tail + while i < n { + let d = a[i].abs_diff(b[i]) as u32; + result = result.wrapping_add(d * d); + i += 1; + } + result + } + } +} + +/// Dispatched u8 squared L2 distance, selecting the best available SIMD backend. +/// +/// The result is the low 32 bits of the exact squared distance. Use +/// [`l2_u8_u64`] when the full result is required. +/// +/// # Panics +/// +/// Panics if `a` and `b` have different lengths. +#[inline] +pub fn l2_u8(a: &[u8], b: &[u8]) -> u32 { + assert_equal_lengths(a.len(), b.len()); + L2_U8.get().call(a, b) +} + +/// Calculates the exact u8 squared L2 distance with a u64 accumulator. +/// +/// This retains the runtime-selected SIMD kernel and widens its result between +/// chunks that are guaranteed to fit in a u32. +/// +/// # Panics +/// +/// Panics if `a` and `b` have different lengths. +/// +/// # Example +/// +/// ``` +/// use lance_linalg::distance::l2_u8::l2_u8_u64; +/// +/// assert_eq!(l2_u8_u64(&[10, 20], &[7, 21]), 10); +/// ``` +#[inline] +pub fn l2_u8_u64(a: &[u8], b: &[u8]) -> u64 { + assert_equal_lengths(a.len(), b.len()); + if a.len() <= U8_U32_ACCUMULATOR_MAX_LEN { + return l2_u8(a, b) as u64; + } + a.chunks(U8_U32_ACCUMULATOR_MAX_LEN) + .zip(b.chunks(U8_U32_ACCUMULATOR_MAX_LEN)) + .map(|(a, b)| l2_u8(a, b) as u64) + .sum() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::u8_inputs::{LENGTHS, Pattern, random}; + + #[test] + fn rejects_mismatched_lengths() { + assert!(std::panic::catch_unwind(|| l2_u8_scalar(&[1, 2], &[1])).is_err()); + assert!(std::panic::catch_unwind(|| l2_u8(&[1, 2], &[1])).is_err()); + } + + /// Every host-supported kernel, and the dispatched entry point, must equal + /// the low 32 bits of the exact distance. + fn assert_kernels_match_reference(a: &[u8], b: &[u8], label: &str) { + let exact: u64 = a + .iter() + .zip(b) + .map(|(&x, &y)| (x.abs_diff(y) as u64).pow(2)) + .sum(); + let want = exact as u32; + for candidate in L2_U8.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(a, b); + assert_eq!(got, want, "{} [{label}] n={}", candidate.name(), a.len()); + } + assert_eq!(l2_u8(a, b), want, "l2_u8 [{label}] n={}", a.len()); + } + + #[rstest::rstest] + #[case::random(Pattern::Random)] + #[case::extremes(Pattern::Extremes)] + #[case::one_sided_zeros(Pattern::OneSidedZeros)] + fn test_l2_u8_kernels_match_reference(#[case] pattern: Pattern) { + for &len in LENGTHS { + for (label, a, b) in pattern.pairs(len) { + assert_kernels_match_reference(&a, &b, label); + } + } + } + + /// The SIMD kernels are safe functions, so unequal lengths must stay in + /// bounds and use the common prefix. The lengths cross both SIMD strides. + #[rstest::rstest] + #[case::shorter_right(129, 65)] + #[case::longer_right(65, 129)] + fn simd_kernels_use_common_prefix_of_unequal_lengths( + #[case] a_len: usize, + #[case] b_len: usize, + ) { + let a = random(a_len, 0); + let b = random(b_len, 1); + let n = a_len.min(b_len); + let want = l2_u8_scalar(&a[..n], &b[..n]); + for candidate in L2_U8.candidates() { + // The scalar kernel asserts equal lengths instead. + if candidate.features().is_empty() { + continue; + } + let Some(kernel) = candidate.kernel() else { + continue; + }; + assert_eq!(kernel.call(&a, &b), want, "{}", candidate.name()); + } + } + + #[test] + fn known_values() { + // 3² + 1² = 10 + assert_eq!(l2_u8_scalar(&[10, 20], &[7, 21]), 10); + assert_eq!(l2_u8(&[10, 20], &[7, 21]), 10); + + // max single-element distance: 255² = 65025 + assert_eq!(l2_u8(&[0], &[255]), 65025); + assert_eq!(l2_u8(&[255], &[0]), 65025); + } + + #[test] + fn overflow_is_backend_independent_and_wide_result_is_exact() { + let len = U8_U32_ACCUMULATOR_MAX_LEN + 1; + let a = vec![u8::MAX; len]; + let b = vec![0; len]; + let exact = u8::MAX as u64 * u8::MAX as u64 * len as u64; + + assert_kernels_match_reference(&a, &b, "u32 overflow"); + assert_eq!(l2_u8_scalar(&a, &b), exact as u32); + assert_eq!(l2_u8_u64(&a, &b), exact); + assert_eq!( + crate::distance::l2::l2_distance_uint_scalar(&a, &b), + exact as f32 + ); + assert_eq!(crate::distance::l2::l2::(&a, &b), exact as f32); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs b/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs new file mode 100644 index 000000000..35aeb2140 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs @@ -0,0 +1,787 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::{iter::Sum, ops::AddAssign}; + +use arrow_array::{FixedSizeListArray, Float32Array}; +use half::{bf16, f16}; + +use super::arrow::{Norm, Operation, dispatch}; +#[allow(unused_imports)] +use lance_core::utils::cpu::{SIMD_SUPPORT, SimdSupport}; +use num_traits::{AsPrimitive, Float, Num}; + +#[cfg(feature = "fp16kernels")] +use super::HalfBackend; +use super::{HALF_KERNELS_COMPILED, HalfType, half_backend, x86_half_features}; + +/// L2 normalization +pub trait Normalize: Num { + /// L2 Normalization over a Vector. + fn norm_l2(vector: &[Self]) -> f32; +} + +#[cfg(feature = "fp16kernels")] +mod kernel { + use super::*; + + // These are the `norm_l2_f16` function in f16.c. Our build.rs script compiles + // a version of this file for each SIMD level with different suffixes. + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn norm_l2_f16_neon(ptr: *const f16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))] + pub fn norm_l2_f16_avx512(ptr: *const f16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn norm_l2_f16_avx2(ptr: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn norm_l2_f16_lsx(ptr: *const f16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn norm_l2_f16_lasx(ptr: *const f16, len: u32) -> f32; + } +} + +impl Normalize for u8 { + #[inline] + fn norm_l2(vector: &[Self]) -> f32 { + norm_l2_impl::(vector) + } +} + +impl Normalize for f16 { + #[inline] + fn norm_l2(vector: &[Self]) -> f32 { + match half_backend( + *SIMD_SUPPORT, + HalfType::F16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + kernel::norm_l2_f16_neon(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_f16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + kernel::norm_l2_f16_avx512(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + kernel::norm_l2_f16_avx2(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + kernel::norm_l2_f16_lasx(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + kernel::norm_l2_f16_lsx(vector.as_ptr(), vector.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx retain their scalar + // route; this fallback only extends the tiers the C kernel already + // served to Avx512FP16 after checking F16C and FMA. + _ => norm_l2_impl::(vector), + } + } +} + +#[cfg(feature = "fp16kernels")] +mod bf16_kernel { + use half::bf16; + + unsafe extern "C" { + #[cfg(target_arch = "aarch64")] + pub fn norm_l2_bf16_neon(ptr: *const bf16, len: u32) -> f32; + #[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))] + pub fn norm_l2_bf16_avx512(ptr: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "x86_64")] + pub fn norm_l2_bf16_avx2(ptr: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn norm_l2_bf16_lsx(ptr: *const bf16, len: u32) -> f32; + #[cfg(target_arch = "loongarch64")] + pub fn norm_l2_bf16_lasx(ptr: *const bf16, len: u32) -> f32; + } +} + +impl Normalize for bf16 { + #[inline] + fn norm_l2(vector: &[Self]) -> f32 { + match half_backend( + *SIMD_SUPPORT, + HalfType::Bf16, + HALF_KERNELS_COMPILED, + cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")), + x86_half_features(), + ) { + #[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))] + HalfBackend::Neon => unsafe { + bf16_kernel::norm_l2_bf16_neon(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all( + feature = "fp16kernels", + kernel_support = "avx512_bf16", + target_arch = "x86_64" + ))] + HalfBackend::Avx512 => unsafe { + bf16_kernel::norm_l2_bf16_avx512(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))] + HalfBackend::Avx2 => unsafe { + bf16_kernel::norm_l2_bf16_avx2(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lasx => unsafe { + bf16_kernel::norm_l2_bf16_lasx(vector.as_ptr(), vector.len() as u32) + }, + #[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))] + HalfBackend::Lsx => unsafe { + bf16_kernel::norm_l2_bf16_lsx(vector.as_ptr(), vector.len() as u32) + }, + // SimdSupport::AvxFma and SimdSupport::Avx fall through here: + // the bf16 C kernels are compiled with `-march=haswell` minimum + // (AVX2), so they cannot run on AVX-only or AVX+FMA hosts. + _ => norm_l2_impl::(vector), + } + } +} + +impl Normalize for f32 { + #[inline] + fn norm_l2(vector: &[Self]) -> f32 { + norm_l2_f32_dispatched(vector) + } +} + +/// L2 norm for f32, runtime-dispatched via `SIMD_SUPPORT` on x86_64 +/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the +/// auto-vectorised scalar loop. +#[inline] +fn norm_l2_f32_dispatched(vector: &[f32]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + match *SIMD_SUPPORT { + SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { + x86::norm_l2_f32_avx512(vector) + }, + SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::norm_l2_f32_avx_fma(vector) }, + SimdSupport::Avx => unsafe { x86::norm_l2_f32_avx(vector) }, + _ => norm_l2_f32_scalar(vector), + } + } + #[cfg(not(target_arch = "x86_64"))] + { + norm_l2_f32_scalar(vector) + } +} + +/// Portable scalar L2 norm for f32. Used as the x86_64 fallback when no +/// AVX2 is detected, and as the only path on non-x86 architectures. The +/// `LANES = 16` chunking matches the explicit-SIMD inner kernels above. +#[inline] +fn norm_l2_f32_scalar(vector: &[f32]) -> f32 { + norm_l2_impl::(vector) +} + +impl Normalize for f64 { + #[inline] + fn norm_l2(vector: &[Self]) -> f32 { + norm_l2_f64_simd(vector) + } +} + +/// L2 norm for f64. Runtime-dispatched to the best available backend. +/// +/// On x86_64, dispatches via `SIMD_SUPPORT` to a native AVX-512 inner kernel +/// (Skylake-X+, Ice Lake, Sapphire Rapids, Zen 4), an AVX2 + FMA kernel +/// (Haswell+), an AVX + FMA kernel (AMD Piledriver / Steamroller), an +/// AVX-only kernel (Intel Sandy Bridge / Ivy Bridge), or a portable scalar +/// fallback. The per-tier inner functions each carry their own +/// `#[target_feature]` so they stay correct under any compile baseline. +/// On aarch64 and loongarch64, the SIMD primitives in `crate::simd::f64` +/// are unconditionally backed by NEON / LSX-LASX respectively, so no +/// runtime gate is required. +#[inline] +pub fn norm_l2_f64_simd(vector: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + match *SIMD_SUPPORT { + SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { + x86::norm_l2_f64_avx512(vector) + }, + SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::norm_l2_f64_avx_fma(vector) }, + SimdSupport::Avx => unsafe { x86::norm_l2_f64_avx(vector) }, + _ => norm_l2_f64_scalar(vector), + } + } + #[cfg(not(target_arch = "x86_64"))] + { + norm_l2_f64_simd_other(vector) + } +} + +/// Portable scalar L2 norm. Used as the x86_64 fallback when no AVX2 is +/// detected, and exposed for cross-backend parity testing. +#[cfg(target_arch = "x86_64")] +#[inline] +fn norm_l2_f64_scalar(vector: &[f64]) -> f32 { + vector.iter().map(|v| v * v).sum::().sqrt() as f32 +} + +#[cfg(target_arch = "x86_64")] +mod x86 { + use std::arch::x86_64::*; + + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::x86::hsum256_ps; + use crate::simd::{FloatSimd, SIMD}; + + /// AVX-512 path for f64: 8-wide `__m512d` with `vfmadd231pd` per iteration. + #[target_feature(enable = "avx512f")] + pub unsafe fn norm_l2_f64_avx512(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + let v = _mm512_loadu_pd(vector.as_ptr().add(i)); + acc = _mm512_fmadd_pd(v, v, acc); + } + + let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (_mm512_reduce_add_pd(acc) + tail).sqrt() as f32 + } + + /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). + #[target_feature(enable = "avx,fma")] + pub unsafe fn norm_l2_f64_avx_fma(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + let v = f64x8::load_unaligned(vector.as_ptr().add(i)); + acc8.multiply_add(v, v); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + let v = f64x4::load_unaligned(vector.as_ptr().add(i)); + acc4.multiply_add(v, v); + } + + let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); + (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 + } + + /// AVX-only path for f64 (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. + #[target_feature(enable = "avx")] + pub unsafe fn norm_l2_f64_avx(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 4 * 4; + + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + let v = _mm256_loadu_pd(vector.as_ptr().add(i)); + acc = _mm256_add_pd(acc, _mm256_mul_pd(v, v)); + } + + // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (acc_sum + tail).sqrt() as f32 + } + + /// AVX-512 path for f32: 16-wide `__m512` with `vfmadd231ps` per iteration. + #[target_feature(enable = "avx512f")] + pub unsafe fn norm_l2_f32_avx512(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 16 * 16; + + let mut acc = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + let v = _mm512_loadu_ps(vector.as_ptr().add(i)); + acc = _mm512_fmadd_ps(v, v, acc); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (_mm512_reduce_add_ps(acc) + tail).sqrt() + } + + /// AVX + FMA path for f32. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). + #[target_feature(enable = "avx,fma")] + pub unsafe fn norm_l2_f32_avx_fma(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let v = _mm256_loadu_ps(vector.as_ptr().add(i)); + acc = _mm256_fmadd_ps(v, v, acc); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (hsum256_ps(acc) + tail).sqrt() + } + + /// AVX-only path for f32 (no FMA): `_mm256_mul_ps` + `_mm256_add_ps` per iteration for Sandy/Ivy Bridge. + #[target_feature(enable = "avx")] + pub unsafe fn norm_l2_f32_avx(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + let v = _mm256_loadu_ps(vector.as_ptr().add(i)); + acc = _mm256_add_ps(acc, _mm256_mul_ps(v, v)); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (hsum256_ps(acc) + tail).sqrt() + } +} + +#[cfg(not(target_arch = "x86_64"))] +#[inline] +fn norm_l2_f64_simd_other(vector: &[f64]) -> f32 { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + unsafe { + let v = f64x8::load_unaligned(vector.as_ptr().add(i)); + acc8.multiply_add(v, v); + } + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + unsafe { + let v = f64x4::load_unaligned(vector.as_ptr().add(i)); + acc4.multiply_add(v, v); + } + } + + let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); + (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 +} + +/// NOTE: this is only pub for benchmarking purposes +#[inline] +pub fn norm_l2_impl< + T: AsPrimitive, + Output: Float + Sum + 'static + AddAssign, + const LANES: usize, +>( + vector: &[T], +) -> Output { + let (chunks, remainder) = vector.as_chunks::(); + let sum = if remainder.is_empty() { + Output::zero() + } else { + remainder.iter().map(|&v| v.as_().powi(2)).sum::() + }; + let mut sums = [Output::zero(); LANES]; + for chunk in chunks { + for i in 0..LANES { + sums[i] += chunk[i].as_().powi(2); + } + } + (sum + sums.iter().copied().sum::()).sqrt() +} + +/// Normalize a vector. +/// +/// The parameters must be cache line aligned. For example, from +/// Arrow Arrays, i.e., Float32Array +#[inline] +pub fn norm_l2(vector: &[T]) -> f32 { + T::norm_l2(vector) +} + +/// L2 norm of every vector in a [FixedSizeListArray], Returns one norm per row. +pub fn norm_l2_fsl(fsl: &FixedSizeListArray) -> crate::Result { + dispatch(Operation::Norm(Norm::L2), None, fsl).map(Float32Array::from) +} + +/// Squared L2 norm of every vector in a [`FixedSizeListArray`]. +/// +/// Supports Float16/Float32/Float64 and rejects zero dimensions. Each square is +/// accumulated in `f32` (or wider) rather than the element type, avoiding f16 +/// overflow and underflow. Like [`norm_l2_fsl`], reads the values of null rows. +/// +/// ``` +/// use arrow_array::{FixedSizeListArray, types::Float32Type}; +/// use lance_linalg::distance::try_norm_squared_fsl; +/// let vectors = FixedSizeListArray::from_iter_primitive::( +/// [Some(vec![Some(3.0), Some(4.0)])], 2); +/// assert_eq!(try_norm_squared_fsl(&vectors)?, vec![25.0]); +/// # Ok::<(), arrow_schema::ArrowError>(()) +/// ``` +pub fn try_norm_squared_fsl(fsl: &FixedSizeListArray) -> crate::Result> { + dispatch(Operation::Norm(Norm::Squared), None, fsl) +} + +/// Squared L2 norms through the legacy infallible API. +/// +/// # Panics +/// Panics for unsupported element types or zero dimensions. Use +/// [`try_norm_squared_fsl`] to receive an error instead. +#[deprecated(note = "Use try_norm_squared_fsl")] +pub fn norm_squared_fsl(fsl: &FixedSizeListArray) -> Vec { + // Retain the public signature while callers migrate to the fallible API. + try_norm_squared_fsl(fsl) + .expect("squared L2 norms require float vectors with positive dimension") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::{ + arbitrary_bf16, arbitrary_f16, arbitrary_f32, arbitrary_f64, dimension_shard, + run_vector_proptest, + }; + use arrow_array::{Float16Array, Float64Array, UInt8Array}; + use arrow_schema::{ArrowError, DataType}; + use lance_arrow::FixedSizeListArrayExt; + use num_traits::ToPrimitive; + use proptest::prelude::*; + use std::sync::Arc; + + /// Reference implementation of L2 norm. + fn norm_l2_reference(data: &[f64]) -> f32 { + data.iter().map(|v| *v * *v).sum::().sqrt() as f32 + } + + fn do_norm_l2_test( + data: &[T], + ) -> std::result::Result<(), TestCaseError> { + let f64_data = data + .iter() + .map(|v| v.to_f64().unwrap()) + .collect::>(); + + let result = norm_l2(data); + let reference = norm_l2_reference(&f64_data); + + prop_assert!(approx::relative_eq!(result, reference, max_relative = 1e-6)); + Ok(()) + } + + #[rstest::rstest] + fn test_l2_norm_f32( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_proptest(arbitrary_f32, dimension_shard(shard), |data| { + do_norm_l2_test(&data) + }); + } + + #[rstest::rstest] + fn test_l2_norm_f64( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_proptest(arbitrary_f64, dimension_shard(shard), |data| { + do_norm_l2_test(&data) + }); + } + + #[rstest::rstest] + fn test_l2_norm_f32_scalar_simd_parity( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_proptest(arbitrary_f32, dimension_shard(shard), |data| { + let scalar = data.iter().map(|&v| (v as f64).powi(2)).sum::().sqrt() as f32; + let simd = ::norm_l2(&data); + prop_assert!(approx::relative_eq!(scalar, simd, max_relative = 1e-3)); + Ok(()) + }); + } + + proptest::proptest! { + #[test] + fn test_l2_norm_f16(data in prop::collection::vec(arbitrary_f16(), 4..4048)) { + do_norm_l2_test(&data)?; + } + + #[test] + fn test_l2_norm_bf16(data in prop::collection::vec(arbitrary_bf16(), 4..4048)){ + do_norm_l2_test(&data)?; + } + + /// Cross-backend parity: scalar fallback must match the dispatched + /// SIMD path within numerical tolerance. Exercises `norm_l2_f64_scalar` + /// directly so the runtime fallback is exercised even on AVX2-capable + /// CI hosts. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_norm_f64_scalar_simd_parity( + data in prop::collection::vec(arbitrary_f64(), 4..4048) + ) { + let scalar = norm_l2_f64_scalar(&data); + let simd = norm_l2_f64_simd(&data); + prop_assert!(approx::relative_eq!(scalar, simd, max_relative = 1e-6)); + } + + /// AVX-512-direct parity: explicitly compares the scalar fallback + /// against the native AVX-512 inner kernel on AVX-512F-capable hosts + /// (Skylake-X+, Ice Lake, Sapphire Rapids, Zen 4). Early-returns on + /// hosts without AVX-512F so the test stays portable; CI runners with + /// AVX-512F exercise the `_mm512_*` path. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_norm_f64_scalar_vs_avx512_parity( + data in prop::collection::vec(arbitrary_f64(), 4..4048) + ) { + if !std::is_x86_feature_detected!("avx512f") { + return Ok(()); + } + let scalar = norm_l2_f64_scalar(&data); + let avx512 = unsafe { x86::norm_l2_f64_avx512(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx512, max_relative = 1e-6)); + } + + /// AVX + FMA-direct parity for the f64 L2-norm kernel. Covers the + /// AMD Piledriver / Steamroller / FX-7500 tier. Early-returns on + /// hosts without both AVX and FMA. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_norm_f64_scalar_vs_avx_fma_parity( + data in prop::collection::vec(arbitrary_f64(), 4..4048) + ) { + if !(std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma")) { + return Ok(()); + } + let scalar = norm_l2_f64_scalar(&data); + let avx_fma = unsafe { x86::norm_l2_f64_avx_fma(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx_fma, max_relative = 1e-6)); + } + + /// AVX-only-direct parity for the f64 L2-norm kernel. Covers the + /// Intel Sandy Bridge / Ivy Bridge tier (AVX without FMA). + /// Early-returns on hosts without AVX. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_l2_norm_f64_scalar_vs_avx_parity( + data in prop::collection::vec(arbitrary_f64(), 4..4048) + ) { + if !std::is_x86_feature_detected!("avx") { + return Ok(()); + } + let scalar = norm_l2_f64_scalar(&data); + let avx = unsafe { x86::norm_l2_f64_avx(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx, max_relative = 1e-6)); + } + + /// AVX-512-direct parity for the f32 L2-norm kernel. Explicitly + /// compares the scalar fallback against the native AVX-512 inner + /// kernel on AVX-512F-capable hosts. Early-returns on hosts without + /// AVX-512F; CI runners with AVX-512F exercise the `_mm512_*` path. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_norm_l2_f32_scalar_vs_avx512_parity( + data in prop::collection::vec(arbitrary_f32(), 4..4048) + ) { + if !std::is_x86_feature_detected!("avx512f") { + return Ok(()); + } + let scalar = norm_l2_f32_scalar(&data); + let avx512 = unsafe { x86::norm_l2_f32_avx512(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx512, max_relative = 1e-3)); + } + + /// AVX + FMA-direct parity for the f32 L2-norm kernel. Covers the + /// AMD Piledriver / Steamroller / FX-7500 tier. Early-returns on + /// hosts without both AVX and FMA. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_norm_l2_f32_scalar_vs_avx_fma_parity( + data in prop::collection::vec(arbitrary_f32(), 4..4048) + ) { + if !(std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma")) { + return Ok(()); + } + let scalar = norm_l2_f32_scalar(&data); + let avx_fma = unsafe { x86::norm_l2_f32_avx_fma(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx_fma, max_relative = 1e-3)); + } + + /// AVX-only-direct parity for the f32 L2-norm kernel. Covers the + /// Intel Sandy Bridge / Ivy Bridge tier (AVX without FMA). + /// Early-returns on hosts without AVX. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_norm_l2_f32_scalar_vs_avx_parity( + data in prop::collection::vec(arbitrary_f32(), 4..4048) + ) { + if !std::is_x86_feature_detected!("avx") { + return Ok(()); + } + let scalar = norm_l2_f32_scalar(&data); + let avx = unsafe { x86::norm_l2_f32_avx(&data) }; + prop_assert!(approx::relative_eq!(scalar, avx, max_relative = 1e-3)); + } + } + + #[test] + fn test_norm_l2_fsl_f32() { + let values = Float32Array::from(vec![3.0, 4.0, 6.0, 8.0]); + let fsl = FixedSizeListArray::try_new_from_values(values, 2).unwrap(); + + let norms = norm_l2_fsl(&fsl).unwrap(); + assert_eq!(norms.len(), 2); + assert!(approx::relative_eq!( + norms.value(0), + 5.0, + max_relative = 1e-6 + )); + assert!(approx::relative_eq!( + norms.value(1), + 10.0, + max_relative = 1e-6 + )); + } + + #[test] + fn test_norm_l2_fsl_f16_and_f64_match_norm_l2() { + // The FSL helper must agree with the per-vector `norm_l2` kernel for + // every supported value type, since callers cache these norms and feed + // them to `cosine_with_norms`. + let f16_vals: Vec = [3.0f32, 4.0, 6.0, 8.0] + .iter() + .map(|&v| f16::from_f32(v)) + .collect(); + let f16_fsl = + FixedSizeListArray::try_new_from_values(Float16Array::from(f16_vals), 2).unwrap(); + let f16_norms = norm_l2_fsl(&f16_fsl).unwrap(); + assert_eq!( + f16_norms.value(0), + norm_l2(&[f16::from_f32(3.0), f16::from_f32(4.0)]) + ); + assert_eq!( + f16_norms.value(1), + norm_l2(&[f16::from_f32(6.0), f16::from_f32(8.0)]) + ); + + let f64_fsl = FixedSizeListArray::try_new_from_values( + Float64Array::from(vec![3.0, 4.0, 6.0, 8.0]), + 2, + ) + .unwrap(); + let f64_norms = norm_l2_fsl(&f64_fsl).unwrap(); + assert_eq!(f64_norms.value(0), norm_l2(&[3.0f64, 4.0])); + assert_eq!(f64_norms.value(1), norm_l2(&[6.0f64, 8.0])); + } + + #[test] + fn test_norm_l2_fsl_rejects_unsupported_value_type() { + let fsl = FixedSizeListArray::try_new_from_values(UInt8Array::from(vec![1u8, 2, 3, 4]), 2) + .unwrap(); + let err = norm_l2_fsl(&fsl).unwrap_err().to_string(); + assert!( + err.contains("unsupported vector element type UInt8"), + "got: {err}" + ); + } + + /// `norm_squared_fsl` must accumulate in a type wider than the element type. + /// `f16 * f16` rounds each square back to `f16`, which saturates to `inf` at + /// `|x| >= 256` and to zero at `|x| <= 1.726e-4`. + #[test] + fn test_norm_squared_fsl_f16_accumulates_wide() { + use arrow_array::Float16Array; + use arrow_schema::Field; + use std::sync::Arc; + + // dim 2: row 0 overflows at the square, row 1 underflows at the square. + let raw = [256.0f32, 0.0, 1e-4, 1e-4]; + let values = Float16Array::from_iter_values(raw.map(f16::from_f32)); + let field = Arc::new(Field::new("item", DataType::Float16, true)); + let fsl = FixedSizeListArray::try_new(field, 2, Arc::new(values), None).unwrap(); + + let got = try_norm_squared_fsl(&fsl).unwrap(); + // Independent reference: square and sum the same f16 inputs in f64. + let expected = raw + .chunks(2) + .map(|c| { + c.iter() + .map(|&x| { + let x = f16::from_f32(x).to_f64(); + x * x + }) + .sum::() + }) + .collect::>(); + + for (row, (&got, &want)) in got.iter().zip(expected.iter()).enumerate() { + assert!( + approx::relative_eq!(got as f64, want, max_relative = 1e-3), + "row {row}: got {got}, want {want}" + ); + } + } + #[rstest::rstest] + #[case::f16(DataType::Float16)] + #[case::f32(DataType::Float32)] + #[case::f64(DataType::Float64)] + #[case::i8(DataType::Int8)] + #[case::u8(DataType::UInt8)] + #[case::i32(DataType::Int32)] + fn test_arrow_norm_support_and_dimension(#[case] dtype: DataType) { + let values = super::super::tests::arrow_values(&dtype, vec![99, 99, 3, 4, 5, 12]); + let vectors = FixedSizeListArray::try_new_from_values(values, 2) + .unwrap() + .slice(1, 2); + let supported = matches!( + dtype, + DataType::Float16 | DataType::Float32 | DataType::Float64 + ); + let norms = norm_l2_fsl(&vectors); + let squared = try_norm_squared_fsl(&vectors); + if supported { + assert_eq!(norms.unwrap().values(), &[5.0, 13.0]); + assert_eq!(squared.unwrap(), vec![25.0, 169.0]); + } else { + for error in [norms.unwrap_err(), squared.unwrap_err()] { + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains("unsupported vector element type") && message.contains(&dtype.to_string())), + "{error}" + ); + } + } + let zero_dim = FixedSizeListArray::try_new_with_length( + Arc::new(arrow_schema::Field::new("item", dtype.clone(), true)), + 0, + super::super::tests::arrow_values(&dtype, vec![]), + None, + 1, + ) + .unwrap(); + for error in [ + norm_l2_fsl(&zero_dim).unwrap_err(), + try_norm_squared_fsl(&zero_dim).unwrap_err(), + ] { + assert!( + matches!(&error, ArrowError::InvalidArgumentError(message) + if message.contains(if supported {"dimension 0"} else {"unsupported vector element type"})), + "{error}" + ); + } + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/kernels.rs b/rust/lancedb/vendor/lance-linalg/src/kernels.rs new file mode 100644 index 000000000..e433037e9 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/kernels.rs @@ -0,0 +1,919 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::cmp::Ordering; +use std::iter::Sum; +use std::sync::Arc; +use std::{collections::hash_map::DefaultHasher, hash::Hash, hash::Hasher}; + +use arrow_array::{ + Array, ArrayRef, ArrowNumericType, ArrowPrimitiveType, FixedSizeListArray, GenericStringArray, + OffsetSizeTrait, PrimitiveArray, UInt64Array, + cast::{AsArray, as_largestring_array, as_primitive_array, as_string_array}, + types::{ + Float16Type, Float32Type, Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, + UInt8Type, UInt16Type, UInt32Type, UInt64Type, + }, +}; +use arrow_schema::{ArrowError, DataType}; +use half::{bf16, f16}; +use num_traits::AsPrimitive; +use num_traits::{Float, Num, bounds::Bounded}; + +use crate::{Error, Result}; + +/// Argmax on a [PrimitiveArray]. +/// +/// Returns the index of the max value in the array. +pub fn argmax(iter: impl Iterator) -> Option { + let mut max_idx: Option = None; + let mut max_value = T::min_value(); + for (idx, value) in iter.enumerate() { + if let Some(Ordering::Greater) = value.partial_cmp(&max_value) { + max_value = value; + max_idx = Some(idx as u32); + } + } + max_idx +} + +/// Finds the index of the maximum value in an iterator of optional values. +/// +/// `None` elements are skipped. +/// +/// Returns `None` if the iterator is empty, contains only `None` values, +/// or no value is strictly greater than the initial lower bound +/// (`T::min_value()`). +pub fn argmax_opt( + iter: impl Iterator>, +) -> Option { + let mut max_idx: Option = None; + let mut max_value = T::min_value(); + for (idx, value) in iter.enumerate() { + if let Some(value) = value + && let Some(Ordering::Greater) = value.partial_cmp(&max_value) + { + max_value = value; + max_idx = Some(idx as u32); + } + } + max_idx +} + +/// Argmin over an iterator. Fused the operation in iterator to avoid memory allocation. +/// +/// Returns the index of the min value in the array. +/// +pub fn argmin(iter: impl Iterator) -> Option { + argmin_value(iter).map(|(idx, _)| idx) +} + +/// Return both argmin and minimal value over an iterator. +/// +/// Return +/// ------ +/// - `Some(idx, min_value)` or +/// - `None` if iterator is empty or all are `Nan/Inf`. +pub fn argmin_value( + iter: impl Iterator, +) -> Option<(u32, T)> { + argmin_value_opt(iter.map(Some)) +} + +/// Returns the minimal value (float) and the index (argmin) from an Iterator. +/// +/// Return `None` if the iterator is empty or all are `Nan/Inf`. +#[inline] +pub fn argmin_value_float(iter: impl Iterator) -> Option<(u32, T)> { + let mut min_idx = None; + let mut min_value = T::infinity(); + for (idx, value) in iter.enumerate() { + if value < min_value { + min_value = value; + min_idx = Some(idx as u32); + } + } + min_idx.map(|idx| (idx, min_value)) +} + +/// Finds the index and value of the element minimizing `value + bias`, +/// where `bias` comes from an optional second iterator. +/// +/// The comparison uses `value + bias`, but the returned value is the +/// original `value` without the bias term. Passing `None` for `bias` +/// is equivalent to [`argmin_value_float`]. +/// +/// The two iterators are zipped, so iteration stops at the shorter one. +/// +/// Returns `None` if the zipped iterator is empty or no `value + bias` +/// is strictly less than the initial bound (`T::infinity()`). +#[inline] +pub fn argmin_value_float_with_bias( + iter: impl Iterator, + bias: Option>, +) -> Option<(u32, T)> { + let Some(bias) = bias else { + return argmin_value_float(iter); + }; + + let mut min_idx = None; + let mut min_value = T::infinity(); + let mut min_original_value = T::infinity(); + for (idx, (value, bias)) in iter.zip(bias).enumerate() { + if value + bias < min_value { + min_value = value + bias; + min_original_value = value; + min_idx = Some(idx as u32); + } + } + min_idx.map(|idx| (idx, min_original_value)) +} + +/// Finds the index and value of the minimum element in an iterator of +/// optional values. +/// +/// `None` elements are skipped. +/// +/// Returns `None` if the iterator is empty, contains only `None` values, +/// or no value is strictly less than the initial upper bound +/// (`T::max_value()`). +pub fn argmin_value_opt( + iter: impl Iterator>, +) -> Option<(u32, T)> { + let mut min_idx: Option = None; + let mut min_value = T::max_value(); + for (idx, value) in iter.enumerate() { + if let Some(value) = value + && let Some(Ordering::Less) = value.partial_cmp(&min_value) + { + min_value = value; + min_idx = Some(idx as u32); + } + } + min_idx.map(|idx| (idx, min_value)) +} + +/// Argmin over an `Option` iterator. +/// +#[inline] +pub fn argmin_opt( + iter: impl Iterator>, +) -> Option { + argmin_value_opt(iter).map(|(idx, _)| idx) +} + +/// The accumulator used to sum squares when normalizing a `T` vector. +/// +/// A type narrow enough that its squares leave its own range, and for which a +/// wider float exists, accumulates in that wider type: squaring an `f16` +/// saturates to `inf` at `|x| >= 256` and to zero at `|x| <= 1.726e-4`, so an +/// ordinary `f16` vector would otherwise normalize to all-zero or all-`inf`. +/// `f32` and `f64` accumulate in themselves — the same saturation still exists at +/// the extremes of their own range (an `f32` square overflows above `1.8447e19`), +/// but widening `f32` would perturb the output of existing f32 vectors by a few +/// ulp (about 10 at dimension 768, growing as sqrt(dim)), so it is deliberately +/// left alone; `f64` has nothing wider to widen to. +/// +/// The width relation is a contract on the implementor, not something the bounds +/// can express. Tying the accumulator to the element type here still buys two +/// things over passing it in: the accumulator cannot drift between the three +/// dispatch sites, and no call site can pick the wrong one. +pub trait Normalizable: Float + AsPrimitive { + /// Must be at least as wide as `Self` in both exponent and mantissa. + type Acc: Float + Sum + AsPrimitive + AsPrimitive; +} + +/// `f16` squares leave its own range, so it accumulates in `f32` — which has +/// 2^96 of headroom over `f16::MAX` squared. +impl Normalizable for f16 { + type Acc = f32; +} + +/// `bf16` has the same exponent range as `f32` (both 8 bits), so widening to +/// `f32` would buy no headroom for squaring — `bf16(1e20)` squared already +/// overflows `f32`. It needs `f64`. +impl Normalizable for bf16 { + type Acc = f64; +} + +impl Normalizable for f32 { + type Acc = Self; +} + +impl Normalizable for f64 { + type Acc = Self; +} + +/// L2 normalize a vector. +/// +/// Returns an iterator of normalized values, and the norm as `f32`. +/// +/// The sum of squares is accumulated in [`Normalizable::Acc`], which is wider +/// than `T` where `T` alone would overflow. +pub fn normalize(v: &[T]) -> (impl Iterator + '_, f32) { + let l2_norm = v + .iter() + .map(|x| { + let x: T::Acc = x.as_(); + x * x + }) + .sum::() + .sqrt(); + ( + v.iter().map(move |&x| (x.as_() / l2_norm).as_()), + l2_norm.as_(), + ) +} + +fn do_normalize_arrow(arr: &dyn Array) -> Result<(ArrayRef, f32)> +where + T::Native: Normalizable, +{ + let v = arr.as_primitive::(); + let (iter, l2_norm) = normalize(v.values()); + Ok(( + Arc::new(PrimitiveArray::::from_iter_values(iter)) as ArrayRef, + l2_norm, + )) +} + +pub fn normalize_arrow(v: &dyn Array) -> Result<(ArrayRef, f32)> { + match v.data_type() { + DataType::Float16 => do_normalize_arrow::(v), + DataType::Float32 => do_normalize_arrow::(v), + DataType::Float64 => do_normalize_arrow::(v), + _ => Err(Error::SchemaError(format!( + "Normalize only supports float array, got: {}", + v.data_type() + ))), + } +} + +fn do_normalize_fsl(fsl: &FixedSizeListArray) -> Result +where + T::Native: Normalizable, +{ + let dim = fsl.value_length() as usize; + let norm_arr = PrimitiveArray::::from_iter_values( + fsl.values() + .as_primitive::() + .values() + .chunks(dim) + .flat_map(|chunk| normalize(chunk).0), + ); + + // Extract the field from the data type + let field = match fsl.data_type() { + DataType::FixedSizeList(field, _) => field.clone(), + _ => unreachable!("FixedSizeListArray must have FixedSizeList data type"), + }; + + // Use try_new to preserve the null buffer from the original array + FixedSizeListArray::try_new( + field, + fsl.value_length(), + Arc::new(norm_arr), + fsl.nulls().cloned(), + ) +} + +/// L2 normalize a [FixedSizeListArray] (of vectors). +pub fn normalize_fsl(fsl: &FixedSizeListArray) -> Result { + match fsl.value_type() { + DataType::Float16 => do_normalize_fsl::(fsl), + DataType::Float32 => do_normalize_fsl::(fsl), + DataType::Float64 => do_normalize_fsl::(fsl), + _ => Err(ArrowError::SchemaError(format!( + "Normalize only supports float array, got: {}", + fsl.value_type() + ))), + } +} + +fn do_normalize_fsl_inplace( + fsl: FixedSizeListArray, +) -> Result +where + T::Native: Normalizable, +{ + let dim = fsl.value_length() as usize; + let (field, size, values_array, nulls) = fsl.into_parts(); + + // Clone the PrimitiveArray (shares the underlying buffer), then drop the + // Arc so the buffer's refcount drops to 1. + let prim = values_array + .as_any() + .downcast_ref::>() + .expect("values must be PrimitiveArray") + .clone(); + drop(values_array); + + // into_builder gives mutable access when the buffer is uniquely owned, + // avoiding a full copy of the (potentially multi-GB) training data. + match prim.into_builder() { + Ok(mut builder) => { + for chunk in builder.values_slice_mut().chunks_mut(dim) { + // Accumulate in the wider type; see [`Normalizable`]. + let l2_norm = chunk + .iter() + .map(|x| { + let x: ::Acc = x.as_(); + x * x + }) + .sum::<::Acc>() + .sqrt(); + for x in chunk.iter_mut() { + *x = (x.as_() / l2_norm).as_(); + } + } + FixedSizeListArray::try_new(field, size, Arc::new(builder.finish()), nulls) + } + Err(prim) => { + let fsl = FixedSizeListArray::try_new(field, size, Arc::new(prim), nulls)?; + do_normalize_fsl::(&fsl) + } + } +} + +/// L2 normalize a [FixedSizeListArray] (of vectors), attempting in-place mutation. +/// +/// If the underlying buffer is uniquely owned, normalization is performed in-place +/// to avoid allocating a second copy. Otherwise falls back to the copy path used +/// by [`normalize_fsl`]. +pub fn normalize_fsl_owned(fsl: FixedSizeListArray) -> Result { + match fsl.value_type() { + DataType::Float16 => do_normalize_fsl_inplace::(fsl), + DataType::Float32 => do_normalize_fsl_inplace::(fsl), + DataType::Float64 => do_normalize_fsl_inplace::(fsl), + _ => Err(ArrowError::SchemaError(format!( + "Normalize only supports float array, got: {}", + fsl.value_type() + ))), + } +} + +fn hash_numeric_type(array: &PrimitiveArray) -> Result +where + T::Native: Hash, +{ + let mut builder = UInt64Array::builder(array.len()); + for i in 0..array.len() { + if array.is_null(i) { + builder.append_null(); + } else { + let mut s = DefaultHasher::new(); + array.value(i).hash(&mut s); + builder.append_value(s.finish()); + } + } + Ok(builder.finish()) +} + +fn hash_string_type(array: &GenericStringArray) -> Result { + let mut builder = UInt64Array::builder(array.len()); + for i in 0..array.len() { + if array.is_null(i) { + builder.append_null(); + } else { + let mut s = DefaultHasher::new(); + array.value(i).hash(&mut s); + builder.append_value(s.finish()); + } + } + Ok(builder.finish()) +} + +/// Calculate hash values for an Arrow Array, using `std::hash::Hash` in rust. +pub fn hash(array: &dyn Array) -> Result { + match array.data_type() { + DataType::UInt8 => hash_numeric_type(as_primitive_array::(array)), + DataType::UInt16 => hash_numeric_type(as_primitive_array::(array)), + DataType::UInt32 => hash_numeric_type(as_primitive_array::(array)), + DataType::UInt64 => hash_numeric_type(as_primitive_array::(array)), + DataType::Int8 => hash_numeric_type(as_primitive_array::(array)), + DataType::Int16 => hash_numeric_type(as_primitive_array::(array)), + DataType::Int32 => hash_numeric_type(as_primitive_array::(array)), + DataType::Int64 => hash_numeric_type(as_primitive_array::(array)), + DataType::Utf8 => hash_string_type(as_string_array(array)), + DataType::LargeUtf8 => hash_string_type(as_largestring_array(array)), + _ => Err(ArrowError::SchemaError(format!( + "Hash only supports integer or string array, got: {}", + array.data_type() + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::collections::HashSet; + + use approx::assert_relative_eq; + use arrow_array::{ + Float16Array, Float32Array, Float64Array, Int8Array, Int16Array, LargeStringArray, + StringArray, UInt8Array, UInt32Array, + }; + use arrow_buffer::NullBuffer; + use arrow_schema::Field; + use half::f16; + use rstest::rstest; + + #[test] + fn test_argmax() { + let f = Float32Array::from(vec![1.0, 5.0, 3.0, 2.0, 20.0, 8.2, 3.5]); + assert_eq!(argmax(f.values().iter().copied()), Some(4)); + + let f = Float32Array::from(vec![1.0, 5.0, f32::NAN, 3.0, 2.0, 20.0, f32::INFINITY, 3.5]); + assert_eq!(argmax_opt(f.iter()), Some(6)); + + let f = Float32Array::from_iter(vec![Some(2.0), None, Some(20.0), Some(f32::NAN)]); + assert_eq!(argmax_opt(f.iter()), Some(2)); + + let f = Float32Array::from(vec![f32::NAN; 3]); + assert_eq!(argmax(f.values().iter().copied()), None); + + let i = Int16Array::from(vec![1, 5, 3, 2, 20, 8, 16]); + assert_eq!(argmax(i.values().iter().copied()), Some(4)); + + let u = UInt32Array::from(vec![1, 5, 3, 2, 20, 8, 16]); + assert_eq!(argmax(u.values().iter().copied()), Some(4)); + + let empty_vec: Vec = vec![]; + let empty = Int16Array::from(empty_vec); + assert_eq!(argmax_opt(empty.iter()), None) + } + + #[test] + fn test_argmin() { + let f = Float32Array::from_iter(vec![5.0, 3.0, 2.0, 20.0, 8.2, 3.5]); + assert_eq!(argmin(f.values().iter().copied()), Some(2)); + + let f = Float32Array::from_iter(vec![5.0, 3.0, 2.0, 20.0, f32::NAN]); + assert_eq!(argmin_opt(f.iter()), Some(2)); + + let f = Float32Array::from_iter(vec![Some(2.0), None, Some(f32::NAN)]); + assert_eq!(argmin_opt(f.iter()), Some(0)); + + let f = Float32Array::from_iter(vec![5.0, 3.0, 2.0, f32::NEG_INFINITY, f32::NAN]); + assert_eq!(argmin(f.values().iter().copied()), Some(3)); + + let f = Float32Array::from_iter(vec![f32::NAN; 4]); + assert_eq!(argmin(f.values().iter().copied()), None); + + let f = Float32Array::from_iter(vec![5.0, 3.0, 2.0, 20.0, 8.2, 3.5]); + assert_eq!(argmin(f.values().iter().copied()), Some(2)); + + let i = Int16Array::from_iter(vec![5, 3, 2, 20, 8, 16]); + assert_eq!(argmin(i.values().iter().copied()), Some(2)); + + let u = UInt32Array::from_iter(vec![5, 3, 2, 20, 8, 16]); + assert_eq!(argmin(u.values().iter().copied()), Some(2)); + + let empty_vec: Vec = vec![]; + let empty = Int16Array::from(empty_vec); + assert_eq!(argmin_opt(empty.iter()), None) + } + + #[rstest] + #[case::no_bias(vec![5.0, 1.0, 3.0], None::>, (1, 1.0))] + #[case::biased_value(vec![5.0, 8.0], Some(vec![-1.0, -5.0]), (1, 8.0))] + // The unpaired value would win if the shorter iterator were not truncated. + #[case::shorter_bias(vec![5.0, 8.0, 1.0], Some(vec![-1.0, -5.0]), (1, 8.0))] + fn test_argmin_value_float_with_bias( + #[case] values: Vec, + #[case] bias: Option>, + #[case] expected: (u32, f32), + ) { + let f = Float32Array::from(values); + assert_eq!( + argmin_value_float_with_bias( + f.values().iter().copied(), + bias.map(|bias| bias.into_iter()) + ), + Some(expected) + ); + } + + #[test] + fn test_numeric_hashes() { + let a: UInt8Array = [1_u8, 2, 3, 4, 5].iter().copied().collect(); + let ha = hash(&a).unwrap(); + let distinct_values: HashSet = ha.values().iter().copied().collect(); + assert_eq!(distinct_values.len(), 5, "hash should be distinct"); + + let b: Int8Array = [1_i8, 2, 3, 4, 5].iter().copied().collect(); + let hb = hash(&b).unwrap(); + + assert_eq!(ha, hb, "hash of the same numeric value should be the same"); + } + + #[test] + fn test_string_hashes() { + let a = StringArray::from(vec!["a", "b", "ccc", "dec", "e", "a"]); + let h = hash(&a).unwrap(); + // first and last value are the same. + assert_eq!(h.value(0), h.value(5)); + + // Other than that, all values should be distinct + let distinct_values: HashSet = h.values().iter().copied().collect(); + assert_eq!(distinct_values.len(), 5); + + let a = LargeStringArray::from(vec!["a", "b", "ccc", "dec", "e", "a"]); + let h = hash(&a).unwrap(); + // first and last value are the same. + assert_eq!(h.value(0), h.value(5)); + } + + #[test] + fn test_hash_unsupported_type() { + let a = Float32Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]); + assert!(hash(&a).is_err()); + } + + #[test] + fn test_normalize_vector() { + let v = vec![1.0_f32, 2.0, 3.0, 4.0, 5.0]; + let l2_norm = v.iter().map(|&x| x.powi(2)).sum::().sqrt(); + assert_relative_eq!(l2_norm, 55_f32.sqrt()); + let normalized = normalize(&v).0.collect::>(); + normalized + .iter() + .enumerate() + .for_each(|(idx, &x)| assert_relative_eq!(x, (idx + 1) as f32 / 55.0_f32.sqrt())); + assert_relative_eq!(1.0, normalized.iter().map(|&x| x.powi(2)).sum::()); + } + + /// The accumulator must not be *narrower* than the element type either. + /// Accumulating f64 in f32 overflows above `|x| = 1.8447e19` (where f64 has + /// headroom to 1.34e154), collapses to a zero norm at or below `|x| = 2^-75` + /// (2.647e-23), and costs ~29 bits of mantissa on every ordinary vector. + #[test] + fn test_normalize_f64_accumulates_wide() { + // Range: each case is finite and correctly normalizable in f64, but + // overflows or underflows an f32 accumulator. + let range_cases: &[(&str, Vec)] = &[ + ("square_overflows", vec![1e20, 0.0]), + ("sum_overflows", vec![1e19; 12]), + ("square_underflows", vec![1e-25, 1e-25]), + ("element_underflows", vec![1e-100, 1e-100]), + ]; + for (name, v) in range_cases { + // Cover all three public entry points: each has its own `match` over + // the element type, so a dispatch cell could regress on its own. + for out in [ + ("normalize_arrow", normalize_f64(v)), + ("normalize_fsl", normalize_f64_fsl(v, false)), + ("normalize_fsl_owned", normalize_f64_fsl(v, true)), + ] { + let (entry, out) = out; + let norm = out.iter().map(|x| x * x).sum::().sqrt(); + assert!( + approx::relative_eq!(norm, 1.0, max_relative = 1e-9), + "{entry} / {name}: normalized norm {norm} != 1, output {out:?}" + ); + } + } + + // Precision: an f32 accumulator would round the output to f32, leaving + // a relative error around f32::EPSILON (~1.2e-7). + let v = vec![1.0_f64, 2.0, 3.0]; + let expected_norm = 14.0_f64.sqrt(); + let out = normalize_f64(&v); + for (i, (&got, &raw)) in out.iter().zip(v.iter()).enumerate() { + let want = raw / expected_norm; + assert!( + approx::relative_eq!(got, want, max_relative = 1e-15), + "element {i}: got {got:.17}, want {want:.17}" + ); + } + } + + /// Normalize an `f64` slice through the public Arrow entry point, so the + /// test exercises the accumulator `normalize_arrow` actually selects. + fn normalize_f64(v: &[f64]) -> Vec { + let arr = Float64Array::from(v.to_vec()); + let (out, _) = normalize_arrow(&arr).unwrap(); + out.as_primitive::().values().to_vec() + } + + /// Same, through the FSL entry points. `owned` selects + /// [`normalize_fsl_owned`], whose freshly built array takes the in-place + /// branch of `do_normalize_fsl_inplace`. + fn normalize_f64_fsl(v: &[f64], owned: bool) -> Vec { + let values = Float64Array::from(v.to_vec()); + let field = Arc::new(Field::new("item", DataType::Float64, true)); + let fsl = + FixedSizeListArray::try_new(field, v.len() as i32, Arc::new(values), None).unwrap(); + let out = if owned { + normalize_fsl_owned(fsl).unwrap() + } else { + normalize_fsl(&fsl).unwrap() + }; + out.values().as_primitive::().values().to_vec() + } + + /// `normalize` must accumulate the sum of squares in a type wider than the + /// element type. `f16::powi` rounds each square back to `f16`, which + /// saturates to `inf` at `|x| >= 256` and to zero at `|x| <= 1.726e-4`, so an + /// ordinary vector normalizes to all-zero or all-`inf`. + #[test] + fn test_normalize_f16_accumulates_wide() { + let cases: &[(&str, &[f32])] = &[ + // A single element whose square leaves the f16 range. + ("square_overflows", &[256.0, 0.0]), + // No element overflows, but the sum of squares does. + ("sum_overflows", &[100.0; 7]), + // Every square rounds to zero, so the norm is zero and x/0 is inf. + ("square_underflows", &[1e-4; 8]), + ]; + for (name, input) in cases { + let v = input.iter().map(|&x| f16::from_f32(x)).collect::>(); + // Independent reference: accumulate the same f16 inputs in f64. + let expected = v + .iter() + .map(|x| x.to_f64() * x.to_f64()) + .sum::() + .sqrt(); + let (normalized, norm) = normalize(&v); + assert!( + approx::relative_eq!(norm, expected as f32, max_relative = 1e-3), + "{name}: norm {norm} != expected {expected}" + ); + let normalized = normalized.collect::>(); + assert!( + normalized.iter().all(|x| x.is_finite()), + "{name}: non-finite output {normalized:?}" + ); + + // The output must be a unit vector. This is the assertion that pins + // the division: an independent f64 sum of the squares, not a + // comparison against another call into the same code. + let unit = normalized + .iter() + .map(|x| x.to_f64() * x.to_f64()) + .sum::(); + assert!( + approx::relative_eq!(unit, 1.0, max_relative = 1e-2), + "{name}: output is not a unit vector, sum of squares {unit}" + ); + + // Also drive the `normalize_arrow` Float16 arm, so the dispatch cell + // is covered. Equality against the generic path only proves the two + // agree — the unit-norm check above is what proves either is right. + let (out, arrow_norm) = normalize_arrow(&Float16Array::from(v)).unwrap(); + assert!( + approx::relative_eq!(arrow_norm, expected as f32, max_relative = 1e-3), + "{name}: normalize_arrow norm {arrow_norm} != expected {expected}" + ); + let out = out.as_primitive::(); + assert_eq!( + out.values().as_ref(), + normalized.as_slice(), + "{name}: normalize_arrow values differ from the generic path" + ); + } + } + + /// `bf16` shares f32's exponent range, so it needs an `f64` accumulator — + /// `f32` would leave the same overflow the f16 case exists to fix. + #[test] + fn test_normalize_bf16_accumulates_wide() { + let cases: &[(&str, &[f32])] = &[ + ("square_overflows", &[1e20, 0.0]), + ("sum_overflows", &[1e19; 12]), + ("square_underflows", &[1e-25, 1e-25]), + ]; + for (name, input) in cases { + let v = input.iter().map(|&x| bf16::from_f32(x)).collect::>(); + let expected = v + .iter() + .map(|x| x.to_f64() * x.to_f64()) + .sum::() + .sqrt(); + let (normalized, norm) = normalize(&v); + let normalized = normalized.collect::>(); + assert!( + approx::relative_eq!(norm as f64, expected, max_relative = 1e-2), + "{name}: norm {norm} != expected {expected}" + ); + let unit = normalized + .iter() + .map(|x| x.to_f64() * x.to_f64()) + .sum::(); + assert!( + approx::relative_eq!(unit, 1.0, max_relative = 1e-2), + "{name}: output is not a unit vector, sum of squares {unit}" + ); + } + } + + /// Both FSL entry points share the defect, including the in-place path in + /// [`do_normalize_fsl_inplace`], which has its own copy of the expression. + #[test] + fn test_normalize_fsl_f16_accumulates_wide() { + // dim 2, row 0 overflows at the square, row 1 underflows at the square. + let make = || { + let values = + Float16Array::from_iter_values([256.0f32, 0.0, 1e-4, 1e-4].map(f16::from_f32)); + let field = Arc::new(Field::new("item", DataType::Float16, true)); + FixedSizeListArray::try_new(field, 2, Arc::new(values), None).unwrap() + }; + + // `normalize_fsl_owned` gets a freshly built array so the buffer is + // uniquely owned and the in-place branch is the one exercised. + let outputs = [ + ("normalize_fsl", normalize_fsl(&make()).unwrap()), + ("normalize_fsl_owned", normalize_fsl_owned(make()).unwrap()), + ]; + for (label, out) in outputs { + let got = out.values().as_primitive::(); + for (row, chunk) in got.values().chunks(2).enumerate() { + let norm = chunk + .iter() + .map(|x| x.to_f64() * x.to_f64()) + .sum::() + .sqrt(); + assert!( + approx::relative_eq!(norm, 1.0, max_relative = 1e-2), + "{label} row {row}: normalized norm {norm} != 1, values {chunk:?}" + ); + } + } + } + + #[test] + fn test_normalize_fsl_with_nulls() { + // Create test data with nulls + let values = Float32Array::from_iter_values(vec![ + 3.0, 4.0, // First vector: [3, 4] -> will be normalized to [0.6, 0.8] + 0.0, 0.0, // Second vector: null (values don't matter) + 5.0, 12.0, // Third vector: [5, 12] -> will be normalized to [5/13, 12/13] + ]); + + // Create null buffer where second vector is null + let null_buffer = NullBuffer::from(vec![true, false, true]); + + let field = Arc::new(Field::new("item", DataType::Float32, true)); + let fsl = + FixedSizeListArray::try_new(field, 2, Arc::new(values), Some(null_buffer.clone())) + .unwrap(); + + // Normalize the array + let normalized = normalize_fsl(&fsl).unwrap(); + + // Verify nulls are preserved + assert_eq!(normalized.nulls(), Some(&null_buffer)); + + // Verify non-null vectors are normalized correctly + let normalized_values = normalized.values().as_primitive::(); + + // First vector [3, 4] -> [0.6, 0.8] + assert_relative_eq!(normalized_values.value(0), 0.6); + assert_relative_eq!(normalized_values.value(1), 0.8); + + // Third vector [5, 12] -> [5/13, 12/13] + assert_relative_eq!(normalized_values.value(4), 5.0 / 13.0); + assert_relative_eq!(normalized_values.value(5), 12.0 / 13.0); + } + + #[test] + fn test_normalize_fsl_edge_cases() { + // Test case 1: All nulls + let values = Float32Array::from_iter_values(vec![0.0; 6]); + let null_buffer = NullBuffer::from(vec![false, false, false]); + let field = Arc::new(Field::new("item", DataType::Float32, true)); + let fsl = FixedSizeListArray::try_new( + field.clone(), + 2, + Arc::new(values), + Some(null_buffer.clone()), + ) + .unwrap(); + + let normalized = normalize_fsl(&fsl).unwrap(); + assert_eq!(normalized.nulls(), Some(&null_buffer)); + + // Test case 2: Empty array + let empty_values = Float32Array::from(vec![] as Vec); + let empty_fsl = + FixedSizeListArray::try_new(field.clone(), 2, Arc::new(empty_values), None).unwrap(); + + let normalized_empty = normalize_fsl(&empty_fsl).unwrap(); + assert_eq!(normalized_empty.len(), 0); + + // Test case 3: No nulls + let values = Float32Array::from_iter_values(vec![1.0, 0.0, 0.0, 1.0]); + let fsl_no_nulls = FixedSizeListArray::try_new(field, 2, Arc::new(values), None).unwrap(); + + let normalized_no_nulls = normalize_fsl(&fsl_no_nulls).unwrap(); + assert_eq!(normalized_no_nulls.nulls(), None); + let values = normalized_no_nulls.values().as_primitive::(); + assert_relative_eq!(values.value(0), 1.0); + assert_relative_eq!(values.value(1), 0.0); + assert_relative_eq!(values.value(2), 0.0); + assert_relative_eq!(values.value(3), 1.0); + } + + fn make_fsl(values: &[f32], dim: i32) -> FixedSizeListArray { + let field = Arc::new(Field::new("item", DataType::Float32, true)); + FixedSizeListArray::try_new( + field, + dim, + Arc::new(Float32Array::from_iter_values(values.iter().copied())), + None, + ) + .unwrap() + } + + /// Assert FSL values match expected, where None means NaN. + fn assert_fsl_eq(actual: &FixedSizeListArray, expected: &[Option], label: &str) { + let vals = actual.values().as_primitive::(); + assert_eq!(vals.len(), expected.len(), "{label}: length mismatch"); + for (i, exp) in expected.iter().enumerate() { + match exp { + None => assert!(vals.value(i).is_nan(), "{label}[{i}]: expected NaN"), + Some(v) => assert_relative_eq!(vals.value(i), *v, epsilon = 1e-6), + } + } + } + + /// normalize_fsl_owned produces correct values and matches normalize_fsl. + /// Zero vectors yield NaN (cosine is undefined; downstream is_finite filters them). + #[test] + fn test_normalize_fsl_owned_values() { + #[allow(clippy::type_complexity)] + let cases: &[(&str, &[f32], &[Option])] = &[ + ( + "basic", + &[3.0, 4.0, 5.0, 12.0], + &[Some(0.6), Some(0.8), Some(5.0 / 13.0), Some(12.0 / 13.0)], + ), + ( + "zero_vector", + &[3.0, 4.0, 0.0, 0.0, 5.0, 12.0], + &[ + Some(0.6), + Some(0.8), + None, + None, + Some(5.0 / 13.0), + Some(12.0 / 13.0), + ], + ), + ]; + for (name, input, expected) in cases { + let fsl = make_fsl(input, 2); + assert_fsl_eq(&normalize_fsl(&fsl).unwrap(), expected, name); + assert_fsl_eq(&normalize_fsl_owned(fsl).unwrap(), expected, name); + } + } + + /// Uniquely-owned buffer is mutated in-place (no copy). + #[test] + fn test_normalize_fsl_owned_inplace() { + let fsl = make_fsl(&[3.0, 4.0, 5.0, 12.0], 2); + let ptr = fsl.values().as_primitive::().values().as_ptr(); + let result = normalize_fsl_owned(fsl).unwrap(); + let new_ptr = result + .values() + .as_primitive::() + .values() + .as_ptr(); + assert_eq!(ptr, new_ptr, "expected in-place mutation"); + } + + /// Sliced inputs normalize correctly via the by-reference path. + /// (normalize_fsl_owned uses into_builder which does not support sliced + /// arrays; use normalize_fsl for sliced data.) + #[test] + fn test_normalize_fsl_sliced_input() { + let sliced = { + let fsl = make_fsl(&[1.0, 0.0, 0.0, 1.0, 3.0, 4.0], 2); + fsl.slice(1, 2) + }; + + let expected = &[Some(0.0), Some(1.0), Some(0.6), Some(0.8)]; + assert_fsl_eq(&normalize_fsl(&sliced).unwrap(), expected, "sliced_ref"); + } + + /// Shared buffer falls back to copy path and still produces correct values. + #[test] + fn test_normalize_fsl_owned_shared_buffer_fallback() { + let fsl = make_fsl(&[3.0, 4.0, 5.0, 12.0], 2); + let _hold = fsl.clone(); // force shared buffer + let expected = &[Some(0.6), Some(0.8), Some(5.0 / 13.0), Some(12.0 / 13.0)]; + assert_fsl_eq(&normalize_fsl_owned(fsl).unwrap(), expected, "fallback"); + } + + /// Null buffer is preserved through normalization. + #[test] + fn test_normalize_fsl_owned_preserves_nulls() { + let values = Float32Array::from_iter_values([3.0, 4.0, 0.0, 0.0, 5.0, 12.0]); + let nulls = NullBuffer::from(vec![true, false, true]); + let field = Arc::new(Field::new("item", DataType::Float32, true)); + let fsl = + FixedSizeListArray::try_new(field, 2, Arc::new(values), Some(nulls.clone())).unwrap(); + assert_eq!(normalize_fsl_owned(fsl).unwrap().nulls(), Some(&nulls)); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/lib.rs b/rust/lancedb/vendor/lance-linalg/src/lib.rs new file mode 100644 index 000000000..0d7654cb7 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/lib.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! High-performance [Apache Arrow](https://docs.rs/arrow/latest/arrow/) native Linear Algebra algorithms. + +#![deny(clippy::unused_async)] +#![cfg_attr(target_arch = "loongarch64", feature(stdarch_loongarch))] + +use arrow_schema::ArrowError; + +mod clustering; +pub mod distance; +pub mod kernels; +pub mod simd; + +#[cfg(test)] +pub(crate) mod test_utils; + +pub use clustering::Clustering; + +type Error = ArrowError; +pub type Result = std::result::Result; diff --git a/rust/lancedb/vendor/lance-linalg/src/simd.rs b/rust/lancedb/vendor/lance-linalg/src/simd.rs new file mode 100644 index 000000000..cc3418c11 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd.rs @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Poor-man's SIMD +//! +//! The difference between this implementation and [std::simd] is that +//! this implementation holds the SIMD register directly, thus it exposes more +//! optimization opportunity to use wide range of instructions available. +//! +//! Also, it gives us more control, for example, it is likely that we will have +//! f16/bf16 support before the standard library does. +//! +//! The API are close to [std::simd] to make migration easier in the future. + +use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; + +pub mod amx_fp16; +pub mod dist_table; +pub mod f32; +pub mod f64; +pub mod i32; +pub mod u8; +#[cfg(target_arch = "x86_64")] +pub(crate) mod x86; + +use num_traits::{Float, Num}; +use u8::u8x16; + +/// Lance SIMD lib. +/// +/// `Mul` operates independently on each lane. Integer implementations keep the +/// low bits of each product, wrapping on overflow, while floating-point +/// implementations follow the scalar type's multiplication semantics. +/// `Add` and `Sub` retain implementation-specific overflow behavior; notably, +/// [`u8x16`] addition saturates while its subtraction wraps. +/// +pub trait SIMD: + std::fmt::Debug + + AddAssign + + Add + + Mul + + Sub + + SubAssign + + Copy + + Clone + + Sized + + for<'a> From<&'a [T]> +{ + const LANES: usize = N; + + /// Create a new instance with all lanes set to `val`. + fn splat(val: T) -> Self; + + /// Create a new instance with all lanes set to zero. + fn zeros() -> Self; + + /// Load aligned data from aligned memory. + /// + /// # Safety + /// + /// It crashes if the ptr is not aligned. + unsafe fn load(ptr: *const T) -> Self; + + /// Load unaligned data from memory. + /// + /// # Safety + /// + /// `ptr` must be valid for reads of `N` elements of `T`. + /// + /// On loongarch64, `f32x8`, `f32x16`, `f64x4`, `f64x8`, and `i32x8` + /// additionally require LASX. These implementations do not check for it at + /// runtime, and calling one without LASX is undefined behavior. + /// + /// `u8x16` has no target-feature requirements beyond the architecture + /// baseline. + unsafe fn load_unaligned(ptr: *const T) -> Self; + + /// Store the values to aligned memory. + /// + /// # Safety + /// + /// It crashes if the ptr is not aligned + unsafe fn store(&self, ptr: *mut T); + + /// Store the values to unaligned memory. + /// + /// # Safety + unsafe fn store_unaligned(&self, ptr: *mut T); + + /// Return the values as an array. + fn as_array(&self) -> [T; N] { + let mut arr = [T::zero(); N]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + arr + } + + /// Calculate the sum across this vector. + fn reduce_sum(&self) -> T; + + /// Find the minimal value in the vector. + fn reduce_min(&self) -> T; + + /// Return the minimal value of these two vectors. + fn min(&self, rhs: &Self) -> Self; + + /// Find the index of value in the vector. If not found, return None. + fn find(&self, val: T) -> Option; +} + +pub trait FloatSimd: SIMD { + /// fused multiply-add + /// + /// c = a * b + c + fn multiply_add(&mut self, a: Self, b: Self); +} + +pub trait Shuffle { + fn shuffle(&self, indices: u8x16) -> Self; +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.c b/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.c new file mode 100644 index 000000000..7d97844d3 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.c @@ -0,0 +1,727 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +// AMX-FP16 tile kernels, and the tile-configuration plumbing they share. +// +// Every kernel here computes fp16 x fp16 dot products with TDPFP16PS +// (fp16 x fp16 -> fp32 accumulate). The tile *shapes* differ per kernel and are +// declared next to each one; the code that turns a shape into a loaded +// LDTILECFG image is shared, because the one subtle step in it (the +// dead-store barrier below) fails silently and only on some compilers, so it +// must exist exactly once. +// +// Two kernels: +// * `lance_amx_dot_f16_batch_16` -- one query against 16 candidates, for +// choosing the IVF partitions a query probes (16 centroids per call). +// Ported in spirit from FAISS PR +// facebookresearch/faiss#5235's AMX-BF16 kernel: fp16 and bf16 are both +// 2-byte tile elements consumed by the same `_tile_dp*ps` shape, so only the +// instruction (`_tile_dpbf16ps` -> `_tile_dpfp16ps`) and the element -> +// float conversion (bf16 bit-shift -> real IEEE fp16 via F16C `_cvtsh_ss`) +// differ. Its C tile is fed by three independent (A, B) tile pairs so three +// TDPFP16PS can be in flight at once; see the tile roles below. +// * `lance_amx_dot_f16_gemm` -- an m x n GEMM, for scoring many vectors +// against many centroids at once (k-means assignment). Uses all eight tiles +// as a 2x2 register-blocked accumulator. +// +// ## Tile configuration is reloaded on every call +// +// Each kernel has one compile-time tile shape (`SEARCH_TILES` / `GEMM_TILES`), +// so caching its LDTILECFG is tempting: that reconfiguration costs a few +// hundred cycles, against the ~64 cycles of useful tile work a dim-128 search +// call performs. It is still wrong, because Lance does not own the tile unit: +// LDTILECFG and TILERELEASE are architectural per-logical-processor state, so +// another AMX user on the thread (oneDNN under PyTorch, ONNX Runtime, same +// Python process) can retire or reshape a configuration Lance believes is live +// -- a foreign TILERELEASE leaves the tiles in INIT and the next tile op raises +// #UD, a foreign LDTILECFG silently substitutes wrong shapes. Neither is +// observable from here, and a kernel reached from arbitrary Rust and C cannot +// bound what runs between two of its own calls. +// +// So nothing is cached: every kernel configures the tiles on entry and releases +// them on exit, and pays that per call. Against a GEMM over a whole block of +// vectors it is noise; against a batch-16 search it is most of the call, and is +// spent anyway, because the alternative is a configuration whose validity this +// file has no way to establish. +// +// ## Thread safety +// +// LDTILECFG sets per-logical-processor state, and nothing here is shared +// mutably: the spec tables are `static const` and the 64-byte config *image* is +// built on the calling thread's stack, so one thread's shape can never reach +// another's tile ops -- as with the XTILECFG it is loaded into, which rides in +// the thread's own XSAVE area. That says nothing about what *other* libraries +// on this thread have done to the tile unit, which is what reconfiguring on +// every entry is for. +// +// SAFETY: executing any AMX tile instruction without first (a) confirming the +// amx-tile + amx-fp16 CPUID bits and (b) obtaining XTILEDATA permission from +// the kernel raises SIGILL. Both are the Rust caller's responsibility (see +// `simd/amx_fp16.rs`); `lance_amx_fp16_request_perm` below performs (b). + +// Must precede all includes: exposes the glibc `syscall()` prototype from +// , which -std=c17 otherwise hides. +#define _GNU_SOURCE + +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#endif + +// --------------------------------------------------------------------------- +// XTILEDATA permission +// --------------------------------------------------------------------------- + +// Ask the kernel to enable AMX tile data state for this process, via +// arch_prctl(ARCH_REQ_XCOMP_PERM, XFEATURE_XTILEDATA). Returns 0 on success, +// non-zero otherwise. Requesting XTILEDATA (18) implicitly also grants +// XTILECFG (17). Constants per Linux Documentation/arch/x86/xstate.rst. +// +// XTILEDATA is the single dynamically-enabled XSAVE state component backing the +// physical TMM tile registers, shared by every AMX compute instruction +// (TDPBUUD / TDPBF16PS / TDPFP16PS ...). The syscall is idempotent, so +// requesting an already-granted permission is harmless. +int lance_amx_fp16_request_perm(void) { +#ifdef __linux__ + const unsigned long ARCH_REQ_XCOMP_PERM = 0x1023; + const unsigned long XFEATURE_XTILEDATA = 18; + return (int)syscall(SYS_arch_prctl, ARCH_REQ_XCOMP_PERM, XFEATURE_XTILEDATA); +#else + return -1; +#endif +} + +// --------------------------------------------------------------------------- +// Shared tile configuration +// --------------------------------------------------------------------------- + +// Tile configuration kinds. One per distinct tile shape, and the selector +// `lance_amx_tilecfg_image` exposes to the Rust tests so they can pin a shape +// without executing a tile instruction. Kept in sync with the `AMX_CFG_*` +// constants in `simd/amx_fp16.rs`. +#define LANCE_AMX_CFG_SEARCH 0 +#define LANCE_AMX_CFG_GEMM 1 + +// The 64-byte tile configuration image loaded by LDTILECFG +// (`_tile_loadconfig`). Layout per Intel SDM: palette_id, start_row, 14 +// reserved bytes, then a u16 colsb[16] (bytes-per-row) array and a u8 rows[16] +// array. Slots not named by a kernel's spec table stay zero. +// +// 64-byte aligned so the configuration load does not straddle a cache line. +typedef struct __attribute__((packed, aligned(64))) { + uint8_t palette_id; + uint8_t start_row; + uint8_t reserved[14]; + uint16_t colsb[16]; + uint8_t rows[16]; +} lance_amx_tilecfg; + +// The image LDTILECFG reads is exactly 64 bytes; a layout change that altered +// the size would silently feed the instruction garbage. +_Static_assert(sizeof(lance_amx_tilecfg) == 64, + "LDTILECFG image must be exactly 64 bytes"); + +// One tile register's shape. `tmm` is the register index (0..7), `colsb` its +// bytes per row, `rows` its row count. +typedef struct { + uint8_t tmm; + uint8_t rows; + uint16_t colsb; +} lance_amx_tile_spec; + +#define LANCE_AMX_TILE_COUNT(specs) (sizeof(specs) / sizeof((specs)[0])) + +// Fill `cfg` with the LDTILECFG image described by `specs`, without loading it. +// Split from the load so `lance_amx_tilecfg_image` can hand the Rust tests the +// exact bytes a kernel would configure. +static void lance_amx_tilecfg_build(lance_amx_tilecfg *cfg, + const lance_amx_tile_spec *specs, + size_t n) { + memset(cfg, 0, sizeof(*cfg)); + cfg->palette_id = 1; + for (size_t i = 0; i < n; i++) { + cfg->rows[specs[i].tmm] = specs[i].rows; + cfg->colsb[specs[i].tmm] = specs[i].colsb; + } +} + +// Load the tile configuration described by `specs`. Unconditional: see the file +// header for why no state is kept about what is already loaded. +// +// The barrier is not optional: some GCC versions do not model +// _tile_loadconfig as reading the 64-byte cfg image, dead-store-eliminate the +// rows/colsb writes, and load an all-zero (unconfigured) tile shape -> #UD on +// the first tile op (documented in FAISS #5235). Keeping it here, in the one +// function that owns the image, is why kernels do not build configurations +// themselves. Harmless under clang. +static inline void lance_amx_tile_ensure(const lance_amx_tile_spec *specs, + size_t n) { + lance_amx_tilecfg cfg; + lance_amx_tilecfg_build(&cfg, specs, n); + __asm__ volatile("" : : "m"(cfg) : "memory"); + _tile_loadconfig(&cfg); +} + +// Hand the tile unit back at the end of a kernel. Pairs with +// `lance_amx_tile_ensure`, and must run on every exit path of a kernel that +// configured tiles. +// +// Not for Lance's own benefit -- `lance_amx_tile_ensure` reloads on every entry, +// so a stale configuration could never reach one of these kernels either way. It +// is for everyone else on the thread: a live tile configuration keeps 8 KB of +// XTILEDATA in this thread's XSAVE area across every context switch, and leaves +// a shape another AMX user did not ask for sitting on hardware it also uses. +// +// Because it is nobody's correctness but the neighbours', deleting it leaves +// every result right and every "did it crash?" test green. Only +// `lance_amx_tilecfg_current_for_test`, which reads the hardware, notices. +static inline void lance_amx_tile_done(void) { _tile_release(); } + +// Test hook: retire the tile configuration the way a *foreign* AMX user on this +// thread would, so a test can put the tile unit in INIT under a kernel that is +// about to run and check the kernel reconfigures instead of assuming. +// +// Hidden visibility because this manufactures the state the rest of this file +// exists to prevent: it is linked into the crate for its regression test, but is +// not something a shipped shared object should offer to whatever else is in the +// process. +// +// TILERELEASE needs no XTILEDATA grant of its own -- XFD traps only instructions +// that touch a TMM register -- but a test calling this is about to call a kernel +// that does, so it should have gone through `amx_supported()` anyway. +__attribute__((visibility("hidden"))) void lance_amx_tile_clobber_for_test(void) { + _tile_release(); +} + +// Test hook: copy this logical processor's *live* tile configuration into the +// 64 bytes at `out`, via STTILECFG. A `palette_id` of 0 means the tile unit is +// in INIT state -- nothing configured. +// +// This reads the hardware rather than any record Lance keeps, which is what +// makes it able to catch the half of this design that has no other symptom: +// `lance_amx_tile_ensure` reloading on every entry is what keeps results +// correct, so dropping `lance_amx_tile_done`'s release leaves behaviour right +// and every "did it crash?" test passing, and only a live `palette_id` reported +// back here says the tile unit was never handed over. +// +// STTILECFG does not touch a TMM register, so unlike the kernels it is legal +// without the XTILEDATA grant. Hidden for the same reason as the clobber hook. +__attribute__((visibility("hidden"))) void lance_amx_tilecfg_current_for_test( + uint8_t *out) { + lance_amx_tilecfg cfg; + _tile_storeconfig(&cfg); + memcpy(out, &cfg, sizeof(cfg)); +} + +// --------------------------------------------------------------------------- +// Kernel: batch-16 search (one query x 16 candidates) +// --------------------------------------------------------------------------- + +// Tile roles. These are immediate operands of the tile intrinsics, so they must +// be compile-time constants; `#define` rather than `enum` avoids relying on how +// strictly a compiler treats enum constants as immediates. +// +// One TDPFP16PS pass covers K = 32 fp16 dims. With N = 1 the query needs no +// VNNI repacking: B.row[k].fp16[i] = query[k*2 + i] is just the contiguous +// query halfwords, obtained by loading with a 4-byte row stride. The candidates +// form the A tile's rows; they live at unrelated addresses, so this kernel +// stages them a few k-blocks at a time into a fixed-stride scratch buffer that +// the tile load can read (see `lance_amx_stage_rows`). +// +// Three (A, B) pairs, not one. A single pair would make the loop strictly +// serial -- every TDPFP16PS waiting on the two loads that just overwrote its +// own operands -- so the tile unit would idle through each load's latency. +// Three independent pairs let three k-blocks' loads issue before the first +// TDPFP16PS needs its result, which is enough to keep the dp ops back to back. +// Seven tiles is what that costs; tmm7 is left unconfigured. +#define SEARCH_TMM_C 0 // 16 results x 1 fp32 +#define SEARCH_TMM_A0 1 // 16 candidate rows x 32 fp16, k-block 3t +#define SEARCH_TMM_B0 2 // query, VNNI-packed at N = 1, k-block 3t +#define SEARCH_TMM_A1 3 // k-block 3t + 1 +#define SEARCH_TMM_B1 4 +#define SEARCH_TMM_A2 5 // k-block 3t + 2 +#define SEARCH_TMM_B2 6 + +static const lance_amx_tile_spec SEARCH_TILES[] = { + {SEARCH_TMM_C, 16, 4}, {SEARCH_TMM_A0, 16, 64}, {SEARCH_TMM_B0, 16, 4}, + {SEARCH_TMM_A1, 16, 64}, {SEARCH_TMM_B1, 16, 4}, {SEARCH_TMM_A2, 16, 64}, + {SEARCH_TMM_B2, 16, 4}, +}; + +// Halfwords of one k-block: 32 fp16 dims, the K a single TDPFP16PS covers. +#define SEARCH_K_BLOCK 32 + +// Bytes one tile row spans in one k-block: 32 fp16, the A tile's full row width. +#define SEARCH_ROW_BYTES (SEARCH_K_BLOCK * (int)sizeof(uint16_t)) + +// K-blocks gathered per staging step. Three, so one staged buffer feeds exactly +// the three (A, B) pairs the main loop issues together. +#define SEARCH_STAGE_BLOCKS 3 +#define SEARCH_STAGE_ROW_BYTES (SEARCH_STAGE_BLOCKS * SEARCH_ROW_BYTES) + +// One staging buffer: the 16 rows a tile load always reads, whatever the batch +// actually holds. +#define SEARCH_STAGE_BYTES (16 * SEARCH_STAGE_ROW_BYTES) + +// The furthest-reaching tile load is A2: 64 bytes at offset 128 of the last of +// 16 rows, so the last byte it touches is at 128 + 15*192 + 63 and the span it +// covers is exactly SEARCH_STAGE_BYTES. Asserted because an overrun here would +// be a stack smash with no other symptom. +// +// What this actually pins is that the three A tiles tile one staging row with +// no gap and no overlap, i.e. SEARCH_STAGE_BLOCKS == 3; it does not check +// SEARCH_K_BLOCK, nor the 64-byte A-tile width, which is hardcoded separately +// in SEARCH_TILES. +_Static_assert(2 * SEARCH_ROW_BYTES + 15 * SEARCH_STAGE_ROW_BYTES + + SEARCH_ROW_BYTES == + SEARCH_STAGE_BYTES, + "the three A tiles must tile a staging row exactly"); + +// Gather `row_bytes` starting at k-block `kb` out of each of the first `count` +// candidates into `dst`, one candidate per row. +// +// Rows are SEARCH_STAGE_ROW_BYTES apart even when `row_bytes` is smaller: an A +// tile only reads 64 bytes at its own offset within a row, so a wider stride +// simply leaves the trailing bytes unread. Keeping the stride fixed across +// every staging step is what lets rows [count, 16) be zeroed once per call -- +// each step then rewrites the same rows at the same addresses. +// +// The k-blocks a row covers are adjacent inside the candidate vector, so each +// candidate costs exactly one straight-line copy no matter how many k-blocks the +// step covers. `row_bytes` should stay a compile-time constant at every call +// site: a constant size expands to inline wide moves, while a variable one +// becomes a libc `memcpy` call that `-funroll-loops` then multiplies (five PLT +// calls for the one remainder loop, measured under clang-16). +// +// Zeroing the padding rows is deliberately *not* routed through here: it writes +// rows [count, 16) rather than [0, count), and when the rows are full width it +// is one contiguous `memset` rather than a per-row loop. +static inline void lance_amx_stage_rows(uint8_t *dst, + const uint16_t *const *candidates, + size_t count, size_t kb, + size_t row_bytes) { + for (size_t n = 0; n < count; n++) { + memcpy(dst + n * SEARCH_STAGE_ROW_BYTES, + candidates[n] + kb * SEARCH_K_BLOCK, row_bytes); + } +} + +// out[i] = sum_{d in 0..dim} f32(query[d]) * f32(candidates[i][d]), i < count. +// +// `query` -- IEEE-754 binary16 values as raw uint16_t bit patterns +// (half::f16 has identical layout); `dim` valid halfwords. +// `candidates` -- pointers to `dim` halfwords each; only the first `count` are +// read. The vectors live wherever the storage put them; this +// kernel owns the gather. +// `count` -- candidates carrying a real vector. **Precondition: +// 1 <= count <= 16**, rejected at the Rust boundary +// (`dot_f16_batch_16`) rather than clamped here; a larger value +// would run the gather off the end of a staging buffer. +// `dim` -- vector dimension. +// `out` -- destination for 16 fp32 dot products. Lanes [count, 16) are +// written as 0, not left untouched. +// +// ## Why `count` rather than always 16 +// +// The caller sweeps centroids 16 at a time, so when their count is not a +// multiple of 16 the last group is short and it fills the spare slots by +// repeating a row it already holds. Staging all 16 rows would copy that row an +// extra 16 - count times; skipping them saves that much of a memcpy on at most +// one group per sweep, so `count` buys far less here than it did for a caller +// whose batches were usually partial. Only rows [0, count) are gathered, so the +// copying scales with the vectors actually scored while the tile work stays one +// fixed-cost pass. The padded rows still have to exist, since a tile load reads +// 16 rows unconditionally; they are zeroed once per call, and an all-zero A row +// yields a zero dot product. +// +// ## Why the gather is here and not in the caller +// +// A tile load reads 16 rows at one fixed stride from one base pointer, and no +// stride is guaranteed between this kernel's 16 candidate pointers, so their +// bytes have to be brought together somewhere. Doing it in the caller means +// copying 16 * dim * 2 bytes -- 24 KB at dim 768, 32 KB at dim 1024 -- and every +// one of those bytes has to land before the first TDPFP16PS can issue. Against a +// 48 KB L1D that buffer alone is half the cache, and the copy is pure exposed +// latency: nothing overlaps it. +// +// Staging inside the k-block loop instead keeps the working buffer at 3 KB and +// lets the copies for one triple run underneath the tile ops of the previous +// one. The bytes moved are identical; what changes is that they move while the +// tile unit is busy rather than before it starts. (Measured on the caller-side +// version at dim 1024: __memmove 3.7M cycles/query against 0.5M for the scalar +// kernel, IPC 1.70 -> 1.17, and a critical path 18% longer even though total CPU +// work per query was 6.5% lower. The same structure is what +// epeshared/hnswlib-amx uses for its AMX-BF16 kernel.) +// +// For dim > 32 we accumulate across floor(dim/32) tile passes into the same C +// tile, three k-blocks at a time. The tail (dim % 32 dims) is computed in +// scalar fp32 afterwards. The result is NOT bit-exact against a sequential +// scalar loop: floating-point tile-order accumulation rounds differently. It +// matches an f32-accumulated reference dot product to within fp16 precision, +// which is all the fp16 distance path requires (see amx_fp16.rs / the Rust-side +// tests). +void lance_amx_dot_f16_batch_16(const uint16_t *query, + const uint16_t *const *candidates, size_t count, + size_t dim, float *out) { + const size_t blocks = dim / SEARCH_K_BLOCK; // whole 32-wide tile passes + const size_t full = blocks * SEARCH_K_BLOCK; // dims they cover + + if (blocks > 0) { + lance_amx_tile_ensure(SEARCH_TILES, LANCE_AMX_TILE_COUNT(SEARCH_TILES)); + + // Two staging buffers, 16 rows x 192 bytes each. Double buffered so a + // triple's gather can be issued a whole triple before the tile loads that + // read it: a tile load cannot take its data from the store buffer, so the + // gather's stores have to reach L1 first, and with one buffer there is + // nothing to overlap that drain with. 3 KB each, so both sit in L1D + // alongside the candidate rows streaming through it. + __attribute__((aligned(64))) uint8_t stage[2][SEARCH_STAGE_BYTES]; + + const size_t triples = blocks / SEARCH_STAGE_BLOCKS; + const size_t rem = blocks % SEARCH_STAGE_BLOCKS; + + // Rows [count, 16) are padding that a tile load reads but no candidate + // fills, so they are zeroed here and an all-zero A row then contributes a + // zero dot product. Once per call is enough: every staging step below + // writes rows [0, count) only, always at the same row stride, so nothing + // disturbs the padding again. + // + // Only bytes some tile load actually reads are zeroed. This cost is the one + // part of the call that does not shrink with `dim`, so zeroing the full + // 2 x 15 x 192 bytes unconditionally would dominate short vectors: + // * `stage[1]` is tile-loaded only if the main loop reaches a second + // iteration, or the remainder lands on it (an odd `triples`). A single + // triple with no remainder never reads it at all. + // * A padding row is read to its full width only by the main loop. With + // `triples == 0` the remainder is the only reader, and it loads A0 -- + // plus A1 when `rem == 2` -- so only the first `rem` k-block slots of + // each row are ever seen. + if (count < 16) { + const size_t pad_off = count * SEARCH_STAGE_ROW_BYTES; + if (triples > 0) { + // Full-width padding rows are contiguous: one memset covers them all. + memset(stage[0] + pad_off, 0, SEARCH_STAGE_BYTES - pad_off); + if (triples > 1 || rem > 0) { + memset(stage[1] + pad_off, 0, SEARCH_STAGE_BYTES - pad_off); + } + } else { + for (size_t n = count; n < 16; n++) { + memset(stage[0] + n * SEARCH_STAGE_ROW_BYTES, 0, + rem * (size_t)SEARCH_ROW_BYTES); + } + } + } + + _tile_zero(SEARCH_TMM_C); + + // Take ownership of the destination line now (PREFETCHW), so the RFO + // overlaps the tile work instead of stalling TILESTORED at the end. The + // store is 64 bytes issued as one instruction, and waiting on the RFO there + // backs up the store queue: measured on the FAISS #5235 BF16 kernel as + // SQ_Full 28.9% of cycles, with XQ.FULL_CYCLES 56x an AVX-512 baseline. + _mm_prefetch((const char *)out, _MM_HINT_ET0); + + // Prologue of the software pipeline below, and the one gather in the call + // with no tile work ahead of it to hide behind. + if (triples > 0) { + lance_amx_stage_rows(stage[0], candidates, count, 0, + SEARCH_STAGE_ROW_BYTES); + + // The in-loop prefetch below runs two triples ahead, so k-blocks + // [3, 6) -- read by the very first iteration's gather -- would otherwise + // be touched by nothing. Guarded on the address staying inside the + // vectors, which also covers a remainder that follows a single triple. + if (SEARCH_STAGE_BLOCKS < blocks) { + for (size_t n = 0; n < count; n++) { + _mm_prefetch( + (const char *)(candidates[n] + + SEARCH_STAGE_BLOCKS * (size_t)SEARCH_K_BLOCK), + _MM_HINT_T0); + } + } + } + + size_t kb = 0; + for (size_t t = 0; t < triples; t++, kb += SEARCH_STAGE_BLOCKS) { + const uint8_t *st = stage[t & 1]; + + // Gather the *next* triple before issuing this one's tile ops, into the + // buffer the previous iteration's tile loads have already consumed. Those + // stores then have a full triple of tile work to commit to L1 under, + // instead of the tile load immediately below them waiting on the drain. + if (t + 1 < triples) { + // Open the candidate streams the iteration after this one will copy + // from, so that copy finds them resident. With the rows at 16 unrelated + // addresses there is no single stride for a hardware prefetcher to + // latch onto; what it can do is run each candidate forward once that + // candidate has been touched, and these touches are what start it. + // (Measured on the FAISS #5235 BF16 kernel without any prefetch: L1D MPI + // 2.6x and DTLB load MPI 14.6x an AVX-512 baseline.) Guarded so the last + // iterations stay inside the vectors. + if (kb + 2 * SEARCH_STAGE_BLOCKS < blocks) { + const size_t ahead = (kb + 2 * SEARCH_STAGE_BLOCKS) * SEARCH_K_BLOCK; + for (size_t n = 0; n < count; n++) { + _mm_prefetch((const char *)(candidates[n] + ahead), _MM_HINT_T0); + } + } + lance_amx_stage_rows(stage[(t + 1) & 1], candidates, count, + kb + SEARCH_STAGE_BLOCKS, SEARCH_STAGE_ROW_BYTES); + } + + // All six loads first: they are independent, so the three dp ops below + // issue back to back rather than each waiting on its own operands. + _tile_loadd(SEARCH_TMM_A0, st + 0 * SEARCH_ROW_BYTES, + SEARCH_STAGE_ROW_BYTES); + _tile_loadd(SEARCH_TMM_B0, query + kb * SEARCH_K_BLOCK, 4); + _tile_loadd(SEARCH_TMM_A1, st + 1 * SEARCH_ROW_BYTES, + SEARCH_STAGE_ROW_BYTES); + _tile_loadd(SEARCH_TMM_B1, query + (kb + 1) * SEARCH_K_BLOCK, 4); + _tile_loadd(SEARCH_TMM_A2, st + 2 * SEARCH_ROW_BYTES, + SEARCH_STAGE_ROW_BYTES); + _tile_loadd(SEARCH_TMM_B2, query + (kb + 2) * SEARCH_K_BLOCK, 4); + + // C += A * B (fp16 x fp16 -> fp32) + _tile_dpfp16ps(SEARCH_TMM_C, SEARCH_TMM_A0, SEARCH_TMM_B0); + _tile_dpfp16ps(SEARCH_TMM_C, SEARCH_TMM_A1, SEARCH_TMM_B1); + _tile_dpfp16ps(SEARCH_TMM_C, SEARCH_TMM_A2, SEARCH_TMM_B2); + } + + // The 1 or 2 k-blocks left over when `blocks` is not a multiple of three. + // `stage[triples & 1]` is the buffer the loop above neither wrote nor read + // last, so filling it now cannot collide with a tile load still in flight. + if (rem > 0) { + uint8_t *st = stage[triples & 1]; + // Two constant-size cases rather than one `rem * 64` copy, because a + // variable-length memcpy here does not stay one instruction: clang-16 + // emits a libc call and `-funroll-loops` then multiplies it, measured as + // five `memcpy@PLT` calls for this one loop (the pre-`count` kernel, + // whose loop ran to 16, paid sixteen). The main loop's gather is + // unaffected either way -- it keeps its inline wide moves -- so this is + // about the remainder alone. The branch costs one predictable compare. + if (rem == 2) { + lance_amx_stage_rows(st, candidates, count, kb, 2 * SEARCH_ROW_BYTES); + } else { + lance_amx_stage_rows(st, candidates, count, kb, SEARCH_ROW_BYTES); + } + + // Loaded at the main loop's row stride even though only `rem` k-blocks are + // live: A0 and A1 read their own 64 bytes at offsets 0 and 64, which is + // what the staging step just filled, and the padding rows are already zero + // at exactly this stride. + _tile_loadd(SEARCH_TMM_A0, st, SEARCH_STAGE_ROW_BYTES); + _tile_loadd(SEARCH_TMM_B0, query + kb * SEARCH_K_BLOCK, 4); + if (rem == 2) { + _tile_loadd(SEARCH_TMM_A1, st + SEARCH_ROW_BYTES, + SEARCH_STAGE_ROW_BYTES); + _tile_loadd(SEARCH_TMM_B1, query + (kb + 1) * SEARCH_K_BLOCK, 4); + } + _tile_dpfp16ps(SEARCH_TMM_C, SEARCH_TMM_A0, SEARCH_TMM_B0); + if (rem == 2) { + _tile_dpfp16ps(SEARCH_TMM_C, SEARCH_TMM_A1, SEARCH_TMM_B1); + } + } + + _tile_stored(SEARCH_TMM_C, out, 4); // 16 fp32, row stride 4 bytes + // Last tile op in this call; the tail below is scalar. Hands the tile unit + // back so an interleaved AMX user on this thread cannot be surprised by a + // configuration it did not ask for. + lance_amx_tile_done(); + } else { + for (int i = 0; i < 16; i++) out[i] = 0.0f; + } + + // Tail: the dims not covered by a full 32-wide tile, in scalar fp32. F16C + // `_cvtsh_ss` is an exact (lossless) binary16 -> binary32 widening. Lanes at + // or past `count` are skipped rather than accumulated onto: they are already + // 0 (zeroed staging rows, or the no-tile-pass branch above) and must stay so. + const size_t tail = dim - full; + if (tail > 0) { + for (size_t i = 0; i < count; i++) { + float acc = 0.0f; + const uint16_t *row = candidates[i]; + for (size_t d = full; d < dim; d++) { + acc += _cvtsh_ss(row[d]) * _cvtsh_ss(query[d]); + } + out[i] += acc; + } + } +} + +// --------------------------------------------------------------------------- +// Kernel: M x N GEMM (many vectors x many centroids) +// --------------------------------------------------------------------------- + +// Tile roles for the 2x2-register-blocked GEMM. Two A tiles (32 vectors) and +// two B tiles (32 centroids) feed four C accumulators, so one k-pass issues 4 +// TDPFP16PS against 4 tile loads -- the highest compute-per-load ratio the 8 +// physical tiles allow, and the reason all 8 are claimed here. +#define GEMM_TMM_C00 0 // 16 vectors x 16 centroids, fp32 +#define GEMM_TMM_C01 1 +#define GEMM_TMM_C10 2 +#define GEMM_TMM_C11 3 +#define GEMM_TMM_A0 4 // 16 vector rows x 32 fp16 dims +#define GEMM_TMM_A1 5 +#define GEMM_TMM_B0 6 // 32 dims x 16 centroids, VNNI-interleaved +#define GEMM_TMM_B1 7 + +// All eight at the architectural maximum (16 rows x 64 bytes = 1 KB), which is +// exactly the 8 KB of tile state AMX provides. +static const lance_amx_tile_spec GEMM_TILES[] = { + {GEMM_TMM_C00, 16, 64}, {GEMM_TMM_C01, 16, 64}, {GEMM_TMM_C10, 16, 64}, + {GEMM_TMM_C11, 16, 64}, {GEMM_TMM_A0, 16, 64}, {GEMM_TMM_A1, 16, 64}, + {GEMM_TMM_B0, 16, 64}, {GEMM_TMM_B1, 16, 64}, +}; + +// Halfwords per packed B block: 16 tile rows x 32 halfwords per row. +#define GEMM_B_BLOCK 512 + +// out[i*out_stride + j] = sum_{d in 0..dim} f32(data[i*data_stride + d]) * +// f32(centroids[j*dim + d]). +// +// `data` -- [m, dim] row-major fp16 bit patterns, rows `data_stride` +// halfwords apart (`data_stride >= dim`). +// `m` -- number of vectors; **must be a multiple of 32**. +// `packed_b` -- centroids pre-interleaved by `pack_centroids_vnni` (see +// `amx_fp16.rs`), holding only the floor(dim/32) whole +// 32-dim k-blocks. +// `centroids` -- the same [n, dim] row-major centroids `packed_b` was built +// from. Read only for the `dim % 32` tail dims, which are not +// worth a tile pass and so are never packed; still required +// when dim % 32 == 0, where it goes unread. +// `n` -- number of centroids; **must be a multiple of 32**. +// `dim` -- vector dimension; any value, the tail runs scalar. +// `out` -- [m, n] row-major fp32, rows `out_stride` floats apart +// (`out_stride >= n`). +// +// The m and n multiple-of-32 requirements are preconditions, not something this +// kernel checks or works around: they let the register-blocked loop run with no +// edge cases, and the Rust caller is the layer that knows how to pad or split. +// +// The k dimension carries no such requirement. TDPFP16PS accumulation rounds +// differently from a sequential scalar loop, so results match an f32-accumulated +// reference to fp16 precision rather than bit-exactly -- same contract as +// `lance_amx_dot_f16_batch_16`. +// +// B's VNNI interleave is what makes A loadable straight out of `data`: with +// packed_b[((kb*(n/16) + jb)*512) + k*32 + nn*2 + p] +// == centroids[(jb*16 + nn)*dim + kb*32 + 2*k + p] +// TDPFP16PS's b.row[k].fp16[2*nn+p] lands on centroid (jb*16+nn) dim +// (kb*32+2*k+p), pairing it with a.row[mm].fp16[2*k+p] = the same dim of vector +// (i+mm). k-blocks are the outer index so one k-pass reads the two B tiles it +// needs from adjacent memory. +void lance_amx_dot_f16_gemm(const uint16_t *data, size_t m, size_t data_stride, + const uint16_t *packed_b, const uint16_t *centroids, + size_t n, size_t dim, float *out, + size_t out_stride) { + const size_t full = (dim / 32) * 32; // dims covered by full 32-wide passes + + if (full > 0) { + lance_amx_tile_ensure(GEMM_TILES, LANCE_AMX_TILE_COUNT(GEMM_TILES)); + + const size_t a_stride_bytes = data_stride * sizeof(uint16_t); + const size_t c_stride_bytes = out_stride * sizeof(float); + const size_t b_blocks_per_k = n / 16; + + for (size_t i = 0; i < m; i += 32) { + const uint16_t *a0 = data + i * data_stride; + const uint16_t *a1 = a0 + 16 * data_stride; + float *c0 = out + i * out_stride; + float *c1 = c0 + 16 * out_stride; + + for (size_t j = 0; j < n; j += 32) { + _tile_zero(GEMM_TMM_C00); + _tile_zero(GEMM_TMM_C01); + _tile_zero(GEMM_TMM_C10); + _tile_zero(GEMM_TMM_C11); + + for (size_t kbase = 0; kbase < full; kbase += 32) { + // The B tiles for centroid blocks j/16 and j/16+1 are adjacent + // because jb is the inner index of the packed layout. + const uint16_t *b = + packed_b + ((kbase / 32) * b_blocks_per_k + j / 16) * GEMM_B_BLOCK; + _tile_loadd(GEMM_TMM_A0, a0 + kbase, a_stride_bytes); + _tile_loadd(GEMM_TMM_A1, a1 + kbase, a_stride_bytes); + _tile_loadd(GEMM_TMM_B0, b, 64); + _tile_loadd(GEMM_TMM_B1, b + GEMM_B_BLOCK, 64); + _tile_dpfp16ps(GEMM_TMM_C00, GEMM_TMM_A0, GEMM_TMM_B0); + _tile_dpfp16ps(GEMM_TMM_C01, GEMM_TMM_A0, GEMM_TMM_B1); + _tile_dpfp16ps(GEMM_TMM_C10, GEMM_TMM_A1, GEMM_TMM_B0); + _tile_dpfp16ps(GEMM_TMM_C11, GEMM_TMM_A1, GEMM_TMM_B1); + } + + _tile_stored(GEMM_TMM_C00, c0 + j, c_stride_bytes); + _tile_stored(GEMM_TMM_C01, c0 + j + 16, c_stride_bytes); + _tile_stored(GEMM_TMM_C10, c1 + j, c_stride_bytes); + _tile_stored(GEMM_TMM_C11, c1 + j + 16, c_stride_bytes); + } + } + // Last tile op in this call; the tail below is scalar. One LDTILECFG plus + // one TILERELEASE against an m x n GEMM is why the per-call reconfiguration + // the file header argues for costs this kernel nothing. + lance_amx_tile_done(); + } else { + // dim < 32: no tile ever stores to `out`, so the scalar tail below has to + // accumulate onto a known-zero destination rather than whatever was there. + for (size_t i = 0; i < m; i++) { + memset(out + i * out_stride, 0, n * sizeof(float)); + } + } + + const size_t tail = dim - full; + if (tail > 0) { + for (size_t i = 0; i < m; i++) { + // Widen this vector's tail once per row instead of once per (row, + // centroid) pair; `tail` is at most 31 so the buffer is a fixed 32. + float vec_tail[32]; + const uint16_t *row = data + i * data_stride + full; + for (size_t d = 0; d < tail; d++) vec_tail[d] = _cvtsh_ss(row[d]); + + float *out_row = out + i * out_stride; + for (size_t j = 0; j < n; j++) { + const uint16_t *cent = centroids + j * dim + full; + float acc = 0.0f; + for (size_t d = 0; d < tail; d++) acc += vec_tail[d] * _cvtsh_ss(cent[d]); + out_row[j] += acc; + } + } + } +} + +// --------------------------------------------------------------------------- +// Configuration introspection +// --------------------------------------------------------------------------- + +// Write the 64-byte LDTILECFG image for `cfg_kind` (a `LANCE_AMX_CFG_*` +// constant) into `out`, without loading it. Returns 0 on success, -1 for an +// unknown `cfg_kind`. +// +// Exposed so the Rust tests can pin each kernel's tile shape byte for byte. A +// wrong shape does not fail cleanly — it is a #UD or silently wrong results — +// so the shape is asserted directly rather than inferred from kernel output. +int lance_amx_tilecfg_image(int cfg_kind, uint8_t *out) { + const lance_amx_tile_spec *specs; + size_t n; + + switch (cfg_kind) { + case LANCE_AMX_CFG_SEARCH: + specs = SEARCH_TILES; + n = LANCE_AMX_TILE_COUNT(SEARCH_TILES); + break; + case LANCE_AMX_CFG_GEMM: + specs = GEMM_TILES; + n = LANCE_AMX_TILE_COUNT(GEMM_TILES); + break; + default: + return -1; + } + + lance_amx_tilecfg cfg; + lance_amx_tilecfg_build(&cfg, specs, n); + memcpy(out, &cfg, sizeof(cfg)); + return 0; +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.rs b/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.rs new file mode 100644 index 000000000..82a19e399 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/amx_fp16.rs @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! AMX-FP16 accelerated f16 x f16 dot products. +//! +//! Two shapes: `dot_f16_batch_16_amx` (one query against 16 candidates, for +//! choosing the partitions a query probes) and `dot_f16_gemm_amx` (an m x n +//! GEMM, for scoring many vectors against many centroids). Both are named in +//! plain code spans rather than intra-doc links: they are +//! `kernel_support = "amx_fp16"`-gated, so a link from these unconditional +//! module docs is unresolved — and hence a rustdoc error under `-D warnings` — +//! on any build without the kernel. +//! +//! The tile math lives in `amx_fp16.c` (compiled by `build.rs` with a compiler +//! new enough for `-mamx-fp16`, which sets `kernel_support = "amx_fp16"`). This +//! module holds the FFI declarations, the B-operand packing the GEMM's tile +//! layout requires, and the runtime safety gate. Everything here is +//! crate-internal; the safe public entry points are +//! [`crate::distance::dot_f16::dot_f16_batch_16`] for the batch-16 shape and +//! `PackedCentroidsF16` for the GEMM (named, not linked, for the same reason as +//! the kernels above). The latter owns what this layer deliberately does not: +//! padding `n` up to a multiple of 32, holding the packed B operand across +//! calls, and turning the absence of AMX into an `Option` its caller — k-means +//! assignment, in another crate that cannot see `kernel_support` — can branch +//! on. Every kernel here is guarded by +//! [`crate::distance::dot_f16::amx_fp16_supported`], which is also what callers +//! consult before routing work here: one gate, decided by run-time capability +//! alone. +//! +//! ## Safety gate +//! +//! A set CPUID bit is not sufficient to run AMX tile instructions on Linux: +//! the OS must first grant the extended (XTILEDATA) +//! state via `arch_prctl(ARCH_REQ_XCOMP_PERM, XFEATURE_XTILEDATA)`; skipping +//! that SIGILLs the first tile instruction. `amx_supported` requires, and +//! caches process-wide, all of: +//! 1. `target_arch = "x86_64"` and `target_os = "linux"` (compile-time cfg), +//! 2. the amx-tile CPUID bit (leaf 7, sub-leaf 0, EDX bit 24) **and** the +//! amx-fp16 CPUID bit (leaf 7, sub-leaf 1, EAX bit 21), +//! 3. a successful one-time `arch_prctl` permission request. +//! +//! On any failure the caller falls back to the existing AVX-512-FP16 / scalar +//! `f16::dot` path, so results are unchanged (both accumulate in f32; only the +//! summation order — hence fp16-level rounding — differs). +//! +//! ## XTILEDATA is a shared AMX state permission +//! +//! XTILEDATA (component 18) is the single dynamically-enabled XSAVE state +//! backing the physical TMM tile registers; it is requested per-*state*, not +//! per-*instruction*, so one grant covers every AMX compute instruction — see +//! Linux `Documentation/arch/x86/xstate.rst` ("Dynamically Enabled XSAVE +//! Features", AMX example) and Intel SDM Vol.1 §13.3. The syscall is +//! idempotent, so requesting an already-granted permission again is harmless. + +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +use crate::distance::dot_f16::strided_len; +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +use half::f16; + +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +unsafe extern "C" { + /// arch_prctl(ARCH_REQ_XCOMP_PERM, XFEATURE_XTILEDATA); 0 on success. + fn lance_amx_fp16_request_perm() -> i32; + + /// out[i] = sum_d f32(query[d]) * f32(candidates[i][d]), i in 0..count; + /// out[count..16] = 0. `query` is `dim` IEEE binary16 bit patterns; + /// `candidates` is 16 pointers to `dim` of them each, of which only the + /// first `count` (1..=16) are read; `out` holds 16 f32. The kernel gathers + /// the rows itself, k-block by k-block. See `amx_fp16.c`. + fn lance_amx_dot_f16_batch_16( + query: *const u16, + candidates: *const *const u16, + count: usize, + dim: usize, + out: *mut f32, + ); + + /// out[i*out_stride + j] = sum_d f32(data[i*data_stride + d]) * + /// f32(centroids[j*dim + d]), for i in 0..m, j in 0..n. `packed_b` is + /// [`pack_centroids_vnni`]'s output for the same centroids; `centroids` + /// itself is read only for the `dim % 32` unpacked tail dims. `m` and `n` + /// must both be multiples of 32. See `amx_fp16.c`. + fn lance_amx_dot_f16_gemm( + data: *const u16, + m: usize, + data_stride: usize, + packed_b: *const u16, + centroids: *const u16, + n: usize, + dim: usize, + out: *mut f32, + out_stride: usize, + ); + + /// Writes the 64-byte LDTILECFG image for `cfg_kind` into `out` without + /// loading it; 0 on success, -1 for an unknown kind. See `amx_fp16.c`. + #[cfg(test)] + fn lance_amx_tilecfg_image(cfg_kind: i32, out: *mut u8) -> i32; + + /// Retires the tile configuration the way a foreign AMX user sharing this + /// thread would. See `amx_fp16.c`. + #[cfg(test)] + fn lance_amx_tile_clobber_for_test(); + + /// Writes this logical processor's live 64-byte tile configuration to `out` + /// via STTILECFG; `palette_id` (byte 0) is 0 when nothing is configured. + /// See `amx_fp16.c`. + #[cfg(test)] + fn lance_amx_tilecfg_current_for_test(out: *mut u8); +} + +/// Test-only: retire this thread's tile configuration the way another AMX user +/// on the same thread would, leaving the tile unit in INIT under a kernel that +/// is about to run. +/// +/// # Safety +/// Executes TILERELEASE, so [`amx_supported`] must have returned `true` first. +#[cfg(all( + test, + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) unsafe fn clobber_tile_state_for_test() { + unsafe { lance_amx_tile_clobber_for_test() }; +} + +/// Test-only: `true` when a tile configuration is currently live on this logical +/// processor, read straight off the hardware with STTILECFG. +/// +/// This is what distinguishes a working release path from a deleted one. +/// `lance_amx_tile_ensure` reloads on every kernel entry, so results stay right +/// with `lance_amx_tile_done`'s TILERELEASE gone and no "did it crash?" test +/// notices; what is lost is only the promise made to whoever shares the thread, +/// and that is visible nowhere but here. +#[cfg(all( + test, + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) fn tile_config_is_live_for_test() -> bool { + let mut image = [0u8; 64]; + // SAFETY: the C side writes exactly 64 bytes, and STTILECFG touches no TMM + // register so it is legal without the XTILEDATA grant. + unsafe { lance_amx_tilecfg_current_for_test(image.as_mut_ptr()) }; + image[0] != 0 +} + +/// Config kind for [`tilecfg_image`]: the batch-16 search kernel's tile shape. +/// Must match `LANCE_AMX_CFG_SEARCH` in `amx_fp16.c`. +#[cfg(all( + test, + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) const AMX_CFG_SEARCH: i32 = 0; + +/// Config kind for [`tilecfg_image`]: the GEMM kernel's tile shape. +/// Must match `LANCE_AMX_CFG_GEMM` in `amx_fp16.c`. +#[cfg(all( + test, + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) const AMX_CFG_GEMM: i32 = 1; + +/// The 64-byte LDTILECFG image a kernel would configure, without loading it. +/// `None` if `cfg_kind` is not one of the `AMX_CFG_*` constants. +/// +/// Exists for the tests: a wrong tile shape never surfaces as a clean error — +/// it is a #UD or silently wrong results — so the shape is pinned directly +/// rather than inferred from kernel output. +#[cfg(all( + test, + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) fn tilecfg_image(cfg_kind: i32) -> Option<[u8; 64]> { + let mut image = [0u8; 64]; + // SAFETY: the C side writes exactly `sizeof(lance_amx_tilecfg)` bytes, which + // a `_Static_assert` there pins to 64 — the length of `image`. + let rc = unsafe { lance_amx_tilecfg_image(cfg_kind, image.as_mut_ptr()) }; + (rc == 0).then_some(image) +} + +/// True iff AMX-FP16 tile instructions can be executed safely in this process. +/// Evaluated once and cached; the `arch_prctl` permission request (a syscall) +/// happens at most once, process-wide. +/// +/// This is a hardware question only — a pure "would a tile instruction fault +/// here?" — so that kernel-level tests can exercise the kernels on any host +/// that can run them. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) fn amx_supported() -> bool { + static SUPPORTED: std::sync::OnceLock = std::sync::OnceLock::new(); + *SUPPORTED.get_or_init(|| { + if !detect_amx_fp16() { + return false; + } + // Request XTILEDATA permission; without a 0 return, any tile instruction + // would SIGILL, so treat anything else as unavailable. + unsafe { lance_amx_fp16_request_perm() == 0 } + }) +} + +/// AMX-TILE = CPUID leaf 7, sub-leaf 0, EDX bit 24. AMX-FP16 = CPUID leaf 7, +/// sub-leaf 1, EAX bit 21. Both required. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +fn detect_amx_fp16() -> bool { + use std::arch::x86_64::__cpuid_count; + // `__cpuid_count` is safe on nightly but `unsafe` on stable; allow both. + #[allow(unused_unsafe)] + let leaf7_0 = unsafe { __cpuid_count(7, 0) }; + let amx_tile = (leaf7_0.edx & (1 << 24)) != 0; + #[allow(unused_unsafe)] + let leaf7_1 = unsafe { __cpuid_count(7, 1) }; + let amx_fp16 = (leaf7_1.eax & (1 << 21)) != 0; + amx_tile && amx_fp16 +} + +/// Batched AMX-FP16 dot product: one query against the first `len` of 16 +/// candidates. Returns the 16 raw dot products (`Σ query·candidate`, no `1.0 -` +/// distance wrapping); lanes `len..16` are 0. +/// +/// Hands the kernel 16 pointers rather than a packed `16 x dim` buffer. The +/// candidates still have to be brought together for a tile load, but the kernel +/// does it one k-block at a time into 3 KB of stack, which overlaps the copies +/// with the tile ops; packing all `16 * dim * 2` bytes here first could not +/// overlap with anything, and at dim 1024 that is 32 KB against a 48 KB L1D. +/// See the kernel comment in `amx_fp16.c` for the measurements behind this. +/// +/// `len` is what keeps a partial batch cheap: the tile pass is a fixed cost for +/// 16 lanes either way, but only `len` rows are gathered. +/// +/// # Safety +/// `amx_supported` must have returned `true`. `len` must be in `1..=16` — the +/// kernel does not clamp it, and a larger value walks its staging buffer off the +/// end; [`crate::distance::dot_f16::dot_f16_batch_16`] is where that is +/// rejected. Every candidate slice must have length `query.len()`, and must +/// outlive the call. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) unsafe fn dot_f16_batch_16_amx( + query: &[f16], + candidates: &[&[f16]; 16], + len: usize, +) -> [f32; 16] { + debug_assert!((1..=16).contains(&len), "len ({len}) must be in 1..=16"); + let dim = query.len(); + // half::f16 is #[repr(transparent)] over u16, so the casts below reinterpret + // the identical IEEE binary16 bit patterns the kernel expects. All 16 slots + // are filled even though the kernel reads only `len` of them: the caller + // already holds 16 valid slices, so there is nothing to gain from leaving + // the tail of the array undefined. + let mut rows = [std::ptr::null::(); 16]; + for (i, cand) in candidates.iter().enumerate() { + debug_assert_eq!( + cand.len(), + dim, + "candidate {i} length must equal query length" + ); + rows[i] = cand.as_ptr() as *const u16; + } + let mut out = [0f32; 16]; + unsafe { + lance_amx_dot_f16_batch_16( + query.as_ptr() as *const u16, + rows.as_ptr(), + len, + dim, + out.as_mut_ptr(), + ); + } + out +} + +/// Halfwords in one packed B block: 16 tile rows x 32 halfwords per row. +/// Mirrors `GEMM_B_BLOCK` in `amx_fp16.c`. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +const GEMM_B_BLOCK: usize = 512; + +/// Number of `f16` [`pack_centroids_vnni`] writes for `n` centroids of `dim` +/// dims. Only whole 32-dim k-blocks are packed; the `dim % 32` tail is left to +/// the kernel's scalar cleanup, which reads the unpacked centroids directly. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) fn packed_centroids_len(n: usize, dim: usize) -> usize { + (dim / 32) * (n / 16) * GEMM_B_BLOCK +} + +/// Interleave `[n, dim]` row-major `centroids` into the VNNI order +/// [`dot_f16_gemm_amx`]'s B tiles are loaded in, replacing `out`'s contents. +/// +/// The layout is dictated by TDPFP16PS, which reads its B operand as +/// `b.row[k].fp16[2*nn + p]` and pairs it with `a.row[mm].fp16[2*k + p]`. Since +/// A is loaded straight out of the vector buffer — `a.row[mm].fp16[2*k+p]` is +/// dim `kb*32 + 2*k + p` of vector `mm` — B must satisfy +/// +/// ```text +/// out[((kb * (n/16)) + jb) * 512 + k*32 + nn*2 + p] +/// == centroids[(jb*16 + nn) * dim + kb*32 + 2*k + p] +/// ``` +/// +/// with `kb` the 32-dim k-block and `jb` the 16-centroid block. `jb` is the +/// inner index so that the two B tiles a single k-pass consumes are adjacent. +/// +/// `n` must be a multiple of 16 (one B tile covers exactly 16 centroids); +/// `centroids` must hold `n * dim` values. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +pub(crate) fn pack_centroids_vnni(centroids: &[f16], n: usize, dim: usize, out: &mut Vec) { + debug_assert_eq!(n % 16, 0, "n ({n}) must be a multiple of 16"); + debug_assert_eq!( + centroids.len(), + n * dim, + "centroids must hold n*dim = {} values", + n * dim + ); + out.clear(); + out.reserve(packed_centroids_len(n, dim)); + for kb in 0..dim / 32 { + for jb in 0..n / 16 { + for k in 0..16 { + for nn in 0..16 { + for p in 0..2 { + out.push(centroids[(jb * 16 + nn) * dim + kb * 32 + 2 * k + p]); + } + } + } + } + } +} + +/// AMX-FP16 `[m, dim] x [n, dim]^T -> [m, n]` dot-product GEMM: scores every +/// row of `data` against every centroid, writing raw dot products (no distance +/// wrapping) into `out`. +/// +/// `packed_b` must come from [`pack_centroids_vnni`] over the same `centroids`, +/// `n` and `dim`; `centroids` is additionally passed through because the +/// `dim % 32` tail dims are not packed and the kernel finishes them in scalar +/// fp32. Rows of `data` are `data_stride` halfwords apart and rows of `out` are +/// `out_stride` floats apart, so a caller can hand over a window of a larger +/// buffer without copying. +/// +/// Accuracy matches [`dot_f16_batch_16_amx`]'s contract: f32-accumulated to +/// within fp16 precision, not bit-exact against a sequential scalar loop. +/// +/// # Safety +/// * [`crate::distance::dot_f16::amx_fp16_supported`] must have returned `true`. +/// * `m % 32 == 0` and `n % 32 == 0`. The kernel has no edge-case path for +/// partial tiles and would read and write past the ends of its buffers. +/// * `data_stride >= dim` and `out_stride >= n`, and the slices must be long +/// enough for the last row those strides reach. +#[cfg(all( + kernel_support = "amx_fp16", + target_arch = "x86_64", + target_os = "linux" +))] +#[allow(clippy::too_many_arguments)] +pub(crate) unsafe fn dot_f16_gemm_amx( + data: &[f16], + m: usize, + data_stride: usize, + packed_b: &[f16], + centroids: &[f16], + n: usize, + dim: usize, + out: &mut [f32], + out_stride: usize, +) { + debug_assert_eq!(m % 32, 0, "m ({m}) must be a multiple of 32"); + debug_assert_eq!(n % 32, 0, "n ({n}) must be a multiple of 32"); + debug_assert!( + data_stride >= dim, + "data_stride ({data_stride}) < dim ({dim})" + ); + debug_assert!(out_stride >= n, "out_stride ({out_stride}) < n ({n})"); + // Through `strided_len` rather than inline arithmetic, for the same reason + // the safe caller uses it: `(m - 1) * stride + row_len` wraps in release + // builds, and a wrapped requirement is small enough to satisfy the very + // check it was computed for. These are `debug_assert`s restating a contract + // the caller already enforced, but they should fail loudly on the + // overflowing shape rather than quietly agree with it. + debug_assert!( + strided_len(m, data_stride, dim).is_some_and(|need| data.len() >= need), + "data too short" + ); + debug_assert!( + strided_len(m, out_stride, n).is_some_and(|need| out.len() >= need), + "out too short" + ); + debug_assert_eq!( + Some(centroids.len()), + n.checked_mul(dim), + "centroids must hold n*dim values" + ); + debug_assert_eq!( + packed_b.len(), + packed_centroids_len(n, dim), + "packed_b must be pack_centroids_vnni's output for this n and dim" + ); + // half::f16 is #[repr(transparent)] over u16, so these casts reinterpret the + // identical IEEE binary16 bit patterns the kernel expects. + unsafe { + lance_amx_dot_f16_gemm( + data.as_ptr() as *const u16, + m, + data_stride, + packed_b.as_ptr() as *const u16, + centroids.as_ptr() as *const u16, + n, + dim, + out.as_mut_ptr(), + out_stride, + ); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/bf16.c b/rust/lancedb/vendor/lance-linalg/src/simd/bf16.c new file mode 100644 index 000000000..cfbe5dee9 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/bf16.c @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +#include +#include +#include +#include + +// Because we might be compiling this library multiple times, we need to +// add a suffix to each of the function names. +#define FUNC_CAT_INNER(A, B) A##B +#define FUNC_CAT(A, B) FUNC_CAT_INNER(A, B) +#define FUNC(N) FUNC_CAT(N, SUFFIX) + +// Convert a bf16 value (stored as uint16_t) to float32. +// BF16 is the upper 16 bits of an IEEE 754 float32, so we just shift left. +static inline float bf16_to_f32(uint16_t v) { + uint32_t bits = (uint32_t)v << 16; + float f; + memcpy(&f, &bits, sizeof(f)); + return f; +} + +float FUNC(norm_l2_bf16)(const uint16_t *data, uint32_t dimension) { + float sum = 0; + +#pragma clang loop unroll(enable) vectorize(enable) interleave(enable) + for (uint32_t i = 0; i < dimension; i++) { + float v = bf16_to_f32(data[i]); + sum += v * v; + } + return sqrtf(sum); +} + +/// @brief Dot product of two bf16 vectors. +/// @param x A bf16 vector (stored as uint16_t) +/// @param y A bf16 vector (stored as uint16_t) +/// @param dimension The dimension of the vectors +/// @return The dot product of the two vectors. +float FUNC(dot_bf16)(const uint16_t *x, const uint16_t *y, uint32_t dimension) { + float sum = 0; + +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + sum += bf16_to_f32(x[i]) * bf16_to_f32(y[i]); + } + return sum; +} + +float FUNC(l2_bf16)(const uint16_t *x, const uint16_t *y, uint32_t dimension) { + float sum = 0.0; + +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + float s = bf16_to_f32(x[i]) - bf16_to_f32(y[i]); + sum += s * s; + } + return sum; +} + +float FUNC(cosine_bf16)(const uint16_t *x, float x_norm, const uint16_t *y, uint32_t dimension) { + float dot = 0.0; + float l2_y = 0.0; + + // Combine the loop to reduce overhead of the bf16 to fp32 conversion. +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + float y_i = bf16_to_f32(y[i]); + dot += bf16_to_f32(x[i]) * y_i; + l2_y += y_i * y_i; + } + + return 1.0 - dot / (x_norm * sqrtf(l2_y)); +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.c b/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.c new file mode 100644 index 000000000..e8be8e520 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.c @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +#include +#include +#include + +void sum_4bit_dist_table_32bytes_batch_avx512(const uint8_t *codes, + size_t code_length, + const uint8_t *dist_table, + uint16_t *dists) { + __m512i c; + __m512i lo; + __m512i hi; + __m512i lut; + __m512i res_lo; + __m512i res_hi; + + const __m512i lo_mask = _mm512_set1_epi8(0x0f); + __m512i accu0 = _mm512_setzero_si512(); + __m512i accu1 = _mm512_setzero_si512(); + __m512i accu2 = _mm512_setzero_si512(); + __m512i accu3 = _mm512_setzero_si512(); + + for (size_t i = 0; i < code_length; i += 64) { + const size_t remaining = code_length - i; + if (remaining >= 64) { + c = _mm512_loadu_si512(&codes[i]); + lut = _mm512_loadu_si512(&dist_table[i]); + } else { + const __mmask64 load_mask = (UINT64_C(1) << remaining) - 1; + c = _mm512_maskz_loadu_epi8(load_mask, &codes[i]); + lut = _mm512_maskz_loadu_epi8(load_mask, &dist_table[i]); + } + lo = _mm512_and_si512(c, lo_mask); + hi = _mm512_and_si512(_mm512_srli_epi16(c, 4), lo_mask); + + res_lo = _mm512_shuffle_epi8(lut, lo); + res_hi = _mm512_shuffle_epi8(lut, hi); + + accu0 = _mm512_add_epi16(accu0, res_lo); + accu1 = _mm512_add_epi16(accu1, _mm512_srli_epi16(res_lo, 8)); + accu2 = _mm512_add_epi16(accu2, res_hi); + accu3 = _mm512_add_epi16(accu3, _mm512_srli_epi16(res_hi, 8)); + } + + accu0 = _mm512_sub_epi16(accu0, _mm512_slli_epi16(accu1, 8)); + accu2 = _mm512_sub_epi16(accu2, _mm512_slli_epi16(accu3, 8)); + + __m512i ret1 = _mm512_add_epi16(_mm512_mask_blend_epi64(0xF0, accu0, accu1), + _mm512_shuffle_i64x2(accu0, accu1, 0x4E)); + __m512i ret2 = _mm512_add_epi16(_mm512_mask_blend_epi64(0xF0, accu2, accu3), + _mm512_shuffle_i64x2(accu2, accu3, 0x4E)); + __m512i ret = _mm512_setzero_si512(); + + ret = _mm512_add_epi16(ret, _mm512_shuffle_i64x2(ret1, ret2, 0x88)); + ret = _mm512_add_epi16(ret, _mm512_shuffle_i64x2(ret1, ret2, 0xDD)); + + _mm512_storeu_si512(dists, ret); +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.rs b/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.rs new file mode 100644 index 000000000..fe52ff096 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/dist_table.rs @@ -0,0 +1,3154 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +#[cfg(target_arch = "aarch64")] +use std::arch::aarch64::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; +use std::mem::MaybeUninit; + +pub const PERM0: [usize; 16] = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15]; +pub const PERM0_INVERSE: [usize; 16] = [0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15]; +pub const BATCH_SIZE: usize = 32; +/// A row sums `2 * code_len` table entries into a `u16`, so a full-range +/// (`0..=u8::MAX`) table fits only up to here: `2 * 128 * u8::MAX == 65280`. +/// Callers that cannot cap their table must use [`sum_4bit_dist_table_u32`]. +pub const SAFE_U16_CODE_LEN: usize = 128; + +/// Sums row-major 4-bit codes into `u16`s: `(codes, dist_table, code_len, +/// dists)` sums `dists.len()` rows, a multiple of [`BATCH_SIZE`], and +/// initializes every slot of `dists`. +type SumU16Fn = unsafe fn(&[u8], &[u8], usize, &mut [MaybeUninit]); + +lance_core::dispatch! { + static SUM_U16: Dispatch = { + #[cfg(all(target_arch = "x86_64", kernel_support = "avx512_dist_table"))] + { + &[SUM_U16_AVX512, SUM_U16_AVX2, SUM_U16_SCALAR] + } + #[cfg(all(target_arch = "x86_64", not(kernel_support = "avx512_dist_table")))] + { + &[SUM_U16_AVX2, SUM_U16_SCALAR] + } + #[cfg(target_arch = "aarch64")] + { + &[SUM_U16_NEON, SUM_U16_SCALAR] + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + &[SUM_U16_SCALAR] + } + }; +} + +/// [`SumU16Fn`] for the high-accuracy table, which holds `64` bytes per code +/// byte and sums into `u32`s. +type SumHaccFn = unsafe fn(&[u8], &[u8], usize, &mut [MaybeUninit]); + +lance_core::dispatch! { + static SUM_HACC: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[SUM_HACC_AVX2, SUM_HACC_SCALAR] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[SUM_HACC_SCALAR] + } + }; +} + +/// Checks the bounds the row-major kernels rely on to sum `n` rows. Products +/// are checked: a wrapped one would let short slices past the unchecked pointer +/// arithmetic of the SIMD kernels. +#[inline] +fn assert_row_major_bounds( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + table_bytes_per_code: usize, +) { + assert!( + n.is_multiple_of(BATCH_SIZE), + "n = {n} is not a multiple of {BATCH_SIZE}" + ); + assert!( + n.checked_mul(code_len) + .is_some_and(|needed| codes.len() >= needed), + "codes has {} bytes, fewer than n * code_len = {n} * {code_len}", + codes.len() + ); + assert!( + code_len + .checked_mul(table_bytes_per_code) + .is_some_and(|needed| dist_table.len() >= needed), + "dist_table has {} bytes, fewer than {table_bytes_per_code} * code_len = \ + {table_bytes_per_code} * {code_len}", + dist_table.len() + ); +} + +// This function is used to sum the distance table for 4-bit codes. +// the distance table is a 2D array, that dist_table[i][j] is the distance between the i-th subvector and the code j, +// the distance table is stored as a flat array for better cache locality and SIMD instruction usage. +// +// The codes are organized in the order of PERM0: +// +----------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ +// | address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | +// | (bytes) | | | | | | | | | | | | | | | | | +// +----------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ +// | bits 0..3| 0 | 8 | 1 | 9 | 2 | 10 | 3 | 11 | 4 | 12 | 5 | 13 | 6 | 14 | 7 | 15 | +// | bits 4..7| 16 | 24 | 17 | 25 | 18 | 26 | 19 | 27 | 20 | 28 | 21 | 29 | 22 | 30 | 23 | 31 | +// +----------+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ +// so that we can use SIMD instruction (especially _mm256_shuffle_epi8) to do the summation. +// The accumulator is `u16`: see [`SAFE_U16_CODE_LEN`] for what that costs the caller. +#[inline] +pub fn sum_4bit_dist_table( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + // A `u16` slice is also a valid `MaybeUninit` slice. The dispatched + // kernels overwrite every output slot. + let dists = unsafe { + std::slice::from_raw_parts_mut(dists.as_mut_ptr().cast::>(), dists.len()) + }; + sum_4bit_dist_table_uninit(n, code_len, codes, dist_table, dists); +} + +/// Sum a 4-bit distance table into potentially uninitialized output storage. +/// +/// Every element in `dists[..n]` is initialized before this function returns. +/// +/// # Panics +/// +/// Unless `n` is a multiple of [`BATCH_SIZE`], `codes` holds at least +/// `n * code_len` bytes, `dist_table` at least `BATCH_SIZE * code_len` bytes +/// and `dists` at least `n` slots. +#[inline] +pub fn sum_4bit_dist_table_uninit( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + SUM_U16 + .get() + .call(codes, dist_table, code_len, &mut dists[..n]); +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(SUM_U16_SCALAR: SumU16Fn)] + fn sum_u16_scalar( + codes: &[u8], + dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, dist_table, BATCH_SIZE); + dists.fill(MaybeUninit::new(0)); + // Every slot was initialized immediately above. + let dists = unsafe { std::slice::from_raw_parts_mut(dists.as_mut_ptr().cast::(), n) }; + sum_4bit_dist_table_scalar(code_len, &codes[..n * code_len], dist_table, dists); + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(SUM_U16_AVX2: SumU16Fn)] + fn sum_u16_avx2( + codes: &[u8], + dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, dist_table, BATCH_SIZE); + for i in (0..n).step_by(BATCH_SIZE) { + // The bounds asserted above cover every load of the batch. + unsafe { + sum_dist_table_32bytes_batch_avx2( + &codes[i * code_len..(i + BATCH_SIZE) * code_len], + dist_table, + &mut dists[i..i + BATCH_SIZE], + ) + } + } + } +} + +// The C object adds only `-mavx512f -mavx512bw` to the build's baseline +// target (see build.rs). +#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_dist_table"))] +lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw")] + #[candidate(SUM_U16_AVX512: SumU16Fn)] + fn sum_u16_avx512( + codes: &[u8], + dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, dist_table, BATCH_SIZE); + for i in (0..n).step_by(BATCH_SIZE) { + let codes = &codes[i * code_len..(i + BATCH_SIZE) * code_len]; + // The kernel reads `codes.len()` bytes of the codes and of the + // table, whose bounds are asserted above, and stores 32 outputs. + unsafe { + sum_4bit_dist_table_32bytes_batch_avx512( + codes.as_ptr(), + codes.len(), + dist_table.as_ptr(), + dists[i..i + BATCH_SIZE].as_mut_ptr().cast::(), + ) + } + } + } +} + +#[cfg(target_arch = "aarch64")] +lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(SUM_U16_NEON: SumU16Fn)] + fn sum_u16_neon( + codes: &[u8], + dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, dist_table, BATCH_SIZE); + for i in (0..n).step_by(BATCH_SIZE) { + // The bounds asserted above cover every load of the batch. + unsafe { + sum_dist_table_32bytes_batch_neon( + &codes[i * code_len..(i + BATCH_SIZE) * code_len], + dist_table, + &mut dists[i..i + BATCH_SIZE], + ) + } + } + } +} + +#[inline] +#[allow(unused)] +pub fn sum_4bit_dist_table_scalar( + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let num_full_vectors = codes.len() / (BATCH_SIZE * code_len) * BATCH_SIZE; + dists[..num_full_vectors].fill(0); + + for (vec_block_idx, blocks) in codes.chunks_exact(BATCH_SIZE * code_len).enumerate() { + for (sub_vec_idx, block) in blocks.as_chunks::().0.iter().enumerate() { + let current_dist_table = &dist_table[sub_vec_idx * 2 * 16..(sub_vec_idx * 2 + 1) * 16]; + let next_dist_table = + &dist_table[(sub_vec_idx * 2 + 1) * 16..(sub_vec_idx * 2 + 2) * 16]; + + for j in 0..16 { + let low_current_code = (block[j] & 0x0F) as usize; + let high_current_code = (block[j] >> 4) as usize; + let low_next_code = (block[j + 16] & 0x0F) as usize; + let high_next_code = (block[j + 16] >> 4) as usize; + + let lower_id = vec_block_idx * BATCH_SIZE + PERM0[j]; + let higher_id = vec_block_idx * BATCH_SIZE + PERM0[j] + 16; + dists[lower_id] = dists[lower_id] + .saturating_add(current_dist_table[low_current_code] as u16) + .saturating_add(next_dist_table[low_next_code] as u16); + dists[higher_id] = dists[higher_id] + .saturating_add(current_dist_table[high_current_code] as u16) + .saturating_add(next_dist_table[high_next_code] as u16); + } + } + } +} + +/// [`sum_4bit_dist_table`] with an accumulator wide enough for any `code_len`: +/// the codes are summed in chunks of [`SAFE_U16_CODE_LEN`] through the same +/// `u16` kernels, and each chunk is widened into the output. +#[inline] +pub fn sum_4bit_dist_table_u32( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u32], +) { + // A `u32` slice is also a valid `MaybeUninit` slice. The chunk loop + // overwrites every output slot. + let dists = unsafe { + std::slice::from_raw_parts_mut(dists.as_mut_ptr().cast::>(), dists.len()) + }; + sum_4bit_dist_table_u32_uninit(n, code_len, codes, dist_table, dists); +} + +/// Sum a 4-bit distance table into potentially uninitialized `u32` output. +/// +/// Every element in `dists[..n]` is initialized before this function returns. +/// +/// # Panics +/// +/// Unless `n` is a multiple of [`BATCH_SIZE`], `codes` holds at least +/// `n * code_len` bytes, `dist_table` at least `BATCH_SIZE * code_len` bytes +/// and `dists` at least `n` slots. +#[inline] +pub fn sum_4bit_dist_table_u32_uninit( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + // The chunk kernels check only their own chunk, so the whole input is + // checked here for a clear panic. + assert_row_major_bounds(n, code_len, codes, dist_table, BATCH_SIZE); + let dists = &mut dists[..n]; + + if code_len == 0 { + dists.fill(MaybeUninit::new(0)); + return; + } + + let sum_u16 = SUM_U16.get(); + for i in (0..n).step_by(BATCH_SIZE) { + let batch_codes = &codes[i * code_len..(i + BATCH_SIZE) * code_len]; + let mut sums = [0u32; BATCH_SIZE]; + for chunk_start in (0..code_len).step_by(SAFE_U16_CODE_LEN) { + let chunk_end = (chunk_start + SAFE_U16_CODE_LEN).min(code_len); + // Bytes are grouped by sub-vector, so one range slices both arrays. + let bytes = chunk_start * BATCH_SIZE..chunk_end * BATCH_SIZE; + let mut chunk_dists = [MaybeUninit::::uninit(); BATCH_SIZE]; + sum_u16.call( + &batch_codes[bytes.clone()], + &dist_table[bytes], + chunk_end - chunk_start, + &mut chunk_dists, + ); + // The dispatched kernel initialized every chunk output slot. + let chunk_dists = unsafe { + std::slice::from_raw_parts(chunk_dists.as_ptr().cast::(), BATCH_SIZE) + }; + sums.iter_mut() + .zip(chunk_dists.iter()) + .for_each(|(sum, chunk_dist)| *sum += *chunk_dist as u32); + } + dists[i..i + BATCH_SIZE] + .iter_mut() + .zip(sums.iter()) + .for_each(|(dist, sum)| { + dist.write(*sum); + }); + } +} + +#[inline] +#[allow(unused)] +pub fn sum_4bit_dist_table_u16( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u16], + dists: &mut [u32], +) { + debug_assert!(n.is_multiple_of(BATCH_SIZE)); + debug_assert!(dists.len() >= n); + debug_assert!(codes.len() >= n * code_len); + sum_4bit_dist_table_u16_scalar( + code_len, + &codes[..n * code_len], + dist_table, + &mut dists[..n], + ); +} + +#[inline] +pub fn transfer_4bit_dist_table_u16(dist_table: &[u16], hacc_dist_table: &mut Vec) { + debug_assert!(dist_table.len().is_multiple_of(32)); + + let num_tables = dist_table.len() / 16; + hacc_dist_table.clear(); + hacc_dist_table.resize(dist_table.len() * 2, 0); + + for table_idx in 0..num_tables { + let table = &dist_table[table_idx * 16..(table_idx + 1) * 16]; + let low_offset = (table_idx / 2) * 64 + (table_idx % 2) * 16; + let high_offset = low_offset + 32; + for (code, value) in table.iter().enumerate() { + hacc_dist_table[low_offset + code] = *value as u8; + hacc_dist_table[high_offset + code] = (value >> 8) as u8; + } + } +} + +#[inline] +pub fn sum_4bit_hacc_dist_table( + n: usize, + code_len: usize, + codes: &[u8], + hacc_dist_table: &[u8], + dists: &mut [u32], +) { + // A `u32` slice is also a valid `MaybeUninit` slice. The dispatched + // kernels overwrite every output slot. + let dists = unsafe { + std::slice::from_raw_parts_mut(dists.as_mut_ptr().cast::>(), dists.len()) + }; + sum_4bit_hacc_dist_table_uninit(n, code_len, codes, hacc_dist_table, dists); +} + +/// Sum a high-accuracy 4-bit distance table into uninitialized output storage. +/// +/// Every element in `dists[..n]` is initialized before this function returns. +/// +/// # Panics +/// +/// Unless `n` is a multiple of [`BATCH_SIZE`], `codes` holds at least +/// `n * code_len` bytes, `hacc_dist_table` at least `code_len * 64` bytes and +/// `dists` at least `n` slots. +#[inline] +pub fn sum_4bit_hacc_dist_table_uninit( + n: usize, + code_len: usize, + codes: &[u8], + hacc_dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + SUM_HACC + .get() + .call(codes, hacc_dist_table, code_len, &mut dists[..n]); +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(SUM_HACC_SCALAR: SumHaccFn)] + fn sum_hacc_scalar( + codes: &[u8], + hacc_dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, hacc_dist_table, 64); + dists.fill(MaybeUninit::new(0)); + // Every slot was initialized immediately above. + let dists = unsafe { std::slice::from_raw_parts_mut(dists.as_mut_ptr().cast::(), n) }; + sum_4bit_hacc_dist_table_scalar(code_len, &codes[..n * code_len], hacc_dist_table, dists); + } +} + +#[inline] +#[allow(unused)] +pub fn sum_4bit_hacc_dist_table_scalar( + code_len: usize, + codes: &[u8], + hacc_dist_table: &[u8], + dists: &mut [u32], +) { + let num_full_vectors = codes.len() / (BATCH_SIZE * code_len) * BATCH_SIZE; + dists[..num_full_vectors].fill(0); + + for (vec_block_idx, blocks) in codes.chunks_exact(BATCH_SIZE * code_len).enumerate() { + for (sub_vec_idx, block) in blocks.as_chunks::().0.iter().enumerate() { + let table_offset = sub_vec_idx * 64; + let current_low = &hacc_dist_table[table_offset..table_offset + 16]; + let next_low = &hacc_dist_table[table_offset + 16..table_offset + 32]; + let current_high = &hacc_dist_table[table_offset + 32..table_offset + 48]; + let next_high = &hacc_dist_table[table_offset + 48..table_offset + 64]; + + for j in 0..16 { + let low_current_code = (block[j] & 0x0F) as usize; + let high_current_code = (block[j] >> 4) as usize; + let low_next_code = (block[j + 16] & 0x0F) as usize; + let high_next_code = (block[j + 16] >> 4) as usize; + + let lower_id = vec_block_idx * BATCH_SIZE + PERM0[j]; + let higher_id = lower_id + 16; + dists[lower_id] += ((current_high[low_current_code] as u32) << 8) + + current_low[low_current_code] as u32 + + ((next_high[low_next_code] as u32) << 8) + + next_low[low_next_code] as u32; + dists[higher_id] += ((current_high[high_current_code] as u32) << 8) + + current_low[high_current_code] as u32 + + ((next_high[high_next_code] as u32) << 8) + + next_low[high_next_code] as u32; + } + } + } +} + +#[inline] +#[allow(unused)] +pub fn sum_4bit_dist_table_u16_scalar( + code_len: usize, + codes: &[u8], + dist_table: &[u16], + dists: &mut [u32], +) { + let num_full_vectors = codes.len() / (BATCH_SIZE * code_len) * BATCH_SIZE; + dists[..num_full_vectors].fill(0); + + for (vec_block_idx, blocks) in codes.chunks_exact(BATCH_SIZE * code_len).enumerate() { + for (sub_vec_idx, block) in blocks.as_chunks::().0.iter().enumerate() { + let current_dist_table = &dist_table[sub_vec_idx * 2 * 16..(sub_vec_idx * 2 + 1) * 16]; + let next_dist_table = + &dist_table[(sub_vec_idx * 2 + 1) * 16..(sub_vec_idx * 2 + 2) * 16]; + + for j in 0..16 { + let low_current_code = (block[j] & 0x0F) as usize; + let high_current_code = (block[j] >> 4) as usize; + let low_next_code = (block[j + 16] & 0x0F) as usize; + let high_next_code = (block[j + 16] >> 4) as usize; + + let lower_id = vec_block_idx * BATCH_SIZE + PERM0[j]; + let higher_id = lower_id + 16; + dists[lower_id] += current_dist_table[low_current_code] as u32 + + next_dist_table[low_next_code] as u32; + dists[higher_id] += current_dist_table[high_current_code] as u32 + + next_dist_table[high_next_code] as u32; + } + } + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(SUM_HACC_AVX2: SumHaccFn)] + fn sum_hacc_avx2( + codes: &[u8], + hacc_dist_table: &[u8], + code_len: usize, + dists: &mut [MaybeUninit], + ) { + let n = dists.len(); + assert_row_major_bounds(n, code_len, codes, hacc_dist_table, 64); + for i in (0..n).step_by(BATCH_SIZE) { + let batch_codes = &codes[i * code_len..(i + BATCH_SIZE) * code_len]; + let batch_dists = &mut dists[i..i + BATCH_SIZE]; + + if code_len == 0 { + batch_dists.fill(MaybeUninit::new(0)); + continue; + } + + for code_start in (0..code_len).step_by(SAFE_U16_CODE_LEN) { + let code_end = (code_start + SAFE_U16_CODE_LEN).min(code_len); + let code_range = code_start * BATCH_SIZE..code_end * BATCH_SIZE; + let table_range = code_start * 64..code_end * 64; + if code_start == 0 { + // The bounds asserted above cover every load of the chunk. + unsafe { + sum_hacc_dist_table_32bytes_batch_avx2( + &batch_codes[code_range], + &hacc_dist_table[table_range], + batch_dists, + ); + } + } else { + let mut chunk_dists = [MaybeUninit::::uninit(); BATCH_SIZE]; + unsafe { + sum_hacc_dist_table_32bytes_batch_avx2( + &batch_codes[code_range], + &hacc_dist_table[table_range], + &mut chunk_dists, + ); + } + // The kernel above initializes every temporary output slot. + let chunk_dists = unsafe { + std::slice::from_raw_parts(chunk_dists.as_ptr().cast::(), BATCH_SIZE) + }; + // The first code chunk initialized every output slot. + let batch_dists = unsafe { + std::slice::from_raw_parts_mut( + batch_dists.as_mut_ptr().cast::(), + BATCH_SIZE, + ) + }; + batch_dists + .iter_mut() + .zip(chunk_dists.iter()) + .for_each(|(dist, chunk_dist)| *dist += *chunk_dist); + } + } + } + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +#[allow(unused)] +unsafe fn sum_hacc_dist_table_32bytes_batch_avx2( + codes: &[u8], + hacc_dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + let low_mask = _mm256_set1_epi8(0x0f); + let mut low_accu0 = _mm256_setzero_si256(); + let mut low_accu1 = _mm256_setzero_si256(); + let mut low_accu2 = _mm256_setzero_si256(); + let mut low_accu3 = _mm256_setzero_si256(); + let mut high_accu0 = _mm256_setzero_si256(); + let mut high_accu1 = _mm256_setzero_si256(); + let mut high_accu2 = _mm256_setzero_si256(); + let mut high_accu3 = _mm256_setzero_si256(); + + for code_offset in (0..codes.len()).step_by(BATCH_SIZE) { + let table_offset = code_offset * 2; + let c = _mm256_loadu_si256(codes.as_ptr().add(code_offset) as *const __m256i); + let lo = _mm256_and_si256(c, low_mask); + let hi = _mm256_and_si256(_mm256_srli_epi16(c, 4), low_mask); + + let low_lut = + _mm256_loadu_si256(hacc_dist_table.as_ptr().add(table_offset) as *const __m256i); + let low_res_lo = _mm256_shuffle_epi8(low_lut, lo); + let low_res_hi = _mm256_shuffle_epi8(low_lut, hi); + low_accu0 = _mm256_add_epi16(low_accu0, low_res_lo); + low_accu1 = _mm256_add_epi16(low_accu1, _mm256_srli_epi16(low_res_lo, 8)); + low_accu2 = _mm256_add_epi16(low_accu2, low_res_hi); + low_accu3 = _mm256_add_epi16(low_accu3, _mm256_srli_epi16(low_res_hi, 8)); + + let high_lut = + _mm256_loadu_si256(hacc_dist_table.as_ptr().add(table_offset + 32) as *const __m256i); + let high_res_lo = _mm256_shuffle_epi8(high_lut, lo); + let high_res_hi = _mm256_shuffle_epi8(high_lut, hi); + high_accu0 = _mm256_add_epi16(high_accu0, high_res_lo); + high_accu1 = _mm256_add_epi16(high_accu1, _mm256_srli_epi16(high_res_lo, 8)); + high_accu2 = _mm256_add_epi16(high_accu2, high_res_hi); + high_accu3 = _mm256_add_epi16(high_accu3, _mm256_srli_epi16(high_res_hi, 8)); + } + + low_accu0 = _mm256_sub_epi16(low_accu0, _mm256_slli_epi16(low_accu1, 8)); + let low_dis0 = _mm256_add_epi16( + _mm256_permute2f128_si256(low_accu0, low_accu1, 0x21), + _mm256_blend_epi32(low_accu0, low_accu1, 0xF0), + ); + low_accu2 = _mm256_sub_epi16(low_accu2, _mm256_slli_epi16(low_accu3, 8)); + let low_dis1 = _mm256_add_epi16( + _mm256_permute2f128_si256(low_accu2, low_accu3, 0x21), + _mm256_blend_epi32(low_accu2, low_accu3, 0xF0), + ); + + high_accu0 = _mm256_sub_epi16(high_accu0, _mm256_slli_epi16(high_accu1, 8)); + let high_dis0 = _mm256_add_epi16( + _mm256_permute2f128_si256(high_accu0, high_accu1, 0x21), + _mm256_blend_epi32(high_accu0, high_accu1, 0xF0), + ); + high_accu2 = _mm256_sub_epi16(high_accu2, _mm256_slli_epi16(high_accu3, 8)); + let high_dis1 = _mm256_add_epi16( + _mm256_permute2f128_si256(high_accu2, high_accu3, 0x21), + _mm256_blend_epi32(high_accu2, high_accu3, 0xF0), + ); + + let low0 = _mm256_cvtepu16_epi32(_mm256_castsi256_si128(low_dis0)); + let low1 = _mm256_cvtepu16_epi32(_mm256_extracti128_si256(low_dis0, 1)); + let high0 = _mm256_cvtepu16_epi32(_mm256_castsi256_si128(high_dis0)); + let high1 = _mm256_cvtepu16_epi32(_mm256_extracti128_si256(high_dis0, 1)); + let res0 = _mm256_add_epi32(low0, _mm256_slli_epi32(high0, 8)); + let res1 = _mm256_add_epi32(low1, _mm256_slli_epi32(high1, 8)); + _mm256_storeu_si256(dists.as_mut_ptr() as *mut __m256i, res0); + _mm256_storeu_si256(dists.as_mut_ptr().add(8) as *mut __m256i, res1); + + let low2 = _mm256_cvtepu16_epi32(_mm256_castsi256_si128(low_dis1)); + let low3 = _mm256_cvtepu16_epi32(_mm256_extracti128_si256(low_dis1, 1)); + let high2 = _mm256_cvtepu16_epi32(_mm256_castsi256_si128(high_dis1)); + let high3 = _mm256_cvtepu16_epi32(_mm256_extracti128_si256(high_dis1, 1)); + let res2 = _mm256_add_epi32(low2, _mm256_slli_epi32(high2, 8)); + let res3 = _mm256_add_epi32(low3, _mm256_slli_epi32(high3, 8)); + _mm256_storeu_si256(dists.as_mut_ptr().add(16) as *mut __m256i, res2); + _mm256_storeu_si256(dists.as_mut_ptr().add(24) as *mut __m256i, res3); +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +#[allow(unused)] +unsafe fn sum_dist_table_32bytes_batch_avx2( + codes: &[u8], + dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + let mut c = _mm256_undefined_si256(); + let mut lo = _mm256_undefined_si256(); + let mut hi = _mm256_undefined_si256(); + let mut lut_vec = _mm256_undefined_si256(); + let mut res_lo = _mm256_undefined_si256(); + let mut res_hi = _mm256_undefined_si256(); + + let mut accu0 = _mm256_setzero_si256(); + let mut accu1 = _mm256_setzero_si256(); + let mut accu2 = _mm256_setzero_si256(); + let mut accu3 = _mm256_setzero_si256(); + let low_mask = _mm256_set1_epi8(0x0f); + + for i in (0..codes.len()).step_by(64) { + // load 32 * 2 codes (we pack 2 codes into 1 byte) + c = _mm256_loadu_si256(codes.as_ptr().add(i) as *const __m256i); + lut_vec = _mm256_loadu_si256(dist_table.as_ptr().add(i) as *const __m256i); + + // split the first 4 bits and the second 4 bits + lo = _mm256_and_si256(c, low_mask); + hi = _mm256_and_si256(_mm256_srli_epi16(c, 4), low_mask); + + // lookup the lut + res_lo = _mm256_shuffle_epi8(lut_vec, lo); + res_hi = _mm256_shuffle_epi8(lut_vec, hi); + + accu0 = _mm256_add_epi16(accu0, res_lo); + accu1 = _mm256_add_epi16(accu1, _mm256_srli_epi16(res_lo, 8)); + accu2 = _mm256_add_epi16(accu2, res_hi); + accu3 = _mm256_add_epi16(accu3, _mm256_srli_epi16(res_hi, 8)); + + if i + 32 >= codes.len() { + continue; + } + + // load the left 32 bytes of codes and lut + c = _mm256_loadu_si256(codes.as_ptr().add(i + 32) as *const __m256i); + lut_vec = _mm256_loadu_si256(dist_table.as_ptr().add(i + 32) as *const __m256i); + + lo = _mm256_and_si256(c, low_mask); + hi = _mm256_and_si256(_mm256_srli_epi16(c, 4), low_mask); + + res_lo = _mm256_shuffle_epi8(lut_vec, lo); + res_hi = _mm256_shuffle_epi8(lut_vec, hi); + + accu0 = _mm256_add_epi16(accu0, res_lo); + accu1 = _mm256_add_epi16(accu1, _mm256_srli_epi16(res_lo, 8)); + accu2 = _mm256_add_epi16(accu2, res_hi); + accu3 = _mm256_add_epi16(accu3, _mm256_srli_epi16(res_hi, 8)); + } + + // merge the low 4 bits + accu0 = _mm256_sub_epi16(accu0, _mm256_slli_epi16(accu1, 8)); + let dis0 = _mm256_add_epi16( + _mm256_permute2f128_si256(accu0, accu1, 0x21), + _mm256_blend_epi32(accu0, accu1, 0xF0), + ); + _mm256_storeu_si256(dists.as_mut_ptr() as *mut __m256i, dis0); + + // merge the high 4 bits + accu2 = _mm256_sub_epi16(accu2, _mm256_slli_epi16(accu3, 8)); + let dis1 = _mm256_add_epi16( + _mm256_permute2f128_si256(accu2, accu3, 0x21), + _mm256_blend_epi32(accu2, accu3, 0xF0), + ); + + _mm256_storeu_si256(dists.as_mut_ptr().add(16) as *mut __m256i, dis1); +} + +#[cfg(target_arch = "aarch64")] +#[inline] +unsafe fn sum_dist_table_32bytes_batch_neon( + codes: &[u8], + dist_table: &[u8], + dists: &mut [MaybeUninit], +) { + let low_mask = vdupq_n_u8(0x0f); + + // 8 accumulators: 4 per 128-bit "lane" (lo = bytes 0..16, hi = bytes 16..32 of each block) + let mut accu0_lo = vdupq_n_u16(0); + let mut accu1_lo = vdupq_n_u16(0); + let mut accu2_lo = vdupq_n_u16(0); + let mut accu3_lo = vdupq_n_u16(0); + let mut accu0_hi = vdupq_n_u16(0); + let mut accu1_hi = vdupq_n_u16(0); + let mut accu2_hi = vdupq_n_u16(0); + let mut accu3_hi = vdupq_n_u16(0); + + let codes_ptr = codes.as_ptr(); + let dt_ptr = dist_table.as_ptr(); + + for i in (0..codes.len()).step_by(32) { + // Process lo lane: bytes [i..i+16] + let c_lo = vld1q_u8(codes_ptr.add(i)); + let lut_lo = vld1q_u8(dt_ptr.add(i)); + + let lo_lo = vandq_u8(c_lo, low_mask); + let hi_lo = vshrq_n_u8::<4>(c_lo); + + let res_lo_lo = vqtbl1q_u8(lut_lo, lo_lo); + let res_hi_lo = vqtbl1q_u8(lut_lo, hi_lo); + + accu0_lo = vaddq_u16(accu0_lo, vreinterpretq_u16_u8(res_lo_lo)); + accu1_lo = vaddq_u16(accu1_lo, vshrq_n_u16::<8>(vreinterpretq_u16_u8(res_lo_lo))); + accu2_lo = vaddq_u16(accu2_lo, vreinterpretq_u16_u8(res_hi_lo)); + accu3_lo = vaddq_u16(accu3_lo, vshrq_n_u16::<8>(vreinterpretq_u16_u8(res_hi_lo))); + + // Process hi lane: bytes [i+16..i+32] + let c_hi = vld1q_u8(codes_ptr.add(i + 16)); + let lut_hi = vld1q_u8(dt_ptr.add(i + 16)); + + let lo_hi = vandq_u8(c_hi, low_mask); + let hi_hi = vshrq_n_u8::<4>(c_hi); + + let res_lo_hi = vqtbl1q_u8(lut_hi, lo_hi); + let res_hi_hi = vqtbl1q_u8(lut_hi, hi_hi); + + accu0_hi = vaddq_u16(accu0_hi, vreinterpretq_u16_u8(res_lo_hi)); + accu1_hi = vaddq_u16(accu1_hi, vshrq_n_u16::<8>(vreinterpretq_u16_u8(res_lo_hi))); + accu2_hi = vaddq_u16(accu2_hi, vreinterpretq_u16_u8(res_hi_hi)); + accu3_hi = vaddq_u16(accu3_hi, vshrq_n_u16::<8>(vreinterpretq_u16_u8(res_hi_hi))); + } + + // Merge: clean even bytes by subtracting the odd-byte bleed + accu0_lo = vsubq_u16(accu0_lo, vshlq_n_u16::<8>(accu1_lo)); + accu0_hi = vsubq_u16(accu0_hi, vshlq_n_u16::<8>(accu1_hi)); + + // Cross-lane merge: add lo and hi lane accumulators + // This is the NEON equivalent of AVX2's permute2f128 + blend + add + let dis0_even = vaddq_u16(accu0_lo, accu0_hi); + let dis0_odd = vaddq_u16(accu1_lo, accu1_hi); + vst1q_u16(dists.as_mut_ptr().cast::(), dis0_even); + vst1q_u16(dists.as_mut_ptr().add(8).cast::(), dis0_odd); + + // Same for hi-nibble accumulators (vectors 16..31) + accu2_lo = vsubq_u16(accu2_lo, vshlq_n_u16::<8>(accu3_lo)); + accu2_hi = vsubq_u16(accu2_hi, vshlq_n_u16::<8>(accu3_hi)); + + let dis1_even = vaddq_u16(accu2_lo, accu2_hi); + let dis1_odd = vaddq_u16(accu3_lo, accu3_hi); + vst1q_u16(dists.as_mut_ptr().add(16).cast::(), dis1_even); + vst1q_u16(dists.as_mut_ptr().add(24).cast::(), dis1_odd); +} + +/// Sum a quantized 4-bit PQ distance table over column-major codes. +/// +/// `codes` holds `code_len` columns of `n` bytes: `codes[c * n + row]` packs +/// the codes of table `2 * c` (low nibble) and table `2 * c + 1` (high nibble) +/// for `row`, which is the layout PQ storage keeps its 4-bit codes in. +/// `dist_table` holds the `2 * code_len` tables of 16 entries each. +/// +/// Sums use wrapping `u16` arithmetic, so the caller must scale the table such +/// that no row's sum exceeds `u16::MAX`. +pub fn sum_4bit_dist_table_transposed( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let dist_table = column_tables(dist_table, code_len); + SUM_TRANSPOSED.get().call(codes, dist_table, n, dists); +} + +/// Sums `n` rows of column-major 4-bit codes into `u16`s: `(codes, +/// dist_table, n, dists)`, with one column per 32 entries of `dist_table`. +type SumTransposedFn = unsafe fn(&[u8], &[u8], usize, &mut [u16]); + +lance_core::dispatch! { + static SUM_TRANSPOSED: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[SUM_TRANSPOSED_AVX512, SUM_TRANSPOSED_AVX2, SUM_TRANSPOSED_SCALAR] + } + #[cfg(target_arch = "aarch64")] + { + &[SUM_TRANSPOSED_NEON, SUM_TRANSPOSED_SCALAR] + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + &[SUM_TRANSPOSED_SCALAR] + } + }; +} + +/// The first `32 * code_len` entries of `dist_table`: one low and one high +/// table of 16 entries per code column. +/// +/// # Panics +/// +/// If `dist_table` has fewer entries. +#[inline] +fn column_tables(dist_table: &[T], code_len: usize) -> &[T] { + let table_len = code_len.checked_mul(32); + assert!( + table_len.is_some_and(|needed| dist_table.len() >= needed), + "dist_table has {} entries, fewer than 32 * code_len = 32 * {code_len}", + dist_table.len() + ); + &dist_table[..32 * code_len] +} + +/// The number of code columns `dist_table` has tables for, after checking +/// that `codes` holds `n` rows of each. The product is checked: a wrapped one +/// would let short slices past the unchecked pointer arithmetic of the SIMD +/// kernels. +#[inline] +fn transposed_code_len(n: usize, codes: &[u8], dist_table: &[T]) -> usize { + let code_len = dist_table.len() / 32; + assert!( + n.checked_mul(code_len) + .is_some_and(|needed| codes.len() >= needed), + "codes has {} bytes, fewer than n * code_len = {n} * {code_len}", + codes.len() + ); + code_len +} + +/// The `n` slots of `dists` the transposed kernels store to. The SIMD kernels +/// store through raw pointers, so this check is what keeps them in bounds. +#[inline] +fn transposed_dists(dists: &mut [T], n: usize) -> &mut [T] { + assert!( + dists.len() >= n, + "dists has {} slots, fewer than n = {n}", + dists.len() + ); + &mut dists[..n] +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(SUM_TRANSPOSED_SCALAR: SumTransposedFn)] + fn sum_transposed_scalar(codes: &[u8], dist_table: &[u8], n: usize, dists: &mut [u16]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + sum_4bit_dist_table_transposed_scalar(0, n, code_len, codes, dist_table, dists); + } +} + +// The SIMD kernels offset the code pointer by the first row before the column +// loop, which with no columns would point past empty `codes`, so they leave +// that case to scalar code. + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw")] + #[candidate(SUM_TRANSPOSED_AVX512: SumTransposedFn)] + fn sum_transposed_avx512(codes: &[u8], dist_table: &[u8], n: usize, dists: &mut [u16]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + if code_len == 0 { + dists.fill(0); + return; + } + // The checks above bound every full-width access; the tail is masked. + unsafe { sum_transposed_all_avx512(n, code_len, codes, dist_table, dists) }; + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(SUM_TRANSPOSED_AVX2: SumTransposedFn)] + fn sum_transposed_avx2(codes: &[u8], dist_table: &[u8], n: usize, dists: &mut [u16]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + let simd_len = if code_len == 0 { + 0 + } else { + sum_transposed_in_batches(n, |start| { + // The checks above bound every load and store of the batch. + unsafe { sum_transposed_batch_avx2(start, n, code_len, codes, dist_table, dists) } + }) + }; + sum_4bit_dist_table_transposed_scalar(simd_len, n, code_len, codes, dist_table, dists); + } +} + +#[cfg(target_arch = "aarch64")] +lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(SUM_TRANSPOSED_NEON: SumTransposedFn)] + fn sum_transposed_neon(codes: &[u8], dist_table: &[u8], n: usize, dists: &mut [u16]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + let simd_len = if code_len == 0 { + 0 + } else { + sum_transposed_in_batches(n, |start| { + // The checks above bound every load and store of the batch. + unsafe { sum_transposed_batch_neon(start, n, code_len, codes, dist_table, dists) } + }) + }; + sum_4bit_dist_table_transposed_scalar(simd_len, n, code_len, codes, dist_table, dists); + } +} + +/// Rows summed per SIMD batch by [`sum_4bit_dist_table_transposed`], and rows +/// per batch reported by [`filter_4bit_dist_table_transposed`]. +pub const TRANSPOSED_BATCH_SIZE: usize = 64; + +/// Calls `batch(start)` on 64-row windows that cover all `n` rows and returns +/// how many leading rows they cover: `n`, or 0 when `n < 64`. +/// +/// When `n` is not a multiple of 64 the last window starts at `n - 64`. It +/// overlaps rows an earlier window already stored, but a batch stores sums that +/// depend only on the codes, so it rewrites them with identical values. That is +/// cheaper than summing up to 63 rows in scalar code. +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +fn sum_transposed_in_batches(n: usize, mut batch: impl FnMut(usize)) -> usize { + if n < TRANSPOSED_BATCH_SIZE { + return 0; + } + let aligned_len = n - n % TRANSPOSED_BATCH_SIZE; + for start in (0..aligned_len).step_by(TRANSPOSED_BATCH_SIZE) { + batch(start); + } + if aligned_len < n { + batch(n - TRANSPOSED_BATCH_SIZE); + } + n +} + +/// Scalar [`sum_4bit_dist_table_transposed`] for rows `start..n`. +fn sum_4bit_dist_table_transposed_scalar( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let dists = &mut dists[start..n]; + dists.fill(0); + for (column, tables) in dist_table + .as_chunks::<32>() + .0 + .iter() + .take(code_len) + .enumerate() + { + let (low_table, high_table) = tables.split_at(16); + let column = &codes[column * n + start..column * n + n]; + for (dist, &code) in dists.iter_mut().zip(column) { + *dist = dist + .wrapping_add(low_table[(code & 0x0f) as usize] as u16) + .wrapping_add(high_table[(code >> 4) as usize] as u16); + } + } +} + +/// Finds the rows of [`sum_4bit_dist_table_transposed`] whose sum is at most a +/// threshold, without storing every sum. +/// +/// Rows are visited in batches of 64 in ascending order. For each batch with at +/// least one such row, `on_batch(start, mask, sums)` is called: bit `i` of +/// `mask` is set when row `start + i` has a sum at most the threshold, and +/// `sums[i]` holds that sum. Other entries of `sums` are unspecified. Every row +/// is reported at most once and no bit is set for a row at or past `n`, though +/// the last batch may start before a multiple of 64. The value `on_batch` +/// returns is the threshold for the batches after it, so a caller can tighten +/// it as candidates arrive. +/// +/// ``` +/// use lance_linalg::simd::dist_table::filter_4bit_dist_table_transposed; +/// +/// // One column: row 0 selects low entry 1 (sum 1), row 1 high entry 1 (sum 5). +/// let codes = [0x01, 0x10]; +/// let mut dist_table = [0u8; 32]; +/// dist_table[1] = 1; +/// dist_table[16 + 1] = 5; +/// let mut rows = Vec::new(); +/// filter_4bit_dist_table_transposed(2, 1, &codes, &dist_table, 3, |start, mut mask, sums| { +/// while mask != 0 { +/// let i = mask.trailing_zeros() as usize; +/// rows.push((start + i, sums[i])); +/// mask &= mask - 1; +/// } +/// 3 +/// }); +/// assert_eq!(rows, [(0, 1)]); +/// ``` +/// +/// # Panics +/// +/// If `codes` holds fewer than `n * code_len` bytes or `dist_table` fewer than +/// `32 * code_len` entries. +pub fn filter_4bit_dist_table_transposed( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + threshold: u16, + mut on_batch: impl FnMut(usize, u64, &[u16; TRANSPOSED_BATCH_SIZE]) -> u16, +) { + let dist_table = column_tables(dist_table, code_len); + // `call` cannot take `&mut OnBatch<'_>`: the trait object's lifetime is + // its own, so no `Kernel::call` signature matches it. + let kernel = FILTER_TRANSPOSED.get().as_fn(); + // SAFETY: `get` returns only a kernel the host supports, and every + // `FILTER_TRANSPOSED` candidate is a safe `target_kernel!` function that + // checks its own bounds, so the target features are its only precondition. + unsafe { kernel(codes, dist_table, n, threshold, &mut on_batch) }; +} + +/// The callback of [`filter_4bit_dist_table_transposed`]. +type OnBatch<'a> = dyn FnMut(usize, u64, &[u16; TRANSPOSED_BATCH_SIZE]) -> u16 + 'a; + +/// [`filter_4bit_dist_table_transposed`] over `n` rows: `(codes, dist_table, n, +/// threshold, on_batch)`, with one column per 32 entries of `dist_table`. The +/// callback is a trait object because a candidate is a function pointer. +type FilterTransposedFn = unsafe fn(&[u8], &[u8], usize, u16, &mut OnBatch<'_>); + +lance_core::dispatch! { + static FILTER_TRANSPOSED: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[FILTER_TRANSPOSED_AVX512, FILTER_TRANSPOSED_AVX2, FILTER_TRANSPOSED_SCALAR] + } + #[cfg(target_arch = "aarch64")] + { + &[FILTER_TRANSPOSED_NEON, FILTER_TRANSPOSED_SCALAR] + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + &[FILTER_TRANSPOSED_SCALAR] + } + }; +} + +// As in the sum kernels, the SIMD paths leave `code_len == 0` to scalar code, +// which reports every row with its sum of 0. + +lance_core::target_kernel! { + #[target_features()] + #[candidate(FILTER_TRANSPOSED_SCALAR: FilterTransposedFn)] + fn filter_transposed_scalar( + codes: &[u8], + dist_table: &[u8], + n: usize, + threshold: u16, + on_batch: &mut OnBatch<'_>, + ) { + let code_len = transposed_code_len(n, codes, dist_table); + filter_transposed_rows_scalar(n, code_len, codes, dist_table, threshold, on_batch); + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx512f", "avx512bw")] + #[candidate(FILTER_TRANSPOSED_AVX512: FilterTransposedFn)] + fn filter_transposed_avx512( + codes: &[u8], + dist_table: &[u8], + n: usize, + threshold: u16, + on_batch: &mut OnBatch<'_>, + ) { + let code_len = transposed_code_len(n, codes, dist_table); + if code_len == 0 { + filter_transposed_rows_scalar(n, code_len, codes, dist_table, threshold, on_batch); + return; + } + // The check above bounds every full-width access; the tail is masked. + unsafe { + filter_transposed_all_avx512(n, code_len, codes, dist_table, threshold, on_batch) + }; + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(FILTER_TRANSPOSED_AVX2: FilterTransposedFn)] + fn filter_transposed_avx2( + codes: &[u8], + dist_table: &[u8], + n: usize, + threshold: u16, + on_batch: &mut OnBatch<'_>, + ) { + let code_len = transposed_code_len(n, codes, dist_table); + if code_len == 0 || n < TRANSPOSED_BATCH_SIZE { + filter_transposed_rows_scalar(n, code_len, codes, dist_table, threshold, on_batch); + return; + } + filter_transposed_in_batches(n, threshold, on_batch, |start, threshold, sums| { + // The check above bounds every load of a batch within `0..n`. + unsafe { + filter_transposed_batch_avx2(start, n, code_len, codes, dist_table, threshold, sums) + } + }) + } +} + +#[cfg(target_arch = "aarch64")] +lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(FILTER_TRANSPOSED_NEON: FilterTransposedFn)] + fn filter_transposed_neon( + codes: &[u8], + dist_table: &[u8], + n: usize, + threshold: u16, + on_batch: &mut OnBatch<'_>, + ) { + let code_len = transposed_code_len(n, codes, dist_table); + if code_len == 0 || n < TRANSPOSED_BATCH_SIZE { + filter_transposed_rows_scalar(n, code_len, codes, dist_table, threshold, on_batch); + return; + } + filter_transposed_in_batches(n, threshold, on_batch, |start, threshold, sums| { + // The check above bounds every load of a batch within `0..n`. + unsafe { + filter_transposed_batch_neon(start, n, code_len, codes, dist_table, threshold, sums) + } + }) + } +} + +/// Drives `batch(start, threshold, sums)` over 64-row windows covering all `n` +/// rows, `n >= 64`, as [`sum_transposed_in_batches`] does. The last window +/// overlaps rows an earlier one already reported, so their bits are cleared +/// before `on_batch` sees them. +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +fn filter_transposed_in_batches( + n: usize, + mut threshold: u16, + on_batch: &mut OnBatch<'_>, + mut batch: impl FnMut(usize, u16, &mut [u16; TRANSPOSED_BATCH_SIZE]) -> u64, +) { + debug_assert!(n >= TRANSPOSED_BATCH_SIZE); + let mut sums = [0u16; TRANSPOSED_BATCH_SIZE]; + let aligned_len = n - n % TRANSPOSED_BATCH_SIZE; + for start in (0..aligned_len).step_by(TRANSPOSED_BATCH_SIZE) { + let mask = batch(start, threshold, &mut sums); + if mask != 0 { + threshold = on_batch(start, mask, &sums); + } + } + if aligned_len < n { + let start = n - TRANSPOSED_BATCH_SIZE; + let mask = batch(start, threshold, &mut sums) & (u64::MAX << (aligned_len - start)); + if mask != 0 { + on_batch(start, mask, &sums); + } + } +} + +/// Scalar [`filter_4bit_dist_table_transposed`]. +fn filter_transposed_rows_scalar( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + mut threshold: u16, + on_batch: &mut OnBatch<'_>, +) { + let mut sums = [0u16; TRANSPOSED_BATCH_SIZE]; + for start in (0..n).step_by(TRANSPOSED_BATCH_SIZE) { + let mask = filter_transposed_batch_scalar( + start, n, code_len, codes, dist_table, threshold, &mut sums, + ); + if mask != 0 { + threshold = on_batch(start, mask, &sums); + } + } +} + +/// Sums rows `start..min(start + 64, n)` into `sums` and returns the mask of +/// those at most `threshold`. +fn filter_transposed_batch_scalar( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + threshold: u16, + sums: &mut [u16; TRANSPOSED_BATCH_SIZE], +) -> u64 { + let end = n.min(start + TRANSPOSED_BATCH_SIZE); + let sums = &mut sums[..end - start]; + sums.fill(0); + for (column, tables) in dist_table + .as_chunks::<32>() + .0 + .iter() + .take(code_len) + .enumerate() + { + let (low_table, high_table) = tables.split_at(16); + let column = &codes[column * n + start..column * n + end]; + for (sum, &code) in sums.iter_mut().zip(column) { + *sum = sum + .wrapping_add(low_table[(code & 0x0f) as usize] as u16) + .wrapping_add(high_table[(code >> 4) as usize] as u16); + } + } + sums.iter().enumerate().fold(0, |mask, (i, &sum)| { + mask | (u64::from(sum <= threshold) << i) + }) +} + +/// Stores the sums of rows `start..start + 64` to `dists`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn sum_transposed_batch_avx2( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let rows = transposed_batch_sums_avx2(start, n, code_len, codes, dist_table); + let out = dists.as_mut_ptr().add(start) as *mut __m256i; + for (i, row) in rows.into_iter().enumerate() { + _mm256_storeu_si256(out.add(i), row); + } +} + +/// Sums rows `start..start + 64` into four vectors of 16 rows each, in row +/// order. Each `u16` lane first accumulates a pair of adjacent byte lookups +/// (`even + 256 * odd`) plus a separate `odd` sum; the even sum is recovered at +/// the end, as in faiss' fast-scan kernels. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +unsafe fn transposed_batch_sums_avx2( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], +) -> [__m256i; 4] { + let low_mask = _mm256_set1_epi8(0x0f); + let mut pairs = [_mm256_setzero_si256(); 2]; + let mut odds = [_mm256_setzero_si256(); 2]; + let codes = codes.as_ptr().add(start); + for column in 0..code_len { + let tables = dist_table.as_ptr().add(column * 32); + let low_table = _mm256_broadcastsi128_si256(_mm_loadu_si128(tables as *const __m128i)); + let high_table = + _mm256_broadcastsi128_si256(_mm_loadu_si128(tables.add(16) as *const __m128i)); + let column = codes.add(column * n); + for half in 0..2 { + let code = _mm256_loadu_si256(column.add(half * 32) as *const __m256i); + let low = _mm256_shuffle_epi8(low_table, _mm256_and_si256(code, low_mask)); + let high = _mm256_shuffle_epi8( + high_table, + _mm256_and_si256(_mm256_srli_epi16(code, 4), low_mask), + ); + // A carry out of the even byte of `low + high` is exact `u16` + // arithmetic, so subtracting `256 * odds` still recovers the even sum. + pairs[half] = _mm256_add_epi16(pairs[half], _mm256_add_epi16(low, high)); + odds[half] = _mm256_add_epi16( + odds[half], + _mm256_add_epi16(_mm256_srli_epi16(low, 8), _mm256_srli_epi16(high, 8)), + ); + } + } + let mut rows = [_mm256_setzero_si256(); 4]; + for half in 0..2 { + let evens = _mm256_sub_epi16(pairs[half], _mm256_slli_epi16(odds[half], 8)); + // Within each 128-bit lane, even rows are in `evens` and odd rows in + // `odds`; interleave them back into row order. + let first = _mm256_unpacklo_epi16(evens, odds[half]); + let second = _mm256_unpackhi_epi16(evens, odds[half]); + rows[2 * half] = _mm256_permute2x128_si256(first, second, 0x20); + rows[2 * half + 1] = _mm256_permute2x128_si256(first, second, 0x31); + } + rows +} + +/// Sums rows `start..start + 64` and returns the mask of those at most +/// `threshold`, writing their sums to `sums` only when the mask is non-zero. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn filter_transposed_batch_avx2( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + threshold: u16, + sums: &mut [u16; TRANSPOSED_BATCH_SIZE], +) -> u64 { + let rows = transposed_batch_sums_avx2(start, n, code_len, codes, dist_table); + let limit = _mm256_set1_epi16(threshold as i16); + let mut at_most = [_mm256_setzero_si256(); 4]; + for (flags, &row) in at_most.iter_mut().zip(rows.iter()) { + // AVX2 has no unsigned `u16` compare, but `min(row, limit) == row` + // holds exactly when `row <= limit`. + *flags = _mm256_cmpeq_epi16(_mm256_min_epu16(row, limit), row); + } + // Packing the all-ones or zero flags to bytes is exact, but it works per + // 128-bit lane and leaves the quadwords in row order 0, 2, 1, 3. + let low = _mm256_permute4x64_epi64(_mm256_packs_epi16(at_most[0], at_most[1]), 0xD8); + let high = _mm256_permute4x64_epi64(_mm256_packs_epi16(at_most[2], at_most[3]), 0xD8); + let mask = u64::from(_mm256_movemask_epi8(low) as u32) + | (u64::from(_mm256_movemask_epi8(high) as u32) << 32); + if mask != 0 { + let out = sums.as_mut_ptr() as *mut __m256i; + for (i, row) in rows.into_iter().enumerate() { + _mm256_storeu_si256(out.add(i), row); + } + } + mask +} + +/// Sums all `n` rows of [`sum_4bit_dist_table_transposed`]. The last partial +/// window uses masked loads and stores, so no row is left for scalar code. +/// +/// # Safety +/// +/// The host must support `avx512f` and `avx512bw`. +/// `codes` and `dist_table` must hold the `n * code_len` bytes and +/// `32 * code_len` entries [`transposed_code_len`] checks, and `dists` at +/// least the `n` slots [`transposed_dists`] checks. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f,avx512bw")] +unsafe fn sum_transposed_all_avx512( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let mut start = 0; + while start + 2 * TRANSPOSED_BATCH_SIZE <= n { + sum_transposed_block_avx512::<2, false>(start, n, code_len, codes, dist_table, dists, 0); + start += 2 * TRANSPOSED_BATCH_SIZE; + } + if start + TRANSPOSED_BATCH_SIZE <= n { + sum_transposed_block_avx512::<1, false>(start, n, code_len, codes, dist_table, dists, 0); + start += TRANSPOSED_BATCH_SIZE; + } + if start < n { + let row_mask = (1u64 << (n - start)) - 1; + sum_transposed_block_avx512::<1, true>( + start, n, code_len, codes, dist_table, dists, row_mask, + ); + } +} + +/// Stores the sums of rows `start..start + 64 * REGS`, or only of the rows set +/// in `row_mask` when `MASKED`, to `dists`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f,avx512bw")] +#[inline] +#[allow(clippy::too_many_arguments)] +unsafe fn sum_transposed_block_avx512( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], + row_mask: u64, +) { + let rows = transposed_block_sums_avx512::( + start, n, code_len, codes, dist_table, row_mask, + ); + for (reg, [first, second]) in rows.into_iter().enumerate() { + let out = dists.as_mut_ptr().add(start + reg * 64); + if MASKED { + _mm512_mask_storeu_epi16(out.cast(), row_mask as u32, first); + // With 32 or fewer tail rows `out + 32` can point past `dists`, and + // forming that pointer is UB even when the store mask is empty. + let high_mask = (row_mask >> 32) as u32; + if high_mask != 0 { + _mm512_mask_storeu_epi16(out.add(32).cast(), high_mask, second); + } + } else { + _mm512_storeu_si512(out.cast(), first); + _mm512_storeu_si512(out.add(32).cast(), second); + } + } +} + +/// Sums rows `start..start + 64 * REGS`, or only the rows set in `row_mask` +/// when `MASKED`, into two vectors of 32 rows each per 64 rows, in row order; +/// masked-off rows sum as if their codes were zero. The even/odd `u16` split is +/// the one [`transposed_batch_sums_avx2`] uses, on 64 rows per register. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f,avx512bw")] +#[inline] +unsafe fn transposed_block_sums_avx512( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + row_mask: u64, +) -> [[__m512i; 2]; REGS] { + const { assert!(!MASKED || REGS == 1) }; + let low_mask = _mm512_set1_epi8(0x0f); + let mut pairs = [_mm512_setzero_si512(); REGS]; + let mut odds = [_mm512_setzero_si512(); REGS]; + let codes = codes.as_ptr().add(start); + for column in 0..code_len { + let tables = dist_table.as_ptr().add(column * 32); + let low_table = _mm512_broadcast_i32x4(_mm_loadu_si128(tables.cast())); + let high_table = _mm512_broadcast_i32x4(_mm_loadu_si128(tables.add(16).cast())); + let column = codes.add(column * n); + for reg in 0..REGS { + // A zeroing masked load costs an extra uop on Intel, so only the + // tail pays for it. Masked-off bytes are never read. + let code = if MASKED { + _mm512_maskz_loadu_epi8(row_mask, column.cast()) + } else { + _mm512_loadu_si512(column.add(reg * 64).cast()) + }; + let low = _mm512_shuffle_epi8(low_table, _mm512_and_si512(code, low_mask)); + let high = _mm512_shuffle_epi8( + high_table, + _mm512_and_si512(_mm512_srli_epi16::<4>(code), low_mask), + ); + // A carry out of the even byte of `low + high` is exact `u16` + // arithmetic, so subtracting `256 * odds` still recovers the even sum. + pairs[reg] = _mm512_add_epi16(pairs[reg], _mm512_add_epi16(low, high)); + odds[reg] = _mm512_add_epi16( + odds[reg], + _mm512_add_epi16(_mm512_srli_epi16::<8>(low), _mm512_srli_epi16::<8>(high)), + ); + } + } + // Unpacking works within 128-bit lanes: lane `l` of `lo` holds rows + // `16l..16l + 8` and lane `l` of `hi` rows `16l + 8..16l + 16`. These qword + // indices (8 and up pick from `hi`) gather lanes 0-1 into `first` and lanes + // 2-3 into `second`, both in row order. + let first_half = _mm512_set_epi64(11, 10, 3, 2, 9, 8, 1, 0); + let second_half = _mm512_set_epi64(15, 14, 7, 6, 13, 12, 5, 4); + let mut rows = [[_mm512_setzero_si512(); 2]; REGS]; + for (reg, rows) in rows.iter_mut().enumerate() { + let evens = _mm512_sub_epi16(pairs[reg], _mm512_slli_epi16::<8>(odds[reg])); + let lo = _mm512_unpacklo_epi16(evens, odds[reg]); + let hi = _mm512_unpackhi_epi16(evens, odds[reg]); + *rows = [ + _mm512_permutex2var_epi64(lo, first_half, hi), + _mm512_permutex2var_epi64(lo, second_half, hi), + ]; + } + rows +} + +/// [`filter_4bit_dist_table_transposed`] over all `n` rows, two 64-row batches +/// per pass; the last partial batch is masked, so no row is left for scalar +/// code. +/// +/// # Safety +/// +/// The host must support `avx512f` and `avx512bw`, and the slices must satisfy +/// the bounds [`transposed_code_len`] checks. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f,avx512bw")] +unsafe fn filter_transposed_all_avx512( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + mut threshold: u16, + on_batch: &mut OnBatch<'_>, +) { + let mut sums = [0u16; TRANSPOSED_BATCH_SIZE]; + let mut start = 0; + while start + 2 * TRANSPOSED_BATCH_SIZE <= n { + let rows = + transposed_block_sums_avx512::<2, false>(start, n, code_len, codes, dist_table, 0); + for (reg, [first, second]) in rows.into_iter().enumerate() { + // The second batch is compared only after the first one's callback, + // against the threshold that callback returned. + threshold = emit_rows_at_most_avx512( + start + reg * TRANSPOSED_BATCH_SIZE, + first, + second, + u64::MAX, + threshold, + &mut sums, + on_batch, + ); + } + start += 2 * TRANSPOSED_BATCH_SIZE; + } + if start + TRANSPOSED_BATCH_SIZE <= n { + let [[first, second]] = + transposed_block_sums_avx512::<1, false>(start, n, code_len, codes, dist_table, 0); + threshold = emit_rows_at_most_avx512( + start, + first, + second, + u64::MAX, + threshold, + &mut sums, + on_batch, + ); + start += TRANSPOSED_BATCH_SIZE; + } + if start < n { + let row_mask = (1u64 << (n - start)) - 1; + let [[first, second]] = transposed_block_sums_avx512::<1, true>( + start, n, code_len, codes, dist_table, row_mask, + ); + emit_rows_at_most_avx512( + start, first, second, row_mask, threshold, &mut sums, on_batch, + ); + } +} + +/// Calls `on_batch` for the rows of the batch at `start` that are in +/// `row_mask` and at most `threshold`, if any, and returns the threshold for +/// the next batch. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f,avx512bw")] +#[inline] +unsafe fn emit_rows_at_most_avx512( + start: usize, + first: __m512i, + second: __m512i, + row_mask: u64, + threshold: u16, + sums: &mut [u16; TRANSPOSED_BATCH_SIZE], + on_batch: &mut OnBatch<'_>, +) -> u16 { + let limit = _mm512_set1_epi16(threshold as i16); + let mask = (u64::from(_mm512_cmple_epu16_mask(first, limit)) + | (u64::from(_mm512_cmple_epu16_mask(second, limit)) << 32)) + & row_mask; + if mask == 0 { + return threshold; + } + _mm512_storeu_si512(sums.as_mut_ptr().cast(), first); + _mm512_storeu_si512(sums.as_mut_ptr().add(32).cast(), second); + on_batch(start, mask, sums) +} + +/// Stores the sums of rows `start..start + 64` to `dists`. +#[cfg(target_arch = "aarch64")] +#[inline] +unsafe fn sum_transposed_batch_neon( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + dists: &mut [u16], +) { + let rows = transposed_batch_sums_neon(start, n, code_len, codes, dist_table); + let out = dists.as_mut_ptr().add(start); + for (i, row) in rows.into_iter().enumerate() { + vst1q_u16(out.add(i * 8), row); + } +} + +/// Sums rows `start..start + 64` with widening adds into eight vectors of 8 +/// rows each, in row order. +#[cfg(target_arch = "aarch64")] +#[inline] +unsafe fn transposed_batch_sums_neon( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], +) -> [uint16x8_t; 8] { + let low_mask = vdupq_n_u8(0x0f); + let mut sums = [vdupq_n_u16(0); 8]; + let codes = codes.as_ptr().add(start); + for column in 0..code_len { + let tables = dist_table.as_ptr().add(column * 32); + let low_table = vld1q_u8(tables); + let high_table = vld1q_u8(tables.add(16)); + let column = codes.add(column * n); + for quarter in 0..4 { + let code = vld1q_u8(column.add(quarter * 16)); + let low = vqtbl1q_u8(low_table, vandq_u8(code, low_mask)); + let high = vqtbl1q_u8(high_table, vshrq_n_u8::<4>(code)); + let first = &mut sums[quarter * 2]; + *first = vaddw_u8(*first, vget_low_u8(low)); + *first = vaddw_u8(*first, vget_low_u8(high)); + let second = &mut sums[quarter * 2 + 1]; + *second = vaddw_high_u8(*second, low); + *second = vaddw_high_u8(*second, high); + } + } + sums +} + +/// Sums rows `start..start + 64` and returns the mask of those at most +/// `threshold`, writing their sums to `sums` only when the mask is non-zero. +#[cfg(target_arch = "aarch64")] +unsafe fn filter_transposed_batch_neon( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[u8], + threshold: u16, + sums: &mut [u16; TRANSPOSED_BATCH_SIZE], +) -> u64 { + let rows = transposed_batch_sums_neon(start, n, code_len, codes, dist_table); + let limit = vdupq_n_u16(threshold); + let mut at_most = [vdupq_n_u16(0); 8]; + let mut any = vdupq_n_u16(0); + for (flags, &row) in at_most.iter_mut().zip(rows.iter()) { + *flags = vcleq_u16(row, limit); + any = vorrq_u16(any, *flags); + } + // Most batches have no row at or below the threshold once it is tight, so + // they skip building the mask. + if vmaxvq_u16(any) == 0 { + return 0; + } + let bits = [1u8, 2, 4, 8, 16, 32, 64, 128]; + let bits = vld1_u8(bits.as_ptr()); + let mut mask = 0u64; + for (i, (&flags, &row)) in at_most.iter().zip(rows.iter()).enumerate() { + vst1q_u16(sums.as_mut_ptr().add(i * 8), row); + let byte = vaddv_u8(vand_u8(vmovn_u16(flags), bits)); + mask |= u64::from(byte) << (i * 8); + } + mask +} + +/// Exact `f32` sum of one row of a 4-bit PQ distance table over column-major +/// codes: the reference every exact `f32` kernel below reproduces. +/// +/// `codes` and `dist_table` have the layout [`sum_4bit_dist_table_transposed`] +/// describes, with `f32` entries. Starting from `-0.0`, each column adds the +/// pair `low + high` its code byte selects, as one value and in column order: +/// `(0..code_len).fold(-0.0, |acc, c| acc + (low(c) + high(c)))`. Rust never +/// contracts or reassociates these adds. +/// +/// ``` +/// use lance_linalg::simd::dist_table::sum_4bit_dist_table_f32_row; +/// +/// // One column: row 0 selects low entry 1, row 1 selects high entry 2. +/// let codes = [0x01, 0x20]; +/// let mut dist_table = [0.0f32; 32]; +/// dist_table[1] = 1.5; +/// dist_table[16 + 2] = 2.5; +/// assert_eq!(sum_4bit_dist_table_f32_row(2, 1, &codes, &dist_table, 1), 2.5); +/// ``` +/// +/// # Panics +/// +/// If `row >= n`, `codes` holds fewer than `n * code_len` bytes or +/// `dist_table` fewer than `32 * code_len` entries. +// Inlined into per-row callers such as `PQDistCalculator::distance`, which the +// workspace builds without LTO. +#[inline] +pub fn sum_4bit_dist_table_f32_row( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + row: usize, +) -> f32 { + assert!(row < n, "row {row} is out of range for {n} rows"); + let dist_table = column_tables(dist_table, code_len); + transposed_code_len(n, codes, dist_table); + f32_row_sum(n, codes, f32_tables(dist_table), row) +} + +/// Exact `f32` sums of all `n` rows of a 4-bit PQ distance table over +/// column-major codes, writing row `r` to `dists[r]`. +/// +/// Every backend performs, per row, the two IEEE-754 additions per column of +/// [`sum_4bit_dist_table_f32_row`] in the same order, from the same `-0.0` +/// start, so each sum is bit-identical to it. SIMD lanes each hold one row, +/// table lookups are bit copies and vector adds (`vaddps`, NEON `fadd`) round +/// like scalar ones (`addss`, `fadd`) under the same MXCSR or FPCR. The one +/// exception is NaN, which only non-finite tables produce: both paths then +/// return NaN, but not necessarily with the same sign or payload. +/// +/// ``` +/// use lance_linalg::simd::dist_table::sum_4bit_dist_table_f32_transposed; +/// +/// // One column: row 0 selects low entry 1, row 1 selects high entry 2. +/// let codes = [0x01, 0x20]; +/// let mut dist_table = [0.0f32; 32]; +/// dist_table[1] = 1.5; +/// dist_table[16 + 2] = 2.5; +/// let mut dists = [0.0f32; 2]; +/// sum_4bit_dist_table_f32_transposed(2, 1, &codes, &dist_table, &mut dists); +/// assert_eq!(dists, [1.5, 2.5]); +/// ``` +/// +/// # Panics +/// +/// If `codes` holds fewer than `n * code_len` bytes, `dist_table` fewer than +/// `32 * code_len` entries or `dists` fewer than `n` slots. +pub fn sum_4bit_dist_table_f32_transposed( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + let dist_table = column_tables(dist_table, code_len); + SUM_F32_TRANSPOSED.get().call(codes, dist_table, n, dists); +} + +/// Exact `f32` sums of the selected `rows`, writing the sum of `rows[i]` to +/// `dists[i]`; rows may repeat and come in any order. +/// +/// Sums are bit-identical to [`sum_4bit_dist_table_f32_row`], for the reasons +/// [`sum_4bit_dist_table_f32_transposed`] gives. The SIMD backends score 16 +/// rows at a time, so a caller rescoring candidates in order loses little by +/// passing 16 per call. +/// +/// ``` +/// use lance_linalg::simd::dist_table::sum_4bit_dist_table_f32_rows; +/// +/// let codes = [0x01, 0x20]; +/// let mut dist_table = [0.0f32; 32]; +/// dist_table[1] = 1.5; +/// dist_table[16 + 2] = 2.5; +/// let mut dists = [0.0f32; 3]; +/// sum_4bit_dist_table_f32_rows(2, 1, &codes, &dist_table, &[1, 0, 1], &mut dists); +/// assert_eq!(dists, [2.5, 1.5, 2.5]); +/// ``` +/// +/// # Panics +/// +/// If any row is `>= n`, `codes` holds fewer than `n * code_len` bytes, +/// `dist_table` fewer than `32 * code_len` entries or `dists` fewer than +/// `rows.len()` slots. +pub fn sum_4bit_dist_table_f32_rows( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + rows: &[u32], + dists: &mut [f32], +) { + let dist_table = column_tables(dist_table, code_len); + SUM_F32_ROWS.get().call(codes, dist_table, n, rows, dists); +} + +/// Exact `f32` sums of all `n` rows: `(codes, dist_table, n, dists)`, with one +/// column per 32 entries of `dist_table`. +type SumF32TransposedFn = unsafe fn(&[u8], &[f32], usize, &mut [f32]); + +lance_core::dispatch! { + static SUM_F32_TRANSPOSED: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[SUM_F32_TRANSPOSED_AVX512, SUM_F32_TRANSPOSED_AVX2, SUM_F32_TRANSPOSED_SCALAR] + } + #[cfg(target_arch = "aarch64")] + { + &[SUM_F32_TRANSPOSED_NEON, SUM_F32_TRANSPOSED_SCALAR] + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + &[SUM_F32_TRANSPOSED_SCALAR] + } + }; +} + +/// Exact `f32` sums of selected rows: `(codes, dist_table, n, rows, dists)`. +type SumF32RowsFn = unsafe fn(&[u8], &[f32], usize, &[u32], &mut [f32]); + +lance_core::dispatch! { + static SUM_F32_ROWS: Dispatch = { + // A NEON kernel measured no faster than scalar on Graviton3: per 16 + // rows it gathers the code bytes and deinterleaves every column's + // tables, which costs more than its lookups save. + #[cfg(target_arch = "x86_64")] + { + &[SUM_F32_ROWS_AVX512, SUM_F32_ROWS_AVX2, SUM_F32_ROWS_SCALAR] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[SUM_F32_ROWS_SCALAR] + } + }; +} + +/// Rows per `f32` lane group: one `zmm` register on AVX-512, two `ymm` on AVX2, +/// four `q` registers on NEON. +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +const F32_GROUP_ROWS: usize = 16; +/// Rows per block of the scalar pair-table path, and the fewest rows it takes: +/// building the 256 pairs of a column costs about as much as summing 256 rows. +const F32_PAIR_TABLE_BLOCK_ROWS: usize = 256; + +/// One 32-entry table per code column: 16 entries for the low nibble, then 16 +/// for the high one. +#[inline] +fn f32_tables(dist_table: &[f32]) -> &[[f32; 32]] { + dist_table.as_chunks::<32>().0 +} + +#[inline] +fn f32_row_sum(n: usize, codes: &[u8], tables: &[[f32; 32]], row: usize) -> f32 { + // An explicit fold rather than `Iterator::sum` pins the `-0.0` start. + tables + .iter() + .enumerate() + .fold(-0.0f32, |acc, (column, table)| { + let code = codes[column * n + row]; + acc + (table[(code & 0x0f) as usize] + table[16 + (code >> 4) as usize]) + }) +} + +// The SIMD kernels offset the code pointer by the first row before the column +// loop, which with no columns would point past empty `codes`, so they leave +// that case, where every sum is `-0.0`, to scalar code. They also need at +// least one full lane group. + +lance_core::target_kernel! { + #[target_features()] + #[candidate(SUM_F32_TRANSPOSED_SCALAR: SumF32TransposedFn)] + fn sum_f32_transposed_scalar(codes: &[u8], dist_table: &[f32], n: usize, dists: &mut [f32]) { + transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + sum_f32_transposed_rows_scalar(n, codes, f32_tables(dist_table), dists); + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(SUM_F32_TRANSPOSED_AVX512: SumF32TransposedFn)] + fn sum_f32_transposed_avx512(codes: &[u8], dist_table: &[f32], n: usize, dists: &mut [f32]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + if code_len == 0 || n < F32_GROUP_ROWS { + sum_f32_transposed_rows_scalar(n, codes, f32_tables(dist_table), dists); + return; + } + // The checks above bound every load and store of the kernel. + unsafe { sum_f32_transposed_all_avx512(n, code_len, codes, dist_table, dists) }; + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(SUM_F32_TRANSPOSED_AVX2: SumF32TransposedFn)] + fn sum_f32_transposed_avx2(codes: &[u8], dist_table: &[f32], n: usize, dists: &mut [f32]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + if code_len == 0 || n < F32_GROUP_ROWS / 2 { + sum_f32_transposed_rows_scalar(n, codes, f32_tables(dist_table), dists); + return; + } + // The checks above bound every load and store of the kernel. + unsafe { sum_f32_transposed_all_avx2(n, code_len, codes, dist_table, dists) }; + } +} + +#[cfg(target_arch = "aarch64")] +lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(SUM_F32_TRANSPOSED_NEON: SumF32TransposedFn)] + fn sum_f32_transposed_neon(codes: &[u8], dist_table: &[f32], n: usize, dists: &mut [f32]) { + let code_len = transposed_code_len(n, codes, dist_table); + let dists = transposed_dists(dists, n); + if code_len == 0 || n < F32_GROUP_ROWS { + sum_f32_transposed_rows_scalar(n, codes, f32_tables(dist_table), dists); + return; + } + // The checks above bound every load and store of the kernel. + unsafe { sum_f32_transposed_all_neon(n, code_len, codes, dist_table, dists) }; + } +} + +/// Checks the bounds of [`SumF32RowsFn`] and returns the code column count and +/// the `dists` slots of `rows`. Together these keep every gathered code byte, +/// table load and store in bounds. +#[inline] +fn f32_rows_bounds<'a>( + codes: &[u8], + dist_table: &[f32], + n: usize, + rows: &[u32], + dists: &'a mut [f32], +) -> (usize, &'a mut [f32]) { + let code_len = transposed_code_len(n, codes, dist_table); + assert!( + dists.len() >= rows.len(), + "dists has {} slots, fewer than the {} rows", + dists.len(), + rows.len() + ); + let max_row = rows.iter().max(); + assert!( + max_row.is_none_or(|&row| (row as usize) < n), + "row {max_row:?} is out of range for {n} rows" + ); + (code_len, &mut dists[..rows.len()]) +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(SUM_F32_ROWS_SCALAR: SumF32RowsFn)] + fn sum_f32_rows_scalar( + codes: &[u8], + dist_table: &[f32], + n: usize, + rows: &[u32], + dists: &mut [f32], + ) { + let (_, dists) = f32_rows_bounds(codes, dist_table, n, rows, dists); + sum_f32_selected_rows_scalar(n, codes, f32_tables(dist_table), rows, dists); + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(SUM_F32_ROWS_AVX512: SumF32RowsFn)] + fn sum_f32_rows_avx512( + codes: &[u8], + dist_table: &[f32], + n: usize, + rows: &[u32], + dists: &mut [f32], + ) { + let (code_len, dists) = f32_rows_bounds(codes, dist_table, n, rows, dists); + // The checks above bound every access of the kernel. + unsafe { sum_f32_selected_rows_avx512(n, code_len, codes, dist_table, rows, dists) }; + } +} + +#[cfg(target_arch = "x86_64")] +lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(SUM_F32_ROWS_AVX2: SumF32RowsFn)] + fn sum_f32_rows_avx2( + codes: &[u8], + dist_table: &[f32], + n: usize, + rows: &[u32], + dists: &mut [f32], + ) { + let (code_len, dists) = f32_rows_bounds(codes, dist_table, n, rows, dists); + // The checks above bound every access of the kernel. + unsafe { sum_f32_selected_rows_avx2(n, code_len, codes, dist_table, rows, dists) }; + } +} + +/// Scalar [`sum_4bit_dist_table_f32_transposed`]. +fn sum_f32_transposed_rows_scalar(n: usize, codes: &[u8], tables: &[[f32; 32]], dists: &mut [f32]) { + let dists = &mut dists[..n]; + if n < F32_PAIR_TABLE_BLOCK_ROWS { + for (row, dist) in dists.iter_mut().enumerate() { + *dist = f32_row_sum(n, codes, tables, row); + } + return; + } + // Every byte of a column selects one of 256 pair sums `low + high`. The + // precomputed pair is the very value the per-row sum adds, so sums stay + // bit-identical while each row needs one lookup per byte instead of two. + let pair_tables = tables + .iter() + .map(|table| { + std::array::from_fn::(|byte| table[byte & 0x0f] + table[16 + (byte >> 4)]) + }) + .collect::>(); + dists.fill(-0.0); + for block_start in (0..n).step_by(F32_PAIR_TABLE_BLOCK_ROWS) { + let block_end = (block_start + F32_PAIR_TABLE_BLOCK_ROWS).min(n); + // A block's sums stay in L1 while every code column is added to them. + let block = &mut dists[block_start..block_end]; + for (column, pair_table) in pair_tables.iter().enumerate() { + let codes = &codes[column * n + block_start..column * n + block_end]; + for (dist, &code) in block.iter_mut().zip(codes) { + *dist += pair_table[code as usize]; + } + } + } +} + +/// Scalar [`sum_4bit_dist_table_f32_rows`]. Eight rows at a time overlap their +/// otherwise serial add chains. +fn sum_f32_selected_rows_scalar( + n: usize, + codes: &[u8], + tables: &[[f32; 32]], + rows: &[u32], + dists: &mut [f32], +) { + const LANES: usize = 8; + let score = |rows: &[u32], dists: &mut [f32]| { + let mut acc = [-0.0f32; LANES]; + for (column, table) in tables.iter().enumerate() { + let codes = &codes[column * n..(column + 1) * n]; + for (acc, &row) in acc.iter_mut().zip(rows) { + let code = codes[row as usize]; + *acc += table[(code & 0x0f) as usize] + table[16 + (code >> 4) as usize]; + } + } + for (dist, acc) in dists.iter_mut().zip(acc) { + *dist = acc; + } + }; + let (row_groups, row_tail) = rows.as_chunks::(); + let (dist_groups, dist_tail) = dists.as_chunks_mut::(); + for (rows, dists) in row_groups.iter().zip(dist_groups) { + score(rows, dists); + } + if !row_tail.is_empty() { + score(row_tail, dist_tail); + } +} + +/// The code bytes of `rows` in the column starting at `column`, row `i` in +/// byte `i`. Packing them in general-purpose registers avoids the failed +/// store-to-load forwarding of 16 byte stores read back as one vector. +/// +/// # Safety +/// +/// `column.add(row)` must be readable for every row. +#[cfg(target_arch = "x86_64")] +#[inline] +unsafe fn gather_code_bytes(column: *const u8, rows: &[usize; F32_GROUP_ROWS]) -> __m128i { + let pack = |rows: &[usize]| { + rows.iter() + .rev() + .fold(0u64, |word, &row| (word << 8) | *column.add(row) as u64) + }; + _mm_set_epi64x(pack(&rows[8..]) as i64, pack(&rows[..8]) as i64) +} + +/// `rows` as offsets into a column, padded to a full group with `rows[0]`, a +/// valid row whose extra sums are discarded. +#[cfg(target_arch = "x86_64")] +fn padded_group_rows(rows: &[u32]) -> [usize; F32_GROUP_ROWS] { + let mut group = [rows[0] as usize; F32_GROUP_ROWS]; + for (slot, &row) in group.iter_mut().zip(rows) { + *slot = row as usize; + } + group +} + +/// `low[code & 15] + high[code >> 4]` per lane of 32-bit codes below 256. +/// `vpermps` reads only index bits 3:0, so the low nibble needs no mask and +/// the shifted code is exactly the high nibble. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f")] +#[inline] +fn lookup_pair_avx512(code: __m512i, low_table: __m512, high_table: __m512) -> __m512 { + _mm512_add_ps( + _mm512_permutexvar_ps(code, low_table), + _mm512_permutexvar_ps(_mm512_srli_epi32::<4>(code), high_table), + ) +} + +/// Sums all `n` rows in 256-row blocks, then 16-row groups. A last partial +/// group is summed as the 16 rows ending at `n`, rewriting some sums of the +/// previous group with the same values. +/// +/// # Safety +/// +/// The host must support `avx512f` and `n >= 16`. +/// `codes` and `dist_table` must hold the `n * code_len` bytes and +/// `32 * code_len` entries [`transposed_code_len`] checks, and `dists` at +/// least the `n` slots [`transposed_dists`] checks. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f")] +unsafe fn sum_f32_transposed_all_avx512( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + const BLOCK_GROUPS: usize = 16; + debug_assert!(n >= F32_GROUP_ROWS); + let mut start = 0; + while start + BLOCK_GROUPS * F32_GROUP_ROWS <= n { + sum_f32_transposed_block_avx512::( + start, n, code_len, codes, dist_table, dists, + ); + start += BLOCK_GROUPS * F32_GROUP_ROWS; + } + while start + F32_GROUP_ROWS <= n { + sum_f32_transposed_block_avx512::<1>(start, n, code_len, codes, dist_table, dists); + start += F32_GROUP_ROWS; + } + if start < n { + sum_f32_transposed_block_avx512::<1>( + n - F32_GROUP_ROWS, + n, + code_len, + codes, + dist_table, + dists, + ); + } +} + +/// Sums rows `start..start + 16 * GROUPS`, one register of 16 rows per group, +/// each an independent add chain. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f")] +#[inline] +unsafe fn sum_f32_transposed_block_avx512( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + let mut acc = [_mm512_set1_ps(-0.0); GROUPS]; + let codes = codes.as_ptr().add(start); + for column in 0..code_len { + let tables = dist_table.as_ptr().add(column * 32); + let low_table = _mm512_loadu_ps(tables); + let high_table = _mm512_loadu_ps(tables.add(16)); + let column = codes.add(column * n); + for (group, acc) in acc.iter_mut().enumerate() { + let code = + _mm512_cvtepu8_epi32(_mm_loadu_si128(column.add(group * F32_GROUP_ROWS).cast())); + *acc = _mm512_add_ps(*acc, lookup_pair_avx512(code, low_table, high_table)); + } + } + let out = dists.as_mut_ptr().add(start); + for (group, acc) in acc.iter().enumerate() { + _mm512_storeu_ps(out.add(group * F32_GROUP_ROWS), *acc); + } +} + +/// Sums `rows` 16 at a time, gathering each column's code bytes first. +/// +/// # Safety +/// +/// The host must support `avx512f`, and the slices must satisfy the bounds +/// [`f32_rows_bounds`] checks, with `dists.len() == rows.len()`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx512f")] +unsafe fn sum_f32_selected_rows_avx512( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + rows: &[u32], + dists: &mut [f32], +) { + for (rows, dists) in rows + .chunks(F32_GROUP_ROWS) + .zip(dists.chunks_mut(F32_GROUP_ROWS)) + { + let rows = padded_group_rows(rows); + let mut acc = _mm512_set1_ps(-0.0); + for column in 0..code_len { + let tables = dist_table.as_ptr().add(column * 32); + let code = + _mm512_cvtepu8_epi32(gather_code_bytes(codes.as_ptr().add(column * n), &rows)); + acc = _mm512_add_ps( + acc, + lookup_pair_avx512( + code, + _mm512_loadu_ps(tables), + _mm512_loadu_ps(tables.add(16)), + ), + ); + } + let mut sums = [0.0f32; F32_GROUP_ROWS]; + _mm512_storeu_ps(sums.as_mut_ptr(), acc); + dists.copy_from_slice(&sums[..dists.len()]); + } +} + +/// `low[code & 15] + high[code >> 4]` per lane of 32-bit codes below 256, +/// with each 16-entry table split into two registers. `vpermps` reads index +/// bits 2:0 and `blendv` picks the upper half by the sign bit, so bit 3 of the +/// code (bit 7 for the high nibble) is shifted into it. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +fn lookup_pair_avx2(code: __m256i, low_table: [__m256; 2], high_table: [__m256; 2]) -> __m256 { + let low = _mm256_blendv_ps( + _mm256_permutevar8x32_ps(low_table[0], code), + _mm256_permutevar8x32_ps(low_table[1], code), + _mm256_castsi256_ps(_mm256_slli_epi32::<28>(code)), + ); + let high_code = _mm256_srli_epi32::<4>(code); + let high = _mm256_blendv_ps( + _mm256_permutevar8x32_ps(high_table[0], high_code), + _mm256_permutevar8x32_ps(high_table[1], high_code), + _mm256_castsi256_ps(_mm256_slli_epi32::<24>(code)), + ); + _mm256_add_ps(low, high) +} + +/// The two halves of each 16-entry table of `column`, low table first. +/// +/// # Safety +/// +/// `dist_table.add(32 * column)` must be readable for 32 entries. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +unsafe fn load_tables_avx2(dist_table: *const f32, column: usize) -> ([__m256; 2], [__m256; 2]) { + let tables = dist_table.add(column * 32); + ( + [_mm256_loadu_ps(tables), _mm256_loadu_ps(tables.add(8))], + [ + _mm256_loadu_ps(tables.add(16)), + _mm256_loadu_ps(tables.add(24)), + ], + ) +} + +/// Sums all `n` rows in 32-row blocks, then 8-row groups, ending with the 8 +/// rows that end at `n` like [`sum_f32_transposed_all_avx512`]. +/// +/// # Safety +/// +/// The host must support `avx2` and `n >= 8`. +/// `codes` and `dist_table` must hold the `n * code_len` bytes and +/// `32 * code_len` entries [`transposed_code_len`] checks, and `dists` at +/// least the `n` slots [`transposed_dists`] checks. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn sum_f32_transposed_all_avx2( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + const BLOCK_GROUPS: usize = 4; + const GROUP_ROWS: usize = F32_GROUP_ROWS / 2; + debug_assert!(n >= GROUP_ROWS); + let mut start = 0; + while start + BLOCK_GROUPS * GROUP_ROWS <= n { + sum_f32_transposed_block_avx2::(start, n, code_len, codes, dist_table, dists); + start += BLOCK_GROUPS * GROUP_ROWS; + } + while start + GROUP_ROWS <= n { + sum_f32_transposed_block_avx2::<1>(start, n, code_len, codes, dist_table, dists); + start += GROUP_ROWS; + } + if start < n { + sum_f32_transposed_block_avx2::<1>(n - GROUP_ROWS, n, code_len, codes, dist_table, dists); + } +} + +/// Sums rows `start..start + 8 * GROUPS`, one register of 8 rows per group. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +unsafe fn sum_f32_transposed_block_avx2( + start: usize, + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + const GROUP_ROWS: usize = F32_GROUP_ROWS / 2; + let mut acc = [_mm256_set1_ps(-0.0); GROUPS]; + let codes = codes.as_ptr().add(start); + for column in 0..code_len { + let (low_table, high_table) = load_tables_avx2(dist_table.as_ptr(), column); + let column = codes.add(column * n); + for (group, acc) in acc.iter_mut().enumerate() { + let code = _mm256_cvtepu8_epi32(_mm_loadl_epi64(column.add(group * GROUP_ROWS).cast())); + *acc = _mm256_add_ps(*acc, lookup_pair_avx2(code, low_table, high_table)); + } + } + let out = dists.as_mut_ptr().add(start); + for (group, acc) in acc.iter().enumerate() { + _mm256_storeu_ps(out.add(group * GROUP_ROWS), *acc); + } +} + +/// Sums `rows` 16 at a time in two 8-row registers, gathering each column's +/// code bytes first. +/// +/// # Safety +/// +/// As for [`sum_f32_selected_rows_avx512`], with `avx2` in place of `avx512f`. +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn sum_f32_selected_rows_avx2( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + rows: &[u32], + dists: &mut [f32], +) { + for (rows, dists) in rows + .chunks(F32_GROUP_ROWS) + .zip(dists.chunks_mut(F32_GROUP_ROWS)) + { + let rows = padded_group_rows(rows); + let mut acc = [_mm256_set1_ps(-0.0); 2]; + for column in 0..code_len { + let (low_table, high_table) = load_tables_avx2(dist_table.as_ptr(), column); + let code = gather_code_bytes(codes.as_ptr().add(column * n), &rows); + let codes = [ + _mm256_cvtepu8_epi32(code), + _mm256_cvtepu8_epi32(_mm_unpackhi_epi64(code, code)), + ]; + for (acc, code) in acc.iter_mut().zip(codes) { + *acc = _mm256_add_ps(*acc, lookup_pair_avx2(code, low_table, high_table)); + } + } + let mut sums = [0.0f32; F32_GROUP_ROWS]; + _mm256_storeu_ps(sums.as_mut_ptr(), acc[0]); + _mm256_storeu_ps(sums.as_mut_ptr().add(F32_GROUP_ROWS / 2), acc[1]); + dists.copy_from_slice(&sums[..dists.len()]); + } +} + +/// The entries of a 16-entry table that 16 nibbles select, as four vectors of +/// 4 rows in row order. `planes` is the table as `vld4q_u8` loads it: plane `b` +/// holds byte `b` of every little-endian entry, so one `tbl` per plane looks up +/// that byte for all 16 nibbles, and two rounds of zips reassemble the four +/// bytes of each row into one lane, bit for bit. +#[cfg(target_arch = "aarch64")] +#[target_feature(enable = "neon")] +#[inline] +fn lookup_neon(planes: uint8x16x4_t, nibbles: uint8x16_t) -> [float32x4_t; 4] { + let byte0 = vqtbl1q_u8(planes.0, nibbles); + let byte1 = vqtbl1q_u8(planes.1, nibbles); + let byte2 = vqtbl1q_u8(planes.2, nibbles); + let byte3 = vqtbl1q_u8(planes.3, nibbles); + // Bytes 0 and 1, then 2 and 3, of rows 0..8 and 8..16 as `u16` lanes. + let low_halves = [ + vreinterpretq_u16_u8(vzip1q_u8(byte0, byte1)), + vreinterpretq_u16_u8(vzip2q_u8(byte0, byte1)), + ]; + let high_halves = [ + vreinterpretq_u16_u8(vzip1q_u8(byte2, byte3)), + vreinterpretq_u16_u8(vzip2q_u8(byte2, byte3)), + ]; + [ + vreinterpretq_f32_u16(vzip1q_u16(low_halves[0], high_halves[0])), + vreinterpretq_f32_u16(vzip2q_u16(low_halves[0], high_halves[0])), + vreinterpretq_f32_u16(vzip1q_u16(low_halves[1], high_halves[1])), + vreinterpretq_f32_u16(vzip2q_u16(low_halves[1], high_halves[1])), + ] +} + +/// `low[code & 15] + high[code >> 4]` for 16 code bytes, as four vectors of 4 +/// rows in row order. +#[cfg(target_arch = "aarch64")] +#[target_feature(enable = "neon")] +#[inline] +fn lookup_pair_neon( + code: uint8x16_t, + low_table: uint8x16x4_t, + high_table: uint8x16x4_t, +) -> [float32x4_t; 4] { + let low = lookup_neon(low_table, vandq_u8(code, vdupq_n_u8(0x0f))); + let high = lookup_neon(high_table, vshrq_n_u8::<4>(code)); + [ + vaddq_f32(low[0], high[0]), + vaddq_f32(low[1], high[1]), + vaddq_f32(low[2], high[2]), + vaddq_f32(low[3], high[3]), + ] +} + +/// Sums all `n` rows in 32-row blocks, then 16-row groups, ending with the 16 +/// rows that end at `n` like the x86 kernels. +/// +/// # Safety +/// +/// `n >= 16`. +/// `codes` and `dist_table` must hold the `n * code_len` bytes and +/// `32 * code_len` entries [`transposed_code_len`] checks, and `dists` at +/// least the `n` slots [`transposed_dists`] checks. +#[cfg(target_arch = "aarch64")] +#[target_feature(enable = "neon")] +unsafe fn sum_f32_transposed_all_neon( + n: usize, + code_len: usize, + codes: &[u8], + dist_table: &[f32], + dists: &mut [f32], +) { + // Two groups hold 8 accumulators next to the 8 table planes and the + // lookup temporaries, within the 32 vector registers. + const BLOCK_GROUPS: usize = 2; + debug_assert!(n >= F32_GROUP_ROWS); + // Deinterleaving once here rather than per block and column: on Graviton3 + // a `vld4q_u8` costs about as much as the lookups of a 16-row group. + let planes: Vec<[uint8x16x4_t; 2]> = (0..code_len) + .map(|column| { + let tables = dist_table.as_ptr().add(column * 32); + [vld4q_u8(tables.cast()), vld4q_u8(tables.add(16).cast())] + }) + .collect(); + let mut start = 0; + while start + BLOCK_GROUPS * F32_GROUP_ROWS <= n { + sum_f32_transposed_block_neon::(start, n, codes, &planes, dists); + start += BLOCK_GROUPS * F32_GROUP_ROWS; + } + while start + F32_GROUP_ROWS <= n { + sum_f32_transposed_block_neon::<1>(start, n, codes, &planes, dists); + start += F32_GROUP_ROWS; + } + if start < n { + sum_f32_transposed_block_neon::<1>(n - F32_GROUP_ROWS, n, codes, &planes, dists); + } +} + +/// Sums rows `start..start + 16 * GROUPS` over the columns whose low and high +/// table `planes` hold, four registers of 4 rows per group, each an +/// independent add chain. +#[cfg(target_arch = "aarch64")] +#[target_feature(enable = "neon")] +#[inline] +unsafe fn sum_f32_transposed_block_neon( + start: usize, + n: usize, + codes: &[u8], + planes: &[[uint8x16x4_t; 2]], + dists: &mut [f32], +) { + let mut acc = [[vdupq_n_f32(-0.0); 4]; GROUPS]; + let codes = codes.as_ptr().add(start); + for (column, &[low_table, high_table]) in planes.iter().enumerate() { + let column = codes.add(column * n); + for (group, acc) in acc.iter_mut().enumerate() { + let code = vld1q_u8(column.add(group * F32_GROUP_ROWS)); + let pairs = lookup_pair_neon(code, low_table, high_table); + for (acc, pair) in acc.iter_mut().zip(pairs) { + *acc = vaddq_f32(*acc, pair); + } + } + } + let out = dists.as_mut_ptr().add(start); + for (group, acc) in acc.iter().enumerate() { + for (quarter, acc) in acc.iter().enumerate() { + vst1q_f32(out.add(group * F32_GROUP_ROWS + quarter * 4), *acc); + } + } +} + +// We implement the AVX512 version in C because AVX512 is not stable yet in Rust, +// implement it in Rust once we upgrade rust to 1.89.0. +unsafe extern "C" { + #[cfg(all(kernel_support = "avx512_dist_table", target_arch = "x86_64"))] + pub fn sum_4bit_dist_table_32bytes_batch_avx512( + codes: *const u8, + code_length: usize, + dist_table: *const u8, + dists: *mut u16, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_perm0_inverse_matches_perm0() { + for (idx, &value) in PERM0.iter().enumerate() { + assert_eq!(PERM0_INVERSE[value], idx); + } + } + + #[test] + fn test_sum_4bit_dist_table_basic() { + // we have 32 vectors + let n = 32; + + // each code is 2 bytes (16 dim), so code_len = 2 + let code_len = 2; + + let codes = [ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, // codes[0..8] + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, // codes[8..16] + 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, // codes[16..24] + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, // codes[24..32] + ]; + let codes = codes.repeat(n * code_len / codes.len()); + + let mut dist_table = vec![0u8; 16 * 4]; + for (i, dist) in dist_table.iter_mut().enumerate() { + *dist = (i % 16 + 1) as u8; + } + + // Test the function + let mut dists = vec![0u16; n]; + sum_4bit_dist_table(n, code_len, &codes, &dist_table, &mut dists); + + // Compare with reference implementation + let mut expected_dists = vec![0u16; n]; + sum_4bit_dist_table_scalar(code_len, &codes, &dist_table, &mut expected_dists); + + assert_eq!(dists, expected_dists); + // the vector 1's code is the low 4bits of codes[PERM0_INVERSE[1]] = codes[2], + // the first 4 bits are the low 4 bits of codes[2], so it's 0x6, + // the second 4 bits are the low 4 bits of codes[2 + 16], so it's 0xb, + // the third 4 bits are the same as the first 4 bits, so it's 0x6, + // the fourth 4 bits are the same as the second 4 bits, so it's 0xb, + + // so the distance is 2 * (dist_table[0x6] + dist_table[0xb + 16]) = 2*(7 + 12) = 38 + assert_eq!(dists[1], 38); + } + + #[test] + fn test_sum_4bit_dist_table_overwrites_output() { + let n = BATCH_SIZE; + let code_len = 16; + let codes = vec![0x12; n * code_len]; + let dist_table = vec![1u8; BATCH_SIZE * code_len]; + + let mut expected = vec![u16::MAX; n]; + sum_4bit_dist_table_scalar(code_len, &codes, &dist_table, &mut expected); + + let mut actual = vec![u16::MAX; n]; + sum_4bit_dist_table(n, code_len, &codes, &dist_table, &mut actual); + + assert_eq!(actual, expected); + assert!(actual.iter().all(|dist| *dist != u16::MAX)); + } + + #[test] + fn test_sum_4bit_dist_table_u16_basic() { + let n = BATCH_SIZE; + let code_len = 2; + let codes = [ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, + 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x12, 0x34, 0x56, 0x78, + 0x9a, 0xbc, 0xde, 0xf0, + ]; + let codes = codes.repeat(n * code_len / codes.len()); + let dist_table: Vec = (0..16 * 4).map(|idx| (idx % 16 + 1) as u16).collect(); + + let mut dists = vec![0u32; n]; + sum_4bit_dist_table_u16(n, code_len, &codes, &dist_table, &mut dists); + + assert_eq!(dists[1], 38); + } + + #[test] + fn test_transfer_4bit_dist_table_u16_layout() { + let dist_table: Vec = (0..32).map(|idx| 0x1200 + idx as u16).collect(); + let mut hacc_dist_table = Vec::new(); + transfer_4bit_dist_table_u16(&dist_table, &mut hacc_dist_table); + + assert_eq!(hacc_dist_table.len(), 64); + for code in 0..16 { + assert_eq!(hacc_dist_table[code], dist_table[code] as u8); + assert_eq!(hacc_dist_table[16 + code], dist_table[16 + code] as u8); + assert_eq!(hacc_dist_table[32 + code], (dist_table[code] >> 8) as u8); + assert_eq!( + hacc_dist_table[48 + code], + (dist_table[16 + code] >> 8) as u8 + ); + } + } + + #[test] + fn test_sum_4bit_dist_table_u16_matches_reference_multi_batch() { + use rand::{Rng, SeedableRng}; + let mut rng = rand::rngs::StdRng::seed_from_u64(99); + + for code_len in [1, 3, 16, 191, 192, 1024] { + let n = BATCH_SIZE * 4; + let codes: Vec = (0..n * code_len).map(|_| rng.random::()).collect(); + let dist_table: Vec = (0..BATCH_SIZE * code_len) + .map(|_| rng.random::()) + .collect(); + + let mut expected = vec![0u32; n]; + sum_4bit_dist_table_u16_scalar(code_len, &codes, &dist_table, &mut expected); + + let mut actual = vec![u32::MAX; n]; + sum_4bit_dist_table_u16(n, code_len, &codes, &dist_table, &mut actual); + + assert_eq!( + actual, + expected, + "u16 dist-table mismatch for code_len={} (DIM={})", + code_len, + code_len * 8, + ); + } + } + + /// Every hacc candidate, and the dispatched entry point, sums a full-range + /// `u16` table exactly, across [`SAFE_U16_CODE_LEN`] chunk boundaries. + #[rstest::rstest] + fn test_sum_4bit_hacc_dist_table_candidates_match_u16_reference( + #[values(1, 3, 16, 191, 192, 1024)] code_len: usize, + ) { + use rand::{Rng, SeedableRng}; + let mut rng = rand::rngs::StdRng::seed_from_u64(101 + code_len as u64); + let n = BATCH_SIZE * 4; + let codes: Vec = (0..n * code_len).map(|_| rng.random::()).collect(); + let dist_table: Vec = (0..BATCH_SIZE * code_len) + .map(|_| rng.random::()) + .collect(); + let mut hacc_dist_table = Vec::new(); + transfer_4bit_dist_table_u16(&dist_table, &mut hacc_dist_table); + + let mut expected = vec![0u32; n]; + sum_4bit_dist_table_u16_scalar(code_len, &codes, &dist_table, &mut expected); + + for candidate in SUM_HACC.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut actual = vec![MaybeUninit::new(u32::MAX); n]; + kernel.call(&codes, &hacc_dist_table, code_len, &mut actual); + let actual = actual + .iter() + .map(|dist| unsafe { dist.assume_init() }) + .collect::>(); + assert_eq!( + actual, + expected, + "{} at code_len {code_len}", + candidate.name() + ); + } + let mut actual = vec![u32::MAX; n]; + sum_4bit_hacc_dist_table(n, code_len, &codes, &hacc_dist_table, &mut actual); + assert_eq!(actual, expected, "entry point at code_len {code_len}"); + } + + /// Every candidate, and the dispatched entry point, matches scalar within + /// the `u16` contract: a full-range table up to [`SAFE_U16_CODE_LEN`], and + /// past it a table capped so no sum overflows, as the ex-code FastScan LUT + /// does. Three batches check that rows do not bleed across batch boundaries. + #[rstest::rstest] + fn test_sum_4bit_dist_table_candidates_match_scalar( + #[values(1, 2, 3, 16, 95, 96, 128, 191, 192, 1024, 8192)] code_len: usize, + #[values(1, 3)] num_batches: usize, + ) { + use rand::{Rng, SeedableRng}; + let mut rng = rand::rngs::StdRng::seed_from_u64((code_len * 100 + num_batches) as u64); + let n = BATCH_SIZE * num_batches; + let max_entry = (u16::MAX as usize / (2 * code_len)).min(u8::MAX as usize) as u8; + let codes: Vec = (0..n * code_len).map(|_| rng.random::()).collect(); + let dist_table: Vec = (0..BATCH_SIZE * code_len) + .map(|_| rng.random_range(0..=max_entry)) + .collect(); + + let mut expected = vec![0u16; n]; + sum_4bit_dist_table_scalar(code_len, &codes, &dist_table, &mut expected); + + for candidate in SUM_U16.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut actual = vec![MaybeUninit::new(u16::MAX); n]; + kernel.call(&codes, &dist_table, code_len, &mut actual); + let actual = actual + .iter() + .map(|dist| unsafe { dist.assume_init() }) + .collect::>(); + assert_eq!( + actual, + expected, + "{} at code_len {code_len}", + candidate.name() + ); + } + let mut actual = vec![u16::MAX; n]; + sum_4bit_dist_table(n, code_len, &codes, &dist_table, &mut actual); + assert_eq!(actual, expected, "entry point at code_len {code_len}"); + } + + /// Exact reference: the `u16`-table scalar kernel already sums into `u32`. + fn reference_u32_sums(n: usize, code_len: usize, codes: &[u8], dist_table: &[u8]) -> Vec { + let dist_table: Vec = dist_table.iter().map(|value| *value as u16).collect(); + let mut expected = vec![0u32; n]; + sum_4bit_dist_table_u16_scalar( + code_len, + &codes[..n * code_len], + &dist_table, + &mut expected, + ); + expected + } + + #[test] + fn test_safe_u16_code_len_is_the_overflow_bound() { + assert!(2 * SAFE_U16_CODE_LEN * u8::MAX as usize <= u16::MAX as usize); + assert!(2 * (SAFE_U16_CODE_LEN + 1) * u8::MAX as usize > u16::MAX as usize); + } + + #[test] + fn test_sum_4bit_dist_table_u32_matches_reference_full_range() { + use rand::{Rng, SeedableRng}; + let mut rng = rand::rngs::StdRng::seed_from_u64(7157); + + for code_len in [1, 3, 16, 128, 129, 191, 192, 300, 512, 1024] { + let n = BATCH_SIZE * 4; + let codes: Vec = (0..n * code_len).map(|_| rng.random::()).collect(); + let dist_table: Vec = (0..BATCH_SIZE * code_len) + .map(|_| rng.random::()) + .collect(); + + let expected = reference_u32_sums(n, code_len, &codes, &dist_table); + + let mut actual = vec![u32::MAX; n]; + sum_4bit_dist_table_u32(n, code_len, &codes, &dist_table, &mut actual); + + assert_eq!( + actual, + expected, + "u32 dist-table mismatch for code_len={} (DIM={})", + code_len, + code_len * 8, + ); + } + } + + /// https://github.com/lance-format/lance/issues/7157: at DIM=4096 a + /// full-range table sums to four times what a `u16` holds. + #[test] + fn test_sum_4bit_dist_table_u32_stays_exact_past_u16_range() { + let code_len = 512; + let n = BATCH_SIZE; + let codes = vec![0u8; n * code_len]; + let dist_table = vec![u8::MAX; BATCH_SIZE * code_len]; + let expected = 2 * code_len as u32 * u8::MAX as u32; + assert!(expected > u16::MAX as u32); + + let mut wide = vec![0u32; n]; + sum_4bit_dist_table_u32(n, code_len, &codes, &dist_table, &mut wide); + assert!(wide.iter().all(|dist| *dist == expected)); + } + + #[test] + fn test_sum_4bit_dist_table_u32_zero_code_len() { + let n = BATCH_SIZE; + let mut dists = vec![u32::MAX; n]; + sum_4bit_dist_table_u32(n, 0, &[], &[], &mut dists); + assert!(dists.iter().all(|dist| *dist == 0)); + } + /// Random column-major codes, a full-range `u8` table and an `f32` table. + fn transposed_case(n: usize, code_len: usize) -> (Vec, Vec, Vec) { + use rand::{Rng, SeedableRng}; + let mut rng = rand::rngs::StdRng::seed_from_u64((n * 1000 + code_len) as u64); + let codes = (0..n * code_len).map(|_| rng.random::()).collect(); + let u8_table = (0..code_len * 32).map(|_| rng.random::()).collect(); + let f32_table = (0..code_len * 32) + .map(|_| rng.random_range(-3.0f32..5.0)) + .collect(); + (codes, u8_table, f32_table) + } + + /// Every candidate of the `u16` store and filter kernels sums like the + /// reference, and the filter reports exactly the rows at most its threshold. + #[rstest::rstest] + fn test_sum_4bit_dist_table_transposed_matches_reference( + #[values(0, 17, 65, 128, 1000)] n: usize, + #[values(0, 3, 48)] code_len: usize, + ) { + let (codes, table, _) = transposed_case(n, code_len); + let expected = (0..n) + .map(|row| { + (0..code_len) + .map(|column| { + let code = codes[column * n + row]; + table[column * 32 + (code & 0x0f) as usize] as u16 + + table[column * 32 + 16 + (code >> 4) as usize] as u16 + }) + .sum::() + }) + .collect::>(); + for candidate in SUM_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut actual = vec![u16::MAX; n]; + kernel.call(&codes, &table, n, &mut actual); + assert_eq!(actual, expected, "{}", candidate.name()); + } + let mut actual = vec![u16::MAX; n]; + sum_4bit_dist_table_transposed(n, code_len, &codes, &table, &mut actual); + assert_eq!(actual, expected, "entry point"); + + let mut sorted = expected.clone(); + sorted.sort_unstable(); + let threshold = sorted.get(n / 2).copied().unwrap_or(0); + let wanted = expected + .iter() + .enumerate() + .filter(|(_, sum)| **sum <= threshold) + .map(|(row, sum)| (row, *sum)) + .collect::>(); + for candidate in FILTER_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut found = Vec::new(); + let mut on_batch = |start, mut mask: u64, sums: &[u16; TRANSPOSED_BATCH_SIZE]| { + while mask != 0 { + let i = mask.trailing_zeros() as usize; + found.push((start + i, sums[i])); + mask &= mask - 1; + } + threshold + }; + // `as_fn` because no `call` signature takes `&mut OnBatch<'_>`. + // SAFETY: `kernel` exists only because the host supports it, and + // the candidate checks its own bounds. + unsafe { kernel.as_fn()(&codes, &table, n, threshold, &mut on_batch) }; + assert_eq!(found, wanted, "{}", candidate.name()); + } + } + + /// Every candidate of the exact `f32` kernels matches the per-row fold bit + /// for bit, over all rows and over selected rows. + #[rstest::rstest] + fn test_sum_4bit_dist_table_f32_matches_fold( + #[values(0, 7, 17, 1000)] n: usize, + #[values(0, 3, 48)] code_len: usize, + ) { + let (codes, _, table) = transposed_case(n, code_len); + let fold = |row: usize| { + (0..code_len) + .map(|column| { + let code = codes[column * n + row]; + table[column * 32 + (code & 0x0f) as usize] + + table[column * 32 + 16 + (code >> 4) as usize] + }) + .fold(-0.0f32, |acc, pair| acc + pair) + .to_bits() + }; + let expected = (0..n).map(fold).collect::>(); + let rows = (0..n as u32).rev().step_by(3).collect::>(); + let expected_rows = rows + .iter() + .map(|&row| fold(row as usize)) + .collect::>(); + let bits = |dists: &[f32]| dists.iter().map(|d| d.to_bits()).collect::>(); + for candidate in SUM_F32_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![f32::NAN; n]; + kernel.call(&codes, &table, n, &mut dists); + assert_eq!(bits(&dists), expected, "{}", candidate.name()); + } + for candidate in SUM_F32_ROWS.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut row_dists = vec![f32::NAN; rows.len()]; + kernel.call(&codes, &table, n, &rows, &mut row_dists); + assert_eq!(bits(&row_dists), expected_rows, "{}", candidate.name()); + } + } + + /// Runs `f`, which must panic, and returns its panic message. + fn panic_message(f: impl FnOnce()) -> String { + let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) + .expect_err("expected a panic"); + payload + .downcast_ref::() + .cloned() + .or_else(|| { + payload + .downcast_ref::<&str>() + .map(|message| message.to_string()) + }) + .unwrap_or_default() + } + + /// Every row-major candidate rejects inputs its SIMD loads would overrun, + /// including an `n * code_len` that wraps to zero. + #[rstest::rstest] + #[case::n_not_a_batch_multiple(33, 1, 33, 1, "is not a multiple of")] + #[case::short_codes(32, 2, 63, 2, "codes has")] + #[case::short_dist_table(32, 2, 64, 1, "dist_table has")] + #[case::wrapping_codes_product(32, usize::MAX / 32 + 1, 0, 0, "codes has")] + fn test_row_major_candidates_check_bounds( + #[case] n: usize, + #[case] code_len: usize, + #[case] codes_len: usize, + #[case] table_codes: usize, + #[case] expected: &str, + ) { + let codes = vec![0u8; codes_len]; + let table = vec![0u8; table_codes * BATCH_SIZE]; + for candidate in SUM_U16.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![MaybeUninit::::uninit(); n]; + let message = panic_message(|| kernel.call(&codes, &table, code_len, &mut dists)); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + let hacc_table = vec![0u8; table_codes * 64]; + for candidate in SUM_HACC.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![MaybeUninit::::uninit(); n]; + let message = panic_message(|| kernel.call(&codes, &hacc_table, code_len, &mut dists)); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + } + + /// The `u32` entry point checks the whole input, not just each chunk. + #[rstest::rstest] + #[case::n_not_a_batch_multiple(33, 1, 64, 1, "is not a multiple of")] + #[case::short_codes(32, 2, 63, 2, "codes has")] + #[case::short_dist_table(32, 2, 64, 1, "dist_table has")] + fn test_sum_4bit_dist_table_u32_checks_bounds( + #[case] n: usize, + #[case] code_len: usize, + #[case] codes_len: usize, + #[case] table_codes: usize, + #[case] expected: &str, + ) { + let codes = vec![0u8; codes_len]; + let table = vec![0u8; table_codes * BATCH_SIZE]; + let mut dists = vec![0u32; 64]; + let message = + panic_message(|| sum_4bit_dist_table_u32(n, code_len, &codes, &table, &mut dists)); + assert!(message.contains(expected), "{message}"); + } + + /// Every transposed candidate rejects inputs its SIMD loads or stores would + /// overrun, including an `n * code_len` that wraps to zero. + #[rstest::rstest] + #[case::short_codes(65, 2, 129, 65, "codes has")] + #[case::wrapping_codes_product(usize::MAX / 2 + 1, 2, 0, 0, "codes has")] + #[case::short_dists(65, 2, 130, 64, "dists has")] + fn test_transposed_candidates_check_bounds( + #[case] n: usize, + #[case] code_len: usize, + #[case] codes_len: usize, + #[case] dists_len: usize, + #[case] expected: &str, + ) { + let codes = vec![0u8; codes_len]; + let u8_table = vec![0u8; 32 * code_len]; + let f32_table = vec![0.0f32; 32 * code_len]; + for candidate in SUM_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![0u16; dists_len]; + let message = panic_message(|| kernel.call(&codes, &u8_table, n, &mut dists)); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + for candidate in SUM_F32_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![0.0f32; dists_len]; + let message = panic_message(|| kernel.call(&codes, &f32_table, n, &mut dists)); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + // The filter stores no sums, so only the `codes` bound applies to it. + if expected != "codes has" { + return; + } + for candidate in FILTER_TRANSPOSED.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut on_batch = |_, _, _: &[u16; TRANSPOSED_BATCH_SIZE]| u16::MAX; + let message = panic_message(|| { + // SAFETY: `kernel` exists only because the host supports it, + // and the candidate checks its own bounds. + unsafe { kernel.as_fn()(&codes, &u8_table, n, u16::MAX, &mut on_batch) } + }); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + } + + /// Every selected-rows candidate rejects a row past `n` and short slices. + #[rstest::rstest] + #[case::row_out_of_range(&[0, 4], 2, 4, "out of range")] + #[case::short_dists(&[0, 1], 1, 4, "dists has")] + #[case::short_codes(&[0], 1, 3, "codes has")] + fn test_f32_rows_candidates_check_bounds( + #[case] rows: &[u32], + #[case] dists_len: usize, + #[case] codes_len: usize, + #[case] expected: &str, + ) { + let n = 4; + let codes = vec![0u8; codes_len]; + let table = vec![0.0f32; 32]; + for candidate in SUM_F32_ROWS.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut dists = vec![0.0f32; dists_len]; + let message = panic_message(|| kernel.call(&codes, &table, n, rows, &mut dists)); + assert!( + message.contains(expected), + "{}: {message}", + candidate.name() + ); + } + } + + /// The transposed entry points reject a short table before dispatching, + /// including a `32 * code_len` that wraps to zero. + #[rstest::rstest] + #[case::short_dist_table(1, 2, 63)] + #[case::wrapping_table_product(0, usize::MAX / 32 + 1, 0)] + fn test_transposed_entry_points_check_dist_table( + #[case] n: usize, + #[case] code_len: usize, + #[case] table_len: usize, + ) { + let codes = [0u8; 2]; + let message = panic_message(|| { + sum_4bit_dist_table_transposed(n, code_len, &codes, &vec![0; table_len], &mut [0; 1]) + }); + assert!(message.contains("dist_table has"), "{message}"); + let message = panic_message(|| { + sum_4bit_dist_table_f32_transposed( + n, + code_len, + &codes, + &vec![0.0; table_len], + &mut [0.0; 1], + ) + }); + assert!(message.contains("dist_table has"), "{message}"); + } + + /// Each entry point's best candidate on x86_64 and aarch64 is a SIMD one, + /// so a host with the features never falls through to scalar. + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn test_every_entry_point_has_a_simd_candidate() { + let firsts = [ + SUM_U16.candidates()[0].features(), + SUM_TRANSPOSED.candidates()[0].features(), + FILTER_TRANSPOSED.candidates()[0].features(), + SUM_F32_TRANSPOSED.candidates()[0].features(), + ]; + for features in firsts { + assert!(!features.is_empty()); + } + #[cfg(target_arch = "x86_64")] + { + assert!(!SUM_HACC.candidates()[0].features().is_empty()); + assert!(!SUM_F32_ROWS.candidates()[0].features().is_empty()); + } + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/f16.c b/rust/lancedb/vendor/lance-linalg/src/simd/f16.c new file mode 100644 index 000000000..b694d4e73 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/f16.c @@ -0,0 +1,145 @@ +// Copyright 2023 Lance Developers. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include + +// Because we might be compiling this library multiple times, we need to +// add a suffix to each of the function names. +#define FUNC_CAT_INNER(A, B) A##B +#define FUNC_CAT(A, B) FUNC_CAT_INNER(A, B) +#define FUNC(N) FUNC_CAT(N, SUFFIX) + +#if defined(__clang__) +// Note: we use __fp16 instead of _Float16 because Clang < 15.0.0 does not +// support it well for most targets. __fp16 works for our purposes here since +// we are always casting it to float anyways. This doesn't make a difference +// in the compiled assembly code for these functions. +#define FP16 __fp16 +#elif defined(__GNUC__) || defined(__GNUG__) +#define FP16 _Float16 +#endif +// Note: MSVC doesn't support _Float16 yet, so we can't use it here. + +// The AVX2 object uses the lane-partitioned reductions below to preserve the +// Rust reference implementation's error bound while still vectorizing each +// 16-element chunk. The AVX-512 object keeps its existing wider reduction. +#define F16_ACCUMULATOR_LANES 16 + +float FUNC(norm_l2_f16)(const FP16 *data, uint32_t dimension) { +#ifdef PRECISE_F16_REDUCTION + float sums[F16_ACCUMULATOR_LANES] = {0}; + uint32_t chunked_dimension = + dimension - dimension % F16_ACCUMULATOR_LANES; + + for (uint32_t i = 0; i < chunked_dimension; + i += F16_ACCUMULATOR_LANES) { +#pragma clang loop unroll(full) + for (uint32_t lane = 0; lane < F16_ACCUMULATOR_LANES; lane++) { + float value = (float)data[i + lane]; + sums[lane] += value * value; + } + } + + float remainder_sum = 0; + for (uint32_t i = chunked_dimension; i < dimension; i++) { + float value = (float)data[i]; + remainder_sum += value * value; + } + + float lane_sum = 0; + for (uint32_t lane = 0; lane < F16_ACCUMULATOR_LANES; lane++) { + lane_sum += sums[lane]; + } + return sqrtf(remainder_sum + lane_sum); +#else + float sum = 0; + +#pragma clang loop unroll(enable) vectorize(enable) interleave(enable) + for (uint32_t i = 0; i < dimension; i++) { + sum += (float) data[i] * (float) data[i]; + } + return sqrtf(sum); +#endif +} + +/// @brief Dot product of two f16 vectors. +/// @param x A f16 vector +/// @param y A f16 vector +/// @param dimension The dimension of the vectors +/// @return The dot product of the two vectors. +float FUNC(dot_f16)(const FP16 *x, const FP16 *y, uint32_t dimension) { + float sum = 0; + +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + sum += (float) x[i] * (float) y[i]; + } + return sum; +} + +float FUNC(l2_f16)(const FP16 *x, const FP16 *y, uint32_t dimension) { +#ifdef PRECISE_F16_REDUCTION + float sums[F16_ACCUMULATOR_LANES] = {0}; + uint32_t chunked_dimension = + dimension - dimension % F16_ACCUMULATOR_LANES; + + for (uint32_t i = 0; i < chunked_dimension; + i += F16_ACCUMULATOR_LANES) { +#pragma clang loop unroll(full) + for (uint32_t lane = 0; lane < F16_ACCUMULATOR_LANES; lane++) { + float difference = (float)x[i + lane] - (float)y[i + lane]; + sums[lane] += difference * difference; + } + } + + float remainder_sum = 0; + for (uint32_t i = chunked_dimension; i < dimension; i++) { + float difference = (float)x[i] - (float)y[i]; + remainder_sum += difference * difference; + } + + float lane_sum = 0; + for (uint32_t lane = 0; lane < F16_ACCUMULATOR_LANES; lane++) { + lane_sum += sums[lane]; + } + return remainder_sum + lane_sum; +#else + float sum = 0.0; + +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + float s = (float) x[i] - (float) y[i]; + sum += s * s; + } + return sum; +#endif +} + +float FUNC(cosine_f16)(const FP16 *x, float x_norm, const FP16 *y, uint32_t dimension) { + float dot = 0.0; + float l2_y = 0.0; + + // Instead of using functions above, we combine the loop to reduce overhead + // of the fp16 to fp32 conversion. +#pragma clang loop unroll(enable) interleave(enable) vectorize(enable) + for (uint32_t i = 0; i < dimension; i++) { + float y_i = (float) y[i]; + dot += (float) x[i] * y_i; + l2_y += y_i * y_i; + } + + return 1.0 - dot / (x_norm * sqrtf(l2_y)); +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/f32.rs b/rust/lancedb/vendor/lance-linalg/src/simd/f32.rs new file mode 100644 index 000000000..718786f99 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/f32.rs @@ -0,0 +1,1363 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! `f32x8`, 8 of `f32` values.s + +use std::fmt::Formatter; + +#[cfg(target_arch = "aarch64")] +use std::arch::aarch64::*; +#[cfg(target_arch = "loongarch64")] +use std::arch::loongarch64::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; +#[cfg(target_arch = "loongarch64")] +use std::mem::transmute; +use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; + +use super::{FloatSimd, SIMD}; + +/// 8 of 32-bit `f32` values. Use 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct f32x8(std::arch::x86_64::__m256); + +/// 8 of 32-bit `f32` values. Use 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct f32x8(float32x4x2_t); + +/// 8 of 32-bit `f32` values. Use 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "loongarch64")] +#[derive(Clone, Copy)] +pub struct f32x8(v8f32); + +#[allow(non_camel_case_types)] +#[cfg(simd_fallback)] +#[derive(Clone, Copy)] +pub struct f32x8([f32; 8]); + +impl std::fmt::Debug for f32x8 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0.0_f32; 8]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "f32x8({:?})", arr) + } +} + +impl f32x8 { + /// Gather 8 f32 values from `slice` at the offsets in `indices`. + /// + /// On x86_64 this uses the AVX2 `vgatherdps` instruction when the host + /// supports it (gated at runtime via `is_x86_feature_detected!`). On + /// other architectures (and on x86_64 hosts without AVX2) the function + /// falls back to a per-index scalar load followed by `Self::from(&out)`, + /// which goes through `load_unaligned` (NEON / LASX / `_mm256_loadu_ps` + /// depending on platform). Per-tier macro stamping (e.g., the + /// `multiversion` crate) was considered but doesn't fit here: the function + /// returns `Self` and `_mm256_i32gather_ps::<4>` requires the const-generic + /// stride to be a compile-time literal — neither composes with the macro. + /// + /// # Panics + /// + /// If any index is negative or lands outside `slice`. + #[inline] + pub fn gather(slice: &[f32], indices: &[i32; 8]) -> Self { + // Every backend below reads without bounds checking: `vgatherdps` does + // none, and the NEON / LASX arms offset a raw pointer. Check once here + // so an out-of-range index panics on every host rather than reading out + // of bounds on some and panicking on others. + for &i in indices { + assert!( + (i as usize) < slice.len(), + "gather index {i} is out of bounds for a slice of length {}", + slice.len() + ); + } + + #[cfg(target_arch = "x86_64")] + { + if is_x86_feature_detected!("avx2") { + unsafe { gather_avx2(slice, indices) } + } else { + gather_scalar_x86(slice, indices) + } + } + + #[cfg(target_arch = "aarch64")] + unsafe { + // aarch64 does not have relevant SIMD instructions. + let ptr = slice.as_ptr(); + + let values = [ + *ptr.add(indices[0] as usize), + *ptr.add(indices[1] as usize), + *ptr.add(indices[2] as usize), + *ptr.add(indices[3] as usize), + *ptr.add(indices[4] as usize), + *ptr.add(indices[5] as usize), + *ptr.add(indices[6] as usize), + *ptr.add(indices[7] as usize), + ]; + Self::load_unaligned(values.as_ptr()) + } + + #[cfg(target_arch = "loongarch64")] + unsafe { + // loongarch64 does not have relevant SIMD instructions. + let ptr = slice.as_ptr(); + + let values = [ + *ptr.add(indices[0] as usize), + *ptr.add(indices[1] as usize), + *ptr.add(indices[2] as usize), + *ptr.add(indices[3] as usize), + *ptr.add(indices[4] as usize), + *ptr.add(indices[5] as usize), + *ptr.add(indices[6] as usize), + *ptr.add(indices[7] as usize), + ]; + Self::load_unaligned(values.as_ptr()) + } + #[cfg(simd_fallback)] + { + Self(indices.map(|i| slice[i as usize])) + } + } +} + +/// AVX2 gather. Caller must ensure the host supports AVX2 (gated by +/// the `is_x86_feature_detected!("avx2")` check in `f32x8::gather`). +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn gather_avx2(slice: &[f32], indices: &[i32; 8]) -> f32x8 { + use super::i32::i32x8; + + let idx = i32x8::from(indices); + f32x8(_mm256_i32gather_ps::<4>(slice.as_ptr(), idx.0)) +} + +/// Portable scalar gather for x86_64 hosts without AVX2. +/// +/// Indexes the slice rather than offsetting a raw pointer: this is the slow +/// path already, so an out-of-range index should panic instead of reading out +/// of bounds. +#[cfg(target_arch = "x86_64")] +#[inline] +fn gather_scalar_x86(slice: &[f32], indices: &[i32; 8]) -> f32x8 { + let values = indices.map(|i| slice[i as usize]); + // SAFETY: `values` is eight contiguous, initialized `f32`. + unsafe { f32x8::load_unaligned(values.as_ptr()) } +} + +impl From<&[f32]> for f32x8 { + /// Loads the first 8 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 8 values. + fn from(value: &[f32]) -> Self { + assert!( + value.len() >= 8, + "f32x8 requires at least 8 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl<'a> From<&'a [f32; 8]> for f32x8 { + fn from(value: &'a [f32; 8]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for f32x8 { + fn splat(val: f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_set1_ps(val)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x2_t(vdupq_n_f32(val), vdupq_n_f32(val))) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(transmute(lasx_xvreplgr2vr_w(transmute(val)))) + } + #[cfg(simd_fallback)] + { + Self([val; 8]) + } + } + + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_setzero_ps()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0.0) + } + #[cfg(target_arch = "loongarch64")] + { + Self::splat(0.0) + } + #[cfg(simd_fallback)] + { + Self::splat(0.0) + } + } + + #[inline] + unsafe fn load(ptr: *const f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_load_ps(ptr)) + } + #[cfg(target_arch = "aarch64")] + { + Self::load_unaligned(ptr) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self::load_unaligned(ptr) } + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + // Treat the register as plain data so this load remains valid on + // pre-AVX hosts. LLVM still lowers this to an AVX move when AVX is + // enabled for the caller. + Self(ptr.cast::<__m256>().read_unaligned()) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_f32_x2(ptr)) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self(std::ptr::read_unaligned(ptr as *const [f32; 8])) } + } + } + + unsafe fn store(&self, ptr: *mut f32) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_store_ps(ptr, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f32_x2(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { self.store_unaligned(ptr) } + } + } + + unsafe fn store_unaligned(&self, ptr: *mut f32) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_storeu_ps(ptr, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f32_x2(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { std::ptr::write_unaligned(ptr as *mut [f32; 8], self.0) } + } + } + + #[inline] + fn reduce_sum(&self) -> f32 { + #[cfg(target_arch = "x86_64")] + unsafe { + let mut sum = self.0; + // Shift and add vector, until only 1 value left. + // sums = [x0-x7], shift = [x4-x7] + let mut shift = _mm256_permute2f128_ps(sum, sum, 1); + // [x0+x4, x1+x5, ..] + sum = _mm256_add_ps(sum, shift); + shift = _mm256_permute_ps(sum, 14); + sum = _mm256_add_ps(sum, shift); + sum = _mm256_hadd_ps(sum, sum); + let mut results: [f32; 8] = [0f32; 8]; + _mm256_storeu_ps(results.as_mut_ptr(), sum); + results[0] + } + #[cfg(target_arch = "aarch64")] + unsafe { + let sum = vaddq_f32(self.0.0, self.0.1); + vaddvq_f32(sum) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array().iter().sum() + } + #[cfg(simd_fallback)] + { + self.0.iter().sum() + } + } + + fn reduce_min(&self) -> f32 { + #[cfg(target_arch = "x86_64")] + { + unsafe { + let mut min = self.0; + // Shift and add vector, until only 1 value left. + // sums = [x0-x7], shift = [x4-x7] + let mut shift = _mm256_permute2f128_ps(min, min, 1); + // [x0+x4, x1+x5, ..] + min = _mm256_min_ps(min, shift); + shift = _mm256_permute_ps(min, 14); + min = _mm256_min_ps(min, shift); + shift = _mm256_permute_ps(min, 1); + min = _mm256_min_ps(min, shift); + _mm256_cvtss_f32(min) + } + } + #[cfg(target_arch = "aarch64")] + unsafe { + let m = vminq_f32(self.0.0, self.0.1); + vminvq_f32(m) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + let m1 = lasx_xvpermi_d::<14>(transmute(self.0)); + let m2 = lasx_xvfmin_s(transmute(m1), self.0); + let m1 = lasx_xvpermi_w::<14>(transmute(m2), transmute(m2)); + let m2 = lasx_xvfmin_s(transmute(m1), transmute(m2)); + let m1 = lasx_xvpermi_w::<1>(transmute(m2), transmute(m2)); + let m2 = lasx_xvfmin_s(transmute(m1), transmute(m2)); + transmute(lasx_xvpickve2gr_w::<0>(transmute(m2))) + } + #[cfg(simd_fallback)] + { + self.0.iter().copied().fold(f32::INFINITY, f32::min) + } + } + + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_min_ps(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x2_t( + vminq_f32(self.0.0, rhs.0.0), + vminq_f32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmin_s(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].min(rhs.0[i]))) + } + } + + fn find(&self, val: f32) -> Option { + #[cfg(target_arch = "x86_64")] + unsafe { + for i in 0..8 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + #[cfg(target_arch = "aarch64")] + unsafe { + let tgt = vdupq_n_f32(val); + let mut arr = [0; 8]; + let mask1 = vceqq_f32(self.0.0, tgt); + let mask2 = vceqq_f32(self.0.1, tgt); + vst1q_u32(arr.as_mut_ptr(), mask1); + vst1q_u32(arr.as_mut_ptr().add(4), mask2); + for i in 0..8 { + if arr.get_unchecked(i) != &0 { + return Some(i as i32); + } + } + } + #[cfg(target_arch = "loongarch64")] + unsafe { + for i in 0..8 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + #[cfg(simd_fallback)] + { + if let Some(i) = self.0.iter().position(|&v| v == val) { + return Some(i as i32); + } + } + None + } +} + +impl FloatSimd for f32x8 { + fn multiply_add(&mut self, a: Self, b: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_fmadd_ps(a.0, b.0, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vfmaq_f32(self.0.0, a.0.0, b.0.0); + self.0.1 = vfmaq_f32(self.0.1, a.0.1, b.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfmadd_s(a.0, b.0, self.0); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] = a.0[i].mul_add(b.0[i], self.0[i]); + } + } + } +} + +impl Add for f32x8 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_add_ps(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x2_t( + vaddq_f32(self.0.0, rhs.0.0), + vaddq_f32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfadd_s(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] + rhs.0[i])) + } + } +} + +impl AddAssign for f32x8 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_add_ps(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vaddq_f32(self.0.0, rhs.0.0); + self.0.1 = vaddq_f32(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfadd_s(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] += rhs.0[i]; + } + } + } +} + +impl Sub for f32x8 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_sub_ps(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x2_t( + vsubq_f32(self.0.0, rhs.0.0), + vsubq_f32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfsub_s(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] - rhs.0[i])) + } + } +} + +impl SubAssign for f32x8 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_sub_ps(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vsubq_f32(self.0.0, rhs.0.0); + self.0.1 = vsubq_f32(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfsub_s(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] -= rhs.0[i]; + } + } + } +} + +impl Mul for f32x8 { + type Output = Self; + + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_mul_ps(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x2_t( + vmulq_f32(self.0.0, rhs.0.0), + vmulq_f32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmul_s(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] * rhs.0[i])) + } + } +} + +/// 16 of 32-bit `f32` values. Stored as a pair of 256-bit AVX vectors on +/// x86_64. Originally there was a sibling AVX-512 variant gated on +/// `target_feature = "avx512f"`, but no project CI configuration enables +/// `+avx512f` globally (and one of the avx512 arms still contained `todo!()`), +/// so the variant was dead code. Removed in the runtime-SIMD-dispatch +/// retrofit; per-tier dispatch happens in the kernel functions in +/// `crate::distance::*` via `match *SIMD_SUPPORT` + per-tier +/// `#[target_feature(enable = "...")]` inner functions. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct f32x16(__m256, __m256); + +/// 16 of 32-bit `f32` values. Use 512-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct f32x16(float32x4x4_t); + +/// 16 of 32-bit `f32` values. Use 256-bit SIMD +#[allow(non_camel_case_types)] +#[cfg(target_arch = "loongarch64")] +#[derive(Clone, Copy)] +pub struct f32x16(v8f32, v8f32); + +#[allow(non_camel_case_types)] +#[cfg(simd_fallback)] +#[derive(Clone, Copy)] +pub struct f32x16([f32; 16]); + +impl std::fmt::Debug for f32x16 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0.0_f32; 16]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "f32x16({:?})", arr) + } +} + +impl From<&[f32]> for f32x16 { + /// Loads the first 16 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 16 values. + fn from(value: &[f32]) -> Self { + assert!( + value.len() >= 16, + "f32x16 requires at least 16 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl<'a> From<&'a [f32; 16]> for f32x16 { + fn from(value: &'a [f32; 16]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for f32x16 { + #[inline] + fn splat(val: f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_set1_ps(val), _mm256_set1_ps(val)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x4_t( + vdupq_n_f32(val), + vdupq_n_f32(val), + vdupq_n_f32(val), + vdupq_n_f32(val), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self( + transmute(lasx_xvreplgr2vr_w(transmute(val))), + transmute(lasx_xvreplgr2vr_w(transmute(val))), + ) + } + #[cfg(simd_fallback)] + { + Self([val; 16]) + } + } + + #[inline] + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_setzero_ps(), _mm256_setzero_ps()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0.0) + } + #[cfg(target_arch = "loongarch64")] + { + Self::splat(0.0) + } + #[cfg(simd_fallback)] + { + Self::splat(0.0) + } + } + + #[inline] + unsafe fn load(ptr: *const f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_load_ps(ptr), _mm256_load_ps(ptr.add(8))) + } + #[cfg(target_arch = "aarch64")] + { + Self::load_unaligned(ptr) + } + #[cfg(target_arch = "loongarch64")] + { + Self( + transmute(lasx_xvld::<0>(transmute(ptr))), + transmute(lasx_xvld::<32>(transmute(ptr))), + ) + } + #[cfg(simd_fallback)] + { + unsafe { Self::load_unaligned(ptr) } + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const f32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + // Treat the registers as plain data so this load remains valid on + // pre-AVX hosts. LLVM still lowers these to AVX moves when AVX is + // enabled for the caller. + let ptr = ptr.cast::<__m256>(); + Self(ptr.read_unaligned(), ptr.add(1).read_unaligned()) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_f32_x4(ptr)) + } + #[cfg(target_arch = "loongarch64")] + { + Self( + transmute(lasx_xvld::<0>(transmute(ptr))), + transmute(lasx_xvld::<32>(transmute(ptr))), + ) + } + #[cfg(simd_fallback)] + { + unsafe { Self(std::ptr::read_unaligned(ptr as *const [f32; 16])) } + } + } + + #[inline] + unsafe fn store(&self, ptr: *mut f32) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_store_ps(ptr, self.0); + _mm256_store_ps(ptr.add(8), self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f32_x4(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + lasx_xvst::<32>(transmute(self.1), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { self.store_unaligned(ptr) } + } + } + + #[inline] + unsafe fn store_unaligned(&self, ptr: *mut f32) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_storeu_ps(ptr, self.0); + _mm256_storeu_ps(ptr.add(8), self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f32_x4(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + lasx_xvst::<32>(transmute(self.1), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { std::ptr::write_unaligned(ptr as *mut [f32; 16], self.0) } + } + } + + #[inline] + fn reduce_sum(&self) -> f32 { + #[cfg(target_arch = "x86_64")] + unsafe { + let mut sum = _mm256_add_ps(self.0, self.1); + // Shift and add vector, until only 1 value left. + // sums = [x0-x7], shift = [x4-x7] + let mut shift = _mm256_permute2f128_ps(sum, sum, 1); + // [x0+x4, x1+x5, ..] + sum = _mm256_add_ps(sum, shift); + shift = _mm256_permute_ps(sum, 14); + sum = _mm256_add_ps(sum, shift); + sum = _mm256_hadd_ps(sum, sum); + let mut results: [f32; 8] = [0f32; 8]; + _mm256_storeu_ps(results.as_mut_ptr(), sum); + results[0] + } + #[cfg(target_arch = "aarch64")] + unsafe { + let mut sum1 = vaddq_f32(self.0.0, self.0.1); + let sum2 = vaddq_f32(self.0.2, self.0.3); + sum1 = vaddq_f32(sum1, sum2); + vaddvq_f32(sum1) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array().iter().sum() + } + #[cfg(simd_fallback)] + { + self.0.iter().sum() + } + } + + #[inline] + fn reduce_min(&self) -> f32 { + #[cfg(target_arch = "x86_64")] + unsafe { + let mut m1 = _mm256_min_ps(self.0, self.1); + let mut m2 = _mm256_permute2f128_ps(m1, m1, 1); + m1 = _mm256_min_ps(m1, m2); + m2 = _mm256_permute_ps(m1, 14); + m1 = _mm256_min_ps(m1, m2); + m2 = _mm256_permute_ps(m1, 1); + m1 = _mm256_min_ps(m1, m2); + _mm256_cvtss_f32(m1) + } + + #[cfg(target_arch = "aarch64")] + unsafe { + let m1 = vminq_f32(self.0.0, self.0.1); + let m2 = vminq_f32(self.0.2, self.0.3); + let m = vminq_f32(m1, m2); + vminvq_f32(m) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + let m1 = lasx_xvfmin_s(self.0, self.1); + let m2 = lasx_xvpermi_d::<14>(transmute(m1)); + let m1 = lasx_xvfmin_s(transmute(m1), transmute(m2)); + let m2 = lasx_xvpermi_w::<14>(transmute(m1), transmute(m1)); + let m1 = lasx_xvfmin_s(transmute(m1), transmute(m2)); + let m2 = lasx_xvpermi_w::<1>(transmute(m1), transmute(m1)); + let m1 = lasx_xvfmin_s(transmute(m1), transmute(m2)); + transmute(lasx_xvpickve2gr_w::<0>(transmute(m1))) + } + #[cfg(simd_fallback)] + { + self.0.iter().copied().fold(f32::INFINITY, f32::min) + } + } + + #[inline] + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_min_ps(self.0, rhs.0), _mm256_min_ps(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x4_t( + vminq_f32(self.0.0, rhs.0.0), + vminq_f32(self.0.1, rhs.0.1), + vminq_f32(self.0.2, rhs.0.2), + vminq_f32(self.0.3, rhs.0.3), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmin_s(self.0, rhs.0), lasx_xvfmin_s(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].min(rhs.0[i]))) + } + } + + #[inline] + fn find(&self, val: f32) -> Option { + #[cfg(target_arch = "x86_64")] + unsafe { + // _mm256_cmpeq_ps_mask requires AVX-512 (avx512f); use a scalar scan here + // since we only require AVX2. + let arr = self.as_array(); + for i in 0..16 { + if arr.get_unchecked(i) == &val { + return Some(i as i32); + } + } + None + } + #[cfg(target_arch = "aarch64")] + unsafe { + let tgt = vdupq_n_f32(val); + let mut arr = [0; 16]; + let mask1 = vceqq_f32(self.0.0, tgt); + let mask2 = vceqq_f32(self.0.1, tgt); + let mask3 = vceqq_f32(self.0.2, tgt); + let mask4 = vceqq_f32(self.0.3, tgt); + + vst1q_u32(arr.as_mut_ptr(), mask1); + vst1q_u32(arr.as_mut_ptr().add(4), mask2); + vst1q_u32(arr.as_mut_ptr().add(8), mask3); + vst1q_u32(arr.as_mut_ptr().add(12), mask4); + + for i in 0..16 { + if arr.get_unchecked(i) != &0 { + return Some(i as i32); + } + } + None + } + #[cfg(target_arch = "loongarch64")] + unsafe { + for i in 0..16 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + None + } + #[cfg(simd_fallback)] + { + self.0.iter().position(|&v| v == val).map(|i| i as i32) + } + } +} + +impl FloatSimd for f32x16 { + #[inline] + fn multiply_add(&mut self, a: Self, b: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_fmadd_ps(a.0, b.0, self.0); + self.1 = _mm256_fmadd_ps(a.1, b.1, self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vfmaq_f32(self.0.0, a.0.0, b.0.0); + self.0.1 = vfmaq_f32(self.0.1, a.0.1, b.0.1); + self.0.2 = vfmaq_f32(self.0.2, a.0.2, b.0.2); + self.0.3 = vfmaq_f32(self.0.3, a.0.3, b.0.3); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfmadd_s(a.0, b.0, self.0); + self.1 = lasx_xvfmadd_s(a.1, b.1, self.1); + } + #[cfg(simd_fallback)] + { + for i in 0..16 { + self.0[i] = a.0[i].mul_add(b.0[i], self.0[i]); + } + } + } +} + +impl Add for f32x16 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_add_ps(self.0, rhs.0), _mm256_add_ps(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x4_t( + vaddq_f32(self.0.0, rhs.0.0), + vaddq_f32(self.0.1, rhs.0.1), + vaddq_f32(self.0.2, rhs.0.2), + vaddq_f32(self.0.3, rhs.0.3), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfadd_s(self.0, rhs.0), lasx_xvfadd_s(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] + rhs.0[i])) + } + } +} + +impl AddAssign for f32x16 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_add_ps(self.0, rhs.0); + self.1 = _mm256_add_ps(self.1, rhs.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vaddq_f32(self.0.0, rhs.0.0); + self.0.1 = vaddq_f32(self.0.1, rhs.0.1); + self.0.2 = vaddq_f32(self.0.2, rhs.0.2); + self.0.3 = vaddq_f32(self.0.3, rhs.0.3); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfadd_s(self.0, rhs.0); + self.1 = lasx_xvfadd_s(self.1, rhs.1); + } + #[cfg(simd_fallback)] + { + for i in 0..16 { + self.0[i] += rhs.0[i]; + } + } + } +} + +impl Mul for f32x16 { + type Output = Self; + + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_mul_ps(self.0, rhs.0), _mm256_mul_ps(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x4_t( + vmulq_f32(self.0.0, rhs.0.0), + vmulq_f32(self.0.1, rhs.0.1), + vmulq_f32(self.0.2, rhs.0.2), + vmulq_f32(self.0.3, rhs.0.3), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmul_s(self.0, rhs.0), lasx_xvfmul_s(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] * rhs.0[i])) + } + } +} + +impl Sub for f32x16 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_sub_ps(self.0, rhs.0), _mm256_sub_ps(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float32x4x4_t( + vsubq_f32(self.0.0, rhs.0.0), + vsubq_f32(self.0.1, rhs.0.1), + vsubq_f32(self.0.2, rhs.0.2), + vsubq_f32(self.0.3, rhs.0.3), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfsub_s(self.0, rhs.0), lasx_xvfsub_s(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] - rhs.0[i])) + } + } +} + +impl SubAssign for f32x16 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_sub_ps(self.0, rhs.0); + self.1 = _mm256_sub_ps(self.1, rhs.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vsubq_f32(self.0.0, rhs.0.0); + self.0.1 = vsubq_f32(self.0.1, rhs.0.1); + self.0.2 = vsubq_f32(self.0.2, rhs.0.2); + self.0.3 = vsubq_f32(self.0.3, rhs.0.3); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfsub_s(self.0, rhs.0); + self.1 = lasx_xvfsub_s(self.1, rhs.1); + } + #[cfg(simd_fallback)] + { + for i in 0..16 { + self.0[i] -= rhs.0[i]; + } + } + } +} + +#[cfg(test)] +mod tests { + + use super::*; + use rstest::rstest; + + #[test] + fn test_slice_conversion_rejects_short_input() { + assert!(std::panic::catch_unwind(|| f32x8::from(&[0.0; 7][..])).is_err()); + assert!(std::panic::catch_unwind(|| f32x16::from(&[0.0; 15][..])).is_err()); + } + + #[test] + fn test_slice_conversion_uses_cpu_baseline() { + let values8 = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + let values16 = [ + 1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, + 16.0, + ]; + let vectors = ( + f32x8::from(&values8[..]), + f32x8::from(&values8), + f32x16::from(&values16[..]), + f32x16::from(&values16), + ); + + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + std::hint::black_box(vectors); + return; + } + + assert_eq!(vectors.0.as_array(), values8); + assert_eq!(vectors.1.as_array(), values8); + assert_eq!(vectors.2.as_array(), values16); + assert_eq!(vectors.3.as_array(), values16); + } + + #[test] + fn test_basic_ops() { + // Load / store / arithmetic on `f32x8` lower to AVX intrinsics, and + // `multiply_add` lowers to `_mm256_fmadd_ps`, which needs FMA. Both + // are present from the AvxFma tier up. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") || !std::is_x86_feature_detected!("fma") { + return; + } + let a = (0..8).map(|f| f as f32).collect::>(); + let b = (10..18).map(|f| f as f32).collect::>(); + + let mut simd_a = unsafe { f32x8::load_unaligned(a.as_ptr()) }; + let simd_b = unsafe { f32x8::load_unaligned(b.as_ptr()) }; + + let simd_add = simd_a + simd_b; + assert!( + (0..8) + .zip(simd_add.as_array().iter()) + .all(|(x, &y)| (x + x + 10) as f32 == y) + ); + + let simd_mul = simd_a * simd_b; + assert!( + (0..8) + .zip(simd_mul.as_array().iter()) + .all(|(x, &y)| (x * (x + 10)) as f32 == y) + ); + + let simd_sub = simd_b - simd_a; + assert!(simd_sub.as_array().iter().all(|&v| v == 10.0)); + + simd_a -= simd_b; + assert_eq!(simd_a.reduce_sum(), -80.0); + + let mut simd_power = f32x8::splat(0.0); + simd_power.multiply_add(simd_a, simd_a); + + assert_eq!( + "f32x8([100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0])", + format!("{:?}", simd_power) + ); + } + + #[test] + fn test_f32x8_cmp_ops() { + // `min` / `reduce_min` are AVX intrinsics; `find` is a scalar scan. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a = [1.0_f32, 2.0, 5.0, 6.0, 7.0, 3.0, 2.0, 1.0]; + let b = [2.0_f32, 1.0, 4.0, 5.0, 9.0, 5.0, 6.0, 2.0]; + let c = [2.0_f32, 1.0, 4.0, 5.0, 7.0, 3.0, 2.0, 1.0]; + let simd_a: f32x8 = (&a).into(); + let simd_b: f32x8 = (&b).into(); + let simd_c: f32x8 = (&c).into(); + + let min_simd = simd_a.min(&simd_b); + assert_eq!( + min_simd.as_array(), + [1.0, 1.0, 4.0, 5.0, 7.0, 3.0, 2.0, 1.0] + ); + let min_val = min_simd.reduce_min(); + assert_eq!(min_val, 1.0); + let min_val = simd_c.reduce_min(); + assert_eq!(min_val, 1.0); + + assert_eq!(Some(2), simd_a.find(5.0)); + assert_eq!(Some(1), simd_a.find(2.0)); + assert_eq!(None, simd_a.find(-200.0)); + } + + #[test] + fn test_basic_f32x16_ops() { + // `f32x16` is a pair of `__m256`; `multiply_add` needs FMA. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") || !std::is_x86_feature_detected!("fma") { + return; + } + let a = (0..16).map(|f| f as f32).collect::>(); + let b = (10..26).map(|f| f as f32).collect::>(); + + let mut simd_a = unsafe { f32x16::load_unaligned(a.as_ptr()) }; + let simd_b = unsafe { f32x16::load_unaligned(b.as_ptr()) }; + + let simd_add = simd_a + simd_b; + assert!( + (0..16) + .zip(simd_add.as_array().iter()) + .all(|(x, &y)| (x + x + 10) as f32 == y) + ); + + let simd_mul = simd_a * simd_b; + assert!( + (0..16) + .zip(simd_mul.as_array().iter()) + .all(|(x, &y)| (x * (x + 10)) as f32 == y) + ); + + simd_a -= simd_b; + assert_eq!(simd_a.reduce_sum(), -160.0); + + let mut simd_power = f32x16::zeros(); + simd_power.multiply_add(simd_a, simd_a); + + assert_eq!( + format!("f32x16({:?})", [100.0; 16]), + format!("{:?}", simd_power) + ); + } + + #[test] + fn test_f32x16_cmp_ops() { + // `min` / `reduce_min` are AVX intrinsics; `find` is a scalar scan. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a = [ + 1.0_f32, 2.0, 5.0, 6.0, 7.0, 3.0, 2.0, 1.0, -0.5, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0, 2.0, + ]; + let b = [ + 2.0_f32, 1.0, 4.0, 5.0, 9.0, 5.0, 6.0, 2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 2.0, 1.0, + ]; + let c = [ + 1.0_f32, 1.0, 4.0, 5.0, 7.0, 3.0, 2.0, 1.0, -0.5, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0, -1.0, + ]; + let simd_a: f32x16 = (&a).into(); + let simd_b: f32x16 = (&b).into(); + let simd_c: f32x16 = (&c).into(); + + let min_simd = simd_a.min(&simd_b); + assert_eq!( + min_simd.as_array(), + [ + 1.0, 1.0, 4.0, 5.0, 7.0, 3.0, 2.0, 1.0, -0.5, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0, 1.0 + ] + ); + let min_val = min_simd.reduce_min(); + assert_eq!(min_val, -0.5); + let min_val = simd_c.reduce_min(); + assert_eq!(min_val, -1.0); + + assert_eq!(Some(2), simd_a.find(5.0)); + assert_eq!(Some(1), simd_a.find(2.0)); + assert_eq!(Some(13), simd_a.find(9.0)); + assert_eq!(None, simd_a.find(-200.0)); + } + + #[test] + fn test_f32x8_gather() { + // `f32x8::gather` does its own runtime AVX2 detection and falls back + // to a scalar gather, so this test only needs whatever reading the + // `__m256`-backed result costs: AVX, for `reduce_sum`. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a = (0..256).map(|f| f as f32).collect::>(); + let idx = [0_i32, 4, 8, 12, 16, 20, 24, 29]; + let v = f32x8::gather(&a, &idx); + assert_eq!(v.reduce_sum(), 113.0); + } + + /// Directly exercises `gather_scalar_x86`, the per-index scalar fallback + /// `f32x8::gather` takes on x86_64 hosts without AVX2. Runtime AVX2 hosts + /// route through `gather_avx2` instead, so the fallback is otherwise never + /// hit under coverage. Reading the `__m256`-backed result needs AVX, so + /// skip on hosts without it. + #[cfg(target_arch = "x86_64")] + #[test] + fn test_gather_scalar_x86() { + let a = (0..256).map(|f| f as f32).collect::>(); + let idx = [0_i32, 4, 8, 12, 16, 20, 24, 29]; + let v = gather_scalar_x86(&a, &idx); + + if !std::is_x86_feature_detected!("avx") { + std::hint::black_box(v); + return; + } + + let expected = idx.map(|i| a[i as usize]); + assert_eq!(v.as_array(), expected); + } + + /// An index past the end of the slice panics rather than reading out of + /// bounds. The bounds check fires before any AVX instruction, so this + /// case runs on every x86_64 host. + #[cfg(target_arch = "x86_64")] + #[test] + #[should_panic(expected = "index out of bounds")] + fn test_gather_scalar_x86_rejects_out_of_range_index() { + let a = (0..8).map(|f| f as f32).collect::>(); + let idx = [0_i32, 1, 2, 3, 4, 5, 6, 99]; + let _ = gather_scalar_x86(&a, &idx); + } + + /// `gather` validates before dispatching, so every backend — `vgatherdps`, + /// the x86 scalar fallback, and the NEON / LASX raw-pointer arms — rejects + /// a bad index identically instead of reading out of bounds. + #[rstest] + #[case::past_end(99)] + #[case::negative(-1)] + #[should_panic(expected = "out of bounds")] + fn test_gather_rejects_invalid_index(#[case] bad_index: i32) { + let a = (0..8).map(|f| f as f32).collect::>(); + let idx = [0_i32, 1, 2, 3, 4, 5, 6, bad_index]; + let _ = f32x8::gather(&a, &idx); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/f64.rs b/rust/lancedb/vendor/lance-linalg/src/simd/f64.rs new file mode 100644 index 000000000..fe72f119d --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/f64.rs @@ -0,0 +1,1058 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! `f64x4` and `f64x8` SIMD types for f64 distance computations. + +use std::fmt::Formatter; + +#[cfg(target_arch = "aarch64")] +use std::arch::aarch64::*; +#[cfg(target_arch = "loongarch64")] +use std::arch::loongarch64::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; +#[cfg(target_arch = "loongarch64")] +use std::mem::transmute; +use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; + +use super::{FloatSimd, SIMD}; + +/// 4 of 64-bit `f64` values. Uses 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct f64x4(std::arch::x86_64::__m256d); + +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct f64x4(float64x2x2_t); + +#[allow(non_camel_case_types)] +#[cfg(target_arch = "loongarch64")] +#[derive(Clone, Copy)] +pub struct f64x4(v4f64); + +#[allow(non_camel_case_types)] +#[cfg(simd_fallback)] +#[derive(Clone, Copy)] +pub struct f64x4([f64; 4]); + +impl std::fmt::Debug for f64x4 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0.0_f64; 4]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "f64x4({:?})", arr) + } +} + +impl From<&[f64]> for f64x4 { + /// Loads the first 4 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 4 values. + fn from(value: &[f64]) -> Self { + assert!( + value.len() >= 4, + "f64x4 requires at least 4 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl<'a> From<&'a [f64; 4]> for f64x4 { + fn from(value: &'a [f64; 4]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for f64x4 { + fn splat(val: f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_set1_pd(val)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float64x2x2_t(vdupq_n_f64(val), vdupq_n_f64(val))) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(transmute(lasx_xvreplgr2vr_d(transmute(val)))) + } + #[cfg(simd_fallback)] + { + Self([val; 4]) + } + } + + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_setzero_pd()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0.0) + } + #[cfg(target_arch = "loongarch64")] + { + Self::splat(0.0) + } + #[cfg(simd_fallback)] + { + Self::splat(0.0) + } + } + + #[inline] + unsafe fn load(ptr: *const f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_load_pd(ptr)) + } + #[cfg(target_arch = "aarch64")] + { + Self::load_unaligned(ptr) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self::load_unaligned(ptr) } + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + // Treat the register as plain data so this load remains valid on + // pre-AVX hosts. LLVM still lowers this to an AVX move when AVX is + // enabled for the caller. + Self(ptr.cast::<__m256d>().read_unaligned()) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_f64_x2(ptr)) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self(std::ptr::read_unaligned(ptr as *const [f64; 4])) } + } + } + + unsafe fn store(&self, ptr: *mut f64) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_store_pd(ptr, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f64_x2(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { self.store_unaligned(ptr) } + } + } + + unsafe fn store_unaligned(&self, ptr: *mut f64) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_storeu_pd(ptr, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f64_x2(ptr, self.0); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { std::ptr::write_unaligned(ptr as *mut [f64; 4], self.0) } + } + } + + #[inline] + fn reduce_sum(&self) -> f64 { + #[cfg(target_arch = "x86_64")] + unsafe { + // [a, b, c, d] -> hadd -> [a+b, a+b, c+d, c+d] + let sum = _mm256_hadd_pd(self.0, self.0); + // Extract low 128 and high 128, add them + let lo = _mm256_castpd256_pd128(sum); + let hi = _mm256_extractf128_pd(sum, 1); + let r = _mm_add_pd(lo, hi); + _mm_cvtsd_f64(r) + } + #[cfg(target_arch = "aarch64")] + unsafe { + let sum = vaddq_f64(self.0.0, self.0.1); + vaddvq_f64(sum) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array().iter().sum() + } + #[cfg(simd_fallback)] + { + self.0.iter().sum() + } + } + + fn reduce_min(&self) -> f64 { + #[cfg(target_arch = "x86_64")] + unsafe { + // Swap high/low 128-bit lanes and min + let hi = _mm256_permute2f128_pd(self.0, self.0, 1); + let m = _mm256_min_pd(self.0, hi); + // Swap within 128-bit lane and min + let shuf = _mm256_permute_pd(m, 0b0101); + let m = _mm256_min_pd(m, shuf); + _mm256_cvtsd_f64(m) + } + #[cfg(target_arch = "aarch64")] + unsafe { + let m = vminq_f64(self.0.0, self.0.1); + vminvq_f64(m) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array() + .iter() + .copied() + .fold(f64::INFINITY, f64::min) + } + #[cfg(simd_fallback)] + { + self.0.iter().copied().fold(f64::INFINITY, f64::min) + } + } + + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_min_pd(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float64x2x2_t( + vminq_f64(self.0.0, rhs.0.0), + vminq_f64(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmin_d(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].min(rhs.0[i]))) + } + } + + fn find(&self, val: f64) -> Option { + unsafe { + for i in 0..4 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + None + } +} + +impl FloatSimd for f64x4 { + fn multiply_add(&mut self, a: Self, b: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_fmadd_pd(a.0, b.0, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vfmaq_f64(self.0.0, a.0.0, b.0.0); + self.0.1 = vfmaq_f64(self.0.1, a.0.1, b.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfmadd_d(a.0, b.0, self.0); + } + #[cfg(simd_fallback)] + { + for i in 0..4 { + self.0[i] = a.0[i].mul_add(b.0[i], self.0[i]); + } + } + } +} + +impl Add for f64x4 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_add_pd(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float64x2x2_t( + vaddq_f64(self.0.0, rhs.0.0), + vaddq_f64(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfadd_d(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] + rhs.0[i])) + } + } +} + +impl AddAssign for f64x4 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_add_pd(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vaddq_f64(self.0.0, rhs.0.0); + self.0.1 = vaddq_f64(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfadd_d(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..4 { + self.0[i] += rhs.0[i]; + } + } + } +} + +impl Sub for f64x4 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_sub_pd(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float64x2x2_t( + vsubq_f64(self.0.0, rhs.0.0), + vsubq_f64(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfsub_d(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] - rhs.0[i])) + } + } +} + +impl SubAssign for f64x4 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_sub_pd(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vsubq_f64(self.0.0, rhs.0.0); + self.0.1 = vsubq_f64(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfsub_d(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..4 { + self.0[i] -= rhs.0[i]; + } + } + } +} + +impl Mul for f64x4 { + type Output = Self; + + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_mul_pd(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(float64x2x2_t( + vmulq_f64(self.0.0, rhs.0.0), + vmulq_f64(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmul_d(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] * rhs.0[i])) + } + } +} + +// --------------------------------------------------------------------------- +// f64x8: 8 × f64 values (512-bit SIMD or 2 × 256-bit) +// --------------------------------------------------------------------------- + +/// 8 of 64-bit `f64` values. Stored as a pair of 256-bit AVX vectors on +/// x86_64. Originally there was a sibling AVX-512 variant gated on +/// `target_feature = "avx512f"`, but no project CI configuration enables +/// `+avx512f` globally, so the variant was dead code. Removed in the +/// runtime-SIMD-dispatch retrofit; per-tier dispatch happens in the kernel +/// functions in `crate::distance::*` via `match *SIMD_SUPPORT` + per-tier +/// `#[target_feature(enable = "...")]` inner functions. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct f64x8(__m256d, __m256d); + +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct f64x8(float64x2x2_t, float64x2x2_t); + +#[allow(non_camel_case_types)] +#[cfg(target_arch = "loongarch64")] +#[derive(Clone, Copy)] +pub struct f64x8(v4f64, v4f64); + +#[allow(non_camel_case_types)] +#[cfg(simd_fallback)] +#[derive(Clone, Copy)] +pub struct f64x8([f64; 8]); + +impl std::fmt::Debug for f64x8 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0.0_f64; 8]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "f64x8({:?})", arr) + } +} + +impl From<&[f64]> for f64x8 { + /// Loads the first 8 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 8 values. + fn from(value: &[f64]) -> Self { + assert!( + value.len() >= 8, + "f64x8 requires at least 8 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl<'a> From<&'a [f64; 8]> for f64x8 { + fn from(value: &'a [f64; 8]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for f64x8 { + #[inline] + fn splat(val: f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_set1_pd(val), _mm256_set1_pd(val)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + let v = vdupq_n_f64(val); + Self(float64x2x2_t(v, v), float64x2x2_t(v, v)) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + let v = transmute(lasx_xvreplgr2vr_d(transmute(val))); + Self(v, v) + } + #[cfg(simd_fallback)] + { + Self([val; 8]) + } + } + + #[inline] + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_setzero_pd(), _mm256_setzero_pd()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0.0) + } + #[cfg(target_arch = "loongarch64")] + { + Self::splat(0.0) + } + #[cfg(simd_fallback)] + { + Self::splat(0.0) + } + } + + #[inline] + unsafe fn load(ptr: *const f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_load_pd(ptr), _mm256_load_pd(ptr.add(4))) + } + #[cfg(target_arch = "aarch64")] + { + Self::load_unaligned(ptr) + } + #[cfg(target_arch = "loongarch64")] + { + Self( + transmute(lasx_xvld::<0>(transmute(ptr))), + transmute(lasx_xvld::<32>(transmute(ptr))), + ) + } + #[cfg(simd_fallback)] + { + unsafe { Self::load_unaligned(ptr) } + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const f64) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + // Treat the registers as plain data so this load remains valid on + // pre-AVX hosts. LLVM still lowers these to AVX moves when AVX is + // enabled for the caller. + let ptr = ptr.cast::<__m256d>(); + Self(ptr.read_unaligned(), ptr.add(1).read_unaligned()) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vld1q_f64_x2(ptr), vld1q_f64_x2(ptr.add(4))) + } + #[cfg(target_arch = "loongarch64")] + { + Self( + transmute(lasx_xvld::<0>(transmute(ptr))), + transmute(lasx_xvld::<32>(transmute(ptr))), + ) + } + #[cfg(simd_fallback)] + { + unsafe { Self(std::ptr::read_unaligned(ptr as *const [f64; 8])) } + } + } + + #[inline] + unsafe fn store(&self, ptr: *mut f64) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_store_pd(ptr, self.0); + _mm256_store_pd(ptr.add(4), self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f64_x2(ptr, self.0); + vst1q_f64_x2(ptr.add(4), self.1); + } + #[cfg(target_arch = "loongarch64")] + { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + lasx_xvst::<32>(transmute(self.1), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { self.store_unaligned(ptr) } + } + } + + #[inline] + unsafe fn store_unaligned(&self, ptr: *mut f64) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_storeu_pd(ptr, self.0); + _mm256_storeu_pd(ptr.add(4), self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_f64_x2(ptr, self.0); + vst1q_f64_x2(ptr.add(4), self.1); + } + #[cfg(target_arch = "loongarch64")] + { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)); + lasx_xvst::<32>(transmute(self.1), transmute(ptr)); + } + #[cfg(simd_fallback)] + { + unsafe { std::ptr::write_unaligned(ptr as *mut [f64; 8], self.0) } + } + } + + #[inline] + fn reduce_sum(&self) -> f64 { + #[cfg(target_arch = "x86_64")] + unsafe { + let sum = _mm256_add_pd(self.0, self.1); + let hi = _mm256_permute2f128_pd(sum, sum, 1); + let sum = _mm256_add_pd(sum, hi); + let sum = _mm256_hadd_pd(sum, sum); + _mm256_cvtsd_f64(sum) + } + #[cfg(target_arch = "aarch64")] + unsafe { + let sum0 = vaddq_f64(self.0.0, self.0.1); + let sum1 = vaddq_f64(self.1.0, self.1.1); + let sum = vaddq_f64(sum0, sum1); + vaddvq_f64(sum) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array().iter().sum() + } + #[cfg(simd_fallback)] + { + self.0.iter().sum() + } + } + + #[inline] + fn reduce_min(&self) -> f64 { + #[cfg(target_arch = "x86_64")] + unsafe { + let m = _mm256_min_pd(self.0, self.1); + let hi = _mm256_permute2f128_pd(m, m, 1); + let m = _mm256_min_pd(m, hi); + let shuf = _mm256_permute_pd(m, 0b0101); + let m = _mm256_min_pd(m, shuf); + _mm256_cvtsd_f64(m) + } + #[cfg(target_arch = "aarch64")] + unsafe { + let m0 = vminq_f64(self.0.0, self.0.1); + let m1 = vminq_f64(self.1.0, self.1.1); + let m = vminq_f64(m0, m1); + vminvq_f64(m) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array() + .iter() + .copied() + .fold(f64::INFINITY, f64::min) + } + #[cfg(simd_fallback)] + { + self.0.iter().copied().fold(f64::INFINITY, f64::min) + } + } + + #[inline] + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_min_pd(self.0, rhs.0), _mm256_min_pd(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self( + float64x2x2_t(vminq_f64(self.0.0, rhs.0.0), vminq_f64(self.0.1, rhs.0.1)), + float64x2x2_t(vminq_f64(self.1.0, rhs.1.0), vminq_f64(self.1.1, rhs.1.1)), + ) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmin_d(self.0, rhs.0), lasx_xvfmin_d(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].min(rhs.0[i]))) + } + } + + #[inline] + fn find(&self, val: f64) -> Option { + unsafe { + for i in 0..8 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + None + } +} + +impl FloatSimd for f64x8 { + #[inline] + fn multiply_add(&mut self, a: Self, b: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_fmadd_pd(a.0, b.0, self.0); + self.1 = _mm256_fmadd_pd(a.1, b.1, self.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vfmaq_f64(self.0.0, a.0.0, b.0.0); + self.0.1 = vfmaq_f64(self.0.1, a.0.1, b.0.1); + self.1.0 = vfmaq_f64(self.1.0, a.1.0, b.1.0); + self.1.1 = vfmaq_f64(self.1.1, a.1.1, b.1.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfmadd_d(a.0, b.0, self.0); + self.1 = lasx_xvfmadd_d(a.1, b.1, self.1); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] = a.0[i].mul_add(b.0[i], self.0[i]); + } + } + } +} + +impl Add for f64x8 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_add_pd(self.0, rhs.0), _mm256_add_pd(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self( + float64x2x2_t(vaddq_f64(self.0.0, rhs.0.0), vaddq_f64(self.0.1, rhs.0.1)), + float64x2x2_t(vaddq_f64(self.1.0, rhs.1.0), vaddq_f64(self.1.1, rhs.1.1)), + ) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfadd_d(self.0, rhs.0), lasx_xvfadd_d(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] + rhs.0[i])) + } + } +} + +impl AddAssign for f64x8 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_add_pd(self.0, rhs.0); + self.1 = _mm256_add_pd(self.1, rhs.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vaddq_f64(self.0.0, rhs.0.0); + self.0.1 = vaddq_f64(self.0.1, rhs.0.1); + self.1.0 = vaddq_f64(self.1.0, rhs.1.0); + self.1.1 = vaddq_f64(self.1.1, rhs.1.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfadd_d(self.0, rhs.0); + self.1 = lasx_xvfadd_d(self.1, rhs.1); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] += rhs.0[i]; + } + } + } +} + +impl Mul for f64x8 { + type Output = Self; + + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_mul_pd(self.0, rhs.0), _mm256_mul_pd(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self( + float64x2x2_t(vmulq_f64(self.0.0, rhs.0.0), vmulq_f64(self.0.1, rhs.0.1)), + float64x2x2_t(vmulq_f64(self.1.0, rhs.1.0), vmulq_f64(self.1.1, rhs.1.1)), + ) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfmul_d(self.0, rhs.0), lasx_xvfmul_d(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] * rhs.0[i])) + } + } +} + +impl Sub for f64x8 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_sub_pd(self.0, rhs.0), _mm256_sub_pd(self.1, rhs.1)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self( + float64x2x2_t(vsubq_f64(self.0.0, rhs.0.0), vsubq_f64(self.0.1, rhs.0.1)), + float64x2x2_t(vsubq_f64(self.1.0, rhs.1.0), vsubq_f64(self.1.1, rhs.1.1)), + ) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvfsub_d(self.0, rhs.0), lasx_xvfsub_d(self.1, rhs.1)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i] - rhs.0[i])) + } + } +} + +impl SubAssign for f64x8 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_sub_pd(self.0, rhs.0); + self.1 = _mm256_sub_pd(self.1, rhs.1); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vsubq_f64(self.0.0, rhs.0.0); + self.0.1 = vsubq_f64(self.0.1, rhs.0.1); + self.1.0 = vsubq_f64(self.1.0, rhs.1.0); + self.1.1 = vsubq_f64(self.1.1, rhs.1.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvfsub_d(self.0, rhs.0); + self.1 = lasx_xvfsub_d(self.1, rhs.1); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] -= rhs.0[i]; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_slice_conversion_rejects_short_input() { + assert!(std::panic::catch_unwind(|| f64x4::from(&[0.0; 3][..])).is_err()); + assert!(std::panic::catch_unwind(|| f64x8::from(&[0.0; 7][..])).is_err()); + } + + #[test] + fn test_slice_conversion_uses_cpu_baseline() { + let values4 = [1.0_f64, 2.0, 3.0, 4.0]; + let values8 = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + let vectors = ( + f64x4::from(&values4[..]), + f64x4::from(&values4), + f64x8::from(&values8[..]), + f64x8::from(&values8), + ); + + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + std::hint::black_box(vectors); + return; + } + + assert_eq!(vectors.0.as_array(), values4); + assert_eq!(vectors.1.as_array(), values4); + assert_eq!(vectors.2.as_array(), values8); + assert_eq!(vectors.3.as_array(), values8); + } + + #[test] + fn test_f64x4_basic_ops() { + // The `f64x4` constructor / load / store / arithmetic paths all lower + // to AVX intrinsics on x86_64; none of them need AVX2. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a = [1.0_f64, 2.0, 3.0, 4.0]; + let b = [5.0_f64, 6.0, 7.0, 8.0]; + + let simd_a: f64x4 = (&a).into(); + let simd_b: f64x4 = (&b).into(); + + let sum = simd_a + simd_b; + assert_eq!(sum.as_array(), [6.0, 8.0, 10.0, 12.0]); + + let product = simd_a * simd_b; + assert_eq!(product.as_array(), [5.0, 12.0, 21.0, 32.0]); + + let diff = simd_b - simd_a; + assert_eq!(diff.as_array(), [4.0, 4.0, 4.0, 4.0]); + + assert_eq!(simd_a.reduce_sum(), 10.0); + assert_eq!(simd_a.reduce_min(), 1.0); + } + + #[test] + fn test_f64x4_fma() { + // `multiply_add` lowers to `_mm256_fmadd_pd`, which needs FMA. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") || !std::is_x86_feature_detected!("fma") { + return; + } + let a = [1.0_f64, 2.0, 3.0, 4.0]; + let b = [2.0_f64, 3.0, 4.0, 5.0]; + + let simd_a: f64x4 = (&a).into(); + let simd_b: f64x4 = (&b).into(); + let mut acc = f64x4::zeros(); + acc.multiply_add(simd_a, simd_b); + assert_eq!(acc.as_array(), [2.0, 6.0, 12.0, 20.0]); + } + + #[test] + fn test_f64x4_min() { + // `min` / `reduce_min` are AVX intrinsics. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a = [1.0_f64, 5.0, 2.0, 8.0]; + let b = [3.0_f64, 2.0, 4.0, 1.0]; + let simd_a: f64x4 = (&a).into(); + let simd_b: f64x4 = (&b).into(); + + let m = simd_a.min(&simd_b); + assert_eq!(m.as_array(), [1.0, 2.0, 2.0, 1.0]); + assert_eq!(m.reduce_min(), 1.0); + } + + #[test] + fn test_f64x8_basic_ops() { + // `f64x8` is a pair of `__m256d`; add / reduce are AVX intrinsics. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a: [f64; 8] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + let b: [f64; 8] = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]; + + let simd_a: f64x8 = (&a).into(); + let simd_b: f64x8 = (&b).into(); + + let sum = simd_a + simd_b; + assert_eq!( + sum.as_array(), + [11.0, 22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 88.0] + ); + + assert_eq!(simd_a.reduce_sum(), 36.0); + assert_eq!(simd_a.reduce_min(), 1.0); + } + + #[test] + fn test_f64x8_fma() { + // `multiply_add` lowers to `_mm256_fmadd_pd`, which needs FMA. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") || !std::is_x86_feature_detected!("fma") { + return; + } + let a: [f64; 8] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]; + let b: [f64; 8] = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]; + + let simd_a: f64x8 = (&a).into(); + let simd_b: f64x8 = (&b).into(); + let mut acc = f64x8::zeros(); + acc.multiply_add(simd_a, simd_b); + assert_eq!(acc.as_array(), a); + assert_eq!(acc.reduce_sum(), 36.0); + } + + #[test] + fn test_f64x8_min() { + // `min` / `reduce_min` are AVX intrinsics. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + return; + } + let a: [f64; 8] = [5.0, 1.0, 8.0, 3.0, 9.0, 2.0, 7.0, 4.0]; + let b: [f64; 8] = [2.0, 6.0, 3.0, 7.0, 1.0, 8.0, 4.0, 9.0]; + let simd_a: f64x8 = (&a).into(); + let simd_b: f64x8 = (&b).into(); + + let m = simd_a.min(&simd_b); + assert_eq!(m.as_array(), [2.0, 1.0, 3.0, 3.0, 1.0, 2.0, 4.0, 4.0]); + assert_eq!(m.reduce_min(), 1.0); + + // Test with negative values + let c: [f64; 8] = [-1.0, 5.0, 3.0, 7.0, 2.0, 4.0, 6.0, -3.0]; + let simd_c: f64x8 = (&c).into(); + assert_eq!(simd_c.reduce_min(), -3.0); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/i32.rs b/rust/lancedb/vendor/lance-linalg/src/simd/i32.rs new file mode 100644 index 000000000..4ba117a9b --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/i32.rs @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::fmt::Formatter; +use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; + +#[cfg(target_arch = "aarch64")] +use std::arch::aarch64::*; +#[cfg(target_arch = "loongarch64")] +use std::arch::loongarch64::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; +#[cfg(target_arch = "loongarch64")] +use std::mem::transmute; + +use super::SIMD; + +/// 8 of 32-bit `i32` values. Use 256-bit SIMD if possible. +/// +/// The x86_64 arm reaches AVX and AVX2 intrinsics with no `#[target_feature]` +/// gate of its own, so callers must already be inside an AVX2-checked context. +/// `x86_64-unknown-linux-gnu` is pinned to `target-cpu=x86-64-v2` +/// (`.cargo/config.toml`), which is below AVX. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct i32x8(pub(crate) __m256i); + +/// 8 of 32-bit `i32` values. Use 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct i32x8(int32x4x2_t); + +/// 8 of 32-bit `i32` values. Use 256-bit SIMD if possible. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "loongarch64")] +#[derive(Clone, Copy)] +pub struct i32x8(v8i32); + +#[allow(non_camel_case_types)] +#[cfg(simd_fallback)] +#[derive(Clone, Copy)] +pub struct i32x8([i32; 8]); + +impl std::fmt::Debug for i32x8 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0; 8]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "i32x8({:?})", arr) + } +} + +impl From<&[i32]> for i32x8 { + /// Loads the first 8 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 8 values. + fn from(value: &[i32]) -> Self { + assert!( + value.len() >= 8, + "i32x8 requires at least 8 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl From<&[i32; 8]> for i32x8 { + fn from(value: &[i32; 8]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for i32x8 { + #[inline] + fn splat(val: i32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_set1_epi32(val)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(int32x4x2_t(vdupq_n_s32(val), vdupq_n_s32(val))) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvreplgr2vr_w(val)) + } + #[cfg(simd_fallback)] + { + Self([val; 8]) + } + } + + #[inline] + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_setzero_si256()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0) + } + #[cfg(target_arch = "loongarch64")] + { + Self::splat(0) + } + #[cfg(simd_fallback)] + { + Self::splat(0) + } + } + + #[inline] + unsafe fn load(ptr: *const i32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_loadu_si256(ptr as *const __m256i)) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_s32_x2(ptr)) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self::load_unaligned(ptr) } + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const i32) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + // Treat the register as plain data so this load remains valid on + // pre-AVX hosts. LLVM still lowers this to an AVX move when AVX is + // enabled for the caller. + Self(ptr.cast::<__m256i>().read_unaligned()) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_s32_x2(ptr)) + } + #[cfg(target_arch = "loongarch64")] + { + Self(transmute(lasx_xvld::<0>(transmute(ptr)))) + } + #[cfg(simd_fallback)] + { + unsafe { Self(std::ptr::read_unaligned(ptr as *const [i32; 8])) } + } + } + + #[inline] + unsafe fn store(&self, ptr: *mut i32) { + self.store_unaligned(ptr) + } + + unsafe fn store_unaligned(&self, ptr: *mut i32) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm256_storeu_si256(ptr as *mut __m256i, self.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_s32_x2(ptr, self.0) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + lasx_xvst::<0>(transmute(self.0), transmute(ptr)) + } + #[cfg(simd_fallback)] + { + unsafe { std::ptr::write_unaligned(ptr as *mut [i32; 8], self.0) } + } + } + + fn reduce_sum(&self) -> i32 { + #[cfg(target_arch = "x86_64")] + { + self.as_array().iter().sum() + } + #[cfg(target_arch = "aarch64")] + unsafe { + let sum = vaddq_s32(self.0.0, self.0.1); + vaddvq_s32(sum) + } + #[cfg(target_arch = "loongarch64")] + { + self.as_array().iter().sum() + } + #[cfg(simd_fallback)] + { + self.0.iter().sum() + } + } + + fn reduce_min(&self) -> i32 { + todo!() + } + + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_min_epi32(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(int32x4x2_t( + vminq_s32(self.0.0, rhs.0.0), + vminq_s32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvmin_w(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].min(rhs.0[i]))) + } + } + + fn find(&self, val: i32) -> Option { + #[cfg(target_arch = "x86_64")] + unsafe { + for i in 0..8 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + #[cfg(target_arch = "aarch64")] + unsafe { + let tgt = vdupq_n_s32(val); + let mut arr = [0; 8]; + let mask1 = vceqq_s32(self.0.0, tgt); + let mask2 = vceqq_s32(self.0.1, tgt); + vst1q_u32(arr.as_mut_ptr(), mask1); + vst1q_u32(arr.as_mut_ptr().add(4), mask2); + for i in 0..8 { + if arr.get_unchecked(i) != &0 { + return Some(i as i32); + } + } + } + #[cfg(target_arch = "loongarch64")] + unsafe { + for i in 0..8 { + if self.as_array().get_unchecked(i) == &val { + return Some(i as i32); + } + } + } + #[cfg(simd_fallback)] + { + if let Some(i) = self.0.iter().position(|&v| v == val) { + return Some(i as i32); + } + } + None + } +} + +impl Add for i32x8 { + type Output = Self; + + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_add_epi32(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(int32x4x2_t( + vaddq_s32(self.0.0, rhs.0.0), + vaddq_s32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvadd_w(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].wrapping_add(rhs.0[i]))) + } + } +} + +impl AddAssign for i32x8 { + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_add_epi32(self.0, rhs.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vaddq_s32(self.0.0, rhs.0.0); + self.0.1 = vaddq_s32(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvadd_w(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] = self.0[i].wrapping_add(rhs.0[i]); + } + } + } +} + +impl Sub for i32x8 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_sub_epi32(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(int32x4x2_t( + vsubq_s32(self.0.0, rhs.0.0), + vsubq_s32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvsub_w(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].wrapping_sub(rhs.0[i]))) + } + } +} + +impl SubAssign for i32x8 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm256_sub_epi32(self.0, rhs.0); + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0.0 = vsubq_s32(self.0.0, rhs.0.0); + self.0.1 = vsubq_s32(self.0.1, rhs.0.1); + } + #[cfg(target_arch = "loongarch64")] + unsafe { + self.0 = lasx_xvsub_w(self.0, rhs.0); + } + #[cfg(simd_fallback)] + { + for i in 0..8 { + self.0[i] = self.0[i].wrapping_sub(rhs.0[i]); + } + } + } +} + +impl Mul for i32x8 { + type Output = Self; + + /// Lane-wise product, keeping the low 32 bits of each result. + /// + /// `mul` wraps on overflow rather than panicking the way scalar `i32 * i32` + /// does in a debug build, and every arm agrees on that: `vpmulld`, + /// `vmulq_s32`, `lasx_xvmul_w` and `wrapping_mul` each discard the high + /// half. This is a statement about `mul` alone — `reduce_sum` sums in scalar + /// `i32` outside aarch64 (so it panics on overflow in a debug build) but + /// reduces in-register on aarch64, where it wraps. + /// + /// Picking a widening variant here is a silent wrong answer, not a compile + /// error: `_mm256_mul_epi32` (`vpmuldq`) multiplies only the even 32-bit + /// lanes and writes four 64-bit results, so `[1, 2, ..., 8]` squared came + /// back as `[1, 0, 9, 0, 25, 0, 49, 0]`. + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm256_mullo_epi32(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(int32x4x2_t( + vmulq_s32(self.0.0, rhs.0.0), + vmulq_s32(self.0.1, rhs.0.1), + )) + } + #[cfg(target_arch = "loongarch64")] + unsafe { + Self(lasx_xvmul_w(self.0, rhs.0)) + } + #[cfg(simd_fallback)] + { + Self(std::array::from_fn(|i| self.0[i].wrapping_mul(rhs.0[i]))) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + #[test] + fn test_slice_conversion_rejects_short_input() { + assert!(std::panic::catch_unwind(|| i32x8::from(&[0; 7][..])).is_err()); + } + + #[test] + fn test_slice_conversion_uses_cpu_baseline() { + let values = [1_i32, 2, 3, 4, 5, 6, 7, 8]; + let from_slice = i32x8::from(&values[..]); + let from_array = i32x8::from(&values); + + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx") { + std::hint::black_box((from_slice, from_array)); + return; + } + + assert_eq!(from_slice.as_array(), values); + assert_eq!(from_array.as_array(), values); + } + + /// Lane-wise, low-32-bits multiplication is what every arm promises, so + /// this runs everywhere: only the x86 feature check is arch-gated, matching + /// `f32.rs`'s and `f64.rs`'s test modules. + /// + /// Every case below has to produce a different answer under the widening + /// `vpmuldq` this file used to call. All-zero *inputs* would not: `vpmuldq` + /// returns zeros for those too. + #[rstest] + #[case::squares([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 4, 9, 16, 25, 36, 49, 64])] + #[case::mixed_signs([-3, 7, -3, 7, -3, 7, -3, 7], [7, -3, 7, -3, 7, -3, 7, -3], [-21; 8])] + #[case::wraps_to_low_32_bits([65536; 8], [65536; 8], [0; 8])] + fn mul_is_lane_wise(#[case] lhs: [i32; 8], #[case] rhs: [i32; 8], #[case] expected: [i32; 8]) { + // `load_unaligned` / `store_unaligned` are AVX and `mul` is AVX2, and + // none of them is `#[target_feature]`-gated, so a pre-Haswell host would + // SIGILL. The `qemu-pre-haswell` CI job runs exactly that. + #[cfg(target_arch = "x86_64")] + if !std::is_x86_feature_detected!("avx2") { + return; + } + + let product = i32x8::from(&lhs) * i32x8::from(&rhs); + + assert_eq!(product.as_array(), expected); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/u8.rs b/rust/lancedb/vendor/lance-linalg/src/simd/u8.rs new file mode 100644 index 000000000..5a35ed5f3 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/u8.rs @@ -0,0 +1,464 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! `u8x8`, 8 of `u8` values + +use std::fmt::Formatter; + +#[cfg(target_arch = "aarch64")] +use std::arch::aarch64::*; +#[cfg(target_arch = "x86_64")] +use std::arch::x86_64::*; +use std::ops::{Add, AddAssign, Mul, Sub, SubAssign}; + +use super::{SIMD, Shuffle}; + +/// 16 of 8-bit `u8` values. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +pub struct u8x16(pub __m128i); + +/// 16 of 8-bit `u8` values. +#[allow(non_camel_case_types)] +#[cfg(target_arch = "aarch64")] +#[derive(Clone, Copy)] +pub struct u8x16(pub uint8x16_t); + +#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] +#[derive(Clone, Copy)] +pub struct u8x16(pub [u8; 16]); + +impl u8x16 { + #[inline] + pub fn bit_and(self, mask: u8) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_and_si128(self.0, _mm_set1_epi8(mask as i8))) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vandq_u8(self.0, vdupq_n_u8(mask))) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = self.0; + for i in 0..16 { + result[i] &= mask; + } + Self(result) + } + } + + #[inline] + pub fn right_shift(self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + let shifted = _mm_srli_epi16(self.0, N); + let mask = _mm_set1_epi8((1_i8 << (8 - N)) - 1); + Self(_mm_and_si128(shifted, mask)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vshrq_n_u8::(self.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = self.0[i] >> N; + } + Self(result) + } + } +} + +impl std::fmt::Debug for u8x16 { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut arr = [0u8; 16]; + unsafe { + self.store_unaligned(arr.as_mut_ptr()); + } + write!(f, "u8x16({:?})", arr) + } +} + +impl From<&[u8]> for u8x16 { + /// Loads the first 16 values from `value`. + /// + /// # Panics + /// + /// Panics if `value` contains fewer than 16 values. + fn from(value: &[u8]) -> Self { + assert!( + value.len() >= 16, + "u8x16 requires at least 16 values, got {}", + value.len() + ); + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl<'a> From<&'a [u8; 16]> for u8x16 { + fn from(value: &'a [u8; 16]) -> Self { + unsafe { Self::load_unaligned(value.as_ptr()) } + } +} + +impl SIMD for u8x16 { + #[inline] + fn splat(val: u8) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_set1_epi8(val as i8)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vdupq_n_u8(val)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = val; + } + Self(result) + } + } + + #[inline] + fn zeros() -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_setzero_si128()) + } + #[cfg(target_arch = "aarch64")] + { + Self::splat(0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + Self([0; 16]) + } + } + + #[inline] + unsafe fn load(ptr: *const u8) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_loadu_si128(ptr as *const __m128i)) + } + #[cfg(target_arch = "aarch64")] + { + Self::load_unaligned(ptr) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + Self::load_unaligned(ptr) + } + } + + #[inline] + unsafe fn load_unaligned(ptr: *const u8) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_loadu_si128(ptr as *const __m128i)) + } + #[cfg(target_arch = "aarch64")] + { + Self(vld1q_u8(ptr)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = *ptr.add(i); + } + Self(result) + } + } + + #[inline] + unsafe fn store(&self, ptr: *mut u8) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm_storeu_si128(ptr as *mut __m128i, self.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_u8(ptr, self.0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + self.store_unaligned(ptr); + } + } + + #[inline] + unsafe fn store_unaligned(&self, ptr: *mut u8) { + #[cfg(target_arch = "x86_64")] + unsafe { + _mm_storeu_si128(ptr as *mut __m128i, self.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + vst1q_u8(ptr, self.0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + for i in 0..16 { + *ptr.add(i) = self.0[i]; + } + } + } + + fn reduce_sum(&self) -> u8 { + todo!("it is not implemented yet"); + } + + #[inline] + fn reduce_min(&self) -> u8 { + #[cfg(target_arch = "x86_64")] + unsafe { + let low = _mm_and_si128(self.0, _mm_set1_epi8(0xFF_u8 as i8)); + let high = _mm_srli_si128(self.0, 8); + let min_low = _mm_min_epu8(low, high); + let min_low = _mm_min_epu8(min_low, _mm_srli_si128(min_low, 4)); + let min_low = _mm_min_epu8(min_low, _mm_srli_si128(min_low, 2)); + let min_low = _mm_min_epu8(min_low, _mm_srli_si128(min_low, 1)); + _mm_extract_epi8(min_low, 0) as u8 + } + #[cfg(target_arch = "aarch64")] + unsafe { + vminvq_u8(self.0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut min = self.0[0]; + for i in 1..16 { + min = std::cmp::min(min, self.0[i]); + } + min + } + } + + #[inline] + fn min(&self, rhs: &Self) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_min_epu8(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vminq_u8(self.0, rhs.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = std::cmp::min(self.0[i], rhs.0[i]); + } + Self(result) + } + } + + fn find(&self, _val: u8) -> Option { + todo!() + } +} + +impl Shuffle for u8x16 { + fn shuffle(&self, indices: u8x16) -> Self { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_shuffle_epi8(self.0, indices.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vqtbl1q_u8(self.0, indices.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = self.0[indices.0[i] as usize]; + } + Self(result) + } + } +} + +impl Add for u8x16 { + type Output = Self; + + /// Lane-wise sum, saturating at [`u8::MAX`] on overflow. + #[inline] + fn add(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_adds_epu8(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vqaddq_u8(self.0, rhs.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = self.0[i].saturating_add(rhs.0[i]); + } + Self(result) + } + } +} + +impl AddAssign for u8x16 { + /// Add `rhs` lane-wise, saturating each sum at [`u8::MAX`]. + #[inline] + fn add_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm_adds_epu8(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0 = vqaddq_u8(self.0, rhs.0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + for i in 0..16 { + self.0[i] = self.0[i].saturating_add(rhs.0[i]); + } + } + } +} + +impl Mul for u8x16 { + type Output = Self; + + /// Lane-wise product, keeping the low 8 bits of each result. + /// + /// Multiplication wraps on overflow on every supported architecture. + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + let a_lo = _mm_unpacklo_epi8(self.0, _mm_setzero_si128()); + let a_hi = _mm_unpackhi_epi8(self.0, _mm_setzero_si128()); + let b_lo = _mm_unpacklo_epi8(rhs.0, _mm_setzero_si128()); + let b_hi = _mm_unpackhi_epi8(rhs.0, _mm_setzero_si128()); + + // Every `u8` product is exact in 16 bits. The pack saturates into + // `0..=255`, so mask to the low byte first to make narrowing exact. + let low_byte_mask = _mm_set1_epi16(u8::MAX as i16); + let res_lo = _mm_and_si128(_mm_mullo_epi16(a_lo, b_lo), low_byte_mask); + let res_hi = _mm_and_si128(_mm_mullo_epi16(a_hi, b_hi), low_byte_mask); + + Self(_mm_packus_epi16(res_lo, res_hi)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vmulq_u8(self.0, rhs.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = self.0[i].wrapping_mul(rhs.0[i]); + } + Self(result) + } + } +} + +impl Sub for u8x16 { + type Output = Self; + + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + #[cfg(target_arch = "x86_64")] + unsafe { + Self(_mm_sub_epi8(self.0, rhs.0)) + } + #[cfg(target_arch = "aarch64")] + unsafe { + Self(vsubq_u8(self.0, rhs.0)) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + let mut result = [0u8; 16]; + for i in 0..16 { + result[i] = self.0[i].wrapping_sub(rhs.0[i]); + } + Self(result) + } + } +} + +impl SubAssign for u8x16 { + #[inline] + fn sub_assign(&mut self, rhs: Self) { + #[cfg(target_arch = "x86_64")] + unsafe { + self.0 = _mm_sub_epi8(self.0, rhs.0) + } + #[cfg(target_arch = "aarch64")] + unsafe { + self.0 = vsubq_u8(self.0, rhs.0) + } + #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] + { + for i in 0..16 { + self.0[i] = self.0[i].wrapping_sub(rhs.0[i]); + } + } + } +} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn test_slice_conversion_rejects_short_input() { + assert!(std::panic::catch_unwind(|| u8x16::from(&[0; 15][..])).is_err()); + } + + #[test] + fn test_basic_u8x16_ops() { + let a = (0..16).map(|f| f as u8).collect::>(); + let b = (16..32).map(|f| f as u8).collect::>(); + + let simd_a = unsafe { u8x16::load_unaligned(a.as_ptr()) }; + let simd_b = unsafe { u8x16::load_unaligned(b.as_ptr()) }; + + let simd_add = simd_a + simd_b; + (0..16) + .zip(simd_add.as_array().iter()) + .for_each(|(x, &y)| assert_eq!((x + x + 16) as u8, y)); + + let simd_mul = simd_a * simd_b; + let expected_mul: [u8; 16] = std::array::from_fn(|i| a[i].wrapping_mul(b[i])); + assert_eq!(simd_mul.as_array(), expected_mul); + + // 16 * 16 is the smallest overflowing square and must wrap to zero + // rather than saturating to 255 during the pack. + let boundary_product = u8x16::splat(16) * u8x16::splat(16); + assert_eq!(boundary_product.as_array(), [0; 16]); + } + + #[test] + fn test_saturating_add() { + let a = u8x16::splat(200); + let b = u8x16::splat(100); + let mut result = a + b; + + let expected = (0..16).map(|_| 255).collect::>(); + assert_eq!(result.as_array(), expected.as_slice()); + + result += b; + assert_eq!(result.as_array(), expected.as_slice()); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/simd/x86.rs b/rust/lancedb/vendor/lance-linalg/src/simd/x86.rs new file mode 100644 index 000000000..437018669 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/simd/x86.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Reduction helpers shared by the x86_64 AVX kernels in [`crate::distance`]. +//! +//! Each distance kernel accumulates into a 256-bit register and folds it down +//! to a scalar once, after the main loop. The fold is identical across +//! `cosine`, `dot`, `l2` and `norm_l2`, so it lives here instead of being +//! copied into each kernel's private `mod x86`. +//! +//! The module itself is `pub(crate)`, which is what keeps these helpers off the +//! public API; the items are `pub` rather than `pub(crate)` only because +//! `clippy::redundant_pub_crate` fires on the narrower visibility. + +use std::arch::x86_64::*; + +/// Horizontal sum of the eight `f32` lanes of an `__m256`. +/// +/// Folds the upper 128-bit lane into the lower one, then reduces the +/// remaining four lanes pairwise. Uses `movehl`/`shuffle` plus scalar adds +/// rather than two `vhaddps`, which is one fewer uop on most cores. +/// +/// # Safety +/// +/// The host must support AVX. Callers are `#[target_feature]`-annotated +/// kernels that the runtime dispatcher only selects after checking. +#[inline] +#[target_feature(enable = "avx")] +pub unsafe fn hsum256_ps(v: __m256) -> f32 { + let lo = _mm256_castps256_ps128(v); + let hi = _mm256_extractf128_ps(v, 1); + let sum128 = _mm_add_ps(lo, hi); + let sum64 = _mm_add_ps(sum128, _mm_movehl_ps(sum128, sum128)); + // 0x55 broadcasts lane 1 into lane 0, so the scalar add below lands the + // last of the four partial sums. + let sum32 = _mm_add_ss(sum64, _mm_shuffle_ps(sum64, sum64, 0x55)); + _mm_cvtss_f32(sum32) +} + +/// Horizontal sum of the four `f64` lanes of an `__m256d`. +/// +/// Folds the upper 128-bit lane into the lower one, then adds the remaining +/// pair. +/// +/// # Safety +/// +/// The host must support AVX. Callers are `#[target_feature]`-annotated +/// kernels that the runtime dispatcher only selects after checking. +#[inline] +#[target_feature(enable = "avx")] +pub unsafe fn hsum256_pd(v: __m256d) -> f64 { + let lo = _mm256_castpd256_pd128(v); + let hi = _mm256_extractf128_pd(v, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + _mm_cvtsd_f64(sum64) +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + #[rstest] + #[case::ascending([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], 36.0)] + #[case::negative_lanes([-1.5, 2.0, -3.0, 4.5, 0.0, -0.5, 1.0, 2.5], 5.0)] + #[case::zeros([0.0; 8], 0.0)] + #[case::cancelling([1.0, -1.0, 2.0, -2.0, 3.0, -3.0, 4.0, -4.0], 0.0)] + fn hsum256_ps_sums_every_lane(#[case] lanes: [f32; 8], #[case] expected: f32) { + if !std::is_x86_feature_detected!("avx") { + return; + } + let sum = unsafe { hsum256_ps(_mm256_loadu_ps(lanes.as_ptr())) }; + assert_eq!(sum, expected); + } + + #[rstest] + #[case::ascending([1.0, 2.0, 3.0, 4.0], 10.0)] + #[case::negative_lanes([-1.5, 2.0, -3.0, 4.5], 2.0)] + #[case::zeros([0.0; 4], 0.0)] + #[case::cancelling([1.0, -1.0, 2.0, -2.0], 0.0)] + fn hsum256_pd_sums_every_lane(#[case] lanes: [f64; 4], #[case] expected: f64) { + if !std::is_x86_feature_detected!("avx") { + return; + } + let sum = unsafe { hsum256_pd(_mm256_loadu_pd(lanes.as_ptr())) }; + assert_eq!(sum, expected); + } +} diff --git a/rust/lancedb/vendor/lance-linalg/src/test_utils.rs b/rust/lancedb/vendor/lance-linalg/src/test_utils.rs new file mode 100644 index 000000000..af716a1b1 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/src/test_utils.rs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use half::{bf16, f16}; +use proptest::prelude::*; +use proptest::test_runner::{Config, TestCaseResult, TestRunner}; +use std::ops::Range; + +const CASES_PER_DIMENSION_SHARD: u32 = 16; +const MIN_TEST_DIMENSION: usize = 4; +const MAX_TEST_DIMENSION: usize = 4048; +const NUM_DIMENSION_SHARDS: usize = 16; + +pub fn dimension_shard(shard: usize) -> Range { + let dimensions_per_shard = (MAX_TEST_DIMENSION - MIN_TEST_DIMENSION) / NUM_DIMENSION_SHARDS; + let start = MIN_TEST_DIMENSION + shard * dimensions_per_shard; + let end = if shard + 1 == NUM_DIMENSION_SHARDS { + MAX_TEST_DIMENSION + } else { + start + dimensions_per_shard + }; + start..end +} + +/// Arbitrary finite f16 value. +pub fn arbitrary_f16() -> impl Strategy { + any::().prop_map(|bits| { + // Convert arbitrary u16 to f16 + let val = f16::from_bits(bits); + // Convert Inf -> Max, -Inf -> Min, NaN -> 0 + if val.is_infinite() && val.is_sign_positive() { + f16::MAX + } else if val.is_infinite() && val.is_sign_negative() { + f16::MIN + } else if val.is_nan() { + f16::from_f32(0.0) + } else { + val + } + }) +} + +pub fn arbitrary_bf16() -> impl Strategy { + any::() + .prop_map(|bits| { + // Convert arbitrary u16 to bf16 + let val = bf16::from_bits(bits); + // Convert Inf -> Max, -Inf -> Min, NaN -> 0 + if val.is_infinite() && val.is_sign_positive() { + bf16::MAX + } else if val.is_infinite() && val.is_sign_negative() { + bf16::MIN + } else if val.is_nan() { + bf16::from_f32(0.0) + } else { + val + } + }) + .prop_map(|val: bf16| { + let scaling = bf16::from_f32(1e12 / f32::MAX); + val * scaling + }) +} + +/// Arbitrary finite f32 value, in the range of +-1e12. +/// +/// We limit the range to avoid overflow. The f32 Max is around 3.4e38, so this +/// gives enough room for multiplying and adding without overflow. +pub fn arbitrary_f32() -> impl Strategy { + use proptest::num::f32::*; + let scaling = 1e12 / f32::MAX; + (NORMAL | SUBNORMAL | POSITIVE | NEGATIVE).prop_map(move |val: f32| val * scaling) +} + +/// Arbitrary finite f64 value, in the range of +-1e12. +/// +/// We limit the range to avoid overflow. Right now, it's mainly limited to +/// keep L2 norm finite. If we changed L2 Norm to be able to return a f64, we +/// can broaden these test values. +pub fn arbitrary_f64() -> impl Strategy { + use proptest::num::f64::*; + let scaling = 1e12 / f64::MAX; + (NORMAL | SUBNORMAL | POSITIVE | NEGATIVE).prop_map(move |val: f64| val * scaling) +} + +/// Two arbitrary vectors with matching dimensions +pub fn arbitrary_vector_pair( + values: impl Fn() -> S + 'static, + dim_range: std::ops::Range, +) -> impl Strategy, Vec)> +where + S: Strategy, +{ + dim_range.prop_flat_map(move |dim| { + let x = prop::collection::vec(values(), dim); + let y = prop::collection::vec(values(), dim); + (x, y) + }) +} + +pub fn run_vector_pair_proptest(values: fn() -> S, dim_range: Range, property: F) +where + T: std::fmt::Debug, + S: Strategy + 'static, + F: Fn(Vec, Vec) -> TestCaseResult, +{ + let strategy = arbitrary_vector_pair(values, dim_range); + let mut runner = TestRunner::new(Config { + cases: CASES_PER_DIMENSION_SHARD, + ..Config::default() + }); + runner.run(&strategy, |(x, y)| property(x, y)).unwrap(); +} + +pub fn run_vector_proptest(values: fn() -> S, dim_range: Range, property: F) +where + T: std::fmt::Debug, + S: Strategy, + F: Fn(Vec) -> TestCaseResult, +{ + let strategy = prop::collection::vec(values(), dim_range); + let mut runner = TestRunner::new(Config { + cases: CASES_PER_DIMENSION_SHARD, + ..Config::default() + }); + runner.run(&strategy, property).unwrap(); +} + +/// Input pairs shared by the u8 distance kernel tests. +pub mod u8_inputs { + /// Covers empty input and both sides of the 32- and 64-element SIMD strides. + pub const LENGTHS: &[usize] = &[ + 0, 1, 7, 15, 16, 31, 32, 33, 63, 64, 65, 127, 128, 255, 256, 1024, 4096, 4097, + ]; + + #[derive(Clone, Copy, Debug)] + pub enum Pattern { + Random, + Extremes, + OneSidedZeros, + } + + impl Pattern { + /// Labeled input pairs of length `len`. + pub fn pairs(self, len: usize) -> Vec<(&'static str, Vec, Vec)> { + let filled = |value| vec![value; len]; + match self { + Self::Random => (0..4) + .map(|seed| ("random", random(len, 2 * seed), random(len, 2 * seed + 1))) + .collect(), + Self::Extremes => { + let alternating = |first| { + (0..len) + .map(|i| if i % 2 == 0 { first } else { u8::MAX - first }) + .collect::>() + }; + vec![ + ("max-0", filled(u8::MAX), filled(0)), + ("0-max", filled(0), filled(u8::MAX)), + ("max-max", filled(u8::MAX), filled(u8::MAX)), + ("0-0", filled(0), filled(0)), + ("1-1", filled(1), filled(1)), + ("alternating", alternating(0), alternating(u8::MAX)), + ] + } + Self::OneSidedZeros => vec![ + ("b=0", random(len, 0), filled(0)), + ("a=0", filled(0), random(len, 1)), + ], + } + } + } + + pub fn random(len: usize, seed: u32) -> Vec { + let mut state = 0xC0FFEE_u32.wrapping_add(seed.wrapping_mul(7919)); + (0..len) + .map(|_| { + state = state.wrapping_mul(1103515245).wrapping_add(12345); + (state >> 16) as u8 + }) + .collect() + } +} diff --git a/rust/lancedb/vendor/lance-linalg/tests/panic_location.rs b/rust/lancedb/vendor/lance-linalg/tests/panic_location.rs new file mode 100644 index 000000000..4d298031c --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/tests/panic_location.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! Where a length-contract panic reports itself. +//! +//! This lives in its own integration binary because it replaces the global +//! panic hook. Any other test that panics while the hook is installed lands in +//! this one's sink instead, and the lib test binary runs its tests on threads of +//! one process. + +use std::ffi::OsStr; +use std::path::Path; + +use lance_linalg::distance::{dot_u8::dot_u8, l2::l2_distance_batch_into}; + +/// Runs `f`, which must panic, and returns where the panic was reported and +/// what it said. +fn panic_details(f: impl FnOnce() + std::panic::UnwindSafe) -> (String, u32, String) { + let captured = std::sync::Arc::new(std::sync::Mutex::new(None)); + let sink = std::sync::Arc::clone(&captured); + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + // Both panics here come from `assert_eq!`, which always formats, so the + // payload is a `String`. A payload of any other type leaves this empty + // and the message assertions below fail rather than pass silently. + let message = info + .payload() + .downcast_ref::() + .cloned() + .unwrap_or_default(); + *sink.lock().unwrap() = info + .location() + .map(|loc| (loc.file().to_owned(), loc.line(), message)); + })); + let outcome = std::panic::catch_unwind(f); + std::panic::set_hook(previous); + assert!(outcome.is_err(), "expected a panic"); + captured.lock().unwrap().take().expect("no panic location") +} + +/// Without `#[track_caller]` on the two helpers in `distance.rs`, both of these +/// panics report `distance.rs` and the reader cannot tell which metric fired. +/// The message is asserted too, so an unrelated panic in the same file does not +/// satisfy the test. +#[test] +fn length_contract_panics_name_the_distance_function() { + let (file, line, message) = panic_details(|| { + dot_u8(&[1, 2], &[1]); + }); + assert_eq!( + Path::new(&file).file_name(), + Some(OsStr::new("dot_u8.rs")), + "expected dot_u8.rs, got {file}:{line}" + ); + assert!( + message.contains("equal lengths"), + "{file}:{line}: {message}" + ); + + let (file, line, message) = panic_details(|| { + l2_distance_batch_into(&[1.0f32, 2.0], &[1.0f32, 2.0, 3.0], 2, &mut [0.0]); + }); + assert_eq!( + Path::new(&file).file_name(), + Some(OsStr::new("l2.rs")), + "expected l2.rs, got {file}:{line}" + ); + assert!( + message.contains("divisible by dimension"), + "{file}:{line}: {message}" + ); +}