python-bindings
Operate hnswlib 0.9.0 Python Index and BFIndex for typed vector search, filtering, mutation, persistence, pickle, and recall checks.
- License 许可
- Apache-2.0
- 最近更新
- 2026-09-03
- Stars
- ★ 351
- Forks
- 27
01 前言 Front Matter
- name
- python-bindings
- license
- Apache 2.0
- metadata
- { "disco-role": "operating" }
- description
- Operate hnswlib 0.9.0 Python Index and BFIndex for typed vector search, filtering, mutation, persistence, pickle, and recall checks.
- disable-model-invocation
- true
02 资源文件 8
- 参考文档references/api-reference.md7.3 KB
- 参考文档references/data-and-distance-semantics.md4.7 KB
- 参考文档references/troubleshooting.md8.9 KB
- 参考文档references/workflows.md6.6 KB
- 脚本scripts/python_filter_smoke.py3.3 KB
- 脚本scripts/python_lifecycle_smoke.py4.1 KB
- 脚本scripts/python_mutation_smoke.py4.4 KB
- 脚本scripts/python_pickle_smoke.py2.8 KB
03 SKILL.md 正文
Python bindings
Use this sub-skill when a Python task mentions hnswlib.Index, hnswlib.BFIndex,
NumPy vectors, knn_query, add_items, save_index, load_index, deletion,
replacement, pickle, filters, or recall. The contract covers the CPU-native
hnswlib 0.9.0 extension and its three exposed spaces: l2, ip, and
cosine. It does not provide a CUDA API.
Operating contract
- Work with an installed
hnswlibextension and NumPy arrays. The package's normal runtime dependency is NumPy; source builds additionally need the C++/pybind11 toolchain described in troubleshooting.md. - Treat labels as integer, non-negative external identifiers. Use explicit,
unique
np.int64labels when persistence, updates, or external metadata must remain stable. - Keep vectors as finite numeric data with shape
(rows, dim)or a single vector of shape(dim,). The binding force-casts input to contiguousfloat32, but applications should validate dimensionality before querying. - Keep mutation, querying, resizing, and serialization phases coordinated. The extension releases the GIL around native work; Python-level safety is not a substitute for the operation compatibility rules in workflows.md.
Standard workflow
- Normalize the request. Record
space,dim, capacity, label policy, queryk, filter cardinality, deletion/replacement needs, persistence path, and the target recall or exactness requirement. - Check import/build state. Import
hnswliband NumPy in the intended environment. If importing a source-built extension, use the compiler and native-linkage diagnosis in troubleshooting.md. - Construct and initialize. Create
Index(space, dim), then callinit_index(max_elements, M=16, ef_construction=200, random_seed=100, allow_replace_deleted=False).Indexis not ready for insertion untilinit_indexsucceeds. - Choose a stable data contract. Convert vectors with
np.asarray(data, dtype=np.float32)and assertdata.ndim in (1, 2)and the trailing dimension equalsdim. Use one scalar integer label only for one vector; otherwise pass one label per row. Omitted labels are assigned by the binding and are not a durable metadata scheme. - Populate and tune. Call
add_items(data, ids=None, num_threads=-1, replace_deleted=False). Reusing an existing label updates its vector. Setindex.efor callset_ef; chooseef >= kand increase it for recall at the cost of search time. Setnum_threads/set_num_threadsdeliberately. - Query and validate. Call
knn_query(data, k=1, num_threads=-1, filter=None). The return is(labels, distances), both shaped(rows, k)even for a single-vector query. A filter is a Python callable over external labels; usenum_threads=1for filtered search and ensure every query has at leastkeligible live items. - Inspect data and metadata. Use explicit label arrays with
get_items(ids, return_type="numpy"|"list"); sortget_ids_list()before comparing it. Checkspace,dim,M,ef_construction,ef,max_elements,element_count, and their method equivalents as needed. In this binding,get_items(None)does not mean “all labels”; retrieve all vectors by passingget_ids_list()explicitly. - Apply lifecycle mutations.
mark_deleted(label)hides a live label;unmark_deleted(label)restores it. For slot reuse, enableallow_replace_deleted=Trueat initialization or load, mark deletions, and passreplace_deleted=Truewith new labels. Without that policy, replacement raises; deletion alone does not create unbounded capacity. - Persist or pickle safely. Use a temporary/application-owned path with
save_index, then create a freshIndexandload_index(path, max_elements=0, allow_replace_deleted=...). Setefagain afterload_index: index-file persistence does not preserve it.pickle.dumpsandpickle.loadspreserve the Python index state, includingef, but pickle/get-index-state operations must not overlapadd_items. - Measure recall when approximate results matter. Build a same-space,
same-dimension
BFIndex, add the same labeled vectors, query both with a validk, and compare label overlap. BFIndex is an exact linear-scan oracle, not a performance substitute. Use the bundled tiny checks first:python scripts/python_lifecycle_smoke.py --helpand then run the selected smoke script from outside the checkout.
API routing map
- Exact signatures, result shapes, properties, and BFIndex: api-reference.md.
- Build/query/persistence/mutation/recall recipes: workflows.md.
- Shape, labels, dtype, metrics, normalization, and distances: data-and-distance-semantics.md.
- Installation, import, native flags, errors, concurrency, and recovery: troubleshooting.md.
- Deterministic executable checks:
scripts/python_lifecycle_smoke.py,scripts/python_filter_smoke.py,scripts/python_mutation_smoke.py, andscripts/python_pickle_smoke.py.
Hard guardrails
- Do not claim GPU or CUDA support. The exposed extension is CPU-native.
- Do not use
kgreater than the live/filtered population, or interpret an exception about a contiguous result array as a partial result. - Do not assume
efis automatically adequate; setef >= kafter every index-file load and tune it against BFIndex when recall is material. - Do not use negative labels, mismatched label counts, wrong vector dimensions, or a scalar label for multiple rows. Validate query dimensions too: the observed binding checks dimensions on insertion but does not provide the same explicit query-dimension guard.
- Do not call
mark_deletedtwice, unmark a label that is not marked, replace without the initialization/load policy, or insert beyond capacity without resizing/loading with a larger capacity. - Do not compare cosine
get_itemsoutput directly to the original unnormalized vectors; returned stored vectors are normalized. - Do not overlap
add_itemswithknn_query; concurrent additions are allowed with other additions, and concurrent queries with other queries. Python filters should run single-threaded. Resizing is not concurrent-safe with adding/querying, and pickle/getIndexParams is not concurrent-safe with adding.
Completion checklist
Before handing off a Python integration, confirm:
- import and package/runtime facts were checked in the target environment;
- the metric, dimension, capacity, dtype, shapes, and labels are explicit;
- initialization precedes insertion and
ef >= kis set for each query phase; - result shapes and filter eligibility are asserted;
- explicit IDs are used for
get_items, metadata, updates, and persistence; - deletion/replacement flags match the intended lifecycle;
- file paths are temporary or application-owned and reload uses a compatible metric/dimension;
efis restored after file loading, while pickle behavior is tested separately;- BFIndex is used for exact comparison when a recall claim is required; and
- no unsupported CUDA, malformed-query, unsafe-concurrency, or dependency claim has been smuggled into the integration.
04 同仓库更多 Skills
passnet-triton-opt
Make a single PassNet Triton kernel fast AND numerically faithful: performance model (when a replacement can win at all), block/grid/warp tuning, autotune policy, launch overhead, and per-op numeric recipes to pass the dtype baseline tolerances. Use when a pass matches and is correct but speedup below expected, or when correctness fails by small numeric margins.
passnet-solve
END-TO-END playbook for solving one PassNet sample: analyze the computation graphs, decide the optimization strategy (what to fuse, what to replace, what to leave alone), drive the iteration loop, and maximize the sample score. This is the ENTRY skill — invoke it first for any PassNet optimization task; it tells you when to use passnet-pattern-fusion, passnet-triton-opt and passnet-feedback.
passnet-skill
PassNet GPU kernel optimization via compiler passes. Design and implement Triton-based optimization passes, create pass files under ./pass_dir/, self-evaluate with pass_evaluator, and iterate to maximize GPU speedup.
passnet-pattern-fusion
Author PassNet pass files: write patterns that actually MATCH the FX graph, pick fusion regions (which ops to absorb into one Triton kernel), and structure multi-pass submissions with the mandatory shared-dispatch architecture. Use when creating or fixing pattern()/replacement_args()/replacement_func() files, when a pass "failed to match", or when deciding how to fuse multiple kernels/ops.
passnet-orchestrate
Round/batch planning and decision support for PassNet graph optimization. Use for multi-sample triage, worker allocation, eval-budget policy, and post-eval keep/revert decisions. For solving one concrete sample end to end, use passnet-solve as the entry skill; consult this skill only when you need broader planning or a specific decision gate.
passnet-feedback
Fast, deterministic feedback for PassNet work: pre-flight pattern/match verification WITHOUT burning a GPU evaluation, per-node bottleneck analysis of a sample's graphs, and eval-log parsing into per-variant status + estimated score + failure classification. Use BEFORE every GPU evaluation (check_pattern), at the START of a sample (analyze_graph), and AFTER every evaluation (parse_eval_log).