Skip to content
Closed
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@
`LlamaStructuredOutput.parse` still decode it); trim replies you compare
exactly. `ChatSession` and its tool loop store assistant turns in `history`
without that whitespace, so the next prompt is unchanged.
- Fix a process abort on an image with more tokens than the context's
micro-batch when the projector's images are decoded with non-causal
attention (Gemma 3 and Gemma 4 other than E2B and E4B, among others): the
prompt now throws `LlamaInferenceException` naming the
`ModelParams.microBatchSize` it needs. With default batch sizes that is an
image above 512 tokens. A context whose batch equals its micro-batch still
decodes such an image in several batches, and now logs a warning that this
can reduce accuracy
([#958](https://github.com/leehack/llamadart/issues/958)).

## 0.11.1

Expand Down
6 changes: 4 additions & 2 deletions doc/llama_cpp_exit_teardown.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,13 @@ new call on an `sd_ctx_t` that can run longer than the 250 ms settle time
sequence is compared for creation and frees, plain generation (one decode
and one sample per token), one-text and batch embedding on a decoder and on
an encoder, state files, LoRA init, a decision head, a decision head that
fails after its context was created, and a fake projector. N-gram and
fails after its context was created, a fake projector, and an image the
service rejects after the tokenize without an evaluating call. N-gram and
draft-model speculation are matched against the sequences their loop
allows. Everything created through the API has to be freed through it.
- `test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart`: `withExitTeardown`
replaces the three evaluating calls and keeps the accessors.
replaces the three evaluating calls and keeps the accessors, which are all
the check of a media chunk against the micro-batch calls.
- `test/unit/backends/llama_cpp/native_barrier_api_test.dart`: the lookup
requests all 18 names and resolves nothing when any one is missing or from
a library that has none; each member calls the function exported under its
Expand Down
23 changes: 23 additions & 0 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,29 @@ after reload or replacement. Pair them with
pre-output stops, buffered tool calls, running handlers, projector creation
and teardown races, and speech parameter validation before file resolution.

### Image above the context micro-batch

```bash
MULTIMODAL_MICRO_BATCH_MODEL=/path/to/gemma-4-12B-it.gguf \
MULTIMODAL_MICRO_BATCH_MMPROJ=/path/to/mmproj.gguf \
MULTIMODAL_MICRO_BATCH_BACKEND=cpu \
dart test -p vm -j 1 --run-skipped \
test/e2e/backends/multimodal_micro_batch_e2e_test.dart
```

These local-only tests need a model whose projector decodes an image with
non-causal attention: Gemma 3, or Gemma 4 other than E2B and E4B. They answer
a small image at the default batch sizes; require a typed error and a working
engine for an image above a micro-batch that is below the batch, explicit or
default, and answer the large image with the micro-batch the error names; and
require an answer and one warning per request where the batch equals the
micro-batch (32/32, batch 32 alone, 256/256, 512/512, and a text turn after
an image turn). Repeat with `MULTIMODAL_MICRO_BATCH_BACKEND=metal` on macOS.
Without the check the first group aborts the process on llama.cpp's
`non-causal attention requires n_ubatch >= n_tokens` assertion. `test/unit/backends/llama_cpp/llama_cpp_service_media_micro_batch_test.dart`
covers the same paths in default CI with a stand-in projector on the real
runtime.

### Native exit teardown

```bash
Expand Down
16 changes: 15 additions & 1 deletion example/chat_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,10 @@ layouts) opens a separate screen for the experimental `ImageGenerationEngine`
**Advanced** for Dart and native/bridge log levels.
- Logical batch size (`n_batch`) and micro-batch size (`n_ubatch`) default to
`Auto`, which keeps the backend's own defaults; an explicit value applies
on the next model load. LiteRT-LM bundles disable these controls.
on the next model load. LiteRT-LM bundles disable these controls. On an
Android GPU, `Auto` loads a GGUF model with smaller sizes instead: batch
32 (64 for Qwen3.5 0.8B) and micro-batch 1 on Vulkan, 256 and 64 on the
other GPU backends.
- `Auto` selects the best supported runtime; on supported Macs it prefers
Metal. The selector also lists concrete runtime-detected options such as
CPU/Vulkan/CUDA for GGUF or CPU/GPU/NPU for LiteRT-LM.
Expand Down Expand Up @@ -466,6 +469,17 @@ await prefs.setInt('preferred_backend', backendIndex);
- Ensure you have successfully downloaded a model from the selection screen.
- If you manually moved a model, verify the path in the settings sheet.

**`The image input has <n> tokens, more than the context's micro-batch of <m> tokens`:**
- llama.cpp cannot split the images of some projectors across micro-batches
(Gemma 3 and Gemma 4 models other than E2B and E4B, among others). On an
Android GPU the `Auto` micro-batch is smaller than an image and smaller
than the batch, so an image prompt with these models fails with this error
there. Set the logical batch size and the micro-batch size to at least
`<n>` and reload the model, or use `CPU`. Those larger sizes have not been
run on Android Vulkan devices. Setting the two sizes equal but below `<n>`
also avoids the error, with the image decoded in pieces and possibly less
accurate answers.

**Slow generation:**
- Ensure hardware acceleration is enabled (e.g., Metal on Apple, Vulkan on Linux/Windows).
- On Android, llama.cpp Vulkan is experimental and device-dependent, so it is
Expand Down
51 changes: 51 additions & 0 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5836,6 +5836,13 @@ class LlamaCppService {
newPast,
);
} else {
_checkNonCausalMediaChunks(
chunkEvalApi,
mmCtx,
chunks,
batchTokens: modelParams.n_batch,
microBatchTokens: llama_n_ubatch(ctx.pointer),
);
chunkFailure = evalMtmdChunksUntilCancelled(
chunkEvalApi,
mmCtx,
Expand Down Expand Up @@ -5884,6 +5891,50 @@ class LlamaCppService {
return initialTokens;
}

/// Rejects a prompt whose non-causal media chunk llama.cpp would abort on.
///
/// `mtmd_helper_decode_image_chunk` decodes such a chunk in pieces of
/// [batchTokens], the `n_batch` it is given, and `llama_context::decode`
/// aborts on a non-causal piece above [microBatchTokens]. With the two
/// equal the pieces pass, and the chunk is decoded in several non-causal
/// batches, which is logged.
void _checkNonCausalMediaChunks(
MtmdChunkEvalApi api,
Pointer<mtmd_context> mmCtx,
Pointer<mtmd_input_chunks> chunks, {
required int batchTokens,
required int microBatchTokens,
}) {
final chunk = findMtmdChunkAboveMicroBatch(
api,
mmCtx,
chunks,
microBatchTokens,
);
if (chunk == null) return;
final media = mtmdMediaChunkName(chunk.chunkType);
if (batchTokens <= microBatchTokens) {
LlamaLogger.instance.warning(
'llama_cpp_service: the $media input has ${chunk.tokenCount} tokens, '
'more than the context\'s micro-batch of $microBatchTokens tokens '
'(n_ubatch), so it is decoded in several non-causal batches, which '
'can reduce accuracy. Load the model with '
'ModelParams.microBatchSize and ModelParams.batchSize of at least '
'${chunk.tokenCount} to decode it in one.',
);
return;
}
throw LlamaInferenceException(
'The $media input has ${chunk.tokenCount} tokens, more than the '
'context\'s micro-batch of $microBatchTokens tokens (n_ubatch), and '
'this projector decodes it with non-causal attention, which llama.cpp '
'cannot split across micro-batches. Raise ModelParams.microBatchSize '
'to at least ${chunk.tokenCount}, and ModelParams.batchSize with it, '
'or pass a smaller $media if the projector sizes its output by the '
'input.',
);
}

void _ensureLogitsAvailableAfterPromptEval(Pointer<llama_context> ctx) {
if (llama_get_logits(ctx) != nullptr) {
return;
Expand Down
79 changes: 71 additions & 8 deletions lib/src/backends/llama_cpp/mtmd_chunk_eval.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ typedef _ChunksGetDart =
Pointer<mtmd_input_chunk> Function(Pointer<mtmd_input_chunks>, int);
typedef _ChunkTypeNative = UnsignedInt Function(Pointer<mtmd_input_chunk>);
typedef _ChunkTypeDart = int Function(Pointer<mtmd_input_chunk>);
typedef _ChunkTokenCountNative = Size Function(Pointer<mtmd_input_chunk>);
typedef _ChunkTokenCountDart = int Function(Pointer<mtmd_input_chunk>);
typedef _DecodeUseNonCausalNative =
Bool Function(Pointer<mtmd_context>, Pointer<mtmd_input_chunk>);
typedef _DecodeUseNonCausalDart =
bool Function(Pointer<mtmd_context>, Pointer<mtmd_input_chunk>);
typedef _EvalChunkSingleNative =
Int32 Function(
Pointer<mtmd_context>,
Expand Down Expand Up @@ -89,14 +95,16 @@ int _primaryDecodeImageChunk(
nullptr,
);

/// The mtmd functions [evalMtmdChunksUntilCancelled] calls, resolved from one
/// library.
/// The mtmd functions [evalMtmdChunksUntilCancelled] and
/// [findMtmdChunkAboveMicroBatch] call, resolved from one library.
final class MtmdChunkEvalApi {
/// Creates an API from resolved functions.
const MtmdChunkEvalApi({
required this.chunksSize,
required this.chunksGet,
required this.chunkType,
required this.chunkTokenCount,
required this.decodeUseNonCausal,
required this.evalChunkSingle,
required this.encodeChunk,
required this.outputEmbd,
Expand All @@ -108,6 +116,8 @@ final class MtmdChunkEvalApi {
chunksSize: mtmd_input_chunks_size,
chunksGet: mtmd_input_chunks_get,
chunkType: raw_bindings.mtmd_input_chunk_get_type_raw,
chunkTokenCount: mtmd_input_chunk_get_n_tokens,
decodeUseNonCausal: mtmd_decode_use_non_causal,
evalChunkSingle: mtmd_helper_eval_chunk_single,
encodeChunk: mtmd_encode_chunk,
outputEmbd: mtmd_get_output_embd,
Expand All @@ -132,6 +142,14 @@ final class MtmdChunkEvalApi {
chunkType: library.lookupFunction<_ChunkTypeNative, _ChunkTypeDart>(
'mtmd_input_chunk_get_type',
),
chunkTokenCount: library
.lookupFunction<_ChunkTokenCountNative, _ChunkTokenCountDart>(
'mtmd_input_chunk_get_n_tokens',
),
decodeUseNonCausal: library
.lookupFunction<_DecodeUseNonCausalNative, _DecodeUseNonCausalDart>(
'mtmd_decode_use_non_causal',
),
evalChunkSingle: library
.lookupFunction<_EvalChunkSingleNative, _EvalChunkSingleDart>(
'mtmd_helper_eval_chunk_single',
Expand Down Expand Up @@ -169,6 +187,8 @@ final class MtmdChunkEvalApi {
chunksSize: chunksSize,
chunksGet: chunksGet,
chunkType: chunkType,
chunkTokenCount: chunkTokenCount,
decodeUseNonCausal: decodeUseNonCausal,
evalChunkSingle: exit.mtmdHelperEvalChunkSingle,
encodeChunk: exit.mtmdEncodeChunk,
outputEmbd: outputEmbd,
Expand Down Expand Up @@ -201,6 +221,16 @@ final class MtmdChunkEvalApi {
/// `mtmd_input_chunk_get_type`, as its raw enum value.
final int Function(Pointer<mtmd_input_chunk> chunk) chunkType;

/// `mtmd_input_chunk_get_n_tokens`.
final int Function(Pointer<mtmd_input_chunk> chunk) chunkTokenCount;

/// `mtmd_decode_use_non_causal`.
final bool Function(
Pointer<mtmd_context> ctx,
Pointer<mtmd_input_chunk> chunk,
)
decodeUseNonCausal;

/// `mtmd_helper_eval_chunk_single`.
final int Function(
Pointer<mtmd_context> ctx,
Expand Down Expand Up @@ -277,10 +307,44 @@ final class MtmdChunkEvalFailure {
? 'failed to eval chunk $chunkIndex'
: 'failed to ${stage.name} $_media chunk $chunkIndex';

String get _media =>
chunkType == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE.value
? 'image'
: 'audio';
String get _media => mtmdMediaChunkName(chunkType);
}

/// `image` or `audio`, for the raw `mtmd_input_chunk_type` of a media chunk.
String mtmdMediaChunkName(int chunkType) =>
chunkType == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE.value
? 'image'
: 'audio';

bool _isMediaChunk(int chunkType) =>
chunkType == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE.value ||
chunkType == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_AUDIO.value;

/// Returns the first image or audio chunk of [chunks] that [ctx] decodes with
/// non-causal attention and that has more than [maxTokens] tokens, as its
/// raw `mtmd_input_chunk_type` and token count, otherwise `null`.
///
/// llama.cpp cannot split such a chunk across micro-batches:
/// `mtmd_helper_decode_image_chunk` turns causal attention off and splits the
/// chunk only by its `n_batch` argument, and `llama_context::decode` aborts
/// on a non-causal batch above `n_ubatch`. Pass `n_ubatch` as [maxTokens].
({int chunkType, int tokenCount})? findMtmdChunkAboveMicroBatch(
MtmdChunkEvalApi api,
Pointer<mtmd_context> ctx,
Pointer<mtmd_input_chunks> chunks,
int maxTokens,
) {
final nChunks = api.chunksSize(chunks);
for (var i = 0; i < nChunks; i++) {
final chunk = api.chunksGet(chunks, i);
final type = api.chunkType(chunk);
if (!_isMediaChunk(type)) continue;
final tokenCount = api.chunkTokenCount(chunk);
if (tokenCount > maxTokens && api.decodeUseNonCausal(ctx, chunk)) {
return (chunkType: type, tokenCount: tokenCount);
}
}
return null;
}

/// Evaluates [chunks] as `mtmd_helper_eval_chunks` does for `n_past` 0,
Expand Down Expand Up @@ -309,8 +373,7 @@ MtmdChunkEvalFailure? evalMtmdChunksUntilCancelled(
final type = api.chunkType(chunk);
MtmdChunkEvalStage stage;
int result;
if (type == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE.value ||
type == mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_AUDIO.value) {
if (_isMediaChunk(type)) {
stage = MtmdChunkEvalStage.encode;
result = api.encodeChunk(ctx, chunk);
if (result == 0) {
Expand Down
8 changes: 8 additions & 0 deletions lib/src/core/models/inference/model_params.dart
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,14 @@ class ModelParams {
/// Native encoder-only models and models whose context has no KV cache,
/// such as BERT and ModernBERT, embed each input in one micro-batch, so a
/// longer embedding input throws `LlamaInferenceException`.
///
/// llama.cpp cannot split an image across micro-batches when the projector
/// has it decoded with non-causal attention, as those of Gemma 3 and of
/// Gemma 4 other than E2B and E4B do. Such an image with more tokens than
/// the micro-batch throws `LlamaInferenceException` when [batchSize] is
/// larger than the micro-batch, which the defaults are. With the two equal
/// it is decoded in several batches, with a logged warning, and answers
/// can be less accurate.
final int microBatchSize;

/// Maximum parallel sequence slots in context memory (n_seq_max).
Expand Down
9 changes: 9 additions & 0 deletions skills/llamadart-multimodal/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ description: >-
- On llama.cpp, `GenerationParams.thinkingBudget` and speculative decoding
throw `LlamaUnsupportedException` for requests that contain media. Leave
them unset for multimodal turns.
- llama.cpp decodes the images of some projectors with non-causal attention
(Gemma 3 and Gemma 4 other than E2B and E4B, among others) and cannot
split one across micro-batches. An image with more tokens than
`ModelParams.microBatchSize` (512 by default) then throws
`LlamaInferenceException` naming the token count: load the model with
`microBatchSize` of at least that and `batchSize` no smaller, or downscale
the image. Gemma 4 gives an image up to 1120 tokens. When `batchSize`
equals `microBatchSize` there is no error; the image is decoded in several
batches with a logged warning, and answers can be less accurate.
- The package does not resize media. Downscale large images (the example chat
app caps the long edge at 384px) and keep `maxTokens` and context budgets
tighter than for text; images in history keep consuming context on later
Expand Down
Loading
Loading