Merge main and align cosine fix with Lance beta.23

This commit is contained in:
Gatefixer
2026-11-16 20:23:43 +00:00
34 changed files with 1499 additions and 874 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "0.42.0-beta.15"
current_version = "0.42.0-beta.17"
parse = """(?x)
(?P<major>0|[1-9]\\d*)\\.
(?P<minor>0|[1-9]\\d*)\\.
Generated
+51 -51
View File
@@ -3885,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsst"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"rand 0.9.5",
@@ -5364,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a"
[[package]]
name = "lance"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arc-swap",
"arrow",
@@ -5440,8 +5440,8 @@ dependencies = [
[[package]]
name = "lance-arrow"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5463,7 +5463,7 @@ dependencies = [
[[package]]
name = "lance-arrow-scalar"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5477,7 +5477,7 @@ dependencies = [
[[package]]
name = "lance-arrow-stats"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5486,8 +5486,8 @@ dependencies = [
[[package]]
name = "lance-bitpacking"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrayref",
"crunchy",
@@ -5497,8 +5497,8 @@ dependencies = [
[[package]]
name = "lance-core"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5536,8 +5536,8 @@ dependencies = [
[[package]]
name = "lance-datafusion"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"arrow-array",
@@ -5568,8 +5568,8 @@ dependencies = [
[[package]]
name = "lance-datafusion-exec"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"arrow-array",
@@ -5594,8 +5594,8 @@ dependencies = [
[[package]]
name = "lance-datagen"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"arrow-array",
@@ -5612,8 +5612,8 @@ dependencies = [
[[package]]
name = "lance-derive"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"proc-macro2",
"quote",
@@ -5622,8 +5622,8 @@ dependencies = [
[[package]]
name = "lance-encoding"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5657,8 +5657,8 @@ dependencies = [
[[package]]
name = "lance-file"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5689,8 +5689,8 @@ dependencies = [
[[package]]
name = "lance-geo"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5721,8 +5721,8 @@ dependencies = [
[[package]]
name = "lance-index"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arc-swap",
"arrow",
@@ -5795,8 +5795,8 @@ dependencies = [
[[package]]
name = "lance-index-core"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5819,8 +5819,8 @@ dependencies = [
[[package]]
name = "lance-io"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"arrow-array",
@@ -5865,8 +5865,8 @@ dependencies = [
[[package]]
name = "lance-jsonb"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"byteorder",
"ethnum",
@@ -5883,7 +5883,7 @@ dependencies = [
[[package]]
name = "lance-linalg"
version = "15.0.0-beta.22"
version = "15.0.0-beta.23"
dependencies = [
"approx",
"argminmax 0.7.1",
@@ -5905,8 +5905,8 @@ dependencies = [
[[package]]
name = "lance-namespace"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"async-trait",
@@ -5920,8 +5920,8 @@ dependencies = [
[[package]]
name = "lance-namespace-impls"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arc-swap",
"arrow",
@@ -5975,8 +5975,8 @@ dependencies = [
[[package]]
name = "lance-select"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5990,8 +5990,8 @@ dependencies = [
[[package]]
name = "lance-table"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow",
"arrow-array",
@@ -6032,8 +6032,8 @@ dependencies = [
[[package]]
name = "lance-testing"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -6046,8 +6046,8 @@ dependencies = [
[[package]]
name = "lance-tokenizer"
version = "15.0.0-beta.22"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
version = "15.0.0-beta.23"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.23#f7ef212132c52f9704c387f342a7ff49a9ebf908"
dependencies = [
"frostem",
"icu_segmenter",
@@ -6060,7 +6060,7 @@ dependencies = [
[[package]]
name = "lancedb"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
dependencies = [
"ahash",
"anyhow",
@@ -6171,7 +6171,7 @@ dependencies = [
[[package]]
name = "lancedb-cli"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
dependencies = [
"anyhow",
"arrow-array",
@@ -6214,7 +6214,7 @@ dependencies = [
[[package]]
name = "lancedb-nodejs"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -6239,7 +6239,7 @@ dependencies = [
[[package]]
name = "lancedb-python"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
dependencies = [
"arc-swap",
"arrow",
+14 -14
View File
@@ -20,20 +20,20 @@ categories = ["database-implementations"]
rust-version = "1.95.0"
[workspace.dependencies]
lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.23", default-features = false, "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lancedb = { path = "rust/lancedb", default-features = false }
ahash = "0.8"
anyhow = "1"
+1 -1
View File
@@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
<dependency>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-core</artifactId>
<version>0.42.0-beta.15</version>
<version>0.42.0-beta.17</version>
</dependency>
```
+1 -1
View File
@@ -8,7 +8,7 @@
<parent>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.15</version>
<version>0.42.0-beta.17</version>
<relativePath>../pom.xml</relativePath>
</parent>
+2 -2
View File
@@ -6,7 +6,7 @@
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.15</version>
<version>0.42.0-beta.17</version>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>LanceDB Java SDK Parent POM</description>
@@ -28,7 +28,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<arrow.version>15.0.0</arrow.version>
<lance-core.version>15.0.0-beta.22</lance-core.version>
<lance-core.version>15.0.0-beta.23</lance-core.version>
<jackson.version>2.18.12</jackson.version>
<spotless.skip>false</spotless.skip>
<spotless.version>2.30.0</spotless.version>
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "lancedb-nodejs"
edition.workspace = true
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
publish = false
license.workspace = true
description.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-darwin-arm64",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["darwin"],
"cpu": ["arm64"],
"main": "lancedb.darwin-arm64.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-gnu",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-musl",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-gnu",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-musl",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-arm64-msvc",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": [
"win32"
],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-x64-msvc",
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"os": ["win32"],
"cpu": ["x64"],
"main": "lancedb.win32-x64-msvc.node",
+1 -1
View File
@@ -11,7 +11,7 @@
"ann"
],
"private": false,
"version": "0.42.0-beta.15",
"version": "0.42.0-beta.17",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b22",
"pylance==15.0.0b23",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+8 -1
View File
@@ -1150,7 +1150,14 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
if not any(child.name in ("data", "uri") for child in source_type):
raise ValueError(
f"blob struct input for column '{field.name}' must contain "
"a 'data' or 'uri' child"
"a 'data' or 'uri' child. A blob query returns an SDK "
"descriptor in this shape, and a descriptor is not payload "
"bytes. Use blob_mode='bytes' to materialize payloads, or "
"inspect descriptors with blob_mode='descriptions'. To copy "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or "
"table.fetch_blob_files(column, row_ids). Keep the source "
"unchanged between selection and fetching."
)
elif not _can_coerce_to_blob(source_type) and not isinstance(
source_type, pa.ExtensionType
+18
View File
@@ -1135,6 +1135,24 @@ def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path):
db = lancedb.connect(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema)
hits = source.search().where("id = 1").to_arrow()
with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc:
db.create_table("copy", data=hits, schema=schema)
message = str(exc.value)
assert "blob_mode='bytes'" in message
assert "blob_mode='descriptions'" in message
assert "with_row_id(True)" in message
assert "fetch_blobs(column, row_ids)" in message
assert "fetch_blob_files(column, row_ids)" in message
assert not db.table_exists(["copy"])
def test_fetch_blobs_round_trip():
table = _blob_table(
"round_trip",
+9 -9
View File
@@ -2147,7 +2147,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b23" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -4301,7 +4301,7 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b22"
version = "15.0.0b23"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,13 +4312,13 @@ dependencies = [
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" },
{ url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" },
{ url = "https://pypi.fury.io/lance-format/-/ver_ldwuz/pylance-15.0.0b23-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:b7980c606424e63e9be645536dbcaff75b479886a53abdae3aef64684c9a6fc4" },
{ url = "https://pypi.fury.io/lance-format/-/ver_5wKzE/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a6d887bc81d5f79b8a23d5cbc840cb56dbea4d8b0a9d2c2edf063dea48bcf741" },
{ url = "https://pypi.fury.io/lance-format/-/ver_FKuk6/pylance-15.0.0b23-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1424bd48cac2160b7745c9b87cd24d81c7cf2b0a89f342ea46ecd2a473ea74e6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_SVglj/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:09de71b60ac6b8b91fdd73207f71c74bc521626de7e437102ebfe4f2c1f78fa0" },
{ url = "https://pypi.fury.io/lance-format/-/ver_SgTr6/pylance-15.0.0b23-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d9385471578bec51ae546f7bd7ea638e20bd12d687082d43ed465017dfd992e7" },
{ url = "https://pypi.fury.io/lance-format/-/ver_wyipY/pylance-15.0.0b23-cp310-abi3-win_amd64.whl", hash = "sha256:7b98b0d78564c5acea3693334c41dc3ced20484fb2c8e738113eeb078281a109" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1v2uEn/pylance-15.0.0b23-cp310-abi3-win_arm64.whl", hash = "sha256:0f4d2645143d44c11237e6ea00772c169a3c6ed23a7c36beaeaef9a18d1be14d" },
]
[[package]]
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
edition.workspace = true
description = "LanceDB: A serverless, low-latency vector database for AI applications"
license.workspace = true
@@ -46,7 +46,7 @@ lance-io = { workspace = true }
lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] }
lance-table = { workspace = true }
# Keep the upstream source for downstream SDKs, where workspace patches do not apply.
lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
lance-linalg = { "version" = "=15.0.0-beta.23", "tag" = "v15.0.0-beta.23", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { workspace = true }
lance-arrow = { workspace = true }
lance-namespace = { workspace = true }
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-cli"
version = "0.42.0-beta.15"
version = "0.42.0-beta.17"
edition = "2021"
license.workspace = true
repository.workspace = true
+130
View File
@@ -3248,6 +3248,136 @@ mod tests {
}
}
#[tokio::test]
async fn input_merge_dirties_only_the_updated_rows_and_retains_outputs() {
let table = fresh_function_table().await;
let source =
arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"]))
.unwrap();
let mut merge = table.merge_insert(&["title"]);
merge.when_matched_update_all(None);
let result = merge
.execute(Box::new(RecordBatchIterator::new(
[Ok(source.clone())],
source.schema(),
)))
.await
.unwrap();
assert_eq!(result.num_updated_rows, 1);
let dataset = table.as_native().unwrap().dataset.get().await.unwrap();
for output in ["search_text", "search_token_count"] {
let stale = function_plan(&dataset, output).await;
let mut dirty_rows = 0;
for fragment in dataset.get_fragments() {
if stale.needs_recompute(fragment.id() as u32) {
let batch = fragment
.scan()
.project(&["title"])
.unwrap()
.try_into_batch()
.await
.unwrap();
let titles = batch
.column(0)
.as_any()
.downcast_ref::<arrow_array::StringArray>()
.unwrap();
assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}");
dirty_rows += batch.num_rows();
}
}
assert_eq!(dirty_rows, 1, "{stale:?}");
}
assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1);
}
#[tokio::test]
async fn input_merge_keeps_an_independent_function_binding_fresh() {
let batch = arrow_array::record_batch!(
("title", Utf8, ["a", "b", "c", "d"]),
("body", Utf8, ["x", "y", "z", "w"]),
("search_text", Utf8, ["a x", "b y", "c z", "d w"]),
("search_token_count", Int64, [2, 2, 2, 2]),
("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]),
("search_token_count_other", Int64, [2, 2, 2, 2])
)
.unwrap();
let table = crate::connect("memory://")
.execute()
.await
.unwrap()
.create_table("independent_merge", batch)
.write_options(crate::table::WriteOptions {
lance_write_params: Some(WriteParams {
max_rows_per_file: 2,
..Default::default()
}),
})
.execute()
.await
.unwrap();
let mut other = serde_json::to_value(text_features_binding("_other")).unwrap();
other["inputs"][1]["field_path"] = serde_json::json!("title");
other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone();
let bindings = [
text_features_binding(""),
serde_json::from_value(other).unwrap(),
];
stamp_bindings(&table, &bindings).await;
let native = table.as_native().unwrap();
let mut dataset = native.dataset.get().await.unwrap().as_ref().clone();
for binding in &bindings {
let paths = binding
.inputs()
.iter()
.map(|input| input.field_path.clone())
.collect::<Vec<_>>();
let inputs = fields_for_paths(dataset.schema(), &paths).unwrap();
let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap();
for output in binding.outputs() {
write_signatures(
&mut dataset,
&output.output_name,
binding.binding_id(),
signatures.clone(),
)
.await
.unwrap();
}
}
native.dataset.update(dataset);
let source =
arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"]))
.unwrap();
let mut merge = table.merge_insert(&["title"]);
merge.when_matched_update_all(None);
merge
.execute(Box::new(RecordBatchIterator::new(
[Ok(source.clone())],
source.schema(),
)))
.await
.unwrap();
let dataset = native.dataset.get().await.unwrap();
assert!(
function_plan(&dataset, "search_text")
.await
.needs_recompute(2)
);
let other = &bindings[1];
let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap();
for output in other.outputs() {
let stale =
staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs)
.await
.unwrap();
assert!(
!stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(),
"{stale:?}"
);
}
}
#[rstest::rstest]
#[case::same_definition(false)]
#[case::changed_definition(true)]
+50 -18
View File
@@ -249,11 +249,13 @@ impl MergeInsertBuilder {
Ok(())
}
/// The existing columns a matched row takes from `source`: every source
/// column but the join keys, which a match leaves equal. An insert-only
/// merge rewrites none; its new rows get Function outputs from the next
/// refresh, as appended rows do.
pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec<String> {
/// The source columns a matched row writes: every column but the join
/// keys, which a match leaves equal. Function inputs stay writable; the
/// merge records their changed signatures so the next refresh recomputes
/// the affected rows. Computed outputs and assignment columns remain
/// protected by the direct-write guard. An insert-only merge writes none;
/// its new rows get Function outputs from the next refresh.
pub(crate) fn matched_source_columns(&self, source: &Fields) -> Vec<String> {
if !self.when_matched_update_all {
return Vec::new();
}
@@ -351,10 +353,10 @@ pub(crate) async fn execute_merge_insert(
) -> Result<MergeResult> {
params.canonicalize_filters()?;
let schema = table.schema().await?;
super::computed_columns::ensure_not_function_bound(
let matched_columns = params.matched_source_columns(new_data.schema().fields());
super::computed_columns::ensure_not_written(
schema.as_ref(),
"merge_insert",
params.function_guarded_columns(new_data.schema().fields()),
matched_columns.iter().map(String::as_str),
)?;
// Normalize blob layouts and JSON extension metadata just as on append.
// Keep arrow.json text labelled until Lance encodes it as JSONB.
@@ -970,10 +972,11 @@ mod tests {
assert_eq!(table.count_rows(None).await.unwrap(), 2);
}
/// A matched row takes every non-key source column, so the merge is
/// refused only when one of those is a binding's input or output.
/// A matched row takes every non-key source column. Function inputs are
/// writable and become stale for the next refresh; computed outputs stay
/// protected, and a mixed input/output source is rejected before commit.
#[tokio::test]
async fn merge_update_on_a_function_table_refuses_only_bound_columns() {
async fn merge_update_allows_function_inputs_but_protects_outputs() {
let table = crate::table::computed_columns::test_support::bound_table_from(
arrow_array::record_batch!(
("id", Int32, [1]),
@@ -998,18 +1001,47 @@ mod tests {
let mut merge = table.merge_insert(&["id"]);
merge.when_matched_update_all(None);
let err = merge
let result = merge
.execute(reader(
arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(),
))
.await
.unwrap_err();
assert!(
matches!(&err, crate::Error::InvalidInput { message }
if message.contains("merge_insert of 'title'")
&& message.contains("a Function binding reads or writes it")),
"{err:?}"
.unwrap();
assert_eq!(result.num_updated_rows, 1);
assert_eq!(
table
.count_rows(Some("title = 'z' AND search_text = 'a b'".into()))
.await
.unwrap(),
1
);
let version = table.version().await.unwrap();
for source in [
arrow_array::record_batch!(("id", Int32, [1]), ("search_text", Utf8, ["uncomputed"]))
.unwrap(),
arrow_array::record_batch!(
("id", Int32, [1]),
("title", Utf8, ["must not commit"]),
("search_text", Utf8, ["uncomputed"])
)
.unwrap(),
] {
let mut merge = table.merge_insert(&["id"]);
merge.when_matched_update_all(None);
let err = merge.execute(reader(source)).await.unwrap_err();
assert!(
matches!(&err, crate::Error::InvalidInput { message }
if message.contains("is computed")
&& message.contains("cannot be written directly")),
"{err:?}"
);
assert_eq!(table.version().await.unwrap(), version);
assert_eq!(
table.count_rows(Some("title = 'z'".into())).await.unwrap(),
1
);
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lance-linalg"
version = "15.0.0-beta.22"
version = "15.0.0-beta.23"
publish = false
edition = { workspace = true }
license = { workspace = true }
+2 -2
View File
@@ -1,5 +1,5 @@
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.22`
(commit `49e29d7beb885e42f3ab01fc9fc25b5281cef467`), licensed under Apache-2.0.
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.23`
(commit `f7ef212132c52f9704c387f342a7ff49a9ebf908`), 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
+12 -8
View File
@@ -18,7 +18,7 @@ fn main() -> Result<(), String> {
// Let clippy know about our custom cfg attribute
println!(
"cargo::rustc-check-cfg=cfg(kernel_support, values(\"avx512_f16\", \"avx512_bf16\", \"amx_fp16\"))"
"cargo::rustc-check-cfg=cfg(kernel_support, values(\"half\", \"avx512_f16\", \"avx512_bf16\", \"amx_fp16\"))"
);
println!("cargo::rustc-check-cfg=cfg(simd_fallback)");
@@ -29,9 +29,10 @@ fn main() -> Result<(), String> {
// 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.
// target_os and the library's features.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let fp16kernels = env::var_os("CARGO_FEATURE_FP16KERNELS").is_some();
// Architectures without SIMD kernels back the vector types with plain arrays.
if !matches!(target_arch.as_str(), "x86_64" | "aarch64" | "loongarch64") {
@@ -68,7 +69,7 @@ fn main() -> Result<(), String> {
"cargo:warning=Skipping build of AVX-512 fp16 kernels. Error: {}",
err
);
} else if cfg!(feature = "fp16kernels") {
} else if 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\"");
@@ -81,7 +82,7 @@ fn main() -> Result<(), String> {
"cargo:warning=Skipping build of AVX-512 bf16 kernels. Error: {}",
err
);
} else if cfg!(feature = "fp16kernels") {
} else if fp16kernels {
println!("cargo:rustc-cfg=kernel_support=\"avx512_bf16\"");
};
// Build the AMX-FP16 batched f16 dot-product kernel (Granite Rapids+).
@@ -138,12 +139,15 @@ fn main() -> Result<(), String> {
} 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() {
if fp16kernels {
return Err("Unable to build f16 kernels on given target_arch. Please use x86_64 or aarch64 or remove the fp16kernels feature".to_string());
}
return Ok(());
}
if fp16kernels {
// Every branch above that reaches here built the f16 and bf16 objects
// for this target.
println!("cargo:rustc-cfg=kernel_support=\"half\"");
}
Ok(())
}
+66 -226
View File
@@ -15,7 +15,72 @@ use std::sync::Arc;
use arrow_array::cast::AsArray;
use arrow_array::{Array, FixedSizeListArray, Float32Array, ListArray};
use arrow_schema::ArrowError;
use lance_core::utils::cpu::SimdSupport;
/// Declares a safe [`lance_core::target_kernel!`] wrapper and its candidate
/// for each half-precision C kernel in the caller's `ffi` module.
///
/// The listed features must be exactly the feature set build.rs compiled that
/// kernel's object for, as `half_c_objects` spells it. The AVX-512 objects target Sapphire
/// Rapids, so they require `avx512fp16`, which stands in for that CPU's
/// features, plus `avx512bf16` for the bf16 object.
///
/// The C arguments must clamp lengths so the kernel only reads within the
/// slices: the wrapper is safe to call on any host with the listed features.
#[cfg(kernel_support = "half")]
macro_rules! half_c_kernels {
(
fn $params:tt -> f32 => $args:tt;
$(
$(#[$attr:meta])*
$candidate:ident: $kernel_type:ty = $name:ident($($feature:literal),*);
)*
) => {
$(
$(#[$attr])*
lance_core::target_kernel! {
#[target_features($($feature),*)]
#[candidate(pub(super) $candidate: $kernel_type)]
fn $name $params -> f32 {
// SAFETY: the arguments bound every read by the slice
// lengths, and the target features are the object's only
// other precondition.
unsafe { ffi::$name $args }
}
}
)*
};
}
/// What build.rs compiles each half-precision C object for, as feature sets.
/// Every `half_c` module checks its candidates against these at compile time.
#[cfg(kernel_support = "half")]
mod half_c_objects {
use lance_core::utils::cpu::CpuFeatures;
/// `CpuFeatures` equality, usable in const asserts where `==` is not.
pub const fn same_features(features: CpuFeatures, object: CpuFeatures) -> bool {
features.contains(object) && object.contains(features)
}
/// `-march=haswell`, less LZCNT and MOVBE, which `CpuFeatures` does not
/// track.
#[cfg(target_arch = "x86_64")]
pub const HASWELL: CpuFeatures =
CpuFeatures::from_target_features(&["avx2", "fma", "f16c", "bmi1", "bmi2"]);
/// `-march=sapphirerapids -mavx512fp16`.
#[cfg(target_arch = "x86_64")]
pub const SAPPHIRE_RAPIDS_F16: CpuFeatures = CpuFeatures::from_target_features(&["avx512fp16"]);
#[cfg(target_arch = "x86_64")]
pub const SAPPHIRE_RAPIDS_BF16: CpuFeatures =
CpuFeatures::from_target_features(&["avx512fp16", "avx512bf16"]);
/// `-march=armv8.2-a+fp16`, or an Apple CPU that has FP16.
#[cfg(target_arch = "aarch64")]
pub const ARMV8_2_FP16: CpuFeatures = CpuFeatures::from_target_features(&["neon", "fp16"]);
#[cfg(target_arch = "loongarch64")]
pub const LASX: CpuFeatures = CpuFeatures::from_target_features(&["lasx"]);
#[cfg(target_arch = "loongarch64")]
pub const LSX: CpuFeatures = CpuFeatures::from_target_features(&["lsx"]);
}
mod arrow;
@@ -76,94 +141,6 @@ fn assert_batch_output_layout(
);
}
/// Runtime backend shared by the f16 and bf16 C kernels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HalfBackend {
Avx512,
Avx2,
Neon,
Lsx,
Lasx,
Scalar,
}
/// Half-precision element type whose fallback kernel is being selected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HalfType {
F16,
Bf16,
}
/// CPU features required by the x86 fallback objects.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct X86HalfFeatures {
has_avx2: bool,
has_f16c: bool,
has_fma: bool,
}
/// Whether this target links the optional half-precision C objects.
const HALF_KERNELS_COMPILED: bool = cfg!(all(
feature = "fp16kernels",
not(target_os = "windows"),
any(
target_arch = "aarch64",
target_arch = "x86_64",
target_arch = "loongarch64"
)
));
/// Selects a half-precision backend without reading host or build state so the
/// exclusive SIMD tier ladder can be tested on any machine.
fn half_backend(
support: SimdSupport,
half_type: HalfType,
has_kernels: bool,
has_avx512_kernel: bool,
x86_features: X86HalfFeatures,
) -> HalfBackend {
if !has_kernels {
return HalfBackend::Scalar;
}
match support {
SimdSupport::Avx512FP16 if has_avx512_kernel => HalfBackend::Avx512,
// SIMD_SUPPORT reports one exclusive tier. An AVX-512 host that cannot
// use the optional AVX-512 C object must therefore be named here to
// reach the always-built x86 fallback object.
SimdSupport::Avx512 | SimdSupport::Avx512FP16 | SimdSupport::Avx2
if x86_features.has_fma
&& match half_type {
HalfType::F16 => x86_features.has_f16c,
HalfType::Bf16 => x86_features.has_avx2,
} =>
{
HalfBackend::Avx2
}
SimdSupport::Neon => HalfBackend::Neon,
SimdSupport::Lsx => HalfBackend::Lsx,
SimdSupport::Lasx => HalfBackend::Lasx,
_ => HalfBackend::Scalar,
}
}
/// Detects every feature emitted by the x86 fallback objects.
#[inline]
fn x86_half_features() -> X86HalfFeatures {
#[cfg(target_arch = "x86_64")]
{
X86HalfFeatures {
has_avx2: std::is_x86_feature_detected!("avx2"),
has_f16c: std::is_x86_feature_detected!("f16c"),
has_fma: std::is_x86_feature_detected!("fma"),
}
}
#[cfg(not(target_arch = "x86_64"))]
{
X86HalfFeatures::default()
}
}
/// Largest number of maximal u8 product terms whose sum fits in a u32.
const U8_U32_ACCUMULATOR_MAX_LEN: usize = u32::MAX as usize / (u8::MAX as usize * u8::MAX as usize);
@@ -373,143 +350,6 @@ mod tests {
use half::f16;
use lance_arrow::FixedSizeListArrayExt;
const NO_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures {
has_avx2: false,
has_f16c: false,
has_fma: false,
};
const F16_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures {
has_avx2: false,
has_f16c: true,
has_fma: true,
};
const BF16_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures {
has_avx2: true,
has_f16c: false,
has_fma: true,
};
const ALL_X86_HALF_FEATURES: X86HalfFeatures = X86HalfFeatures {
has_avx2: true,
has_f16c: true,
has_fma: true,
};
const X86_HALF_FEATURES_WITHOUT_FMA: X86HalfFeatures = X86HalfFeatures {
has_avx2: true,
has_f16c: true,
has_fma: false,
};
#[rstest::rstest]
#[case::kernels_disabled(
SimdSupport::Avx512FP16,
HalfType::F16,
false,
false,
ALL_X86_HALF_FEATURES,
HalfBackend::Scalar
)]
#[case::avx512_kernel_ready(
SimdSupport::Avx512FP16,
HalfType::F16,
true,
true,
NO_X86_HALF_FEATURES,
HalfBackend::Avx512
)]
#[case::f16_fallback_from_avx512fp16(
SimdSupport::Avx512FP16,
HalfType::F16,
true,
false,
F16_X86_HALF_FEATURES,
HalfBackend::Avx2
)]
#[case::bf16_fallback_from_avx512fp16(
SimdSupport::Avx512FP16,
HalfType::Bf16,
true,
false,
BF16_X86_HALF_FEATURES,
HalfBackend::Avx2
)]
#[case::fallback_from_avx512(
SimdSupport::Avx512,
HalfType::Bf16,
true,
false,
BF16_X86_HALF_FEATURES,
HalfBackend::Avx2
)]
#[case::f16_missing_f16c(
SimdSupport::Avx512FP16,
HalfType::F16,
true,
false,
BF16_X86_HALF_FEATURES,
HalfBackend::Scalar
)]
#[case::bf16_missing_avx2(
SimdSupport::Avx512FP16,
HalfType::Bf16,
true,
false,
F16_X86_HALF_FEATURES,
HalfBackend::Scalar
)]
#[case::fallback_missing_fma(
SimdSupport::Avx512FP16,
HalfType::F16,
true,
false,
X86_HALF_FEATURES_WITHOUT_FMA,
HalfBackend::Scalar
)]
#[case::avx2_tier(
SimdSupport::Avx2,
HalfType::Bf16,
true,
false,
BF16_X86_HALF_FEATURES,
HalfBackend::Avx2
)]
#[case::neon(
SimdSupport::Neon,
HalfType::F16,
true,
false,
NO_X86_HALF_FEATURES,
HalfBackend::Neon
)]
#[case::lsx(
SimdSupport::Lsx,
HalfType::Bf16,
true,
false,
NO_X86_HALF_FEATURES,
HalfBackend::Lsx
)]
#[case::lasx(
SimdSupport::Lasx,
HalfType::Bf16,
true,
false,
NO_X86_HALF_FEATURES,
HalfBackend::Lasx
)]
fn half_backend_follows_exclusive_tier_and_feature_requirements(
#[case] support: SimdSupport,
#[case] half_type: HalfType,
#[case] has_kernels: bool,
#[case] has_avx512_kernel: bool,
#[case] features: X86HalfFeatures,
#[case] expected: HalfBackend,
) {
assert_eq!(
half_backend(support, half_type, has_kernels, has_avx512_kernel, features),
expected
);
}
#[cfg(target_arch = "x86_64")]
#[test]
fn test_x86_runtime_feature_report() {
+287 -140
View File
@@ -12,17 +12,11 @@ use std::sync::Arc;
use arrow_array::{Array, FixedSizeListArray, Float32Array};
use half::{bf16, f16};
use lance_core::utils::cpu::SIMD_SUPPORT;
#[cfg(feature = "fp16kernels")]
use super::HalfBackend;
use super::{
BatchKernel, Dot, HALF_KERNELS_COMPILED, HalfType, Normalize, assert_batch_output_layout,
assert_equal_lengths,
BatchKernel, Dot, Normalize, assert_batch_output_layout, assert_equal_lengths,
dot::dot,
half_backend,
norm_l2::{norm_l2, norm_l2_impl},
x86_half_features,
};
use crate::Result;
#[cfg(not(target_arch = "x86_64"))]
@@ -79,139 +73,6 @@ impl Cosine for u8 {
}
}
#[cfg(feature = "fp16kernels")]
mod bf16_kernel {
use half::bf16;
// These are the `cosine_bf16` function in bf16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn cosine_bf16_neon(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32)
-> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn cosine_bf16_avx512(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn cosine_bf16_avx2(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32)
-> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_bf16_lsx(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_bf16_lasx(x: *const bf16, x_norm: f32, y: *const bf16, dimension: u32)
-> f32;
}
}
impl Cosine for bf16 {
fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
match half_backend(
*SIMD_SUPPORT,
HalfType::Bf16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")),
x86_half_features(),
) {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe {
bf16_kernel::cosine_bf16_neon(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_bf16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
bf16_kernel::cosine_bf16_avx512(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe {
bf16_kernel::cosine_bf16_avx2(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe {
bf16_kernel::cosine_bf16_lasx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe {
bf16_kernel::cosine_bf16_lsx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
// SimdSupport::AvxFma and SimdSupport::Avx fall through here:
// the bf16 C kernels in `bf16_kernel::*` are compiled with
// `-march=haswell` minimum (which requires AVX2), so they cannot
// run on AVX-only or AVX+FMA hosts. Scalar is the correct route.
_ => cosine_scalar(x, x_norm, y),
}
}
}
#[cfg(feature = "fp16kernels")]
mod kernel {
use super::*;
// These are the `cosine_f16` function in f16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn cosine_f16_neon(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32;
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn cosine_f16_avx512(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn cosine_f16_avx2(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_f16_lsx(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_f16_lasx(x: *const f16, x_norm: f32, y: *const f16, dimension: u32) -> f32;
}
}
impl Cosine for f16 {
fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
match half_backend(
*SIMD_SUPPORT,
HalfType::F16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")),
x86_half_features(),
) {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe {
kernel::cosine_f16_neon(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_f16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
kernel::cosine_f16_avx512(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe {
kernel::cosine_f16_avx2(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe {
kernel::cosine_f16_lasx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe {
kernel::cosine_f16_lsx(x.as_ptr(), x_norm, y.as_ptr(), y.len() as u32)
},
// SimdSupport::AvxFma and SimdSupport::Avx retain their scalar
// route; this fallback only extends the tiers the C kernel already
// served to Avx512FP16 after checking F16C and FMA.
_ => cosine_scalar(x, x_norm, y),
}
}
}
/// Cosine distance from `x`, whose L2 norm is `x_norm`, to `y`.
type CosineKernel<T> = unsafe fn(&[T], f32, &[T]) -> f32;
@@ -219,6 +80,219 @@ type CosineKernel<T> = unsafe fn(&[T], f32, &[T]) -> f32;
/// order of [`Cosine::cosine_with_norms`].
type CosineWithNormsKernel = unsafe fn(&[f32], f32, f32, &[f32]) -> f32;
impl Cosine for bf16 {
fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
COSINE_BF16.get().call(x, x_norm, y)
}
}
impl Cosine for f16 {
fn cosine_fast(x: &[Self], x_norm: f32, y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
COSINE_F16.get().call(x, x_norm, y)
}
}
lance_core::dispatch! {
static COSINE_F16: Dispatch<CosineKernel<f16>> = &[
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
half_c::COSINE_F16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::COSINE_F16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::COSINE_F16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::COSINE_F16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::COSINE_F16_LSX,
COSINE_F16_SCALAR,
];
}
lance_core::dispatch! {
static COSINE_BF16: Dispatch<CosineKernel<bf16>> = &[
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
half_c::COSINE_BF16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::COSINE_BF16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::COSINE_BF16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::COSINE_BF16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::COSINE_BF16_LSX,
COSINE_BF16_SCALAR,
];
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(COSINE_F16_SCALAR: CosineKernel<f16>)]
fn cosine_f16_scalar(x: &[f16], x_norm: f32, y: &[f16]) -> f32 {
cosine_scalar(x, x_norm, y)
}
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(COSINE_BF16_SCALAR: CosineKernel<bf16>)]
fn cosine_bf16_scalar(x: &[bf16], x_norm: f32, y: &[bf16]) -> f32 {
cosine_scalar(x, x_norm, y)
}
}
/// The `cosine_f16` and `cosine_bf16` functions in f16.c and bf16.c. build.rs
/// compiles each file once per SIMD level, suffixing the symbols with the level.
#[cfg(kernel_support = "half")]
mod half_c {
use half::{bf16, f16};
use super::CosineKernel;
mod ffi {
use half::{bf16, f16};
unsafe extern "C" {
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn cosine_f16_avx512(
x: *const f16,
x_norm: f32,
y: *const f16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn cosine_f16_avx2(
x: *const f16,
x_norm: f32,
y: *const f16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn cosine_f16_neon(
x: *const f16,
x_norm: f32,
y: *const f16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_f16_lasx(
x: *const f16,
x_norm: f32,
y: *const f16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_f16_lsx(x: *const f16, x_norm: f32, y: *const f16, dimension: u32)
-> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn cosine_bf16_avx512(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn cosine_bf16_avx2(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn cosine_bf16_neon(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_bf16_lasx(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn cosine_bf16_lsx(
x: *const bf16,
x_norm: f32,
y: *const bf16,
dimension: u32,
) -> f32;
}
}
half_c_kernels! {
fn (x: &[f16], x_norm: f32, y: &[f16]) -> f32
=> (x.as_ptr(), x_norm, y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
COSINE_F16_AVX512: CosineKernel<f16> = cosine_f16_avx512("avx512fp16");
#[cfg(target_arch = "x86_64")]
COSINE_F16_AVX2: CosineKernel<f16> = cosine_f16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
COSINE_F16_NEON: CosineKernel<f16> = cosine_f16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
COSINE_F16_LASX: CosineKernel<f16> = cosine_f16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
COSINE_F16_LSX: CosineKernel<f16> = cosine_f16_lsx("lsx");
}
half_c_kernels! {
fn (x: &[bf16], x_norm: f32, y: &[bf16]) -> f32
=> (x.as_ptr(), x_norm, y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
COSINE_BF16_AVX512: CosineKernel<bf16> = cosine_bf16_avx512("avx512fp16", "avx512bf16");
#[cfg(target_arch = "x86_64")]
COSINE_BF16_AVX2: CosineKernel<bf16> = cosine_bf16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
COSINE_BF16_NEON: CosineKernel<bf16> = cosine_bf16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
COSINE_BF16_LASX: CosineKernel<bf16> = cosine_bf16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
COSINE_BF16_LSX: CosineKernel<bf16> = cosine_bf16_lsx("lsx");
}
// Each candidate must require what build.rs compiled its object for.
#[cfg(target_arch = "x86_64")]
const _: () = {
use crate::distance::half_c_objects::{HASWELL, same_features};
assert!(same_features(COSINE_F16_AVX2.features(), HASWELL));
assert!(same_features(COSINE_BF16_AVX2.features(), HASWELL));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_f16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_F16, same_features};
assert!(same_features(
COSINE_F16_AVX512.features(),
SAPPHIRE_RAPIDS_F16
));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_bf16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_BF16, same_features};
assert!(same_features(
COSINE_BF16_AVX512.features(),
SAPPHIRE_RAPIDS_BF16
));
};
#[cfg(target_arch = "aarch64")]
const _: () = {
use crate::distance::half_c_objects::{ARMV8_2_FP16, same_features};
assert!(same_features(COSINE_F16_NEON.features(), ARMV8_2_FP16));
assert!(same_features(COSINE_BF16_NEON.features(), ARMV8_2_FP16));
};
#[cfg(target_arch = "loongarch64")]
const _: () = {
use crate::distance::half_c_objects::{LASX, LSX, same_features};
assert!(same_features(COSINE_F16_LASX.features(), LASX));
assert!(same_features(COSINE_BF16_LASX.features(), LASX));
assert!(same_features(COSINE_F16_LSX.features(), LSX));
assert!(same_features(COSINE_BF16_LSX.features(), LSX));
};
}
impl Cosine for f32 {
#[inline]
fn cosine_fast(x: &[Self], x_norm: Self, other: &[Self]) -> f32 {
@@ -1212,6 +1286,7 @@ mod tests {
dimension_shard, run_vector_pair_proptest,
};
use approx::assert_relative_eq;
use lance_core::utils::cpu::Dispatch;
use num_traits::AsPrimitive;
use proptest::prelude::*;
@@ -1557,6 +1632,78 @@ mod tests {
});
}
/// Every host-supported half-precision kernel must agree with an f64
/// reference.
fn check_half_cosine_kernels<T: Cosine + AsPrimitive<f64>>(
dispatch: &Dispatch<CosineKernel<T>>,
x: &[T],
y: &[T],
) -> std::result::Result<(), TestCaseError> {
let x_norm = norm_l2(x);
prop_assume!(x_norm > 1e-6);
prop_assume!(norm_l2(y) > 1e-6);
let x_f64 = x.iter().map(|&v| v.as_()).collect::<Vec<_>>();
let y_f64 = y.iter().map(|&v| v.as_()).collect::<Vec<_>>();
let (want, max_error) = cosine_ref(&x_f64, &y_f64, 1e-6);
for candidate in dispatch.candidates() {
let Some(kernel) = candidate.kernel() else {
continue;
};
let got = kernel.call(x, x_norm, y);
prop_assert!(
approx::relative_eq!(got, want, epsilon = max_error),
"{} at dim {}: {got} != {want}",
candidate.name(),
x.len()
);
// The C candidates' safe wrappers clamp the length to the shorter
// slice, so extra elements on either side must not change the
// result. The scalar candidate is the one without features.
if candidate.features().is_empty() {
continue;
}
for (x, y) in [(x, &[y, x].concat()[..]), (&[x, y].concat()[..], y)] {
let clamped = kernel.call(x, x_norm, y);
prop_assert!(
clamped.to_bits() == got.to_bits(),
"{} at lengths {} and {}: {clamped} != {got}",
candidate.name(),
x.len(),
y.len()
);
}
}
Ok(())
}
#[test]
fn test_cosine_half_kernels_short_lengths() {
run_vector_pair_proptest(arbitrary_f16, 0..4, |x, y| {
check_half_cosine_kernels(&COSINE_F16, &x, &y)
});
run_vector_pair_proptest(arbitrary_bf16, 0..4, |x, y| {
check_half_cosine_kernels(&COSINE_BF16, &x, &y)
});
}
#[rstest::rstest]
fn test_cosine_f16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_f16, dimension_shard(shard), |x, y| {
check_half_cosine_kernels(&COSINE_F16, &x, &y)
});
}
#[rstest::rstest]
fn test_cosine_bf16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_bf16, dimension_shard(shard), |x, y| {
check_half_cosine_kernels(&COSINE_BF16, &x, &y)
});
}
proptest::proptest! {
#[test]
fn test_cosine_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) {
+266 -119
View File
@@ -10,16 +10,11 @@ use std::sync::Arc;
use arrow_array::{Array, FixedSizeListArray, Float32Array};
use half::{bf16, f16};
use lance_core::{deepsize::DeepSizeOf, utils::cpu::SIMD_SUPPORT};
use lance_core::deepsize::DeepSizeOf;
use num_traits::{AsPrimitive, Num, real::Real};
use crate::Result;
#[cfg(feature = "fp16kernels")]
use crate::distance::HalfBackend;
use crate::distance::{
BatchKernel, HALF_KERNELS_COMPILED, HalfType, PairKernel, assert_batch_output_layout,
assert_equal_lengths, half_backend, x86_half_features,
};
use crate::distance::{BatchKernel, PairKernel, assert_batch_output_layout, assert_equal_lengths};
/// Default implementation of dot product.
///
@@ -196,7 +191,9 @@ pub trait Dot: Num {
/// The default calls [`Dot::dot`] per vector. `f32` overrides it with one
/// batch kernel call, so the SIMD tier is chosen once for the whole batch
/// instead of once per vector. `f64` overrides it off x86_64 to specialize
/// the loop for the common PQ sub-vector lengths.
/// the loop for the common PQ sub-vector lengths. `f16` and `bf16` call the
/// portable scalar kernel directly when the build has no C half kernels, so
/// that it inlines; otherwise they keep selecting per vector.
///
/// # Panics
///
@@ -211,86 +208,30 @@ pub trait Dot: Num {
}
}
#[cfg(feature = "fp16kernels")]
mod bf16_kernel {
use half::bf16;
// These are the `dot_bf16` function in bf16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn dot_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn dot_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn dot_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
}
}
impl Dot for bf16 {
#[inline]
fn dot(x: &[Self], y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
match half_backend(
*SIMD_SUPPORT,
HalfType::Bf16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")),
x86_half_features(),
) {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe {
bf16_kernel::dot_bf16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_bf16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
bf16_kernel::dot_bf16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe {
bf16_kernel::dot_bf16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe {
bf16_kernel::dot_bf16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe {
bf16_kernel::dot_bf16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
// SimdSupport::AvxFma and SimdSupport::Avx fall through here:
// the bf16 C kernels are compiled with `-march=haswell` minimum
// (AVX2), so they cannot run on AVX-only or AVX+FMA hosts.
_ => dot_scalar::<Self, f32, 32>(x, y),
}
DOT_BF16.get().call(x, y)
}
}
#[cfg(feature = "fp16kernels")]
mod kernel {
use super::*;
// These are the `dot_f16` function in f16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn dot_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn dot_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn dot_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[inline]
fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) {
assert_batch_output_layout(x.len(), batch.len(), dimension, output.len());
for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
#[cfg(not(any(kernel_support = "half", kernel_support = "avx512_bf16")))]
{
// Without C half kernels `DOT_BF16` has a single portable
// candidate. Calling it through the dispatch function pointer
// keeps the scalar kernel out of line, adding a call per
// vector to the PQ table build loop.
*product = dot_scalar::<Self, f32, 32>(x, y);
}
#[cfg(any(kernel_support = "half", kernel_support = "avx512_bf16"))]
{
*product = Self::dot(x, y);
}
}
}
}
@@ -298,45 +239,178 @@ impl Dot for f16 {
#[inline]
fn dot(x: &[Self], y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
match half_backend(
*SIMD_SUPPORT,
HalfType::F16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")),
x86_half_features(),
) {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe {
kernel::dot_f16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_f16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
kernel::dot_f16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe {
kernel::dot_f16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe {
kernel::dot_f16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe {
kernel::dot_f16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
// SimdSupport::AvxFma and SimdSupport::Avx retain their scalar
// route; this fallback only extends the tiers the C kernel already
// served to Avx512FP16 after checking F16C and FMA.
_ => dot_scalar::<Self, f32, 32>(x, y),
DOT_F16.get().call(x, y)
}
#[inline]
fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) {
assert_batch_output_layout(x.len(), batch.len(), dimension, output.len());
for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
#[cfg(not(any(kernel_support = "half", kernel_support = "avx512_f16")))]
{
// See `dot_batch_into` for bf16: inline the only portable
// candidate instead of calling it through the dispatch.
*product = dot_scalar::<Self, f32, 32>(x, y);
}
#[cfg(any(kernel_support = "half", kernel_support = "avx512_f16"))]
{
*product = Self::dot(x, y);
}
}
}
}
lance_core::dispatch! {
static DOT_F16: Dispatch<PairKernel<f16>> = &[
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
half_c::DOT_F16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::DOT_F16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::DOT_F16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::DOT_F16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::DOT_F16_LSX,
DOT_F16_SCALAR,
];
}
lance_core::dispatch! {
static DOT_BF16: Dispatch<PairKernel<bf16>> = &[
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
half_c::DOT_BF16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::DOT_BF16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::DOT_BF16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::DOT_BF16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::DOT_BF16_LSX,
DOT_BF16_SCALAR,
];
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(DOT_F16_SCALAR: PairKernel<f16>)]
fn dot_f16_scalar(x: &[f16], y: &[f16]) -> f32 {
dot_scalar::<f16, f32, 32>(x, y)
}
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(DOT_BF16_SCALAR: PairKernel<bf16>)]
fn dot_bf16_scalar(x: &[bf16], y: &[bf16]) -> f32 {
dot_scalar::<bf16, f32, 32>(x, y)
}
}
/// The `dot_f16` and `dot_bf16` functions in f16.c and bf16.c. build.rs compiles
/// each file once per SIMD level, suffixing the symbols with the level.
#[cfg(kernel_support = "half")]
mod half_c {
use half::{bf16, f16};
use crate::distance::PairKernel;
mod ffi {
use half::{bf16, f16};
unsafe extern "C" {
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn dot_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn dot_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn dot_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn dot_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn dot_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn dot_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn dot_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
}
}
half_c_kernels! {
fn (x: &[f16], y: &[f16]) -> f32 => (x.as_ptr(), y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
DOT_F16_AVX512: PairKernel<f16> = dot_f16_avx512("avx512fp16");
#[cfg(target_arch = "x86_64")]
DOT_F16_AVX2: PairKernel<f16> = dot_f16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
DOT_F16_NEON: PairKernel<f16> = dot_f16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
DOT_F16_LASX: PairKernel<f16> = dot_f16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
DOT_F16_LSX: PairKernel<f16> = dot_f16_lsx("lsx");
}
half_c_kernels! {
fn (x: &[bf16], y: &[bf16]) -> f32 => (x.as_ptr(), y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
DOT_BF16_AVX512: PairKernel<bf16> = dot_bf16_avx512("avx512fp16", "avx512bf16");
#[cfg(target_arch = "x86_64")]
DOT_BF16_AVX2: PairKernel<bf16> = dot_bf16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
DOT_BF16_NEON: PairKernel<bf16> = dot_bf16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
DOT_BF16_LASX: PairKernel<bf16> = dot_bf16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
DOT_BF16_LSX: PairKernel<bf16> = dot_bf16_lsx("lsx");
}
// Each candidate must require what build.rs compiled its object for.
#[cfg(target_arch = "x86_64")]
const _: () = {
use crate::distance::half_c_objects::{HASWELL, same_features};
assert!(same_features(DOT_F16_AVX2.features(), HASWELL));
assert!(same_features(DOT_BF16_AVX2.features(), HASWELL));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_f16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_F16, same_features};
assert!(same_features(
DOT_F16_AVX512.features(),
SAPPHIRE_RAPIDS_F16
));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_bf16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_BF16, same_features};
assert!(same_features(
DOT_BF16_AVX512.features(),
SAPPHIRE_RAPIDS_BF16
));
};
#[cfg(target_arch = "aarch64")]
const _: () = {
use crate::distance::half_c_objects::{ARMV8_2_FP16, same_features};
assert!(same_features(DOT_F16_NEON.features(), ARMV8_2_FP16));
assert!(same_features(DOT_BF16_NEON.features(), ARMV8_2_FP16));
};
#[cfg(target_arch = "loongarch64")]
const _: () = {
use crate::distance::half_c_objects::{LASX, LSX, same_features};
assert!(same_features(DOT_F16_LASX.features(), LASX));
assert!(same_features(DOT_BF16_LASX.features(), LASX));
assert!(same_features(DOT_F16_LSX.features(), LSX));
assert!(same_features(DOT_BF16_LSX.features(), LSX));
};
}
impl Dot for f32 {
#[inline]
fn dot(x: &[Self], y: &[Self]) -> f32 {
@@ -935,6 +1009,7 @@ mod tests {
arbitrary_bf16, arbitrary_f16, arbitrary_f32, arbitrary_f64, arbitrary_vector_pair,
dimension_shard, run_vector_pair_proptest,
};
use lance_core::utils::cpu::Dispatch;
use num_traits::{Float, FromPrimitive};
use proptest::prelude::*;
@@ -1302,6 +1377,76 @@ mod tests {
}
}
/// Every host-supported half-precision kernel must agree with an f64
/// reference.
fn check_half_dot_kernels<T: AsPrimitive<f64> + Float>(
dispatch: &Dispatch<PairKernel<T>>,
x: &[T],
y: &[T],
) -> std::result::Result<(), TestCaseError> {
let x_f64 = x.iter().map(|&v| v.as_()).collect::<Vec<f64>>();
let y_f64 = y.iter().map(|&v| v.as_()).collect::<Vec<f64>>();
let want = dot_scalar_ref(&x_f64, &y_f64);
let max_error = max_error::<T>(&x_f64, &y_f64);
for candidate in dispatch.candidates() {
let Some(kernel) = candidate.kernel() else {
continue;
};
let got = kernel.call(x, y);
prop_assert!(
approx::relative_eq!(got, want, epsilon = max_error),
"{} at dim {}: {got} != {want}",
candidate.name(),
x.len()
);
// The C candidates' safe wrappers clamp the length to the shorter
// slice, so extra elements on either side must not change the
// result. The scalar candidate is the one without features.
if candidate.features().is_empty() {
continue;
}
for (x, y) in [(x, &[y, x].concat()[..]), (&[x, y].concat()[..], y)] {
let clamped = kernel.call(x, y);
prop_assert!(
clamped.to_bits() == got.to_bits(),
"{} at lengths {} and {}: {clamped} != {got}",
candidate.name(),
x.len(),
y.len()
);
}
}
Ok(())
}
#[test]
fn test_dot_half_kernels_short_lengths() {
run_vector_pair_proptest(arbitrary_f16, 0..4, |x, y| {
check_half_dot_kernels(&DOT_F16, &x, &y)
});
run_vector_pair_proptest(arbitrary_bf16, 0..4, |x, y| {
check_half_dot_kernels(&DOT_BF16, &x, &y)
});
}
#[rstest::rstest]
fn test_dot_f16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_f16, dimension_shard(shard), |x, y| {
check_half_dot_kernels(&DOT_F16, &x, &y)
});
}
#[rstest::rstest]
fn test_dot_bf16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_bf16, dimension_shard(shard), |x, y| {
check_half_dot_kernels(&DOT_BF16, &x, &y)
});
}
proptest::proptest! {
#[test]
fn test_dot_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) {
@@ -1331,8 +1476,8 @@ mod tests {
}
/// `dot_batch_into` must agree with the per-vector `dot`. The f32 batch
/// kernel may differ in rounding; the f64 batch loops run the pair
/// kernel's arithmetic, so f64 must match bit for bit.
/// kernel may differ in rounding; the f64 and half batches run the pair
/// kernel's arithmetic, so they must match bit for bit.
#[rstest::rstest]
#[case::dim_8(8)]
#[case::dim_12(12)]
@@ -1371,6 +1516,8 @@ mod tests {
}
}
}
check::<f16>(dimension, true);
check::<bf16>(dimension, true);
check::<f32>(dimension, false);
check::<f64>(dimension, true);
}
+364 -143
View File
@@ -14,13 +14,11 @@ use argminmax::ArgMinMax;
use arrow_array::{Array, FixedSizeListArray, Float32Array};
use half::{bf16, f16};
use lance_core::deepsize::DeepSizeOf;
use lance_core::utils::cpu::SIMD_SUPPORT;
use num_traits::{AsPrimitive, Num};
use crate::distance::{
BatchKernel, HALF_KERNELS_COMPILED, HalfBackend, HalfType, PairKernel,
U8_U32_ACCUMULATOR_MAX_LEN, assert_batch_output_layout, assert_equal_lengths, half_backend,
x86_half_features,
BatchKernel, PairKernel, U8_U32_ACCUMULATOR_MAX_LEN, assert_batch_output_layout,
assert_equal_lengths,
};
/// Calculate the L2 distance between two vectors.
@@ -184,168 +182,266 @@ impl L2 for u8 {
}
}
#[cfg(feature = "fp16kernels")]
mod bf16_kernel {
use half::bf16;
// These are the `l2_bf16` function in bf16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn l2_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn l2_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn l2_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
}
}
impl L2 for bf16 {
#[inline]
fn l2(x: &[Self], y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
match half_backend(
*SIMD_SUPPORT,
HalfType::Bf16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_bf16", target_arch = "x86_64")),
x86_half_features(),
) {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe {
bf16_kernel::l2_bf16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_bf16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
bf16_kernel::l2_bf16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe {
bf16_kernel::l2_bf16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe {
bf16_kernel::l2_bf16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe {
bf16_kernel::l2_bf16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
// SimdSupport::AvxFma and SimdSupport::Avx fall through here:
// the bf16 C kernels are compiled with `-march=haswell` minimum
// (AVX2), so they cannot run on AVX-only or AVX+FMA hosts.
_ => l2_scalar::<Self, f32, 16>(x, y),
}
L2_BF16.get().call(x, y)
}
}
#[cfg(feature = "fp16kernels")]
mod kernel {
use super::*;
// These are the `l2_f16` function in f16.c. Our build.rs script compiles
// a version of this file for each SIMD level with different suffixes.
unsafe extern "C" {
#[cfg(target_arch = "aarch64")]
pub fn l2_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn l2_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn l2_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
}
}
fn f16_backend() -> HalfBackend {
half_backend(
*SIMD_SUPPORT,
HalfType::F16,
HALF_KERNELS_COMPILED,
cfg!(all(kernel_support = "avx512_f16", target_arch = "x86_64")),
x86_half_features(),
)
}
impl L2 for f16 {
#[inline]
fn l2(x: &[Self], y: &[Self]) -> f32 {
assert_equal_lengths(x.len(), y.len());
l2_f16_with(f16_backend(), x, y)
L2_F16.get().call(x, y)
}
fn l2_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) {
assert_batch_output_layout(x.len(), batch.len(), dimension, output.len());
// Selecting the backend reads several runtime feature flags, which
// costs as much as a dimension-8 distance, so select it once per batch.
// The scalar backend converts the query to f32 once, instead of once
// per vector, and gets its own loop so the scalar kernel inlines.
// Interim: f16 still selects through `half_backend`, not `Dispatch`;
// it moves onto `Dispatch` batch candidates later in #10083, which
// must keep the convert-the-query-once step.
let backend = f16_backend();
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
if backend == HalfBackend::Neon {
return l2_f16_batch_neon(x, batch, dimension, output);
}
if backend == HalfBackend::Scalar {
let x: Vec<f32> = x.iter().map(|v| v.to_f32()).collect();
for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
*distance = l2_scalar_mixed::<f32, Self, f32, 16>(&x, y);
}
} else {
for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
*distance = l2_f16_with(backend, x, y);
}
L2_F16_BATCH.get().call(x, batch, dimension, output);
}
}
lance_core::dispatch! {
static L2_F16: Dispatch<PairKernel<f16>> = &[
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
half_c::L2_F16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::L2_F16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::L2_F16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_F16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_F16_LSX,
L2_F16_SCALAR,
];
}
lance_core::dispatch! {
/// Each batch candidate loops over its tier's `L2_F16` kernel. Selecting
/// once per batch matters: at dimension 8 a selection costs about as much
/// as a distance.
static L2_F16_BATCH: Dispatch<BatchKernel<f16>> = &[
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
half_c::L2_F16_BATCH_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::L2_F16_BATCH_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::L2_F16_BATCH_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_F16_BATCH_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_F16_BATCH_LSX,
L2_F16_BATCH_SCALAR,
];
}
lance_core::dispatch! {
static L2_BF16: Dispatch<PairKernel<bf16>> = &[
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
half_c::L2_BF16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::L2_BF16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::L2_BF16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_BF16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::L2_BF16_LSX,
L2_BF16_SCALAR,
];
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(L2_F16_SCALAR: PairKernel<f16>)]
fn l2_f16_scalar(x: &[f16], y: &[f16]) -> f32 {
l2_scalar::<f16, f32, 16>(x, y)
}
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(L2_F16_BATCH_SCALAR: BatchKernel<f16>)]
/// Converts the query to f32 once instead of once per vector, with the
/// same results as `l2_f16_scalar`.
fn l2_batch_f16_scalar(x: &[f16], batch: &[f16], dimension: usize, output: &mut [f32]) {
let x: Vec<f32> = x.iter().map(|v| v.to_f32()).collect();
for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
*distance = l2_scalar_mixed::<f32, f16, f32, 16>(&x, y);
}
}
}
/// Out of line so the loop gets registers of its own: inlined into
/// `l2_batch_into`, LLVM spilled the batch pointer to the stack, which put a
/// store-to-load round trip on every dimension-8 distance.
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
#[inline(never)]
fn l2_f16_batch_neon(x: &[f16], batch: &[f16], dimension: usize, output: &mut [f32]) {
for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) {
*distance = l2_f16_with(HalfBackend::Neon, x, y);
lance_core::target_kernel! {
#[target_features()]
#[candidate(L2_BF16_SCALAR: PairKernel<bf16>)]
fn l2_bf16_scalar(x: &[bf16], y: &[bf16]) -> f32 {
l2_scalar::<bf16, f32, 16>(x, y)
}
}
#[inline(always)]
fn l2_f16_with(backend: HalfBackend, x: &[f16], y: &[f16]) -> f32 {
match backend {
#[cfg(all(feature = "fp16kernels", target_arch = "aarch64"))]
HalfBackend::Neon => unsafe { kernel::l2_f16_neon(x.as_ptr(), y.as_ptr(), x.len() as u32) },
#[cfg(all(
feature = "fp16kernels",
kernel_support = "avx512_f16",
target_arch = "x86_64"
))]
HalfBackend::Avx512 => unsafe {
kernel::l2_f16_avx512(x.as_ptr(), y.as_ptr(), x.len() as u32)
},
#[cfg(all(feature = "fp16kernels", target_arch = "x86_64"))]
HalfBackend::Avx2 => unsafe { kernel::l2_f16_avx2(x.as_ptr(), y.as_ptr(), x.len() as u32) },
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lasx => unsafe { kernel::l2_f16_lasx(x.as_ptr(), y.as_ptr(), x.len() as u32) },
#[cfg(all(feature = "fp16kernels", target_arch = "loongarch64"))]
HalfBackend::Lsx => unsafe { kernel::l2_f16_lsx(x.as_ptr(), y.as_ptr(), x.len() as u32) },
// SimdSupport::AvxFma and SimdSupport::Avx retain their scalar
// route; this fallback only extends the tiers the C kernel already
// served to Avx512FP16 after checking F16C and FMA.
_ => l2_scalar::<f16, f32, 16>(x, y),
/// The `l2_f16` and `l2_bf16` functions in f16.c and bf16.c. build.rs compiles
/// each file once per SIMD level, suffixing the symbols with the level.
#[cfg(kernel_support = "half")]
mod half_c {
use half::{bf16, f16};
use crate::distance::{BatchKernel, PairKernel};
mod ffi {
use half::{bf16, f16};
unsafe extern "C" {
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
pub fn l2_f16_avx512(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn l2_f16_avx2(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn l2_f16_neon(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_f16_lasx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_f16_lsx(ptr1: *const f16, ptr2: *const f16, len: u32) -> f32;
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
pub fn l2_bf16_avx512(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "x86_64")]
pub fn l2_bf16_avx2(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "aarch64")]
pub fn l2_bf16_neon(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_bf16_lasx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn l2_bf16_lsx(ptr1: *const bf16, ptr2: *const bf16, len: u32) -> f32;
}
}
half_c_kernels! {
fn (x: &[f16], y: &[f16]) -> f32 => (x.as_ptr(), y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
L2_F16_AVX512: PairKernel<f16> = l2_f16_avx512("avx512fp16");
#[cfg(target_arch = "x86_64")]
L2_F16_AVX2: PairKernel<f16> = l2_f16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
L2_F16_NEON: PairKernel<f16> = l2_f16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
L2_F16_LASX: PairKernel<f16> = l2_f16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
L2_F16_LSX: PairKernel<f16> = l2_f16_lsx("lsx");
}
/// Declares a batch candidate that loops over a pair kernel with the same
/// features.
macro_rules! batch_kernels {
($(
$(#[$attr:meta])*
$candidate:ident = $name:ident($pair:ident; $($feature:literal),*);
)*) => {
$(
$(#[$attr])*
lance_core::target_kernel! {
#[target_features($($feature),*)]
#[candidate(pub(super) $candidate: BatchKernel<f16>)]
/// Out of line even where the dispatch resolves at compile
/// time, so the loop gets registers of its own: inlined into
/// `l2_batch_into` on aarch64, LLVM spilled the batch pointer
/// to the stack, a store-to-load round trip on every
/// dimension-8 distance. Other tiers share it for uniformity.
#[inline(never)]
fn $name(x: &[f16], batch: &[f16], dimension: usize, output: &mut [f32]) {
// A pointer walk rather than `zip` with `chunks_exact`:
// the zip kept a row index, its successor and the row
// count live across the C call, more values than x86
// has callee-saved registers, so two of them were
// reloaded from the stack on every row.
let batch = &batch[..output.len() * dimension];
let mut y = batch.as_ptr();
for distance in output.iter_mut() {
// SAFETY: `batch` holds `output.len()` vectors of
// `dimension` elements.
unsafe {
*distance = $pair(x, std::slice::from_raw_parts(y, dimension));
y = y.add(dimension);
}
}
}
}
)*
};
}
batch_kernels! {
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
L2_F16_BATCH_AVX512 = l2_batch_f16_avx512(l2_f16_avx512; "avx512fp16");
#[cfg(target_arch = "x86_64")]
L2_F16_BATCH_AVX2 = l2_batch_f16_avx2(l2_f16_avx2; "avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
L2_F16_BATCH_NEON = l2_batch_f16_neon(l2_f16_neon; "neon", "fp16");
#[cfg(target_arch = "loongarch64")]
L2_F16_BATCH_LASX = l2_batch_f16_lasx(l2_f16_lasx; "lasx");
#[cfg(target_arch = "loongarch64")]
L2_F16_BATCH_LSX = l2_batch_f16_lsx(l2_f16_lsx; "lsx");
}
half_c_kernels! {
fn (x: &[bf16], y: &[bf16]) -> f32 => (x.as_ptr(), y.as_ptr(), x.len().min(y.len()) as u32);
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
L2_BF16_AVX512: PairKernel<bf16> = l2_bf16_avx512("avx512fp16", "avx512bf16");
#[cfg(target_arch = "x86_64")]
L2_BF16_AVX2: PairKernel<bf16> = l2_bf16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
L2_BF16_NEON: PairKernel<bf16> = l2_bf16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
L2_BF16_LASX: PairKernel<bf16> = l2_bf16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
L2_BF16_LSX: PairKernel<bf16> = l2_bf16_lsx("lsx");
}
// Each candidate must require what build.rs compiled its object for.
#[cfg(target_arch = "x86_64")]
const _: () = {
use crate::distance::half_c_objects::{HASWELL, same_features};
assert!(same_features(L2_F16_AVX2.features(), HASWELL));
assert!(same_features(L2_F16_BATCH_AVX2.features(), HASWELL));
assert!(same_features(L2_BF16_AVX2.features(), HASWELL));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_f16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_F16, same_features};
assert!(same_features(L2_F16_AVX512.features(), SAPPHIRE_RAPIDS_F16));
assert!(same_features(
L2_F16_BATCH_AVX512.features(),
SAPPHIRE_RAPIDS_F16
));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_bf16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_BF16, same_features};
assert!(same_features(
L2_BF16_AVX512.features(),
SAPPHIRE_RAPIDS_BF16
));
};
#[cfg(target_arch = "aarch64")]
const _: () = {
use crate::distance::half_c_objects::{ARMV8_2_FP16, same_features};
assert!(same_features(L2_F16_NEON.features(), ARMV8_2_FP16));
assert!(same_features(L2_F16_BATCH_NEON.features(), ARMV8_2_FP16));
assert!(same_features(L2_BF16_NEON.features(), ARMV8_2_FP16));
};
#[cfg(target_arch = "loongarch64")]
const _: () = {
use crate::distance::half_c_objects::{LASX, LSX, same_features};
assert!(same_features(L2_F16_LASX.features(), LASX));
assert!(same_features(L2_F16_BATCH_LASX.features(), LASX));
assert!(same_features(L2_BF16_LASX.features(), LASX));
assert!(same_features(L2_F16_LSX.features(), LSX));
assert!(same_features(L2_F16_BATCH_LSX.features(), LSX));
assert!(same_features(L2_BF16_LSX.features(), LSX));
};
}
impl L2 for f32 {
@@ -1154,6 +1250,7 @@ mod tests {
use arrow_array::{cast::AsArray, types::Float32Type};
use approx::assert_relative_eq;
use lance_core::utils::cpu::Dispatch;
use num_traits::ToPrimitive;
use proptest::prelude::*;
@@ -1500,6 +1597,130 @@ mod tests {
}
}
/// Every host-supported half-precision kernel must agree with an f64
/// reference.
fn check_half_l2_kernels<T: ToPrimitive + Copy>(
dispatch: &Dispatch<PairKernel<T>>,
x: &[T],
y: &[T],
) -> std::result::Result<(), TestCaseError> {
let x_f64 = x.iter().map(|v| v.to_f64().unwrap()).collect::<Vec<_>>();
let y_f64 = y.iter().map(|v| v.to_f64().unwrap()).collect::<Vec<_>>();
let want = l2_distance_reference(&x_f64, &y_f64) as f32;
for candidate in dispatch.candidates() {
let Some(kernel) = candidate.kernel() else {
continue;
};
let got = kernel.call(x, y);
prop_assert!(
approx::relative_eq!(got, want, max_relative = 1e-6),
"{} at dim {}: {got} != {want}",
candidate.name(),
x.len()
);
// The C candidates' safe wrappers clamp the length to the shorter
// slice, so extra elements on either side must not change the
// result. The scalar candidate is the one without features.
if candidate.features().is_empty() {
continue;
}
for (x, y) in [(x, &[y, x].concat()[..]), (&[x, y].concat()[..], y)] {
let clamped = kernel.call(x, y);
prop_assert!(
clamped.to_bits() == got.to_bits(),
"{} at lengths {} and {}: {clamped} != {got}",
candidate.name(),
x.len(),
y.len()
);
}
}
Ok(())
}
/// Also checks that each f16 batch kernel matches its tier's pair kernel
/// bit for bit.
#[rstest::rstest]
fn test_l2_f16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_f16, dimension_shard(shard), |x, y| {
check_half_l2_kernels(&L2_F16, &x, &y)?;
let batch = [&y[..], &x[..]].concat();
for (pair, batch_candidate) in L2_F16.candidates().iter().zip(L2_F16_BATCH.candidates())
{
let (Some(pair_kernel), Some(batch_kernel)) =
(pair.kernel(), batch_candidate.kernel())
else {
continue;
};
let mut got = [f32::NAN; 2];
batch_kernel.call(&x, &batch, x.len(), &mut got);
let want = [pair_kernel.call(&x, &y), pair_kernel.call(&x, &x)];
prop_assert!(
got.map(f32::to_bits) == want.map(f32::to_bits),
"{} at dim {}: {got:?} != {want:?}",
batch_candidate.name(),
x.len()
);
}
Ok(())
});
}
#[test]
fn test_l2_half_kernels_short_lengths() {
run_vector_pair_proptest(arbitrary_f16, 0..4, |x, y| {
check_half_l2_kernels(&L2_F16, &x, &y)
});
run_vector_pair_proptest(arbitrary_bf16, 0..4, |x, y| {
check_half_l2_kernels(&L2_BF16, &x, &y)
});
}
/// With `fp16kernels` on a target build.rs supports, the C kernels must
/// be candidates; otherwise every candidate test passes on scalar alone.
#[cfg(all(
feature = "fp16kernels",
not(target_os = "windows"),
any(
target_arch = "x86_64",
target_arch = "aarch64",
target_arch = "loongarch64"
)
))]
#[test]
fn test_half_c_kernels_are_candidates() {
assert!(L2_F16.candidates().len() > 1);
assert!(L2_F16_BATCH.candidates().len() > 1);
assert!(L2_BF16.candidates().len() > 1);
}
#[test]
fn test_l2_f16_batch_candidates_mirror_pair_candidates() {
let pairs = L2_F16.candidates();
let batches = L2_F16_BATCH.candidates();
assert_eq!(pairs.len(), batches.len());
for (pair, batch) in pairs.iter().zip(batches) {
assert_eq!(
pair.features(),
batch.features(),
"{} vs {}",
pair.name(),
batch.name()
);
}
}
#[rstest::rstest]
fn test_l2_bf16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_pair_proptest(arbitrary_bf16, dimension_shard(shard), |x, y| {
check_half_l2_kernels(&L2_BF16, &x, &y)
});
}
// Test L2 distance over different types.
// * L2 is valid over the entire range of f16.
// * L2 is valid over f32 and bf16 in the range of +-1e12.
+198 -117
View File
@@ -8,39 +8,14 @@ use arrow_array::{FixedSizeListArray, Float32Array};
use half::{bf16, f16};
use super::arrow::{Norm, Operation, dispatch};
use lance_core::utils::cpu::SIMD_SUPPORT;
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 {
@@ -48,110 +23,174 @@ impl Normalize for u8 {
}
}
/// L2 norm of one vector.
type NormKernel<T> = unsafe fn(&[T]) -> f32;
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;
NORM_L2_F16.get().call(vector)
}
}
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),
}
NORM_L2_BF16.get().call(vector)
}
}
/// L2 norm of one vector.
type NormKernel<T> = unsafe fn(&[T]) -> f32;
lance_core::dispatch! {
static NORM_L2_F16: Dispatch<NormKernel<f16>> = &[
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
half_c::NORM_L2_F16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::NORM_L2_F16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::NORM_L2_F16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::NORM_L2_F16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::NORM_L2_F16_LSX,
NORM_L2_F16_SCALAR,
];
}
lance_core::dispatch! {
static NORM_L2_BF16: Dispatch<NormKernel<bf16>> = &[
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
half_c::NORM_L2_BF16_AVX512,
#[cfg(all(kernel_support = "half", target_arch = "x86_64"))]
half_c::NORM_L2_BF16_AVX2,
#[cfg(all(kernel_support = "half", target_arch = "aarch64"))]
half_c::NORM_L2_BF16_NEON,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::NORM_L2_BF16_LASX,
#[cfg(all(kernel_support = "half", target_arch = "loongarch64"))]
half_c::NORM_L2_BF16_LSX,
NORM_L2_BF16_SCALAR,
];
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(NORM_L2_F16_SCALAR: NormKernel<f16>)]
fn norm_l2_f16_scalar(vector: &[f16]) -> f32 {
norm_l2_impl::<f16, f32, 32>(vector)
}
}
lance_core::target_kernel! {
#[target_features()]
#[candidate(NORM_L2_BF16_SCALAR: NormKernel<bf16>)]
fn norm_l2_bf16_scalar(vector: &[bf16]) -> f32 {
norm_l2_impl::<bf16, f32, 32>(vector)
}
}
/// The `norm_l2_f16` and `norm_l2_bf16` functions in f16.c and bf16.c.
/// build.rs compiles each file once per SIMD level, suffixing the symbols with
/// the level.
#[cfg(kernel_support = "half")]
mod half_c {
use half::{bf16, f16};
use super::NormKernel;
mod ffi {
use half::{bf16, f16};
unsafe extern "C" {
#[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 = "aarch64")]
pub fn norm_l2_f16_neon(ptr: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn norm_l2_f16_lasx(ptr: *const f16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn norm_l2_f16_lsx(ptr: *const f16, 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 = "aarch64")]
pub fn norm_l2_bf16_neon(ptr: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn norm_l2_bf16_lasx(ptr: *const bf16, len: u32) -> f32;
#[cfg(target_arch = "loongarch64")]
pub fn norm_l2_bf16_lsx(ptr: *const bf16, len: u32) -> f32;
}
}
half_c_kernels! {
fn (vector: &[f16]) -> f32 => (vector.as_ptr(), vector.len() as u32);
#[cfg(all(kernel_support = "avx512_f16", target_arch = "x86_64"))]
NORM_L2_F16_AVX512: NormKernel<f16> = norm_l2_f16_avx512("avx512fp16");
#[cfg(target_arch = "x86_64")]
NORM_L2_F16_AVX2: NormKernel<f16> = norm_l2_f16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
NORM_L2_F16_NEON: NormKernel<f16> = norm_l2_f16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
NORM_L2_F16_LASX: NormKernel<f16> = norm_l2_f16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
NORM_L2_F16_LSX: NormKernel<f16> = norm_l2_f16_lsx("lsx");
}
half_c_kernels! {
fn (vector: &[bf16]) -> f32 => (vector.as_ptr(), vector.len() as u32);
#[cfg(all(kernel_support = "avx512_bf16", target_arch = "x86_64"))]
NORM_L2_BF16_AVX512: NormKernel<bf16> = norm_l2_bf16_avx512("avx512fp16", "avx512bf16");
#[cfg(target_arch = "x86_64")]
NORM_L2_BF16_AVX2: NormKernel<bf16> = norm_l2_bf16_avx2("avx2", "fma", "f16c", "bmi1", "bmi2");
#[cfg(target_arch = "aarch64")]
NORM_L2_BF16_NEON: NormKernel<bf16> = norm_l2_bf16_neon("neon", "fp16");
#[cfg(target_arch = "loongarch64")]
NORM_L2_BF16_LASX: NormKernel<bf16> = norm_l2_bf16_lasx("lasx");
#[cfg(target_arch = "loongarch64")]
NORM_L2_BF16_LSX: NormKernel<bf16> = norm_l2_bf16_lsx("lsx");
}
// Each candidate must require what build.rs compiled its object for.
#[cfg(target_arch = "x86_64")]
const _: () = {
use crate::distance::half_c_objects::{HASWELL, same_features};
assert!(same_features(NORM_L2_F16_AVX2.features(), HASWELL));
assert!(same_features(NORM_L2_BF16_AVX2.features(), HASWELL));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_f16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_F16, same_features};
assert!(same_features(
NORM_L2_F16_AVX512.features(),
SAPPHIRE_RAPIDS_F16
));
};
#[cfg(all(target_arch = "x86_64", kernel_support = "avx512_bf16"))]
const _: () = {
use crate::distance::half_c_objects::{SAPPHIRE_RAPIDS_BF16, same_features};
assert!(same_features(
NORM_L2_BF16_AVX512.features(),
SAPPHIRE_RAPIDS_BF16
));
};
#[cfg(target_arch = "aarch64")]
const _: () = {
use crate::distance::half_c_objects::{ARMV8_2_FP16, same_features};
assert!(same_features(NORM_L2_F16_NEON.features(), ARMV8_2_FP16));
assert!(same_features(NORM_L2_BF16_NEON.features(), ARMV8_2_FP16));
};
#[cfg(target_arch = "loongarch64")]
const _: () = {
use crate::distance::half_c_objects::{LASX, LSX, same_features};
assert!(same_features(NORM_L2_F16_LASX.features(), LASX));
assert!(same_features(NORM_L2_BF16_LASX.features(), LASX));
assert!(same_features(NORM_L2_F16_LSX.features(), LSX));
assert!(same_features(NORM_L2_BF16_LSX.features(), LSX));
};
}
impl Normalize for f32 {
#[inline]
@@ -495,6 +534,7 @@ mod tests {
use arrow_array::{Float16Array, Float64Array, UInt8Array};
use arrow_schema::{ArrowError, DataType};
use lance_arrow::FixedSizeListArrayExt;
use lance_core::utils::cpu::Dispatch;
use num_traits::ToPrimitive;
use proptest::prelude::*;
use std::sync::Arc;
@@ -589,6 +629,47 @@ mod tests {
});
}
/// Every host-supported half-precision kernel must agree with an f64
/// reference.
fn check_half_norm_l2_kernels<T: ToPrimitive>(
dispatch: &Dispatch<NormKernel<T>>,
data: &[T],
) -> std::result::Result<(), TestCaseError> {
let data_f64 = data.iter().map(|v| v.to_f64().unwrap()).collect::<Vec<_>>();
let want = norm_l2_reference(&data_f64);
for candidate in dispatch.candidates() {
let Some(kernel) = candidate.kernel() else {
continue;
};
let got = kernel.call(data);
prop_assert!(
approx::relative_eq!(got, want, max_relative = 1e-6),
"{} at dim {}: {got} != {want}",
candidate.name(),
data.len()
);
}
Ok(())
}
#[rstest::rstest]
fn test_norm_l2_f16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_proptest(arbitrary_f16, dimension_shard(shard), |data| {
check_half_norm_l2_kernels(&NORM_L2_F16, &data)
});
}
#[rstest::rstest]
fn test_norm_l2_bf16_kernels_match_reference(
#[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize,
) {
run_vector_proptest(arbitrary_bf16, dimension_shard(shard), |data| {
check_half_norm_l2_kernels(&NORM_L2_BF16, &data)
});
}
proptest::proptest! {
#[test]
fn test_l2_norm_f16(data in prop::collection::vec(arbitrary_f16(), 4..4048)) {
+2 -3
View File
@@ -591,9 +591,8 @@ impl Mul for f32x8 {
/// `target_feature = "avx512f"`, but no project CI configuration enables
/// `+avx512f` globally (and one of the avx512 arms still contained `todo!()`),
/// so the variant was dead code. Removed in the runtime-SIMD-dispatch
/// retrofit; per-tier dispatch happens in the kernel functions in
/// `crate::distance::*` via `match *SIMD_SUPPORT` + per-tier
/// `#[target_feature(enable = "...")]` inner functions.
/// retrofit; `crate::distance::*` now selects a per-tier `target_kernel!`
/// candidate through a `Dispatch` list.
#[allow(non_camel_case_types)]
#[cfg(target_arch = "x86_64")]
#[derive(Clone, Copy)]
+2 -3
View File
@@ -444,9 +444,8 @@ impl Mul for f64x4 {
/// x86_64. Originally there was a sibling AVX-512 variant gated on
/// `target_feature = "avx512f"`, but no project CI configuration enables
/// `+avx512f` globally, so the variant was dead code. Removed in the
/// runtime-SIMD-dispatch retrofit; per-tier dispatch happens in the kernel
/// functions in `crate::distance::*` via `match *SIMD_SUPPORT` + per-tier
/// `#[target_feature(enable = "...")]` inner functions.
/// runtime-SIMD-dispatch retrofit; `crate::distance::*` now selects a
/// per-tier `target_kernel!` candidate through a `Dispatch` list.
#[allow(non_camel_case_types)]
#[cfg(target_arch = "x86_64")]
#[derive(Clone, Copy)]