diff --git a/.bumpversion.toml b/.bumpversion.toml index 076443831..e4989d1eb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.11" +current_version = "0.42.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2fabb4a6a..e208ac7cd 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -130,7 +130,8 @@ jobs: run: pytest --doctest-modules python/lancedb linux: name: "Linux: python-3.${{ matrix.python-minor-version }}" - timeout-minutes: 30 + # A cold native build plus both test passes can exhaust 30 minutes. + timeout-minutes: 60 strategy: matrix: python-minor-version: ["10", "13"] diff --git a/Cargo.lock b/Cargo.lock index f6e027f50..16e076cd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1441,6 +1441,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.5" @@ -2783,7 +2792,7 @@ dependencies = [ "arrow", "arrow-buffer", "base64 0.23.1", - "blake2", + "blake2 0.10.6", "blake3", "chrono", "chrono-tz 0.10.4", @@ -3246,6 +3255,15 @@ dependencies = [ "dirs-sys 0.5.0", ] +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys 0.5.0", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -3491,6 +3509,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -3621,6 +3650,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "file_url" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec49f140842acf886ff3e4fd47600ffdbb5f1b1ba70f6775880e688837a0b174" +dependencies = [ + "itertools 0.15.0", + "percent-encoding", + "thiserror 2.0.18", + "typed-path", + "url", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -3665,6 +3707,15 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + [[package]] name = "float8" version = "0.7.0" @@ -3796,6 +3847,15 @@ version = "1.20260804.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "fs4" version = "0.13.1" @@ -3814,8 +3874,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4372,6 +4432,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "halfbrown" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "hash32" version = "0.3.1" @@ -4477,7 +4547,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ - "dirs", + "dirs 6.0.0", "futures", "http", "indicatif", @@ -5292,8 +5362,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5368,8 +5438,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5391,7 +5461,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.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5405,7 +5475,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.17#471352665e1e5ce453af154efd53b4d65c931127" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5414,8 +5484,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrayref", "crunchy", @@ -5425,8 +5495,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5464,8 +5534,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5496,8 +5566,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5522,8 +5592,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5540,8 +5610,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "proc-macro2", "quote", @@ -5550,8 +5620,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5584,8 +5654,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-arith", "arrow-array", @@ -5616,8 +5686,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5648,8 +5718,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5673,7 +5743,7 @@ dependencies = [ "datafusion-functions-nested", "datafusion-physical-expr", "datafusion-physical-plan", - "dirs", + "dirs 6.0.0", "fst", "futures", "half", @@ -5721,8 +5791,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5745,8 +5815,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5791,8 +5861,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "byteorder", "ethnum", @@ -5809,7 +5879,7 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.17" +version = "15.0.0-beta.18" dependencies = [ "approx", "argminmax 0.7.1", @@ -5831,8 +5901,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "async-trait", @@ -5846,8 +5916,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arc-swap", "arrow", @@ -5901,8 +5971,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-buffer", @@ -5916,8 +5986,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow", "arrow-array", @@ -5958,8 +6028,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "arrow-array", "arrow-schema", @@ -5972,8 +6042,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.17#471352665e1e5ce453af154efd53b4d65c931127" +version = "15.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.18#079fd77683a7acf056b0912f6ecda938e39ee120" dependencies = [ "frostem", "icu_segmenter", @@ -5986,7 +6056,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -6097,7 +6167,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "anyhow", "arrow-array", @@ -6140,7 +6210,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -6165,7 +6235,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" dependencies = [ "arc-swap", "arrow", @@ -6188,6 +6258,7 @@ dependencies = [ "pyo3", "pyo3-async-runtimes", "pyo3-build-config", + "rattler_conda_types", "reqwest 0.13.5", "serde", "serde_json", @@ -6196,6 +6267,29 @@ dependencies = [ "uuid", ] +[[package]] +name = "lazy-regex" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" +dependencies = [ + "lazy-regex-proc_macros", + "once_cell", + "regex", +] + +[[package]] +name = "lazy-regex-proc_macros" +version = "3.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 3.0.3", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -6959,6 +7053,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom 8.0.0", +] + [[package]] name = "now" version = "0.1.3" @@ -8663,6 +8766,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" +[[package]] +name = "purl" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60ebe4262ae91ddd28c8721111a0a6e9e58860e211fc92116c4bb85c98fd96ad" +dependencies = [ + "hex", + "percent-encoding", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pyo3" version = "0.29.3" @@ -9064,6 +9179,99 @@ dependencies = [ "rustversion", ] +[[package]] +name = "rattler_conda_types" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fda631350e17df9bc789082d6b6c0fbde38e65cba580593ee3317fb6730644f2" +dependencies = [ + "ahash", + "core-foundation 0.10.1", + "dirs 7.0.0", + "fancy-regex 0.19.2", + "file_url", + "fs-err", + "glob", + "hex", + "indexmap 2.14.0", + "itertools 0.15.0", + "jiff", + "lazy-regex", + "memmap2 0.9.10", + "nom 8.0.0", + "nom-language", + "purl", + "rattler_conda_version", + "rattler_digest", + "rattler_macros", + "rattler_redaction", + "regex", + "serde", + "serde-untagged", + "serde_json", + "serde_repr", + "serde_with", + "serde_yaml", + "simd-json", + "smallvec", + "strum", + "tempfile", + "thiserror 2.0.18", + "tracing", + "typed-path", + "url", +] + +[[package]] +name = "rattler_conda_version" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee922b54cd30c198e93c542096a0d671cefba1a97600768b2ec4af3c11c44f55" +dependencies = [ + "itertools 0.15.0", + "nom 8.0.0", + "serde", + "smallvec", + "thiserror 2.0.18", +] + +[[package]] +name = "rattler_digest" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bda554663860e074665f838a4d9a89fbf671f576eaf288d29525114b345adc9" +dependencies = [ + "blake2 0.11.0", + "digest 0.11.3", + "hex", + "md-5", + "serde", + "serde-untagged", + "serde_bytes", + "serde_with", + "sha2 0.11.0", + "url", +] + +[[package]] +name = "rattler_macros" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a42690ed14c8b9d610aafc0f2eb715b85c05f3d3a2a307896e4f8d820aaa284f" +dependencies = [ + "quote", + "syn 3.0.3", +] + +[[package]] +name = "rattler_redaction" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b5ee47d0375643b037205a4fe238b90c518ca3fc83c7c240d82c49ba87d61c" +dependencies = [ + "url", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -10058,6 +10266,28 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -10188,6 +10418,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -10302,7 +10545,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32824fab5e16e6c4d86dc1ba84489390419a39f97699852b66480bb87d297ed8" dependencies = [ "bstr", - "dirs", + "dirs 6.0.0", "os_str_bytes", ] @@ -10367,6 +10610,20 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd-json" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebe141eb4a23ecc4d5de93fa5b139ac65dc07c38037a2fe9a8fb7c9d36bd832" +dependencies = [ + "halfbrown", + "ref-cast", + "serde", + "serde_json", + "simdutf8", + "value-trait", +] + [[package]] name = "simd_cesu8" version = "1.1.1" @@ -10406,6 +10663,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "smartstring" @@ -11535,6 +11795,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.0" @@ -11721,6 +11987,18 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-trait" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b" +dependencies = [ + "float-cmp", + "halfbrown", + "itoa", + "ryu", +] + [[package]] name = "vcpkg" version = "0.2.15" @@ -12708,7 +12986,7 @@ dependencies = [ "colored", "const-str", "ctor", - "dirs", + "dirs 6.0.0", "futures", "git-version", "humantime", diff --git a/Cargo.toml b/Cargo.toml index dd358fb76..4edc28264 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,20 +20,20 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.17", default-features = false, "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.18", default-features = false, "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index c06b4f230..ca77b251c 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.11 + 0.42.0-beta.12 ``` diff --git a/docs/src/python/python.md b/docs/src/python/python.md index eccaae6ce..8de5b5517 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -42,6 +42,18 @@ table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same patterns apply to `list_namespaces()`. Other resource listings use `page_limit`. +For existence checks, use `db.table_exists(["events"])` or `"events" in db`. +These look up the table directly and work even when the database has more than +100 tables. For a table in a namespace, include the namespace segments: + +```python +exists = db.table_exists(["analytics", "events"]) +``` + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. Checking `name in db.list_tables().tables` only +searches the first page and can miss an existing table. + Resource listings (`list_storage_integrations`, `list_secrets`, `list_views`, `list_jobs`, `list_functions`, and `list_materialized_views`) return lazy iterators. Use `list(db.list_views())` to collect synchronous results, or `[name async for name in db.list_views()]` with @@ -1055,6 +1067,11 @@ the page list does not consume the iterator. `page.page_token` is the token for the next request; drain cached results before using it to resume in a new listing. The same behavior applies to namespaces. +Use `await db.table_exists(["events"])` to check for a table in the root +namespace, or `await db.table_exists(["analytics", "events"])` for a table in +a namespace. Checking membership in an awaited listing's `.tables` attribute +only searches one page. + ::: lancedb.listing.AsyncTableListing ::: lancedb.listing.AsyncNamespaceListing diff --git a/docs/web/basics/jobs.mdx b/docs/web/basics/jobs.mdx index 5336d1dfd..47285f5d0 100644 --- a/docs/web/basics/jobs.mdx +++ b/docs/web/basics/jobs.mdx @@ -42,9 +42,21 @@ print(job.status()) result. If it failed or was cancelled, inspect the failure details and any results it committed before stopping. -In Python, `job.status()` reports the current state and `job.wait()` waits for -completion, raising if the job fails or is cancelled. Both `Job.wait()` and -`AsyncJob.wait()` retry transient connection and read errors with capped +In Python, `job.status()` returns the current state: + +| State | Meaning | +| --- | --- | +| `running` | The operation is in progress. | +| `finished` | The operation completed successfully. | +| `failed` | The operation failed. | +| `cancelled` | The operation was cancelled. | + +`job.status()` checks the current state without waiting for completion. +It returns `failed` or `cancelled` for unsuccessful jobs. + +Use `job.wait()` to wait for completion and raise if the job fails or is +cancelled. Both `Job.wait()` and `AsyncJob.wait()` retry transient connection +and read errors with capped exponential backoff within the caller's timeout. Without a timeout, retries continue indefinitely. diff --git a/docs/web/maintenance/compaction.mdx b/docs/web/maintenance/compaction.mdx index 9c8765293..e7b79f768 100644 --- a/docs/web/maintenance/compaction.mdx +++ b/docs/web/maintenance/compaction.mdx @@ -13,8 +13,8 @@ import { PyStorageCompactionTuning, PyStorageRebuildVectorIndex, RsStorageCompac Every write commits a new table version, and versions accumulate: small files from frequent appends, superseded files from updates and deletes, and rows added since an index was built. In the embedded library, `optimize()` addresses all -three; a deployment handles them in the background and does not support -`optimize()`. +three. Enterprise handles maintenance in the background and also supports +on-demand compaction through `optimize()` on compatible servers. Run optimization as regular table maintenance, particularly after many small writes or a large ingest. diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 2a05b4a0f..23fdbdb4a 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -201,7 +201,7 @@ setting. See [Limits](/basics/limits#schema). ```python Python icon="python" tbl = db.open_table("documents") -db.table_names() +names = list(db.list_tables()) ``` ```typescript TypeScript icon="square-js" @@ -230,6 +230,27 @@ listing. A missing table raises `ValueError` on a local directory and A listing returns one page of names at a time, so check every page. TypeScript has no `tableExists`. +{/* +Draft for the table-existence lookup release (#4974). Once released, replace +the two table-existence paragraphs above with this guidance: + +For Python local, remote, and namespace connections, use +`db.table_exists(["documents"])` or `"documents" in db` to check whether a root +table exists. For an async connection, use +`await db.table_exists(["documents"])`. Include namespace segments before the +table name, for example `["analytics", "documents"]`. These checks return +`False` when the table is missing and propagate other errors, including +permission errors. They look up the table directly, regardless of the number +of tables in the database. + +When migrating from `name in db.table_names()`, use `name in db` or +`db.table_exists([name])`. To collect every table name, use +`list(db.list_tables())`, or `[name async for name in db.list_tables()]` on an +async connection. The `.tables` attribute holds only one page (100 names by +default), so membership checks against it can miss existing tables. TypeScript +has no `tableExists`. +*/} + ## Rename and clone tables {#rename-clone} diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 903be2b77..792b434a1 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 610c095b9..df709fb4f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.11 + 0.42.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.17 + 15.0.0-beta.18 2.18.12 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 91d808647..22cfe6ecc 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index 1a9011b34..283a32fdc 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index 00b2918d6..5fd392245 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index f94f27216..ec5103284 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index e0eefa2e9..1d45a2ed2 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index f0891fbed..d17a3b4e7 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 04b65ba86..a7c4a74b6 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index e5e0effab..0e3a4a626 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a03e1a794..b0d99fb60 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.11", + "version": "0.42.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 03c77d8c4..1d5d65055 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" publish = false edition.workspace = true description = "Python bindings for LanceDB" @@ -39,6 +39,7 @@ pyo3-async-runtimes = { version = "0.29", features = [ "tokio-runtime", ] } reqwest.workspace = true +rattler_conda_types = { version = "0.58.3", default-features = false } pin-project.workspace = true futures.workspace = true serde.workspace = true diff --git a/python/pyproject.toml b/python/pyproject.toml index 5ba1d4bbf..6940dce4f 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b17", + "pylance==15.0.0b18", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 4029525e9..521cc46bb 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1310,3 +1310,4 @@ class AuthzObject: def __repr__(self) -> str: ... def validate_function_retry_policy(json: str) -> None: ... +def _validate_conda_requirement(requirement: str) -> None: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 73c8305ff..84ebb41a1 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -322,6 +322,9 @@ class DBConnection(EnforceOverrides): def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in + ``list_tables().tables``, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -331,12 +334,20 @@ class DBConnection(EnforceOverrides): Returns ------- bool - True if the table exists, False otherwise. + True if the table exists, False if it is not found. + Other errors, including permission errors, are propagated. Raises ------ NotImplementedError - If the connection type does not support namespace operations. + If the connection type does not support table existence checks. + + Examples + -------- + >>> def check_table(conn): + ... root_exists = conn.table_exists(["events"]) + ... nested_exists = conn.table_exists(["analytics", "events"]) + ... return root_exists, nested_exists """ raise NotImplementedError( "Namespace operations are not supported for this connection type" @@ -348,7 +359,11 @@ class DBConnection(EnforceOverrides): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + ``list_tables().tables`` contains only the first page (100 names by + default). Use ``list(list_tables())`` to collect all names, or + ``table_exists([name])`` to check whether a particular table exists. Parameters ---------- @@ -934,7 +949,7 @@ class DBConnection(EnforceOverrides): def __contains__(self, name: str) -> bool: """Return whether the root namespace contains the named table.""" - return name in self._all_table_names() + return self.table_exists([name]) def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -1849,6 +1864,10 @@ class LanceDBConnection(DBConnection): ) -> DescribeNamespaceResponse: return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path)) + @override + def table_exists(self, table_id: List[str]) -> bool: + return LOOP.run(self._conn.table_exists(table_id)) + @override def list_tables( self, @@ -1856,7 +1875,11 @@ class LanceDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1894,7 +1917,9 @@ class LanceDBConnection(DBConnection): """Get the names of all tables in the database. The names are sorted. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -1914,7 +1939,8 @@ class LanceDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -2878,6 +2904,9 @@ class AsyncConnection(object): async def table_exists(self, table_id: List[str]) -> bool: """Check if a table exists. + Use this method instead of checking membership in an awaited listing's + ``tables`` attribute, which contains only one page of table names. + Parameters ---------- table_id: List[str] @@ -2903,7 +2932,11 @@ class AsyncConnection(object): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> AsyncTableListing: - """List tables in this database, one page at a time. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -2942,7 +2975,9 @@ class AsyncConnection(object): """List all tables in this database, in sorted order .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -2966,7 +3001,8 @@ class AsyncConnection(object): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 6d0c2ff52..a5c741cd8 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -44,6 +44,7 @@ from typing import ( ) import pyarrow as pa +from packaging.requirements import Requirement from pydantic import ( AfterValidator, BaseModel, @@ -57,6 +58,7 @@ from pydantic import ( from .schema import blob as _blob_field from .schema import is_blob_v2_field as _is_blob_v2_field from ._blob_reader import BlobReader +from ._lancedb import _validate_conda_requirement from .secrets import EnvVarSecret _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) @@ -493,6 +495,35 @@ class PythonRuntimeSpec(_RemoteValue): object.__setattr__(self, "gpu_class", None) return self + @property + def digest(self) -> str: + """SHA-256 identity of the declared runtime, before building an image. + + Covers Python version, environment sources, environment variables, and + GPU settings. Package and system-package order is ignored; conda channel + order is preserved. Compare with ``runtime_digest`` on + [FunctionVersion][lancedb.functions.FunctionVersion]. + This identifies build inputs, not the resolved contents of unpinned + dependencies or the deployment's default base image. + """ + if self.kind not in {"python", "python_v2"}: + raise ValueError(f"cannot digest unknown runtime kind {self.kind!r}") + value = self._known_dict() + if not value.get("env"): + value.pop("env", None) + environment = value["environment"] + for field in ("packages", "system_packages"): + if field in environment: + environment[field] = sorted(environment[field]) + encoded = json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return f"sha256:{hashlib.sha256(encoded).hexdigest()}" + class FunctionImage(_RemoteValue): """A complete OCI Function image identified by its exact manifest digest.""" @@ -534,8 +565,17 @@ class FunctionVersion(_RemoteValue): of the built ``image``. Compare it with ``definition.registration_request.artifact.digest`` to check whether a local [FunctionDefinition][lancedb.functions.FunctionDefinition] has the same source. + It does not cover dependencies, environment variables, Python version, or + GPU settings. Equal source digests alone do not mean a version can be reused. It is ``None`` when the server does not provide a source digest. + ``runtime_digest`` identifies the declared environment inputs. Compare it + with ``definition.registration_request.runtime.digest`` to check whether + the local runtime matches. It is ``None`` for images built before runtime + identity was exposed. A missing digest cannot establish a match. Reusing a + version also requires matching the source and all other registration inputs, + including signature, Secret bindings, models, and execution controls. + ``gpu_class`` is the operator-defined GPU pool fixed into this Function version, or ``None`` when registration used the deployment default. @@ -552,6 +592,7 @@ class FunctionVersion(_RemoteValue): version: _ObjectVersion image: FunctionImage source_digest: Optional[str] = None + runtime_digest: Optional[str] = None signature: FunctionSignature secret_bindings: tuple[SecretBinding, ...] = () created_at_millis: int @@ -873,17 +914,47 @@ class RefreshColumnResult(_RemoteValue): LanceDB Embedded jobs produce this value in process. LanceDB Enterprise decodes the same value from the durable server-job terminal payload. + + Row counters describe logical rows planned for this refresh, not user-code + calls or retry attempts. ``rows_assigned`` counts rows successfully written + with an output value, ``rows_failed`` counts rows whose computation failed, + and ``rows_remaining`` counts planned rows neither assigned nor terminally + skipped. Rows already counted in ``rows_failed`` are covered and are not + counted again in ``rows_remaining``. + + For example, a refresh over 2,001 logical rows that assigns 1,891 values and + fails 110 rows reports ``rows_assigned=1,891``, ``rows_failed=110``, and + ``rows_remaining=0``. Its failure-rate denominator is those 2,001 logical + rows, not the number of execution attempts. """ rows_assigned: _UInt64 + """Number of logical rows successfully assigned an output value by this + refresh. Each row counts once, regardless of retry attempts, and failed rows + are not included.""" + rows_failed: _UInt64 + """Number of logical rows whose computation failed. Rows deferred because + an input was not ready are not failures.""" + rows_remaining: _UInt64 + """Number of planned logical rows neither assigned nor terminally skipped. + Rows already counted in ``rows_failed`` are covered and are not counted + again.""" + source_version: _UInt64 + """Exact table version the refresh read.""" + published_version: Optional[_UInt64] = None + """Table version made visible by the refresh, when one was published.""" @property def rows_filled(self) -> int: - """Deprecated compatibility alias for :attr:`rows_assigned`.""" + """Deprecated compatibility alias for :attr:`rows_assigned`. + + The value is the same successful logical-row count; it does not count + execution attempts. + """ return self.rows_assigned @property @@ -1266,6 +1337,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: raise TypeError(f"unsupported Function annotation: {annotation!r}") +def _validate_callable(function: Any) -> None: + if hasattr(function, "__wrapped__"): + raise TypeError( + "decorated wrappers are not supported; put caching inside the function " + "body or use a class Function with a cache in __init__" + ) + if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function): + raise TypeError( + "generator Functions are not supported; return a value instead of " + "yielding, or return a list for multiple values" + ) + if inspect.isfunction(function) and function.__name__ == "": + raise TypeError("lambda Functions are not supported; use a named def instead") + + def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]: parameters = tuple(inspect.signature(function).parameters.values()) for parameter in parameters: @@ -1276,7 +1362,11 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete ): raise TypeError("Function callables require named, non-variadic parameters") if parameter.default is not inspect.Parameter.empty: - raise TypeError("Function callable defaults are not supported") + raise TypeError( + f"Function callable defaults are not supported: {parameter.name!r}; " + "move configuration parameters to a class Function's __init__ " + "and pass them as binding-time initialization values" + ) return parameters @@ -1671,6 +1761,29 @@ def _packaged_by_source(value: Any) -> bool: return True +def _validate_package_requirements(kind: str, packages: Sequence[str]) -> None: + for index, package in enumerate(packages): + field = f"{kind}[{index}]" + if not isinstance(package, str): + raise TypeError(f"{field} must be a string, got {package!r}") + if not package or package != package.strip(): + raise ValueError( + f"{field} requirement {package!r} must be non-empty and trimmed" + ) + try: + if kind == "conda": + _validate_conda_requirement(package) + else: + candidate = package + if re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://", package): + candidate = f"dependency @ {package}" + Requirement(candidate) + except ValueError as error: + raise ValueError( + f"invalid {field} requirement {package!r}: {error}" + ) from error + + def _requirement_name(requirement: str) -> str: requirement = requirement.rpartition("::")[2] match = _REQUIREMENT_NAME.match(requirement.strip()) @@ -2146,6 +2259,7 @@ def _class_member(cls: type, name: str) -> Any: def _class_call(cls: type) -> Callable[..., Any]: call = _class_member(cls, "__call__") + _validate_callable(call) if not inspect.isfunction(call) or inspect.iscoroutinefunction(call): raise TypeError("a class Function must define a synchronous __call__ method") close = _class_member(cls, "close") @@ -2202,16 +2316,15 @@ class FunctionDefinition: if not is_class and ( not inspect.isfunction(function) or inspect.iscoroutinefunction(function) ): + _validate_callable(function) raise TypeError( "@function requires a synchronous Python function or a class" ) - function_name = name or function.__name__ - if not _FUNCTION_NAME.fullmatch(function_name): - raise ValueError(f"invalid Function name: {function_name!r}") if pip and conda: raise ValueError("a Function environment is pip or conda, not both") if conda_channels and not conda: raise ValueError("conda_channels requires conda packages") + _validate_package_requirements("conda" if conda else "pip", conda or pip) gpu_marker = _normalize_gpu_marker(gpu) if gpu_class is not None: _validate_gpu_class_name(gpu_class) @@ -2268,6 +2381,11 @@ class FunctionDefinition: "model Functions reserve environment variables " f"{reserved!r}; the worker sets them for the private snapshot" ) + if not is_class: + _validate_callable(function) + function_name = name or function.__name__ + if not _FUNCTION_NAME.fullmatch(function_name): + raise ValueError(f"invalid Function name: {function_name!r}") if is_class: if "<" in function.__qualname__ or "." in function.__qualname__: raise ValueError( @@ -2499,6 +2617,14 @@ def function( reuses them. An instance serves many batches of one binding, so state is shared across them, but not across instances or workers. + Functions and ``__call__`` methods must return a value. Generators, + including async generators, are not supported; return a list to produce + multiple values for a list output. Lambdas and decorated wrappers such as + ``functools.lru_cache`` are not supported. Use a named ``def`` and keep + caches inside the body or in a class instance initialized by ``__init__``. + Callable input parameters cannot have defaults; move configurable values + to class initialization fields instead. + **Initialization.** The annotated parameters of a class's ``__init__`` are the Function's initialization fields. Their values belong to each binding, not to the Function: ``function(text=col("body"), model="small")`` @@ -2565,9 +2691,12 @@ def function( non-nullable. Required for batch annotations. When omitted, the output is inferred from the return annotation. pip : sequence of str, optional - Pip requirements for the remote environment. + Pip requirements for the remote environment. Syntax is validated at + decoration time, including extras and environment markers. Named direct + references and bare package or git URLs are supported. conda : sequence of str, optional - Conda packages for the remote environment, instead of ``pip``. + Conda packages for the remote environment, instead of ``pip``. MatchSpec + syntax is validated at decoration time, including channels and builds. conda_channels : sequence of str, optional Conda channels in priority order; requires ``conda``. apt : sequence of str, optional diff --git a/python/python/lancedb/listing.py b/python/python/lancedb/listing.py index 8abc9d85b..59aba1431 100644 --- a/python/python/lancedb/listing.py +++ b/python/python/lancedb/listing.py @@ -175,6 +175,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]): class AsyncTableListing(_AsyncPagedNameListing): """Awaitable table iterator; awaiting loads one page. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``await db.table_exists([name])`` for existence checks. + For example:: page = await db.list_tables(limit=20) @@ -229,6 +232,10 @@ class _PagedNameListing(Iterator[str]): class TableListing(_PagedNameListing): """Table iterator retaining the current page as a list. + Iteration fetches all pages. The ``tables`` attribute contains only the + current page, so use ``db.table_exists([name])`` or ``name in db`` for + existence checks. Use ``list(db.list_tables())`` to collect all names. + For example:: page = db.list_tables(limit=20) @@ -239,6 +246,7 @@ class TableListing(_PagedNameListing): @property def tables(self) -> list[str]: + """A copy of the table names in the most recently fetched page.""" return self._inner.tables diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3356b363c..aa9025641 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -579,12 +579,15 @@ class LanceNamespaceDBConnection(DBConnection): If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1015,6 +1018,8 @@ class LanceNamespaceDBConnection(DBConnection): bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return LOOP.run(self._inner.table_exists(table_id)) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1030,7 +1035,11 @@ class LanceNamespaceDBConnection(DBConnection): limit: Optional[int] = None, ) -> TableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -1227,12 +1236,15 @@ class AsyncLanceNamespaceDBConnection: If limit is None, return all table names; zero returns an empty list. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. """ import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) @@ -1614,6 +1626,8 @@ class AsyncLanceNamespaceDBConnection: bool True if the table exists, False otherwise. """ + if self._route_pushdown_to_rust: + return await self._inner.table_exists(table_id) request = TableExistsRequest(id=table_id) try: self._namespace_client.table_exists(request) @@ -1628,7 +1642,11 @@ class AsyncLanceNamespaceDBConnection: limit: Optional[int] = None, ) -> AsyncTableListing: """ - List all tables in this database with pagination support. + Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index ebceba16b..21ad37b36 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -430,7 +430,11 @@ class RemoteDBConnection(DBConnection): page_token: Optional[str] = None, limit: Optional[int] = None, ) -> TableListing: - """List a page of tables in this database. + """Iterate over all tables in this database, fetching pages as needed. + + The ``tables`` attribute contains only the current page (100 names by + default). Iterate over the listing to visit all pages, or use + ``table_exists([name])`` to check for a particular table. Parameters ---------- @@ -468,7 +472,9 @@ class RemoteDBConnection(DBConnection): """List the names of all tables in the database. .. deprecated:: - Use :meth:`list_tables` instead, which provides proper pagination support. + Iterate over :meth:`list_tables` to get all names, or use + :meth:`table_exists` to check for a particular table. The listing's + ``tables`` attribute contains only one page. Parameters ---------- @@ -488,7 +494,8 @@ class RemoteDBConnection(DBConnection): import warnings warnings.warn( - "table_names() is deprecated, use list_tables() instead", + "table_names() is deprecated, iterate list_tables() for all names " + "or use table_exists([name]) to check existence", DeprecationWarning, stacklevel=2, ) diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 64bf928c0..80a98bc18 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -282,9 +282,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path): assert empty.page_token is None -def test_db_contains_stops_after_matching_table_page( - tmp_db: lancedb.DBConnection, monkeypatch -): +def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch): calls = [] pages = { None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"), @@ -297,18 +295,44 @@ def test_db_contains_stops_after_matching_table_page( monkeypatch.setattr(tmp_db, "list_tables", list_tables) - assert "table_1" in tmp_db - assert calls == [None] - - calls.clear() - assert "table_2" in tmp_db - assert calls == [None, "next"] - - calls.clear() assert len(tmp_db) == 3 assert calls == [None, "next"] +@pytest.mark.asyncio +@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]]) +async def test_local_table_exists_without_listing( + tmp_path, monkeypatch, namespace_path +): + db = lancedb.connect(tmp_path) + for depth in range(1, len(namespace_path) + 1): + db.create_namespace(namespace_path[:depth]) + db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path) + if not namespace_path: + for idx in range(100): + (tmp_path / f"a{idx:03}.lance").mkdir() + assert "events" not in db.list_tables().tables + adb = await lancedb.connect_async(tmp_path) + + def fail_listing(*args, **kwargs): + raise AssertionError("Existence checks must not list tables") + + monkeypatch.setattr(db, "list_tables", fail_listing) + monkeypatch.setattr(adb, "list_tables", fail_listing) + table_id = namespace_path + ["events"] + assert db.table_exists(table_id) is True + assert await adb.table_exists(table_id) is True + assert db.table_exists(namespace_path + ["missing"]) is False + assert await adb.table_exists(namespace_path + ["missing"]) is False + assert ("events" in db) is (not namespace_path) + assert "missing" not in db + assert table_id == namespace_path + ["events"] + + db.drop_table("events", namespace_path=namespace_path) + assert db.table_exists(table_id) is False + assert await adb.table_exists(table_id) is False + + @pytest.mark.asyncio async def test_table_names_async(tmp_path): db = lancedb.connect(tmp_path) diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index f8e225183..867672fe9 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -34,7 +34,7 @@ FIXTURES = ( def fixture(name: str) -> str: - return (FIXTURES / name).read_text() + return (FIXTURES / name).read_text(encoding="utf-8") def job_result(name: str) -> dict: @@ -148,6 +148,38 @@ def test_function_version_identity_is_immutable_and_exact(): FunctionVersion(**{**value, "version": invalid}) +@pytest.mark.parametrize( + "case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"] +) +def test_runtime_digests_match_server_golden_values(case): + runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"])) + assert runtime.digest == case["digest"] + assert ( + PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest + == runtime.digest + ) + + +def test_unknown_runtime_digest_fails_closed(): + runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}') + with pytest.raises(ValueError, match="cannot digest unknown runtime kind"): + runtime.digest + + +@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"]) +def test_function_version_preserves_runtime_digest(runtime_digest): + value = job_result("remote_function_job.json") + legacy = FunctionVersion.from_json(json.dumps(value)) + assert legacy.runtime_digest is None + assert "runtime_digest" not in json.loads(legacy.to_canonical_json()) + value["runtime_digest"] = runtime_digest + version = FunctionVersion.from_json(json.dumps(value)) + assert version.runtime_digest == runtime_digest + assert FunctionVersion.from_json(version.to_canonical_json()) == version + with pytest.raises((TypeError, ValueError)): + version.runtime_digest = "sha256:changed" + + @pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"]) def test_function_version_preserves_source_digest(source_digest): value = job_result("remote_function_job.json") diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 2cc731892..d99a7aa21 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1891,6 +1891,29 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): return value +def test_default_function_runtime_matches_server_identity(): + definition = function(python_version="3.12")(analyze_caption.__wrapped__) + runtime = definition.registration_request.runtime + assert runtime.env == {} + cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8")) + expected = next( + case["digest"] for case in cases if case["name"] == "empty-environment" + ) + assert runtime.digest == expected + + +def test_environment_changes_do_not_change_source_identity(): + definition = function( + pip=["openai==3.46.0"], + env={"MODE": "test"}, + python_version="3.12", + )(analyze_caption.__wrapped__) + previous = analyze_caption.registration_request + changed = definition.registration_request + assert previous.artifact.digest == changed.artifact.digest + assert previous.runtime.digest != changed.runtime.digest + + def test_local_function_catalog_operations_are_not_supported(tmp_path): db = lancedb.connect(tmp_path) message = "Function catalog operations are not supported by this database" @@ -1950,6 +1973,7 @@ async def test_async_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -1977,6 +2001,7 @@ def test_sync_catalog_path_preserves_execution_controls(): (FIXTURES / "remote_function_version.canonical.json").read_text() ) definition.update( + runtime_digest=normalize_score.registration_request.runtime.digest, batch_size=12, row_timeout_seconds=8.0, result_stability="input_and_context", @@ -2090,6 +2115,9 @@ def _mock_remote_function_catalog(): )["image"], "signature": body["signature"], "source_digest": body["artifact"]["digest"], + "runtime_digest": PythonRuntimeSpec.from_json( + json.dumps(body["runtime"]) + ).digest, "secret_bindings": body.get("secret_bindings", []), "created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z } diff --git a/python/python/tests/test_function_packaging.py b/python/python/tests/test_function_packaging.py index 83dfdaeb3..440adc4da 100644 --- a/python/python/tests/test_function_packaging.py +++ b/python/python/tests/test_function_packaging.py @@ -20,7 +20,7 @@ import pyarrow as pa import pytest from lancedb import col -from lancedb.functions import FunctionDefinition, FunctionVersion, function +from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf FIXTURES = ( Path(__file__).parents[3] @@ -127,6 +127,108 @@ def test_function_without_initialization_keeps_its_wire_form(): assert request["artifact"]["kind"] == "python_callable" +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_schemas", [False, True]) +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize( + ("declaration", "statement"), + [ + ("def", "yield value"), + ("def", "yield from [value]"), + ("async def", "yield value"), + ], +) +def test_generator_functions_are_rejected_at_decoration( + helper_package, decorator, explicit_schemas, class_function, declaration, statement +): + signature = ( + "__call__(self, value: int)" if class_function else "generates(value: int)" + ) + source = f"{declaration} {signature} -> int:\n {statement}\n" + if class_function: + source = "class generates:\n" + textwrap.indent(source, " ") + module = helper_package("fx_generator", {"__init__.py": source}) + options = ( + { + "input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]), + "output_schema": pa.int64(), + } + if explicit_schemas + else {} + ) + with pytest.raises(TypeError) as error: + decorator(**options)(module.generates) + message = str(error.value) + assert "generator Functions are not supported" in message + assert "return a value" in message + assert "return a list" in message + + +@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning") +@pytest.mark.parametrize("decorator", [function, udf]) +@pytest.mark.parametrize("explicit_name", [False, True]) +def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name): + options = {"name": "double"} if explicit_name else {} + with pytest.raises(TypeError, match="lambda.*use a named def"): + decorator(**options)(lambda value: value * 2) + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"]) +def test_cached_functions_explain_where_to_keep_caches( + helper_package, class_function, cache_decorator +): + signature = "__call__(self, value: int)" if class_function else "cached(value: int)" + source = ( + f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n" + ) + if class_function: + source = "class cached:\n" + textwrap.indent(source, " ") + module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source}) + with pytest.raises(TypeError) as error: + function(module.cached) + message = str(error.value) + assert "decorated wrappers are not supported" in message + assert "inside the function body" in message + assert "class Function with a cache in __init__" in message + + +@pytest.mark.parametrize("class_function", [False, True]) +@pytest.mark.parametrize("keyword_only", [False, True]) +def test_callable_defaults_explain_class_initialization( + helper_package, class_function, keyword_only +): + parameters = "value: float, " + ("*, " if keyword_only else "") + parameters += "threshold: float = 0.5" + signature = ( + f"__call__(self, {parameters})" + if class_function + else f"thresholded({parameters})" + ) + source = f"def {signature} -> bool:\n return value >= threshold\n" + if class_function: + source = "class thresholded:\n" + textwrap.indent(source, " ") + module = helper_package("fx_defaults", {"__init__.py": source}) + with pytest.raises(TypeError) as error: + function(module.thresholded) + message = str(error.value) + assert "defaults are not supported: 'threshold'" in message + assert "class Function's __init__" in message + assert "binding-time initialization values" in message + + +def test_function_can_return_a_list_from_a_generator_expression(): + @function + def many(value: int) -> list[int]: + return list(item * 2 for item in range(value)) + + namespace = {} + exec(compile(artifact(many), "user_function.py", "exec"), namespace) + assert namespace["many"](3) == [0, 2, 4] + assert many.registration_request.signature.output.arrow_type == "list" + + @pytest.mark.parametrize("kind", ["function", "class"]) @pytest.mark.parametrize( ("global_value", "value_type"), diff --git a/python/python/tests/test_function_requirements.py b/python/python/tests/test_function_requirements.py new file mode 100644 index 000000000..6f94d1313 --- /dev/null +++ b/python/python/tests/test_function_requirements.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import pytest + +from lancedb import function, udf +from lancedb.functions import FunctionDefinition + + +def identity(value: int) -> int: + return value + + +@pytest.mark.parametrize( + "package", + [ + "torch>=2.0,,<3", + "torch>=", + "torch=>2.0", + "torch[", + "torch; python_version >=", + "", + " torch", + "torch ", + ], +) +def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch): + def unexpected_packaging(*args, **kwargs): + pytest.fail("invalid requirements must fail before packaging the function") + + monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging) + with pytest.raises(ValueError) as error: + function(pip=["numpy", package])(identity) + assert "pip[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize( + "package", + [ + "numpy>=1,,<3", + "numpy>=", + "numpy[version=]", + "numpy[unknown_field=value]", + "", + " numpy", + "numpy ", + ], +) +def test_invalid_conda_requirement_names_entry(package): + with pytest.raises(ValueError) as error: + function(conda=["scipy", package])(identity) + assert "conda[1]" in str(error.value) + assert repr(package) in str(error.value) + + +@pytest.mark.parametrize("kind", ["pip", "conda"]) +@pytest.mark.parametrize("package", [None, 42, ["numpy"]]) +def test_requirement_must_be_a_string(kind, package): + with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"): + function(**{kind: ["numpy", package]})(identity) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "torch>=2.0,<3", + 'requests[security,socks]>=2; python_version >= "3.10"', + "numpy (>=1.26, <3)", + "six @ https://example.com/six-1.16.0.tar.gz", + "six @ git+https://github.com/benjaminp/six.git@main", + "https://example.com/six-1.16.0.tar.gz", + "git+https://github.com/benjaminp/six.git@main", + "git+ssh://git@github.com/benjaminp/six.git@main", + ], +) +def test_supported_pip_requirements_are_preserved(package): + definition = function(pip=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +@pytest.mark.parametrize( + "package", + [ + "numpy", + "numpy=1.26", + "numpy>=1.26,<3", + "numpy=1.26=py310_0", + "numpy 1.26 py310_0", + "conda-forge::numpy>=1.26", + "conda-forge/linux-64::numpy>=1.26", + "numpy[version='>=1.26,<3',build='py310*']", + ], +) +def test_supported_conda_requirements_are_preserved(package): + definition = function(conda=[package])(identity) + assert definition.registration_request.runtime.environment.packages == (package,) + + +def test_requirements_still_sort_and_deduplicate(): + definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity) + assert definition.registration_request.runtime.environment.packages == ( + "numpy", + "torch>=2", + ) + + +def test_deprecated_udf_alias_validates_requirements(): + with pytest.warns(DeprecationWarning, match="use lancedb.function"): + with pytest.raises(ValueError, match=r"pip\[0\]"): + udf(pip=["torch>=2.0,,<3"])(identity) + + +def test_direct_function_definition_validates_requirements(): + with pytest.raises(ValueError, match=r"pip\[0\]"): + FunctionDefinition( + identity, + name=None, + input_schema=None, + output_schema=None, + pip=("torch>=2.0,,<3",), + env={}, + python_version=None, + ) diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 5eb9c02bd..9bce1059d 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -34,6 +34,27 @@ PUSHDOWN_DATA = pa.table( ) +@pytest.mark.asyncio +@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]]) +async def test_custom_namespace_table_exists_uses_namespace_api(table_id): + class ExistenceNamespace(LanceNamespace): + def namespace_id(self): + return "existence-test" + + def table_exists(self, request): + if request.id == ["missing"]: + raise TableNotFoundError("Table not found") + + def describe_table(self, request): + raise AssertionError("Custom existence checks must not open tables") + + namespace = ExistenceNamespace() + db = LanceNamespaceDBConnection(namespace) + adb = lancedb.AsyncLanceNamespaceDBConnection(namespace) + assert db.table_exists(table_id) is (table_id != ["missing"]) + assert await adb.table_exists(table_id) is (table_id != ["missing"]) + + class TestNamespaceCreateTableOptions: @pytest.mark.parametrize("version", ["legacy", "stable"]) @pytest.mark.parametrize("empty", [False, True]) @@ -411,8 +432,16 @@ class TestNamespaceConnection: assert "test_ns" in db.list_namespaces().namespaces schema = pa.schema([pa.field("id", pa.int64())]) + db.create_table("root_table", schema=schema) + assert db.table_exists(["root_table"]) is True + assert "root_table" in db + assert db.table_exists(["missing"]) is False + assert "missing" not in db table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"]) assert table.namespace == ["test_ns"] + assert db.table_exists(["test_ns", "test_table"]) is True + assert db.table_exists(["test_ns", "missing"]) is False + assert "test_table" not in db assert "test_table" in db.table_names(namespace_path=["test_ns"]) assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables @@ -420,7 +449,10 @@ class TestNamespaceConnection: assert opened.namespace == ["test_ns"] db.drop_table("test_table", namespace_path=["test_ns"]) + assert db.table_exists(["test_ns", "test_table"]) is False assert db.list_tables(namespace_path=["test_ns"]).tables == [] + db.drop_table("root_table") + assert "root_table" not in db db.drop_namespace(["test_ns"]) assert "test_ns" not in db.list_namespaces().namespaces @@ -942,12 +974,18 @@ class TestAsyncNamespaceConnection: assert "test_ns" in (await db.list_namespaces()).namespaces schema = pa.schema([pa.field("id", pa.int64())]) + await db.create_table("root_table", schema=schema) + assert await db.table_exists(["root_table"]) is True + assert await db.table_exists(["missing"]) is False table = await db.create_table( "test_table", schema=schema, namespace_path=["test_ns"] ) assert table._namespace_path == ["test_ns"] assert table._namespace_client is None assert table._route_pushdown_to_rust is True + assert await db.table_exists(["test_ns", "test_table"]) is True + assert await db.table_exists(["test_ns", "missing"]) is False + assert await db.table_exists(["test_table"]) is False assert "test_table" in await db.table_names(namespace_path=["test_ns"]) assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables @@ -955,7 +993,10 @@ class TestAsyncNamespaceConnection: assert opened._namespace_path == ["test_ns"] await db.drop_table("test_table", namespace_path=["test_ns"]) + assert await db.table_exists(["test_ns", "test_table"]) is False assert (await db.list_tables(namespace_path=["test_ns"])).tables == [] + await db.drop_table("root_table") + assert await db.table_exists(["root_table"]) is False await db.drop_namespace(["test_ns"]) assert "test_ns" not in (await db.list_namespaces()).namespaces diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 407596d26..b0098aca3 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -22,6 +22,7 @@ import time from urllib.parse import parse_qs, urlparse from unittest.mock import MagicMock, patch import uuid +import warnings from packaging.version import Version from lance_namespace.errors import TableNotFoundError @@ -461,6 +462,31 @@ def test_remote_table_exists_rechecks_cached_table(): assert requests == ["/v1/table/ns$table/describe/"] * 2 +@pytest.mark.parametrize("status", [200, 404, 403]) +def test_remote_membership_uses_direct_lookup(status): + requests = [] + + def handler(request): + requests.append(request.path) + assert request.command == "POST" + assert request.path == "/v1/table/t129/describe/" + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}" if status == 200 else b"lookup failed") + + with mock_lancedb_connection(handler) as db: + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + if status in (200, 404): + assert ("t129" in db) is (status == 200) + else: + with pytest.raises(HttpError) as exc_info: + "t129" in db + assert exc_info.value.status_code == status + assert requests == ["/v1/table/t129/describe/"] + + def paginated_table_listing_handler(request): url = urlparse(request.path) assert url.path in { @@ -6278,6 +6304,8 @@ def test_remote_function_registration_transports_max_concurrency(): def registered(value: float) -> float: return value + definition["runtime_digest"] = registered.registration_request.runtime.digest + class RegistrationServer(flight.FlightServerBase): def __init__(self): super().__init__("grpc://127.0.0.1:0") @@ -6296,6 +6324,7 @@ def test_remote_function_registration_transports_max_concurrency(): assert len(server.tickets) == 1 assert b'"max_concurrency":4' in server.tickets[0] assert version.max_concurrency == 4 + assert version.runtime_digest == registered.registration_request.runtime.digest @pytest.mark.asyncio diff --git a/python/python/tests/test_sync_api_parity.py b/python/python/tests/test_sync_api_parity.py index a12efd0c9..230fb45c6 100644 --- a/python/python/tests/test_sync_api_parity.py +++ b/python/python/tests/test_sync_api_parity.py @@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table): ] -def respond(request, body): - request.send_response(200) +def respond(request, body, status=200): + request.send_response(status) request.send_header("Content-Type", "application/json") request.end_headers() request.wfile.write(json.dumps(body).encode()) @@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute): @pytest.mark.parametrize("tables", [[], ["first", "last"]]) -def test_remote_len_and_contains_follow_pages(tables): +def test_remote_len_paginates_and_contains_looks_up_table(tables): requests = [] def handler(request): requests.append(request.path) - query = parse_qs(urlparse(request.path).query) + url = urlparse(request.path) + if request.command == "POST": + name = url.path.split("/")[3] + assert url.path == f"/v1/table/{name}/describe/" + respond(request, {}, status=200 if name in tables else 404) + return + assert request.command == "GET" + assert url.path == "/v1/namespace/$/table/list" + query = parse_qs(url.query) if tables and "page_token" not in query: respond(request, {"tables": [tables[0]], "page_token": "opaque-next"}) else: @@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables): with mock_lancedb_connection(handler) as db: assert len(db) == len(tables) - assert ("last" in db) == bool(tables) - assert "missing" not in db + assert len(requests) == (2 if tables else 1) requests.clear() - assert ("first" in db) == bool(tables) - assert len(requests) == 1 + for name in ("last", "missing", "first"): + assert (name in db) is (name in tables) + assert requests == [f"/v1/table/{name}/describe/"] + requests.clear() @pytest.mark.parametrize("namespace", [[], ["parent", "child"]]) diff --git a/python/src/lib.rs b/python/src/lib.rs index f78c4e7bb..b0698d5e0 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -150,6 +150,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(table::tokenize, m)?)?; m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?; m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?; + m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?; m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?; m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?; m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?; diff --git a/python/src/util.rs b/python/src/util.rs index a956066f1..44efa165a 100644 --- a/python/src/util.rs +++ b/python/src/util.rs @@ -9,6 +9,7 @@ use pyo3::{ exceptions::{PyRuntimeError, PyValueError}, pyfunction, }; +use rattler_conda_types::{MatchSpec, ParseStrictness}; /// A wrapper around a rust builder /// @@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> { .map_err(|e| PyValueError::new_err(e.to_string())) } +#[pyfunction(name = "_validate_conda_requirement")] +pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> { + MatchSpec::from_str(requirement, ParseStrictness::Lenient) + .map(|_| ()) + .map_err(|error| PyValueError::new_err(error.to_string())) +} + /// Parse field references with the same identifier syntax as Lance writes. #[pyfunction(name = "_parse_field_path")] pub fn parse_field_path(path: &str) -> PyResult> { diff --git a/python/uv.lock b/python/uv.lock index 01693079f..369d558d2 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -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.0b17" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b18" }, { 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.0b17" +version = "15.0.0b18" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, @@ -4312,12 +4312,12 @@ 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_il4JF/pylance-15.0.0b17-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:ee3c3d2baf1f0d788d706638873317740178a81988b71ffda47a2e71d1e15ff3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2hFd0a/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a5b576e35054d4866d823ebadc9d3c531165628feb29ca1528db15b9082675a" }, - { url = "https://pypi.fury.io/lance-format/-/ver_29zVw5/pylance-15.0.0b17-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:47c534032d2f251f396657e47efbc224ee2d1964495d7982a449e5e1cdcf3169" }, - { url = "https://pypi.fury.io/lance-format/-/ver_548nr/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:509db7d8be3eebb111b7d28aa486437424cb3663cfb7f502b71532fa37ba7155" }, - { url = "https://pypi.fury.io/lance-format/-/ver_gmpNu/pylance-15.0.0b17-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:bd2cc05c2d553d44c54570612e793136e3433fcba28e4d51a503cca8f45435ea" }, - { url = "https://pypi.fury.io/lance-format/-/ver_Otspk/pylance-15.0.0b17-cp310-abi3-win_amd64.whl", hash = "sha256:510c419e21a4daa4c18db4cc5048bd7dfc706924b23e13136306935f2e3e0c25" }, + { url = "https://pypi.fury.io/lance-format/-/ver_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" }, ] [[package]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 881130af3..7bd682612 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" 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.17", "tag" = "v15.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.18", "tag" = "v15.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { workspace = true } lance-arrow = { workspace = true } lance-namespace = { workspace = true } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index cde8b295a..b22a3b8d8 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.11" +version = "0.42.0-beta.12" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 3566fc938..e3d47948e 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -594,6 +594,8 @@ pub struct FunctionVersion { image: FunctionImage, #[serde(default, skip_serializing_if = "Option::is_none")] source_digest: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + runtime_digest: Option, signature: FunctionSignature, #[serde(default, skip_serializing_if = "Vec::is_empty")] secret_bindings: Vec, @@ -665,7 +667,9 @@ impl FunctionVersion { /// Digest of the registered source artifact, when provided by the server. /// /// Compare this with [`FunctionArtifactRequest::digest`] to identify matching - /// source, independently of the built image's manifest digest. + /// source, independently of the built image's manifest digest. It excludes + /// dependencies, environment variables, Python version, and GPU settings; + /// matching source alone does not establish that a version can be reused. /// /// ``` /// use lancedb::function::{FunctionArtifactRequest, FunctionVersion}; @@ -678,6 +682,15 @@ impl FunctionVersion { self.source_digest.as_deref() } + /// Digest of canonical runtime inputs, when provided by the server. + /// + /// Includes Python version, environment sources, variables, and GPU settings. + /// A missing digest cannot establish that a local runtime matches. Reusing a + /// version also requires matching its source and other registration inputs. + pub fn runtime_digest(&self) -> Option<&str> { + self.runtime_digest.as_deref() + } + /// Operator-defined GPU class declared at registration. pub fn gpu_class(&self) -> Option<&str> { self.gpu_class.as_deref() @@ -1329,6 +1342,30 @@ mod conda_environment_tests { mod tests { use super::*; + #[test] + fn function_version_preserves_runtime_digest() { + const VERSION: &str = include_str!( + "../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let mut document: Value = serde_json::from_str(VERSION).unwrap(); + let legacy = FunctionVersion::from_json(VERSION).unwrap(); + assert_eq!(legacy.runtime_digest(), None); + assert_eq!(legacy.to_canonical_json().unwrap(), VERSION.trim_end()); + for digest in [Value::Null, serde_json::json!("sha256:runtime-inputs")] { + document["runtime_digest"] = digest.clone(); + let version = FunctionVersion::from_json(&document.to_string()).unwrap(); + assert_eq!(version.runtime_digest(), digest.as_str()); + let encoded = version.to_canonical_json().unwrap(); + let encoded_value: Value = serde_json::from_str(&encoded).unwrap(); + if digest.is_null() { + assert!(encoded_value.get("runtime_digest").is_none()); + } else { + assert_eq!(encoded_value["runtime_digest"], digest); + } + assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version); + } + } + #[test] fn function_version_preserves_source_digest() { const VERSION: &str = include_str!( diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index efc2ba6a4..cfaf2a625 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -95,6 +95,7 @@ struct TestSqlService { exchanges: ReceivedExchanges, result_overrides: Arc>>, materialized_view_job_handle_supported: bool, + optimize_error: Option, /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, @@ -269,6 +270,7 @@ impl Default for TestSqlService { exchanges: Arc::new(std::sync::Mutex::new(Vec::new())), result_overrides: Arc::new(std::sync::Mutex::new(HashMap::new())), materialized_view_job_handle_supported: false, + optimize_error: None, exchange_drops: Arc::new(AtomicUsize::new(0)), result, large_result, @@ -439,6 +441,11 @@ impl FlightService for TestSqlService { .and_then(|command| command.unpack::().ok().flatten()); if let Some(command) = &initial { self.statements.lock().unwrap().push(command.query.clone()); + if command.query.starts_with("OPTIMIZE ") + && let Some(error) = &self.optimize_error + { + return Err(error.clone()); + } if command.query == "SELECT rejected" { return Err(Status::invalid_argument("invalid statement")); } @@ -3932,3 +3939,119 @@ async fn remote_compact_preserves_omissions_and_explicit_default_values() { shutdown.send(()).unwrap(); } } + +#[tokio::test] +async fn remote_optimize_parser_errors_are_clear_without_resubmission() { + use crate::table::optimize::CompactionOverrides; + for (code, message, unsupported) in [ + ( + tonic::Code::InvalidArgument, + "ParserError(\"Expected: end of statement, found: REWRITE at Line: 1\")", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: Expected: TABLE, found: events", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'io_buffer_size'", + true, + ), + ( + tonic::Code::InvalidArgument, + "ParserError: future grammar diagnostic", + true, + ), + ( + tonic::Code::InvalidArgument, + "Unknown OPTIMIZE option 'future_option'", + true, + ), + ( + tonic::Code::PermissionDenied, + "ParserError: future grammar diagnostic", + false, + ), + (tonic::Code::PermissionDenied, "permission denied", false), + (tonic::Code::NotFound, "table not found", false), + (tonic::Code::Unavailable, "transport error", false), + ( + tonic::Code::InvalidArgument, + "invalid table configuration", + false, + ), + ] { + let status = Status::new(code, message); + let service = TestSqlService { + adaptive: true, + optimize_error: Some(status), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = + client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ); + let error = table + .compact(CompactionOverrides::default()) + .await + .unwrap_err(); + assert_eq!( + matches!(error, Error::NotSupported { .. }), + unsupported, + "{error:?}" + ); + assert!(error.to_string().contains(message)); + assert!(error.to_string().contains("request_id")); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_optimize_branch_options_are_not_dropped() { + let service = TestSqlService { + adaptive: true, + optimize_error: Some(Status::invalid_argument( + "ParserError: Expected: ), found: , at Line: 1", + )), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql_client, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let client = client_with_handler(|_| -> http::Response { panic!("no REST fallback") }); + let table = RemoteTable::new_with_sql_client( + client, + "analytics".into(), + "events".into(), + vec![], + "events".into(), + Default::default(), + Some(sql_client), + ) + .with_branch(Some("exp".into())); + let error = table + .compact(crate::table::optimize::CompactionOverrides { + io_buffer_size: Some(0), + ..Default::default() + }) + .await + .unwrap_err(); + assert!(matches!(error, Error::NotSupported { .. })); + assert!(error.to_string().contains("compatible release")); + assert_eq!( + *statements.lock().unwrap(), + ["OPTIMIZE \"events\" REWRITE DATA WITH (branch = 'exp', io_buffer_size = 0)"] + ); + shutdown.send(()).unwrap(); +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3859cb830..48e5652ae 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3717,14 +3717,14 @@ impl BaseTable for RemoteTable { /// `OptimizeAction::All`, `::Prune`, and `::Index` remain unsupported /// remotely: there is no SQL statement yet for version pruning or index /// optimization. A branch-scoped table handle submits a - /// `WITH (branch = '')` clause; the statement does not itself - /// validate the branch exists, so a nonexistent branch surfaces as an - /// async job failure rather than an error from this call. Per-job + /// `WITH (branch = '')` clause; the server resolves and validates + /// the selected target. Per-job /// `target_rows_per_fragment`, `max_source_rows`, `io_buffer_size`, and /// `batch_size` are forwarded in the SQL `WITH` clause. Other non-default /// options are rejected before submission. Servers must support these - /// SQL options; an older server's error is returned without retrying - /// with the settings removed. + /// SQL options. Parser errors and unknown optimize option errors become + /// `NotSupported` with the server diagnostic after one SQL submission. + /// No settings are removed and the operation is never resubmitted. async fn optimize(&self, action: OptimizeAction) -> Result { self.check_mutable().await?; let OptimizeAction::Compact { @@ -3782,9 +3782,11 @@ impl BaseTable for RemoteTable { // value is built afterward. sql_client .submit_as_job(statement, self.namespace.clone(), || async { Ok(()) }) - .await? + .await + .map_err(optimize::map_optimize_error)? .wait() - .await?; + .await + .map_err(optimize::map_optimize_error)?; Ok(OptimizeStats { compaction: Some(lance::dataset::optimize::CompactionMetrics::default()), prune: None, diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 2a42dd3ab..6f4b7f7e8 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -35,10 +35,172 @@ pub(super) fn compaction_sql_options( Ok(result) } +const UNSUPPORTED_OPTIMIZE: &str = "Compaction on an Enterprise table requires support for OPTIMIZE REWRITE DATA. Upgrade LanceDB Enterprise to a compatible release."; +const UNSUPPORTED_OPTIONS: &str = "The requested compaction options are not supported by this version of LanceDB Enterprise. Upgrade to a compatible release; requested options will not be removed or retried."; + +/// The client generates the whole statement, so parser errors indicate a +/// client/server syntax mismatch. Match option errors without enumerating names. +fn unsupported_optimize_message(message: &str) -> Option<&'static str> { + let message = message.to_ascii_lowercase(); + if message.contains("parsererror") { + Some(UNSUPPORTED_OPTIMIZE) + } else if message.contains("unknown optimize option") { + Some(UNSUPPORTED_OPTIONS) + } else { + None + } +} + +/// Apply compatibility handling only to this constructed operation. +/// Preserve every unrelated SQL/authentication/transport error unchanged. +pub(super) fn map_optimize_error(error: Error) -> Error { + fn unsupported(error: &Error) -> Option<(&Error, &'static str)> { + match error { + Error::Sql { + message, grpc_code, .. + } if *grpc_code == tonic::Code::InvalidArgument as i32 => { + unsupported_optimize_message(message).map(|reason| (error, reason)) + } + Error::JobFailed { failure, .. } => failure + .source + .as_deref() + .and_then(|source| unsupported(source)), + _ => None, + } + } + if let Some((source, reason)) = unsupported(&error) { + let diagnostic = match &error { + Error::Sql { .. } => error.to_string(), + // JobFailure's Display omits its source, including the SQL request ID. + _ => format!("{error}; {source}"), + }; + Error::NotSupported { + message: format!("{reason} Server diagnostic: {diagnostic}"), + } + } else { + error + } +} + #[cfg(test)] mod tests { use super::*; + use crate::error::JobFailure; use crate::table::{CompactionOptions, CompactionOverrides}; + use std::sync::Arc; + + fn sql_error(code: tonic::Code, message: &str) -> Error { + Error::Sql { + message: message.into(), + request_id: "optimize-request".into(), + grpc_code: code as i32, + metadata: Default::default(), + } + } + + #[test] + fn direct_optimize_error_prints_its_diagnostic_once() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let Error::NotSupported { message } = + map_optimize_error(sql_error(tonic::Code::InvalidArgument, diagnostic)) + else { + panic!("known optimize syntax must be unsupported"); + }; + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn wrapped_optimize_error_keeps_job_context_and_sql_diagnostic() { + let diagnostic = "ParserError: Expected: end of statement, found: REWRITE"; + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + source: Some(Arc::new(sql_error( + tonic::Code::InvalidArgument, + diagnostic, + ))), + ..Default::default() + }), + }; + let Error::NotSupported { message } = map_optimize_error(error) else { + panic!("wrapped unsupported optimize SQL must be translated"); + }; + assert!(message.contains(UNSUPPORTED_OPTIMIZE)); + assert!(message.contains("optimize-job")); + assert!(message.contains("SQL planning failed (in planning)")); + assert_eq!(message.matches(diagnostic).count(), 1); + assert_eq!(message.matches("request_id=optimize-request").count(), 1); + } + + #[test] + fn unrelated_wrapped_sql_errors_pass_through_unchanged() { + let unsupported = "ParserError: Expected: end of statement, found: REWRITE"; + for (code, diagnostic) in [ + (tonic::Code::PermissionDenied, unsupported), + (tonic::Code::Unavailable, unsupported), + (tonic::Code::InvalidArgument, "invalid table configuration"), + ] { + let source = Arc::new(sql_error(code, diagnostic)); + let error = Error::JobFailed { + job_id: Some("optimize-job".into()), + failure: Box::new(JobFailure { + phase: Some("planning".into()), + message: Some("SQL planning failed".into()), + sql_job_id: Some("sql-job".into()), + retryable: Some(false), + source: Some(source.clone()), + ..Default::default() + }), + }; + let Error::JobFailed { job_id, failure } = map_optimize_error(error) else { + panic!("{code:?}: unrelated SQL failure must keep its classification"); + }; + assert_eq!(job_id.as_deref(), Some("optimize-job")); + assert_eq!(failure.phase.as_deref(), Some("planning")); + assert_eq!(failure.message.as_deref(), Some("SQL planning failed")); + assert_eq!(failure.sql_job_id.as_deref(), Some("sql-job")); + assert_eq!(failure.retryable, Some(false)); + assert!(Arc::ptr_eq(failure.source.as_ref().unwrap(), &source)); + } + } + + #[test] + fn generated_optimize_syntax_errors_indicate_incompatible_servers() { + for diagnostic in [ + "ParserError: Expected: end of statement, found: REWRITE", + "ParserError: Expected: identifier", + "SQL error: ParserError: future grammar diagnostic", + "parsererror: lowercase diagnostic", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIMIZE) + ); + } + for diagnostic in [ + "Unknown OPTIMIZE option 'io_buffer_size'", + "Error during planning: Unknown OPTIMIZE option 'future_option'", + ] { + assert_eq!( + unsupported_optimize_message(diagnostic), + Some(UNSUPPORTED_OPTIONS) + ); + } + for diagnostic in [ + "permission denied", + "table not found", + "connection reset", + "invalid table configuration", + ] { + assert!( + unsupported_optimize_message(diagnostic).is_none(), + "{diagnostic}" + ); + } + } #[test] fn omissions_and_explicit_default_target_are_distinct() { diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json new file mode 100644 index 000000000..7bf0c375c --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/runtime_identity.json @@ -0,0 +1,269 @@ +[ + { + "name": "pip", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "reordered-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy==2.2.0", + "openai==3.40.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:e2891a0af2567af2798c7de67a2f91b031088ef2a7015b501022892995eaca1c" + }, + { + "name": "changed-pin", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.46.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:43da49cfcf8ecd47becb5be20b9eff06c5267f9244c18e751b230c624f5ad12a" + }, + { + "name": "changed-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "prod", + "LABEL": "你好" + } + }, + "digest": "sha256:9b305e9188f4ddda5a0b72d2235c2c46ba50de9bf82c699f5060b02e4aa0820d" + }, + { + "name": "changed-python", + "runtime": { + "kind": "python", + "python_version": "3.11", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:8fa58561581414b02d0619e466e3720828d1820d8211b0e73c90ec4b0d3ecd0c" + }, + { + "name": "gpu", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true + }, + "digest": "sha256:3ea9354ff101038937b1f5a3b6639c4cc6dcb88ee975dcb8e1a5dee2500c283c" + }, + { + "name": "gpu-class", + "runtime": { + "kind": "python_v2", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + }, + "gpu": true, + "gpu_class": "a100" + }, + "digest": "sha256:253f0641ef029aed8337bbcb210f7769147d671747406f7ce4fa5dc40d5c5efc" + }, + { + "name": "conda", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "conda-forge", + "defaults" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:9246f88a6b1daceb3090c51930650ea967947142cdc70737c847a6bf72c85d30" + }, + { + "name": "reordered-channels", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "conda", + "packages": [ + "numpy=2.2.0", + "scipy=1.15.0" + ], + "channels": [ + "defaults", + "conda-forge" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:12ef13a6f5b8730a719288ab2406e7f6c13634b14dbef2390f0bbe62f847e18d" + }, + { + "name": "system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "zlib1g", + "ffmpeg" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "reordered-system-packages", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "openai==3.40.0", + "numpy==2.2.0" + ], + "system_packages": [ + "ffmpeg", + "zlib1g" + ] + }, + "env": { + "MODE": "test", + "LABEL": "你好" + } + }, + "digest": "sha256:129706ec54d8bf5fe36f89a9cf9131b37b2293028e03da7d686c77c3c483d958" + }, + { + "name": "empty-environment", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + } + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-env", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip" + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + }, + { + "name": "explicit-empty-fields", + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [], + "channels": [], + "modules": [], + "system_packages": [] + }, + "env": {} + }, + "digest": "sha256:a3d52daa7573e7fc6d052e0bf05b5189b9413ad8e136c10bc48f6dedc3add047" + } +] diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index 9650a3a1b..2705d7225 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "15.0.0-beta.17" +version = "15.0.0-beta.18" publish = false edition = { workspace = true } license = { workspace = true } @@ -66,6 +66,10 @@ harness = false name = "batch_distance" harness = false +[[bench]] +name = "hamming" +harness = false + [lints.rust] unsafe_op_in_unsafe_fn = "allow" unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage,coverage_nightly)"] } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index b706acd1f..ba5672984 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.17` -(commit `471352665e1e5ce453af154efd53b4d65c931127`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.18` +(commit `079fd77683a7acf056b0912f6ecda938e39ee120`), 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 diff --git a/rust/lancedb/vendor/lance-linalg/benches/hamming.rs b/rust/lancedb/vendor/lance-linalg/benches/hamming.rs new file mode 100644 index 000000000..9e1d7b652 --- /dev/null +++ b/rust/lancedb/vendor/lance-linalg/benches/hamming.rs @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::hint::black_box; + +use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; +use rand::Rng; + +use lance_linalg::distance::hamming::{ + BinaryHashValues, hamming_batch_u64, hamming_distance_batch_into, + pairwise_hamming_distance_binary_parallel, pairwise_hamming_distance_parallel, +}; + +#[cfg(target_os = "linux")] +use lance_testing::pprof::{Output, PProfProfiler}; + +const NUM_VECTORS: usize = 16 * 1024; +const NUM_TARGETS: usize = 10_000; +const NUM_HASHES: usize = 5_000; +const THRESHOLD: u32 = 10; + +fn bench_hamming_u8(c: &mut Criterion) { + let mut rng = rand::rng(); + let mut group = c.benchmark_group("hamming_u8_batch"); + group.throughput(Throughput::Elements(NUM_VECTORS as u64)); + for dimension in [16, 32, 64, 128, 256] { + let query: Vec = (0..dimension).map(|_| rng.random()).collect(); + let vectors: Vec = (0..dimension * NUM_VECTORS).map(|_| rng.random()).collect(); + let mut distances = vec![0.0; NUM_VECTORS]; + group.bench_function(BenchmarkId::from_parameter(dimension), |b| { + b.iter(|| { + hamming_distance_batch_into( + black_box(&query), + black_box(&vectors), + dimension, + &mut distances, + ); + black_box(&distances); + }) + }); + } + group.finish(); +} + +fn bench_hamming_batch_u64(c: &mut Criterion) { + let mut rng = rand::rng(); + let targets: Vec = (0..NUM_TARGETS).map(|_| rng.random()).collect(); + let mut results = vec![0; NUM_TARGETS]; + let mut group = c.benchmark_group("hamming_batch_u64"); + group.throughput(Throughput::Elements(NUM_TARGETS as u64)); + group.bench_function(BenchmarkId::from_parameter(NUM_TARGETS), |b| { + b.iter(|| { + hamming_batch_u64(black_box(rng.random()), black_box(&targets), &mut results); + black_box(&results); + }) + }); + group.finish(); +} + +/// One thread, so the row loop is measured rather than the scheduler. +fn bench_pairwise(c: &mut Criterion) { + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(1) + .build() + .unwrap(); + let mut rng = rand::rng(); + let num_pairs = (NUM_HASHES * (NUM_HASHES - 1) / 2) as u64; + let mut group = c.benchmark_group("hamming_pairwise"); + group.throughput(Throughput::Elements(num_pairs)); + for bits in [64, 128, 256] { + let num_lanes = bits / 64; + let lane_values: Vec = (0..NUM_HASHES * num_lanes).map(|_| rng.random()).collect(); + let hashes = BinaryHashValues::try_new(lane_values, NUM_HASHES, bits / 8).unwrap(); + group.bench_function(BenchmarkId::from_parameter(bits), |b| { + b.iter(|| { + pool.install(|| { + if num_lanes == 1 { + black_box(pairwise_hamming_distance_parallel( + hashes.lane(0), + None, + Some(THRESHOLD), + )) + } else { + black_box(pairwise_hamming_distance_binary_parallel( + &hashes, + None, + Some(THRESHOLD), + )) + } + }) + }) + }); + } + group.finish(); +} + +#[cfg(target_os = "linux")] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(20) + .with_profiler(PProfProfiler::new(100, Output::Flamegraph(None))); + targets = bench_hamming_u8, bench_hamming_batch_u64, bench_pairwise); + +// Non-linux version does not support pprof. +#[cfg(not(target_os = "linux"))] +criterion_group!( + name=benches; + config = Criterion::default().significance_level(0.1).sample_size(20); + targets = bench_hamming_u8, bench_hamming_batch_u64, bench_pairwise); + +criterion_main!(benches); diff --git a/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs b/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs index 037c05902..8f937c669 100644 --- a/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs +++ b/rust/lancedb/vendor/lance-linalg/benches/norm_l2.rs @@ -16,7 +16,7 @@ use num_traits::Float; use rand::Rng; use lance_arrow::{ArrowFloatType, FloatArray, bfloat16::BFloat16Type}; -use lance_linalg::distance::{norm_l2, norm_l2_f64_simd, norm_l2_impl}; +use lance_linalg::distance::{norm_l2, norm_l2_impl}; use lance_testing::datagen::generate_random_array_with_seed; #[cfg(target_os = "linux")] @@ -113,7 +113,7 @@ fn bench_distance(c: &mut Criterion) { c, target.as_slice(), norm_l2_impl::, - Some(norm_l2_f64_simd), + Some(norm_l2), ); } diff --git a/rust/lancedb/vendor/lance-linalg/src/distance.rs b/rust/lancedb/vendor/lance-linalg/src/distance.rs index ca844de40..2daefd75a 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance.rs @@ -168,11 +168,11 @@ fn x86_half_features() -> X86HalfFeatures { const U8_U32_ACCUMULATOR_MAX_LEN: usize = u32::MAX as usize / (u8::MAX as usize * u8::MAX as usize); /// Distance between two vectors of equal length. -pub(crate) type PairKernel = unsafe fn(&[f32], &[f32]) -> f32; +pub(crate) type PairKernel = unsafe fn(&[T], &[T]) -> f32; /// Writes the distance from `key` to each `dimension`-sized vector of `batch` /// into the matching element of `output`. -pub(crate) type BatchKernel = unsafe fn(&[f32], &[f32], usize, &mut [f32]); +pub(crate) type BatchKernel = unsafe fn(&[T], &[T], usize, &mut [f32]); pub use cosine::*; pub use dot::*; diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs b/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs index a87e844d0..ae166e3bf 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/arrow.rs @@ -125,7 +125,9 @@ impl Operation<'_> { fn binary(self, query: &[u8], values: &[u8], dim: usize) -> Result> { match self { Self::Batch(DistanceType::Hamming) => { - Ok(hamming::hamming_distance_batch(query, values, dim).collect()) + let mut distances = vec![0.0; values.len() / dim]; + hamming::hamming_distance_batch_into(query, values, dim, &mut distances); + Ok(distances) } Self::Multivec(DistanceType::Hamming, rows) => { Ok(multivec(query, values, dim, rows, hamming::hamming)) diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs b/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs index d61418dc2..2d29891b4 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/cosine.rs @@ -18,7 +18,11 @@ use lance_core::utils::cpu::SIMD_SUPPORT; use super::HalfBackend; use super::{ BatchKernel, Dot, HALF_KERNELS_COMPILED, HalfType, Normalize, assert_batch_output_layout, - assert_equal_lengths, dot::dot, half_backend, norm_l2::norm_l2, x86_half_features, + 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"))] @@ -388,7 +392,7 @@ mod x86 { use super::{ CosineKernel, CosineWithNormsKernel, cosine_f32_from_sums, cosine_f32_with_norms, dot, - norm_l2, + norm_l2, norm_l2_impl, }; use crate::distance::BatchKernel; use crate::simd::f32::{f32x8, f32x16}; @@ -610,8 +614,14 @@ mod x86 { xy8.multiply_add(xv, yv); y_norm8.multiply_add(yv, yv); } - let y_norm = - y_norm16.reduce_sum() + y_norm8.reduce_sum() + norm_l2(&other[aligned_len..]).powi(2); + // Inlined rather than the dispatched `norm_l2`, which is an + // indirect call unless the baseline covers its best candidate. On + // a tail this short every norm candidate computes the same sum. + // The tail `dot` keeps its dispatched call, as in the + // `cosine_with_norms` kernels: it was dispatched before `norm_l2` + // was, so inlining it would be a separate change to all of them. + let tail_norm = norm_l2_impl::(&other[aligned_len..]); + let y_norm = y_norm16.reduce_sum() + y_norm8.reduce_sum() + tail_norm.powi(2); let xy = xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &other[aligned_len..]); cosine_f32_from_sums(x, x_norm, other, xy, y_norm) @@ -645,7 +655,9 @@ mod x86 { // SAFETY: AVX is enabled for this function. let (xy_main, yy_main) = unsafe { (hsum256_ps(acc_xy), hsum256_ps(acc_yy)) }; - let y_norm = yy_main + norm_l2(&other[aligned_len..]).powi(2); + // See `cosine_f32_avx_fma` for `norm_l2_impl`. + let tail_norm = norm_l2_impl::(&other[aligned_len..]); + let y_norm = yy_main + tail_norm.powi(2); let xy = xy_main + dot(&x[aligned_len..], &other[aligned_len..]); cosine_f32_from_sums(x, x_norm, other, xy, y_norm) } @@ -929,8 +941,9 @@ lance_core::target_kernel! { xy8.multiply_add(xv, yv); y_norm8.multiply_add(yv, yv); } - let y_norm = - y_norm16.reduce_sum() + y_norm8.reduce_sum() + norm_l2(&other[aligned_len..]).powi(2); + // See the x86 `cosine_f32_avx_fma` for `norm_l2_impl`. + let tail_norm = norm_l2_impl::(&other[aligned_len..]); + let y_norm = y_norm16.reduce_sum() + y_norm8.reduce_sum() + tail_norm.powi(2); let xy = xy16.reduce_sum() + xy8.reduce_sum() + dot(&x[aligned_len..], &other[aligned_len..]); cosine_f32_from_sums(x, x_norm, other, xy, y_norm) } diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs b/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs index 00248dd46..2abea5d53 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/dot.rs @@ -10,11 +10,7 @@ use std::sync::Arc; use arrow_array::{Array, FixedSizeListArray, Float32Array}; use half::{bf16, f16}; -#[allow(unused_imports)] -use lance_core::{ - deepsize::DeepSizeOf, - utils::cpu::{SIMD_SUPPORT, SimdSupport}, -}; +use lance_core::{deepsize::DeepSizeOf, utils::cpu::SIMD_SUPPORT}; use num_traits::{AsPrimitive, Num, real::Real}; use crate::Result; @@ -415,33 +411,134 @@ impl Dot for f64 { #[inline] fn dot(x: &[Self], y: &[Self]) -> f32 { assert_equal_lengths(x.len(), y.len()); - dot_f64_simd(x, y) + DOT_F64.get().call(x, y) } fn dot_batch_into(x: &[Self], batch: &[Self], dimension: usize, output: &mut [f32]) { assert_batch_output_layout(x.len(), batch.len(), dimension, output.len()); - // Interim: on x86_64 f64 keeps the per-vector loop, since its PQ dot - // tables already beat the pre-`Dispatch` code; f64 moves onto - // `Dispatch` batch candidates later in #10083. + DOT_F64_BATCH.get().call(x, batch, dimension, output); + } +} + +lance_core::dispatch! { + static DOT_F64: Dispatch> = { #[cfg(target_arch = "x86_64")] - for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { - *product = dot_f64_simd(x, y); + { + &[ + x86::DOT_F64_AVX512, + x86::DOT_F64_AVX_FMA, + x86::DOT_F64_AVX, + DOT_F64_PORTABLE, + ] } - // Fixed query lengths and the pointer walk below are for the same - // reasons as in `L2::l2_batch_into` for f64. #[cfg(not(target_arch = "x86_64"))] - if let Ok(x) = <&[Self; 8]>::try_from(x) { - dot_batch_f64_fixed(x, batch, output); - } else if let Ok(x) = <&[Self; 16]>::try_from(x) { - dot_batch_f64_fixed(x, batch, output); - } else { - let mut y = batch.as_ptr(); - for product in output.iter_mut() { - // SAFETY: the layout assert guarantees `batch.len() == output.len() * dimension`. - unsafe { - *product = dot_f64_simd_other(x, std::slice::from_raw_parts(y, dimension)); - y = y.add(dimension); - } + { + &[DOT_F64_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(DOT_F64_PORTABLE: PairKernel)] + /// The x86_64 fallback below AVX, and the only kernel elsewhere. On + /// x86_64 `simd::f64` requires AVX, so this body is plain Rust there; + /// elsewhere `simd::f64` is backed by the baseline NEON or LSX. + #[inline] + fn dot_f64_portable(x: &[f64], y: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum::() as f32 + } + #[cfg(not(target_arch = "x86_64"))] + { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + acc8.multiply_add(a, b); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + acc4.multiply_add(a, b); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 + } + } +} + +lance_core::dispatch! { + /// Each batch candidate loops over its tier's `DOT_F64` kernel, so the + /// selection runs once per batch and the pair kernel inlines. See + /// `L2_F64_BATCH` for why this keeps an AVX-512 candidate. + static DOT_F64_BATCH: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::DOT_F64_BATCH_AVX512, + x86::DOT_F64_BATCH_AVX_FMA, + x86::DOT_F64_BATCH_AVX, + DOT_F64_BATCH_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[DOT_F64_BATCH_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(DOT_F64_BATCH_PORTABLE: BatchKernel)] + fn dot_batch_f64_portable(x: &[f64], batch: &[f64], dimension: usize, output: &mut [f32]) { + // Fixed query lengths and the pointer walk below are for the same + // reasons as in `l2_batch_f64_portable`. + #[cfg(not(target_arch = "x86_64"))] + { + if let Ok(x) = <&[f64; 8]>::try_from(x) { + return dot_batch_f64_fixed(x, batch, output); + } + if let Ok(x) = <&[f64; 16]>::try_from(x) { + return dot_batch_f64_fixed(x, batch, output); + } + } + let batch = &batch[..output.len() * dimension]; + let mut y = batch.as_ptr(); + for product in output.iter_mut() { + // SAFETY: `batch` holds `output.len()` vectors of `dimension` elements. + unsafe { + *product = dot_f64_portable(x, std::slice::from_raw_parts(y, dimension)); + y = y.add(dimension); } } } @@ -451,38 +548,10 @@ impl Dot for f64 { #[inline(always)] fn dot_batch_f64_fixed(x: &[f64; N], batch: &[f64], output: &mut [f32]) { for (product, y) in output.iter_mut().zip(batch.as_chunks::().0) { - *product = dot_f64_simd_other(x, y); + *product = dot_f64_portable(x, y); } } -/// Dot product for f64, runtime-dispatched via `SIMD_SUPPORT` on x86_64 -/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the SIMD -/// primitives in `crate::simd::f64`, unconditionally backed by NEON / LSX-LASX. -#[inline] -fn dot_f64_simd(x: &[f64], y: &[f64]) -> f32 { - #[cfg(target_arch = "x86_64")] - { - match *SIMD_SUPPORT { - SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { x86::dot_f64_avx512(x, y) }, - SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::dot_f64_avx_fma(x, y) }, - SimdSupport::Avx => unsafe { x86::dot_f64_avx(x, y) }, - _ => dot_f64_scalar(x, y), - } - } - #[cfg(not(target_arch = "x86_64"))] - { - dot_f64_simd_other(x, y) - } -} - -/// Portable scalar dot product for f64. Used as the x86_64 fallback when no -/// AVX2 is detected, and exposed for cross-backend parity testing. -#[cfg(target_arch = "x86_64")] -#[inline] -fn dot_f64_scalar(x: &[f64], y: &[f64]) -> f32 { - x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum::() as f32 -} - #[cfg(target_arch = "x86_64")] mod x86 { use std::arch::x86_64::*; @@ -553,85 +622,171 @@ mod x86 { } } - /// AVX-512 path for f64: 8-wide `__m512d` with `vfmadd231pd` per iteration. - #[target_feature(enable = "avx512f")] - pub unsafe fn dot_f64_avx512(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 8 * 8; + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) DOT_F64_AVX512: PairKernel)] + /// 8-wide `__m512d` with `vfmadd231pd` per iteration. + #[inline] + pub(super) fn dot_f64_avx512(x: &[f64], y: &[f64]) -> f32 { + // See `dot_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; - let mut acc = _mm512_setzero_pd(); - for i in (0..unrolled_len).step_by(8) { - let a = _mm512_loadu_pd(x.as_ptr().add(i)); - let b = _mm512_loadu_pd(y.as_ptr().add(i)); - acc = _mm512_fmadd_pd(a, b, acc); + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + _mm512_loadu_pd(x.as_ptr().add(i)), + _mm512_loadu_pd(y.as_ptr().add(i)), + ) + }; + acc = _mm512_fmadd_pd(a, b, acc); + } + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (_mm512_reduce_add_pd(acc) + tail) as f32 } - - let tail: f64 = x[unrolled_len..] - .iter() - .zip(y[unrolled_len..].iter()) - .map(|(&a, &b)| a * b) - .sum(); - - (_mm512_reduce_add_pd(acc) + tail) as f32 } - /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). - #[target_feature(enable = "avx,fma")] - pub unsafe fn dot_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 8 * 8; + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) DOT_F64_AVX_FMA: PairKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn dot_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { + // See `dot_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - let a = f64x8::load_unaligned(x.as_ptr().add(i)); - let b = f64x8::load_unaligned(y.as_ptr().add(i)); - acc8.multiply_add(a, b); + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + acc8.multiply_add(a, b); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + acc4.multiply_add(a, b); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 } - - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - let a = f64x4::load_unaligned(x.as_ptr().add(i)); - let b = f64x4::load_unaligned(y.as_ptr().add(i)); - acc4.multiply_add(a, b); - } - - let tail: f64 = x[aligned_len..] - .iter() - .zip(y[aligned_len..].iter()) - .map(|(&a, &b)| a * b) - .sum(); - - (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 } - /// AVX-only path for f64 (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. - #[target_feature(enable = "avx")] - pub unsafe fn dot_f64_avx(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 4 * 4; + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) DOT_F64_AVX: PairKernel)] + /// AVX-only path (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. + #[inline] + pub(super) fn dot_f64_avx(x: &[f64], y: &[f64]) -> f32 { + // See `dot_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 4 * 4; - let mut acc = _mm256_setzero_pd(); - for i in (0..unrolled_len).step_by(4) { - let a = _mm256_loadu_pd(x.as_ptr().add(i)); - let b = _mm256_loadu_pd(y.as_ptr().add(i)); - acc = _mm256_add_pd(acc, _mm256_mul_pd(a, b)); + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + _mm256_loadu_pd(x.as_ptr().add(i)), + _mm256_loadu_pd(y.as_ptr().add(i)), + ) + }; + acc = _mm256_add_pd(acc, _mm256_mul_pd(a, b)); + } + + // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| a * b) + .sum(); + + (acc_sum + tail) as f32 } + } - // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. - let lo = _mm256_castpd256_pd128(acc); - let hi = _mm256_extractf128_pd(acc, 1); - let sum128 = _mm_add_pd(lo, hi); - let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); - let acc_sum = _mm_cvtsd_f64(sum64); + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) DOT_F64_BATCH_AVX512: BatchKernel)] + pub(super) fn dot_batch_f64_avx512( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // See `l2_batch_f64_avx512` in `l2.rs` for slicing the key. + let x = &x[..dimension]; + for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *product = dot_f64_avx512(x, y); + } + } + } - let tail: f64 = x[unrolled_len..] - .iter() - .zip(y[unrolled_len..].iter()) - .map(|(&a, &b)| a * b) - .sum(); + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) DOT_F64_BATCH_AVX_FMA: BatchKernel)] + pub(super) fn dot_batch_f64_avx_fma( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // See `l2_batch_f64_avx512` in `l2.rs` for slicing the key. + let x = &x[..dimension]; + for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *product = dot_f64_avx_fma(x, y); + } + } + } - (acc_sum + tail) as f32 + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) DOT_F64_BATCH_AVX: BatchKernel)] + pub(super) fn dot_batch_f64_avx( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // See `l2_batch_f64_avx512` in `l2.rs` for slicing the key. + let x = &x[..dimension]; + for (product, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *product = dot_f64_avx(x, y); + } + } } lance_core::target_kernel! { @@ -731,43 +886,6 @@ mod x86 { } } -#[cfg(not(target_arch = "x86_64"))] -#[inline] -fn dot_f64_simd_other(x: &[f64], y: &[f64]) -> f32 { - use crate::simd::f64::{f64x4, f64x8}; - use crate::simd::{FloatSimd, SIMD}; - - let dim = x.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - unsafe { - let a = f64x8::load_unaligned(x.as_ptr().add(i)); - let b = f64x8::load_unaligned(y.as_ptr().add(i)); - acc8.multiply_add(a, b); - } - } - - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - unsafe { - let a = f64x4::load_unaligned(x.as_ptr().add(i)); - let b = f64x4::load_unaligned(y.as_ptr().add(i)); - acc4.multiply_add(a, b); - } - } - - let tail: f64 = x[aligned_len..] - .iter() - .zip(y[aligned_len..].iter()) - .map(|(&a, &b)| a * b) - .sum(); - - (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 -} - impl Dot for u8 { #[inline] fn dot(x: &[Self], y: &[Self]) -> f32 { @@ -839,6 +957,8 @@ mod tests { assert!(std::panic::catch_unwind(|| dot(&short, &long)).is_err()); assert!(std::panic::catch_unwind(|| dot_f32(&short, &long)).is_err()); assert!(std::panic::catch_unwind(|| f32::dot(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| dot(&[1.0_f64], &[1.0_f64, 2.0])).is_err()); + assert!(std::panic::catch_unwind(|| f64::dot(&[1.0_f64], &[1.0_f64, 2.0])).is_err()); assert!(std::panic::catch_unwind(|| dot_distance(&short, &long)).is_err()); assert!( std::panic::catch_unwind(|| dot_distance_batch_into(&short, &long, 2, &mut [0.0])) @@ -984,7 +1104,7 @@ mod tests { .zip(y.iter().cloned()) .map(|(x, y)| x.abs() * y.abs()) .sum::(); - let k = ((2 * x.len()) - 1) as f64; + let k = (2 * x.len()).saturating_sub(1) as f64; let k_epsilon = k * T::epsilon().as_(); let error = if k_epsilon < 1.0 { @@ -1106,6 +1226,82 @@ mod tests { }); } + /// Every host-supported f64 kernel must agree with an f64 reference, and + /// each batch kernel must match its tier's pair kernel bit for bit. + /// Prefixes of length 0 to 3 are all tail, and 8 and 16 pin the portable + /// batch kernel's PQ-width fast paths regardless of the generated dimension. + /// A longer second input checks that each pair kernel reads only the + /// shorter length. + #[rstest::rstest] + fn test_dot_f64_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + for dimension in [0, 1, 2, 3, 8, 16, x.len()] + .into_iter() + .filter(|&d| d <= x.len()) + { + let (x, y) = (&x[..dimension], &y[..dimension]); + let want = dot_scalar_ref(x, y); + let max_error = max_error::(x, y); + let batch = [y, x].concat(); + let longer_y = [y, &[f64::MAX]].concat(); + for (pair, batch_candidate) in + DOT_F64.candidates().iter().zip(DOT_F64_BATCH.candidates()) + { + let (Some(pair_kernel), Some(batch_kernel)) = + (pair.kernel(), batch_candidate.kernel()) + else { + continue; + }; + let got = pair_kernel.call(x, y); + prop_assert!( + approx::relative_eq!(got, want, epsilon = max_error), + "{} at dim {dimension}: {got} != {want}", + pair.name() + ); + prop_assert!( + pair_kernel.call(x, &longer_y).to_bits() == got.to_bits() + && pair_kernel.call(&longer_y, x).to_bits() == got.to_bits(), + "{} read past the shorter input at dim {dimension}", + pair.name() + ); + + // Batch entry points reject dimension 0. + if dimension == 0 { + continue; + } + let mut got_batch = [f32::NAN; 2]; + batch_kernel.call(x, &batch, dimension, &mut got_batch); + let want_second = pair_kernel.call(x, x); + prop_assert!( + got_batch[0].to_bits() == got.to_bits() + && got_batch[1].to_bits() == want_second.to_bits(), + "{} at dim {dimension}: {got_batch:?} != [{got}, {want_second}]", + batch_candidate.name() + ); + } + } + Ok(()) + }); + } + + #[test] + fn test_dot_f64_batch_candidates_mirror_pair_candidates() { + let pairs = DOT_F64.candidates(); + let batches = DOT_F64_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() + ); + } + } + proptest::proptest! { #[test] fn test_dot_f16((x, y) in arbitrary_vector_pair(arbitrary_f16, 4..4048)) { @@ -1116,34 +1312,6 @@ mod tests { fn test_dot_bf16((x, y) in arbitrary_vector_pair(arbitrary_bf16, 4..4048)){ do_dot_test(&x, &y)?; } - - /// Every f64 kernel the host supports, plus the runtime dispatch, must - /// match the scalar fallback. Calling `dot_f64_scalar` directly - /// exercises the fallback even on AVX2-capable CI hosts. - #[cfg(target_arch = "x86_64")] - #[test] - fn test_dot_f64_kernels_match_scalar( - (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) - ) { - let scalar = dot_f64_scalar(&x, &y); - let max_error = max_error::(&x, &y); - let mut results = vec![("dispatched", dot_f64_simd(&x, &y))]; - if std::is_x86_feature_detected!("avx512f") { - results.push(("avx512", unsafe { x86::dot_f64_avx512(&x, &y) })); - } - if std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma") { - results.push(("avx_fma", unsafe { x86::dot_f64_avx_fma(&x, &y) })); - } - if std::is_x86_feature_detected!("avx") { - results.push(("avx", unsafe { x86::dot_f64_avx(&x, &y) })); - } - for (kernel, got) in results { - prop_assert!( - approx::relative_eq!(scalar, got, epsilon = max_error), - "{kernel}: {got} != scalar {scalar}" - ); - } - } } /// An empty batch with a valid dimension, e.g. no centroids, writes diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs b/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs index d7faebbeb..d2b0b2e4f 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/hamming.rs @@ -18,7 +18,7 @@ use arrow_array::{ use arrow_schema::{DataType, Field, Schema, SchemaRef}; use rayon::prelude::*; -use crate::distance::assert_batch_layout; +use crate::distance::{BatchKernel, assert_batch_output_layout}; use crate::{Error, Result}; /// Schema of a Hamming distance-pair batch. @@ -47,31 +47,201 @@ pub trait Hamming { fn hamming(x: &[u8], y: &[u8]) -> f32; } -/// Hamming distance between two vectors. -#[inline] -pub fn hamming(x: &[u8], y: &[u8]) -> f32 { - hamming_autovec::<64>(x, y) +/// Hamming distance from `x` to `y`. +type HammingKernel = unsafe fn(&[u8], &[u8]) -> f32; + +lance_core::dispatch! { + static HAMMING: Dispatch = { + #[cfg(target_arch = "aarch64")] + { + &[aarch64::HAMMING_NEON, HAMMING_PORTABLE] + } + // No AVX-512 candidate. A `Dispatch` resolves at compile time only + // when the build baseline covers its first candidate; Haswell builds + // cover AVX2 but not AVX-512, so listing AVX-512 first would turn this + // per-pair call into a runtime selection. The batch kernels below + // select once per batch, so they do list it. + #[cfg(target_arch = "x86_64")] + { + &[x86::HAMMING_AVX2, HAMMING_PORTABLE] + } + #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] + { + &[HAMMING_PORTABLE] + } + }; } +lance_core::dispatch! { + static HAMMING_BATCH: Dispatch> = { + #[cfg(target_arch = "aarch64")] + { + &[aarch64::HAMMING_BATCH_NEON, HAMMING_BATCH_PORTABLE] + } + #[cfg(target_arch = "x86_64")] + { + &[ + x86::HAMMING_BATCH_AVX512, + x86::HAMMING_BATCH_AVX2, + HAMMING_BATCH_PORTABLE, + ] + } + #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] + { + &[HAMMING_BATCH_PORTABLE] + } + }; +} + +/// Bytes the NEON kernel sums into its 16-bit lanes before widening them. +/// +/// A 64-byte step adds four `vcntq_u8` vectors (at most `4 * 8 = 32` per byte +/// lane, which fits `u8`) and pairwise-widens them into the 8 `u16` lanes with +/// `vpadalq_u8`, adding at most `2 * 32 = 64` per lane; a 16-byte step adds at +/// most `2 * 8 = 16`. Either way a lane gains at most 1 per input byte, so a +/// block of at most `1023 * 64` bytes keeps every lane at most +/// `65472 <= u16::MAX`. +#[cfg_attr(not(any(target_arch = "aarch64", test)), allow(dead_code))] +const HAMMING_NEON_FLUSH_BYTES: usize = 1023 * 64; + +/// Hamming distance between two vectors. +/// +/// Like [`hamming_scalar`], compares only the first `min(x.len(), y.len())` +/// bytes when the lengths differ. #[inline] -fn hamming_autovec(x: &[u8], y: &[u8]) -> f32 { - let (x_chunks, x_remainder) = x.as_chunks::(); - let (y_chunks, y_remainder) = y.as_chunks::(); - let sum = x_remainder +pub fn hamming(x: &[u8], y: &[u8]) -> f32 { + HAMMING.get().call(x, y) +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(HAMMING_PORTABLE: HammingKernel)] + #[inline] + fn hamming_portable(x: &[u8], y: &[u8]) -> f32 { + hamming_words(x, y) + } +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(HAMMING_BATCH_PORTABLE: BatchKernel)] + #[inline] + fn hamming_into_portable(from: &[u8], to: &[u8], dimension: usize, output: &mut [f32]) { + hamming_rows(from, to, dimension, output, hamming_words); + } +} + +/// Hamming distance over 8-byte words, which LLVM vectorizes to the widest +/// popcount the enclosing kernel's target features allow. +#[inline(always)] +fn hamming_words(x: &[u8], y: &[u8]) -> f32 { + let n = x.len().min(y.len()); + let (x_words, x_tail) = x[..n].as_chunks::<8>(); + let (y_words, y_tail) = y[..n].as_chunks::<8>(); + // Summing in u64 lets LLVM accumulate `vpsadbw`/`vpopcntq` results + // directly instead of narrowing each one to u32. + let words = x_words .iter() - .zip(y_remainder) - .map(|(&a, &b)| (a ^ b).count_ones()) - .sum::(); - (sum + x_chunks + .zip(y_words) + .map(|(a, b)| (u64::from_ne_bytes(*a) ^ u64::from_ne_bytes(*b)).count_ones() as u64) + .sum::(); + let tail = x_tail .iter() - .zip(y_chunks) - .map(|(x, y)| { - x.iter() - .zip(y.iter()) - .map(|(&a, &b)| (a ^ b).count_ones()) - .sum::() - }) - .sum::()) as f32 + .zip(y_tail) + .map(|(&a, &b)| (a ^ b).count_ones() as u64) + .sum::(); + (words + tail) as f32 +} + +/// Writes `pair(from, vector)` for each `dimension`-sized vector of `to`. +#[inline(always)] +fn hamming_rows( + from: &[u8], + to: &[u8], + dimension: usize, + output: &mut [f32], + pair: impl Fn(&[u8], &[u8]) -> f32, +) { + for (distance, vector) in output.iter_mut().zip(to.chunks_exact(dimension)) { + *distance = pair(from, vector); + } +} + +#[cfg(target_arch = "aarch64")] +mod aarch64 { + use std::arch::aarch64::*; + + use super::{HAMMING_NEON_FLUSH_BYTES, HammingKernel, hamming_rows}; + use crate::distance::BatchKernel; + + lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(pub(super) HAMMING_BATCH_NEON: BatchKernel)] + #[inline] + pub(super) fn hamming_into_neon( + from: &[u8], + to: &[u8], + dimension: usize, + output: &mut [f32], + ) { + hamming_rows(from, to, dimension, output, |x, y| hamming_neon(x, y)); + } + } + + lance_core::target_kernel! { + #[target_features("neon")] + #[candidate(pub(super) HAMMING_NEON: HammingKernel)] + /// Sums per-byte popcounts in 16-bit lanes and reduces them once per + /// block. + #[inline] + pub(super) fn hamming_neon(x: &[u8], y: &[u8]) -> f32 { + let n = x.len().min(y.len()); + let (mut x, mut y) = (&x[..n], &y[..n]); + let mut total = 0; + // A plain loop rather than `chunks().zip()`, whose fold LLVM + // left as a call per vector. + while x.len() > HAMMING_NEON_FLUSH_BYTES { + let (x_block, x_rest) = x.split_at(HAMMING_NEON_FLUSH_BYTES); + let (y_block, y_rest) = y.split_at(HAMMING_NEON_FLUSH_BYTES); + total += hamming_block(x_block, y_block); + (x, y) = (x_rest, y_rest); + } + (total + hamming_block(x, y)) as f32 + } + } + + /// `x` and `y` must have equal lengths. + #[inline(always)] + fn hamming_block(x: &[u8], y: &[u8]) -> u32 { + let (x_64, x_rest) = x.as_chunks::<64>(); + let (y_64, y_rest) = y.as_chunks::<64>(); + let (x_16, x_tail) = x_rest.as_chunks::<16>(); + let (y_16, y_tail) = y_rest.as_chunks::<16>(); + // SAFETY: every load reads 16 bytes at an offset of at most 48 into a + // 64-byte array, or at the start of a 16-byte array. + let sum = unsafe { + let mut acc = vdupq_n_u16(0); + for (a, b) in x_64.iter().zip(y_64) { + let (a, b) = (a.as_ptr(), b.as_ptr()); + let c0 = vcntq_u8(veorq_u8(vld1q_u8(a), vld1q_u8(b))); + let c1 = vcntq_u8(veorq_u8(vld1q_u8(a.add(16)), vld1q_u8(b.add(16)))); + let c2 = vcntq_u8(veorq_u8(vld1q_u8(a.add(32)), vld1q_u8(b.add(32)))); + let c3 = vcntq_u8(veorq_u8(vld1q_u8(a.add(48)), vld1q_u8(b.add(48)))); + acc = vpadalq_u8(acc, vaddq_u8(vaddq_u8(c0, c1), vaddq_u8(c2, c3))); + } + for (a, b) in x_16.iter().zip(y_16) { + let c = vcntq_u8(veorq_u8(vld1q_u8(a.as_ptr()), vld1q_u8(b.as_ptr()))); + acc = vpadalq_u8(acc, c); + } + vaddlvq_u16(acc) + }; + let tail = x_tail + .iter() + .zip(y_tail) + .map(|(&a, &b)| (a ^ b).count_ones()) + .sum::(); + sum + tail + } } /// Scalar version of hamming distance. Used for benchmarks. @@ -83,30 +253,29 @@ pub fn hamming_scalar(x: &[u8], y: &[u8]) -> f32 { .sum::() as f32 } -/// Compute Hamming distances from one vector to a batch of vectors. +/// Writes the Hamming distance from `from` to each `dimension`-sized vector of +/// `to` into the matching element of `output`. /// /// # Examples /// /// ``` -/// use lance_linalg::distance::hamming::hamming_distance_batch; +/// use lance_linalg::distance::hamming::hamming_distance_batch_into; /// /// let query = [0, u8::MAX]; /// let targets = [0, u8::MAX, 1, u8::MAX - 1]; -/// let distances = hamming_distance_batch(&query, &targets, query.len()).collect::>(); +/// let mut distances = [0.0; 2]; +/// hamming_distance_batch_into(&query, &targets, query.len(), &mut distances); /// assert_eq!(distances, [0.0, 2.0]); /// ``` /// /// # Panics /// -/// Panics if `dimension` is zero, `from.len()` differs from `dimension`, or -/// `to` does not contain a whole number of vectors with that dimension. -pub fn hamming_distance_batch<'a>( - from: &'a [u8], - to: &'a [u8], - dimension: usize, -) -> Box + 'a> { - assert_batch_layout(from.len(), to.len(), dimension); - Box::new(to.chunks_exact(dimension).map(|v| hamming(from, v))) +/// Panics if `dimension` is zero, `from.len()` differs from `dimension`, `to` +/// does not contain a whole number of vectors with that dimension, or +/// `output` does not have one slot per vector. +pub fn hamming_distance_batch_into(from: &[u8], to: &[u8], dimension: usize, output: &mut [f32]) { + assert_batch_output_layout(from.len(), to.len(), dimension, output.len()); + HAMMING_BATCH.get().call(from, to, dimension, output); } /// Compute Hamming distances with the validation of [`super::DistanceType::batch`]. @@ -378,6 +547,27 @@ impl Default for PairwiseResult { } } +/// Writes the Hamming distance from `query` to each target into the matching +/// result slot. Kernels fill `min(targets.len(), results.len())` slots. +type HammingBatchU64Kernel = unsafe fn(u64, &[u64], &mut [u32]); + +lance_core::dispatch! { + static HAMMING_BATCH_U64: Dispatch = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::HAMMING_BATCH_U64_AVX512, + x86::HAMMING_BATCH_U64_AVX2, + HAMMING_BATCH_U64_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[HAMMING_BATCH_U64_PORTABLE] + } + }; +} + /// Compute hamming distances for a query against multiple targets. /// Uses SIMD acceleration when available. /// @@ -386,13 +576,10 @@ impl Default for PairwiseResult { /// Panics if `results` is not the same length as `targets`. #[inline] pub fn hamming_batch_u64(query: u64, targets: &[u64], results: &mut [u32]) { - // Rejected in either direction, and before the dispatch. A shorter `results` the - // dispatcher's reslice would refuse on its own, and that reslice is what keeps the - // kernels' raw stores in bounds; this check just gets there first, with a message - // that names both lengths. An over-long one the reslice would instead truncate, - // handing the surplus tail back unwritten for the caller to read as distances. - // That is wrong output rather than a crash, which is why this is an `assert_eq!` - // and not a `debug_assert_eq!`. + // The kernels would stay in bounds on a mismatch, but silently fill only + // the shorter of the two, leaving an over-long `results` tail unwritten for + // the caller to read as distances. That is wrong output rather than a + // crash, which is why this is an `assert_eq!` and not a `debug_assert_eq!`. let num_targets = targets.len(); let num_slots = results.len(); assert_eq!( @@ -400,172 +587,155 @@ pub fn hamming_batch_u64(query: u64, targets: &[u64], results: &mut [u32]) { "hamming_batch_u64 needs one result slot per target, \ got {num_targets} target(s) and {num_slots} slot(s)" ); - hamming_batch_simd(query, targets, results); + HAMMING_BATCH_U64.get().call(query, targets, results); } -/// SIMD-accelerated batch hamming distance computation. -/// -/// # Panics -/// -/// Panics if `results` is shorter than `targets`. `results.len()` is required to equal -/// `targets.len()`: an over-long `results` is truncated here rather than rejected, and -/// the surplus tail goes back to the caller unwritten. `hamming_batch_u64` asserts the -/// equality before dispatching. -#[inline] -fn hamming_batch_simd(query: u64, targets: &[u64], results: &mut [u32]) { - // Both x86 kernels store through raw pointers over a range bounded by - // `targets.len()`, and this reslice makes `results` exactly that long, so it has to - // stay above the dispatch. - let results = &mut results[..targets.len()]; - - #[cfg(target_arch = "x86_64")] - { - if is_x86_feature_detected!("avx512vpopcntdq") && is_x86_feature_detected!("avx512f") { - // SAFETY: both required features were just detected, and the reslice - // above makes `results.len() == targets.len()`. - unsafe { - hamming_batch_avx512(query, targets, results); - } - return; - } - if is_x86_feature_detected!("avx2") { - // SAFETY: AVX2 was just detected, and the reslice above makes - // `results.len() == targets.len()`. - unsafe { - hamming_batch_avx2(query, targets, results); - } - return; +lance_core::target_kernel! { + #[target_features()] + #[candidate(HAMMING_BATCH_U64_PORTABLE: HammingBatchU64Kernel)] + /// A plain zip lets LLVM vectorize the popcount (NEON `cnt` on aarch64) + /// with no per-element bounds checks. + #[inline] + fn hamming_batch_u64_portable(query: u64, targets: &[u64], results: &mut [u32]) { + for (result, &target) in results.iter_mut().zip(targets) { + *result = (query ^ target).count_ones(); } } - - // Scalar fallback (LLVM auto-vectorizes well on Apple Silicon) - hamming_batch_scalar(query, targets, results); } -/// Scalar fallback using count_ones() which compiles to POPCNT. -#[inline] -fn hamming_batch_scalar(query: u64, targets: &[u64], results: &mut [u32]) { - // Unroll for better auto-vectorization - let n = targets.len(); - let chunks = n / 8; - let mut i = 0; - - for _ in 0..chunks { - results[i] = (query ^ targets[i]).count_ones(); - results[i + 1] = (query ^ targets[i + 1]).count_ones(); - results[i + 2] = (query ^ targets[i + 2]).count_ones(); - results[i + 3] = (query ^ targets[i + 3]).count_ones(); - results[i + 4] = (query ^ targets[i + 4]).count_ones(); - results[i + 5] = (query ^ targets[i + 5]).count_ones(); - results[i + 6] = (query ^ targets[i + 6]).count_ones(); - results[i + 7] = (query ^ targets[i + 7]).count_ones(); - i += 8; - } - - // Handle remainder - while i < n { - results[i] = (query ^ targets[i]).count_ones(); - i += 1; - } -} - -/// AVX-512 VPOPCNTDQ: Process 8 x 64-bit values at once. -/// -/// The chunk loop reaches only the first `targets.len() / 8 * 8` slots through a -/// raw pointer, 8 x u32 per chunk with no bounds check; the trailing slots go -/// through bounds-checked indexing. -/// -/// # Safety -/// -/// The host must support AVX-512F and AVX512VPOPCNTDQ, and `results.len()` must -/// be at least `targets.len()`. #[cfg(target_arch = "x86_64")] -#[target_feature(enable = "avx512f", enable = "avx512vpopcntdq")] -unsafe fn hamming_batch_avx512(query: u64, targets: &[u64], results: &mut [u32]) { +mod x86 { use std::arch::x86_64::*; - let n = targets.len(); - let query_vec = _mm512_set1_epi64(query as i64); + use super::{HammingBatchU64Kernel, HammingKernel, hamming_rows, hamming_words}; + use crate::distance::BatchKernel; - let chunks = n / 8; - let remainder = n % 8; - - for i in 0..chunks { - let offset = i * 8; - let targets_ptr = targets.as_ptr().add(offset) as *const __m512i; - let target_vec = _mm512_loadu_si512(targets_ptr); - - let xor_result = _mm512_xor_si512(query_vec, target_vec); - let popcount = _mm512_popcnt_epi64(xor_result); - let popcount_32 = _mm512_cvtepi64_epi32(popcount); - - _mm256_storeu_si256( - results.as_mut_ptr().add(offset) as *mut __m256i, - popcount_32, - ); - } - - if remainder > 0 { - let offset = chunks * 8; - for j in 0..remainder { - results[offset + j] = (query ^ targets[offset + j]).count_ones(); + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) HAMMING_AVX2: HammingKernel)] + /// PSHUFB nibble-lookup popcount, generated by LLVM. + #[inline] + pub(super) fn hamming_avx2(x: &[u8], y: &[u8]) -> f32 { + hamming_words(x, y) } } -} -/// AVX2 popcount using a PSHUFB nibble lookup table. -/// -/// The chunk loop reaches only the first `targets.len() / 4 * 4` slots through a -/// raw pointer, 4 x u32 per chunk with no bounds check; the trailing slots go -/// through bounds-checked indexing. -/// -/// # Safety -/// -/// The host must support AVX2, and `results.len()` must be at least -/// `targets.len()`. -#[cfg(target_arch = "x86_64")] -#[target_feature(enable = "avx2")] -unsafe fn hamming_batch_avx2(query: u64, targets: &[u64], results: &mut [u32]) { - use std::arch::x86_64::*; - - let n = targets.len(); - - let lookup = _mm256_setr_epi8( - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, - 3, 4, - ); - let low_mask = _mm256_set1_epi8(0x0f); - let query_vec = _mm256_set1_epi64x(query as i64); - - let chunks = n / 4; - let remainder = n % 4; - - for i in 0..chunks { - let offset = i * 4; - let targets_ptr = targets.as_ptr().add(offset) as *const __m256i; - let target_vec = _mm256_loadu_si256(targets_ptr); - - let xor_result = _mm256_xor_si256(query_vec, target_vec); - - // Popcount using nibble lookup - let lo = _mm256_and_si256(xor_result, low_mask); - let hi = _mm256_and_si256(_mm256_srli_epi16(xor_result, 4), low_mask); - let popcnt_lo = _mm256_shuffle_epi8(lookup, lo); - let popcnt_hi = _mm256_shuffle_epi8(lookup, hi); - let popcnt_bytes = _mm256_add_epi8(popcnt_lo, popcnt_hi); - let popcount = _mm256_sad_epu8(popcnt_bytes, _mm256_setzero_si256()); - - let results_ptr = results.as_mut_ptr().add(offset); - *results_ptr = _mm256_extract_epi32::<0>(popcount) as u32; - *results_ptr.add(1) = _mm256_extract_epi32::<2>(popcount) as u32; - *results_ptr.add(2) = _mm256_extract_epi32::<4>(popcount) as u32; - *results_ptr.add(3) = _mm256_extract_epi32::<6>(popcount) as u32; + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) HAMMING_BATCH_AVX2: BatchKernel)] + pub(super) fn hamming_into_avx2( + from: &[u8], + to: &[u8], + dimension: usize, + output: &mut [f32], + ) { + hamming_rows(from, to, dimension, output, hamming_words); + } } - if remainder > 0 { - let offset = chunks * 4; - for j in 0..remainder { - results[offset + j] = (query ^ targets[offset + j]).count_ones(); + lance_core::target_kernel! { + #[target_features("avx512f", "avx512vpopcntdq")] + #[candidate(pub(super) HAMMING_BATCH_AVX512: BatchKernel)] + /// `vpopcntq` over 64-byte vectors, generated by LLVM. + pub(super) fn hamming_into_avx512( + from: &[u8], + to: &[u8], + dimension: usize, + output: &mut [f32], + ) { + hamming_rows(from, to, dimension, output, hamming_words); + } + } + + lance_core::target_kernel! { + #[target_features("avx512f", "avx512vpopcntdq")] + #[candidate(pub(super) HAMMING_BATCH_U64_AVX512: HammingBatchU64Kernel)] + /// AVX-512 VPOPCNTDQ: Process 8 x 64-bit values at once. + pub(super) fn hamming_batch_u64_avx512(query: u64, targets: &[u64], results: &mut [u32]) { + // The chunk loop loads and stores through raw pointers, so `n` + // bounds both slices, as a safe function must. + let n = targets.len().min(results.len()); + let query_vec = _mm512_set1_epi64(query as i64); + + let chunks = n / 8; + let remainder = n % 8; + + for i in 0..chunks { + let offset = i * 8; + // SAFETY: `offset + 8 <= n`, which bounds both slices. + unsafe { + let targets_ptr = targets.as_ptr().add(offset) as *const __m512i; + let target_vec = _mm512_loadu_si512(targets_ptr); + + let xor_result = _mm512_xor_si512(query_vec, target_vec); + let popcount = _mm512_popcnt_epi64(xor_result); + let popcount_32 = _mm512_cvtepi64_epi32(popcount); + + _mm256_storeu_si256( + results.as_mut_ptr().add(offset) as *mut __m256i, + popcount_32, + ); + } + } + + if remainder > 0 { + let offset = chunks * 8; + for j in 0..remainder { + results[offset + j] = (query ^ targets[offset + j]).count_ones(); + } + } + } + } + + lance_core::target_kernel! { + #[target_features("avx2")] + #[candidate(pub(super) HAMMING_BATCH_U64_AVX2: HammingBatchU64Kernel)] + /// AVX2 popcount using a PSHUFB nibble lookup table. + pub(super) fn hamming_batch_u64_avx2(query: u64, targets: &[u64], results: &mut [u32]) { + // See `hamming_batch_u64_avx512`. + let n = targets.len().min(results.len()); + + let lookup = _mm256_setr_epi8( + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, + 2, 3, 3, 4, + ); + let low_mask = _mm256_set1_epi8(0x0f); + let query_vec = _mm256_set1_epi64x(query as i64); + + let chunks = n / 4; + let remainder = n % 4; + + for i in 0..chunks { + let offset = i * 4; + // SAFETY: `offset + 4 <= n`, which bounds both slices. + unsafe { + let targets_ptr = targets.as_ptr().add(offset) as *const __m256i; + let target_vec = _mm256_loadu_si256(targets_ptr); + + let xor_result = _mm256_xor_si256(query_vec, target_vec); + + // Popcount using nibble lookup + let lo = _mm256_and_si256(xor_result, low_mask); + let hi = _mm256_and_si256(_mm256_srli_epi16(xor_result, 4), low_mask); + let popcnt_lo = _mm256_shuffle_epi8(lookup, lo); + let popcnt_hi = _mm256_shuffle_epi8(lookup, hi); + let popcnt_bytes = _mm256_add_epi8(popcnt_lo, popcnt_hi); + let popcount = _mm256_sad_epu8(popcnt_bytes, _mm256_setzero_si256()); + + let results_ptr = results.as_mut_ptr().add(offset); + *results_ptr = _mm256_extract_epi32::<0>(popcount) as u32; + *results_ptr.add(1) = _mm256_extract_epi32::<2>(popcount) as u32; + *results_ptr.add(2) = _mm256_extract_epi32::<4>(popcount) as u32; + *results_ptr.add(3) = _mm256_extract_epi32::<6>(popcount) as u32; + } + } + + if remainder > 0 { + let offset = chunks * 4; + for j in 0..remainder { + results[offset + j] = (query ^ targets[offset + j]).count_ones(); + } + } } } } @@ -747,6 +917,32 @@ fn compute_balanced_chunks(n: usize, target_pairs_per_chunk: usize) -> Vec<(usiz chunks } +/// Calls `on_match(offset, distance)` for each distance at most `threshold`. +#[inline] +fn for_each_within(distances: &[u32], threshold: u32, mut on_match: impl FnMut(usize, u32)) { + // Matches are rare, so test 16 distances at a time without branching, + // which LLVM vectorizes, and only walk the chunks that hold one. + let (chunks, tail) = distances.as_chunks::<16>(); + for (chunk_index, chunk) in chunks.iter().enumerate() { + if chunk + .iter() + .fold(false, |any, &dist| any | (dist <= threshold)) + { + for (k, &dist) in chunk.iter().enumerate() { + if dist <= threshold { + on_match(chunk_index * 16 + k, dist); + } + } + } + } + let tail_start = chunks.len() * 16; + for (k, &dist) in tail.iter().enumerate() { + if dist <= threshold { + on_match(tail_start + k, dist); + } + } +} + /// Process a range of rows for pairwise comparison using SIMD. fn process_row_range( hashes: &[u64], @@ -757,6 +953,13 @@ fn process_row_range( ) -> PairwiseResult { let n = hashes.len(); let mut result = PairwiseResult::new(); + // Selected once per range rather than per row through `hamming_batch_u64`, + // whose length assert is redundant here: each row slices `distances` to + // exactly the targets' length. + let kernel = HAMMING_BATCH_U64.get(); + // Rows only get shorter, so the first row's buffer fits every later one, + // and the kernel overwrites each slot it is handed. + let mut distances = vec![0u32; n.saturating_sub(start_row + 1)]; for i in start_row..end_row { let remaining = n - i - 1; @@ -764,17 +967,15 @@ fn process_row_range( continue; } - let mut distances = vec![0u32; remaining]; - hamming_batch_u64(hashes[i], &hashes[i + 1..], &mut distances); + let row_distances = &mut distances[..remaining]; + kernel.call(hashes[i], &hashes[i + 1..], row_distances); let id_a = row_ids.map_or(i as u64, |ids| ids[i]); - for (j_offset, &dist) in distances.iter().enumerate() { - if dist <= threshold { - let j = i + 1 + j_offset; - let id_b = row_ids.map_or(j as u64, |ids| ids[j]); - result.push(id_a, id_b, dist); - } - } + for_each_within(row_distances, threshold, |j_offset, dist| { + let j = i + 1 + j_offset; + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + }); } result @@ -790,8 +991,11 @@ fn process_row_range_binary( ) -> PairwiseResult { let n = hashes.len(); let mut result = PairwiseResult::new(); - let mut distances = Vec::new(); - let mut lane_distances = Vec::new(); + let kernel = HAMMING_BATCH_U64.get(); + // See `process_row_range`. + let max_remaining = n.saturating_sub(start_row + 1); + let mut distances = vec![0u32; max_remaining]; + let mut lane_distances = vec![0u32; max_remaining]; for i in start_row..end_row { let remaining = n - i - 1; @@ -799,38 +1003,25 @@ fn process_row_range_binary( continue; } - distances.clear(); - distances.resize(remaining, 0); - + let row_distances = &mut distances[..remaining]; let first_lane = hashes.lane(0); - hamming_batch_u64( - first_lane[i], - &first_lane[i + 1..], - distances.as_mut_slice(), - ); + kernel.call(first_lane[i], &first_lane[i + 1..], row_distances); + let row_lane_distances = &mut lane_distances[..remaining]; for lane in 1..hashes.num_lanes() { - lane_distances.clear(); - lane_distances.resize(remaining, 0); let lane_values = hashes.lane(lane); - hamming_batch_u64( - lane_values[i], - &lane_values[i + 1..], - lane_distances.as_mut_slice(), - ); - for (distance, lane_distance) in distances.iter_mut().zip(&lane_distances) { + kernel.call(lane_values[i], &lane_values[i + 1..], row_lane_distances); + for (distance, lane_distance) in row_distances.iter_mut().zip(&*row_lane_distances) { *distance += *lane_distance; } } let id_a = row_ids.map_or(i as u64, |ids| ids[i]); - for (j_offset, &dist) in distances.iter().enumerate() { - if dist <= threshold { - let j = i + 1 + j_offset; - let id_b = row_ids.map_or(j as u64, |ids| ids[j]); - result.push(id_a, id_b, dist); - } - } + for_each_within(row_distances, threshold, |j_offset, dist| { + let j = i + 1 + j_offset; + let id_b = row_ids.map_or(j as u64, |ids| ids[j]); + result.push(id_a, id_b, dist); + }); } result @@ -1141,15 +1332,122 @@ mod tests { assert_eq!(hamming(&x, &y), 2.0); } + /// Lengths straddle the 16- and 64-byte steps of the NEON kernel; the + /// longest ones run past the block after which it flushes its 16-bit + /// accumulators, with every bit differing so each lane is at its maximum. + /// Unequal inputs compare their common prefix, as `hamming_scalar` does. + #[rstest] + #[case::empty(0)] + #[case::one(1)] + #[case::fifteen(15)] + #[case::sixteen(16)] + #[case::seventeen(17)] + #[case::sixty_three(63)] + #[case::sixty_four(64)] + #[case::sixty_five(65)] + #[case::one_hundred_twenty_eight(128)] + #[case::two_hundred(200)] + #[case::one_flush(HAMMING_NEON_FLUSH_BYTES + 81)] + #[case::two_flushes(2 * HAMMING_NEON_FLUSH_BYTES + 17)] + fn test_hamming_kernels_match_reference(#[case] len: usize) { + const EXTRA: usize = 17; + let random: Vec = (0..(2 * len + EXTRA) as u64) + .map(|i| (i.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56) as u8) + .collect(); + let zeros = vec![0; len]; + let ones = vec![u8::MAX; len + EXTRA]; + let inputs = [ + ("random", &random[..len], &random[len..2 * len]), + ("all bits differ", &zeros[..], &ones[..len]), + ("y longer", &zeros[..], &ones[..]), + ("x longer", &ones[..], &zeros[..]), + ("random y longer", &random[..len], &random[len..]), + ]; + for (pattern, x, y) in inputs { + let want = hamming_scalar(x, y); + for candidate in HAMMING.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(x, y); + assert_eq!(got, want, "{} [{pattern}] len={len}", candidate.name()); + } + assert_eq!(hamming(x, y), want, "hamming [{pattern}] len={len}"); + } + } + + #[rstest] + #[case::one(1)] + #[case::eight(8)] + #[case::sixteen(16)] + #[case::thirty_one(31)] + #[case::sixty_four(64)] + #[case::two_hundred(200)] + fn test_hamming_batch_kernels_match_reference(#[case] dimension: usize) { + const NUM_VECTORS: usize = 5; + let random: Vec = (0..(NUM_VECTORS + 1) * dimension) + .map(|i| ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56) as u8) + .collect(); + let zeros = vec![0; dimension]; + let ones = vec![u8::MAX; NUM_VECTORS * dimension]; + let inputs = [ + ("random", &random[..dimension], &random[dimension..]), + ("all bits differ", &zeros[..], &ones[..]), + ]; + for (pattern, query, vectors) in inputs { + let want: Vec = vectors + .chunks_exact(dimension) + .map(|vector| hamming_scalar(query, vector)) + .collect(); + for candidate in HAMMING_BATCH.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let mut got = vec![f32::NAN; NUM_VECTORS]; + kernel.call(query, vectors, dimension, &mut got); + assert_eq!( + got, + want, + "{} [{pattern}] dimension={dimension}", + candidate.name() + ); + } + let mut got = vec![f32::NAN; NUM_VECTORS]; + hamming_distance_batch_into(query, vectors, dimension, &mut got); + assert_eq!( + got, want, + "hamming_distance_batch_into [{pattern}] dimension={dimension}" + ); + } + } + + #[test] + fn test_hamming_distance_batch_into() { + let query = [0, u8::MAX]; + let targets = [0, u8::MAX, 1, u8::MAX - 1, u8::MAX, 0]; + let mut distances = [f32::NAN; 3]; + hamming_distance_batch_into(&query, &targets, query.len(), &mut distances); + assert_eq!(distances, [0.0, 2.0, 16.0]); + } + #[test] #[should_panic( expected = "distance batch length must be divisible by dimension: batch=5, dimension=2" )] - fn test_hamming_distance_batch_rejects_partial_vector() { + fn test_hamming_distance_batch_into_rejects_partial_vector() { let query = [0, 0]; let targets = [u8::MAX, u8::MAX, 0, 1, 0]; + let mut distances = [0.0; 2]; + hamming_distance_batch_into(&query, &targets, query.len(), &mut distances); + } - let _ = hamming_distance_batch(&query, &targets, query.len()); + #[test] + #[should_panic(expected = "distance output length must match")] + fn test_hamming_distance_batch_into_rejects_short_output() { + let query = [0, 0]; + let targets = [u8::MAX; 4]; + let mut distances = [0.0; 1]; + hamming_distance_batch_into(&query, &targets, query.len(), &mut distances); } #[test] @@ -1161,47 +1459,45 @@ mod tests { assert_eq!(hamming_u64(0xAAAAAAAAAAAAAAAA, 0x5555555555555555), 64); } - /// Runs `kernel` over `n` targets, with 8 guard slots past the output it is - /// handed, then checks every value and every guard. + /// Runs `kernel` with `num_slots` result slots and 8 guard slots past + /// them, then checks that it filled the first `min(targets, slots)` slots + /// and wrote nothing else. /// - /// 8 is the widest unchecked chunk store in the file, so an unchecked chunk - /// store that overruns by one chunk lands inside this allocation instead of - /// past it. The remainder loops cannot trip the guards at all: all three - /// index through bounds-checked `results[..]` and would panic instead. - fn check_kernel_tail(n: usize, kernel: impl FnOnce(u64, &[u64], &mut [u32])) { + /// 8 is the widest unchecked chunk store in the file, so a chunk store that + /// overruns by one chunk lands inside this allocation instead of past it. + fn check_kernel( + query: u64, + targets: &[u64], + num_slots: usize, + label: &str, + kernel: impl FnOnce(u64, &[u64], &mut [u32]), + ) { const GUARD: u32 = u32::MAX; const GUARD_SLOTS: usize = 8; - let query = 0xDEAD_BEEF_CAFE_F00D_u64; - let targets: Vec = (0..n as u64) - .map(|i| i.wrapping_mul(0x9E37_79B9_7F4A_7C15)) - .collect(); - let mut results = vec![GUARD; n + GUARD_SLOTS]; + let mut results = vec![GUARD; num_slots + GUARD_SLOTS]; - kernel(query, &targets, &mut results[..n]); + kernel(query, targets, &mut results[..num_slots]); - for (slot, &target) in targets.iter().enumerate() { + let n = targets.len().min(num_slots); + for (slot, &target) in targets[..n].iter().enumerate() { assert_eq!( results[slot], (query ^ target).count_ones(), - "n={n}, slot {slot}" + "{label}: n={n}, slot {slot}" ); } for (slot, &guard) in results.iter().enumerate().skip(n) { - assert_eq!(guard, GUARD, "n={n}: wrote past results, at {slot}"); + assert_eq!( + guard, GUARD, + "{label}: n={n}: wrote past results, at {slot}" + ); } } - /// Each kernel behind `hamming_batch_u64` takes a fixed number of targets per - /// chunk and finishes the rest in a remainder loop: 4 for - /// `hamming_batch_avx2`, 8 for `hamming_batch_avx512` and for the unrolled - /// scalar fallback. - /// - /// The pairwise tests reach a remainder loop only when they are large enough - /// to take a parallel path. There the row ranges together pass every width - /// from one below the row count down to 1, so whichever kernel the host - /// dispatches has every residue covered incidentally, and a dropped or - /// out-of-bounds tail write surfaces somewhere in thousands of pairs, as a - /// mismatch or a panic. This asserts every slot at each width instead. + /// The x86 candidates take a fixed number of targets per chunk and finish + /// the rest in a remainder loop: 8 for AVX-512, 4 for AVX2. The portable + /// kernel's chunking is whatever LLVM vectorizes it to. The cases cover + /// every residue of both widths, with and without a chunk ahead of it. #[rstest] #[case::one(1)] #[case::two(2)] @@ -1216,16 +1512,56 @@ mod tests { #[case::sixteen(16)] #[case::seventeen(17)] #[case::one_hundred_twenty_eight(128)] - fn test_hamming_batch_u64(#[case] n: usize) { - check_kernel_tail(n, hamming_batch_u64); - // Also directly, because an x86_64 host with AVX2 takes an earlier branch - // and never reaches the scalar kernel through the dispatcher. - check_kernel_tail(n, hamming_batch_scalar); + fn test_hamming_batch_u64_kernels(#[case] n: usize) { + let random: Vec = (0..n as u64) + .map(|i| i.wrapping_mul(0x9E37_79B9_7F4A_7C15)) + .collect(); + let extremes: Vec = (0..n) + .map(|i| if i % 2 == 0 { u64::MAX } else { 0 }) + .collect(); + let inputs = [ + ("random", 0xDEAD_BEEF_CAFE_F00D_u64, random), + ("extremes", 0, extremes), + ]; + + for (pattern, query, targets) in &inputs { + for candidate in HAMMING_BATCH_U64.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let label = format!("{} [{pattern}]", candidate.name()); + check_kernel(*query, targets, n, &label, |query, targets, results| { + kernel.call(query, targets, results) + }); + } + let label = format!("hamming_batch_u64 [{pattern}]"); + check_kernel(*query, targets, n, &label, hamming_batch_u64); + } + } + + /// The kernels are safe functions, so a length mismatch that + /// `hamming_batch_u64` would reject must still stay in bounds. + #[rstest] + #[case::fewer_slots(17, 9)] + #[case::more_slots(9, 17)] + fn test_hamming_batch_u64_kernels_stay_in_bounds( + #[case] num_targets: usize, + #[case] num_slots: usize, + ) { + let targets: Vec = (0..num_targets as u64).map(|i| !i).collect(); + for candidate in HAMMING_BATCH_U64.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + check_kernel(0, &targets, num_slots, candidate.name(), |q, t, r| { + kernel.call(q, t, r) + }); + } } #[rstest] // Fewer slots than targets is the case that used to write out of bounds: on a - // host that takes the AVX2 path, `hamming_batch_avx2` wrote 28 bytes past a + // host that takes the AVX2 path, `hamming_batch_u64_avx2` wrote 28 bytes past a // one-slot `results`. #[case::eight_targets_one_slot(8, 1)] // On the same path this one overran by 4 bytes instead of 28. @@ -1252,8 +1588,8 @@ mod tests { ) { // No CPU feature gate: the length check precedes every kernel, so the panic // happens on each host and no case reaches a kernel at all. Every case here is - // a mismatch; matching lengths are covered by `test_hamming_batch_u64` above, - // which calls `hamming_batch_u64` directly, and by + // a mismatch; matching lengths are covered by `test_hamming_batch_u64_kernels` + // above, which calls `hamming_batch_u64` directly, and by // `test_pairwise_correctness_1000_deterministic` below, which reaches it // through `pairwise_hamming_distance_parallel`'s chunked path and checks the // result against `reference_pairwise`. @@ -1507,19 +1843,31 @@ mod tests { assert_eq!(result_to_sorted_vec(&par), expected); } - #[test] - fn test_pairwise_binary_hashes_parallel_128_matches_sequential() { - let rows: Vec<(u64, u64)> = (0..80) + /// 160 rows is past the sequential cutoff, so this reaches + /// `process_row_range_binary`; 4 lanes reuse its lane buffer several + /// times per row. + #[rstest] + #[case::bits_128(2)] + #[case::bits_256(4)] + fn test_pairwise_binary_hashes_parallel_matches_sequential(#[case] num_lanes: usize) { + let rows: Vec> = (0..80) .flat_map(|i| { - let lo = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); - let hi = !lo.rotate_left(17); - [(lo, hi), (lo ^ 1, hi)] + let lanes: Vec = (0..num_lanes) + .map(|lane| { + (i as u64 + 1) + .wrapping_mul(0x9E37_79B9_7F4A_7C15) + .rotate_left(17 * lane as u32) + }) + .collect(); + let mut near = lanes.clone(); + near[num_lanes - 1] ^= 1; + [lanes, near] }) .collect(); - let mut lane_values = Vec::with_capacity(rows.len() * 2); - lane_values.extend(rows.iter().map(|(lo, _)| *lo)); - lane_values.extend(rows.iter().map(|(_, hi)| *hi)); - let hashes = BinaryHashValues::try_new(lane_values, rows.len(), 16).unwrap(); + let lane_values: Vec = (0..num_lanes) + .flat_map(|lane| rows.iter().map(move |row| row[lane])) + .collect(); + let hashes = BinaryHashValues::try_new(lane_values, rows.len(), num_lanes * 8).unwrap(); let row_ids: Vec = (0..rows.len()).map(|i| 10_000 + i as u64).collect(); let seq = pairwise_hamming_distance_binary(&hashes, Some(&row_ids), Some(1)); @@ -1529,6 +1877,46 @@ mod tests { assert!(par.len() >= 80); } + /// Parallel chunks start past row 0, and the last chunk can hold only the + /// final row, which has no later row to pair with. + #[rstest] + #[case::whole(0, 40)] + #[case::middle(5, 23)] + #[case::tail(30, 40)] + #[case::last_row_only(39, 40)] + fn test_process_row_range_matches_sequential(#[case] start_row: usize, #[case] end_row: usize) { + const NUM_ROWS: usize = 40; + const THRESHOLD: u32 = 40; + let lane_values: Vec = (0..2 * NUM_ROWS as u64) + .map(|i| i.wrapping_mul(0x9E37_79B9_7F4A_7C15)) + .collect(); + let hashes = BinaryHashValues::try_new(lane_values, NUM_ROWS, 16).unwrap(); + let row_ids: Vec = (0..NUM_ROWS as u64).map(|i| 1000 + i).collect(); + let in_range = |result: &PairwiseResult| -> Vec<(u64, u64, u32)> { + result_to_sorted_vec(result) + .into_iter() + .filter(|&(a, _, _)| (start_row..end_row).contains(&((a - 1000) as usize))) + .collect() + }; + + let lane = hashes.lane(0); + let want = in_range(&pairwise_hamming_distance( + lane, + Some(&row_ids), + Some(THRESHOLD), + )); + let got = process_row_range(lane, Some(&row_ids), THRESHOLD, start_row, end_row); + assert_eq!(result_to_sorted_vec(&got), want); + + let want = in_range(&pairwise_hamming_distance_binary( + &hashes, + Some(&row_ids), + Some(THRESHOLD), + )); + let got = process_row_range_binary(&hashes, Some(&row_ids), THRESHOLD, start_row, end_row); + assert_eq!(result_to_sorted_vec(&got), want); + } + #[test] fn test_pairwise_binary_hashes_32_with_row_ids() { let hashes = BinaryHashValues::try_new( @@ -1593,6 +1981,30 @@ mod tests { } } + /// Groups of four hashes one or two bits apart, so matches cluster within + /// rows and the threshold separates them from the ~32-bit background. + /// 200 hashes is past the sequential cutoff. + #[rstest] + #[case::exact_only(0)] + #[case::one_bit(1)] + #[case::two_bits(2)] + #[case::half(32)] + #[case::all_pairs(u32::MAX)] + fn test_pairwise_parallel_threshold_matches_reference(#[case] threshold: u32) { + let hashes: Vec = (0u64..200) + .map(|i| { + let base = (i / 4 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); + base ^ ((1 << (i % 4)) >> 1) + }) + .collect(); + let want: Vec<(u64, u64, u32)> = reference_pairwise(&hashes, Some(threshold)) + .into_iter() + .map(|(i, j, dist)| (i as u64, j as u64, dist)) + .collect(); + let got = pairwise_hamming_distance_parallel(&hashes, None, Some(threshold)); + assert_eq!(result_to_sorted_vec(&got), want); + } + #[test] fn test_pairwise_correctness_1000_deterministic() { // Generate deterministic hashes using simple linear pattern @@ -1803,110 +2215,6 @@ mod tests { } } - // ========================================================================= - // SIMD-specific tests - // ========================================================================= - - // `hamming_batch_simd` returns early on the AVX-512 branch when - // `avx512vpopcntdq` and `avx512f` are both present, so on a host with both - // nothing reaches `hamming_batch_avx2` through `hamming_batch_u64`. This - // calls it directly. The AVX-512 kernel needs no such test: it only runs - // where the dispatched test already drives it. - - /// `hamming_batch_avx2` consumes 4 targets per chunk, so `n % 4` covers its - /// remainder loop. - #[rstest] - #[cfg(target_arch = "x86_64")] - #[case::one(1)] - #[case::two(2)] - #[case::three(3)] - #[case::four(4)] - // Five, six and seven repeat remainders 1 through 3 with a chunk ahead of - // them, which one, two and three alone do not reach. - #[case::five(5)] - #[case::six(6)] - #[case::seven(7)] - fn test_avx2_covers_tail(#[case] n: usize) { - if !is_x86_feature_detected!("avx2") { - return; - } - check_kernel_tail(n, |query, targets, results| { - // SAFETY: AVX2 was just detected, and `check_kernel_tail` passes a - // `results` of exactly `targets.len()`. - unsafe { hamming_batch_avx2(query, targets, results) } - }); - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn test_avx2_popcount() { - if !is_x86_feature_detected!("avx2") { - return; - } - - let query = 0u64; - let targets = vec![0u64, 1, 3, 7, 15, 31, 63, 127]; - let mut results = vec![0u32; 8]; - - unsafe { - hamming_batch_avx2(query, &targets, &mut results); - } - - assert_eq!(results[0], 0); // 0 ^ 0 = 0 bits - assert_eq!(results[1], 1); // 0 ^ 1 = 1 bit - assert_eq!(results[2], 2); // 0 ^ 3 = 2 bits - assert_eq!(results[3], 3); // 0 ^ 7 = 3 bits - assert_eq!(results[4], 4); // 0 ^ 15 = 4 bits - assert_eq!(results[5], 5); // 0 ^ 31 = 5 bits - assert_eq!(results[6], 6); // 0 ^ 63 = 6 bits - assert_eq!(results[7], 7); // 0 ^ 127 = 7 bits - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn test_avx2_max_distance() { - if !is_x86_feature_detected!("avx2") { - return; - } - - let query = 0u64; - let targets = vec![u64::MAX; 4]; - let mut results = vec![0u32; 4]; - - unsafe { - hamming_batch_avx2(query, &targets, &mut results); - } - - for &r in &results { - assert_eq!(r, 64); - } - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn test_avx512_popcount() { - if !is_x86_feature_detected!("avx512vpopcntdq") || !is_x86_feature_detected!("avx512f") { - return; - } - - let query = 0u64; - let targets = vec![0u64, 1, 3, 7, 15, 31, 63, 127]; - let mut results = vec![0u32; 8]; - - unsafe { - hamming_batch_avx512(query, &targets, &mut results); - } - - assert_eq!(results[0], 0); - assert_eq!(results[1], 1); - assert_eq!(results[2], 2); - assert_eq!(results[3], 3); - assert_eq!(results[4], 4); - assert_eq!(results[5], 5); - assert_eq!(results[6], 6); - assert_eq!(results[7], 7); - } - // ========================================================================= // Additional clustering tests // ========================================================================= diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs index b4f89849a..78b981367 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/l2.rs @@ -15,8 +15,6 @@ use arrow_array::{Array, FixedSizeListArray, Float32Array}; use half::{bf16, f16}; use lance_core::deepsize::DeepSizeOf; use lance_core::utils::cpu::SIMD_SUPPORT; -#[cfg(target_arch = "x86_64")] -use lance_core::utils::cpu::SimdSupport; use num_traits::{AsPrimitive, Num}; use crate::distance::{ @@ -435,56 +433,153 @@ impl L2 for f64 { #[inline] fn l2(x: &[Self], y: &[Self]) -> f32 { assert_equal_lengths(x.len(), y.len()); - l2_f64_simd(x, y) + L2_F64.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()); - // Reading `SIMD_SUPPORT` per vector costs a large share of a - // dimension-8 distance, so pick the tier once per batch. Each tier's - // loop carries that tier's target features, so its kernel inlines. - // Interim: f64 still selects through `SIMD_SUPPORT`, not `Dispatch`; - // these per-tier loops become its `Dispatch` batch candidates later - // in #10083. - // - // SAFETY (all three calls): `SIMD_SUPPORT` reports a tier only when - // the host has its features: avx512f for the AVX-512 tiers, avx and - // fma for `Avx2`/`AvxFma`, and avx for `Avx`. + L2_F64_BATCH.get().call(x, batch, dimension, output); + } +} + +lance_core::dispatch! { + static L2_F64: Dispatch> = { #[cfg(target_arch = "x86_64")] - match *SIMD_SUPPORT { - SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { - x86::l2_batch_f64_avx512(x, batch, dimension, output) - }, - SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { - x86::l2_batch_f64_avx_fma(x, batch, dimension, output) - }, - SimdSupport::Avx => unsafe { x86::l2_batch_f64_avx(x, batch, dimension, output) }, - _ => { - for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { - *distance = l2_f64_scalar(x, y); - } - } + { + &[ + x86::L2_F64_AVX512, + x86::L2_F64_AVX_FMA, + x86::L2_F64_AVX, + L2_F64_PORTABLE, + ] } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_F64_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_F64_PORTABLE: PairKernel)] + /// The x86_64 fallback below AVX, and the only kernel elsewhere. On + /// x86_64 `simd::f64` requires AVX, so this body is plain Rust there; + /// elsewhere `simd::f64` is backed by the baseline NEON or LSX. + #[inline] + fn l2_f64_portable(x: &[f64], y: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + x.iter() + .zip(y.iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum::() as f32 + } + #[cfg(not(target_arch = "x86_64"))] + { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + // Callers pass equal lengths; `min` keeps the unchecked loads in + // bounds for any input, as a safe function must. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; + let diff = a - b; + acc8.multiply_add(diff, diff); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + let diff = a - b; + acc4.multiply_add(diff, diff); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 + } + } +} + +lance_core::dispatch! { + /// Each batch candidate loops over its tier's `L2_F64` kernel, so the + /// selection runs once per batch and the pair kernel inlines. Unlike + /// `L2_F32_BATCH`, this keeps an AVX-512 candidate: f64 batches have + /// always used the AVX-512 kernel on AVX-512 hosts, and matching `L2_F64` + /// tier for tier keeps batch results bit-identical to `l2`, at one + /// indirect call per batch on Haswell builds. + static L2_F64_BATCH: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::L2_F64_BATCH_AVX512, + x86::L2_F64_BATCH_AVX_FMA, + x86::L2_F64_BATCH_AVX, + L2_F64_BATCH_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[L2_F64_BATCH_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(L2_F64_BATCH_PORTABLE: BatchKernel)] + fn l2_batch_f64_portable(x: &[f64], batch: &[f64], dimension: usize, output: &mut [f32]) { // A compile-time query length lets LLVM keep the query in registers // and drop the kernel's 4-lane and scalar tail stages, which it // otherwise doesn't reliably unswitch out of the loop. 8 and 16 are // the PQ sub-vector lengths of 128-dimension vectors. #[cfg(not(target_arch = "x86_64"))] - if let Ok(x) = <&[Self; 8]>::try_from(x) { - l2_batch_f64_fixed(x, batch, output); - } else if let Ok(x) = <&[Self; 16]>::try_from(x) { - l2_batch_f64_fixed(x, batch, output); - } else { - // A pointer walk rather than `zip` with `chunks_exact`: on aarch64 - // the zip indexed each vector with a multiply, which measurably - // slowed short vectors. - let mut y = batch.as_ptr(); - for distance in output.iter_mut() { - // SAFETY: the layout assert guarantees `batch.len() == output.len() * dimension`. - unsafe { - *distance = l2_f64_simd_other(x, std::slice::from_raw_parts(y, dimension)); - y = y.add(dimension); - } + { + if let Ok(x) = <&[f64; 8]>::try_from(x) { + return l2_batch_f64_fixed(x, batch, output); + } + if let Ok(x) = <&[f64; 16]>::try_from(x) { + return l2_batch_f64_fixed(x, batch, output); + } + } + // A pointer walk rather than `zip` with `chunks_exact`: on aarch64 + // the zip indexed each vector with a multiply, which measurably + // slowed short vectors. + let 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 = l2_f64_portable(x, std::slice::from_raw_parts(y, dimension)); + y = y.add(dimension); } } } @@ -494,44 +589,10 @@ impl L2 for f64 { #[inline(always)] fn l2_batch_f64_fixed(x: &[f64; N], batch: &[f64], output: &mut [f32]) { for (distance, y) in output.iter_mut().zip(batch.as_chunks::().0) { - *distance = l2_f64_simd_other(x, y); + *distance = l2_f64_portable(x, y); } } -/// L2 distance for f64, runtime-dispatched via `SIMD_SUPPORT` on x86_64 -/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the SIMD -/// primitives in `crate::simd::f64`, unconditionally backed by NEON / LSX-LASX. -#[inline] -fn l2_f64_simd(x: &[f64], y: &[f64]) -> f32 { - #[cfg(target_arch = "x86_64")] - { - match *SIMD_SUPPORT { - SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { x86::l2_f64_avx512(x, y) }, - SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::l2_f64_avx_fma(x, y) }, - SimdSupport::Avx => unsafe { x86::l2_f64_avx(x, y) }, - _ => l2_f64_scalar(x, y), - } - } - #[cfg(not(target_arch = "x86_64"))] - { - l2_f64_simd_other(x, y) - } -} - -/// Portable scalar L2 distance for f64. Used as the x86_64 fallback when no -/// AVX2 is detected, and exposed for cross-backend parity testing. -#[cfg(target_arch = "x86_64")] -#[inline] -fn l2_f64_scalar(x: &[f64], y: &[f64]) -> f32 { - x.iter() - .zip(y.iter()) - .map(|(&a, &b)| { - let diff = a - b; - diff * diff - }) - .sum::() as f32 -} - #[cfg(target_arch = "x86_64")] mod x86 { use std::arch::x86_64::*; @@ -612,146 +673,185 @@ mod x86 { } } - /// # Safety - /// - /// The host must support AVX-512F. - #[target_feature(enable = "avx512f")] - pub(super) unsafe fn l2_batch_f64_avx512( - x: &[f64], - batch: &[f64], - dimension: usize, - output: &mut [f32], - ) { - for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { - *distance = unsafe { l2_f64_avx512(x, y) }; + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) L2_F64_AVX512: PairKernel)] + /// 8-wide `__m512d` with `vsubpd` + `vfmadd231pd` per iteration. + #[inline] + pub(super) fn l2_f64_avx512(x: &[f64], y: &[f64]) -> f32 { + // See `l2_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + _mm512_loadu_pd(x.as_ptr().add(i)), + _mm512_loadu_pd(y.as_ptr().add(i)), + ) + }; + let diff = _mm512_sub_pd(a, b); + acc = _mm512_fmadd_pd(diff, diff, acc); + } + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (_mm512_reduce_add_pd(acc) + tail) as f32 } } - /// # Safety - /// - /// The host must support AVX and FMA. - #[target_feature(enable = "avx,fma")] - pub(super) unsafe fn l2_batch_f64_avx_fma( - x: &[f64], - batch: &[f64], - dimension: usize, - output: &mut [f32], - ) { - for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { - *distance = unsafe { l2_f64_avx_fma(x, y) }; - } - } + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) L2_F64_AVX_FMA: PairKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn l2_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { + // See `l2_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 8 * 8; - /// # Safety - /// - /// The host must support AVX. - #[target_feature(enable = "avx")] - pub(super) unsafe fn l2_batch_f64_avx( - x: &[f64], - batch: &[f64], - dimension: usize, - output: &mut [f32], - ) { - for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { - *distance = unsafe { l2_f64_avx(x, y) }; - } - } - - /// AVX-512 path for f64: 8-wide `__m512d` with `vsubpd` + `vfmadd231pd` per iteration. - #[target_feature(enable = "avx512f")] - #[inline] - pub unsafe fn l2_f64_avx512(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc = _mm512_setzero_pd(); - for i in (0..unrolled_len).step_by(8) { - let a = _mm512_loadu_pd(x.as_ptr().add(i)); - let b = _mm512_loadu_pd(y.as_ptr().add(i)); - let diff = _mm512_sub_pd(a, b); - acc = _mm512_fmadd_pd(diff, diff, acc); - } - - let tail: f64 = x[unrolled_len..] - .iter() - .zip(y[unrolled_len..].iter()) - .map(|(&a, &b)| { + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x8::load_unaligned(x.as_ptr().add(i)), + f64x8::load_unaligned(y.as_ptr().add(i)), + ) + }; let diff = a - b; - diff * diff - }) - .sum(); + acc8.multiply_add(diff, diff); + } - (_mm512_reduce_add_pd(acc) + tail) as f32 + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + f64x4::load_unaligned(x.as_ptr().add(i)), + f64x4::load_unaligned(y.as_ptr().add(i)), + ) + }; + let diff = a - b; + acc4.multiply_add(diff, diff); + } + + let tail: f64 = x[aligned_len..] + .iter() + .zip(y[aligned_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 + } } - /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). - #[target_feature(enable = "avx,fma")] - #[inline] - pub unsafe fn l2_f64_avx_fma(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 8 * 8; + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) L2_F64_AVX: PairKernel)] + /// AVX-only path (no FMA): squared diff via `_mm256_mul_pd` + `_mm256_add_pd` for Sandy/Ivy Bridge. + #[inline] + pub(super) fn l2_f64_avx(x: &[f64], y: &[f64]) -> f32 { + // See `l2_f32_avx512` for `min`. + let dim = x.len().min(y.len()); + let unrolled_len = dim / 4 * 4; - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - let a = f64x8::load_unaligned(x.as_ptr().add(i)); - let b = f64x8::load_unaligned(y.as_ptr().add(i)); - let diff = a - b; - acc8.multiply_add(diff, diff); + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds for both slices. + let (a, b) = unsafe { + ( + _mm256_loadu_pd(x.as_ptr().add(i)), + _mm256_loadu_pd(y.as_ptr().add(i)), + ) + }; + let diff = _mm256_sub_pd(a, b); + acc = _mm256_add_pd(acc, _mm256_mul_pd(diff, diff)); + } + + // Horizontal sum of __m256d -> f64. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = x[unrolled_len..] + .iter() + .zip(y[unrolled_len..].iter()) + .map(|(&a, &b)| { + let diff = a - b; + diff * diff + }) + .sum(); + + (acc_sum + tail) as f32 } - - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - let a = f64x4::load_unaligned(x.as_ptr().add(i)); - let b = f64x4::load_unaligned(y.as_ptr().add(i)); - let diff = a - b; - acc4.multiply_add(diff, diff); - } - - let tail: f64 = x[aligned_len..] - .iter() - .zip(y[aligned_len..].iter()) - .map(|(&a, &b)| { - let diff = a - b; - diff * diff - }) - .sum(); - - (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 } - /// AVX-only path for f64 (no FMA): squared diff via `_mm256_mul_pd` + `_mm256_add_pd` for Sandy/Ivy Bridge. - #[target_feature(enable = "avx")] - #[inline] - pub unsafe fn l2_f64_avx(x: &[f64], y: &[f64]) -> f32 { - let dim = x.len(); - let unrolled_len = dim / 4 * 4; - - let mut acc = _mm256_setzero_pd(); - for i in (0..unrolled_len).step_by(4) { - let a = _mm256_loadu_pd(x.as_ptr().add(i)); - let b = _mm256_loadu_pd(y.as_ptr().add(i)); - let diff = _mm256_sub_pd(a, b); - acc = _mm256_add_pd(acc, _mm256_mul_pd(diff, diff)); + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) L2_F64_BATCH_AVX512: BatchKernel)] + pub(super) fn l2_batch_f64_avx512( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // With the key the same length as each vector, the pair kernel's + // `min` folds away, which frees registers in the per-vector loop. + let x = &x[..dimension]; + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f64_avx512(x, y); + } } + } - // Horizontal sum of __m256d -> f64. - let lo = _mm256_castpd256_pd128(acc); - let hi = _mm256_extractf128_pd(acc, 1); - let sum128 = _mm_add_pd(lo, hi); - let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); - let acc_sum = _mm_cvtsd_f64(sum64); + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) L2_F64_BATCH_AVX_FMA: BatchKernel)] + pub(super) fn l2_batch_f64_avx_fma( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // See `l2_batch_f64_avx512` for slicing the key. + let x = &x[..dimension]; + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f64_avx_fma(x, y); + } + } + } - let tail: f64 = x[unrolled_len..] - .iter() - .zip(y[unrolled_len..].iter()) - .map(|(&a, &b)| { - let diff = a - b; - diff * diff - }) - .sum(); - - (acc_sum + tail) as f32 + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) L2_F64_BATCH_AVX: BatchKernel)] + pub(super) fn l2_batch_f64_avx( + x: &[f64], + batch: &[f64], + dimension: usize, + output: &mut [f32], + ) { + // See `l2_batch_f64_avx512` for slicing the key. + let x = &x[..dimension]; + for (distance, y) in output.iter_mut().zip(batch.chunks_exact(dimension)) { + *distance = l2_f64_avx(x, y); + } + } } lance_core::target_kernel! { @@ -863,48 +963,6 @@ mod x86 { } } -#[cfg(not(target_arch = "x86_64"))] -#[inline] -fn l2_f64_simd_other(x: &[f64], y: &[f64]) -> f32 { - use crate::simd::f64::{f64x4, f64x8}; - use crate::simd::{FloatSimd, SIMD}; - - let dim = x.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - unsafe { - let a = f64x8::load_unaligned(x.as_ptr().add(i)); - let b = f64x8::load_unaligned(y.as_ptr().add(i)); - let diff = a - b; - acc8.multiply_add(diff, diff); - } - } - - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - unsafe { - let a = f64x4::load_unaligned(x.as_ptr().add(i)); - let b = f64x4::load_unaligned(y.as_ptr().add(i)); - let diff = a - b; - acc4.multiply_add(diff, diff); - } - } - - let tail: f64 = x[aligned_len..] - .iter() - .zip(y[aligned_len..].iter()) - .map(|(&a, &b)| { - let diff = a - b; - diff * diff - }) - .sum(); - - (acc8.reduce_sum() + acc4.reduce_sum() + tail) as f32 -} - /// Accumulate squared differences for one dimension into per-target results. /// /// Separated into its own function so that LLVM sees `row` and `result` @@ -1107,6 +1165,8 @@ mod tests { assert!(std::panic::catch_unwind(|| l2(&short, &long)).is_err()); assert!(std::panic::catch_unwind(|| l2_f32(&short, &long)).is_err()); assert!(std::panic::catch_unwind(|| f32::l2(&short, &long)).is_err()); + assert!(std::panic::catch_unwind(|| l2(&[1.0_f64], &[1.0_f64, 2.0])).is_err()); + assert!(std::panic::catch_unwind(|| f64::l2(&[1.0_f64], &[1.0_f64, 2.0])).is_err()); assert!(std::panic::catch_unwind(|| l2_distance(&short, &long)).is_err()); assert!(std::panic::catch_unwind(|| l2_distance_batch_vec(&short, &long, 2)).is_err()); assert!( @@ -1366,6 +1426,80 @@ mod tests { }); } + /// Every host-supported f64 kernel must agree with an f64 reference, and + /// each batch kernel must match its tier's pair kernel bit for bit. + /// Prefixes of length 0 to 3 are all tail, and 8 and 16 pin the portable + /// batch kernel's PQ-width fast paths regardless of the generated dimension. + /// A longer second input checks that each pair kernel reads only the + /// shorter length. + #[rstest::rstest] + fn test_l2_f64_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_pair_proptest(arbitrary_f64, dimension_shard(shard), |x, y| { + for dimension in [0, 1, 2, 3, 8, 16, x.len()] + .into_iter() + .filter(|&d| d <= x.len()) + { + let (x, y) = (&x[..dimension], &y[..dimension]); + let want = l2_distance_reference(x, y) as f32; + // The second vector equals the key, so its distance is exactly 0. + let batch = [y, x].concat(); + let longer_y = [y, &[f64::MAX]].concat(); + for (pair, batch_candidate) in + L2_F64.candidates().iter().zip(L2_F64_BATCH.candidates()) + { + let (Some(pair_kernel), Some(batch_kernel)) = + (pair.kernel(), batch_candidate.kernel()) + else { + continue; + }; + let got = pair_kernel.call(x, y); + prop_assert!( + approx::relative_eq!(got, want, max_relative = 1e-6), + "{} at dim {dimension}: {got} != {want}", + pair.name() + ); + prop_assert!( + pair_kernel.call(x, &longer_y).to_bits() == got.to_bits() + && pair_kernel.call(&longer_y, x).to_bits() == got.to_bits(), + "{} read past the shorter input at dim {dimension}", + pair.name() + ); + + // Batch entry points reject dimension 0. + if dimension == 0 { + continue; + } + let mut got_batch = [f32::NAN; 2]; + batch_kernel.call(x, &batch, dimension, &mut got_batch); + prop_assert!( + got_batch[0].to_bits() == got.to_bits() && got_batch[1] == 0.0, + "{} at dim {dimension}: {got_batch:?} != [{got}, 0]", + batch_candidate.name() + ); + } + } + Ok(()) + }); + } + + #[test] + fn test_l2_f64_batch_candidates_mirror_pair_candidates() { + let pairs = L2_F64.candidates(); + let batches = L2_F64_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() + ); + } + } + // 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. @@ -1380,33 +1514,6 @@ mod tests { fn test_l2_distance_bf16((x, y) in arbitrary_vector_pair(arbitrary_bf16, 4..4048)){ do_l2_test(&x, &y)?; } - - /// Every f64 kernel the host supports, plus the runtime dispatch, must - /// match the scalar fallback. Calling `l2_f64_scalar` directly - /// exercises the fallback even on AVX2-capable CI hosts. - #[cfg(target_arch = "x86_64")] - #[test] - fn test_l2_f64_kernels_match_scalar( - (x, y) in arbitrary_vector_pair(arbitrary_f64, 4..4048) - ) { - let scalar = l2_f64_scalar(&x, &y); - let mut results = vec![("dispatched", l2_f64_simd(&x, &y))]; - if std::is_x86_feature_detected!("avx512f") { - results.push(("avx512", unsafe { x86::l2_f64_avx512(&x, &y) })); - } - if std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma") { - results.push(("avx_fma", unsafe { x86::l2_f64_avx_fma(&x, &y) })); - } - if std::is_x86_feature_detected!("avx") { - results.push(("avx", unsafe { x86::l2_f64_avx(&x, &y) })); - } - for (kernel, got) in results { - prop_assert!( - approx::relative_eq!(scalar, got, max_relative = 1e-6), - "{kernel}: {got} != scalar {scalar}" - ); - } - } } #[test] @@ -1589,62 +1696,6 @@ mod tests { check::(dimension, true); } - /// Each x86 f64 batch loop must match its pair kernel bit for bit, - /// including the tiers this host's `SIMD_SUPPORT` doesn't select. - #[cfg(target_arch = "x86_64")] - #[rstest::rstest] - #[case::dim_8(8)] - #[case::dim_13(13)] - #[case::dim_1024(1024)] - fn test_l2_batch_f64_tiers_match_pair_kernels(#[case] dimension: usize) { - type BatchFn = unsafe fn(&[f64], &[f64], usize, &mut [f32]); - type PairFn = unsafe fn(&[f64], &[f64]) -> f32; - - let num_vectors = 37; - let x: Vec = (0..dimension).map(|i| (i as f64 * 0.37).sin()).collect(); - let batch: Vec = (0..dimension * num_vectors) - .map(|i| (i as f64 * 0.73).cos() * 2.0) - .collect(); - - let tiers: [(&str, bool, BatchFn, PairFn); 3] = [ - ( - "avx512", - std::is_x86_feature_detected!("avx512f"), - x86::l2_batch_f64_avx512, - x86::l2_f64_avx512, - ), - ( - "avx_fma", - std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma"), - x86::l2_batch_f64_avx_fma, - x86::l2_f64_avx_fma, - ), - ( - "avx", - std::is_x86_feature_detected!("avx"), - x86::l2_batch_f64_avx, - x86::l2_f64_avx, - ), - ]; - for (name, is_supported, batch_fn, pair_fn) in tiers { - if !is_supported { - continue; - } - let mut got = vec![f32::NAN; num_vectors]; - // SAFETY: the host supports this tier's target features. - unsafe { batch_fn(&x, &batch, dimension, &mut got) }; - for (g, y) in got.iter().zip(batch.chunks_exact(dimension)) { - // SAFETY: as above. - let want = unsafe { pair_fn(&x, y) }; - assert_eq!( - g.to_bits(), - want.to_bits(), - "{name} dim {dimension}: batch {g} != pair {want}" - ); - } - } - } - /// The f64 batch loops off x86 walk `batch` by pointer, sized by `output`, /// so the layout check must reject a wrong `output` length for every type. #[rstest::rstest] diff --git a/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs b/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs index 342c62ddd..cea6ec846 100644 --- a/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs +++ b/rust/lancedb/vendor/lance-linalg/src/distance/norm_l2.rs @@ -8,8 +8,7 @@ use arrow_array::{FixedSizeListArray, Float32Array}; use half::{bf16, f16}; use super::arrow::{Norm, Operation, dispatch}; -#[allow(unused_imports)] -use lance_core::utils::cpu::{SIMD_SUPPORT, SimdSupport}; +use lance_core::utils::cpu::SIMD_SUPPORT; use num_traits::{AsPrimitive, Float, Num}; #[cfg(feature = "fp16kernels")] @@ -151,235 +150,271 @@ impl Normalize for bf16 { } } +/// L2 norm of one vector. +type NormKernel = unsafe fn(&[T]) -> f32; + impl Normalize for f32 { #[inline] fn norm_l2(vector: &[Self]) -> f32 { - norm_l2_f32_dispatched(vector) + NORM_L2_F32.get().call(vector) } } -/// L2 norm for f32, runtime-dispatched via `SIMD_SUPPORT` on x86_64 -/// (AVX-512 / AVX2+FMA / AVX+FMA / AVX / scalar). Non-x86 uses the -/// auto-vectorised scalar loop. -#[inline] -fn norm_l2_f32_dispatched(vector: &[f32]) -> f32 { - #[cfg(target_arch = "x86_64")] - { - match *SIMD_SUPPORT { - SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { - x86::norm_l2_f32_avx512(vector) - }, - SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::norm_l2_f32_avx_fma(vector) }, - SimdSupport::Avx => unsafe { x86::norm_l2_f32_avx(vector) }, - _ => norm_l2_f32_scalar(vector), +lance_core::dispatch! { + static NORM_L2_F32: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::NORM_L2_F32_AVX512, + x86::NORM_L2_F32_AVX_FMA, + x86::NORM_L2_F32_AVX, + NORM_L2_F32_SCALAR, + ] } - } - #[cfg(not(target_arch = "x86_64"))] - { - norm_l2_f32_scalar(vector) - } + #[cfg(not(target_arch = "x86_64"))] + { + &[NORM_L2_F32_SCALAR] + } + }; } -/// Portable scalar L2 norm for f32. Used as the x86_64 fallback when no -/// AVX2 is detected, and as the only path on non-x86 architectures. The -/// `LANES = 16` chunking matches the explicit-SIMD inner kernels above. -#[inline] -fn norm_l2_f32_scalar(vector: &[f32]) -> f32 { - norm_l2_impl::(vector) +lance_core::target_kernel! { + #[target_features()] + #[candidate(NORM_L2_F32_SCALAR: NormKernel)] + /// Portable L2 norm for f32, relying on LLVM to auto-vectorize it. The + /// `LANES = 16` chunking matches the explicit-SIMD kernels. + #[inline] + fn norm_l2_f32_scalar(vector: &[f32]) -> f32 { + norm_l2_impl::(vector) + } } impl Normalize for f64 { #[inline] fn norm_l2(vector: &[Self]) -> f32 { - norm_l2_f64_simd(vector) + NORM_L2_F64.get().call(vector) } } -/// L2 norm for f64. Runtime-dispatched to the best available backend. -/// -/// On x86_64, dispatches via `SIMD_SUPPORT` to a native AVX-512 inner kernel -/// (Skylake-X+, Ice Lake, Sapphire Rapids, Zen 4), an AVX2 + FMA kernel -/// (Haswell+), an AVX + FMA kernel (AMD Piledriver / Steamroller), an -/// AVX-only kernel (Intel Sandy Bridge / Ivy Bridge), or a portable scalar -/// fallback. The per-tier inner functions each carry their own -/// `#[target_feature]` so they stay correct under any compile baseline. -/// On aarch64 and loongarch64, the SIMD primitives in `crate::simd::f64` -/// are unconditionally backed by NEON / LSX-LASX respectively, so no -/// runtime gate is required. +/// L2 norm for f64, using the best kernel the host supports. +#[deprecated(note = "use norm_l2, which selects the same kernel")] #[inline] pub fn norm_l2_f64_simd(vector: &[f64]) -> f32 { - #[cfg(target_arch = "x86_64")] - { - match *SIMD_SUPPORT { - SimdSupport::Avx512 | SimdSupport::Avx512FP16 => unsafe { - x86::norm_l2_f64_avx512(vector) - }, - SimdSupport::Avx2 | SimdSupport::AvxFma => unsafe { x86::norm_l2_f64_avx_fma(vector) }, - SimdSupport::Avx => unsafe { x86::norm_l2_f64_avx(vector) }, - _ => norm_l2_f64_scalar(vector), - } - } - #[cfg(not(target_arch = "x86_64"))] - { - norm_l2_f64_simd_other(vector) - } + f64::norm_l2(vector) } -/// Portable scalar L2 norm. Used as the x86_64 fallback when no AVX2 is -/// detected, and exposed for cross-backend parity testing. -#[cfg(target_arch = "x86_64")] -#[inline] -fn norm_l2_f64_scalar(vector: &[f64]) -> f32 { - vector.iter().map(|v| v * v).sum::().sqrt() as f32 +lance_core::dispatch! { + static NORM_L2_F64: Dispatch> = { + #[cfg(target_arch = "x86_64")] + { + &[ + x86::NORM_L2_F64_AVX512, + x86::NORM_L2_F64_AVX_FMA, + x86::NORM_L2_F64_AVX, + NORM_L2_F64_PORTABLE, + ] + } + #[cfg(not(target_arch = "x86_64"))] + { + &[NORM_L2_F64_PORTABLE] + } + }; +} + +lance_core::target_kernel! { + #[target_features()] + #[candidate(NORM_L2_F64_PORTABLE: NormKernel)] + /// The x86_64 fallback below AVX, and the only kernel elsewhere. On + /// x86_64 `simd::f64` requires AVX, so this body is plain Rust there; + /// elsewhere `simd::f64` is backed by the baseline NEON or LSX. As in + /// `COSINE_F64_PORTABLE`, `_PORTABLE` marks a per-architecture body, while + /// `NORM_L2_F32_SCALAR` is plain Rust everywhere. + #[inline] + fn norm_l2_f64_portable(vector: &[f64]) -> f32 { + #[cfg(target_arch = "x86_64")] + { + vector.iter().map(|v| v * v).sum::().sqrt() as f32 + } + #[cfg(not(target_arch = "x86_64"))] + { + use crate::simd::f64::{f64x4, f64x8}; + use crate::simd::{FloatSimd, SIMD}; + + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds. + let v = unsafe { f64x8::load_unaligned(vector.as_ptr().add(i)) }; + acc8.multiply_add(v, v); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds. + let v = unsafe { f64x4::load_unaligned(vector.as_ptr().add(i)) }; + acc4.multiply_add(v, v); + } + + let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); + (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 + } + } } #[cfg(target_arch = "x86_64")] mod x86 { use std::arch::x86_64::*; + use super::NormKernel; use crate::simd::f64::{f64x4, f64x8}; use crate::simd::x86::hsum256_ps; use crate::simd::{FloatSimd, SIMD}; - /// AVX-512 path for f64: 8-wide `__m512d` with `vfmadd231pd` per iteration. - #[target_feature(enable = "avx512f")] - pub unsafe fn norm_l2_f64_avx512(vector: &[f64]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 8 * 8; + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) NORM_L2_F64_AVX512: NormKernel)] + /// 8-wide `__m512d` with `vfmadd231pd` per iteration. + #[inline] + pub(super) fn norm_l2_f64_avx512(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; - let mut acc = _mm512_setzero_pd(); - for i in (0..unrolled_len).step_by(8) { - let v = _mm512_loadu_pd(vector.as_ptr().add(i)); - acc = _mm512_fmadd_pd(v, v, acc); - } + let mut acc = _mm512_setzero_pd(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds. + let v = unsafe { _mm512_loadu_pd(vector.as_ptr().add(i)) }; + acc = _mm512_fmadd_pd(v, v, acc); + } - let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); - (_mm512_reduce_add_pd(acc) + tail).sqrt() as f32 - } - - /// AVX + FMA path for f64. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). - #[target_feature(enable = "avx,fma")] - pub unsafe fn norm_l2_f64_avx_fma(vector: &[f64]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - let v = f64x8::load_unaligned(vector.as_ptr().add(i)); - acc8.multiply_add(v, v); - } - - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - let v = f64x4::load_unaligned(vector.as_ptr().add(i)); - acc4.multiply_add(v, v); - } - - let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); - (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 - } - - /// AVX-only path for f64 (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. - #[target_feature(enable = "avx")] - pub unsafe fn norm_l2_f64_avx(vector: &[f64]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 4 * 4; - - let mut acc = _mm256_setzero_pd(); - for i in (0..unrolled_len).step_by(4) { - let v = _mm256_loadu_pd(vector.as_ptr().add(i)); - acc = _mm256_add_pd(acc, _mm256_mul_pd(v, v)); - } - - // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. - let lo = _mm256_castpd256_pd128(acc); - let hi = _mm256_extractf128_pd(acc, 1); - let sum128 = _mm_add_pd(lo, hi); - let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); - let acc_sum = _mm_cvtsd_f64(sum64); - - let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); - (acc_sum + tail).sqrt() as f32 - } - - /// AVX-512 path for f32: 16-wide `__m512` with `vfmadd231ps` per iteration. - #[target_feature(enable = "avx512f")] - pub unsafe fn norm_l2_f32_avx512(vector: &[f32]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 16 * 16; - - let mut acc = _mm512_setzero_ps(); - for i in (0..unrolled_len).step_by(16) { - let v = _mm512_loadu_ps(vector.as_ptr().add(i)); - acc = _mm512_fmadd_ps(v, v, acc); - } - - let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); - (_mm512_reduce_add_ps(acc) + tail).sqrt() - } - - /// AVX + FMA path for f32. Covers both AvxFma and AVX2 dispatch (body uses no AVX2-specific intrinsics). - #[target_feature(enable = "avx,fma")] - pub unsafe fn norm_l2_f32_avx_fma(vector: &[f32]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc = _mm256_setzero_ps(); - for i in (0..unrolled_len).step_by(8) { - let v = _mm256_loadu_ps(vector.as_ptr().add(i)); - acc = _mm256_fmadd_ps(v, v, acc); - } - - let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); - (hsum256_ps(acc) + tail).sqrt() - } - - /// AVX-only path for f32 (no FMA): `_mm256_mul_ps` + `_mm256_add_ps` per iteration for Sandy/Ivy Bridge. - #[target_feature(enable = "avx")] - pub unsafe fn norm_l2_f32_avx(vector: &[f32]) -> f32 { - let dim = vector.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc = _mm256_setzero_ps(); - for i in (0..unrolled_len).step_by(8) { - let v = _mm256_loadu_ps(vector.as_ptr().add(i)); - acc = _mm256_add_ps(acc, _mm256_mul_ps(v, v)); - } - - let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); - (hsum256_ps(acc) + tail).sqrt() - } -} - -#[cfg(not(target_arch = "x86_64"))] -#[inline] -fn norm_l2_f64_simd_other(vector: &[f64]) -> f32 { - use crate::simd::f64::{f64x4, f64x8}; - use crate::simd::{FloatSimd, SIMD}; - - let dim = vector.len(); - let unrolled_len = dim / 8 * 8; - - let mut acc8 = f64x8::zeros(); - for i in (0..unrolled_len).step_by(8) { - unsafe { - let v = f64x8::load_unaligned(vector.as_ptr().add(i)); - acc8.multiply_add(v, v); + let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (_mm512_reduce_add_pd(acc) + tail).sqrt() as f32 } } - let aligned_len = dim / 4 * 4; - let mut acc4 = f64x4::zeros(); - for i in (unrolled_len..aligned_len).step_by(4) { - unsafe { - let v = f64x4::load_unaligned(vector.as_ptr().add(i)); - acc4.multiply_add(v, v); + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) NORM_L2_F64_AVX_FMA: NormKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn norm_l2_f64_avx_fma(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc8 = f64x8::zeros(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds. + let v = unsafe { f64x8::load_unaligned(vector.as_ptr().add(i)) }; + acc8.multiply_add(v, v); + } + + let aligned_len = dim / 4 * 4; + let mut acc4 = f64x4::zeros(); + for i in (unrolled_len..aligned_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds. + let v = unsafe { f64x4::load_unaligned(vector.as_ptr().add(i)) }; + acc4.multiply_add(v, v); + } + + let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); + (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 } } - let tail: f64 = vector[aligned_len..].iter().map(|&v| v * v).sum(); - (acc8.reduce_sum() + acc4.reduce_sum() + tail).sqrt() as f32 + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) NORM_L2_F64_AVX: NormKernel)] + /// AVX-only path (no FMA): `_mm256_mul_pd` + `_mm256_add_pd` per iteration for Sandy/Ivy Bridge. + #[inline] + pub(super) fn norm_l2_f64_avx(vector: &[f64]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 4 * 4; + + let mut acc = _mm256_setzero_pd(); + for i in (0..unrolled_len).step_by(4) { + // SAFETY: `i + 4 <= dim`, which is in bounds. + let v = unsafe { _mm256_loadu_pd(vector.as_ptr().add(i)) }; + acc = _mm256_add_pd(acc, _mm256_mul_pd(v, v)); + } + + // Horizontal sum of __m256d -> f64. Two pairwise adds across lanes. + let lo = _mm256_castpd256_pd128(acc); + let hi = _mm256_extractf128_pd(acc, 1); + let sum128 = _mm_add_pd(lo, hi); + let sum64 = _mm_add_pd(sum128, _mm_unpackhi_pd(sum128, sum128)); + let acc_sum = _mm_cvtsd_f64(sum64); + + let tail: f64 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (acc_sum + tail).sqrt() as f32 + } + } + + lance_core::target_kernel! { + #[target_features("avx512f")] + #[candidate(pub(super) NORM_L2_F32_AVX512: NormKernel)] + /// 16-wide `__m512` with `vfmadd231ps` per iteration. + #[inline] + pub(super) fn norm_l2_f32_avx512(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 16 * 16; + + let mut acc = _mm512_setzero_ps(); + for i in (0..unrolled_len).step_by(16) { + // SAFETY: `i + 16 <= dim`, which is in bounds. + let v = unsafe { _mm512_loadu_ps(vector.as_ptr().add(i)) }; + acc = _mm512_fmadd_ps(v, v, acc); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + (_mm512_reduce_add_ps(acc) + tail).sqrt() + } + } + + lance_core::target_kernel! { + #[target_features("avx", "fma")] + #[candidate(pub(super) NORM_L2_F32_AVX_FMA: NormKernel)] + /// Covers both AVX+FMA and AVX2 hosts (body uses no AVX2-specific intrinsics). + #[inline] + pub(super) fn norm_l2_f32_avx_fma(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds. + let v = unsafe { _mm256_loadu_ps(vector.as_ptr().add(i)) }; + acc = _mm256_fmadd_ps(v, v, acc); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + // SAFETY: AVX is enabled for this function. + (unsafe { hsum256_ps(acc) } + tail).sqrt() + } + } + + lance_core::target_kernel! { + #[target_features("avx")] + #[candidate(pub(super) NORM_L2_F32_AVX: NormKernel)] + /// AVX-only path (no FMA): `_mm256_mul_ps` + `_mm256_add_ps` per iteration for Sandy/Ivy Bridge. + #[inline] + pub(super) fn norm_l2_f32_avx(vector: &[f32]) -> f32 { + let dim = vector.len(); + let unrolled_len = dim / 8 * 8; + + let mut acc = _mm256_setzero_ps(); + for i in (0..unrolled_len).step_by(8) { + // SAFETY: `i + 8 <= dim`, which is in bounds. + let v = unsafe { _mm256_loadu_ps(vector.as_ptr().add(i)) }; + acc = _mm256_add_ps(acc, _mm256_mul_ps(v, v)); + } + + let tail: f32 = vector[unrolled_len..].iter().map(|&v| v * v).sum(); + // SAFETY: AVX is enabled for this function. + (unsafe { hsum256_ps(acc) } + tail).sqrt() + } + } } /// NOTE: this is only pub for benchmarking purposes @@ -502,14 +537,54 @@ mod tests { }); } + /// Every host-supported f32 kernel must agree with an f64 reference. + /// Prefixes of length 0 to 3 are all tail. #[rstest::rstest] - fn test_l2_norm_f32_scalar_simd_parity( + fn test_norm_l2_f32_kernels_match_reference( #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, ) { run_vector_proptest(arbitrary_f32, dimension_shard(shard), |data| { - let scalar = data.iter().map(|&v| (v as f64).powi(2)).sum::().sqrt() as f32; - let simd = ::norm_l2(&data); - prop_assert!(approx::relative_eq!(scalar, simd, max_relative = 1e-3)); + for data in [0, 1, 2, 3, data.len()].map(|dim| &data[..dim]) { + let want = norm_l2_reference(&data.iter().map(|&v| v as f64).collect::>()); + for candidate in NORM_L2_F32.candidates() { + let Some(kernel) = candidate.kernel() else { + continue; + }; + let got = kernel.call(data); + prop_assert!( + approx::relative_eq!(got, want, max_relative = 1e-3), + "{} at dim {}: {got} != {want}", + candidate.name(), + data.len() + ); + } + } + Ok(()) + }); + } + + /// Every host-supported f64 kernel must agree with an f64 reference. + /// Prefixes of length 0 to 3 are all tail. + #[rstest::rstest] + fn test_norm_l2_f64_kernels_match_reference( + #[values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] shard: usize, + ) { + run_vector_proptest(arbitrary_f64, dimension_shard(shard), |data| { + for data in [0, 1, 2, 3, data.len()].map(|dim| &data[..dim]) { + let want = norm_l2_reference(data); + for candidate in NORM_L2_F64.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(()) }); } @@ -524,59 +599,6 @@ mod tests { fn test_l2_norm_bf16(data in prop::collection::vec(arbitrary_bf16(), 4..4048)){ do_norm_l2_test(&data)?; } - - /// Every f64 kernel the host supports, plus the runtime dispatch, must - /// match the scalar fallback. Calling `norm_l2_f64_scalar` directly - /// exercises the fallback even on AVX2-capable CI hosts. - #[cfg(target_arch = "x86_64")] - #[test] - fn test_l2_norm_f64_kernels_match_scalar( - data in prop::collection::vec(arbitrary_f64(), 4..4048) - ) { - let scalar = norm_l2_f64_scalar(&data); - let mut results = vec![("dispatched", norm_l2_f64_simd(&data))]; - if std::is_x86_feature_detected!("avx512f") { - results.push(("avx512", unsafe { x86::norm_l2_f64_avx512(&data) })); - } - if std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma") { - results.push(("avx_fma", unsafe { x86::norm_l2_f64_avx_fma(&data) })); - } - if std::is_x86_feature_detected!("avx") { - results.push(("avx", unsafe { x86::norm_l2_f64_avx(&data) })); - } - for (kernel, got) in results { - prop_assert!( - approx::relative_eq!(scalar, got, max_relative = 1e-6), - "{kernel}: {got} != scalar {scalar}" - ); - } - } - - /// Every f32 x86 kernel the host supports must match the scalar - /// fallback. - #[cfg(target_arch = "x86_64")] - #[test] - fn test_norm_l2_f32_kernels_match_scalar( - data in prop::collection::vec(arbitrary_f32(), 4..4048) - ) { - let scalar = norm_l2_f32_scalar(&data); - let mut results = vec![]; - if std::is_x86_feature_detected!("avx512f") { - results.push(("avx512", unsafe { x86::norm_l2_f32_avx512(&data) })); - } - if std::is_x86_feature_detected!("avx") && std::is_x86_feature_detected!("fma") { - results.push(("avx_fma", unsafe { x86::norm_l2_f32_avx_fma(&data) })); - } - if std::is_x86_feature_detected!("avx") { - results.push(("avx", unsafe { x86::norm_l2_f32_avx(&data) })); - } - for (kernel, got) in results { - prop_assert!( - approx::relative_eq!(scalar, got, max_relative = 1e-3), - "{kernel}: {got} != scalar {scalar}" - ); - } - } } #[test]