Metadata-Version: 2.4
Name: mm-libtorch-encoder
Version: 0.2.23
License-File: native/DEEPSEEK_LICENSE
License-File: native/PILLOW_LICENSE
License-File: native/NEMOTRON_LICENSE
License-File: native/DLPACK_LICENSE
Summary: Native Rust/C++ multimodal encoder for a matching Torch runtime
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Requires-Dist: torch>=2.11

# Native Python integration

## Frontend expansion is authoritative

The frontend resolves every input, prepares its exact media plan, and calls
`planner.expand_prompt(...)` once before routing/context admission. The serving
adapter must transfer the resulting token IDs, positions, lengths, and identities
unchanged alongside the planned media. Prompt expansion is not part of worker
resolution or encoding.

Every `PlannedMedia` requires a frontend plan, exact metadata, and content:
`bytes` for proxied/inline inputs or a URL `str` for non-proxied remote inputs.
There is no unknown-content or unplanned state in this public container.
Worker resolution fetches URL bytes, applies the frontend's explicit image resize
setting if needed, and checks original source size, payload hash, and worker
preprocessing identity against the supplied plan. It does not create a replacement
plan or invoke prompt expansion. The returned item retains the exact transferred
plan, metadata, and segment objects; only its content becomes bytes. Mismatches
fail rather than changing the frontend's token count or segment layout.

Encoder output validation and tower-input preparation check the supplied plan;
they do not expand prompt tokens. When an `expected_plan` is supplied for CPU tower
inputs, that same plan object is retained after validation.

## Python-mode handoff with shared blob references

```python
from mm_libtorch_encoder import plan_from_python_mode

planned = await planner.async_plan_batch(requests, limits=limits)
data = planned.dump_python_mode()
assert data["items"][0]["content"] is planned[0].content

# Pass data to the serving transport's serializer; no intermediate bytes blob.
received = plan_from_python_mode(data)  # Also PlannedBatch.from_python_mode(data).
assert received[0].content is planned[0].content  # Same-process round trip.
received = await received.resolve(worker_planner)
encoded = await encoder.generate_async(received)
```

The dump contains only `dict`, `list`, `str`, `bytes`, `int`, `float`, `bool`, and
`None`. It creates metadata containers while retaining the exact existing `bytes`
and `str` objects. Completed items omit redundant original source URL/base64 data;
deferred items retain their source/settings. The loader reconstructs typed plans
and native segments, validates metadata consistency and content hashes, and borrows
Python byte buffers during native validation. Loading in the same process retains
the input media byte and string references.

This avoids an intermediate aggregated blob. Base64 decoding, initial native
boundary conversion, and the chosen transport may still allocate/copy buffers.
Processes/machines do not share Python object identity. The library exposes only
Python-mode dump/load for transfer.

`PlannedBatch` supports iteration, indexing and `len()`, and exposes `.items` and
`.limits`. URL-backed items retain settings and exact frontend metadata.
`.resolve()` keeps completed items, validates the transferred batch in Rust, and
accounts for completed source bytes with integers before downloading pending URLs.

## Typed request planning and cache

```python
from mm_libtorch_encoder import ImageOptions, ImageRequest, VideoRequest, AudioRequest, MediaLimits

limits = MediaLimits(max_images=8, max_videos=2, max_total_media_mb=64, timeout_sec=5)
planned = await planner.async_plan_batch(
    [ImageRequest(image_content, ImageOptions(max_pixels=1024 * 1024)),
     VideoRequest(video_content, settings={})],
    limits=limits,
    proxy_mm_payload_from_frontend_to_worker=True,
)
for item in planned:
    print(item.metadata.size_bytes, item.metadata.tokens, item.cache_hit)
    for segment in item.segments:
        print(segment.token_offset, segment.token_end, segment.tokens)
results = await encoder.generate_async(planned)
```

Content accepts bytes, HTTP(S) URLs, and base64 data URLs. The ordered results are
`PlannedMedia` for every modality, each with required `content` (`bytes` or URL
`str`), `plan`, `metadata`, and `segments`, plus `kind`, `settings`, and `cache_hit`.
`AudioRequest` uses the same API on an audio-capable checkpoint. Metadata reports original compressed source
bytes and exact embedding tokens. Video and audio content retain their original encoded source bytes; workers
decode them normally. Image options may resize content, while metadata always
retains the original source byte count.

Segments are modality-independent: an image, video, or audio source may produce
one or more. Each `PlannedSegment` exposes `token_offset`, `tokens`, and `token_end`,
describing its half-open range in the parent's combined embedding output. The sum
of segment token counts equals the parent token count. Current video groups fan
out into multiple segments; current audio planning yields one. Segment count is
never inferred from source modality, so future image/audio splitting fits the
same container. Segments share the parent payload and are not independently
decodable files. `Encoder.generate_async(planned)` still returns one combined
embedding result per original request. URL-backed handoffs already include exact segments; worker resolution validates
their bytes against the frontend plan.

The Rust pipeline validates request counts and byte limits, then performs at
most **16 concurrent async downloads per batch**, without creating 16 OS threads.
Frontend resolution always fetches remote media (or reuses a valid cache entry)
and computes exact sizes, token counts, segments and plans before routing.
`proxy_mm_payload_from_frontend_to_worker=True` returns encoded bytes in `.content`.
With `False`, `.content` is the original URL string for remote inputs, and bytes
for inline bytes/base64 inputs. Inline base64 is always decoded in the frontend.
The flag controls payload forwarding, never frontend download or planning.
On the worker, `await planned.resolve(worker_planner)` fetches URL-backed items
under the transferred policy and checks the exact frontend plan. Byte-backed
items are retained without another download. A worker may also use its cache.


Each planner owns a Rust cache bounded to 64 MiB and 1,024 entries with a 60-second
TTL. Keys include exact request content, settings, and checkpoint preprocessing;
URL entries expire because origin content can change. Cache hits still count
toward all request limits. `planner.clear_planning_cache()` invalidates the cache.
Rust sources, cached payloads, and plans use immutable shared ownership; decoding
and resizing allocate new buffers. Python/native conversion can still copy bytes.
No HEAD requests are issued. `MediaLimits(timeout_sec=5)` is the default maximum
elapsed time for **each individual remote download**, including DNS, redirects,
and response-body reading. The timer starts when a download gets a concurrency
slot. Queue wait, other downloads, inline base64 decoding, and CPU/GPU preprocessing
are excluded. There is no total batch deadline; multiple download waves may take
more than five seconds overall. A slow origin returns `media_fetch_timeout` (504)
and cancels the remaining downloads for that failed request.

Image settings currently support `ImageOptions` or `{"max_pixels": ...}`. Audio/video
settings currently use checkpoint defaults (`None` or `{}`); unsupported settings
are rejected rather than ignored.

## Deprecated batch planning API

`BatchPlan`, `MediaPlanner.prepare_batch()`, and `prepare_batch_async()` remain
available for compatibility and emit `DeprecationWarning`. They delegate to the
Rust-backed `async_plan_batch()` pipeline and return resolved media. Existing
`MediaSource`, raw bytes/data URLs, and `ResolvedMedia` inputs remain accepted.
Migrate to typed `ImageRequest` / `VideoRequest` / `AudioRequest` inputs and the
returned `PlannedBatch`. The legacy adapter does not restore binary serialization,
nullable plans, or a separate native planning implementation.

## Media limits

Images and video frames require width and height of at least 3 pixels and a
maximum aspect ratio of 20:1 in either orientation (20:1 and 1:20 are accepted).
This includes raw video dimensions, inline frames, and explicit resize outputs.

Raw videos also obey `MM_VIDEO_MAX_FPS=31`, `MM_VIDEO_MAX_PIXELS=2073600`
(1080p), and `MM_VIDEO_MAX_SECONDS=61`. These source admission limits are read once
per process, independently of model frame sampling. Use `8294400` pixels for 4K.
Existing decoded-frame and RGB-memory bounds still apply.

Counts cover the complete request. Byte budgets count compressed source bytes,
after base64 decoding for inline inputs, including audio in the aggregate budget.
`max_image_mb`, `max_video_mb`, and `max_audio_mb` accept integers or floats such as `50` or `0.5`;
one MB is 1,000,000 bytes, with fractional bytes rounded down. `max_total_media_mb` sets the cumulative budget for all modalities.
The byte-based configuration fields have been removed. MB limits also apply before processing and on planning-cache hits.
`None` leaves a configurable budget unrestricted; zero disables that allowance.
Existing native per-item, decoded-memory, duration, and work bounds still apply.
All counts and inline sizes are checked before network I/O. Up to sixteen remote
downloads run concurrently, with per-item caps and one shared atomic request byte budget.
The native fetcher checks Content-Length and charges every retained chunk to
the shared budget. Failure or caller cancellation aborts outstanding downloads.
Results retain input order. Bytes already in flight can arrive before cancellation;
the budget bounds accepted source bytes, rather than exact network traffic. These
budgets do not include JSON/base64 wire overhead.
The HTTP server retains its own request-body limit.

The `python` Cargo feature exposes the Rust/C++ encoder through PyO3. It shares
preprocessing and model execution with the HTTP server, but does not start a
server or compile its HTTP client, routing, and serialization dependencies.
`generate()` accepts image bytes or `ResolvedMedia` / `PlannedMedia` values for
images, video, and audio supported by the selected checkpoint, and returns owning
Torch tensors. Media resolution and model-specific preprocessing live in the library.

Video planning preserves the original encoded video bytes and content identity.
Workers decode and sample those bytes normally; no sampled RGB transport is
introduced. `MediaLimits` and `PlannedSegment` are immutable PyO3 classes backed by
Rust. Worker handoff uses the Python-mode data representation. Admission checks run before cache-key
hashing, with inline decoding and bulk hashing in a bounded blocking stage.

Frontend resolution and planning raise `MediaInputError` for invalid media and
`MediaProcessingError` for operational failures. Both expose `code`, `http_status`,
and `upstream_status` (when a download received an HTTP error). Invalid input and
origin 4xx responses map to 400; origin 429/5xx and transport failures map to 502;
download timeouts map to 504; internal preprocessing failures map to 500.
Specific media codes such as `video_duration_limit` survive native planning.
The serving harness rejects these errors before worker dispatch and includes the
code in the sanitized message because its Dynamo HTTP bridge carries only status
and message, not a separate media-code field.

```python
from mm_libtorch_encoder import Encoder

with Encoder("/models/glm53", "zai-org/GLM-5.3-Flash", device="cuda:0") as encoder:
    results = encoder.generate([first_image_bytes, second_image_bytes])
    for embeddings, metadata in results:
        # Actual BF16 Torch tensor on cuda:0, sharing the native allocation.
        print(embeddings.shape, metadata.grid_thws, metadata.mm_hash)
```

```python
from mm_libtorch_encoder import MediaPlanner, MediaResolver

media = MediaResolver(max_bytes=200 * 1024**2).resolve(video_bytes, kind="video_url")
planned = MediaPlanner("/models/glm53", "zai-org/GLM-5.3-Flash").prepare(media)
with Encoder("/models/glm53", "zai-org/GLM-5.3-Flash") as encoder:
    result = encoder.generate(planned)[0]
```

At startup, each image encoder replica warms four square source images
(4096×4096, 2048×2048, 1024×1024, 128×128) plus wide and tall images before
becoming ready. DeepSeek derives its aspect warmups from the checkpoint's patch,
downsample, and token budgets within the shared source-dimension limits: the
default configuration uses 3024×588 and 546×3066 and reaches the 1,024-token budget.
The wide case runs first. Other image families use 4096×256 and
256×4096, except Nemotron's 1024×512 and 512×1024 to respect its position-table
memory limit. Every image uses normal checkpoint preprocessing. These profiles
do not cover every model's maximum workload or every possible dynamic shape.
Audio warmup uses one second of silence and includes the vision profiles when
an auxiliary vision tower is present.
The HTTP server uses the same profiles on each worker before binding its listener.
`MM_ENCODER_WARMUP=0` disables startup warmup in both entry points. Additional
dynamic shapes can still allocate memory, so reserve headroom beyond the
post-warmup footprint.

### Async API (0.2.15)

The synchronous API remains available. Async counterparts use `pyo3-async-runtimes`
with a shared Tokio runtime, without the Python event loop's thread pool:

```python
media = await resolver.resolve_async(image_url)
planned = await planner.prepare_async(media, image_options=ImageOptions(max_pixels=1024 * 1024))
results = await encoder.generate_async(planned)
await encoder.close_async()
```

`prepare_inputs_async`, `prepare_tower_inputs_async`, and `encode_image_async`
are also available. `Encoder` supports `async with`; construction still loads
weights synchronously and should happen during startup. Cheap prompt-layout,
expansion, and cache-stat methods remain synchronous.

Downloads use async network I/O. GPU requests await capacity in a bounded native
queue and then await a completion channel, without a blocked thread per request.
GPU execution stays on the encoder's existing owner threads, with one queued job
per configured replica. Cancelled jobs are skipped before execution; already-running
GPU work finishes safely.

CPU planning/resizing and shutdown use Tokio's blocking pool, limited to eight
concurrent operations per process. Permits remain held until blocking work finishes,
even after cancellation. Cancellation also stops network downloads. Callers must still bound concurrent requests and media
bytes. Bytes and data URLs resolve inline; async methods preserve synchronous
validation, output ordering, and per-image options. Concurrent calls can use the
encoder's configured replicas; a single call does not introduce batching. If another
coroutine changes the current CUDA stream during an await, GPU outputs are copied
onto that stream to give the consumer allocator-owned storage. The usual unchanged-
stream path retains zero-copy DLPack outputs.

Version 0.2.12 includes image/video/audio generation through this API and Muse
execution in stable-ABI wheels. Qwen3.5 accepts temporal grids at the native tower
interface; encoded-video preprocessing and prompt framing remain unimplemented.
This library release does not establish full-model HTTP, KV-cache, or disaggregated
serving compatibility across SGLang, vLLM, and TRT-LLM.

Pass `expected_tokens=[first_length, second_length]` to `generate()` to validate
frontend-planned token counts against the final embedding rows. Supply one positive
integer per media item (a one-element iterable for a single bytes input). Invalid counts
or mismatched lengths raise `ValueError`; omitting the argument skips this check.

`generate()` returns a list of `ImageResult(tensor, metadata)` pairs in input
order, one per media item. A single bytes object is interpreted as an image. Each tensor owns
its storage independently of the result tuple and encoder; keeping a tensor
after deleting its result or closing the encoder is supported. The API does not
copy embeddings, serialize them, or move them to CPU. Treat tensor contents as
read-only; Torch does not enforce immutability.

`ImageMetadata` is a frozen dataclass with only immutable values: `model`,
`mm_hash`, `length`, `shape`, `dtype`, `device`, `strides` (in elements),
`embedding_offsets`, and `grid_thws`. It preserves crop boundaries and grid
rows from the model output. Only the small CPU metadata tensors are converted
to tuples. Metadata can be pickled independently; this API does not implement
cross-process tensor transport or shared CPU/memfd storage. Images are executed
sequentially, without automatic model batching.

The lower-level `encode_image(image_bytes)` interface remains available and
returns the original dictionary of named Torch tensors, including the integer
metadata tensors.

DeepSeek V4.1 Flash support is available in the published
[0.2.1 wheels](https://pypi.org/project/mm-libtorch-encoder/0.2.1/) (0.2.0
wheels do not include it):

```python
with Encoder("/models/deepseek-v41", "deepseek-ai/DeepSeek-V4.1-Flash") as encoder:
    tensor, metadata = encoder.generate(image_bytes)[0]
    print(metadata.length, metadata.grid_thws)
```

Its tensor contains the full image span, including start/end and row newline
embeddings. `metadata.length` is `ceil(h / 3) * (ceil(w / 3) + 1) + 2`, where
`(1, h, w)` is the returned ViT patch grid. It supports images; audio/video are
rejected. Local checkpoint aliases can select `family="deepseek41"` explicitly.

## Nemotron 3.5 Super VL images and video

Images are available from version **0.2.2** for BF16 and NVFP4 checkpoints.
Encoded-video preprocessing, prompt planning, and temporal projection require
**0.2.18** or newer and the checkpoint's `video_embedder.weight`.

```python
with Encoder(
    "/models/nemotron35",
    "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4",
    replicas_per_gpu=2,
) as encoder:
    tensor, metadata = encoder.generate(image_bytes)[0]
```

Keep `config.json` and `preprocessor_config.json` beside the encoder weights.
Local aliases can use `family="nemotron35"`. Images use `grid_thws=(1, h, w)`;
video uses `(t, h, w)`, where `t` counts temporal projection groups. Incomplete
groups repeat the final frame. The embedding length and HTTP `expected_tokens`
are `t * h * w / 4`, excluding text delimiters. Generate video with
`encoder.generate(video_bytes, kind="video_url")`. Frontend prompt expansion
retains the checkpoint's timestamped frame-group placeholders.
CUDA BF16/FP16 uses Torch Flash attention. Audio and extreme aspect ratios
exceeding the 256 MiB position workspace are rejected.

## Qwen3.5 images

Source builds support dense and MoE Qwen3.5 checkpoints with unquantized vision
weights under `model.visual.*`. Qwen3.5 support requires version 0.2.3 or newer.
Use the checkpoint's matching `preprocessor_config.json` and `config.json`:

```python
with Encoder("/models/qwen35", "Qwen/Qwen3.5-0.8B", family="qwen35") as encoder:
    tensor, metadata = encoder.generate(image_bytes)[0]
```

`grid_thws` retains the original `(1, h, w)` patch grid for the serving engine's
multimodal RoPE. The embedding length is `h * w / spatial_merge_size**2`.
Vision start/end tokens remain the tokenizer's responsibility; their embeddings
are not included. This implementation accepts images only and rejects videos.
Tiny upstream tower and processor fixtures exercise CPU parity; trained-weight
GPU parity has not yet been qualified.

## Image preprocessing memory limit

Across all model families, image preprocessing rejects packed patch payloads over
256 MB before resizing or allocating patches (HTTP 400 / `image_memory_limit`). Set
`MM_ENCODER_MAX_IMAGE_PATCH_MB` to a positive integer to adjust this limit in
both frontend and worker processes; MB means 1,000,000 bytes. Invalid settings
fail checkpoint setup. The count includes temporal repeats and patch padding.
At Inkling-Small's defaults this permits roughly 10.6 MP, depending on padding. Native
host/device copies and model activations require additional memory: this is a
per-image patch-payload cap, not a bound on total runtime memory. Shared decoded-image and request limits also apply.

## Inkling images and audio

Inkling-Small exposes a paired HMLP vision tower and dMel audio tower behind
the single `family="inkling"`. The encoder loads every tower enabled by the
checkpoint and dispatches each request by its media inputs; image and audio
requests share the same native encoder instance.

`MediaPlanner` validates both Inkling placeholders against `tokenizer.json` at setup.
Constructing `MediaModel` directly requires `tokenizer_vocab=tokenizer.get_vocab()`;
both placeholders must be present with distinct nonnegative IDs.
Disabled towers return HTTP 400 with `unsupported_modality`. Enabled processor
settings are validated when loading the checkpoint, even with warmup disabled.

```python
with Encoder(
    "/models/inkling-small", "thinkingmachines/Inkling-Small", family="inkling"
) as encoder:
    tensor, metadata = encoder.generate(image_bytes)[0]
    audio, audio_metadata = encoder.generate(audio_bytes, kind="audio_url")[0]
```

Images use the upstream processor's `size`/`resample`/`rescale_image_frac`
fields. The public Inkling-Small processor config does not set
`rescale_image_frac`, so images are not pre-scaled; declared factors use the
configured BICUBIC resampling mode; other resample modes are
rejected when a resize is required. `grid_thws` is the padded `(1, h, w)` patch grid and
each patch contributes one embedding row. Audio is decoded at its source rate,
mixed to mono, resampled to 16 kHz, and converted to 80-bin dMel tokens at
20 tokens/s. Video is rejected. Prompt expansion replaces only the template's
single image/audio placeholder token; `<|content_image|>`,
`<|content_audio_input|>`, `<|audio_end|>`, and `<|end_message|>` remain text
tokens.

## GPU replicas

`Encoder(..., replicas_per_gpu=N)` creates `N` persistent native workers on the
selected GPU. The default is `1`; the count must be an integer from `1` to `32`.
Larger counts are rejected before allocating queues or starting workers. Each
worker owns a separate copy of the model and installs its own pooled CUDA stream
before loading weights. Workers take jobs from one bounded queue. The optional
Foyer cache is shared by all replicas, with one disk writer and one cache budget.
`encoder.replicas_per_gpu` reports the configured count.

```python
from concurrent.futures import ThreadPoolExecutor
from mm_libtorch_encoder import Encoder

with Encoder("/models/kimi-k3", "moonshotai/Kimi-K3", replicas_per_gpu=2) as encoder:
    with ThreadPoolExecutor(max_workers=2) as callers:
        outputs = list(callers.map(encoder.encode_image, image_bytes_list))
```

Calls from different Python threads can execute on different replicas; a single
`generate(images)` call still processes its images sequentially and preserves
their order. This does not batch requests together. Startup waits for all model
loads and cleans up initialized workers if any load fails. `close()` drains
accepted calls, joins every worker, then closes the shared cache. Each replica
adds model weights and activation memory; throughput gains depend on the workload.
The HTTP server exposes the same count as `MM_ENCODER_REPLICAS_PER_GPU`.

## Sharing a GPU with prefill

Each worker executes at most one image at a time, so an instance can execute up
to `replicas_per_gpu` images concurrently. Its CUDA stream requests
`stream_priority=1` by default. The pinned LibTorch implementation clamps every
positive request to `0`, the lowest supported priority, so this default has the
same priority as the default Torch stream. It does not deprioritize encoding
relative to default-priority work. Lower numbers mean higher priority; negative
requests select higher-priority streams within the supported range. To favor
prefill, run the engine's model work on a higher-priority stream.

```python
import torch
from mm_libtorch_encoder import Encoder

encoder = Encoder("/models/glm53", "zai-org/GLM-5.3-Flash")  # Requests priority 1.
prefill_stream = torch.cuda.Stream(device="cuda:0", priority=-1)
print(encoder.stream_priority, prefill_stream.priority)  # Actual priorities after clamping.
# Integrate prefill_stream into the engine's own execution/graph lifecycle.
# Run encoder.generate(...) from a separate CPU thread for concurrent dispatch.
```

`encoder.stream_priority` and the `native_ready` log report the actual priority
selected by Torch. The worker installs its stream before loading weights;
ATen, attention, custom CUDA kernels and cuBLASLt use its current stream.
Concurrent Python callers share the instance's queue. Create one `Encoder` per
GPU and set `replicas_per_gpu` to control how many workers share that device.

Stream priority favors pending kernels; it does not preempt running kernels,
reserve SMs, or isolate memory bandwidth. See the
[CUDA scheduling documentation](https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/asynchronous-execution.html#stream-prioritization).
When the encoder is clamped to `0`, it shares the default stream's priority.
For stricter scheduling, the engine should defer calls to `generate()` while
prefill is busy; avoid deferring an image that the current prefill needs.
Existing engine CUDA graphs and auxiliary streams must be integrated by the
engine, rather than assuming that an outer Python stream context changes them.

Results are fenced on the encoder stream before return and registered with the
caller's consumer stream for allocator lifetime safety; the encoder does not
add a device-wide synchronization. Set the consumer stream context around
`generate()` when its GPU results will be consumed on a nondefault stream.
CPU cache hits skip GPU work entirely. A consumer uploading cached CPU results
still needs its normal copy/event dependencies.

## Optional Foyer CPU and disk cache

The same Rust implementation is bundled into the standalone HTTP server; its
[`MM_ENCODER_CACHE` setting](README.md#optional-output-cache) enables caching at
runtime. Both interfaces default to caching disabled.

```python
from mm_libtorch_encoder import CacheConfig, Encoder

with Encoder(
    "/models/glm53", "zai-org/GLM-5.3-Flash",
    cache=CacheConfig(
        memory_bytes=1024**3,
        disk_path="/cache/glm53-gpu0",
        disk_bytes=8 * 1024**3,
    ),
) as encoder:
    tensor, metadata = encoder.generate(image_bytes)[0]
    assert tensor.device.type == "cpu"
    print(encoder.cache_stats())
```

Caching is disabled by default. `CacheConfig(memory_bytes=...)` enables only the
CPU tier; configure both `disk_path` and `disk_bytes` for Foyer's hybrid cache.
With caching enabled, **all results are CPU tensors**, including misses. The
first request transfers embeddings from GPU into owned CPU storage. Memory hits
reuse that allocation without payload copies and skip preprocessing and GPU
execution. Tensor views keep their backing storage alive after cache eviction or
encoder shutdown. Clone tensors before modifying them: the cache shares their
contents and Torch does not enforce immutability. The metadata remains frozen.
Keep the CPU tensor alive until any asynchronous upload to a GPU has completed.

Disk writes serialize CPU bytes; disk reads allocate and reconstruct CPU tensors.
The disk path is not zero-copy and this does not implement memfd/worker transport.
Each disk directory allows one encoder writer at a time, enforced by a process
lock. Use separate paths for simultaneous encoder instances. `close()` waits for
Foyer's pending persistence work; cache read/close errors are counted and logged.
Read errors fall back to recomputation. The cache is disposable, not a durable
source of model results.

Keys include image content plus a namespace derived from the actual selected
encoder weights, model/processor configuration, native extension binary,
Torch/CUDA identity, GPU architecture/name and matmul precision. Hashing weights
adds one encoder-weight read at cache-enabled startup. Keep checkpoint files and
execution precision settings unchanged while the encoder is running.

`memory_bytes` limits byte-weighted cache retention, not total process RSS.
Outstanding tensors can keep evicted storage alive; `live_cpu_bytes_process`
reports live cached tensor payload across all encoders, including those external
references. Torch allocator retention, metadata, disk I/O buffers and transient
disk decoding allocations are additional memory. Request admission must bound
the number/size of outstanding results.

`max_entry_bytes` defaults to 256 MiB (up to 1 GiB). Larger results are returned
normally but bypass caching. Disk storage needs at least four blocks; each block
is `max_entry_bytes + 1 MiB`, rounded up to 4 KiB. One block-sized I/O buffer pool
is configured. Counters expose `memory_hits`, `disk_hits`, `misses`, `bypasses`,
`errors`, and `live_cpu_bytes_process`.

Checkpoint files must already be present. The host application handles fetching,
request admission, and batching. Each encoder owns its configured worker replicas;
Python releases the GIL while waiting. Create one instance per GPU inside the
serving process after process creation.
Instances reject calls after fork. `close()` drains accepted calls and releases
model ownership. Returned tensors retain their storage after the encoder closes.

The producer uses a private CUDA stream and fences execution before exporting
DLPack tensors. Allocations are recorded on the caller's current CUDA stream;
consume returned tensors on that stream, or synchronize before releasing them
when using another stream. Embeddings stay on the GPU, with no HTTP, MessagePack, base64, or
GPU-to-CPU output transfer. This first interface is synchronous; asynchronous
stream handoff is a future optimization. Encoding and the serving engine still
compete for GPU compute and memory, so reserve space for encoder weights and
outputs when sizing the engine's KV cache.

## Wheel and runtime boundary

The crate and Python package share a release version. `Cargo.toml` owns the version;
Maturin derives the wheel version through `project.dynamic` in `pyproject.toml`.
Update the crate version and its `Cargo.lock` entry together for each release.
Read the installed wheel version with
`importlib.metadata.version("mm-libtorch-encoder")`.

The wheel builder reads the installed Torch SDK, CUDA version and C++ ABI instead
of pinning a single engine runtime. Each wheel records its Torch version/source
revision/build configuration, CUDA version, C++ ABI, machine architecture and
libc version. Build and final engine stages must retain compatible system C++
libraries; the intended recipe builds inside the engine's own SDK environment.
The Python adapter verifies this manifest before importing native code. CPython
3.11+ uses the abi3 extension. Exact engine images still require qualification;
matching metadata alone does not establish model correctness or performance.

| Component | Packaging |
| --- | --- |
| Rust and our C++ bridge/model code | Compiled into the extension |
| Custom CUDA DSO and restricted media libraries | Bundled in the wheel with private repaired library names |
| Torch/ATen, CUDA runtime and NVIDIA math libraries | Dynamically linked to the matching host installation |
| NVIDIA driver | Supplied by the host |
| Model weights | Supplied on disk, outside the wheel |

A wheel can bundle shared libraries: static linking is not required for a single
pip-installable artifact. Static linking a second Torch runtime would not provide
process isolation for its dispatcher, allocator, and CUDA dependencies. Sharing
the host runtime is the intended in-process contract. Images with a different
Torch/CUDA stack require a separately built and qualified matching wheel.

Build inside each engine's SDK environment with Rust 1.93+, a C++20 compiler,
the restricted media libraries from the Dockerfile, and an NVCC toolkit matching
that engine's `torch.version.cuda`. Runtime-only images may need these build tools
in a separate builder stage. CUDA 12 split NVIDIA wheel headers and CUDA 13's
unified layout are both discovered by the builder:

```sh
python -m pip install maturin==1.12.6 patchelf==0.19.1.0 auditwheel==6.6.0 cmake==3.31.6
export CUDA_HOME=/path/to/matching/cuda
export FFMPEG_DIR=/path/to/restricted/media
python python/build_wheel.py
```

The build script selects the installed Torch SDK, builds the extension, and repairs
media/kernel dependencies into `dist/<runtime-key>/`. Compiler caches are also
separated by runtime key so changing Torch at the same SDK path cannot reuse
incompatible compiled objects. Torch and NVIDIA libraries are explicitly
excluded. The artifact keeps a Linux platform tag because its runtime contract
extends beyond manylinux's system-library baseline. Install the resulting wheel
into the qualified engine image using the local wheel selector:

```sh
python python/install_wheel.py /path/to/wheelhouse
```

The selector inspects embedded manifests and requires exactly one matching wheel,
then installs with `--no-deps`. It neither downloads code nor replaces Torch.
Collect runtime-specific `dist/` subdirectories in one wheelhouse for SGLang,
vLLM and TRT-LLM images; each image selects its own implementation at build time.
A missing match requires compiling and qualifying a wheel in that engine's SDK
build environment. Use separate source checkouts for concurrent runtime builds,
because the builder writes a generated package manifest. Runtime startup only
loads the selected extension; it does not compile anything.

Media decoding retains the server's size bounds and decoder restrictions. It
runs in the host process with that process's privileges; this integration does
not add a security isolation boundary.

## Validation so far

A repaired wheel was installed in the matching Python 3.12/Torch 2.14.1 CUDA 13
SDK container and exercised on an H100 with trained GLM5.3 weights. The smoke
covers BF16 GPU output, repeatability with two Python caller threads, malformed
image recovery, delayed consumer-stream work, and output ownership after close.
Installing that CUDA 13 wheel in the Torch 2.11/CUDA 12.9 image was rejected
before native import; building a matching wheel for the older image passed.
All 18 existing server library tests passed after the shared-module extraction.

This establishes the packaging and ownership path, not production throughput
or a new accuracy/performance comparison for every model family. The smoke is runnable as
`python python/tests/smoke.py /models/glm53` after installing the wheel.

## Compiled PyPI releases

Manual runs of `mm-standalone-encoder.yml` also build compiled AMD64 and ARM64
wheels against the pinned Torch 2.14.1/CUDA 13 SDK. The `encoder-wheel-amd64` and
`encoder-wheel-arm64` artifacts contain only `.whl` files; no source distribution
is built or uploaded. The Rust/C++/CUDA implementation and media libraries are
compiled into the wheel alongside the Python interface. Torch, CUDA libraries,
the driver, and model weights remain external.

These public wheels use CPython 3.11+ abi3 and audited `manylinux_2_35` tags.
The upcoming 0.2.8 stable-ABI release adds prompt expansion, video timestamps,
image framing metadata, and CPU preprocessing inputs. It requires glibc 2.35 or newer and `torch>=2.11`;
startup additionally checks CUDA 13.0 and CPU architecture. Muse is excluded
from this release. The 0.2.5 wheels retain the exact Torch 2.14.1 build check
and Muse support. Other CUDA runtimes still need their own qualified wheels.

### Publish from the release workflow

To enable publishing, configure a PyPI Trusted Publisher for project
`mm-libtorch-encoder`, GitHub owner `basetenlabs`, repository `baseten`, workflow
`mm-standalone-encoder.yml`, and environment `pypi`. For the first release of a
new project, create a [pending publisher](https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/)
from your [PyPI publishing settings](https://pypi.org/manage/account/publishing/)
using those same fields. The first successful upload creates the project.
For an existing project, add the publisher in that project's Publishing settings.
CI authenticates with GitHub OIDC; no PyPI API token is needed in GitHub secrets.
Then dispatch the same image/wheel release workflow from your local machine:

```sh
gh workflow run mm-standalone-encoder.yml --repo basetenlabs/baseten --ref master \
  -F publish_pypi=true -F stable_abi=true
```

The publish job uploads only compiled wheel artifacts after both architecture
builds, CPU tests, sanitizer checks, native import checks, wheel validation, and
trained GPU execution of the release wheel pass. Stable wheel builds always run
this GPU gate, including attention, DLPack ownership, and cache regressions.
Standalone image publication is independent (`publish_image=true`). Opt into its
HTTP GPU cache qualification with `qualify_standalone=true` and `publish_image=true`;
it does not gate wheel publication. Engine-specific Python GPU qualification remains
available through `qualify_python=true`. Publishing is disabled by default.
Bump `Cargo.toml` and `Cargo.lock` together before each new PyPI version; PyPI
does not allow replacing existing release files.

### Publish built wheels from a local machine

You can also upload the built wheels directly from a laptop. Download both
architecture wheels into one directory, such as `./encoder-wheelhouse/`.
Uploading does not import the extension or compile code, so the publishing
machine does not need Linux, Torch, CUDA, Rust, or the model weights.

Create a [PyPI API token](https://pypi.org/manage/account/token/) authorized to
publish `mm-libtorch-encoder`. The first upload of a new project requires an
account-scoped token; once the project exists, a project-scoped token can be used.
Run [Twine](https://twine.readthedocs.io/en/stable/) in a separate environment:

```sh
python3 -m venv /tmp/mm-encoder-publish
/tmp/mm-encoder-publish/bin/python -m pip install twine==6.2.0
/tmp/mm-encoder-publish/bin/python -m twine check --strict ./encoder-wheelhouse/*.whl
/tmp/mm-encoder-publish/bin/python -m twine upload --username __token__ ./encoder-wheelhouse/*.whl
```

Twine prompts for the API token as the password. These commands upload only
`.whl` files, including both AMD64 and ARM64; no source distribution is uploaded.
On Windows, use the publishing environment's `Scripts/python.exe` path instead
of `bin/python`. A repeated upload of an existing filename is rejected; bump
the package version and rebuild for the next release.

### Install in a serving image

Install into a serving image that already has the matching CUDA Torch runtime:

```sh
pip install --no-deps --only-binary=:all: mm-libtorch-encoder==0.2.7
```

## Engine-image qualification

Manually dispatch `.github/workflows/mm-standalone-encoder.yml` with
`qualify_python=true` on the native
encoder branch to qualify the SGLang, vLLM and TRT-LLM images pinned by the
repository's `versions/<engine>.env` files. The matrix resolves image tags to
immutable digests, builds a wheel with `Dockerfile.python`, and checks loading in
the original engine image. Each artifact includes that digest and its wheel.
After all three wheels build, a serialized B200 job installs each wheel in its
original engine image, imports that engine, and runs the trained GLM smoke. It
downloads only the pinned vision checkpoint subset and uses the shared node GPU
mutex. This tests native inference with engine imports in the same process;
full serving-engine model execution and production throughput still require
target-deployment qualification.

[CI run 38857534601](https://github.com/basetenlabs/baseten/actions/runs/38857534601)
passed wheel builds, original-image imports, the B200 trained GLM smoke for all
three engines, and the standalone server checks. The artifacts record the exact
base-image digests and runtime manifests; wheels are approximately 5.8 MB and
contain neither Torch nor CUDA runtime libraries.

| Engine image | Bundled Torch | CUDA | Build, import, GPU smoke |
| --- | --- | --- | --- |
| SGLang nightly `a6a8c560` | `2.14.1+cu130` | 13.0 | Passed |
| vLLM `v0.26.0` | `2.11.0+cu130` | 13.0 | Passed |
| TRT-LLM `9442083b7d` | `2.14.0a0+4fdf77b940.nv26.08` | 13.4 | Passed |

These results cover Linux x86_64. ARM64 builds have not been qualified. The GPU
smoke imports each engine in the encoder process but does not load an LLM or
exercise that engine's scheduler, CUDA graphs, or custom memory allocator.

Local H100 validation also covered a Torch 2.11.0/CUDA 12.9 build. On three GLM5.3
image geometries (224x224, 319x257, 672x448), two outputs matched the Torch
2.14.1/CUDA 13.0 build bitwise; the third had cosine similarity 0.99999958,
relative L2 error 0.000916, and maximum absolute difference 0.0004883. These are
small synthetic-image checks, not a replacement for the trained-model corpus.

## Experimental stable Torch ABI

The 0.2.7 Python release uses the stable ABI and excludes Muse. Use 0.2.5 for
the existing Muse Python integration. The standalone server and default source
build retain Muse support. To produce stable wheels through CI, set
`stable_abi=true` on `mm-standalone-encoder.yml`; direct Docker builds accept
`--build-arg STABLE_ABI=true`.

`python/build_wheel.py --stable-abi` builds an opt-in vision-only wheel using the
Torch 2.11 C ABI. Its runtime manifest accepts Torch 2.11 and newer builds while
still requiring the recorded CUDA version, CPU architecture, and libc policy.
The existing runtime-matched build remains the default. Do not publish this
variant under an existing release version.

Cross-runtime checks cover Torch 2.11.0, 2.13.0, 2.14.1, and
2.15.0.dev20261005 with CUDA 13.0. The 2.15 nightly passed real GLM5.3 encoding
with concurrent replicas and the native ownership, resize, and stream checks.
Torch 2.11 passed trained DeepSeek and GLM encoding, attention rejection/recovery,
and side-stream output lifetime checks with the 2.11 ABI target.
Accepting newer versions is a compatibility policy, not a claim that each release
has been tested: boxed dispatcher operations have weaker compatibility guarantees
than the [stable C ABI](https://docs.pytorch.org/docs/main/notes/libtorch_stable_abi.html).

For native development, set `MM_TORCH_STABLE_ABI=1` for Cargo or
`-DMM_TORCH_STABLE_ABI=ON` for CMake. Supported factories are GLM5.3, DeepSeek4.1,
Qwen3.5, Kimi, Nemotron3.5, and Inkling. Muse is rejected before loading weights because
its bundled FlashAttention library still depends on the Torch C++ ABI.

The adapter uses C shims and boxed dispatcher calls. Scalar arguments are not
supported by the stable dispatcher, so scalar math uses tensor operands or
existing typed C shims. Integer addition uses an exact integer reduction;
range construction uses CPU storage followed by a device transfer. These paths
need end-to-end performance qualification before replacing the default build.
CUDA attention uses Torch's backend selection and accepts FlashAttention,
memory-efficient attention, or cuDNN attention. If only math attention is
available, it fails before allocating a quadratic attention matrix. DeepSeek
requires the reference's 3D SDPA rounding: when that layout selects math, it
processes at most 64 query rows at a time, so score storage grows linearly with
the key-token count. This path trades kernel-launch overhead for trained BF16
parity on Torch 2.13. CPU execution continues to support math attention for
fixture tests.

DLPack exports retain the original tensor. CUDA exports fence their device on
release because consumers can use additional streams and the stable API does not
expose allocator stream recording. This can block deletion and wait for unrelated
GPU work. Set Torch CPU threads before starting the
encoder; the stable build validates the requested count rather than changing it.
The independent DLPack header is from dmlc/dlpack v1.2; see `native/DLPACK_LICENSE`.

Run the existing DeepSeek, Qwen, and Nemotron golden tests with the stable build,
then run the same executables with the other runtime's library directory on
`LD_LIBRARY_PATH`. Set `MM_TEST_DEVICE=cuda:0` to repeat their numeric and invalid
input checks on CUDA. For the CMake library's ownership and stream checks:

```bash
MM_STABLE_LIBRARY=/path/to/libmm_encoder.so python native/tests/stable_abi.py
```

A full production qualification still needs the exact NVIDIA TRT-LLM Torch build,
ARM64 execution, and realistic image batches. This option does not enable the
encoder in TRT-LLM serving images.

