diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a9ee102e..10ca8272b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 39cfe32b4..f0076c0b7 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -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 diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 8c154ddae..93b341ca2 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -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 diff --git a/example/chat_app/README.md b/example/chat_app/README.md index f16086963..f05010b08 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -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. @@ -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 tokens, more than the context's micro-batch of 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 + `` 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 `` + 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 diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 1924bcf0f..11a7a2639 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -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, @@ -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 mmCtx, + Pointer 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 ctx) { if (llama_get_logits(ctx) != nullptr) { return; diff --git a/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart b/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart index 327eee26a..a7f1751e4 100644 --- a/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart +++ b/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart @@ -12,6 +12,12 @@ typedef _ChunksGetDart = Pointer Function(Pointer, int); typedef _ChunkTypeNative = UnsignedInt Function(Pointer); typedef _ChunkTypeDart = int Function(Pointer); +typedef _ChunkTokenCountNative = Size Function(Pointer); +typedef _ChunkTokenCountDart = int Function(Pointer); +typedef _DecodeUseNonCausalNative = + Bool Function(Pointer, Pointer); +typedef _DecodeUseNonCausalDart = + bool Function(Pointer, Pointer); typedef _EvalChunkSingleNative = Int32 Function( Pointer, @@ -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, @@ -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, @@ -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', @@ -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, @@ -201,6 +221,16 @@ final class MtmdChunkEvalApi { /// `mtmd_input_chunk_get_type`, as its raw enum value. final int Function(Pointer chunk) chunkType; + /// `mtmd_input_chunk_get_n_tokens`. + final int Function(Pointer chunk) chunkTokenCount; + + /// `mtmd_decode_use_non_causal`. + final bool Function( + Pointer ctx, + Pointer chunk, + ) + decodeUseNonCausal; + /// `mtmd_helper_eval_chunk_single`. final int Function( Pointer ctx, @@ -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 ctx, + Pointer 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, @@ -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) { diff --git a/lib/src/core/models/inference/model_params.dart b/lib/src/core/models/inference/model_params.dart index 1b5ff2893..135c95b38 100644 --- a/lib/src/core/models/inference/model_params.dart +++ b/lib/src/core/models/inference/model_params.dart @@ -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). diff --git a/skills/llamadart-multimodal/SKILL.md b/skills/llamadart-multimodal/SKILL.md index 1369050da..f852b60d2 100644 --- a/skills/llamadart-multimodal/SKILL.md +++ b/skills/llamadart-multimodal/SKILL.md @@ -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 diff --git a/test/e2e/backends/multimodal_micro_batch_e2e_test.dart b/test/e2e/backends/multimodal_micro_batch_e2e_test.dart new file mode 100644 index 000000000..51147f54f --- /dev/null +++ b/test/e2e/backends/multimodal_micro_batch_e2e_test.dart @@ -0,0 +1,261 @@ +@TestOn('vm') +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 30)) +library; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:llamadart/llamadart.dart'; +import 'package:test/test.dart'; + +/// An image whose projector decodes it non-causally against a context whose +/// micro-batch is smaller than the image, as in issue #958. +/// +/// Set `MULTIMODAL_MICRO_BATCH_MODEL` to a chat GGUF whose projector is +/// non-causal (Gemma 3, or a Gemma 4 model other than E2B and E4B) and +/// `MULTIMODAL_MICRO_BATCH_MMPROJ` to that projector. +/// `MULTIMODAL_MICRO_BATCH_BACKEND` is a `GpuBackend` name and defaults to +/// `cpu`. +void main() { + final modelPath = Platform.environment['MULTIMODAL_MICRO_BATCH_MODEL'] ?? ''; + final mmprojPath = + Platform.environment['MULTIMODAL_MICRO_BATCH_MMPROJ'] ?? ''; + final backend = GpuBackend.values.byName( + Platform.environment['MULTIMODAL_MICRO_BATCH_BACKEND'] ?? 'cpu', + ); + final skip = modelPath.isEmpty || mmprojPath.isEmpty + ? 'Set MULTIMODAL_MICRO_BATCH_MODEL and MULTIMODAL_MICRO_BATCH_MMPROJ ' + 'to a model with a non-causal projector.' + : null; + const greedy = GenerationParams(maxTokens: 8, temp: 0, seed: 1); + const question = LlamaTextContent( + 'What single color fills this image? Answer with one word.', + ); + final smallImage = _redBitmap(336); + final largeImage = _redBitmap(2016); + final splitWarnings = []; + + setUpAll( + () => LlamaLogging.configure( + level: LlamaLogLevel.warn, + nativeLevel: LlamaLogLevel.none, + handler: (record) { + if (record.message.contains('non-causal batches')) { + splitWarnings.add(record.message); + } + }, + ), + ); + + setUp(splitWarnings.clear); + + tearDownAll(LlamaLogging.configure); + + Future load({int batchSize = 0, int microBatchSize = 0}) => + LlamaEngine.load( + LlamaModel( + ModelSource.path(modelPath), + projector: ModelSource.path(mmprojPath), + ), + params: ModelParams( + contextSize: 4096, + gpuLayers: backend == GpuBackend.cpu ? 0 : ModelParams.maxGpuLayers, + preferredBackend: backend, + batchSize: batchSize, + microBatchSize: microBatchSize, + ), + ); + + Future colorOf(LlamaEngine engine, Uint8List image) async { + final reply = await engine.complete( + [ + LlamaChatMessage.withContent( + role: LlamaChatRole.user, + content: [ + LlamaImageContent(bytes: image), + question, + ], + ), + ], + params: greedy, + enableThinking: false, + ); + return reply.text.trim().toLowerCase(); + } + + void report(String name, Map result) { + // ignore: avoid_print + print( + 'MULTIMODAL_MICRO_BATCH ${jsonEncode({'case': name, 'backend': backend.name, ...result})}', + ); + } + + /// The image token count and the micro-batch a message names. + (int imageTokens, int microBatch) limits(String message) { + final match = RegExp( + r'image input has (\d+) tokens, more than the context.s micro-batch ' + r'of (\d+) tokens', + ).firstMatch(message); + expect(match, isNotNull, reason: message); + return (int.parse(match!.group(1)!), int.parse(match.group(2)!)); + } + + /// The typed error [engine] gives [image], after reporting it as [name]. + Future rejection( + String name, + LlamaEngine engine, + Uint8List image, + ) async { + Object? error; + String? answer; + try { + answer = await colorOf(engine, image); + } on LlamaException catch (caught) { + error = caught; + } + report(name, {'answer': answer, 'error': error?.toString()}); + expect(error, isA()); + expect(splitWarnings, isEmpty); + return error! as LlamaInferenceException; + } + + test('an image that fits the default micro-batch is answered', () async { + final engine = await load(); + addTearDown(engine.dispose); + + final answer = await colorOf(engine, smallImage); + + report('default sizes, small image', {'answer': answer}); + expect(answer, contains('red')); + expect(splitWarnings, isEmpty); + }, skip: skip); + + test('an image above an explicit micro-batch below the batch is a typed ' + 'error and the engine keeps working', () async { + final engine = await load(microBatchSize: 32); + addTearDown(engine.dispose); + + final error = await rejection( + 'microBatchSize 32, small image', + engine, + smallImage, + ); + + final (imageTokens, microBatch) = limits(error.message); + expect(microBatch, 32); + expect(imageTokens, greaterThan(32)); + expect(error.message, contains('ModelParams.microBatchSize')); + final text = await engine.complete(const [ + LlamaChatMessage.fromText( + role: LlamaChatRole.user, + text: 'Reply with the word ready.', + ), + ], params: greedy); + expect('${text.thinking}${text.text}', isNotEmpty); + }, skip: skip); + + for (final (batchSize, microBatchSize, image, name) in [ + (32, 32, smallImage, 'small image'), + (32, 0, smallImage, 'small image'), + (256, 256, largeImage, 'large image'), + (512, 512, largeImage, 'large image'), + ]) { + test('an image above a micro-batch equal to the batch ' + '($batchSize/$microBatchSize, $name) is answered in several ' + 'non-causal batches, with a warning', () async { + final engine = await load( + batchSize: batchSize, + microBatchSize: microBatchSize, + ); + addTearDown(engine.dispose); + + final answer = await colorOf(engine, image); + + report('batchSize $batchSize, microBatchSize $microBatchSize, $name', { + 'answer': answer, + 'warnings': splitWarnings, + }); + expect(answer, contains('red')); + expect(splitWarnings, hasLength(1)); + final (imageTokens, microBatch) = limits(splitWarnings.single); + expect(microBatch, batchSize); + expect(imageTokens, greaterThan(batchSize)); + }, skip: skip); + } + + test('a text turn after an image turn answers on a context that splits ' + 'the image', () async { + final engine = await load(batchSize: 32, microBatchSize: 32); + addTearDown(engine.dispose); + final session = ChatSession(engine); + + Future turn(List parts) => session + .create(parts, params: greedy, enableThinking: false) + .map((chunk) => chunk.choices.first.delta.content ?? '') + .join(); + + final first = await turn([LlamaImageContent(bytes: smallImage), question]); + final second = await turn(const [ + LlamaTextContent('Answer again with the same one word.'), + ]); + + report('32/32, image turn then text turn', { + 'first': first, + 'second': second, + 'warnings': splitWarnings.length, + }); + expect(first.toLowerCase(), contains('red')); + expect(second.toLowerCase(), contains('red')); + expect(splitWarnings, hasLength(2)); + }, skip: skip); + + test('an image above the default micro-batch is a typed error, and the ' + 'micro-batch the error names answers it in one pass', () async { + final engine = await load(); + addTearDown(engine.dispose); + + final error = await rejection( + 'default sizes, large image', + engine, + largeImage, + ); + final (imageTokens, microBatch) = limits(error.message); + expect(microBatch, ModelParams.defaultMicroBatchSize); + expect(imageTokens, greaterThan(microBatch)); + await engine.dispose(); + + final roomy = await load(batchSize: 2048, microBatchSize: imageTokens); + addTearDown(roomy.dispose); + final roomyAnswer = await colorOf(roomy, largeImage); + + report('microBatchSize $imageTokens, large image', {'answer': roomyAnswer}); + expect(roomyAnswer, contains('red')); + expect(splitWarnings, isEmpty); + }, skip: skip); +} + +/// A [side] by [side] 24-bit BMP filled with red. +Uint8List _redBitmap(int side) { + final rowBytes = (side * 3 + 3) & ~3; + final bytes = Uint8List(54 + rowBytes * side); + final header = ByteData.sublistView(bytes); + header.setUint8(0, 0x42); + header.setUint8(1, 0x4d); + header.setUint32(2, bytes.length, Endian.little); + header.setUint32(10, 54, Endian.little); + header.setUint32(14, 40, Endian.little); + header.setInt32(18, side, Endian.little); + header.setInt32(22, side, Endian.little); + header.setUint16(26, 1, Endian.little); + header.setUint16(28, 24, Endian.little); + header.setUint32(34, rowBytes * side, Endian.little); + for (var row = 0; row < side; row++) { + final start = 54 + row * rowBytes; + for (var column = 0; column < side; column++) { + bytes[start + column * 3 + 2] = 0xff; + } + } + return bytes; +} diff --git a/test/integration/backends/llama_cpp/native_symbol_integration_test.dart b/test/integration/backends/llama_cpp/native_symbol_integration_test.dart index 97750f048..8f466e642 100644 --- a/test/integration/backends/llama_cpp/native_symbol_integration_test.dart +++ b/test/integration/backends/llama_cpp/native_symbol_integration_test.dart @@ -65,6 +65,8 @@ const _mtmdChunkEvalSymbols = [ 'mtmd_input_chunks_size', 'mtmd_input_chunks_get', 'mtmd_input_chunk_get_type', + 'mtmd_input_chunk_get_n_tokens', + 'mtmd_decode_use_non_causal', 'mtmd_helper_eval_chunk_single', 'mtmd_encode_chunk', 'mtmd_get_output_embd', diff --git a/test/support/fake_mtmd.dart b/test/support/fake_mtmd.dart index aabea0465..036d30d13 100644 --- a/test/support/fake_mtmd.dart +++ b/test/support/fake_mtmd.dart @@ -11,9 +11,25 @@ import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; import 'package:llamadart/src/backends/llama_cpp/mtmd_chunk_eval.dart'; import 'package:llamadart/src/core/models/chat/content_part.dart'; +/// What a [FakeMtmd] with chunk-level functions presents its media part as. +enum FakeMtmdChunk { + /// A text chunk. + text, + + /// An image chunk the projector decodes causally. + causalImage, + + /// An image chunk the projector decodes non-causally. + nonCausalImage, +} + /// Stands in for libmtmd through [service]'s fallback API: a projector whose /// one media part evaluates [tokens] as text. /// +/// With an image [chunk] the chunk-level functions present the part as an +/// image chunk of [tokens]. A non-causal one is decoded with causal attention +/// off, as `mtmd_helper_decode_image_chunk` does. +/// /// It records the upstream mtmd function behind each call that creates, /// tokenizes with, evaluates with or frees the projector. A service on the /// tracked calls makes those through its `ExitTeardownApi` instead, so they @@ -26,6 +42,7 @@ final class FakeMtmd { this.service, { required this.tokens, this.chunkEval = false, + this.chunk = FakeMtmdChunk.text, this.decode = llama_decode, this.audioBitmap = _audioBitmap, }) { @@ -110,6 +127,9 @@ final class FakeMtmd { /// Whether the fallback has the chunk-level functions. final bool chunkEval; + /// What the chunk-level functions present the media part as. + final FakeMtmdChunk chunk; + /// The decode call the media evaluation makes. final int Function(Pointer context, llama_batch batch) decode; @@ -137,15 +157,30 @@ final class FakeMtmd { late final MtmdChunkEvalApi _chunkEvalApi = MtmdChunkEvalApi( chunksSize: (_) => 1, chunksGet: (_, _) => Pointer.fromAddress(0x40), - chunkType: (_) => mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_TEXT.value, + chunkType: (_) => chunk == FakeMtmdChunk.text + ? mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_TEXT.value + : mtmd_input_chunk_type.MTMD_INPUT_CHUNK_TYPE_IMAGE.value, + chunkTokenCount: (_) => tokens.length, + decodeUseNonCausal: (_, _) => chunk == FakeMtmdChunk.nonCausalImage, evalChunkSingle: (_, context, _, nPast, _, nBatch, _, newNPast) { calls.add('mtmd_helper_eval_chunk_single'); return evalMedia(context, nPast, nBatch, newNPast); }, - encodeChunk: (_, _) => throw StateError('unexpected mtmd call'), - outputEmbd: (_) => throw StateError('unexpected mtmd call'), - decodeImageChunk: (_, _, _, _, _, _, _, _) => - throw StateError('unexpected mtmd call'), + encodeChunk: (_, _) { + calls.add('mtmd_encode_chunk'); + return 0; + }, + outputEmbd: (_) => nullptr, + decodeImageChunk: (_, context, _, _, nPast, _, nBatch, newNPast) { + calls.add('mtmd_helper_decode_image_chunk'); + final nonCausal = chunk == FakeMtmdChunk.nonCausalImage; + if (nonCausal) llama_set_causal_attn(context, false); + try { + return evalMedia(context, nPast, nBatch, newNPast); + } finally { + if (nonCausal) llama_set_causal_attn(context, true); + } + }, ); /// Decodes [tokens] on [context] from [nPast] in batches of [nBatch]. diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_exit_teardown_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_exit_teardown_test.dart index b99ab166d..e07dbc7c3 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_exit_teardown_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_exit_teardown_test.dart @@ -430,6 +430,39 @@ void main() { }, ); + test('rejects a non-causal image above a micro-batch below the batch after ' + 'the tokenize, before any evaluating call', () async { + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + final small = service.createContext( + model, + const ModelParams( + gpuLayers: 0, + contextSize: 64, + batchSize: 16, + microBatchSize: 8, + ), + ); + final fake = mtmd = FakeMtmd.install( + service, + tokens: service.tokenize(model, 'abcdefgh', true), + chunkEval: true, + chunk: FakeMtmdChunk.nonCausalImage, + decode: recorder.api.decode, + ); + addTearDown(fake.dispose); + service.createMultimodalContext(model, projectorPath); + recorder.clearCalls(); + + await expectLater( + _generate(service, small, '<__media__>', _greedy, parts: fake.parts), + throwsA(isA()), + ); + + expect(recorder.calls, [_synchronize, 'llama_dart_mtmd_tokenize']); + expect(fake.calls, isEmpty); + }); + for (final chunkEval in [true, false]) { final evalCall = chunkEval ? 'mtmd_helper_eval_chunk_single' diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_media_micro_batch_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_media_micro_batch_test.dart new file mode 100644 index 000000000..bcdf8f6b2 --- /dev/null +++ b/test/unit/backends/llama_cpp/llama_cpp_service_media_micro_batch_test.dart @@ -0,0 +1,208 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/src/backends/llama_cpp/bindings.dart'; +import 'package:llamadart/src/backends/llama_cpp/exit_teardown_api.dart'; +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/llama_logger.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; +import 'package:llamadart/src/core/models/inference/generation_params.dart'; +import 'package:llamadart/src/core/models/inference/model_params.dart'; +import 'package:test/test.dart'; + +import '../../../support/fake_mtmd.dart'; +import '../../../support/synthetic_embedding_gguf.dart'; + +const _greedy = GenerationParams(maxTokens: 4, temp: 0, topK: 1, seed: 1); +const _imageText = 'abcdefgh'; +const _imageCalls = [ + 'mtmd_tokenize', + 'mtmd_encode_chunk', + 'mtmd_helper_decode_image_chunk', +]; + +String _splitWarning(int microBatch) => + 'llama_cpp_service: the image input has 12 tokens, more than the ' + "context's micro-batch of $microBatch 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 12 to decode it in one.'; + +// Runs the real llama.cpp runtime on the CPU with a stand-in projector whose +// non-causal image decode is a real non-causal llama_decode: one above +// n_ubatch aborts the process on llama.cpp's own assertion. +void main() { + late Directory dir; + late LlamaCppService service; + late FakeMtmd mtmd; + late int context; + late List warnings; + // Token count of each batch the image decode gave llama.cpp. + late List decoded; + + setUp(() { + dir = Directory.systemTemp.createTempSync('llamadart_media_ubatch_'); + writeSyntheticLlamaGguf('${dir.path}/model.gguf'); + File('${dir.path}/mmproj.gguf').writeAsStringSync('GGUF'); + service = LlamaCppService(objectCalls: LlamaCppObjectCalls.upstream) + ..initializeBackend(); + warnings = []; + decoded = []; + LlamaLogger.instance + ..setLevel(LlamaLogLevel.warn) + ..setHandler((record) { + if (record.level == LlamaLogLevel.warn) warnings.add(record.message); + }); + }); + + tearDown(() { + LlamaLogger.instance + ..setLevel(LlamaLogLevel.none) + ..setHandler(null); + service.dispose(); + mtmd.dispose(); + dir.deleteSync(recursive: true); + }); + + /// Loads the model with a projector whose one image has the 12 tokens of + /// [_imageText] and a BOS. + void load({ + required int batchSize, + required int microBatchSize, + FakeMtmdChunk chunk = FakeMtmdChunk.nonCausalImage, + bool chunkEval = true, + }) { + final params = ModelParams( + gpuLayers: 0, + contextSize: 64, + batchSize: batchSize, + microBatchSize: microBatchSize, + ); + final model = service.loadModel('${dir.path}/model.gguf', params); + context = service.createContext(model, params); + mtmd = FakeMtmd.install( + service, + tokens: service.tokenize(model, _imageText, true), + chunkEval: chunkEval, + chunk: chunk, + decode: (context, batch) { + decoded.add(batch.n_tokens); + return llama_decode(context, batch); + }, + ); + expect(mtmd.tokens, hasLength(12)); + service.createMultimodalContext(model, '${dir.path}/mmproj.gguf'); + mtmd.calls.clear(); + warnings.clear(); + } + + Future> generate(String prompt, {bool image = false}) async { + final cancel = calloc(); + try { + final chunks = await service + .generate( + context, + prompt, + _greedy, + cancel.address, + parts: image ? mtmd.parts : null, + ) + .toList(); + return [for (final chunk in chunks) ...chunk]; + } finally { + calloc.free(cancel); + } + } + + test('a non-causal image above a micro-batch below the batch is a typed ' + 'error before any evaluation, and the context still generates', () async { + load(batchSize: 16, microBatchSize: 8); + + await expectLater( + generate('<__media__>', image: true), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The image input has 12 tokens, more than the context\'s ' + 'micro-batch of 8 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 12, and ModelParams.batchSize with it, or pass a ' + 'smaller image if the projector sizes its output by the input.', + ), + ), + ); + + expect(mtmd.calls, ['mtmd_tokenize']); + expect(decoded, isEmpty); + expect(warnings, isEmpty); + await generate('ab'); + }); + + for (final (name, batchSize, microBatchSize) in [ + ('equal to the batch', 8, 8), + ('left unset under a smaller batch', 8, 0), + ('set above the batch', 8, 16), + ]) { + test('a non-causal image above a micro-batch $name is decoded in ' + 'batch-sized non-causal pieces with one warning', () async { + load(batchSize: batchSize, microBatchSize: microBatchSize); + + await generate('<__media__>', image: true); + + expect(mtmd.calls, _imageCalls); + expect(decoded, [8, 4]); + expect(warnings, [_splitWarning(8)]); + }); + } + + test('a later turn that holds the split image again answers as the first ' + 'did, with one warning a request', () async { + load(batchSize: 8, microBatchSize: 8); + + final first = await generate('<__media__>', image: true); + final second = await generate('<__media__>', image: true); + await generate('ab'); + + expect(second, first); + expect(decoded, [8, 4, 8, 4]); + expect(warnings, [_splitWarning(8), _splitWarning(8)]); + }); + + test('a non-causal image of exactly the micro-batch is decoded in one ' + 'pass', () async { + load(batchSize: 16, microBatchSize: 12); + + await generate('<__media__>', image: true); + + expect(mtmd.calls, _imageCalls); + expect(decoded, [12]); + expect(warnings, isEmpty); + }); + + test('a causal image above the micro-batch is decoded', () async { + load(batchSize: 8, microBatchSize: 4, chunk: FakeMtmdChunk.causalImage); + + await generate('<__media__>', image: true); + + expect(mtmd.calls, _imageCalls); + expect(decoded, [8, 4]); + expect(warnings, isEmpty); + }); + + test('a runtime without the chunk-level functions evaluates the prompt ' + 'unchecked', () async { + load(batchSize: 8, microBatchSize: 8, chunkEval: false); + + await generate('<__media__>', image: true); + + expect(mtmd.calls, ['mtmd_tokenize', 'mtmd_helper_eval_chunks']); + expect(warnings, isEmpty); + }); +} diff --git a/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart b/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart index f4d9a8dad..acf151f77 100644 --- a/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart +++ b/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart @@ -24,10 +24,11 @@ final _chunks = Pointer.fromAddress(0x300); final _embd = Pointer.fromAddress(0x400); class _FakeChunk { - const _FakeChunk(this.type, this.nPos); + const _FakeChunk(this.type, this.nPos, {this.nonCausal = false}); final int type; final int nPos; + final bool nonCausal; } class _FakeMtmd { @@ -62,6 +63,15 @@ class _FakeMtmd { calls.add('type ${_index(chunk)}'); return prompt[_index(chunk)].type; }, + chunkTokenCount: (chunk) { + calls.add('tokens ${_index(chunk)}'); + return prompt[_index(chunk)].nPos; + }, + decodeUseNonCausal: (ctx, chunk) { + expect(ctx, _ctx); + calls.add('nonCausal ${_index(chunk)}'); + return prompt[_index(chunk)].nonCausal; + }, evalChunkSingle: (ctx, lctx, chunk, nPast, seqId, nBatch, logitsLast, newNPast) { expect((ctx, lctx), (_ctx, _lctx)); @@ -280,6 +290,90 @@ void main() { }); } + group('findMtmdChunkAboveMicroBatch', () { + ({int chunkType, int tokenCount})? find(_FakeMtmd fake, int maxTokens) => + findMtmdChunkAboveMicroBatch(fake.api, _ctx, _chunks, maxTokens); + + test('returns the first non-causal media chunk above the limit', () { + final fake = _FakeMtmd(const [ + _FakeChunk(_text, 600), + _FakeChunk(_image, 256, nonCausal: true), + _FakeChunk(_image, 600), + _FakeChunk(_audio, 300, nonCausal: true), + _FakeChunk(_image, 280, nonCausal: true), + ], cancelToken); + + expect(find(fake, 256), (chunkType: _audio, tokenCount: 300)); + expect(fake.calls, [ + 'size', + 'get 0', + 'type 0', + 'get 1', + 'type 1', + 'tokens 1', + 'get 2', + 'type 2', + 'tokens 2', + 'nonCausal 2', + 'get 3', + 'type 3', + 'tokens 3', + 'nonCausal 3', + ]); + }); + + test('names an image chunk one token above the limit', () { + final fake = _FakeMtmd(const [ + _FakeChunk(_image, 257, nonCausal: true), + ], cancelToken); + + expect(find(fake, 256), (chunkType: _image, tokenCount: 257)); + }); + + test('returns null when every non-causal media chunk fits', () { + final fake = _FakeMtmd(const [ + _FakeChunk(_text, 600), + _FakeChunk(_image, 256, nonCausal: true), + _FakeChunk(_audio, 600), + _FakeChunk(7, 600, nonCausal: true), + ], cancelToken); + + expect(find(fake, 256), isNull); + }); + + test('makes none of the evaluating calls, with exit teardown too', () { + final fake = _FakeMtmd(const [ + _FakeChunk(_image, 64, nonCausal: true), + ], cancelToken); + final exit = RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + ); + + expect( + findMtmdChunkAboveMicroBatch( + fake.api.withExitTeardown(exit.api), + _ctx, + _chunks, + 32, + ), + (chunkType: _image, tokenCount: 64), + ); + expect(exit.calls, isEmpty); + expect(fake.calls, [ + 'size', + 'get 0', + 'type 0', + 'tokens 0', + 'nonCausal 0', + ]); + }); + }); + + test('mtmdMediaChunkName names image and audio chunks', () { + expect(mtmdMediaChunkName(_image), 'image'); + expect(mtmdMediaChunkName(_audio), 'audio'); + }); + test('tryLoad returns null when a library lacks the mtmd symbols', () { final library = DynamicLibrary.open(switch (Platform.operatingSystem) { 'macos' => '/usr/lib/libSystem.B.dylib', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index af314b957..f80022fca 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -107,6 +107,15 @@ For canonical full release notes, use: `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 diff --git a/website/docs/configuration/runtime-parameters.md b/website/docs/configuration/runtime-parameters.md index a94b517a0..1a6e46d0e 100644 --- a/website/docs/configuration/runtime-parameters.md +++ b/website/docs/configuration/runtime-parameters.md @@ -78,6 +78,15 @@ Important fields: non-causal attention models, and MEAN/CLS pooling embed each input in one micro-batch. `embed()` and `embedBatch()` throw `LlamaInferenceException` for longer input; raise `microBatchSize` and `batchSize` or shorten the input. + llama.cpp also 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 such an image across micro-batches: when the image has more + tokens than `n_ubatch` and `n_batch` is larger than `n_ubatch`, as with the + defaults, the prompt throws `LlamaInferenceException` before anything is + decoded. With `n_batch` equal to `n_ubatch` the image is decoded in several + batches instead, with a logged warning, which can reduce accuracy. The + default of `512` does not hold the largest Gemma 4 images + ([Image input exceeds `n_ubatch`](../troubleshooting/common-issues#image-input-exceeds-n_ubatch)). - `maxParallelSequences`: max sequence slots (`n_seq_max`) for parallel sequence workloads (for example, batched embeddings). - `loadMtp` (llama.cpp, native and WebGPU): load MTP tensors embedded in the diff --git a/website/docs/guides/multimodal.md b/website/docs/guides/multimodal.md index 25437c81b..8551d28b2 100644 --- a/website/docs/guides/multimodal.md +++ b/website/docs/guides/multimodal.md @@ -163,6 +163,13 @@ does not by itself provide a transcript contract. For typed transcription, see - Projector load success does not imply every modality is available. Re-check `capabilities.supportsVision` / `supportsAudio` after loading `mmproj`. - Keep context and generation budgets tighter than your text-only defaults. +- With a projector whose images llama.cpp decodes with non-causal attention + (Gemma 3 and Gemma 4 other than E2B and E4B, among others), an image + should fit `ModelParams.microBatchSize` (512 tokens by default). A larger + one throws `LlamaInferenceException` naming the size to load the model + with, or, when `batchSize` equals `microBatchSize`, is decoded in several + batches with a logged warning and possibly lower accuracy + ([Image input exceeds `n_ubatch`](../troubleshooting/common-issues#image-input-exceeds-n_ubatch)). - Follow-up turns after an image can still overflow the active context window if conversation history grows too large. - If multimodal is unstable on GPU, establish a working CPU baseline first. diff --git a/website/docs/troubleshooting/common-issues.md b/website/docs/troubleshooting/common-issues.md index c9c3d9c12..282d128bc 100644 --- a/website/docs/troubleshooting/common-issues.md +++ b/website/docs/troubleshooting/common-issues.md @@ -308,6 +308,33 @@ and MEAN/CLS pooling embed each input in one micro-batch. Shorten the input, or raise `ModelParams.microBatchSize` and `ModelParams.batchSize`. Batched embedding calls reject an oversized input before evaluating any of the batch. +### Image input exceeds `n_ubatch` + +`LlamaInferenceException`: +`The image input has tokens, more than the context's micro-batch of tokens (n_ubatch), and this projector decodes it with non-causal attention, which llama.cpp cannot split across micro-batches.` +llama.cpp decodes the images of some projectors with non-causal attention: +Gemma 3 and Gemma 4 other than E2B and E4B, among others. It decodes such an +image in pieces of the context's batch (`n_batch`), and each piece has to fit +one micro-batch (`n_ubatch`). The error is thrown when the image has more +tokens than the micro-batch and the batch is larger than the micro-batch, +which the default sizes of 2048 and 512 are. The prompt is rejected before +anything is decoded, and the engine stays usable. + +- Load the model with `ModelParams.microBatchSize` of at least `` and a + `ModelParams.batchSize` no smaller. The image is then decoded in one pass. + Gemma 4 gives an image up to 1120 tokens: a 2016 x 2016 image is 1089 + tokens with Gemma 4 12B. +- Or downscale the image, when the projector sizes its output by the image. +- With `batchSize` equal to `microBatchSize` there is no error: the image is + decoded in several non-causal batches, whose tokens do not all attend to + each other, and llamadart logs one warning per request (at + `LlamaLogLevel.warn`). Answers can be less accurate than with the whole + image in one pass. + +A runtime without llama.cpp's chunk-level multimodal functions, which the +pinned one has, is not checked: the failing configuration still aborts the +process there. + ### Recurrent speculative rollback is unsupported Native llama.cpp rejects a nonzero `ModelParams.speculativeRollbackTokenMax`