fix: stabilize exact cosine distances for extreme float32 vectors

This commit is contained in:
Gatefixer
2026-11-08 14:57:40 +00:00
parent bff93ff314
commit df4eaa543d
45 changed files with 22375 additions and 6 deletions
Generated
+153 -6
View File
@@ -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"
+5
View File
@@ -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"
+2
View File
@@ -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
+62
View File
@@ -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]
+71
View File
@@ -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)"] }
+255
View File
@@ -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
+14
View File
@@ -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.
+4
View File
@@ -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).
+65
View File
@@ -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<UInt32Array> {
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::<Float32Type>(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);
@@ -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::<Vec<_>>();
let batch = (0..TOTAL_VALUES)
.map(|index| (index % 31) as f32 * 0.03125 - 0.5)
.collect::<Vec<_>>();
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(|| {
<f32 as Dot>::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(|| {
<f32 as L2>::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(|| {
<f32 as Cosine>::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);
+153
View File
@@ -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<T: Float>(x: &[T], y: &[T], dim: usize) -> Vec<T> {
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<T: ArrowFloatType>(c: &mut Criterion)
where
T::Native: Cosine,
{
const DIMENSION: usize = 1024;
const TOTAL: usize = 512 * 1024;
let type_name = std::any::type_name::<T::Native>();
let key = generate_random_array_with_seed::<T>(DIMENSION, [0; 32]);
let target = generate_random_array_with_seed::<T>(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::<BFloat16Type>(c);
run_bench::<Float16Type>(c);
run_bench::<Float32Type>(c);
run_bench::<Float64Type>(c);
let key: Float32Array = generate_random_array_with_seed::<Float32Type>(8, [0; 32]);
let target = generate_random_array_with_seed::<Float32Type>(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<u8> = 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<u8> = 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::<DIMENSION>()
.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::<DIMENSION>()
.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);
+66
View File
@@ -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<u8> = repeat_with(|| rng.random::<u8>())
.take(n * code_len)
.collect();
let dist_table: Vec<u8> = repeat_with(|| rng.random::<u8>())
.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);
+190
View File
@@ -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<T: Float + Sum>(x: &[T], y: &[T]) -> T {
x.iter().zip(y.iter()).map(|(&xi, &yi)| xi * yi).sum::<T>()
}
fn run_bench<T: ArrowFloatType>(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::<T>(DIMENSION, [0; 32]);
// 1M of 1024 D vectors
let target = generate_random_array_with_seed::<T>(TOTAL * DIMENSION, [42; 32]);
let type_name = std::any::type_name::<T::Native>();
c.bench_function(format!("Dot({type_name}, arrow_artiy)").as_str(), |b| {
b.iter(|| {
<T::ArrayType as FloatArray<T>>::from_values(
target
.as_slice()
.chunks(DIMENSION)
.map(|arr| dot_scalar(key.as_slice(), arr))
.collect::<Vec<_>>(),
)
});
});
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::<Vec<_>>(),
)
});
},
);
// TODO: SIMD needs generic specialization
}
fn bench_distance(c: &mut Criterion) {
const DIMENSION: usize = 1024;
const TOTAL: usize = 1024 * 1024; // 1M vectors
run_bench::<Float16Type>(c);
c.bench_function("Dot(f16, SIMD)", |b| {
let key = generate_random_array_with_seed::<Float16Type>(DIMENSION, [0; 32]);
// 1M of 1024 D vectors
let target = generate_random_array_with_seed::<Float16Type>(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::<u16>())
.map(bf16::from_bits)
.take(DIMENSION)
.collect::<Vec<_>>();
let target = repeat_with(|| rng.random::<u16>())
.map(bf16::from_bits)
.take(TOTAL * DIMENSION)
.collect::<Vec<_>>();
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::<Vec<_>>(),
)
});
});
// 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<u8> = (0..dim + 63).map(|_| rng.random()).collect();
let key_u8 = &key_buf[key_buf.as_ptr().align_offset(64)..][..dim];
let target_buf: Vec<u8> = (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::<Vec<_>>(),
)
});
});
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::<Vec<_>>(),
)
});
});
}
}
run_bench::<Float32Type>(c);
c.bench_function("Dot(f32, SIMD)", |b| {
let key = generate_random_array_with_seed::<Float32Type>(DIMENSION, [0; 32]);
// 1M of 1024 D vectors
let target = generate_random_array_with_seed::<Float32Type>(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::<Float64Type>(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);
+194
View File
@@ -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<T: Float + AsPrimitive<f32>>(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<T: ArrowFloatType>(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::<T>(DIMENSION, [0; 32]);
// 1M of 1024 D vectors
let target = generate_random_array_with_seed::<T>(TOTAL * DIMENSION, [42; 32]);
let type_name = std::any::type_name::<T::Native>();
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::<Float16Type>(c);
run_bench::<Float32Type>(c);
let key: Float32Array = generate_random_array_with_seed::<Float32Type>(DIMENSION, [0; 32]);
let target: Float32Array =
generate_random_array_with_seed::<Float32Type>(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::<Float64Type>(c);
}
fn bench_small_distance(c: &mut Criterion) {
let key = generate_random_array_with_seed::<Float32Type>(8, [5; 32]);
// 1M of 1024 D vectors. 4GB in memory.
let target = generate_random_array_with_seed::<Float32Type>(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::<LANE>();
let (y_chunks, y_reminder) = target.as_chunks::<LANE>();
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::<u32>();
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::<u8>())
.take(DIMENSION + 63)
.collect::<Vec<_>>();
let key = &key_buf[key_buf.as_ptr().align_offset(64)..][..DIMENSION];
let target_buf = repeat_with(|| rng.random::<u8>())
.take(TOTAL * DIMENSION + 63)
.collect::<Vec<_>>();
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::<DIMENSION>()
.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::<DIMENSION>()
.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::<DIMENSION>()
.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);
+133
View File
@@ -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<T: ArrowFloatType>(
c: &mut Criterion,
target: &[T::Native],
auto_vec_impl: fn(&[T::Native]) -> f32,
simd_impl: Option<fn(&[T::Native]) -> f32>,
) where
T::Native: Float,
{
let type_name = std::any::type_name::<T::Native>();
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::<T::Native>().sqrt())
.collect::<Vec<_>>()
});
});
c.bench_function(
format!("NormL2({type_name}, auto-vectorization)").as_str(),
|b| {
b.iter(|| {
black_box(
target
.as_chunks::<DIMENSION>()
.0
.iter()
.map(|v| auto_vec_impl(v))
.collect::<Vec<_>>(),
);
});
},
);
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::<DIMENSION>()
.0
.iter()
.map(|v| simd_impl(v))
.collect::<Vec<_>>(),
);
});
},
);
}
}
fn bench_distance(c: &mut Criterion) {
let mut rng = rand::rng();
let target = repeat_with(|| rng.random::<u16>())
.map(bf16::from_bits)
.take(TOTAL * DIMENSION)
.collect::<Vec<_>>();
// We currently don't have a SIMD implementation for bf16.
run_bench::<BFloat16Type>(c, &target, norm_l2, None);
let target: Float16Array =
generate_random_array_with_seed::<Float16Type>(TOTAL * DIMENSION, [42; 32]);
run_bench::<Float16Type>(
c,
target.as_slice(),
norm_l2_impl::<f16, f32, 32>,
Some(norm_l2),
);
let target: Float32Array =
generate_random_array_with_seed::<Float32Type>(TOTAL * DIMENSION, [42; 32]);
run_bench::<Float32Type>(
c,
target.as_slice(),
norm_l2_impl::<f32, f32, 16>,
Some(norm_l2),
);
let target: Float64Array =
generate_random_array_with_seed::<Float64Type>(TOTAL * DIMENSION, [42; 32]);
run_bench::<Float64Type>(
c,
target.as_slice(),
norm_l2_impl::<f64, f32, 8>,
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);
+327
View File
@@ -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<String> {
let mut candidates: Vec<String> = 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 <immintrin.h>\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)
}
@@ -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])
+41
View File
@@ -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<T: Num> {
/// 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<UInt32Array>;
/// 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<usize>) -> Vec<Option<u32>>;
}
File diff suppressed because it is too large Load Diff
+260
View File
@@ -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<T>(self, query: &[T], values: &[T], dim: usize) -> Result<Vec<f32>>
where
T: L2 + Dot + Cosine + Normalize + AsPrimitive<f32> + AsPrimitive<f64>,
{
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::<T>() > std::mem::size_of::<f32>() {
v.iter()
.map(|&v| {
let v: f64 = v.as_();
v * v
})
.sum::<f64>() 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<Vec<f32>> {
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<Vec<f32>> {
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::<Float16Type>(operation, query, vectors, dim),
DataType::Float32 if int8_query => numeric_int8_query(operation, query, vectors, dim),
DataType::Float32 => numeric::<Float32Type>(operation, query, vectors, dim),
DataType::Float64 => numeric::<Float64Type>(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::<UInt8Type>().values().as_ref()),
vectors.values().as_primitive::<UInt8Type>().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<Vec<f32>> {
let query = query.ok_or_else(|| operation.error("Int8 values require a query"))?;
let query = query.as_primitive::<Int8Type>();
let query = Float32Array::from(query.values().iter().map(|&v| v as f32).collect::<Vec<_>>());
let vectors = vectors.convert_to_floating_point()?;
numeric::<Float32Type>(operation, Some(&query), &vectors, dim)
}
fn numeric<T>(
operation: Operation<'_>,
query: Option<&dyn Array>,
vectors: &FixedSizeListArray,
dim: usize,
) -> Result<Vec<f32>>
where
T: ArrowPrimitiveType,
T::Native: L2 + Dot + Cosine + Normalize + AsPrimitive<f32> + AsPrimitive<f64>,
{
operation.numeric(
query.map_or(&[], |q| q.as_primitive::<T>().values().as_ref()),
vectors.values().as_primitive::<T>().values(),
dim,
)
}
fn multivec<T>(
query: &[T],
values: &[T],
dim: usize,
rows: &ListArray,
distance: DistanceFunc<T>,
) -> Vec<f32> {
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()
}
File diff suppressed because it is too large Load Diff
@@ -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<CosineU8AccumKernel> = {
#[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"
);
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+292
View File
@@ -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<DotU8Kernel> = {
#[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::<u8>(&a, &b), exact as f32);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+311
View File
@@ -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<L2U8Kernel> = {
#[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::<u8>(&a, &b), exact as f32);
}
}
+787
View File
@@ -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::<Self, f32, 16>(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::<Self, f32, 32>(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::<Self, f32, 32>(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::<f32, f32, 16>(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::<f64>().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>,
Output: Float + Sum + 'static + AddAssign,
const LANES: usize,
>(
vector: &[T],
) -> Output {
let (chunks, remainder) = vector.as_chunks::<LANES>();
let sum = if remainder.is_empty() {
Output::zero()
} else {
remainder.iter().map(|&v| v.as_().powi(2)).sum::<Output>()
};
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::<Output>()).sqrt()
}
/// Normalize a vector.
///
/// The parameters must be cache line aligned. For example, from
/// Arrow Arrays, i.e., Float32Array
#[inline]
pub fn norm_l2<T: Normalize>(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<Float32Array> {
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::<Float32Type, _, _>(
/// [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<Vec<f32>> {
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<f32> {
// 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::<f64>().sqrt() as f32
}
fn do_norm_l2_test<T: Normalize + ToPrimitive>(
data: &[T],
) -> std::result::Result<(), TestCaseError> {
let f64_data = data
.iter()
.map(|v| v.to_f64().unwrap())
.collect::<Vec<f64>>();
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::<f64>().sqrt() as f32;
let simd = <f32 as Normalize>::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<f16> = [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::<f64>()
})
.collect::<Vec<_>>();
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}"
);
}
}
}
+919
View File
@@ -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<T: Num + Bounded + PartialOrd>(iter: impl Iterator<Item = T>) -> Option<u32> {
let mut max_idx: Option<u32> = 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<T: Num + Bounded + PartialOrd>(
iter: impl Iterator<Item = Option<T>>,
) -> Option<u32> {
let mut max_idx: Option<u32> = 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<T: Num + PartialOrd + Copy + Bounded>(iter: impl Iterator<Item = T>) -> Option<u32> {
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<T: Num + Bounded + PartialOrd + Copy>(
iter: impl Iterator<Item = T>,
) -> 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<T: Float>(iter: impl Iterator<Item = T>) -> 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<T: Float>(
iter: impl Iterator<Item = T>,
bias: Option<impl Iterator<Item = T>>,
) -> 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<T: Num + Bounded + PartialOrd>(
iter: impl Iterator<Item = Option<T>>,
) -> Option<(u32, T)> {
let mut min_idx: Option<u32> = 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<Float>` iterator.
///
#[inline]
pub fn argmin_opt<T: Num + Bounded + PartialOrd>(
iter: impl Iterator<Item = Option<T>>,
) -> Option<u32> {
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<Self::Acc> {
/// Must be at least as wide as `Self` in both exponent and mantissa.
type Acc: Float + Sum + AsPrimitive<Self> + AsPrimitive<f32>;
}
/// `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<T: Normalizable>(v: &[T]) -> (impl Iterator<Item = T> + '_, f32) {
let l2_norm = v
.iter()
.map(|x| {
let x: T::Acc = x.as_();
x * x
})
.sum::<T::Acc>()
.sqrt();
(
v.iter().map(move |&x| (x.as_() / l2_norm).as_()),
l2_norm.as_(),
)
}
fn do_normalize_arrow<T: ArrowPrimitiveType>(arr: &dyn Array) -> Result<(ArrayRef, f32)>
where
T::Native: Normalizable,
{
let v = arr.as_primitive::<T>();
let (iter, l2_norm) = normalize(v.values());
Ok((
Arc::new(PrimitiveArray::<T>::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::<Float16Type>(v),
DataType::Float32 => do_normalize_arrow::<Float32Type>(v),
DataType::Float64 => do_normalize_arrow::<Float64Type>(v),
_ => Err(Error::SchemaError(format!(
"Normalize only supports float array, got: {}",
v.data_type()
))),
}
}
fn do_normalize_fsl<T: ArrowPrimitiveType>(fsl: &FixedSizeListArray) -> Result<FixedSizeListArray>
where
T::Native: Normalizable,
{
let dim = fsl.value_length() as usize;
let norm_arr = PrimitiveArray::<T>::from_iter_values(
fsl.values()
.as_primitive::<T>()
.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<FixedSizeListArray> {
match fsl.value_type() {
DataType::Float16 => do_normalize_fsl::<Float16Type>(fsl),
DataType::Float32 => do_normalize_fsl::<Float32Type>(fsl),
DataType::Float64 => do_normalize_fsl::<Float64Type>(fsl),
_ => Err(ArrowError::SchemaError(format!(
"Normalize only supports float array, got: {}",
fsl.value_type()
))),
}
}
fn do_normalize_fsl_inplace<T: ArrowPrimitiveType>(
fsl: FixedSizeListArray,
) -> Result<FixedSizeListArray>
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<dyn Array> so the buffer's refcount drops to 1.
let prim = values_array
.as_any()
.downcast_ref::<PrimitiveArray<T>>()
.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: <T::Native as Normalizable>::Acc = x.as_();
x * x
})
.sum::<<T::Native as Normalizable>::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::<T>(&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<FixedSizeListArray> {
match fsl.value_type() {
DataType::Float16 => do_normalize_fsl_inplace::<Float16Type>(fsl),
DataType::Float32 => do_normalize_fsl_inplace::<Float32Type>(fsl),
DataType::Float64 => do_normalize_fsl_inplace::<Float64Type>(fsl),
_ => Err(ArrowError::SchemaError(format!(
"Normalize only supports float array, got: {}",
fsl.value_type()
))),
}
}
fn hash_numeric_type<T: ArrowNumericType>(array: &PrimitiveArray<T>) -> Result<UInt64Array>
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<O: OffsetSizeTrait>(array: &GenericStringArray<O>) -> Result<UInt64Array> {
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<UInt64Array> {
match array.data_type() {
DataType::UInt8 => hash_numeric_type(as_primitive_array::<UInt8Type>(array)),
DataType::UInt16 => hash_numeric_type(as_primitive_array::<UInt16Type>(array)),
DataType::UInt32 => hash_numeric_type(as_primitive_array::<UInt32Type>(array)),
DataType::UInt64 => hash_numeric_type(as_primitive_array::<UInt64Type>(array)),
DataType::Int8 => hash_numeric_type(as_primitive_array::<Int8Type>(array)),
DataType::Int16 => hash_numeric_type(as_primitive_array::<Int16Type>(array)),
DataType::Int32 => hash_numeric_type(as_primitive_array::<Int32Type>(array)),
DataType::Int64 => hash_numeric_type(as_primitive_array::<Int64Type>(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<i16> = 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<i16> = 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::<Vec<f32>>, (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<f32>,
#[case] bias: Option<Vec<f32>>,
#[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<u64> = 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<u64> = 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::<f32>().sqrt();
assert_relative_eq!(l2_norm, 55_f32.sqrt());
let normalized = normalize(&v).0.collect::<Vec<f32>>();
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::<f32>());
}
/// 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<f64>)] = &[
("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::<f64>().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<f64> {
let arr = Float64Array::from(v.to_vec());
let (out, _) = normalize_arrow(&arr).unwrap();
out.as_primitive::<Float64Type>().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<f64> {
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::<Float64Type>().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::<Vec<_>>();
// Independent reference: accumulate the same f16 inputs in f64.
let expected = v
.iter()
.map(|x| x.to_f64() * x.to_f64())
.sum::<f64>()
.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::<Vec<_>>();
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::<f64>();
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::<Float16Type>();
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::<Vec<_>>();
let expected = v
.iter()
.map(|x| x.to_f64() * x.to_f64())
.sum::<f64>()
.sqrt();
let (normalized, norm) = normalize(&v);
let normalized = normalized.collect::<Vec<_>>();
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::<f64>();
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::<Float16Type>();
for (row, chunk) in got.values().chunks(2).enumerate() {
let norm = chunk
.iter()
.map(|x| x.to_f64() * x.to_f64())
.sum::<f64>()
.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::<Float32Type>();
// 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<f32>);
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::<Float32Type>();
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<f32>], label: &str) {
let vals = actual.values().as_primitive::<Float32Type>();
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<f32>])] = &[
(
"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::<Float32Type>().values().as_ptr();
let result = normalize_fsl_owned(fsl).unwrap();
let new_ptr = result
.values()
.as_primitive::<Float32Type>()
.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));
}
}
+22
View File
@@ -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<T> = std::result::Result<T, Error>;
+121
View File
@@ -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<T: Num + Copy, const N: usize>:
std::fmt::Debug
+ AddAssign<Self>
+ Add<Self, Output = Self>
+ Mul<Self, Output = Self>
+ Sub<Self, Output = Self>
+ SubAssign<Self>
+ 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<i32>;
}
pub trait FloatSimd<F: Float, const N: usize>: SIMD<F, N> {
/// 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;
}
+727
View File
@@ -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
// <unistd.h>, which -std=c17 otherwise hides.
#define _GNU_SOURCE
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifdef __linux__
#include <sys/syscall.h>
#include <unistd.h>
#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;
}
+454
View File
@@ -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<bool> = 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::<u16>(); 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<f16>) {
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,
);
}
}
+74
View File
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
#include <stddef.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
// 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));
}
+60
View File
@@ -0,0 +1,60 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
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);
}
File diff suppressed because it is too large Load Diff
+145
View File
@@ -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 <stddef.h>
#include <stdint.h>
#include <math.h>
// 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));
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+467
View File
@@ -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<i32, 8> 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<i32> {
#[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);
}
}
+464
View File
@@ -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<const N: i32>(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::<N>(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<u8, 16> 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<i32> {
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::<Vec<_>>();
let b = (16..32).map(|f| f as u8).collect::<Vec<_>>();
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::<Vec<_>>();
assert_eq!(result.as_array(), expected.as_slice());
result += b;
assert_eq!(result.as_array(), expected.as_slice());
}
}
+89
View File
@@ -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);
}
}
+183
View File
@@ -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<usize> {
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<Value = f16> {
any::<u16>().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<Value = bf16> {
any::<u16>()
.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<Value = f32> {
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<Value = f64> {
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<T: std::fmt::Debug, S>(
values: impl Fn() -> S + 'static,
dim_range: std::ops::Range<usize>,
) -> impl Strategy<Value = (Vec<T>, Vec<T>)>
where
S: Strategy<Value = T>,
{
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<T, S, F>(values: fn() -> S, dim_range: Range<usize>, property: F)
where
T: std::fmt::Debug,
S: Strategy<Value = T> + 'static,
F: Fn(Vec<T>, Vec<T>) -> 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<T, S, F>(values: fn() -> S, dim_range: Range<usize>, property: F)
where
T: std::fmt::Debug,
S: Strategy<Value = T>,
F: Fn(Vec<T>) -> 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<u8>, Vec<u8>)> {
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<_>>()
};
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<u8> {
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()
}
}
@@ -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::<String>()
.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}"
);
}