XVector C API Examples
Code examples demonstrating XVector library usage via the public C API.
XVector provides two ways to run vector search on MX1:
| Approach | Description | When to Use |
|---|---|---|
| XVector C API (this page) | Native C API for exact KNN, IVF-Flat, IVF-RaBitQ, and HNSW-Flat (experimental) search | Custom applications, fine-grained control |
| XFaiss | Drop-in Faiss replacement with MU acceleration | Existing Faiss workflows and .faiss index files |
This page walks through the KNN exact example; the same C API pattern (context → buffers → load index → search) applies to the IVF-Flat, IVF-RaBitQ, and HNSW-Flat (experimental) indexes.
KNN Exact Search
The xvector-examples package includes a complete KNN example that demonstrates exact nearest neighbor search using the XVector C API.
Compared to the raw XArith/PXL approach, XVector handles device kernel loading, data partitioning, task scheduling, and result merging internally:
| Aspect | XArith/PXL (raw) | XVector C API |
|---|---|---|
| Device kernel | Write and compile manually | Built-in |
| Memory management | Manual PXL alloc/free | xvecCreateBuffer / xvecDestroyBuffer |
| Data partitioning | Manual NDArray setup | Automatic |
| Result merging | Manual per-task merge | Automatic |
| API style | C++ (PXL + device headers) | Pure C (xvec_*.h) |
Want to see how this search is implemented? The XArith KNN example is the device-kernel version of this same KNN — manual data partitioning, per-task kernel dispatch, and top-k merge that the C API does for you here.
Build
Extract and build the example:
tar -xzf xvector-examples-0.3.0.tar.gz
cd xvector-examples-0.3.0/knn
mkdir build && cd build
cmake ..
make
Run
./xvector_knn # run with defaults
./xvector_knn --dim 128 --vectors 1000000 --k 10 # custom parameters
The production kernel is embedded in the linked XVector library and used automatically.
Options:
| Option | Default | Description |
|---|---|---|
--dim N | 1024 | Vector dimension |
--vectors N | 100000 | Number of dataset vectors |
--queries N | 10 | Number of query vectors |
--k N | 5 | Number of nearest neighbors |
--dist l2\|ip\|all | all | Distance metric |
Environment Variables:
| Variable | Default | Description |
|---|---|---|
PXL_DEVICE_ID | 0 | Device ID |
PXL_NUM_SUB | (device) | Number of subsystems. Unset asks the device, which differs per part |
PXL_TASK_COUNT | 192 | Task count for parallelism |
Sample Output
XVector KNN Example
Config: dim=1024 vectors=100000 queries=10 k=5 numSub=auto taskCount=192
Generating random test data... done
KNN L2 Test (vectors=100000, queries=10, dim=1024, k=5)
[xvector] Index loaded: ...
[xvector] Search: ...
KNN DOT_PRODUCT Test (vectors=100000, queries=10, dim=1024, k=5)
[xvector] Index loaded: ...
[xvector] Search: ...
Code Walkthrough
The full example (knn/main.cpp) follows a straightforward flow: create context, load data, search, read results.
Headers
#include <xvector/xvec_buffer.h>
#include <xvector/xvec_context.h>
#include <xvector/xvec_knn_exact.h>
#include <xvector/xvec_types.h>
1. Create Execution Context
The execution context connects to the MX1 device and loads the built-in kernel binary:
xvecExecutionContextTag* ctx = nullptr;
xvecStatus status = xvecCreateContext(&ctx, deviceId);
if (status != XVEC_SUCCESS) {
// handle error
}
// Configure parallelism. Leave "numSub" unset to use the device's detected Sub count.
// An explicit value above that count is clamped to the detected count.
xvecSetContextProperty(ctx, "taskCount", "192");
For RAII-style resource management, wrap handles in
std::unique_ptrwith custom deleters. See the full example forContextDeleter,BufferDeleter, andKnnExactIndexDeleterpatterns.
2. Load Index from Raw Vectors
Load a dataset of float32 vectors into a KNN exact index:
xvecKnnExactIndexTag* index = nullptr;
xvecKnnExactLoadIndexFromRawVectors(
ctx,
dataset, // const float* — contiguous float32 array
vectorCount, // number of vectors
dim, // vector dimension
XVEC_DISTANCE_L2, // or XVEC_DISTANCE_DOT_PRODUCT
&index);
3. Prepare Query Vectors
Create a buffer and copy query vectors into it:
size_t queryBufSize = sizeof(float) * queryCount * dim;
xvecBufferTag* queryBuf = nullptr;
xvecCreateBuffer(ctx, queryBufSize, &queryBuf);
void* queryData = nullptr;
xvecGetBufferData(queryBuf, &queryData);
memcpy(queryData, queryVectors, queryBufSize);
4. Execute Search
Build the search query and execute:
xvecKnnExactSearchQueryFloat32 searchQuery{};
searchQuery.dimension = dim;
searchQuery.queryVectorCount = queryCount;
searchQuery.queryVectorsBufferHandle = queryBuf;
searchQuery.topK = k;
// Allocate result buffer
size_t resultBufSize = sizeof(xvecKnnExactSearchResultFloat32) * queryCount * k;
xvecBufferTag* resultBuf = nullptr;
xvecCreateBuffer(ctx, resultBufSize, &resultBuf);
// Run search
xvecKnnExactSearch(ctx, index, &searchQuery, resultBuf, nullptr);
See Search scores for score ordering and how to identify unfilled result slots.
5. Cleanup
Destroy resources in reverse order:
xvecDestroyBuffer(ctx, resultBuf);
xvecDestroyBuffer(ctx, queryBuf);
xvecKnnExactDestroyIndex(ctx, index);
xvecDestroyContext(ctx);
Index device memory remains allocated until the owning context is destroyed, including when using C++ index wrappers. See Index resource lifetime before repeatedly loading indexes into the same context.
Adding Your Own Kernel to a Search
The knn_rerank example applies per-vector weights to search result scores on the device. It preserves result order; sort the weighted scores separately if you need a new ranking.
The host code and __pxl_kernel__ function share one main.cpp. Build it with pxcc++, which embeds the user kernel in the executable.
The example requires at least two available Subs: one for the user kernel and the remainder for search. An explicit PXL_NUM_SUB must leave at least one Sub free for the user kernel.
The handoff needs no copy, because xvecGetBufferData() returns the same device-visible pointer that the kernel takes as an argument:
__pxl_kernel__ void applyVectorWeights(xvecKnnExactSearchResultFloat32* results,
const float* weights, uint64_t resultCount)
{
for (uint64_t i = mu::getTaskIdx(); i < resultCount; i += mu::getTaskCount())
results[i].score = results[i].score * weights[results[i].vectorId];
mu::flushCacheAll();
}
// Host side, after xvecKnnExactSearch:
void* rawResults = nullptr;
xvecGetBufferData(resultBuf, &rawResults);
auto* results = static_cast<xvecKnnExactSearchResultFloat32*>(rawResults);
pxl::flushHostCache(results, resultBufSize); // Before reading search results on the host.
// Validate result IDs before indexing weights; unfilled slots may contain sentinels.
pxl::flushHostCache(weights, sizeof(float) * vectorCount); // Publish host-written weights.
pxl::Launcher(deviceId).execute<applyVectorWeights>(taskCount, results, weights, resultCount).reserve(1).run();
pxl::flushHostCache(results, resultBufSize);
Flush the search results before reading them on the host, flush host-written weights before launching the user kernel, and flush the results again before reading the updated scores.
pxl::Launcherautomatically synchronizes only buffers it allocated itself.
Building the example package requires pxcc / pxcc++ on PATH.
Next Steps
- Writing XArith Kernels — Lower-level VPE vector primitives
- XVector API Reference — Full C API reference