design(vlm): support multimodal KV prefix reuse
Problem
The llama.cpp VLM path currently keeps only n_past, past_prompt, and past_gen. On the next turn, it compares the rendered prompt as text and assumes the previous generated text immediately follows the common prefix. This append-only assumption fails when the new prompt is a valid revision of the full conversation rather than an exact extension.
One important example is thinking mode. Some chat templates omit earlier reasoning content when they render the next turn. The KV cache can therefore contain more tokens than the newly rendered prompt, and the current VLM path returns GENIEX_ERROR_VLM_PREFIX_REUSE_FAILED. For this reason, LlamaVlm::apply_chat_template() currently ignores enable_thinking=true.
Unlike text-only LLM input, a VLM prompt also contains image or audio chunks processed by mtmd. Comparing only the flattened prompt cannot establish whether the cached multimodal prefix represents the same media.
Goals
- Enable thinking-mode chat templates for llama.cpp VLMs.
- Reuse the longest verified text and media prefix across turns.
- Support full-history callers that append one or more turns, trim history, or edit an earlier turn.
- Keep the matching policy and implementation small enough to audit and test.
- Preserve
geniex_vlm_reset()as an explicit way for callers to invalidate all retained state.
Non-goals
- Persistent or cross-session KV-cache storage.
- Server session ownership or transaction lineage, which is covered separately by #1413.
- Exact matching of media position or preprocessing fingerprints in the first version.
- Changes to the QAIRT plugin.
Proposed design
Introduce an internal multimodal prefix-matcher module in the llama.cpp VLM implementation. Its interface should accept the previous and current canonical conversation sequences and return the longest reusable boundary plus the required action: reuse, truncate and prefill, or reset and prefill. This keeps matching and boundary bookkeeping local instead of spreading it across chat templating, generation, and bindings.
Build the canonical sequence from the structured messages passed to geniex_vlm_apply_chat_template() before they are flattened into media markers and text. Preserve the order of message content parts and represent them as:
- text segments using the rendered or tokenized text identity;
- media segments using modality plus a stable media identity.
For the initial policy, two media segments are the same when they have the same modality and stable identity in the same relative order. Position and preprocessing fingerprints are deliberately not required. This is a practical reuse policy rather than a guarantee that every preprocessing change is equivalent. Applications that need stricter invalidation can call geniex_vlm_reset().
The VLM should record only boundaries that were successfully evaluated into the KV cache. Each boundary must map the canonical segment position to the actual KV position returned by mtmd. This is important because media token counts and KV positions can differ with M-RoPE.
For each new full history:
- Compare the previous and current canonical sequences in order.
- Find the longest matching prefix that ends at a recorded safe KV boundary.
- Retain KV state through that boundary.
- Remove cached state after the boundary when the model supports truncation, then prefill the changed suffix.
- If partial rollback is unsupported, reset and rebuild from the available full input.
- If historical media needed for rebuilding is unavailable or its identity cannot be verified, do not reuse it silently. Reset and return a clear result if the required media cannot be supplied.
- Commit the new descriptor and boundaries only after successful prefill and generation.
geniex_vlm_reset() must clear both the model KV state and the stored multimodal descriptor.
Interface considerations
geniex_vlm_apply_chat_template() receives structured history, while geniex_vlm_generate() receives flattened text and media paths from the generation configuration. The implementation therefore needs a clear contract connecting the template result to the next generation call.
A minimal implementation can store a pending descriptor on the same VLM handle when the template is applied and consume it when the matching formatted prompt is generated. The review should confirm:
- whether the existing
geniex_VlmContent.textreference is stable enough to identify media; - whether an optional caller-provided
media_idorcache_keyis needed; - how historical media is supplied when an edit requires re-prefill;
- whether failure to rebuild should reset automatically or return an explicit media-required error;
- how recurrent models that cannot truncate KV state should fall back.
A content digest can be considered later if path or URL identity proves insufficient. It should not be required for the first implementation unless correctness testing shows that it is necessary.
Expected behavior
| Scenario | Expected result |
|---|---|
| Identical history with the same ordered media identities | Reuse the full verified prefix. |
| One or multiple turns appended | Reuse the previous prefix and prefill only the appended suffix. |
| Earlier thinking content omitted by the template | Do not fail prefix reuse. Roll back to the longest safe matching boundary and prefill the remainder. |
| Earlier text edited or history trimmed | Invalidate state after the first changed boundary and prefill from there, or rebuild when truncation is unsupported. |
| Image or audio reordered, replaced, or given a different identity | Invalidate at the first changed media segment. |
| Historical media is missing or cannot be verified | Never reuse beyond the verified boundary. Rebuild if possible; otherwise return a clear error. |
| Same media identity with a position or preprocessing difference | Treat it as the same input in the initial relaxed policy. Callers can use geniex_vlm_reset() when strict invalidation is required. |
| Explicit reset | Clear KV state and the stored descriptor; the next request performs a full prefill. |
Test plan
Add focused unit tests for the prefix matcher and integration coverage for:
- unchanged image history followed by a new text turn;
- multiple appended turns in one request;
- prior thinking content removed by the next template application;
- trimmed or edited text history;
- reordered, replaced, and missing image or audio input;
- explicit reset followed by the same conversation;
- fallback behavior for a model that cannot partially truncate KV state;
- media token to KV-position boundary accounting under mtmd and M-RoPE.
Where practical, use test instrumentation to confirm that unchanged media is not encoded again. If the interface changes, keep C, Go, Python, Android, and server behavior consistent.
Acceptance criteria
enable_thinking=trueis supported for llama.cpp VLM chat templates instead of being ignored.- Supported full-history updates do not fail with
GENIEX_ERROR_VLM_PREFIX_REUSE_FAILED. - Reuse never continues past an unverified text or media boundary.
- Unchanged multimodal prefixes avoid unnecessary media re-encoding.
geniex_vlm_reset()reliably forces a clean full prefill.- Public interface and usage documentation are updated if a media identity field or new error is introduced.
Alternatives considered
- Append-only rollback to the previous turn boundary: simple, but too narrow for callers that trim, edit, or append multiple turns.
- Exact content digest plus position and preprocessing fingerprints: stronger identity, but more engineering complexity than the initial policy needs.
- Reset on every turn: correct, but gives up text KV reuse and repeats expensive media encoding.
This issue is intended for design review before implementation, especially around stable media identity, historical media availability, and rollback behavior for recurrent models.
Source: qualcomm/GenieX