libembedding-ng 1.13.0__cp313-cp313-android_24_arm64_v8a.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,212 @@
1
+ """libembedding — Fast ONNX-based text, image, and sparse embeddings for Python."""
2
+
3
+ import logging
4
+ from importlib.metadata import PackageNotFoundError, version
5
+
6
+ try:
7
+ __version__ = version("libembedding-ng")
8
+ except PackageNotFoundError:
9
+ __version__ = "0.0.0"
10
+
11
+ from ._binding import ffi, lib
12
+ from .autotune import (
13
+ auto_select_model,
14
+ autotune,
15
+ autotune_unified,
16
+ cleanup_model_cache,
17
+ cleanup_model_cache_except,
18
+ clear_autotune_cache,
19
+ clear_autotune_cache_unified,
20
+ )
21
+ from .backend import detect_backend
22
+ from .benchmark import (
23
+ Benchmark,
24
+ BenchmarkResult,
25
+ ComparisonResult,
26
+ CorpusType,
27
+ HardwareInfo,
28
+ Metrics,
29
+ Objective,
30
+ cache_path,
31
+ clear_cache,
32
+ detect_hardware,
33
+ )
34
+ from .cache import EmbeddingCache, cache_config_default
35
+ from .exceptions import LembedError, LlamaError
36
+ from .gguf_inspect import (
37
+ SPARSE_FORMULA_SCALAR,
38
+ SPARSE_FORMULA_SPLADE,
39
+ SPARSE_FORMULA_UNKNOWN,
40
+ GgufCapabilities,
41
+ GgufDesc,
42
+ inspect_gguf,
43
+ )
44
+ from .image_embedding import ImageEmbedding, image_autotune
45
+ from .models import (
46
+ list_image_models,
47
+ list_reranker_models,
48
+ list_sparse_models,
49
+ list_text_models,
50
+ )
51
+ from .reranker import (
52
+ Reranker,
53
+ clear_reranker_autotune_cache,
54
+ reranker_auto_config,
55
+ reranker_auto_config_profile,
56
+ reranker_autotune,
57
+ reranker_autotune_constrained,
58
+ reranker_autotune_custom,
59
+ )
60
+ from .similarity import cosine_similarity, dot_product, euclidean_distance
61
+ from .sparse_text_embedding import (
62
+ SparseTextEmbedding,
63
+ sparse_autotune,
64
+ sparse_best_config,
65
+ )
66
+ from .text_embedding import ( # pyright: ignore[reportPrivateImportUsage]
67
+ TextEmbedding,
68
+ TextEmbeddingPool, # pyright: ignore[reportPrivateImportUsage]
69
+ )
70
+ from .types import (
71
+ ImageTuningResult,
72
+ ModelDesc,
73
+ ModelInfo,
74
+ ModelSelectionResult,
75
+ RerankerTuningResult,
76
+ RerankResult,
77
+ SparseEmbedding,
78
+ SparseTuningResult,
79
+ Stats,
80
+ TuningResult,
81
+ UnifiedTuningResult,
82
+ )
83
+
84
+ _logger = logging.getLogger(__name__)
85
+
86
+ # Version from C API (runtime)
87
+ try:
88
+ __version__ = lib.lembed_version().decode("utf-8", errors="replace")
89
+ except (AttributeError, OSError) as e:
90
+ _logger.debug("Could not get version from C API: %s", e)
91
+
92
+
93
+ def ggml_cpu_features() -> list[str]:
94
+ """Instruction sets of the ggml CPU backend that runs GGUF models.
95
+
96
+ The wheel ships one ggml CPU library per instruction-set level and ggml
97
+ loads the best match for this machine; this names the one it picked, e.g.
98
+ ``["SSE3", ..., "AVX512", "AVX512_VNNI", "LLAMAFILE", "REPACK"]``. Record
99
+ it with any GGUF benchmark: AVX2 and AVX-512 VNNI kernels are not
100
+ comparable. Loads the backend on first call. Empty when no CPU backend
101
+ could be loaded (a broken install).
102
+ """
103
+ return ffi.string(lib.lembed_ggml_cpu_features()).decode("ascii").split()
104
+
105
+
106
+ # Autotune modes (re-exported for convenience)
107
+ LEMBED_AUTOTUNE_QUICK = lib.LEMBED_AUTOTUNE_QUICK
108
+ LEMBED_AUTOTUNE_FULL = lib.LEMBED_AUTOTUNE_FULL
109
+
110
+ # Optimization objectives
111
+ LEMBED_OBJECTIVE_LATENCY = lib.LEMBED_OBJECTIVE_LATENCY
112
+ LEMBED_OBJECTIVE_THROUGHPUT = lib.LEMBED_OBJECTIVE_THROUGHPUT
113
+ LEMBED_OBJECTIVE_BALANCED = lib.LEMBED_OBJECTIVE_BALANCED
114
+ LEMBED_OBJECTIVE_MEMORY = lib.LEMBED_OBJECTIVE_MEMORY
115
+
116
+ # Task types for unified auto-tuner
117
+ LEMBED_TASK_EMBEDDING = lib.LEMBED_TASK_EMBEDDING
118
+ LEMBED_TASK_RERANKING = lib.LEMBED_TASK_RERANKING
119
+ LEMBED_TASK_IMAGE = lib.LEMBED_TASK_IMAGE
120
+ LEMBED_TASK_SPARSE = lib.LEMBED_TASK_SPARSE
121
+
122
+ # Reranker profiles
123
+ LEMBED_PROFILE_INTERACTIVE = lib.LEMBED_PROFILE_INTERACTIVE
124
+ LEMBED_PROFILE_BALANCED = lib.LEMBED_PROFILE_BALANCED
125
+ LEMBED_PROFILE_QUALITY = lib.LEMBED_PROFILE_QUALITY
126
+
127
+ # Sparse embedding storage formats
128
+ LEMBED_SPARSE_FORMAT_DICT = lib.LEMBED_SPARSE_FORMAT_DICT
129
+ LEMBED_SPARSE_FORMAT_INDEX_ORDER = lib.LEMBED_SPARSE_FORMAT_INDEX_ORDER
130
+ LEMBED_SPARSE_FORMAT_CSR = lib.LEMBED_SPARSE_FORMAT_CSR
131
+ LEMBED_SPARSE_FORMAT_NUMPY = lib.LEMBED_SPARSE_FORMAT_NUMPY
132
+
133
+ __all__ = [
134
+ "LEMBED_AUTOTUNE_FULL",
135
+ "LEMBED_AUTOTUNE_QUICK",
136
+ "LEMBED_OBJECTIVE_BALANCED",
137
+ "LEMBED_OBJECTIVE_LATENCY",
138
+ "LEMBED_OBJECTIVE_MEMORY",
139
+ "LEMBED_OBJECTIVE_THROUGHPUT",
140
+ "LEMBED_PROFILE_BALANCED",
141
+ "LEMBED_PROFILE_INTERACTIVE",
142
+ "LEMBED_PROFILE_QUALITY",
143
+ "LEMBED_SPARSE_FORMAT_CSR",
144
+ "LEMBED_SPARSE_FORMAT_DICT",
145
+ "LEMBED_SPARSE_FORMAT_INDEX_ORDER",
146
+ "LEMBED_SPARSE_FORMAT_NUMPY",
147
+ "LEMBED_TASK_EMBEDDING",
148
+ "LEMBED_TASK_IMAGE",
149
+ "LEMBED_TASK_RERANKING",
150
+ "LEMBED_TASK_SPARSE",
151
+ "SPARSE_FORMULA_SCALAR",
152
+ "SPARSE_FORMULA_SPLADE",
153
+ "SPARSE_FORMULA_UNKNOWN",
154
+ "Benchmark",
155
+ "BenchmarkResult",
156
+ "ComparisonResult",
157
+ "CorpusType",
158
+ "EmbeddingCache",
159
+ "GgufCapabilities",
160
+ "GgufDesc",
161
+ "HardwareInfo",
162
+ "ImageEmbedding",
163
+ "ImageTuningResult",
164
+ "LembedError",
165
+ "LlamaError",
166
+ "Metrics",
167
+ "ModelDesc",
168
+ "ModelInfo",
169
+ "ModelSelectionResult",
170
+ "Objective",
171
+ "RerankResult",
172
+ "Reranker",
173
+ "RerankerTuningResult",
174
+ "SparseEmbedding",
175
+ "SparseTextEmbedding",
176
+ "SparseTuningResult",
177
+ "Stats",
178
+ "TextEmbedding",
179
+ "TextEmbeddingPool",
180
+ "TuningResult",
181
+ "UnifiedTuningResult",
182
+ "auto_select_model",
183
+ "autotune",
184
+ "autotune_unified",
185
+ "cache_config_default",
186
+ "cache_path",
187
+ "cleanup_model_cache",
188
+ "cleanup_model_cache_except",
189
+ "clear_autotune_cache",
190
+ "clear_autotune_cache_unified",
191
+ "clear_cache",
192
+ "clear_reranker_autotune_cache",
193
+ "cosine_similarity",
194
+ "detect_backend",
195
+ "detect_hardware",
196
+ "dot_product",
197
+ "euclidean_distance",
198
+ "ggml_cpu_features",
199
+ "image_autotune",
200
+ "inspect_gguf",
201
+ "list_image_models",
202
+ "list_reranker_models",
203
+ "list_sparse_models",
204
+ "list_text_models",
205
+ "reranker_auto_config",
206
+ "reranker_auto_config_profile",
207
+ "reranker_autotune",
208
+ "reranker_autotune_constrained",
209
+ "reranker_autotune_custom",
210
+ "sparse_autotune",
211
+ "sparse_best_config",
212
+ ]
@@ -0,0 +1,233 @@
1
+ """Low-level cffi binding layer. Loads the shared library and exposes ffi/lib.
2
+
3
+ Auteur: David Orel
4
+ Version: 1.13.0
5
+
6
+ SPDX-License-Identifier: MIT
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import platform
13
+ import sys
14
+ import warnings
15
+ from pathlib import Path
16
+
17
+
18
+ def _preload_android_chaquopy_libs() -> None:
19
+ """Make Chaquopy's shared libraries visible on Android outside Chaquopy.
20
+
21
+ PyPI has no Android cffi or numpy; Chaquopy's index provides them, and
22
+ their extensions link libraries (libffi.so for cffi, libopenblas.so for
23
+ numpy) that companion wheels install under site-packages/chaquopy/lib.
24
+ Chaquopy's app runtime adds that directory to the loader path; plain
25
+ CPython on Android (PEP 738: BeeWare, cibuildwheel's testbed) does not,
26
+ and importing cffi or numpy fails with 'library "libffi.so" not found'.
27
+ Loaded once by absolute path with RTLD_GLOBAL, the Android linker reuses
28
+ them for the extensions' dependencies. This runs before libembedding
29
+ imports cffi or numpy; it cannot help a program that imported numpy first.
30
+ """
31
+ if sys.platform != "android":
32
+ return
33
+ import ctypes
34
+ import logging
35
+
36
+ log = logging.getLogger(__name__)
37
+ for base in sys.path:
38
+ lib_dir = Path(base) / "chaquopy" / "lib"
39
+ if not lib_dir.is_dir():
40
+ continue
41
+ # Every library is loaded, not a fixed list: the directory only holds
42
+ # Chaquopy companion libraries, and its content depends on the
43
+ # packages installed. *.so* also matches versioned names: openblas
44
+ # needs libgfortran.so.3, which a narrower pattern once missed.
45
+ pending = sorted(lib_dir.glob("*.so*"))
46
+ # The dependency order between them is unknown: retry until a pass
47
+ # loads nothing new. A library that never loads is left to the
48
+ # importing extension, whose error is the one users should see.
49
+ errors: dict[Path, OSError] = {}
50
+ while pending:
51
+ failed = []
52
+ for path in pending:
53
+ try:
54
+ ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)
55
+ log.debug("preloaded %s", path)
56
+ except OSError as exc:
57
+ failed.append(path)
58
+ errors[path] = exc
59
+ if len(failed) == len(pending):
60
+ for path in failed:
61
+ log.debug("could not preload %s: %s", path, errors[path])
62
+ break
63
+ pending = failed
64
+ return
65
+
66
+
67
+ _preload_android_chaquopy_libs()
68
+
69
+ # Must follow the Android preload above.
70
+ import cffi
71
+
72
+ ffi = cffi.FFI()
73
+
74
+ _cdefs_path = Path(__file__).with_name("_cdefs.h")
75
+ ffi.cdef(_cdefs_path.read_text(encoding="utf-8"))
76
+
77
+
78
+ def _library_candidates(pkg_dir: Path, root: Path, ext: str) -> tuple[list[Path], int]:
79
+ """Candidate library paths in lookup order, and how many are package copies.
80
+
81
+ The package copies come first: they are what a wheel install ships. The
82
+ build-tree paths only exist in a source checkout.
83
+ """
84
+ packaged = [pkg_dir / f"libembedding{ext}", pkg_dir / "lib" / f"libembedding{ext}"]
85
+ build_tree = [
86
+ root / "build" / "Debug" / f"libembedding{ext}",
87
+ root / "build" / "Release" / f"libembedding{ext}",
88
+ root / "build" / "python" / f"libembedding{ext}",
89
+ root / "build" / f"libembedding{ext}",
90
+ root / "build3" / "Release" / f"libembedding{ext}",
91
+ root / "build3" / f"libembedding{ext}",
92
+ root / "build_test" / "Debug" / f"libembedding{ext}",
93
+ root / "build_test" / "Release" / f"libembedding{ext}",
94
+ ]
95
+ return packaged + build_tree, len(packaged)
96
+
97
+
98
+ def _pick_library(candidates: list[Path], packaged_count: int) -> Path | None:
99
+ """First existing candidate; warns when it is a package copy older than a build.
100
+
101
+ In a source checkout the package directory is the wheel staging area: a copy
102
+ left there goes stale as soon as the tree is rebuilt, and every test or
103
+ benchmark run without LIBEMBEDDING_LIBRARY then silently exercises old code.
104
+ """
105
+ existing = [c for c in candidates if c.is_file()]
106
+ if not existing:
107
+ return None
108
+ chosen = existing[0]
109
+ if chosen in candidates[:packaged_count]:
110
+ newer = [
111
+ c for c in existing
112
+ if c in candidates[packaged_count:]
113
+ and c.stat().st_mtime > chosen.stat().st_mtime
114
+ ]
115
+ if newer:
116
+ warnings.warn(
117
+ f"Loading {chosen}, which is older than the build output {newer[0]}. "
118
+ "Set LIBEMBEDDING_LIBRARY to the library to test, or remove the "
119
+ "stale copy.",
120
+ stacklevel=3,
121
+ )
122
+ return chosen
123
+
124
+
125
+ def _find_library() -> str:
126
+ # An explicit path wins: it is the only unambiguous choice in a source
127
+ # checkout that holds several builds.
128
+ override = os.environ.get("LIBEMBEDDING_LIBRARY")
129
+ if override:
130
+ if not Path(override).is_file():
131
+ raise OSError(f"LIBEMBEDDING_LIBRARY points to a missing file: {override}")
132
+ return str(Path(override).resolve())
133
+
134
+ ext = {"Darwin": ".dylib", "Linux": ".so", "Windows": ".dll"}.get(
135
+ platform.system(), ".so"
136
+ )
137
+ pkg_dir = Path(__file__).parent
138
+ root = pkg_dir.parent.parent.parent # project root (libembedding/)
139
+ chosen = _pick_library(*_library_candidates(pkg_dir, root, ext))
140
+ return str(chosen.resolve()) if chosen else f"libembedding{ext}"
141
+
142
+
143
+ # Runtime dependencies that must be discoverable before libembedding is loaded.
144
+ # On Windows the loader resolves a DLL's imports from the executable directory,
145
+ # the directories registered with SetDllDirectoryW, and PATH. The libcurl build
146
+ # that ships inside the package lives in the package directory, which is not the
147
+ # same directory as libembedding.dll in a source checkout, so both are registered
148
+ # (see _runtime_dirs for the bundled third_party/curl/bin location).
149
+ # ggml's CPU backend is not listed: with CPU dispatch it is one of several
150
+ # ggml-cpu-<variant> modules that ggml scores and loads itself, from the
151
+ # library's directory; preloading one here would pick the variant for it.
152
+ _DEPENDENT_DLLS = (
153
+ "onnxruntime.dll",
154
+ "onnxruntime_providers_shared.dll",
155
+ "ggml.dll",
156
+ "ggml-base.dll",
157
+ "llama.dll",
158
+ "libcurl-x64.dll",
159
+ "libcurl.dll",
160
+ )
161
+
162
+
163
+ def _runtime_dirs(lib_path: Path) -> list[Path]:
164
+ """Directories that may contain dependent shared libraries, in priority order.
165
+
166
+ The library's own directory comes first: a build tree places the matching
167
+ ggml, llama and ONNX Runtime copies next to libembedding. Other build
168
+ directories (build/bin/Debug, build/bin/Release) are deliberately absent:
169
+ taking a dependency from there mixes Debug with Release, or a stale build
170
+ with a fresh one, in the same process.
171
+ """
172
+ root = Path(__file__).parent.parent.parent.parent
173
+ dirs = [
174
+ lib_path.parent,
175
+ # Wheel layout, and the MSVC runtime a wheel bundles.
176
+ Path(__file__).parent,
177
+ # Source-checkout libcurl installed by scripts/fetch_windows_libcurl.ps1;
178
+ # absent from a wheel install, hence the is_dir() filter below.
179
+ root / "third_party" / "curl" / "bin",
180
+ ]
181
+ seen: set[Path] = set()
182
+ ordered: list[Path] = []
183
+ for d in dirs:
184
+ if d.is_dir() and d not in seen:
185
+ seen.add(d)
186
+ ordered.append(d)
187
+ return ordered
188
+
189
+
190
+ def _select_dependencies(dirs: list[Path]) -> list[Path]:
191
+ """One path per known dependency: the copy in the first directory holding it.
192
+
193
+ Windows resolves an import by module name to an already loaded DLL, so
194
+ whichever copy is preloaded first is the one libembedding binds to. Loading
195
+ a single copy per name makes that choice explicit and keeps every other copy
196
+ out of the process.
197
+ """
198
+ selected: list[Path] = []
199
+ for name in _DEPENDENT_DLLS:
200
+ for d in dirs:
201
+ if (d / name).is_file():
202
+ selected.append(d / name)
203
+ break
204
+ return selected
205
+
206
+
207
+ if platform.system() == "Windows":
208
+ import ctypes
209
+
210
+ _lib_path_str = _find_library()
211
+ _lib_path = Path(_lib_path_str)
212
+ if _lib_path.exists():
213
+ _dirs = _runtime_dirs(_lib_path)
214
+ for _dep_path in _select_dependencies(_dirs):
215
+ try:
216
+ ctypes.CDLL(str(_dep_path))
217
+ except OSError:
218
+ pass
219
+ for _dir in reversed(_dirs):
220
+ ctypes.windll.kernel32.AddDllDirectory(str(_dir))
221
+ os.environ["PATH"] = str(_dir) + os.pathsep + os.environ.get("PATH", "")
222
+ # SetDllDirectoryW keeps a single directory: the library's own.
223
+ ctypes.windll.kernel32.SetDllDirectoryW(str(_dirs[0]))
224
+ lib = ffi.dlopen(_lib_path_str)
225
+ else:
226
+ _lib_path_str = _find_library()
227
+ _lib_path = Path(_lib_path_str)
228
+ if _lib_path.exists():
229
+ _dirs = [str(d) for d in _runtime_dirs(_lib_path)]
230
+ _env_var = "DYLD_LIBRARY_PATH" if platform.system() == "Darwin" else "LD_LIBRARY_PATH"
231
+ _existing = os.environ.get(_env_var, "")
232
+ os.environ[_env_var] = os.pathsep.join([*_dirs, _existing]) if _existing else os.pathsep.join(_dirs)
233
+ lib = ffi.dlopen(_lib_path_str)