Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions changelog.d/gemma-image-feature-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
### Gemma image feature cache

- Add opt-in, bounded RAM reuse of evaluated Gemma still-image encoder features within a loaded model and authenticated vision scope. Repeated images skip the tower/projector while current text and image ordering retain their own prompt and spans.
- Charge pending snapshots, hashing/hydration scratch and pinned readers against process, slot and scope budgets, with scope-aware eviction, expiry and lifecycle fences. Shutdown cancels owned preparations before draining; invalid requests preserve committed entries. Missing scope or budget and unsupported adapters remain uncached.
- Add optional `vision_cache_scope` metadata and bounded image-work profile counters. Feature hits do not reduce prompt/KV token usage or produce prefix-cache credit. Default activation and performance claims await actual-model qualification.
3 changes: 2 additions & 1 deletion docs/architecture/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider And Native Architecture

> Last updated: 2026-11-06
> Last updated: 2026-11-09

Provider execution, local security and external contracts. Backend and console implementation live in [platform architecture](https://github.com/Layr-Labs/darkbloom-platform/tree/48a198c71a2d30feec5597bacf1101120f7f955d/docs/architecture).

Expand All @@ -11,6 +11,7 @@ Provider execution, local security and external contracts. Backend and console i
- [Landing public HTML, Markdown, pricing and API discovery](components/landing.md)
- [Hardware support and the provider memory model](hardware-support.md)
- [Provider inference engine](inference.md)
- [Gemma image feature cache: ownership and qualification](image-feature-cache.md)
- [Provider Autopilot](model-autopilot.md)
- [Provider Model Registry Boundary](model-registry.md)
- [Model artifact revisions](model-revisions.md)
Expand Down
10 changes: 10 additions & 0 deletions docs/architecture/hardware-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -1467,3 +1467,13 @@ memory is free. Admission limits and native memory guards are unchanged. See
[planned cluster stop ordering](inference.md#planned-cluster-stop-ordering) and
`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift`
(`ClusterService.stopLocalPart`).

## Image feature host ownership

The optional [Gemma image feature cache](image-feature-cache.md) uses the existing
`GlobalKVCacheBudget.processLedger` for host Data, with no materialized MLX credit.
Persistent features and bounded hash/hydration scratch reserve before allocation;
pending and pinned retired bytes stay charged across eviction and shutdown.
This does not change OS reserves, activation floors, LOAD quotations or KV caps.
Source: `provider-swift/Sources/ProviderCore/Inference/Vision/VisionFeatureCache.swift`
(`VisionFeatureCacheBudget`).
133 changes: 133 additions & 0 deletions docs/architecture/image-feature-cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Gemma image feature caching

> Last updated: 2026-10-29

The provider can retain evaluated Gemma still-image encoder results in bounded RAM.
This opt-in path skips the vision tower and projector on a hit; decode, resize,
prompt construction and full prompt prefill still run. Native parity and
performance qualification are required before default activation.

## Context

Repeated images can accompany different text or appear in a different order.
`EngineV2VisionPrefill` keeps the current processor and span construction while
`GemmaVisionFeatureCache` reuses individual image features. Only the pinned
`MLXVLM.Gemma4` / `Gemma4Processor` adapter is eligible. Other families, unified
Gemma wrappers, diffusion models and video-frame features remain uncached.

## Mechanism

```mermaid
flowchart LR
A["Authenticated outer vision scope"] --> B["Existing decode and processor"]
B --> C["Hash raw payload and unpadded normalized image"]
C --> D{"Eligible resident feature?"}
D -->|yes| E["Pin CPU bytes; restore and evaluate fresh MLX array"]
D -->|no| F["Run image tower and projector; evaluate"]
F --> G["Reserve host bytes; stage CPU copy"]
E --> H["Build current prompt spans; check faults and cancellation"]
G --> H
H --> I["Commit valid staged entries; prefill full current prompt"]
```

The loaded bridge owns `VisionFeatureCache`. `ModelContainer.perform` excludes
other model preparations across awaits. `VisionFeaturePreparationOwner` registers
up to 128 cache-eligible preparation tasks and propagates caller cancellation.
Disabled, unscoped and unsupported paths acquire no cache transaction; owner
saturation falls back to ordinary cold preparation. A transaction publishes only after the whole
submission passes span, evaluation and cancellation checks. A cancelled producer
may be recomputed by a later request.

The key binds the dedicated authenticated scope, bridge lifetime, model instance,
processor/configuration metadata, adapter revision and current MLX device, raw
payload SHA-256, and exact unpadded normalized tensor bytes, dtype, shape and THW.
Hashes are internal RAM identities. Prompt text and image ordinal are excluded;
current prompt tokens and placeholder spans are always rebuilt. A change to a
bound model/processor/device identity clears eligibility and runs cold. Provider
serving keeps loaded weights and processor configuration immutable; in-place SDK
training or mutation is outside this adapter's contract.

`GemmaVisionProcessorIdentity` accepts either `processor_config.json` or
`preprocessor_config.json`, matching the pinned factory's supported layouts.
Both files contribute when present, together with `config.json`; each read is
bounded to 64 KiB. Missing both processor files, unreadable metadata or an
oversized file disables reuse. This supports the processor-only layout of the
Gemma QAT artifact without inferring identity from a model name.

`MediaIngest` hashes decoded payload bytes while it already owns them. The adapter
currently reads bounded metadata files on each eligible preparation and copies
normalized pixels for hashing. These costs remain in preparation time and must
be measured against saved encoder work. A preprocessing cache or load-time
fingerprint optimization requires separate evidence.

## Invariants

1. Missing scope, absent shared budget, disabled policy, unsupported adapters or
denied optional allocations run cold. Scope comes only from coordinator outer
metadata, never from the request body or `cache_scope`. Local endpoints without
an authenticated vision scope remain cold (`ProviderLoop.handleInferenceRequest`,
`MultiModelBatchSchedulerEngine`, `GemmaVisionFeatureCache`).
2. A snapshot contains only evaluated, independently copied CPU tensor bytes.
No live MLX array, lazy graph, raster, raw media or prompt is retained. Restore
runs under model serialization and evaluates a fresh MLX allocation before
releasing the reader (`gemmaImageFeatures`, `VisionFeatureCache.Tensor`).
3. Pending copies, scratch, pinned retired entries and published entries consume
the process, slot and scope limits in [configuration](../reference/configuration.md#image-feature-cache).
Reservations precede copying and hydration; failure bypasses caching. Host
bytes use the same `ProcessMemoryLedger` owned by `GlobalKVCacheBudget`, with
zero MLX materialization credit (`VisionFeatureCacheBudget`).
Scope-quota denial can evict only that scope's own entries. If its allowance
remains pinned or pending elsewhere, admission fails cold without evicting
another scope. Slot/process/ledger pressure can reclaim local LRU entries;
an impossible allocation or non-capacity ledger refusal triggers no eviction.
4. LRU eviction and TTL expiry remove lookup eligibility first. Borrowed readers
keep the payload and charge alive. Destruction drops Data before releasing its
charge. Shutdown synchronously closes the preparation owner and cache before
cancelling pumps and shutting down the engine, then joins preparation tasks
and reader leases. Native reporting first verifies engine identity and SDK
quiescence; unfinished host consumers return `pendingConsumers` while retaining
ownership. Timeouts never refund bytes (`closeAndDrain`, `shutdownNativeConstruction`).
5. Model LOAD and request pressure trim optional entries. Monotonic absolute TTL
is swept periodically, including while idle. Pinned bytes remain charged until
their final reader retires (`GlobalKVCacheBudget.commit`, `claimPendingLoad`,
`VisionFeatureCache.sweep`).
6. Feature hits change no token usage, prefix evidence, cached-token billing,
admission floor, SLA or output cap. The complete current prompt is prefilled
into request-owned KV. Only bounded image-work counters are added to the
[terminal profile](../reference/telemetry-schema.md#image-feature-work-in-terminal-profiles).

## Failure modes

Allocation refusal preserves ordinary cold inference admission. A copy error,
MLX fault, cancellation or invalid geometry prevents partial publication.
Deterministic input errors and cancellation abandon only the current transaction;
existing entries in all scopes remain eligible. A recorded MLX fault invalidates
the cache generation. Cache
retirement accounting failures conservatively retain their ledger charge rather
than refund unproven ownership. Shutdown ordering and native fault retirement
must be qualified with actual model work; CPU cache tests cannot establish GPU
completion or deadlock freedom.

The current implementation is an opt-in qualification candidate. Native checks
must exercise preparation drain versus pump cancellation, disabled and unsupported
slots, and quota fairness under real memory pressure. Neither implementation nor a
passing CPU suite establishes a production latency benefit.

## Code map

| Concern | Source and symbol |
|---|---|
| CPU ownership, limits, leases | `provider-swift/Sources/ProviderCore/Inference/Vision/VisionFeatureCache.swift` — `VisionFeatureCache`, `VisionFeatureCacheBudget` |
| Preparation cancellation and completion | `provider-swift/Sources/ProviderCore/Inference/Vision/VisionFeaturePreparationOwner.swift` — `perform`, `close`, `drain` |
| Processor metadata layouts and bounded identity | `provider-swift/Sources/ProviderCore/Inference/Vision/GemmaVisionProcessorIdentity.swift` — `fingerprint` |
| Gemma hashing, tower bypass, snapshot/restore | `provider-swift/Sources/ProviderCore/Inference/Vision/GemmaVisionFeatureCache.swift` — `gemmaImageFeatures` |
| Raw identity at existing decode | `provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift` — `buildUserInput` |
| Current prompt/span construction | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` — `prepare`, `buildGemmaSubmission` |
| Shared host accounting | `provider-swift/Sources/ProviderCore/Inference/Memory/GlobalKVCacheBudget.swift` — `visionFeatureCacheBudget` |
| Bridge shutdown | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Lifecycle.swift` — `shutdown` |

## Related

- [Inference architecture](inference.md)
- [Prefix-cache semantics](prefix-cache.md)
- [CPU and native verification](../developer/test.md#image-feature-cache-verification)
7 changes: 7 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -8272,3 +8272,10 @@ Each tensor-parallel rank reserves only the request state it holds (`QwenTensorP
Concurrent speculative requests verify their draft windows in one target forward, and each request must emit exactly the tokens it emits alone. MLX picks a quantized matmul kernel from the product's total row count. Up to the device's vector limit (`get_qmv_batch_limit`: 12 rows at Qwen27's widths on the M3 Ultra, 13 on the M5 Max) a product runs `qmv_wide`; at or beyond it, split-K QMM, with a different reduction order. One request's three-column window is 3 rows; four requests' windows in one product are 12, so on the M3 they took the other kernel. In an installed run before this change, 5 of 30 concurrent requests, all in waves with four-request cohorts, chose a different near-tie token. `QwenTensorParallelTargetWindow.beginBatch` therefore runs the batched verify forward under `Qwen35BatchDecodeScope.verifyRows`. Every projection computes each request's `[1, S, H]` rows as that request's own window would, the row-parallel projections concatenate those partials into one collective per projection (two per dense layer), and the LM head follows the same rule. Below the vector limit, `qmv_wide` (and `qmv` before Apple GPU family 15) computes each vector the same way at any vector count: its tile size only decides which vectors share a weight read. So requests share a quantized call while their windows' total rows stay below the limit (`Qwen35QuantizedVectorLimit`, which mirrors `get_qmv_batch_limit` for the device MLX reads, including `MLX_METAL_GPU_ARCH`). At Qwen27's widths with depth 3 that is two four-column windows per call on the M3 Ultra and three on the M5 Max. `qmv_wide` still reads the weights once per tile of up to five vectors, so sharing saves launches and some weight reads rather than whole passes; the installed round profile (`darkbloom-tp-mtp-profile-v1`, c35) still shows about 44 ms of verify time per additional row. Only exact base `QuantizedLinear` modules in affine mode on the GPU share calls; the CPU, other quantizers, overridden forwards and MLX's 64/128-wide quad kernel keep one call per row. `QwenTensorParallelBatchMTPWindowTests.sharedWindowCallsKeepEveryRowsQuantizedArithmetic` checks the shared calls byte for byte against each row's own call at Qwen27's projection shapes. Attention and the recurrent layers were already per-request, so only the projection row count changed between alone and together. `QwenTensorParallelBatchMTPWindowTests.everyRectangleRowEqualsItsOwnSingleRequestWindowBitwise` compares every row of eight-request rectangles with its own window, byte for byte, on both ranks. The agreement carries `verify-rows=single-window-v1`.

Where it measured faster and byte-equal, a cohort's verify rows go through one kernel instead of MLX's own calls (`Qwen35WideQuantizedKernel`, a port of `qmv_wide_impl`): each vector keeps `qmv_wide`'s lanes, sub-chunk sums and shuffle ladder, but up to eight vectors (two four-column windows) share a weight read instead of five, and a thread may carry two output rows so each input value is converted once for both. The layout follows the GPU family (`Qwen35WideQuantizedKernel.layout`). On the M5 Max (family 17), one row a thread for bfloat16 and float32 inputs, up to 20% faster than MLX's calls. On the M3 Ultra (family 15), two rows a thread for the row-parallel float32 partials, 1.5-2.1x faster, while its bfloat16 projections keep MLX's calls, which measured as fast or faster; one row a thread was up to 1.6x slower there. Other families keep MLX's calls. The figures come from `QwenTensorParallelVerifyBenchTests` (opt-in) on each Mac with Qwen27's shard shapes, and `QwenTensorParallelBatchMTPWindowTests.wideKernelRowsEqualEachRowsOwnWindowCall` checks both layouts byte for byte against each row's own call on whichever GPU runs it.

## Image encoder feature reuse

The opt-in [Gemma image feature cache](image-feature-cache.md) preserves current
prompt construction and spans while skipping eligible per-image tower/projector
work. It retains only charged CPU tensor bytes; full prompt prefill and prefix
cache semantics are unchanged. Other VLM adapters remain cold.
12 changes: 11 additions & 1 deletion docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# KV cache layouts and prefix caching

> Last updated: 2026-11-07
> Last updated: 2026-11-09

How the provider lays out a request's KV cache, how it decides whether a
previously computed prefix can be reused, and where reusable state lives:
Expand Down Expand Up @@ -1370,3 +1370,13 @@ state at and after the boundary, hits and misses on both ranks, the request
loop and lanes, budget and eviction, the SSD round trip, refused records and
the cache rules) and the paged oracle matrix's `--prefix repeat` runs
([focused checks](../developer/test.md#focused-gemma-4-tensor-parallel-checks)).

## Separate image encoder reuse

[Gemma image feature caching](image-feature-cache.md) reuses evaluated encoder
outputs before full current-prompt prefill. It does not adopt KV, emit prefix
receipts, change `cache_scope`/`cacheEnabled`, or count feature hits as cached
prompt tokens. The independent outer `vision_cache_scope` is optional; no scope
means cold image encoding. Source:
`provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift`
(`prepareCompletion`).
11 changes: 10 additions & 1 deletion docs/architecture/telemetry.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Provider telemetry

> Last updated: 2026-10-23
> Last updated: 2026-10-29

Provider diagnostics travel on typed heartbeats and terminal profiles. The Swift event-emitter facade is inert; do not add prompt or completion content to heartbeats or profiles. The [wire schema](../reference/telemetry-schema.md) and [protocol reference](../reference/protocol-messages.md) define the boundary.

Expand Down Expand Up @@ -209,3 +209,12 @@ Coordinator validation, persistence, Datadog transport and retention are owned b
- [Prediction and deadline observations](../reference/prediction-decision-telemetry.md)
- [Privacy model](security/encryption.md)
- [Provider component](components/provider.md)

## Image encoder work

Gemma preparation adds only the two bounded numeric
[terminal-profile counters](../reference/telemetry-schema.md#image-feature-work-in-terminal-profiles).
They report successful feature hydrations and attempted image encoder executions,
independently of token/KV cache accounting. Scopes and media digests are never
emitted. `RequestProfileBuilder` batches this update once per preparation;
unsupported families leave the optional fields absent.
17 changes: 16 additions & 1 deletion docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build The Provider And Landing

> Last updated: 2026-11-08
> Last updated: 2026-11-09

Build the provider, its source-matched native resources, and the independent
landing site from this repository. Backend, sidecar, console and admin builds
Expand Down Expand Up @@ -1058,3 +1058,18 @@ Qwen27 TP batch prefix capture/restore changes the Runtime target only; it
reuses the pinned SDK owned-state APIs. Rebuild the worker and planner together
because the same complete LOAD budget prices the additional snapshot banks.
See [warm-prefix validation](test.md#qwen27-tp-warm-prefix-checks).

## Image feature cache CPU check

The [isolated cache runner](test.md#image-feature-cache-verification) compiles only
Foundation/CryptoKit accounting and profile sources with Swift 6. It uses an
explicit task-owned scratch directory and does not resolve the MLX package graph.
A passing result is not a native provider build or typecheck of the Gemma adapter.

The native `GemmaVisionFeatureCacheLiveTests` suite requires a freshly built
provider test product and the compiled MLX Metal resources. Its encoder/output
test and process-ledger trim/close test share the exact artifact and opt-in
requirements in the [verification instructions](test.md#image-feature-cache-verification).
When changing only these tests, record the new test executable identity and
verify whether the provider executable, Metal libraries and runtime resources
changed before reusing earlier serving evidence.
Loading
Loading