Antfly Inference

The model runtime inside Antfly, what it runs, and how to pull and configure models for it

Beginner10 min
inferenceembeddingsrerankingmodels
Prerequisites
  • Antfly installed and running

Antfly Inference is the model runtime inside Antfly. It runs embedding, chunking, reranking, extraction, decision, transcription, reading, and generation models (text generation from text, image, and audio prompts) on the same machine as the database, with no external API and nothing leaving the host. It executes GGUF, safetensors, and ONNX artifacts on its own native backend (CPU, Metal on macOS, CUDA in CUDA builds); ONNX graphs are parsed and run on Antfly's kernels, with no external ONNX runtime. The decision it puts in front of you is which model to pull for each job; the Local Model Compatibility page holds the verified list, and this page covers how the runtime finds, stores, and serves them.

For the v0.3.0 development source documented here, standalone public inference requires an explicit opt-in before calling /ai/v1. Save antfly.json:

{"public_inference": {"enabled": true}}
antfly standalone --config antfly.json

There is no enablement CLI flag. Without this setting, /ai/v1/models still lists the installed models, marked invocable: false, but public execution returns HTTP 403. See the public execution policy. This prerequisite applies to database API nodes on this source version; the independent antfly inference run listener and older stable releases have their own policies.

Pull a model, then embed a sentence through the running engine:

antfly inference pull hf:google/embeddinggemma-2:bf16-safetensors-bundle-v1

curl -X POST http://127.0.0.1:8080/ai/v1/embed \
  -H "Content-Type: application/json" \
  -d '{"model":"google/embeddinggemma-2:bf16-safetensors-bundle-v1","input":["a photograph of a lighthouse"]}'

The response is a 768-dimension vector in the OpenAI embeddings shape ({"object":"list","data":[{"embedding":[...]}]}).

Where It Listens#

In standalone mode the runtime is served on the API port under /ai/v1, beside /db/v1. Run as its own process with antfly inference run, it listens on 127.0.0.1:8090 by default, and a database points at it with the inference.api_url config key. External providers (Ollama, OpenAI, Bedrock) plug into the same embedder, reranker, and generator interfaces, so an index config names a provider and a model and never cares which process answers.

In a CPU-only build, standalone runs models inside the database process. A build that includes a GPU or driver-backed backend (Metal, which is on by default on macOS, or CUDA or PJRT) starts a supervised child worker (antfly inference _worker) at startup and sends all embedded inference to it, CPU models included. A driver call cannot be interrupted safely, so a wedged or crashed worker is killed and respawned without taking the database down.

Setting inference.api_url disables embedded inference. It is not a fallback. Standalone then keeps no embedded provider, loads no preloads, and serves no /ai/v1 routes on its own port, and every provider: antfly call goes to that URL. antfly inference run refuses a non-loopback --host unless you also pass --allow-insecure-public-bind, because the listener has no built-in auth or TLS.

Configuring a Separate Inference Process#

antfly inference run --config inference.json reads model settings under inference and resource policy under resources:

{
  "inference": {
    "models_dir": "/models",
    "max_loaded_models": 3,
    "keep_alive": "5m",
    "preload": [
      {"kind": "embedder", "name": "BAAI/bge-small-en-v1.5", "backend": "native"}
    ]
  },
  "resources": {"inference": {"admission": {"max_concurrent_requests": 8}}}
}

Pull the referenced models into models_dir before starting the process. CLI flags override the file; see the inference runtime reference for every setting, preload rules, and migrating older flat configs.

Inference-Only Executable#

From the zig/ directory, build and start antfly-inference:

zig build inference-artifact -Doptimize=ReleaseFast
zig-out/bin/antfly-inference run --config inference.json

The executable serves the same routes as antfly inference run. Use /ai/v1 for embeddings, generation, reranking, reading, and other inference operations. Both /ai/v1 and /ml/v1 expose OpenAI-compatible /embeddings and /chat/completions routes. Use /ml/v1 for traditional ML predictors and metrics, and /healthz and /readyz for operational probes.

Models installed in the runtime can serve these operations. The listener also accepts configured OpenAI-compatible image readers for /ai/v1/read, including llama.cpp-backed LightOnOCR. The database API gateway provides additional named provider and connection routing.

Pulling Models#

Models come from Hugging Face by their full owner/name reference. Pull rejects all bare names and friendly aliases. The hf: prefix is accepted. Append @revision to request a branch, tag, or commit; omit it to use main. Each pull resolves one immutable snapshot for all files. See Model Downloads for format selection and revision examples.

antfly inference pull hf:BAAI/bge-small-en-v1.5 --tasks embed
antfly inference pull hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF:gguf:Q8_0 --tasks rerank
antfly inference pull hf:ggml-org/gemma-4-E4B-it-GGUF:gguf:Q4_0 --tasks generate --projector auto

Pull publishes the model atomically, and the running process discovers it on the next model-list or inference request. No restart or refresh call is needed. The Antfarm dashboard refreshes its model list about every 30 seconds, so allow up to a minute for a newly pulled model to appear there.

--tasks records what the model is for, which decides where it is discovered and which endpoints serve it. Text generation supports a specific set of decoder architectures, so check Local Model Compatibility before pulling a generator.

--projector auto is the default. Gemma 4's unified projector enables image and audio inputs and is recorded in the generated model manifest. Use --projector none for a text-only installation.

On Apple silicon the Gemma 4 audio encoder runs on Metal end to end: the log-mel front end is two BLAS matrix products, and from the convolutional subsampler through the conformer blocks (clamped projections, chunked local attention with relative position bias, gated depthwise convolution) to the output projection every op executes as a device kernel inside one command buffer. The projector's tensors are served from the session's resident copies and the projector file is parsed once per model rather than per request. A 2.5-second clip encodes in about 50 ms on an M-series laptop, and the audio prompt tokens then flow through the same framed prefill as text. Set TERMITE_SERVER_GENERATE_TIMING=1 to log the multimodal_prepare, prefill and decode split for each request, and TERMITE_GEMMA4_AUDIO_METAL_PROFILE=1 to print the encoder's per-stage GPU time for each clip.

Verified starting points, one per job. Start with the first model, which runs well on a laptop, and move to the second for quality:

JobStart withFor quality
Embedding (text, image, audio, video)google/embeddinggemma-2:bf16-safetensors-bundle-v1
Rerankingggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF:gguf:Q8_0
Generationggml-org/gemma-4-E4B-it-GGUFgoogle/gemma-4-E4B-it-qat-q4_0-gguf
Transcriptionopenai/whisper-tinyantflydb/whisper-large-v3-turbo:gguf:Q8_0
Reading and OCRlightonai/LightOnOCR-3-0.8Blightonai/LightOnOCR-3-4B
Extractionfastino/gliner2.5-base-v1
Classificationfastino/gliner2.5-base-v1fastino/GLiNER2.5-Decide

Local Model Compatibility has the pull command for each.

See what is installed:

antfly inference list

The full registry, with descriptions and sizes, is the models browser.

Variants#

A variant appended to the reference selects an artifact format or quantization. The advertised variants are gguf, gguf:<quant> (for example gguf:Q4_K), onnx, hybrid, and safetensors; i8 and f32 are still recognized and select among the ONNX artifacts:

antfly inference pull hf:BAAI/bge-small-en-v1.5:i8 --tasks embed

With no variant the pull is auto. Keep one variant per model directory: a second variant pulled beside the first leaves both in place, and different parts of a model can then resolve to different variants. If a model misbehaves after a second pull, delete the directory and pull once.

Local Gemma4 Video Prompts#

Gemma 4 generation accepts one video alongside text when the model has its matching vision projector. For example, to describe a local MP4 file, run

antfly inference generate /models/gemma4 'Describe this video.' \
  --video clip.mp4 --backend cuda --max-tokens 128 --disable-thinking

The CLI, native generation library, and inference gateway support video. Named gateway targets declare video: supported under inference_capabilities. Audio tracks in the clip are ignored. Each selected frame contributes up to 70 visual tokens. The model targets one frame per second in presentation order and uniformly spaces up to 32 targets across the clip. MP4 edit bounds apply.

On Linux, the CUDA path uses NVDEC for compatible progressive H.264, HEVC and AV1 MP4 files. Its limits include 256 MiB, 60 seconds, 18,000 samples and 4096 pixels per coded axis. The GPU must also support the clip's codec, bit depth and dimensions. NVIDIA containers should expose the driver's video capability alongside compute and utility. The runtime uses checked-in CUDA kernels.

When NVDEC is unavailable or a clip falls outside its decoder envelope, the runtime tries the host's portable decoding route under the request's memory budget. Projection still runs on the selected backend. HEVC requires NVDEC or VideoToolbox. See the inference gateway reference for supported inputs and host-specific decoder requirements.

Model Storage#

Models live under $ANTFLY_INFERENCE_MODELS_DIR, else ~/.antfly/inference/models; --models-dir overrides both. A variant-less pull installs flat under the HuggingFace owner and repository name:

~/.antfly/inference/models/
  BAAI/bge-small-en-v1.5/

An explicit variant gets its own distinct leaf directory beside the plain one, so quantizations cannot be mixed accidentally. Older per-task subdirectories (embedders/, chunkers/, rerankers/, generators/) are still discovered. Antfly Inference discovers what it finds there. A model loads on its first request unless it is listed in preload or --preload-model.

Traditional ML predictors use the parallel ~/.antfly/inference/ml/ directory; --ml-dir overrides it. Neither inference asset directory follows the database --data-dir implicitly.

Naming a Model in an Index or Query#

The provider name is antfly. The same three shapes appear in table, index, and query configs:

{ "provider": "antfly", "model": "BAAI/bge-small-en-v1.5" }

The API uses one EmbedderProvider and one canonical EmbedderConfig across inference features. Index creation accepts the purpose-specific IndexEmbedderConfig subset (antfly, ollama, openai, openrouter, cohere, gemini, vertex, or bedrock), so generated clients cannot advertise providers that the indexing runtime cannot execute.

{ "provider": "antfly", "model": "ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF:gguf:Q8_0", "field": "body" }

Reranking supports antfly, cohere, and vertex. Ollama reranking is not advertised because Antfly does not implement a compatible Ollama rerank API.

{ "provider": "antfly", "model": "fixed_bert", "text": { "target_tokens": 512, "overlap_tokens": 50 } }

The chunkers fixed_bert and fixed_bpe are built in and need no download. Chunk sizing nests under text, and target_tokens must be larger than overlap_tokens or the request fails with InvalidChunkOverlap.

Capacity, Admission, and Memory#

  • Request admission. At most 32 concurrent inference requests by default (resources.inference.admission.max_concurrent_requests).
  • Model residency. Up to 10 models stay loaded (max_loaded_models); idle models unload after keep_alive (default 5m).
  • Memory. Model loads and requests reserve memory from one process envelope shared with storage and caches. Set it with --process-memory-budget-mb or ANTFLY_PROCESS_MEMORY_BUDGET_MB; otherwise the cgroup or host limit applies. A request that can never fit returns MODEL_RESOURCE_LIMIT; temporary contention returns MODEL_RESOURCE_BUSY.
  • Query priority. Background enrichment yields to query-time work in the same database process. Embedding backfill pauses (up to 5 s) while a query-time embed is running, and background generation pauses while an interactive generate or chat request is in flight. Backfill that receives 503 retries with backoff.

Admission checks every request limit before considering contention. A request that exceeds its own scratch, KV, backend, host, or combined limit fails permanently even when another model currently occupies memory. Feasible requests may reclaim idle models and caches before returning a retryable capacity refusal.

Default CPU and Metal host budgets use the shared safe host pool; on Metal, host and device allocations also share a combined unified-memory cap. Lazy media encoders must fit alongside their required resident model. Explicit --host-budget-mb and other budget overrides remain hard caps.

CPU scratch defaults to one quarter of the safe host pool (with a 256 MiB tuning floor, always clamped to that pool). It scales with the effective process/cgroup limit instead of stopping at 1 GiB. This is a ceiling for actual reservations, not memory allocated at startup. Host and combined limits still constrain the sum of weights, KV and scratch across concurrent requests. An explicit resources.inference.memory.max_scratch_bytes overrides the automatic value.

For a bounded CPU media worker, start with a 32 GiB process envelope and one concurrent request. A reproducible fixed policy can set a 4 GiB scratch cap:

{
  "resources": {
    "memory": {"max_bytes": 34359738368},
    "inference": {
      "admission": {"max_concurrent_requests": 1, "max_work_units": 64},
      "request_limits": {"max_decoded_pixels_per_batch": 4000000},
      "memory": {"max_scratch_bytes": 4294967296}
    }
  }
}

These are workload starting points, not a promise that every page, clip or model fits. Keep request/output ceilings and deadlines bounded; measure the actual checkpoint and geometry before enabling a CPU fallback. Changing the number of CPU threads does not change the memory envelope. The CPU media verification procedure records complete /read results, first-use and warm timings, checkpoint/library hashes, and request cancellation recovery.

Feasibility includes the model's live session and tokenizer leases in their original CPU or GPU domains. Releasing an optional component removes it from the required working set. Incremental preprocessing checks the cumulative memory owned by that request, while charging only its new allocations. Failed trial reservations remain local to their retrying operation; successful fallbacks do not overwrite another operation’s terminal diagnostic.

Generation requests that exceed a stable budget return HTTP 400 with retryable: false, the blocking budget, required_bytes (including required resident resources), and limit_bytes. These diagnostics also cover lazy model/component loads and incremental media preprocessing. A checkpoint resume includes its held upload/decode reservation when checking whether execution can fit; that reservation is not charged twice. After streaming headers have been sent, permanent budget failures use the same JSON fields in an SSE error event and close without [DONE]. SDK stream readers preserve these fields and continue to accept legacy plain-text error events.

Both permanent and temporary memory-admission failures record the error identity, requested bytes, current reservations, and configured limits in the inference process logs. For MODEL_RESOURCE_LIMIT, inspect the inference run admission denied and inference run admission request records before changing budgets. A loaded model's RSS does not include all request scratch or preprocessing memory. The process envelope and live host/cgroup capacity apply in addition to the individual inference budgets.

Native EmbeddingGemma text execution lets physical temporary allocations consume its prepaid workspace, reserving only additional bytes. The 512 MiB temporary-allocation ceiling is a guard, not an upfront reservation. Retained output buffers keep their admission when an execution phase finishes. Cumulative scratch owned by one request is checked against the policy separately from other requests' occupancy.

The inference runtime reference covers weighted work admission, request ceilings, and the model-instance API.

Loading models in Antfarm#

Antfarm's Models page shows whether a local model is available, loading, loaded, or in use. Load model warms the same cache used by ordinary inference. Unload releases an idle model; it does not delete downloaded files. These are dashboard controls, not public model-instance resources or SDK operations.

The controls affect the shared local inference process, not just the current browser tab. Loading does not pin weights: normal idle and memory-pressure eviction still applies. Loaded models may use streamed or backend-managed weights rather than full GPU residency. Models that are loading, serving requests, or managed by startup preload configuration cannot be unloaded from the dashboard.

When to Split Inference Out#

Embedded inference suits a single machine and models that fit comfortably beside the database's caches. Run antfly inference run (or an operator InferencePool) and point inference.api_url at it when:

  • models are large enough to crowd the database's memory envelope
  • you want to scale or restart GPU capacity independently of storage
  • several database nodes should share one pool of loaded models

Query-over-backfill priority applies within one database process. Admission and memory limits apply within one inference process.

When Enrichment Falls Behind#

An embeddings index reports its own backlog. Inspect it while enrichment is pending:

curl http://127.0.0.1:8080/db/v1/tables/TABLE/indexes/INDEX

The enrichment_runtime object carries sequence progress, retry and failure counters, the active batch, and worker lifecycle state. worker_started says whether the background worker is running. stalled is the narrower condition: work is pending, no retry or terminal failure already explains the backlog, and either no worker is running or the active batch has passed its deadline without progress. stall_reason says which (worker_missing, model_loading, embedding_overdue, or publishing_overdue).

During capacity contention, retrying: true, last_error_code: "EmbedAdmissionRefused" (or ResourceTemporarilyUnavailable), and next_retry_at_ms explain the wait. Admission refusals do not consume the provider-failure attempt budget. A separate ceiling allows 16 admission attempts for the same request, approximately five minutes of capped backoff excluding execution time. That counter survives restart. Persistent refusals then become terminal repair debt, preserving the underlying error; they do not retry indefinitely. Once capacity or configuration is corrected, run a bounded repair pass for the affected documents.

Index creation preserves permanent inference-budget failures as HTTP 400 MODEL_RESOURCE_LIMIT with retryable: false; a temporarily unavailable validation probe remains HTTP 503 with a retry hint. Query hierarchy validation reports a JSON pointer and a reason when grouped matches omit fields or child navigation uses an invalid order_by.

For keys that have reached the durable repair queues, ask the bounded operator endpoint:

curl -X POST http://127.0.0.1:8080/db/v1/tables/TABLE/repair/issues \
  -H 'Content-Type: application/json' \
  -d '{"target":"artifact","limit":100}'

It lists durable repair issues, not every document in the pending tail. Pending work with no listed issue means the cause is a worker lifecycle problem or inference that is still retrying; the runtime counters and server logs tell those apart.

Use Agent Skills#

Everything above is also encoded in the Antfly skill, so a coding agent can execute this guide for you:

npx skills add antflydb/antfly-skills

Then prompt it with the outcome, for example "Set up local embeddings and reranking with Antfly Inference and wire them into my table's index", and use this page to judge the result.

Next Steps#