From 6bc6c2a64cbe9a23edf87a9175160d8222cf49e7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:17:41 -0400 Subject: [PATCH 1/7] docs: allow landing audited PRs as a batch integration PR (#989) --- AGENTS.md | 18 ++- doc/high_risk_pre_merge_readiness.md | 133 ++++++++++++++++++ .../tooling/high_risk_review_policy_test.dart | 17 +++ 3 files changed, 164 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0c96cf668..d1b836e10 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -164,10 +164,20 @@ analyze and the relevant tests before the final commit. - Use the closest affected-family model or artifact; if its weights are unavailable, name each unavailable family and use primary upstream emissions plus durable fixtures. An unrelated model is pipeline-only evidence. -- Post-merge QA is still required but is never the first adversarial pass. If - it finds a PR-caused P1, stop lower-priority merge work, file a causally - accurate issue, and prepare one cohesive recovery before resuming feature - work. +- Several PRs may land as one batch integration PR. High-risk constituents are + audited at their own exact head as above and standard-risk ones pinned at the + head whose CI passed; they are then combined on a new branch cut from current + `main`, one commit per PR, and landed with a rebase merge, never squash. A + constituent audit lets its diff land through a batch + only together with a passing integration audit of the integration head. + Dropping or replacing a constituent, or `main` moving, means + a new integration branch and PR. + Procedure: `doc/high_risk_pre_merge_readiness.md`, "Batch integration PR". +- Post-merge QA is still required but is never the first adversarial pass. When + the merged tree equals an audited head, it need not repeat checks the + independent audit already ran on that head. If it finds a PR-caused P1, stop + lower-priority merge work, file a causally accurate issue, and prepare one + cohesive recovery before resuming feature work. ## This file diff --git a/doc/high_risk_pre_merge_readiness.md b/doc/high_risk_pre_merge_readiness.md index 1f0c4cf43..7b416d896 100644 --- a/doc/high_risk_pre_merge_readiness.md +++ b/doc/high_risk_pre_merge_readiness.md @@ -228,6 +228,139 @@ add a focused rendering regression in that case. No unrelated compiled-grammar edit is required. This policy example is not a claim that historical #529 had already supplied v2 causal evidence or an authenticated audit. +## Batch integration PR + +Whenever a PR head moves, earlier CI runs, approvals, audits and matrix +evidence no longer count. Landing N high-risk PRs one at a time therefore +costs N rounds of merging `main` in, re-audit, CI and post-merge QA. A batch +integration PR is the allowed alternative. It changes nothing for a PR that +lands on its own. + +A release-prep PR is never a constituent, and the integration PR never carries +the `release-prep` label or a `release/prep-*` branch name. + +1. **Constituent gates.** Each constituent PR first passes its own pre-merge + gate at its own exact head, exactly as if it were landing alone. + - A high-risk constituent has its [independent audit](#independent-audit) + at that head: blocking-only, by an auditor who took no part in the + implementation, with decision `accepted`, zero known PR-caused P1 + regressions and zero unresolved review threads. + - A standard-risk constituent is pinned at the exact head whose CI passed. + + A constituent whose head moves afterwards passes its gate again at the new + head before it joins a batch. +2. **Integration branch.** Cut a new branch from current `main` and add the + constituents as one commit each, so each stays individually revertable. + Each commit subject ends with `(#)`. Resolve + conflicts once, inside the commit of the constituent being applied. Publish + the branch through `tool/git/safe_pr_head_update.dart`. +3. **Conflict resolutions.** A resolution only reconciles hunks that two sides + both changed: a real merge conflict, or the mechanical union of changelog + or doc lines. Anything else, including a fix for a defect found in a + constituent, goes back to that constituent's PR and is re-audited there. +4. **Integration PR body.** Besides the normal template, it lists: + - for every constituent, its PR number, risk class, pinned head SHA and + audit result (or the passing CI run for a standard-risk one); + - every conflict resolution, listed per hunk, not per file; + - the closing keywords (`Closes #N`) of every constituent, because a PR + that is closed without merging does not close its issues. +5. **Integration audit.** One independent auditor reviews the integration PR's + exact head against current `main`, blocking-only. The auditor took no part + in implementing any constituent or in the integration; having audited a + constituent does not disqualify. The audit checks only what is new: + - the tree is a clean combination of the pinned heads plus the listed + resolutions and nothing else: each commit's diff matches + `git diff main...` of its constituent, for audited and + standard-risk constituents alike, and every difference is a listed hunk; + - each listed resolution, reviewed as a change in its own right; + - the full default suites and the relevant real-model smokes pass on the + combined tree; + - the readiness evidence is valid for the integration head (below). + + A constituent audit lets its diff land through a batch + only together with a passing integration audit of the integration head. It + stays valid for landing that PR alone at its audited head against the base + it was audited on, under the normal single-PR rules. +6. **CI** runs once, on the integration head. +7. **Review threads.** Before the merge, every review thread on the + integration PR and on every constituent PR is replied to and resolved. The + live unresolved count per constituent, which must be 0, is recorded in the + integration PR body at merge time. +8. **Merge** with a rebase merge, never squash, so `main` stays linear and + keeps one commit per constituent. Only then close each constituent PR with + a link to the integration PR. +9. **Post-merge QA** runs once for the batch. See + [Post-merge QA scope](#post-merge-qa-scope). + +### When the batch has to change + +`tool/git/safe_pr_head_update.dart` is fast-forward only, so the integration +branch can only gain commits. Appending a constituent moves the integration +head, so its audit, CI and evidence are redone. Each of these needs a +new integration branch and PR cut from current `main`, and the old integration +PR is closed: + +- dropping a constituent; +- replacing a constituent's commit after that constituent was fixed and + re-audited in its own PR; +- `main` moving after the branch was cut. + +The integration branch never takes a history rewrite, a revert commit or a +merge-from-`main` commit. If the integration audit finds a problem caused by +one constituent, that constituent is either fixed in its own PR or dropped; +both lead to a new integration branch. Its audit, CI and evidence are done +against the new integration head; the gates of the untouched constituents +still stand. A PR-caused P1 found in post-merge QA is handled as for any other +merge. + +### Evidence for the integration head + +The integration PR is an ordinary PR to the evaluator. Its evidence document +binds the integration PR number, author, exact head and current base; its +`independent_audit` is the integration audit; and its surfaces, matrix rows, +impacts and `test_evidence` cover the whole combined diff, which the evaluator +derives from Git as usual. That includes `test_evidence` controls for the +changed `lib/`, `tool/` and `hook/` paths of standard-risk constituents, which +had none of their own. Each high-risk constituent keeps its own evidence +document for its own audited head. + +A `test_evidence` control (`control_result`) observed on a constituent's +audited head may be carried over only when every `production_refs` path and +the cited test file are identical on the integration head: + +```bash +git diff --exit-code -- +``` + +Take the paths from the evidence and check that each exists at both commits; a +mistyped path prints nothing. Re-observe the control on the integration head +when the files differ, or when another constituent, or `main` since the +constituent's audited base, changed anything the test runs through. A cited +`local-only` test is always re-run on the integration head. + +The schema has no field for constituent PR numbers, pinned heads, audit +results or conflict resolutions. Those live in the integration PR body, and the +integration audit's `summary` names the constituents it verified. The +readiness tool therefore cannot check the clean-combination claim; it rests on +the integration auditor. + +## Post-merge QA scope + +Post-merge QA is still required and is never the first adversarial pass. When +the merged tree equals an audited head, it need not repeat checks the +independent audit already ran on that head. Compare the tree of the commit +`main` points to once the merge lands (after a rebase merge, the last rebased +commit) with the audited head's tree: + +```bash +git rev-parse ^{tree} ^{tree} +``` + +QA is then limited to what cannot be checked before merge: workflow runs on +`main`, deployed demos and anything else environment-specific. Local suites +are not repeated. When the trees differ, the checks run on the audited head do +not carry over. + ## CLI ```bash diff --git a/test/unit/tooling/high_risk_review_policy_test.dart b/test/unit/tooling/high_risk_review_policy_test.dart index 2d4958007..9fafd9b3b 100644 --- a/test/unit/tooling/high_risk_review_policy_test.dart +++ b/test/unit/tooling/high_risk_review_policy_test.dart @@ -40,6 +40,23 @@ void main() { expect(matrix, contains('compiled production-path coverage')); }); + test('batch integration PR rule keeps its audit and merge boundaries', () { + final agentGuidance = read('AGENTS.md'); + final runbook = read('doc/high_risk_pre_merge_readiness.md'); + const auditBoundary = + 'only together with a passing integration audit of the integration ' + 'head'; + + for (final document in [agentGuidance, runbook]) { + expect(document, contains('rebase merge, never squash')); + expect(document, contains(auditBoundary)); + } + expect(agentGuidance, contains('a new integration branch and PR')); + expect(runbook, contains('listed per hunk, not per file')); + expect(runbook, contains('new integration branch and PR cut from')); + expect(runbook, contains('reviewed as a change in its own right')); + }); + test('classifier help preserves rename and deletion visibility', () { final classifier = read('tool/testing/classify_high_risk_changes.dart'); From c0f050bb367da555f36b53d743c68f07ac15b09d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:17:41 -0400 Subject: [PATCH 2/7] fix: keep a reply's trailing whitespace out of the CLI example history and the chat app token count (#990) --- .../lib/services/chat_generation_service.dart | 14 +- .../test/chat_generation_service_test.dart | 26 ++ .../llamadart_cli/lib/src/chat_runner.dart | 24 +- .../llamadart_cli/test/chat_runner_test.dart | 267 ++++++++++++++++++ .../test/coding_agent_session_test.dart | 2 +- .../docs/guides/generation-and-streaming.md | 4 +- 6 files changed, 327 insertions(+), 10 deletions(-) create mode 100644 example/llamadart_cli/test/chat_runner_test.dart diff --git a/example/chat_app/lib/services/chat_generation_service.dart b/example/chat_app/lib/services/chat_generation_service.dart index 58ad32209..3e573a640 100644 --- a/example/chat_app/lib/services/chat_generation_service.dart +++ b/example/chat_app/lib/services/chat_generation_service.dart @@ -257,8 +257,18 @@ class ChatGenerationService { fullThinking += thinking .replaceAll(r'\n', '\n') .replaceAll(r'\r', '\r'); - generatedTokens++; - pendingTokenDelta += 1; + // The whitespace that ends a reply arrives as a chunk of its own + // after the text; counting it would raise this chunk-count fallback + // by one for the same reply. + final isWhitespaceOnly = + content.isNotEmpty && + content.trim().isEmpty && + thinking.trim().isEmpty && + chunk.toolCalls.isEmpty; + if (!isWhitespaceOnly) { + generatedTokens++; + pendingTokenDelta += 1; + } cleanTarget = cleanResponse(fullResponse); if (visibleCleanText.isEmpty && cleanTarget.isNotEmpty) { diff --git a/example/chat_app/test/chat_generation_service_test.dart b/example/chat_app/test/chat_generation_service_test.dart index 1e8147c30..f6e4a5482 100644 --- a/example/chat_app/test/chat_generation_service_test.dart +++ b/example/chat_app/test/chat_generation_service_test.dart @@ -156,6 +156,32 @@ void main() { expect(updates.last.shouldNotify, isTrue); }); + test('does not count the whitespace chunk that ends a reply', () async { + final updates = []; + final result = await service.consumeStream( + stream: Stream.fromIterable( + [ + _chunk(content: '4'), + _chunk(content: '\n'), + _chunk(), + ], + ), + thinkingEnabled: true, + uiNotifyIntervalMs: -1, + cleanResponse: (value) => value, + shouldContinue: () => true, + onUpdate: updates.add, + ); + + expect(result.fullResponse, '4\n'); + expect(updates.last.cleanText, '4\n'); + expect(result.generatedTokens, 2); + expect( + updates.fold(0, (sum, update) => sum + update.generatedTokenDelta), + 2, + ); + }); + test('smooths large streamed chunks and flushes final text', () async { final longChunk = List.filled(260, 'x').join(); final updates = []; diff --git a/example/llamadart_cli/lib/src/chat_runner.dart b/example/llamadart_cli/lib/src/chat_runner.dart index 32df4bcad..8f6a2157e 100644 --- a/example/llamadart_cli/lib/src/chat_runner.dart +++ b/example/llamadart_cli/lib/src/chat_runner.dart @@ -16,6 +16,7 @@ class LlamaCliRunner { final LlamaCliConfig config; final ModelLocator _modelLocator; + final LlamaEngine? _injectedEngine; final List _history = []; LlamaEngine? _engine; @@ -30,8 +31,11 @@ class LlamaCliRunner { bool get _simpleIo => config.simpleIo; /// Creates a runner for one CLI invocation. - LlamaCliRunner(this.config) - : _modelLocator = ModelLocator(modelsDirectory: config.modelsDirectory); + /// + /// [engine] replaces the default llama.cpp engine, for tests. + LlamaCliRunner(this.config, {LlamaEngine? engine}) + : _modelLocator = ModelLocator(modelsDirectory: config.modelsDirectory), + _injectedEngine = engine; /// Starts model resolution, loading, and chat mode. Future run() async { @@ -44,8 +48,7 @@ class LlamaCliRunner { ); _loadedModelPath = modelPath; - final backend = LlamaBackend(); - final engine = LlamaEngine(backend); + final engine = _injectedEngine ?? LlamaEngine(LlamaBackend()); _engine = engine; await LlamaLogging.configure(nativeLevel: LlamaLogLevel.warn); @@ -265,6 +268,10 @@ class LlamaCliRunner { final assistantText = StringBuffer(); final assistantThinking = StringBuffer(); var printedThinkingStart = false; + // A reply keeps the whitespace the model ended it with. It is printed and + // stored only once more text follows, so the transcript and the next + // prompt do not gain it. + var heldWhitespace = ''; try { await for (final chunk in engine.create(messages, params: turnParams)) { final thinking = chunk.thinking; @@ -279,8 +286,13 @@ class LlamaCliRunner { final content = chunk.text; if (content.isNotEmpty) { - assistantText.write(content); - stdout.write(content); + final pending = heldWhitespace + content; + final visible = pending.trimRight(); + heldWhitespace = pending.substring(visible.length); + if (visible.isNotEmpty) { + assistantText.write(visible); + stdout.write(visible); + } } } stdout.writeln(); diff --git a/example/llamadart_cli/test/chat_runner_test.dart b/example/llamadart_cli/test/chat_runner_test.dart new file mode 100644 index 000000000..b6b631a35 --- /dev/null +++ b/example/llamadart_cli/test/chat_runner_test.dart @@ -0,0 +1,267 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_cli_example/llamadart_cli.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + late Directory tempDir; + late String modelPath; + + setUp(() async { + tempDir = await Directory.systemTemp.createTemp('llamadart_cli_runner_'); + modelPath = p.join(tempDir.path, 'model.gguf'); + await File(modelPath).writeAsBytes(const []); + }); + + tearDown(() async { + await tempDir.delete(recursive: true); + }); + + LlamaCliConfig configFor({required bool simpleIo}) => LlamaCliConfig( + showHelp: false, + modelPathOrUrl: modelPath, + modelsDirectory: tempDir.path, + interactive: true, + interactiveFirst: false, + contextSize: 4096, + gpuLayers: 0, + threads: 1, + threadsBatch: 1, + maxTokens: 8, + temperature: 0, + topK: 40, + topP: 0.95, + minP: 0.05, + repeatPenalty: 1, + fitContext: true, + jinja: true, + instruct: false, + simpleIo: simpleIo, + color: false, + reversePrompts: const [], + ); + + Future runPiped(_QueuedBackend backend, String input) async { + final output = _RecordingStdout(); + final runner = LlamaCliRunner( + configFor(simpleIo: true), + engine: LlamaEngine(backend), + ); + await IOOverrides.runZoned( + () async { + try { + await runner.run(); + } finally { + await runner.dispose(); + } + }, + stdout: () => output, + stdin: () => _PipedStdin(input), + ); + return output.text; + } + + test( + 'a reply ending in a newline is stored and printed without it', + () async { + final backend = _QueuedBackend() + ..queueResponse(['4', '\n']) + ..queueResponse(['6']); + + final transcript = await runPiped(backend, '2+2?\n3+3?\n'); + + expect(backend.prompts, hasLength(2)); + expect( + backend.prompts[1], + '<|im_start|>user\n2+2?<|im_end|>\n' + '<|im_start|>assistant\n4<|im_end|>\n' + '<|im_start|>user\n3+3?<|im_end|>\n' + '<|im_start|>assistant\n', + ); + expect(transcript, endsWith('> \n4\n\n> \n6\n\n\nExiting...\n')); + }, + ); + + test('whitespace inside a reply is printed and stored', () async { + final backend = _QueuedBackend() + ..queueResponse(['a', '\n\n', 'b ', ' ']) + ..queueResponse(['c']); + + final transcript = await runPiped(backend, 'one\ntwo\n'); + + expect(transcript, contains('> \na\n\nb\n\n> \nc\n\n')); + expect(backend.prompts[1], contains('assistant\na\n\nb<|im_end|>')); + }); +} + +class _QueuedBackend implements LlamaBackend { + final List> _responses = >[]; + final List prompts = []; + + void queueResponse(List chunks) => _responses.add(chunks); + + @override + bool get isReady => true; + + @override + Future modelLoad(String path, ModelParams params) async => 1; + + @override + Future modelLoadFromUrl( + String url, + ModelParams params, { + Function(double progress)? onProgress, + }) async => 1; + + @override + Future modelFree(int modelHandle) async {} + + @override + Future contextCreate(int modelHandle, ModelParams params) async => 1; + + @override + Future contextFree(int contextHandle) async {} + + @override + Future getContextSize(int contextHandle) async => 4096; + + @override + Stream> generate( + int contextHandle, + String prompt, + GenerationParams params, { + List? parts, + }) async* { + prompts.add(prompt); + for (final chunk in _responses.removeAt(0)) { + yield utf8.encode(chunk); + } + } + + @override + void cancelGeneration() {} + + @override + Future> tokenize( + int modelHandle, + String text, { + bool addSpecial = true, + }) async => List.filled(utf8.encode(text).length, 0); + + @override + Future detokenize( + int modelHandle, + List tokens, { + bool special = false, + }) async => ''; + + @override + Future> modelMetadata(int modelHandle) async => + { + 'tokenizer.chat_template': + '{% for message in messages %}' + "{{ '<|im_start|>' + message['role'] + '\\n' " + "+ message['content'] + '<|im_end|>' + '\\n' }}" + '{% endfor %}' + "{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}" + '{% endif %}', + }; + + @override + Future setLoraAdapter( + int contextHandle, + String path, + double scale, + ) async {} + + @override + Future removeLoraAdapter(int contextHandle, String path) async {} + + @override + Future clearLoraAdapters(int contextHandle) async {} + + @override + Future getBackendName() async => 'queued-test'; + + @override + bool get supportsUrlLoading => false; + + @override + Future isGpuSupported() async => false; + + @override + Future setLogLevel(LlamaLogLevel level) async {} + + @override + Future dispose() async {} + + @override + Future multimodalContextCreate( + int modelHandle, + String mmProjPath, + ) async => null; + + @override + Future multimodalContextFree(int mmContextHandle) async {} + + @override + Future supportsVision(int mmContextHandle) async => false; + + @override + Future supportsAudio(int mmContextHandle) async => false; + + @override + Future<({int total, int free})> getVramInfo() async => (total: 0, free: 0); + + @override + Future applyChatTemplate( + int modelHandle, + List> messages, { + String? customTemplate, + bool addAssistant = true, + }) async => ''; +} + +class _RecordingStdout implements Stdout { + final StringBuffer _buffer = StringBuffer(); + + String get text => _buffer.toString(); + + @override + void write(Object? object) => _buffer.write(object); + + @override + void writeln([Object? object = '']) => _buffer.writeln(object); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _PipedStdin extends Stream> implements Stdin { + final String _input; + + _PipedStdin(this._input); + + @override + bool get hasTerminal => false; + + @override + StreamSubscription> listen( + void Function(List event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) => Stream>.value(utf8.encode(_input)).listen( + onData, + onError: onError, + onDone: onDone, + cancelOnError: cancelOnError, + ); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/example/tui_coding_agent/test/coding_agent_session_test.dart b/example/tui_coding_agent/test/coding_agent_session_test.dart index 82608340e..ca8ef4ca6 100644 --- a/example/tui_coding_agent/test/coding_agent_session_test.dart +++ b/example/tui_coding_agent/test/coding_agent_session_test.dart @@ -359,7 +359,7 @@ void main() { .where((event) => event.type == SessionEventType.assistantToken) .map((event) => event.message) .join(), - 'First ', + 'First', ); releaseGeneration.complete(); diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 4abbe2bc1..cdc1c9b9b 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -117,7 +117,9 @@ messages.add(completion.message); // Assistant turn for the next request. `engine.complete(messages, ...)` is `engine.create(messages, ...).collect()`, and `session.send('...')` sends one text turn through a `ChatSession` and -collects the reply. +collects the reply. `completion.message` keeps the whitespace the model ended +the reply with; `ChatSession` stores the turn without it, so `trimRight()` the +text of a turn you keep yourself if the next prompt should not carry it. `finishReason` does not tell you that a generation was cancelled. On native llama.cpp and LiteRT-LM, a stream stopped by `engine.cancelGeneration()`, From 612603ad3e4cb582959523cc3829c4fb94cd4531 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:17:41 -0400 Subject: [PATCH 3/7] fix: reject an image above the micro-batch of a non-causal projector with a typed error (#984) --- CHANGELOG.md | 9 + doc/llama_cpp_exit_teardown.md | 6 +- doc/testing_matrix.md | 23 ++ example/chat_app/README.md | 16 +- .../backends/llama_cpp/llama_cpp_service.dart | 51 ++++ .../backends/llama_cpp/mtmd_chunk_eval.dart | 79 +++++- .../core/models/inference/model_params.dart | 8 + skills/llamadart-multimodal/SKILL.md | 9 + .../multimodal_micro_batch_e2e_test.dart | 261 ++++++++++++++++++ .../native_symbol_integration_test.dart | 2 + test/support/fake_mtmd.dart | 45 ++- .../llama_cpp_service_exit_teardown_test.dart | 33 +++ ...ma_cpp_service_media_micro_batch_test.dart | 208 ++++++++++++++ .../llama_cpp/mtmd_chunk_eval_test.dart | 96 ++++++- website/docs/changelog/recent-releases.md | 9 + .../docs/configuration/runtime-parameters.md | 9 + website/docs/guides/multimodal.md | 7 + website/docs/troubleshooting/common-issues.md | 27 ++ 18 files changed, 881 insertions(+), 17 deletions(-) create mode 100644 test/e2e/backends/multimodal_micro_batch_e2e_test.dart create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_media_micro_batch_test.dart 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` From 6eccb3826228fbb2d68695b26f53b2af7e16a34b Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:17:53 -0400 Subject: [PATCH 4/7] fix: make all in llamadart_native_runtimes include stable_diffusion (#985) --- CHANGELOG.md | 13 + README.md | 17 +- example/basic_app/README.md | 5 + example/basic_app/pubspec.yaml | 4 +- example/chat_app/README.md | 6 +- example/chat_app/pubspec.yaml | 19 +- hook/build.dart | 30 +- .../stable_diffusion_runtime_io.dart | 21 +- .../core/image/image_generation_engine.dart | 11 +- lib/src/hook/native_bundle_config.dart | 70 ++-- .../README.md | 5 + skills/llamadart-flutter-app/SKILL.md | 11 +- skills/llamadart-image-generation/SKILL.md | 19 +- .../stable_diffusion_runtime_hook_test.dart | 64 +++- .../stable_diffusion_runtime_io_test.dart | 24 +- .../hook/build_hook_integration_test.dart | 4 +- ...build_hook_litert_lm_integration_test.dart | 15 +- ...ook_stable_diffusion_integration_test.dart | 322 ++++++++++++++++-- test/unit/hook/native_bundle_config_test.dart | 195 +++++++++-- website/docs/changelog/recent-releases.md | 13 + website/docs/guides/backend-selection.md | 4 +- website/docs/guides/image-generation.md | 26 +- website/docs/platforms/native-build-hooks.md | 56 ++- 23 files changed, 771 insertions(+), 183 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10ca8272b..d10f66bbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -107,6 +107,19 @@ 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)). +- **Behavior change:** `all` in `llamadart_native_runtimes` now includes the + opt-in `stable_diffusion` image runtime, so `llamadart_native_runtimes: all` + ships GGUF, `.litertlm` and image generation together. An app that already + sets `all`, or a list containing it, downloads 14.7 to 15.6 MB more per + target, or 25.8 to 27.8 MB for the Vulkan build Linux and Windows use by + default, and grows by about 37 MB as measured on macOS arm64 and Android + arm64. android-x64 and Windows arm64 publish no image runtime and skip it + with a warning. A Flutter iOS or macOS app skips it with a build warning + unless `llamadart_stable_diffusion_flutter` is a dependency; a pub + workspace member, whose user-defines live in the workspace root pubspec, is + not recognised as one and bundles it. Leaving the key unset, or setting + `both`, still bundles only `llama_cpp` and `litert_lm` + ([#856](https://github.com/leehack/llamadart/issues/856)). ## 0.11.1 diff --git a/README.md b/README.md index ac7d9aaae..a0cbf508f 100644 --- a/README.md +++ b/README.md @@ -99,18 +99,25 @@ experimental and may change, and the runtime is opt-in. hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_native_runtimes: all ``` - Keep `litert_lm` in the list if the app also loads `.litertlm` models. + Unset, the key bundles `llama_cpp` and `litert_lm`. A list replaces those + defaults, so it names everything the app loads: + - `all`: every runtime published for the target, `llama_cpp`, `litert_lm` + and `stable_diffusion`. + - `[llama_cpp, stable_diffusion]`: GGUF chat and images, no LiteRT-LM. + - `[stable_diffusion]`: images only. - **Flutter iOS/macOS apps** should add the `llamadart_stable_diffusion_flutter` companion (see [Install](#install)), which links the runtime through Swift Package Manager and selects it without the entry above. Pair companion `0.0.2` with core `0.11.1` and `0.11.0`. - Without it the hook bundles the runtime, App Store Connect rejects that iOS - framework's `MinimumOSVersion`, and only Xcode and `xcodebuild` show the - build warning about it. + Without it, `all` leaves the image runtime out of a Flutter iOS/macOS app + with a build warning. A list naming `stable_diffusion` bundles it through + the hook instead, and App Store Connect rejects that iOS framework's + `MinimumOSVersion`. `flutter build ios` output shows neither warning; Xcode + and `xcodebuild` show both. - **Platforms:** Android arm64 (CPU), iOS and macOS (Metal), Linux arm64/x64 and Windows x64 (CPU or Vulkan). Not available on the web yet diff --git a/example/basic_app/README.md b/example/basic_app/README.md index 61eb6b756..6ce0bd43e 100644 --- a/example/basic_app/README.md +++ b/example/basic_app/README.md @@ -232,6 +232,11 @@ hooks: llamadart_native_runtimes: [llama_cpp, stable_diffusion] ``` +Unset, the key bundles `llama_cpp` and `litert_lm`; a list replaces those +defaults. This one ships GGUF chat and images without LiteRT-LM, which no +example here loads; `all` ships every runtime published for the target, and +`[stable_diffusion]` images only. + The first run downloads the runtime (40 to 70 MB) through the build hook. `ImageGenerationEngine.load` then downloads the files this example pins for the preset in `lib/services/image_cli_options.dart`, unless a flag names a diff --git a/example/basic_app/pubspec.yaml b/example/basic_app/pubspec.yaml index 89d3457ff..5d5d3a0bd 100644 --- a/example/basic_app/pubspec.yaml +++ b/example/basic_app/pubspec.yaml @@ -21,5 +21,7 @@ dev_dependencies: hooks: user_defines: llamadart: - # The image example needs the opt-in stable_diffusion runtime. + # The image example needs the opt-in stable_diffusion runtime. A list + # replaces the defaults; every example here loads GGUF, so litert_lm is + # left out. `all` would keep it. llamadart_native_runtimes: [llama_cpp, stable_diffusion] diff --git a/example/chat_app/README.md b/example/chat_app/README.md index f05010b08..a9a8c82e4 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -68,8 +68,10 @@ targets. It also opts into the experimental `stable_diffusion` runtime for the image screen, which adds about 37 MB per iOS, macOS and Android arm64 target and 38 to 72 MB on Linux and Windows (CPU or Vulkan build; Vulkan by default), and declares `llamadart_stable_diffusion_flutter` so iOS and macOS link it -through SwiftPM. Android x64 has no `stable_diffusion` build and skips it with -a build warning; the Windows arm64 entry leaves it out. If you copy +through SwiftPM. Its `llamadart_native_runtimes` is `all`, every runtime +published for the target; unset, the key bundles only `llama_cpp` and +`litert_lm`. Android x64 and Windows arm64 have no `stable_diffusion` build and +skip it with a build warning. If you copy this app and only ship GGUF models, set `llamadart_native_runtimes` to `[llama_cpp]` and keep only `llamadart_llama_cpp_flutter` to reduce bundle size. Flutter iOS/macOS apps should declare the companion package for every diff --git a/example/chat_app/pubspec.yaml b/example/chat_app/pubspec.yaml index 1b19ad331..293f85092 100644 --- a/example/chat_app/pubspec.yaml +++ b/example/chat_app/pubspec.yaml @@ -58,15 +58,10 @@ hooks: llamadart: # The chat example intentionally demonstrates both GGUF and .litertlm # model flows, plus the opt-in stable_diffusion runtime for its image - # screen. On iOS and macOS the companion packages above link these - # runtimes through Swift Package Manager instead. android-x64 has no - # stable_diffusion build and skips it with a build warning; the entries - # below leave out what is not published. Smaller examples rely on the - # package defaults. - llamadart_native_runtimes: - runtimes: [llama_cpp, litert_lm, stable_diffusion] - platforms: - # No LiteRT-LM bundle for these targets, nor stable_diffusion for - # windows-arm64. - ios-x86_64-sim: [llama_cpp, stable_diffusion] - windows-arm64: [llama_cpp] + # screen: `all` is llama_cpp, litert_lm and stable_diffusion. On iOS and + # macOS the companion packages above link these runtimes through Swift + # Package Manager instead. android-x64 has no stable_diffusion build + # and windows-arm64 has neither that nor LiteRT-LM; each skips what it + # lacks with a build warning. Smaller examples rely on the package + # defaults. + llamadart_native_runtimes: all diff --git a/hook/build.dart b/hook/build.dart index 3a4de49fa..38f5a3bff 100644 --- a/hook/build.dart +++ b/hook/build.dart @@ -184,6 +184,33 @@ void main(List args) async { !selectedRuntimes.contains(nativeRuntimeStableDiffusion)) { selectedRuntimes = [...selectedRuntimes, nativeRuntimeStableDiffusion]; } + if (appleCompanions != null && + !stableDiffusionCompanion && + selectedRuntimes.contains(nativeRuntimeStableDiffusion) && + !nativeRuntimeExplicitlySelectedForBundle( + bundle: spec.bundle, + rawUserConfig: rawNativeRuntimeConfig, + runtime: nativeRuntimeStableDiffusion, + )) { + // App Store Connect rejects the iOS framework Flutter wraps the + // hook-bundled library in, and only the companion's XCFramework carries + // the privacy manifest, so `all` alone must not start shipping it. + selectedRuntimes = selectedRuntimes + .where((runtime) => runtime != nativeRuntimeStableDiffusion) + .toList(growable: false); + const skipped = + 'stable_diffusion is only implied by `all` in ' + '$nativeRuntimesUserDefineKey, so this Flutter iOS/macOS build ' + 'leaves the image runtime out: $_stableDiffusionFlutterPackageName ' + 'is not a dependency. Add that package to link the runtime through ' + 'Swift Package Manager, or name stable_diffusion to bundle it ' + 'through the hook.'; + log.warning('$skipped (${spec.bundle})'); + // Hook log records stay in the hooks_runner stdout.txt; Flutter relays + // hook stderr into the Xcode build, where a `warning:` line becomes an + // Xcode build warning. + stderr.writeln('warning: llamadart: $skipped'); + } final liteRtLmBundleSpec = _liteRtLmBundleSpecForCode(code); if (selectedRuntimes.contains(nativeRuntimeLiteRtLm) && liteRtLmBundleSpec == null) { @@ -203,8 +230,7 @@ void main(List args) async { .where((runtime) => runtime != nativeRuntimeLiteRtLm) .toList(growable: false); log.warning( - 'LiteRT-LM runtime is not available for ${spec.bundle}; using ' - 'available runtime families: ${selectedRuntimes.join(', ')}.', + 'LiteRT-LM runtime is not available for ${spec.bundle}; skipping it.', ); } final stableDiffusionBundleSpec = diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart index 8cd51da68..04accc4c5 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -197,13 +197,22 @@ LlamaUnsupportedException stableDiffusionLoadFailure({ final detail = '${error.message ?? error}'; final isApple = platform.startsWith('ios-') || platform.startsWith('macos-'); if (detail.contains('No asset with id')) { - final companionAdvice = isApple - ? ', or add the $_appleCompanion package to a Flutter iOS/macOS app,' - : ''; + const key = 'hooks.user_defines.llamadart.llamadart_native_runtimes'; + const hookAdvice = + 'set $key to all, or add stable_diffusion to its list, and rebuild. ' + 'A list replaces the default llama_cpp and litert_lm.'; + if (isApple) { + return LlamaUnsupportedException( + 'stable_diffusion runtime is not bundled for $platform. In a Flutter ' + 'iOS/macOS app, add the $_appleCompanion package and rebuild: ' + 'without it the build hook leaves out a stable_diffusion that all ' + 'only implies. Naming stable_diffusion in $key bundles it through ' + 'the hook instead, in a framework App Store Connect rejects on iOS. ' + 'In any other build, $hookAdvice', + ); + } return LlamaUnsupportedException( - 'stable_diffusion runtime is not bundled for $platform; add ' - 'stable_diffusion to hooks.user_defines.llamadart.' - 'llamadart_native_runtimes$companionAdvice and rebuild.', + 'stable_diffusion runtime is not bundled for $platform; $hookAdvice', ); } if (_vulkanLoaderNames.any(detail.toLowerCase().contains)) { diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index 310ce7323..0af163be3 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -145,11 +145,12 @@ class ImageGenerationTask { /// Experimental on-device text-to-image generation through the opt-in /// stable_diffusion runtime (stable-diffusion.cpp). /// -/// The app must bundle the runtime by adding `stable_diffusion` to -/// `hooks.user_defines.llamadart.llamadart_native_runtimes`. It runs on -/// Android arm64 (CPU), iOS and macOS (Metal), and Linux and Windows (CPU or -/// Vulkan). On the web and other platforms [load] throws -/// [LlamaUnsupportedException]. +/// The app must bundle the runtime by setting +/// `hooks.user_defines.llamadart.llamadart_native_runtimes` to `all` or to a +/// list naming `stable_diffusion`; a list replaces the default `llama_cpp` +/// and `litert_lm`. It runs on Android arm64 (CPU), iOS and macOS (Metal), and +/// Linux and Windows (CPU or Vulkan). On the web and other platforms [load] +/// throws [LlamaUnsupportedException]. /// /// The model runs in a worker isolate, so the calling isolate stays /// responsive. stable-diffusion.cpp reports progress through one diff --git a/lib/src/hook/native_bundle_config.dart b/lib/src/hook/native_bundle_config.dart index 7405a1a46..18e5c9428 100644 --- a/lib/src/hook/native_bundle_config.dart +++ b/lib/src/hook/native_bundle_config.dart @@ -12,7 +12,7 @@ /// [selectNativeRuntimesForBundle] picks the runtime families and /// [nativeRuntimeExplicitlySelectedForBundle] and /// [nativeRuntimeNamedForExactBundle] say how hard to fail when one is -/// unpublished; [stableDiffusionBundleForNativeBundle] names the opt-in +/// unpublished, and whether `all` only implied it; [stableDiffusionBundleForNativeBundle] names the opt-in /// stable_diffusion archive; [describeNativeLibrary] classifies a discovered /// file; [selectLibrariesForBundling] picks which ship; /// [codeAssetNameForLibrary] names each as a code asset. A Flutter Apple build @@ -20,7 +20,8 @@ /// llama_cpp and litert_lm families from it, not /// [selectNativeRuntimesForBundle]. stable_diffusion is decided on its own: the /// stable_diffusion companion selects it, and otherwise it still comes from -/// [selectNativeRuntimesForBundle]. +/// [selectNativeRuntimesForBundle], unless `all` only implied it: such a build +/// skips it. /// /// User-facing docs: `website/docs/platforms/native-build-hooks.md` and /// `website/docs/guides/backend-selection.md`. @@ -63,28 +64,28 @@ const String nativeRuntimeLlamaCpp = 'llama_cpp'; /// The LiteRT-LM runtime family; not published for every bundle. const String nativeRuntimeLiteRtLm = 'litert_lm'; -/// The experimental stable-diffusion.cpp runtime family. Opt-in only: it is -/// bundled when named, never by default and never through `all` or `both`, -/// because it adds tens of megabytes per platform. Not published for every -/// bundle; see [stableDiffusionBundleForNativeBundle]. +/// The experimental stable-diffusion.cpp runtime family. Opt-in: it is +/// bundled when named or through `all`, never by default and never through +/// `both`, because it adds tens of megabytes per platform. Not published for +/// every bundle; see [stableDiffusionBundleForNativeBundle]. const String nativeRuntimeStableDiffusion = 'stable_diffusion'; -/// The runtime families `all` and `both` expand to, in that order. Opt-in -/// families such as [nativeRuntimeStableDiffusion] are not included. +/// The runtime families `all` expands to, in that order. const List allNativeRuntimes = [ nativeRuntimeLlamaCpp, nativeRuntimeLiteRtLm, + nativeRuntimeStableDiffusion, ]; /// Every runtime family a config may name. -const List supportedNativeRuntimes = [ - ...allNativeRuntimes, - nativeRuntimeStableDiffusion, -]; +const List supportedNativeRuntimes = allNativeRuntimes; -/// Fallback families for config that names no runtimes. An explicit `none` -/// selects nothing instead. -const List defaultNativeRuntimes = allNativeRuntimes; +/// The families `both` expands to, and the fallback for config that names no +/// runtimes. An explicit `none` selects nothing instead. +const List defaultNativeRuntimes = [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, +]; const Set _coreLibraries = { 'llamadart', @@ -536,7 +537,7 @@ List? parseRequestedBackends({ /// /// Precedence, first match wins: the `platforms` entry canonicalising to /// [bundle]; the entry for that bundle's OS; the top-level `runtimes` key; the -/// top-level `default` key; else [defaultNativeRuntimes], every family. A +/// top-level `default` key; else [defaultNativeRuntimes]. A /// matched platform entry with a `null` value ends the platform search, so the /// OS entry is skipped. `runtimes` is consulted by key presence, so an /// explicit `runtimes: null` suppresses `default` instead of falling through @@ -545,14 +546,14 @@ List? parseRequestedBackends({ /// Tokens are trimmed, lowercased and `_`-to-`-` normalised before alias /// lookup: `gguf` and `llama.cpp` reach `llama_cpp`; `litert`, `litertlm` and /// `.litertlm` reach `litert_lm`; `stable-diffusion` reaches -/// `stable_diffusion`. `all` and `both` expand to [allNativeRuntimes], which -/// leaves out the opt-in `stable_diffusion`; the string tokens `none`, `off` and `false` clear what -/// has accumulated. A bare YAML boolean `false` clears it too, including in a -/// list. +/// `stable_diffusion`. `all` expands to [allNativeRuntimes] and `both` to +/// [defaultNativeRuntimes], which leaves out the opt-in `stable_diffusion`; +/// the string tokens `none`, `off` and `false` clear what has accumulated. A +/// bare YAML boolean `false` clears it too, including in a list. /// Unrecognised non-empty tokens are dropped and reported once through /// [warn]; empty tokens are ignored silently. A string or list that selects /// nothing because it was empty or all-unrecognised yields -/// [allNativeRuntimes]. Once a `none` token clears the selection only a later +/// [defaultNativeRuntimes]. Once a `none` token clears the selection only a later /// recognised token refills it, so `['none', 'llama_cpp']` selects `llama_cpp` /// while `['none', 'tflite']` stays empty, which `hook/build.dart` throws on. /// @@ -587,13 +588,15 @@ List selectNativeRuntimesForBundle({ } /// Whether [runtime] was named for [bundle], not implied by a default or by -/// `all`/`both` expansion. `false` for `all`, `none`, unrecognised spellings, -/// and for a name a later `none` cleared (`['litert_lm', 'none']`). Order -/// decides it, so `['none', 'litert_lm']` is explicit. +/// `all`/`both` expansion. `false` for `all`, `both`, `none`, unrecognised +/// spellings, and for a name a later `none` cleared (`['litert_lm', 'none']`). +/// Order decides it, so `['none', 'litert_lm']` is explicit. /// /// `hook/build.dart` uses this when LiteRT-LM is selected but the bundle /// publishes no LiteRT-LM archive: an explicit request throws, an implied one -/// is dropped with a warning. +/// is dropped with a warning. It also uses it on Flutter iOS and macOS builds +/// without the stable_diffusion companion, where a stable_diffusion that +/// `all` only implied is skipped. bool nativeRuntimeExplicitlySelectedForBundle({ required String bundle, required Object? rawUserConfig, @@ -1243,8 +1246,11 @@ _parseRuntimeList(Object? value) { } return; } - if (normalized == 'all') { - for (final runtime in allNativeRuntimes) { + if (normalized == 'all' || normalized == 'both') { + final expansion = normalized == 'all' + ? allNativeRuntimes + : defaultNativeRuntimes; + for (final runtime in expansion) { if (!result.contains(runtime)) { result.add(runtime); } @@ -1273,7 +1279,9 @@ _parseRuntimeList(Object? value) { addToken(token); } return ( - runtimes: result.isEmpty && !explicitNone ? allNativeRuntimes : result, + runtimes: result.isEmpty && !explicitNone + ? defaultNativeRuntimes + : result, invalid: invalid, explicit: explicit, ); @@ -1290,7 +1298,9 @@ _parseRuntimeList(Object? value) { } } return ( - runtimes: result.isEmpty && !explicitNone ? allNativeRuntimes : result, + runtimes: result.isEmpty && !explicitNone + ? defaultNativeRuntimes + : result, invalid: invalid, explicit: explicit, ); @@ -1324,7 +1334,7 @@ String? _normalizeRuntime(String value) { } normalized = normalized.replaceAll('_', '-'); if (normalized == 'all' || normalized == 'both') { - return 'all'; + return normalized; } if (normalized == 'none' || normalized == 'off' || normalized == 'false') { return 'none'; diff --git a/packages/llamadart_stable_diffusion_flutter/README.md b/packages/llamadart_stable_diffusion_flutter/README.md index b8a724347..d1e467b82 100644 --- a/packages/llamadart_stable_diffusion_flutter/README.md +++ b/packages/llamadart_stable_diffusion_flutter/README.md @@ -24,6 +24,11 @@ dependencies: Adding the package selects the `stable_diffusion` runtime for Flutter iOS and macOS builds; `llamadart_native_runtimes` still decides the other platforms. +A list there replaces the default `llama_cpp` and `litert_lm`: +`[llama_cpp, stable_diffusion]` ships GGUF chat and images, +`[stable_diffusion]` images only, and `[all, stable_diffusion]` every runtime. +On cores newer than `0.11.1`, `all` alone includes `stable_diffusion`; on +Flutter iOS and macOS it does so only with this package. This package has no runtime Dart API of its own. Import `package:llamadart` normally from the core package and use `ImageGenerationEngine` there. diff --git a/skills/llamadart-flutter-app/SKILL.md b/skills/llamadart-flutter-app/SKILL.md index 9dcf69363..77720ea9f 100644 --- a/skills/llamadart-flutter-app/SKILL.md +++ b/skills/llamadart-flutter-app/SKILL.md @@ -142,10 +142,13 @@ or shipping runtimes the app does not use. user-defines do not change SwiftPM binaries either. The stable_diffusion companion is independent: it selects image generation on iOS and macOS and leaves llama.cpp and LiteRT-LM where they were. -- Image generation (`ImageGenerationEngine`) needs `stable_diffusion` added - to `llamadart_native_runtimes`; it is never bundled by default. On iOS and - macOS add `llamadart_stable_diffusion_flutter` instead, since App Store - Connect rejects the iOS framework the hook bundles. Details are in the +- Image generation (`ImageGenerationEngine`) needs the `stable_diffusion` + runtime, which is never bundled by default. Set `llamadart_native_runtimes` + to `all`, or to a list naming `stable_diffusion`; a list replaces the + default `llama_cpp` and `litert_lm`. On iOS and macOS add + `llamadart_stable_diffusion_flutter`: without it `all` leaves the image + runtime out there, and App Store Connect rejects the iOS framework the hook + bundles when `stable_diffusion` is named. Details are in the llamadart-image-generation skill. - Native runtimes are downloaded by the build hook on the first `flutter run` or `flutter build` for each target; no C++ toolchain is diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index 375759d99..027bd4285 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -20,26 +20,31 @@ description: >- stable-diffusion.cpp through the opt-in `stable_diffusion` native runtime. Text-to-image only: no image-to-image, inpainting, LoRA or ControlNet. - The app must bundle the runtime (about 40 to 70 MB per target); it is never - included by default or by `all`. In the app's `pubspec.yaml`: + included by default. In the app's `pubspec.yaml`: ```yaml hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_native_runtimes: all ``` - Keep `litert_lm` in the list if the app also loads `.litertlm` models. Run + Unset, the key bundles `llama_cpp` and `litert_lm`. A list replaces those + defaults, so it names everything the app loads: `all` is every runtime + published for the target, `[llama_cpp, stable_diffusion]` is GGUF chat and + images without LiteRT-LM, and `[stable_diffusion]` is images only. Run `flutter clean` once after changing it. Linux and Windows bundle the Vulkan build when `llamadart_native_backends` selects Vulkan (the default); `llamadart_stable_diffusion_backends: [cpu]` picks the CPU build. - Flutter iOS and macOS apps should add the `llamadart_stable_diffusion_flutter` companion package. It links the runtime's XCFramework through Swift Package Manager and selects the runtime - on iOS and macOS without the entry above. Without it the hook bundles the - runtime, and App Store Connect rejects that iOS framework's - `MinimumOSVersion`; only Xcode and `xcodebuild` show the build warning about - it. Pair companion `0.0.2` with core `0.11.1` and `0.11.0`; adding it opts + on iOS and macOS without the entry above. Without it, `all` leaves the + image runtime out of a Flutter iOS/macOS app and `checkRuntime()` reports + it as not bundled; a list naming `stable_diffusion` bundles it through the + hook, and App Store Connect rejects that iOS framework's + `MinimumOSVersion`. `flutter build ios` output shows neither build warning; + Xcode and `xcodebuild` show both. Pair companion `0.0.2` with core `0.11.1` and `0.11.0`; adding it opts the app into the runtime (about 37 MB per Apple target). - Platforms: Android arm64 (CPU only; Armv8.2 dot-product and fp16), iOS 16.4+ and macOS 13.3+ (Metal), Linux arm64/x64 and Windows x64 (CPU or Vulkan; x64 diff --git a/test/integration/stable_diffusion_runtime_hook_test.dart b/test/integration/stable_diffusion_runtime_hook_test.dart index e56010801..f69e29ac3 100644 --- a/test/integration/stable_diffusion_runtime_hook_test.dart +++ b/test/integration/stable_diffusion_runtime_hook_test.dart @@ -15,10 +15,14 @@ import 'package:test/test.dart'; void main() { test('opting in bundles a runtime that loads and lists devices', () async { final status = await _probeConsumer( - runtimesDefine: const ['llama_cpp', 'stable_diffusion'], + runtimes: '[llama_cpp, stable_diffusion]', ); expect(status['available'], isTrue, reason: '$status'); + expect( + status['hookLog'], + contains('Selected native runtimes: llama_cpp, stable_diffusion.'), + ); expect( status['version'], isA().having((v) => v, 'version', isNotEmpty), @@ -32,30 +36,52 @@ void main() { expect(devices, contains(startsWith('MTL'))); }); + test('all bundles it beside the default runtimes', () async { + for (final runtimes in const ['all', '{runtimes: [all]}']) { + final status = await _probeConsumer(runtimes: runtimes); + + expect(status['available'], isTrue, reason: '$runtimes $status'); + expect( + status['hookLog'], + contains( + 'Selected native runtimes: llama_cpp, litert_lm, stable_diffusion.', + ), + reason: runtimes, + ); + } + }); + test('without opting in the runtime is reported as not bundled', () async { - final status = await _probeConsumer(runtimesDefine: null); + for (final runtimes in const [null, 'both']) { + final status = await _probeConsumer(runtimes: runtimes); - expect(status['available'], isFalse); - expect( - status['reason'], - contains('stable_diffusion runtime is not bundled'), - ); + expect(status['available'], isFalse, reason: '$runtimes'); + expect( + status['reason'], + contains('stable_diffusion runtime is not bundled'), + reason: '$runtimes', + ); + expect( + status['hookLog'], + contains('Selected native runtimes: llama_cpp, litert_lm.'), + reason: '$runtimes', + ); + } }); } -Future> _probeConsumer({ - required List? runtimesDefine, -}) async { +/// The probe's status for a consumer whose `llamadart_native_runtimes` is the +/// YAML value [runtimes], plus the llamadart hook's output under `hookLog`. +Future> _probeConsumer({required String? runtimes}) async { final consumer = await Directory.systemTemp.createTemp('llamadart-sd-hook-'); addTearDown(() => consumer.delete(recursive: true)); - final hooks = runtimesDefine == null + final hooks = runtimes == null ? '' : ''' hooks: user_defines: llamadart: - llamadart_native_runtimes: - runtimes: [${runtimesDefine.join(', ')}] + llamadart_native_runtimes: $runtimes '''; await File(path.join(consumer.path, 'pubspec.yaml')).writeAsString(''' name: llamadart_sd_hook_consumer @@ -95,7 +121,17 @@ void main() { final line = LineSplitter.split( output, ).singleWhere((line) => line.startsWith('SD_PROBE ')); - return jsonDecode(line.substring('SD_PROBE '.length)) as Map; + final hookLog = + Directory( + path.join(consumer.path, '.dart_tool', 'hooks_runner', 'llamadart'), + ) + .listSync(recursive: true) + .whereType() + .where((file) => path.basename(file.path) == 'stdout.txt'); + return { + ...jsonDecode(line.substring('SD_PROBE '.length)) as Map, + 'hookLog': hookLog.map((file) => file.readAsStringSync()).join(), + }; } Future _expectSuccess( diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart index 312fa41c4..c57d1a78a 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart @@ -226,10 +226,10 @@ void main() { isA().having( (error) => error.message, 'message', - allOf( - contains('stable_diffusion runtime is not bundled for linux-x64'), - contains('llamadart_native_runtimes'), - ), + 'stable_diffusion runtime is not bundled for linux-x64; set ' + 'hooks.user_defines.llamadart.llamadart_native_runtimes to ' + 'all, or add stable_diffusion to its list, and rebuild. A list ' + 'replaces the default llama_cpp and litert_lm.', ), ); }); @@ -306,11 +306,17 @@ void main() { ).message; expect( message, - allOf( - contains('not bundled for $platform'), - contains('llamadart_native_runtimes'), - contains('llamadart_stable_diffusion_flutter'), - ), + 'stable_diffusion runtime is not bundled for $platform. In a ' + 'Flutter iOS/macOS app, add the ' + 'llamadart_stable_diffusion_flutter package and rebuild: without ' + 'it the build hook leaves out a stable_diffusion that all only ' + 'implies. Naming stable_diffusion in ' + 'hooks.user_defines.llamadart.llamadart_native_runtimes bundles it ' + 'through the hook instead, in a framework App Store Connect ' + 'rejects on iOS. In any other build, set ' + 'hooks.user_defines.llamadart.llamadart_native_runtimes to all, or ' + 'add stable_diffusion to its list, and rebuild. A list replaces ' + 'the default llama_cpp and litert_lm.', reason: platform, ); } diff --git a/test/unit/hook/build_hook_integration_test.dart b/test/unit/hook/build_hook_integration_test.dart index 577a35a8d..22b5a9b38 100644 --- a/test/unit/hook/build_hook_integration_test.dart +++ b/test/unit/hook/build_hook_integration_test.dart @@ -147,7 +147,7 @@ void main() { final userDefines = PackageUserDefines( workspacePubspec: PackageUserDefinesSource( defines: { - 'llamadart_native_runtimes': ['all'], + 'llamadart_native_runtimes': ['both'], 'llamadart_native_backends': { 'platforms': { 'windows-x64': ['vulkan'], @@ -733,6 +733,8 @@ Future _writeBundleLibraries( const List _windowsLiteRtLibraries = [ 'LiteRtLm.dll', + 'dxcompiler.dll', + 'dxil.dll', 'libGemmaModelConstraintProvider.dll', 'libLiteRt.dll', 'libwebgpu_dawn.dll', diff --git a/test/unit/hook/build_hook_litert_lm_integration_test.dart b/test/unit/hook/build_hook_litert_lm_integration_test.dart index 9a6ec6e65..8482350a8 100644 --- a/test/unit/hook/build_hook_litert_lm_integration_test.dart +++ b/test/unit/hook/build_hook_litert_lm_integration_test.dart @@ -185,7 +185,7 @@ void main() { mainMethod: build_hook.main, targetOS: OS.linux, targetArchitecture: Architecture.arm64, - userDefines: _allRuntimeUserDefines(), + userDefines: _bothRuntimeUserDefines(), check: (input, output) { final codeAssets = output.assets.encodedAssets .where((asset) => asset.isCodeAsset) @@ -220,7 +220,7 @@ void main() { mainMethod: build_hook.main, targetOS: OS.macOS, targetArchitecture: architecture, - userDefines: _allRuntimeUserDefines(), + userDefines: _bothRuntimeUserDefines(), check: (input, output) { final codeAssets = output.assets.encodedAssets .where((asset) => asset.isCodeAsset) @@ -290,7 +290,7 @@ void main() { targetOS: OS.iOS, targetArchitecture: Architecture.arm64, targetIOSSdk: IOSSdk.iPhoneOS, - userDefines: _allRuntimeUserDefines(), + userDefines: _bothRuntimeUserDefines(), check: (input, output) { final codeAssets = output.assets.encodedAssets .where((asset) => asset.isCodeAsset) @@ -740,9 +740,10 @@ dependency_overrides: {llamadart_llama_cpp_flutter: {path: resolved companion}} }, ); - test('build hook drops unavailable LiteRT-LM from all selections', () async { + test('build hook drops unavailable LiteRT-LM from both and empty ' + 'selections', () async { for (final userDefines in [ - _allRuntimeUserDefines(), + _bothRuntimeUserDefines(), _emptyRuntimeUserDefines(), ]) { await testCodeBuildHook( @@ -903,10 +904,10 @@ PackageUserDefines _liteRtLmOnlyUserDefines() => PackageUserDefines( ), ); -PackageUserDefines _allRuntimeUserDefines() => PackageUserDefines( +PackageUserDefines _bothRuntimeUserDefines() => PackageUserDefines( workspacePubspec: PackageUserDefinesSource( defines: { - 'llamadart_native_runtimes': ['all'], + 'llamadart_native_runtimes': ['both'], }, basePath: Directory.current.uri, ), diff --git a/test/unit/hook/build_hook_stable_diffusion_integration_test.dart b/test/unit/hook/build_hook_stable_diffusion_integration_test.dart index 09ce70d0a..719a7a202 100644 --- a/test/unit/hook/build_hook_stable_diffusion_integration_test.dart +++ b/test/unit/hook/build_hook_stable_diffusion_integration_test.dart @@ -1,6 +1,7 @@ @TestOn('vm') library; +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -15,6 +16,7 @@ import '../../../hook/build.dart' as build_hook; const _stableDiffusionAssetId = 'package:llamadart/stable_diffusion'; const _primaryAssetId = 'package:llamadart/llamadart'; +const _liteRtLmAssetIdPrefix = 'package:llamadart/litert_lm_'; void main() { final nativeBundlesRoot = '.dart_tool/llamadart/native_bundles/$llamaCppTag'; @@ -43,6 +45,14 @@ void main() { 'libggml-cpu.so', ], 'macos-arm64': const ['libllamadart.dylib'], + 'ios-x86_64-sim': const ['libllamadart.dylib'], + 'windows-arm64': const [ + 'llamadart-windows-arm64.dll', + 'llama-windows-arm64.dll', + 'ggml-windows-arm64.dll', + 'ggml-base-windows-arm64.dll', + 'ggml-cpu-windows-arm64.dll', + ], }; final stableDiffusionBundles = { for (final spec in stableDiffusionBundleSpecs) @@ -51,17 +61,23 @@ void main() { 'linux-x64-vulkan', 'macos-arm64', 'ios-arm64', + 'ios-x64-sim', }.contains(spec.bundle)) spec.bundle: spec.requiredLibraries.single, }; - final liteRtLmLinuxBundle = Directory( - '.dart_tool/llamadart/litert_lm/$liteRtLmVersion/linux/x64', - ); + final liteRtLmBundles = { + 'linux-x64': Directory( + '.dart_tool/llamadart/litert_lm/$liteRtLmVersion/linux/x64', + ), + 'android-x64': Directory( + '.dart_tool/llamadart/litert_lm/$liteRtLmVersion/android/x64', + ), + }; final backups = [ for (final bundle in nativeBundles.keys) nativeBundle(bundle), for (final bundle in stableDiffusionBundles.keys) stableDiffusionBundle(bundle), - liteRtLmLinuxBundle, + ...liteRtLmBundles.values, ]; setUpAll(() async { @@ -83,13 +99,16 @@ void main() { library: 'fake-sd-$bundle', }); } - await _writeLibraries(liteRtLmLinuxBundle, { - for (final library - in liteRtLmBundleSpecs - .singleWhere((spec) => spec.bundle == 'linux-x64') - .requiredLibraries) - library: 'fake-$library', - }); + for (final MapEntry(key: bundle, value: directory) + in liteRtLmBundles.entries) { + await _writeLibraries(directory, { + for (final library + in liteRtLmBundleSpecs + .singleWhere((spec) => spec.bundle == bundle) + .requiredLibraries) + library: 'fake-$library', + }); + } }); tearDownAll(() async { @@ -101,26 +120,45 @@ void main() { } }); - test('default and all selections never bundle stable_diffusion', () async { + test('unset, empty, unrecognised and both selections never bundle ' + 'stable_diffusion', () async { final vulkanCache = stableDiffusionBundle('linux-x64-vulkan'); await vulkanCache.delete(recursive: true); for (final defines in >[ {}, + {'llamadart_native_runtimes': []}, { - 'llamadart_native_runtimes': ['all'], + 'llamadart_native_runtimes': ['onnx'], }, {'llamadart_native_runtimes': 'both'}, - ]) { - await testCodeBuildHook( - mainMethod: build_hook.main, - targetOS: OS.linux, - targetArchitecture: Architecture.x64, - userDefines: _userDefines(defines), - check: (_, output) { - final ids = _codeAssetIds(output); - expect(ids, contains(_primaryAssetId), reason: '$defines'); - expect(ids, isNot(contains(_stableDiffusionAssetId))); + { + 'llamadart_native_runtimes': { + 'platforms': {'android': 'all'}, }, + }, + ]) { + final log = await _captureHookLog( + () => testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.linux, + targetArchitecture: Architecture.x64, + userDefines: _userDefines(defines), + check: (_, output) { + final ids = _codeAssetIds(output); + expect(ids, contains(_primaryAssetId), reason: '$defines'); + expect( + ids.any((id) => id.startsWith(_liteRtLmAssetIdPrefix)), + isTrue, + reason: '$defines', + ); + expect(ids, isNot(contains(_stableDiffusionAssetId))); + }, + ), + ); + expect( + log, + contains(endsWith('Selected native runtimes: llama_cpp, litert_lm.')), + reason: '$defines', ); expect( vulkanCache.existsSync(), @@ -130,6 +168,225 @@ void main() { } }); + test('all bundles every runtime a target publishes and skips the rest with ' + 'a warning', () async { + const liteRtLmSkipped = 'LiteRT-LM runtime is not available for'; + const stableDiffusionSkipped = 'stable_diffusion runtime is not available'; + const targets = [ + ( + os: OS.linux, + architecture: Architecture.x64, + simulator: false, + bundle: 'linux-x64', + liteRtLm: true, + stableDiffusion: true, + ), + ( + os: OS.android, + architecture: Architecture.x64, + simulator: false, + bundle: 'android-x64', + liteRtLm: true, + stableDiffusion: false, + ), + ( + os: OS.iOS, + architecture: Architecture.x64, + simulator: true, + bundle: 'ios-x86_64-sim', + liteRtLm: false, + stableDiffusion: true, + ), + ( + os: OS.windows, + architecture: Architecture.arm64, + simulator: false, + bundle: 'windows-arm64', + liteRtLm: false, + stableDiffusion: false, + ), + ]; + for (final (runtimes, selectsImages) in const <(Object?, bool)>[ + ('all', true), + (['all'], true), + (['all', 'stable_diffusion'], true), + ({'runtimes': 'all'}, true), + ('both', false), + (null, false), + ]) { + for (final target in targets) { + final reason = '${target.bundle} $runtimes'; + final stableDiffusion = selectsImages && target.stableDiffusion; + final log = await _captureHookLog( + () => testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: target.os, + targetArchitecture: target.architecture, + targetAndroidNdkApi: target.os == OS.android ? 30 : null, + targetIOSSdk: target.simulator ? IOSSdk.iPhoneSimulator : null, + userDefines: _userDefines({'llamadart_native_runtimes': ?runtimes}), + check: (_, output) { + final ids = _codeAssetIds(output); + expect(ids, contains(_primaryAssetId), reason: reason); + expect( + ids.any((id) => id.startsWith(_liteRtLmAssetIdPrefix)), + target.liteRtLm, + reason: reason, + ); + expect( + ids.contains(_stableDiffusionAssetId), + stableDiffusion, + reason: reason, + ); + }, + ), + ); + final warnings = log.where((line) => line.startsWith('WARNING: ')); + expect( + warnings.any( + (line) => line.contains('$liteRtLmSkipped ${target.bundle}'), + ), + !target.liteRtLm, + reason: reason, + ); + expect( + warnings.any( + (line) => + line.contains('$stableDiffusionSkipped for ${target.bundle}'), + ), + selectsImages && !target.stableDiffusion, + reason: reason, + ); + expect( + log, + contains( + endsWith( + 'Selected native runtimes: ${['llama_cpp', if (target.liteRtLm) 'litert_lm', if (stableDiffusion) 'stable_diffusion'].join(', ')}.', + ), + ), + reason: reason, + ); + } + } + }); + + test('all under an exact bundle key still skips an unpublished ' + 'stable_diffusion', () async { + await testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.android, + targetArchitecture: Architecture.x64, + targetAndroidNdkApi: 30, + userDefines: _userDefines({ + 'llamadart_native_runtimes': { + 'platforms': {'android-x64': 'all'}, + }, + }), + check: (_, output) { + final ids = _codeAssetIds(output); + expect(ids, contains(_primaryAssetId)); + expect(ids, isNot(contains(_stableDiffusionAssetId))); + }, + ); + }); + + for (final (os, sdk, bundle) in const [ + (OS.iOS, IOSSdk.iPhoneOS, 'ios-arm64'), + (OS.macOS, null, 'macos-arm64'), + ]) { + for (final companion in const [false, true]) { + for (final (runtimes, explicit) in const <(List, bool)>[ + (['all'], false), + (['all', 'stable_diffusion'], true), + ]) { + test('Flutter $bundle with $runtimes ' + '${companion ? 'and' : 'without'} the stable_diffusion ' + 'companion', () async { + final defines = await _flutterAppleApp( + companions: [ + _llamaCppCompanionName, + if (companion) _stableDiffusionCompanionName, + ], + defines: {'llamadart_native_runtimes': runtimes}, + ); + late final List log; + final stderrLines = await _captureStderr(() async { + log = await _captureHookLog( + () => testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: os, + targetArchitecture: Architecture.arm64, + targetIOSSdk: sdk, + userDefines: defines, + check: (_, output) { + final ids = _codeAssetIds(output); + expect(ids, contains(_primaryAssetId)); + expect( + ids.contains(_stableDiffusionAssetId), + companion || explicit, + ); + if (companion || explicit) { + expect( + _stableDiffusionAsset(output).linkMode, + companion + ? isA() + : isA(), + ); + } + }, + ), + ); + }); + final skipped = log.where( + (line) => + line.startsWith('WARNING: ') && + line.contains('stable_diffusion is only implied by `all`'), + ); + final relayed = stderrLines.where( + (line) => line.contains('stable_diffusion is only implied'), + ); + if (companion || explicit) { + expect(skipped, isEmpty); + expect(relayed, isEmpty); + } else { + expect(skipped.single, endsWith('$_impliedSkipWarning ($bundle)')); + expect(relayed.single, 'warning: llamadart: $_impliedSkipWarning'); + } + expect( + stderrLines.any((line) => line.contains('MinimumOSVersion')), + os == OS.iOS && explicit && !companion, + ); + }); + } + } + } + + test('a Flutter Apple app without any companion skips a stable_diffusion ' + 'that all only implies', () async { + final defines = await _flutterAppleApp( + companions: const [], + defines: {'llamadart_native_runtimes': 'all'}, + ); + late final List log; + final stderrLines = await _captureStderr(() async { + log = await _captureHookLog( + () => testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.iOS, + targetArchitecture: Architecture.x64, + targetIOSSdk: IOSSdk.iPhoneSimulator, + userDefines: defines, + check: (_, output) { + expect(_codeAssetIds(output), {_primaryAssetId}); + }, + ), + ); + }); + expect(log, contains(endsWith('$_impliedSkipWarning (ios-x86_64-sim)'))); + expect(stderrLines, ['warning: llamadart: $_impliedSkipWarning']); + expect(log, contains(endsWith('Selected native runtimes: llama_cpp.'))); + }); + test('Linux bundles the Vulkan archive with default backends', () async { await testCodeBuildHook( mainMethod: build_hook.main, @@ -508,6 +765,13 @@ dependencies: } } +const _impliedSkipWarning = + 'stable_diffusion is only implied by `all` in llamadart_native_runtimes, ' + 'so this Flutter iOS/macOS build leaves the image runtime out: ' + 'llamadart_stable_diffusion_flutter is not a dependency. Add that package ' + 'to link the runtime through Swift Package Manager, or name ' + 'stable_diffusion to bundle it through the hook.'; + const _llamaCppCompanionName = 'llamadart_llama_cpp_flutter'; const _stableDiffusionCompanionName = 'llamadart_stable_diffusion_flutter'; @@ -578,6 +842,18 @@ ${companions.map((name) => ' $name: any').join('\n')} ); } +/// The records the hook logs while [body] runs, as `LEVEL: time: message`. +Future> _captureHookLog(Future Function() body) async { + final lines = {}; + await runZoned( + body, + zoneSpecification: ZoneSpecification( + print: (_, _, _, line) => lines.add(line), + ), + ); + return lines.toList(); +} + /// Lines the hook writes to stderr while [body] runs; Flutter relays them /// into the Xcode build, where `warning:` lines become build warnings. Future> _captureStderr(Future Function() body) async { diff --git a/test/unit/hook/native_bundle_config_test.dart b/test/unit/hook/native_bundle_config_test.dart index 278ea0c4d..7d34070df 100644 --- a/test/unit/hook/native_bundle_config_test.dart +++ b/test/unit/hook/native_bundle_config_test.dart @@ -166,7 +166,7 @@ void main() { }); group('selectNativeRuntimesForBundle', () { - test('defaults to all runtime families', () { + test('defaults to the two default runtime families', () { for (final bundle in [ 'android-arm64', 'ios-arm64', @@ -197,17 +197,26 @@ void main() { expect(selected, [nativeRuntimeLlamaCpp, nativeRuntimeLiteRtLm]); }); - test('parses all as both runtime families on non-Android targets', () { - final selected = selectNativeRuntimesForBundle( - bundle: 'linux-x64', - rawUserConfig: 'all', - warn: (_) {}, - ); + test('parses both as the two default runtime families', () { + for (final rawUserConfig in const [ + 'both', + ' Both ', + ['both'], + ]) { + final selected = selectNativeRuntimesForBundle( + bundle: 'linux-x64', + rawUserConfig: rawUserConfig, + warn: (_) {}, + ); - expect(selected, [nativeRuntimeLlamaCpp, nativeRuntimeLiteRtLm]); + expect(selected, [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ], reason: '$rawUserConfig'); + } }); - test('parses empty runtime list as all runtime families', () { + test('parses empty runtime list as the two default families', () { for (final rawUserConfig in const [ [], '', @@ -460,24 +469,29 @@ void main() { for (final rawUserConfig in const [null, '', []]) { final warnings = []; - expect( - select(rawUserConfig, warnings), - allNativeRuntimes, - reason: rawUserConfig.toString(), - ); + expect(select(rawUserConfig, warnings), [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ], reason: rawUserConfig.toString()); expect(warnings, isEmpty, reason: rawUserConfig.toString()); } final warnings = []; - expect(select(true, warnings), allNativeRuntimes); + expect(select(true, warnings), [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ]); expect(warnings, hasLength(1)); expect(warnings.single, contains('true')); }); - test('all-unrecognised list warns and stays all runtime families', () { + test('all-unrecognised list warns and stays the two default families', () { final warnings = []; - expect(select(const ['tflite', 'onnx'], warnings), allNativeRuntimes); + expect(select(const ['tflite', 'onnx'], warnings), [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ]); expect(warnings, hasLength(1)); expect(warnings.single, contains('tflite, onnx')); @@ -901,29 +915,64 @@ void main() { warn: warnings.add, ); - test('is never selected by default, all or both', () { + test('is never selected by default, an empty or unrecognised value, or ' + 'both', () { for (final rawUserConfig in const [ null, '', [], - 'all', 'both', - ['all'], + ['both'], ['tflite'], + true, + {'runtimes': []}, + {'runtimes': 'both'}, + { + 'platforms': { + 'android': ['all'], + }, + }, + ]) { + final warnings = []; + expect(select(rawUserConfig, warnings), [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ], reason: rawUserConfig.toString()); + } + expect(defaultNativeRuntimes, [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ]); + }); + + test('is selected by all, after the two default families', () { + for (final rawUserConfig in const [ + 'all', + ' ALL ', + ['all'], + ['both', 'all'], + ['all', 'stable_diffusion'], + ['llama_cpp', 'all'], {'runtimes': 'all'}, + { + 'runtimes': ['llama_cpp'], + 'platforms': {'linux': 'all'}, + }, ]) { final warnings = []; - expect( - select(rawUserConfig, warnings), - isNot(contains(nativeRuntimeStableDiffusion)), - reason: rawUserConfig.toString(), - ); + expect(select(rawUserConfig, warnings), [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + nativeRuntimeStableDiffusion, + ], reason: rawUserConfig.toString()); + expect(warnings, isEmpty, reason: rawUserConfig.toString()); } - expect(allNativeRuntimes, isNot(contains(nativeRuntimeStableDiffusion))); - expect( - defaultNativeRuntimes, - isNot(contains(nativeRuntimeStableDiffusion)), - ); + expect(select(const ['stable_diffusion', 'all'], []), [ + nativeRuntimeStableDiffusion, + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + ]); + expect(select(const ['all', 'none'], []), isEmpty); }); test('is selected when named, including the stable-diffusion alias', () { @@ -945,14 +994,92 @@ void main() { nativeRuntimeLlamaCpp, nativeRuntimeStableDiffusion, ]); - expect(select(const ['all', 'stable_diffusion'], warnings), [ - ...allNativeRuntimes, - nativeRuntimeStableDiffusion, - ]); expect(select(const ['stable_diffusion', 'none'], warnings), isEmpty); expect(warnings, isEmpty); }); + test('all implies every runtime on every bundle and names none', () { + for (final bundle in const [ + 'android-arm64', + 'android-x64', + 'ios-arm64', + 'ios-arm64-sim', + 'ios-x86_64-sim', + 'linux-arm64', + 'linux-x64', + 'macos-arm64', + 'macos-x86_64', + 'windows-arm64', + 'windows-x64', + ]) { + for (final rawUserConfig in const [ + 'all', + ['all'], + ['all', 'stable_diffusion'], + ]) { + final reason = '$bundle $rawUserConfig'; + final warnings = []; + expect( + selectNativeRuntimesForBundle( + bundle: bundle, + rawUserConfig: rawUserConfig, + warn: warnings.add, + ), + [ + nativeRuntimeLlamaCpp, + nativeRuntimeLiteRtLm, + nativeRuntimeStableDiffusion, + ], + reason: reason, + ); + expect(warnings, isEmpty, reason: reason); + // What lets `hook/build.dart` skip a runtime `all` implies with a + // warning instead of failing the build. + expect( + nativeRuntimeExplicitlySelectedForBundle( + bundle: bundle, + rawUserConfig: rawUserConfig, + runtime: nativeRuntimeLiteRtLm, + ), + isFalse, + reason: reason, + ); + expect( + nativeRuntimeExplicitlySelectedForBundle( + bundle: bundle, + rawUserConfig: rawUserConfig, + runtime: nativeRuntimeStableDiffusion, + ), + rawUserConfig is List && rawUserConfig.length == 2, + reason: reason, + ); + expect( + nativeRuntimeNamedForExactBundle( + bundle: bundle, + rawUserConfig: rawUserConfig, + runtime: nativeRuntimeStableDiffusion, + ), + isFalse, + reason: reason, + ); + } + } + }); + + test('all and both never count as an explicitly selected runtime', () { + for (final runtime in const ['all', 'both', 'none']) { + expect( + nativeRuntimeExplicitlySelectedForBundle( + bundle: 'linux-x64', + rawUserConfig: const ['all', 'both', 'llama_cpp'], + runtime: runtime, + ), + isFalse, + reason: runtime, + ); + } + }); + test('unknown-runtime warning lists stable_diffusion as supported', () { final warnings = []; select(const ['onnx'], warnings); diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index f80022fca..c0fd8a5d1 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -116,6 +116,19 @@ For canonical full release notes, use: 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)). +- **Behavior change:** `all` in `llamadart_native_runtimes` now includes the + opt-in `stable_diffusion` image runtime, so `llamadart_native_runtimes: all` + ships GGUF, `.litertlm` and image generation together. An app that already + sets `all`, or a list containing it, downloads 14.7 to 15.6 MB more per + target, or 25.8 to 27.8 MB for the Vulkan build Linux and Windows use by + default, and grows by about 37 MB as measured on macOS arm64 and Android + arm64. android-x64 and Windows arm64 publish no image runtime and skip it + with a warning. A Flutter iOS or macOS app skips it with a build warning + unless `llamadart_stable_diffusion_flutter` is a dependency; a pub + workspace member, whose user-defines live in the workspace root pubspec, is + not recognised as one and bundles it. Leaving the key unset, or setting + `both`, still bundles only `llama_cpp` and `litert_lm` + ([#856](https://github.com/leehack/llamadart/issues/856)). ## 0.11.1 diff --git a/website/docs/guides/backend-selection.md b/website/docs/guides/backend-selection.md index 8a4fcdde5..57e0d4103 100644 --- a/website/docs/guides/backend-selection.md +++ b/website/docs/guides/backend-selection.md @@ -236,4 +236,6 @@ one build can load both GGUF and `.litertlm` models. To ship only one, set `llamadart_native_runtimes` as described in [Native Build Hooks](../platforms/native-build-hooks). The experimental `stable_diffusion` runtime, which [image generation](./image-generation) -needs, is never included unless named there. +needs, is never included unless named there or selected with `all`. A list +there replaces the defaults: `all` bundles every runtime published for the +target. diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index 29763f8ac..c4047dfa9 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -78,9 +78,19 @@ default. Name it in the app's `pubspec.yaml`, then run `flutter clean` once: hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_native_runtimes: all ``` +Unset, `llamadart_native_runtimes` bundles `llama_cpp` and `litert_lm`. A list +replaces those defaults, so it names every runtime the app loads: + +| The app loads | `llamadart_native_runtimes` | +| --- | --- | +| GGUF and `.litertlm` models | unset | +| Images only | `[stable_diffusion]` | +| GGUF models and images | `[llama_cpp, stable_diffusion]` | +| Every runtime published for the target | `all` | + Linux and Windows get the Vulkan build when `llamadart_native_backends` selects Vulkan, which it does by default; set `llamadart_stable_diffusion_backends: [cpu]` for the CPU build. See @@ -97,11 +107,15 @@ dependencies: llamadart_stable_diffusion_flutter: ^0.0.2 ``` -Without it, the hook bundles the runtime into a framework that Flutter marks -`MinimumOSVersion` 13.0 while the library needs iOS 16.4, so App Store Connect -rejects the iOS upload. The iOS build reports this as an Xcode build warning, -which Xcode and `xcodebuild` show but plain `flutter build` and `flutter run` -output does not. See +Without it, `all` leaves the image runtime out of a Flutter iOS or macOS app +and `ImageGenerationEngine.checkRuntime()` reports it as not bundled. The +build warns about it: `flutter build macos`, Xcode and `xcodebuild` show the +warning, and `flutter build ios` output does not. A list naming +`stable_diffusion` bundles the runtime through the hook instead, into a +framework that Flutter marks `MinimumOSVersion` 13.0 while the library needs +iOS 16.4, so App Store Connect rejects the iOS upload. The iOS build reports +this as an Xcode build warning, which Xcode and `xcodebuild` show but plain +`flutter build` and `flutter run` output does not. See [Flutter Apple apps](../platforms/native-build-hooks#flutter-apple-apps). The hook-bundled runtime also cannot carry an Apple privacy manifest. The companion's XCFramework carries one from `stable-diffusion-native` `v0.2.0-1`, diff --git a/website/docs/platforms/native-build-hooks.md b/website/docs/platforms/native-build-hooks.md index 67fd98b03..a720a1486 100644 --- a/website/docs/platforms/native-build-hooks.md +++ b/website/docs/platforms/native-build-hooks.md @@ -62,14 +62,16 @@ hooks: bundle keys: `android-arm64`, `android-x64`, `ios-arm64`, `ios-arm64-sim`, `ios-x86_64-sim`, `linux-arm64`, `linux-x64`, `macos-arm64`, `macos-x86_64`, `windows-arm64` and `windows-x64`. For each bundle the - exact bundle key wins, then its OS key, then `runtimes`, then every family. + exact bundle key wins, then its OS key, then `runtimes`, then the default + `llama_cpp` and `litert_lm`. - Aliases: `gguf`, `llama`, `llama.cpp` for `llama_cpp`; `litert`, `litert-lm`, `litertlm`, `.litertlm` for `litert_lm`; `stable-diffusion` for - `stable_diffusion`. `all` and `both` select `llama_cpp` and `litert_lm`. - Unknown names are dropped with a warning. + `stable_diffusion`. `all` selects every family, the opt-in + `stable_diffusion` included; `both` selects `llama_cpp` and `litert_lm`, the + same as leaving the key unset. Unknown names are dropped with a warning. - Selecting `litert_lm` by name for a target without a LiteRT-LM runtime, such as the iOS x86_64 simulator or Windows arm64, fails the build. When it is only - implied by the default or `all`, the hook drops it with a warning. + implied by the default, `both` or `all`, the hook drops it with a warning. - An empty or all-unknown selection falls back to `llama_cpp` and `litert_lm`; one that leaves no runtime, such as `none`, fails the build. @@ -79,17 +81,40 @@ hooks: [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) runtime from `leehack/stable-diffusion-native` for the experimental [`ImageGenerationEngine`](../guides/image-generation). It adds about 40 to -70 MB per target, so it is never bundled by default or by `all`/`both`; name it -explicitly: +70 MB per target, so it is never bundled by default or by `both`; name it, or +select `all`. Unset, `llamadart_native_runtimes` bundles `llama_cpp` and +`litert_lm`; a list replaces those defaults, so it names every runtime the app +loads: + +| The app loads | `llamadart_native_runtimes` | +| --- | --- | +| GGUF and `.litertlm` models | unset | +| Images only | `[stable_diffusion]` | +| GGUF models and images | `[llama_cpp, stable_diffusion]` | +| Every runtime published for the target | `all` | ```yaml hooks: user_defines: llamadart: - llamadart_native_runtimes: - runtimes: [llama_cpp, stable_diffusion] + llamadart_native_runtimes: all ``` +- `all` only implies its runtimes, so a target without a LiteRT-LM or + `stable_diffusion` build skips that runtime with a warning. + `[llama_cpp, litert_lm, stable_diffusion]` names `litert_lm` and fails the + build on a target without it. +- In a Flutter iOS or macOS app, `all` includes `stable_diffusion` only when + the `llamadart_stable_diffusion_flutter` companion is a dependency. Without + it the hook leaves the runtime out with a build warning that names the + companion, and `ImageGenerationEngine.checkRuntime()` reports it as not + bundled. `flutter build macos`, Xcode and `xcodebuild` show the warning; + `flutter build ios` output does not. Naming `stable_diffusion` still bundles + it through the hook there. + The hook reads the pubspec that carries the user-defines, so a Flutter app + that is a pub workspace member, whose user-defines live in the workspace + root pubspec, is not recognised as a Flutter app: `all` at the root bundles + the runtime through the hook with no warning. - Published for `android-arm64`, `ios-arm64`, `ios-arm64-sim`, `ios-x86_64-sim`, `macos-arm64`, `macos-x86_64`, `linux-arm64`, `linux-x64` and `windows-x64`, built for iOS @@ -131,11 +156,11 @@ hooks: `android-x64: [stable_diffusion]`, fails the build instead. - Flutter iOS and macOS apps should add the `llamadart_stable_diffusion_flutter` companion instead; see [Flutter Apple apps](#flutter-apple-apps). Without it - the hook bundles the runtime, and App Store Connect rejects that iOS - framework: Flutter writes `MinimumOSVersion` 13.0 into it, while the library - needs iOS 16.4. The hook reports this as an Xcode build warning, which Xcode - and `xcodebuild` show but plain `flutter build` and `flutter run` output - does not. + a list naming `stable_diffusion` makes the hook bundle the runtime, and App + Store Connect rejects that iOS framework: Flutter writes `MinimumOSVersion` + 13.0 into it, while the library needs iOS 16.4. The hook reports this as an + Xcode build warning, which Xcode and `xcodebuild` show but plain + `flutter build` and `flutter run` output does not. ## Choose llama.cpp backend modules @@ -305,7 +330,10 @@ When the llama.cpp or LiteRT-LM companion is present, the installed companions choose the Apple `llama_cpp` and `litert_lm` families and the rest of `llamadart_native_runtimes` is ignored with a warning. `stable_diffusion` is decided on its own: its companion selects it, and otherwise the hook bundles it -when `llamadart_native_runtimes` names it. Adding only the stable_diffusion +when `llamadart_native_runtimes` names it, not when `all` only implies it; +a pub workspace member is the exception described under +[Opt-in stable_diffusion runtime](#opt-in-stable_diffusion-runtime-experimental). +Adding only the stable_diffusion companion leaves llama.cpp and LiteRT-LM on the hook. The build checks the resolved llama.cpp and stable_diffusion companions' pins against the core package and rejects local `Artifacts` overrides. The tag, From bef5aba55f0dfb136567c165091759873dc8369b Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:17:56 -0400 Subject: [PATCH 5/7] test: record the Android Vulkan prompt cap decision in a micro-batch sweep E2E (#987) --- doc/testing_matrix.md | 1 + example/chat_app/README.md | 92 ++ .../MainActivityTest.java | 34 +- .../micro_batch_sweep_e2e_test.dart | 973 ++++++++++++++++++ .../support/micro_batch_sweep_support.dart | 228 ++++ .../test/micro_batch_sweep_support_test.dart | 366 +++++++ .../android_vulkan_prompt_cap_log_test.dart | 156 +++ test/unit/tooling/run_local_e2e_test.dart | 25 + tool/testing/run_local_e2e.dart | 27 + tool/testing/test_matrix.dart | 22 + 10 files changed, 1921 insertions(+), 3 deletions(-) create mode 100644 example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart create mode 100644 example/chat_app/integration_test/support/micro_batch_sweep_support.dart create mode 100644 example/chat_app/test/micro_batch_sweep_support_test.dart create mode 100644 test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 93b341ca2..53e335ce4 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -150,6 +150,7 @@ Pick targeted rows based on the touched surface: | LiteRT-LM web / Gemma 4 web bundle | `gemma4-litert-web` | | Chat app model cache/download/projector | `chat-app-device-cache` | | LiteRT-LM engine reload memory on a device | `chat-app-litert-reload-memory` | +| Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` | | Isolate shutdown releases, exit teardown, a Flutter pin bump, or app-exit guidance | `chat-app-macos-quit` | | Speech-to-text API or adapter | `speech-to-text-smoke`, `web-speech-to-text-smoke`, plus `litert-lm-asr-smoke` for the dedicated LiteRT-LM streaming engine | | Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | diff --git a/example/chat_app/README.md b/example/chat_app/README.md index a9a8c82e4..16ed48d1c 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -823,3 +823,95 @@ temperature 0, seed 1). The matching build-time defaults are `LITERT_RELOAD_TEMPERATURE` and `LITERT_RELOAD_SEED`. An argument passed as an empty string keeps its default. Fewer than three iterations record the steps without the memory check. + +#### Micro-batch sweep and the Android Vulkan prompt cap + +`integration_test/micro_batch_sweep_e2e_test.dart` loads the locked +`chat-gguf-vulkan` model at several micro-batch sizes in one process and sends +a short history prompt, a long history prompt and a tool request with +`ToolChoice.auto` and `ToolChoice.required` at each. Size `0` is the library +default and the only one the test judges, so the sizes must include it: a +default attempt must load, answer both history prompts with the code and +nothing else, and end both tool requests as the `get_weather` call. + +Every other size is a control that is only recorded. An explicit size, even +`512` (the default `n_ubatch`), makes the library leave the Android Vulkan +prompt cap off, so `0+512` compares the capped default with the same context +uncapped. On a Vulkan device with the small matmul tile defect the control is +expected to answer wrongly (a Pixel 9 Pro's Mali-G715, subgroup size 16, +answered `8888...`); a correct control there says the cap is no longer needed. + +Every repeat of the default size runs first, then the controls repeat by +repeat, and a control sends the tool requests only in its last repeat, so +nothing a control does to the process costs a judged repeat. + +```sh +dart run tool/testing/run_local_e2e.dart \ + --scenario chat-app-micro-batch-sweep --device +``` + +Only an Android device whose GPU ggml-vulkan registers makes the library +decide about the cap. Elsewhere the run checks the default path and the +harness. + +For Test Lab, build both APKs from that target as above, then add: + +```sh +--environment-variables=microBatchArms=0+512,microBatchRepeats=6,microBatchBudgetSeconds=450,microBatchNativeLog=debug \ +--directories-to-pull=/sdcard/Android/data/com.example.llamadart_chat_example/files/micro_batch_sweep +``` + +The pulled directory holds `journal.jsonl`, `native_stderr.log`, `vkjson.json` +(`cmd gpu vkjson`, saved before Flutter starts: the driver's API version and +subgroup size) and `app_apk.sha256`. Every journal record is written through +before the next step, and the same records appear in logcat as +`MICRO_BATCH_SWEEP` lines. In the journal: + +- `attempt_verdict` is the verdict of one attempt: `passed`, the judged cases + one by one, the failures and the cap state. `judged` is true for the default + size. A run that dies keeps the verdicts of the attempts before it. +- `prompt_cap` is what is known about the cap of an attempt's context, as + `state`: + - `capped` (with `cap_tokens`) or `not_capped`: the library's own debug + line, with the Vulkan devices it decided from (`name`, `api_version`, + `loader_api_version`, `subgroup_size`). The library logs it only when it + has a Vulkan device to decide from. + - `no_vulkan_device`: the load asked Vulkan for GPU layers but ggml-vulkan + registered no device. The library logs nothing and applies the cap all the + same, although the context runs on the CPU (an emulator, or a load that + fell back). + - `explicit_size`: an explicit size, which leaves the cap off. + - `vulkan_not_requested`, `not_android`: no cap. + - `not_logged`: a Vulkan device is registered and the cap was to be decided, + but no decision reached the log. Treat the record as missing. +- `load` holds the backend the model runs on, its GPU layer count and the GPU + devices the runtime lists. +- `log` is every `LlamaLogger` record, among them the warning of a load that + fell back to the CPU because the Vulkan driver is below 1.2. +- `load_refused` is a typed exception from a load. +- `case` and `case_error` are each answer (with `passed` for a judged case) + and each typed exception from a request; `summary` counts the passing + answers by size. + +`microBatchDevice=gpu` asks each load for `ComputeDevice.gpu` first, records a +typed refusal as `load_refused` and then loads as the profile does +(`ComputeDevice.auto`), so one run shows whether a device that cannot run +Vulkan gets a typed error and a CPU fallback. The other arguments are +`microBatchProfile` (a validation profile id) and, at build time, +`--dart-define=MICRO_BATCH_SWEEP_ARMS`, `MICRO_BATCH_SWEEP_REPEATS`, +`MICRO_BATCH_SWEEP_BUDGET_SECONDS`, `MICRO_BATCH_SWEEP_NATIVE_LOG`, +`MICRO_BATCH_SWEEP_DEVICE`, `MICRO_BATCH_SWEEP_PROFILE` and +`MICRO_BATCH_SWEEP_MODEL`. + +The budget counts from the end of the model download and check. Past it no +attempt and no request starts and the test fails, which keeps a slow device +inside the Test Lab timeout; give the timeout the download on top (it took 1.5 +to 4 minutes for this model on Test Lab) and the length of one request. + +`--dart-define=MICRO_BATCH_SWEEP_NEGATIVE_CONTROL=true` checks the judge: it +expects a code the prompts do not hold, so the test must fail, with failures +of the default size only. + +When a native crash ends the app, Test Lab reports `Test failed to run`. It +still pulls the directory: the last `attempt_started` or `case_started` record +without its result names the step that was running. diff --git a/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java b/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java index 87c10a159..556a28f80 100644 --- a/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java +++ b/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java @@ -30,6 +30,7 @@ public MainActivityTest() throws IOException { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); if ("true".equals(arguments.getString("stageModel"))) stageModel(instrumentation); forwardReloadMemoryArguments(arguments, instrumentation); + forwardMicroBatchSweepArguments(arguments, instrumentation); } private static void stageModel(Instrumentation instrumentation) throws IOException { @@ -85,6 +86,33 @@ private static void forwardReloadMemoryArguments(Bundle arguments, Instrumentati if (snapshots) startDumpsysResponder(instrumentation, cache); } + // Hands micro_batch_sweep_e2e_test.dart its instrumentation arguments, and + // with any of them saves the device facts next to its journal. + private static void forwardMicroBatchSweepArguments(Bundle arguments, Instrumentation instrumentation) + throws IOException { + File file = new File(instrumentation.getTargetContext().getCacheDir(), "micro_batch_sweep_args.json"); + JSONObject json = new JSONObject(); + try { + json.put("arms", optional(arguments, "microBatchArms")); + json.put("repeats", optional(arguments, "microBatchRepeats")); + json.put("budget_seconds", optional(arguments, "microBatchBudgetSeconds")); + json.put("profile", optional(arguments, "microBatchProfile")); + json.put("native_log", optional(arguments, "microBatchNativeLog")); + json.put("device", optional(arguments, "microBatchDevice")); + if (json.length() == 0) { + file.delete(); + return; + } + json.put("pid", Process.myPid()); + } catch (JSONException error) { + throw new IOException(error); + } + write(file, json.toString()); + // Connect UiAutomation before Flutter starts, as the dumpsys responder does. + instrumentation.getUiAutomation(); + saveDeviceFacts(instrumentation, "micro_batch_sweep"); + } + // Null for a blank value: a runner that passes an optional argument as an // empty string means the default, and JSONObject.put drops a null value. private static String optional(Bundle arguments, String name) { @@ -95,10 +123,10 @@ private static String optional(Bundle arguments, String name) { // Next to the journal: the Vulkan driver's own limits, from which a WebGPU // limit that a run trips over is derived, and the hash of the installed // app APK, which names the runtime libraries the run loaded. - private static void saveDeviceFacts(Instrumentation instrumentation) { + private static void saveDeviceFacts(Instrumentation instrumentation, String output) { try { Context context = instrumentation.getTargetContext(); - File directory = new File(context.getExternalFilesDir(null), "litert_reload_memory"); + File directory = new File(context.getExternalFilesDir(null), output); if (!directory.isDirectory() && !directory.mkdirs()) { throw new IOException("Unable to create " + directory); } @@ -122,7 +150,7 @@ private static void startDumpsysResponder(Instrumentation instrumentation, File // semantics. Connect before Flutter starts: a semantics handle that // appears during the test fails it at the end. instrumentation.getUiAutomation(); - saveDeviceFacts(instrumentation); + saveDeviceFacts(instrumentation, "litert_reload_memory"); Thread responder = new Thread(() -> { while (true) { try { diff --git a/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart b/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart new file mode 100644 index 000000000..92dbc5075 --- /dev/null +++ b/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart @@ -0,0 +1,973 @@ +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 25)) +/// Local-only E2E that runs history, long-history and tool prompts at several +/// micro-batch sizes (`ModelParams.microBatchSize`, llama.cpp `n_ubatch`) in +/// one process, and records what the library decided about the Android Vulkan +/// text prompt cap (https://github.com/leehack/llamadart/issues/948). +/// +/// Each attempt loads the locked model of a validation profile on a new +/// engine, generates the `C03.raw`, `C04.hello`, `C04.arithmetic`, +/// `C06.history`, `X01.long_history`, `C07.tools.auto` and +/// `C07.tools.required` requests through the validation engine, and disposes +/// the engine. +/// +/// Size `0` is the library default and the only one the test judges; the +/// sizes must include it. A default attempt passes when it loads, answers +/// `C06.history` and `X01.long_history` with the code and nothing else, and +/// ends both tool requests as the `get_weather` call. The test fails after +/// the sweep when a default attempt did not pass. On Android Vulkan the +/// default is the capped path wherever the library applies the cap. +/// +/// Every other size is a control and is only recorded. An explicit size, even +/// one equal to the default `n_ubatch` (512), makes the library leave the cap +/// off, so `0,512` compares the capped default with the same context +/// uncapped. That control is expected to answer wrongly on a Vulkan device +/// with the small matmul tile defect (a Pixel 9 Pro's Mali-G715, subgroup size +/// 16, answered `8888...`); a correct control there says the cap is no longer +/// needed. +/// +/// Every repeat of the default size runs first, then the controls repeat by +/// repeat, and a control sends the tool requests only in its last repeat: a +/// grammar over a control's logits is what aborted the process before native +/// exceptions were typed, and nothing a control does to the process may cost +/// a judged repeat. +/// +/// Records go to `micro_batch_sweep/journal.jsonl` (app external files on +/// Android, the temporary directory elsewhere), each written through before +/// the next step, and, shortened, to the log as `MICRO_BATCH_SWEEP {json}` +/// lines. An `attempt_started` and a `case_started` record precede each step, +/// so a run that dies names the step it died in, and the verdicts of the +/// attempts before it are already in the file. `t_ms` is the time since the +/// test opened the journal. +/// +/// - `log`: every `LlamaLogger` record at `debug` and above, among them the +/// warning of a load that fell back to the CPU. +/// - `load`: the backend the model runs on, its GPU layer count, the batch +/// sizes and the GPU devices the runtime lists. +/// - `prompt_cap`: what is known about the cap of the attempt's context, as +/// `state`. `capped` (with `cap_tokens`) and `not_capped` are the library's +/// own debug line, with the Vulkan devices the decision was made from +/// (name, driver and loader API version, subgroup size). The library logs +/// that line only when it has a Vulkan device to decide from, so the other +/// states are derived from the load: `explicit_size` (an explicit size +/// leaves the cap off), `not_android`, `vulkan_not_requested` (no GPU layer +/// asked of Vulkan: no cap), `no_vulkan_device` (GPU layers asked of Vulkan +/// but ggml-vulkan registered no device: the library applies the cap +/// without logging, and the context runs on the CPU) and `not_logged` (a +/// Vulkan device is registered but no decision reached the log). +/// - `load_refused`: a typed exception from a load, such as the refusal of a +/// Vulkan driver below 1.2. +/// - `case`, `case_error`: each answer with its timings and, for a judged +/// case, `passed`; a typed exception from a request. +/// - `attempt_verdict`: whether the attempt passed, case by case, with the +/// failures and the cap state. `judged` is true for the default size. +/// - `summary`: the passing answers by size and the test's failures. +/// +/// A `case` record times the prompt twice. `native_prompt_ms` is the llama.cpp +/// worker's own clock around prompt ingestion, valid at every micro-batch +/// size, and `prompt_tps` is `prompt_tokens` over it. `native_prompt_tokens` +/// is llama.cpp's counter, which leaves the prompt out at micro-batch size 1. +/// `ttfa_ms` is this isolate's clock from the request to the first streamed +/// text: it adds templating, the isolate hops and the first stream batch. +/// +/// Native llama.cpp output goes to standard error, which Android discards; +/// this test points standard error at `micro_batch_sweep/native_stderr.log` +/// and copies the `ggml_vulkan:` device lines and the context's `n_batch` and +/// `n_ubatch` from it into the records. The device lines need `debug`. +/// +/// ```bash +/// cd example/chat_app +/// flutter test --run-skipped -t local-only \ +/// integration_test/micro_batch_sweep_e2e_test.dart -d \ +/// --dart-define=MICRO_BATCH_SWEEP_ARMS=0,512 \ +/// --dart-define=MICRO_BATCH_SWEEP_REPEATS=3 +/// ``` +/// +/// `MICRO_BATCH_SWEEP_ARMS` lists the sizes. `MICRO_BATCH_SWEEP_REPEATS` +/// counts the rounds. `MICRO_BATCH_SWEEP_BUDGET_SECONDS` is the time the sweep +/// may take, counted from the end of the model download and check: past it no +/// attempt and no request starts, and the test fails. +/// `MICRO_BATCH_SWEEP_PROFILE` names the validation profile (default +/// `chat-gguf-vulkan`), `MICRO_BATCH_SWEEP_NATIVE_LOG` the native log level +/// (`info` or `debug`, default `info`) and `MICRO_BATCH_SWEEP_MODEL` a local +/// copy of the profile's model. `MICRO_BATCH_SWEEP_DEVICE=gpu` asks each load +/// for `ComputeDevice.gpu` first, records a typed refusal and then loads as +/// the profile does (`ComputeDevice.auto`), so one run shows both what a +/// required GPU and what the default do on the device. A blank value keeps +/// the default. +/// +/// `MICRO_BATCH_SWEEP_NEGATIVE_CONTROL=true` checks the judge: it expects a +/// code the prompts do not hold, so the test must fail, with failures of the +/// default size only. +/// +/// Under Android instrumentation (Firebase Test Lab or `adb shell am +/// instrument`), `MainActivityTest` forwards the arguments `microBatchArms` +/// (`+`-separated), `microBatchRepeats`, `microBatchBudgetSeconds`, +/// `microBatchProfile`, `microBatchNativeLog` and `microBatchDevice`, and with +/// any of them saves `cmd gpu vkjson` (the Vulkan driver's properties, among +/// them the API version and the subgroup size) and the installed app APK's +/// SHA-256 next to the journal before Flutter starts. +library; + +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:integration_test/integration_test.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_validation/io.dart'; +import 'package:llamadart_validation/llamadart_validation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import 'support/micro_batch_sweep_support.dart'; +import 'support/process_memory_snapshot.dart'; + +const _logTag = 'MICRO_BATCH_SWEEP'; +const _profileAssets = 'packages/llamadart_validation/assets/profiles/'; +const _argumentsFile = 'micro_batch_sweep_args.json'; +const _maxLoggedText = 160; +const _defaultArm = 0; +const _historyCase = 'C06.history'; +const _longCase = 'X01.long_history'; +// The locked Q4_0 model answers this prompt with `42` on CPU and Metal too; +// only the Q4_K_M quantization repeats the whole `maple42`. +const _longCodes = ['42', 'maple42']; +const _negativeControlCode = 'birch93'; +const _longMaxTokens = 12; +const _toolMaxTokens = 128; +const _toolCases = { + 'C07.tools.auto': ToolChoice.auto, + 'C07.tools.required': ToolChoice.required, +}; + +/// A history of about 300 prompt tokens whose first turn holds the code. The +/// filler spells its numbers out, so a digit in the answer comes from the code. +const _longHistory = <(LlamaChatRole, String)>[ + ( + LlamaChatRole.system, + 'You are a careful assistant. Remember the access code exactly.', + ), + (LlamaChatRole.user, 'The access code is maple42.'), + (LlamaChatRole.assistant, 'I will remember the access code.'), + ( + LlamaChatRole.user, + 'Before we continue, here is a note about the warehouse. The north ' + 'shelves hold garden tools, the south shelves hold paint, and the ' + 'loading dock opens at seven each morning.', + ), + ( + LlamaChatRole.assistant, + 'Noted: garden tools north, paint south, and the dock opens at seven.', + ), + ( + LlamaChatRole.user, + 'Another note. The delivery van is blue, it needs new tires before ' + 'winter, and the driver prefers the coastal road because it has fewer ' + 'traffic lights.', + ), + ( + LlamaChatRole.assistant, + 'Noted: the blue van needs tires, and the driver likes the coastal road.', + ), + ( + LlamaChatRole.user, + 'One more. The office plants are watered on Mondays, the printer on the ' + 'second floor jams when the paper is damp, and the spare keys are ' + 'kept in the grey cabinet.', + ), + ( + LlamaChatRole.assistant, + 'Noted: plants on Mondays, a moody printer, and keys in the grey cabinet.', + ), + ( + LlamaChatRole.user, + 'Last note. The team lunch is on Thursday at noon, the bakery across the ' + 'street closes early on Fridays, and the meeting room projector needs ' + 'a new cable.', + ), + ( + LlamaChatRole.assistant, + 'Noted: lunch on Thursday at noon, the bakery closes early on Fridays, ' + 'and the projector needs a cable.', + ), + (LlamaChatRole.user, 'What is the access code? Reply with only the code.'), +]; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('the default micro-batch answers history and tool prompts', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold(body: Text('Running micro-batch sweep E2E')), + ), + ); + final temporary = await getTemporaryDirectory(); + final config = _Config.resolve(temporary); + final output = Directory( + p.join( + ((Platform.isAndroid ? await getExternalStorageDirectory() : null) ?? + temporary) + .path, + 'micro_batch_sweep', + ), + )..createSync(recursive: true); + final journal = _Journal(File(p.join(output.path, 'journal.jsonl'))); + final nativeLog = _NativeLog.capture( + File(p.join(output.path, 'native_stderr.log')), + ); + addTearDown(nativeLog.restore); + final order = sweepOrder( + config.arms, + config.repeats, + judgedArm: _defaultArm, + ); + journal.log({ + 'event': 'config', + 'profile': config.profile, + 'arms': config.arms, + 'repeats': config.repeats, + 'order': [ + for (final attempt in order) [attempt.repeat, attempt.arm], + ], + 'budget_seconds': config.budget?.inSeconds, + 'native_log': config.nativeLevel.name, + 'device': config.device?.name, + 'negative_control': config.negativeControl, + 'source': config.source, + 'native_stderr_captured': nativeLog.captured, + 'pid': pid, + 'os': Platform.operatingSystem, + 'os_version': Platform.operatingSystemVersion, + }); + final logs = _LibraryLog(journal); + // Set once, before the first engine starts its worker: ggml-vulkan prints + // its device lines only when the process first initializes the backend. + await LlamaLogging.configure( + level: LlamaLogLevel.debug, + nativeLevel: config.nativeLevel, + handler: logs.record, + ); + addTearDown(LlamaLogging.configure); + + final profile = await _loadProfile(config.profile); + final modelPath = await _prepareModel(profile, config.model, journal); + // The budget is for the sweep: a download takes minutes that vary with + // the network, and would otherwise decide how many repeats run. + final elapsed = Stopwatch()..start(); + final budget = config.budget; + bool overBudget() => budget != null && elapsed.elapsed > budget; + final codes = config.negativeControl + ? const { + _historyCase: [_negativeControlCode], + _longCase: [_negativeControlCode], + } + : { + _historyCase: [profile.fixtureText('history', 'expected')], + _longCase: _longCodes, + }; + final judgedCases = [...codes.keys, ..._toolCases.keys]; + final failures = []; + final correct = { + for (final id in judgedCases) id: {for (final arm in config.arms) arm: 0}, + }; + final capStates = {for (final arm in config.arms) arm: {}}; + var judgedPassed = 0; + for (final (:repeat, :arm) in order) { + final labels = {'repeat': repeat, 'micro_batch': arm}; + final judged = arm == _defaultArm; + final withTools = judged || repeat == config.repeats; + if (overBudget()) { + journal.log({ + 'event': 'budget_exhausted', + ...labels, + 'elapsed_seconds': elapsed.elapsed.inSeconds, + }); + failures.add( + 'stopped before micro-batch $arm repeat $repeat: over the ' + '${budget!.inSeconds} s budget', + ); + break; + } + logs.begin(labels); + var results = const {}; + String? loadError; + try { + results = await _attempt( + profile, + modelPath, + labels, + arm, + config.device, + withTools: withTools, + codes: codes, + overBudget: overBudget, + journal: journal, + nativeLog: nativeLog, + logs: logs, + ); + } on LlamaException catch (error) { + journal.log({ + 'event': 'attempt_error', + ...labels, + 'error_type': '${error.runtimeType}', + 'error': '$error', + }); + loadError = '${error.runtimeType}: $error'; + } + final verdict = judgeAttempt( + [...codes.keys, if (withTools) ..._toolCases.keys], + results, + loadError: loadError, + ); + journal.log({ + 'event': 'attempt_verdict', + ...labels, + 'judged': judged, + 'passed': verdict.passed, + 'cases': verdict.cases, + 'failures': verdict.failures, + 'prompt_cap': logs.capState, + }); + for (final MapEntry(key: id, value: passed) in verdict.cases.entries) { + if (passed) correct[id]![arm] = correct[id]![arm]! + 1; + } + if (logs.capState case final state?) capStates[arm]!.add(state); + if (judged) { + if (verdict.passed) judgedPassed++; + failures.addAll([ + for (final failure in verdict.failures) + 'default micro-batch repeat $repeat: $failure', + ]); + } + } + logs.begin(const {}); + journal.log({ + 'event': 'summary', + 'expected': codes, + 'repeats': config.repeats, + 'judged_micro_batch': _defaultArm, + 'judged_passed': judgedPassed, + 'correct': { + for (final MapEntry(key: id, value: arms) in correct.entries) + id: { + for (final MapEntry(:key, :value) in arms.entries) '$key': value, + }, + }, + 'prompt_cap': { + for (final MapEntry(:key, :value) in capStates.entries) + '$key': value.toList(), + }, + 'failures': failures, + }); + expect(failures, isEmpty, reason: failures.join('\n')); + }, timeout: const Timeout(Duration(minutes: 25))); +} + +class _Config { + _Config( + this.profile, + this.arms, + this.repeats, + this.budget, + this.nativeLevel, + this.device, + this.model, + this.source, { + required this.negativeControl, + }); + + factory _Config.resolve(Directory temporary) { + var profile = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_PROFILE'), + ) ?? + 'chat-gguf-vulkan'; + var arms = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_ARMS'), + ) ?? + '0,512'; + var repeats = const int.fromEnvironment( + 'MICRO_BATCH_SWEEP_REPEATS', + defaultValue: 3, + ); + var budget = const int.fromEnvironment('MICRO_BATCH_SWEEP_BUDGET_SECONDS'); + var nativeLog = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_NATIVE_LOG'), + ) ?? + 'info'; + var device = optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_DEVICE'), + ); + var source = 'dart-define'; + final file = File(p.join(temporary.path, _argumentsFile)); + if (Platform.isAndroid && file.existsSync()) { + final arguments = jsonDecode(file.readAsStringSync()) as Map; + // The file outlives the instrumentation that wrote it. + if (arguments['pid'] == pid) { + profile = optionalArgument(arguments['profile']) ?? profile; + arms = optionalArgument(arguments['arms']) ?? arms; + final count = optionalArgument(arguments['repeats']); + if (count != null) repeats = int.parse(count); + final seconds = optionalArgument(arguments['budget_seconds']); + if (seconds != null) budget = int.parse(seconds); + nativeLog = optionalArgument(arguments['native_log']) ?? nativeLog; + device = optionalArgument(arguments['device']) ?? device; + source = 'instrumentation'; + } + } + final sizes = [ + for (final size in arms.split(RegExp('[,+]'))) + if (size.trim().isNotEmpty) int.parse(size.trim()), + ]; + if (sizes.any((size) => size < 0)) { + throw ArgumentError.value(arms, 'arms', 'needs non-negative sizes'); + } + if (!sizes.contains(_defaultArm)) { + throw ArgumentError.value( + arms, + 'arms', + 'must include 0, the library default, which is the size the test ' + 'judges', + ); + } + if (repeats < 1) { + throw ArgumentError.value(repeats, 'repeats', 'must be at least 1'); + } + if (budget < 0) { + throw ArgumentError.value(budget, 'budget', 'must not be negative'); + } + if (!const {'info', 'debug'}.contains(nativeLog)) { + throw ArgumentError.value(nativeLog, 'native log', 'is info or debug'); + } + if (!const {null, 'auto', 'gpu'}.contains(device)) { + throw ArgumentError.value(device, 'device', 'is auto or gpu'); + } + return _Config( + profile, + sizes, + repeats, + budget == 0 ? null : Duration(seconds: budget), + LlamaLogLevel.values.byName(nativeLog), + device == null ? null : ComputeDevice.values.byName(device), + optionalArgument(const String.fromEnvironment('MICRO_BATCH_SWEEP_MODEL')), + source, + negativeControl: const bool.fromEnvironment( + 'MICRO_BATCH_SWEEP_NEGATIVE_CONTROL', + ), + ); + } + + final String profile; + + /// Micro-batch sizes; 0 is the library default and is always among them. + final List arms; + final int repeats; + + /// The time after the model is ready past which no attempt and no request + /// starts; null for no limit. + final Duration? budget; + final LlamaLogLevel nativeLevel; + + /// The device each load asks for first; null for the profile's own. + final ComputeDevice? device; + final String? model; + final String source; + + /// Whether the judge expects a code the prompts do not hold. + final bool negativeControl; +} + +Future _loadProfile(String id) async { + final source = await rootBundle.loadString('$_profileAssets$id.json'); + final data = jsonDecode(source) as Map; + data['execution_path'] = 'public_api'; + return ValidationProfile.fromJson(data); +} + +Future _prepareModel( + ValidationProfile profile, + String? supplied, + _Journal journal, +) async { + final cache = Directory( + p.join( + (await getApplicationSupportDirectory()).path, + 'validation', + 'models', + ), + ); + final client = http.Client(); + try { + final model = await prepareModel( + profile, + cache, + suppliedPath: supplied, + client: client, + timeout: const Duration(minutes: 10), + ); + journal.log({ + 'event': 'model', + 'filename': profile.filename, + 'revision': profile.model['revision'], + ...model.evidence, + }); + return model.path; + } finally { + client.close(); + } +} + +/// Loads [modelPath] on a new engine with [params]. +/// +/// With a [first] device other than the one in [params], that device is +/// tried first; a typed refusal is recorded and the load is repeated as +/// [params] has it. +Future<({LlamaEngine engine, ModelParams params})> _load( + String modelPath, + ModelParams params, + ComputeDevice? first, + Map labels, + _Journal journal, +) async { + final devices = {?first, params.device}; + for (final device in devices) { + final attempt = params.copyWith(device: device); + final engine = LlamaEngine(LlamaBackend()); + try { + await engine.setModel( + LlamaModel(ModelSource.parse(modelPath)), + params: attempt, + ); + return (engine: engine, params: attempt); + } on LlamaException catch (error) { + await engine.dispose(); + journal.log({ + 'event': 'load_refused', + ...labels, + 'device': device.name, + 'error_type': '${error.runtimeType}', + 'message': error.message, + 'details': error.details?.toString(), + }); + if (device == devices.last) rethrow; + } + } + throw StateError('unreachable: the last device rethrows'); +} + +/// Runs one load, the requests and the dispose, and returns how each judged +/// request ended by case. A request that [overBudget] stopped is left out. +Future> _attempt( + ValidationProfile profile, + String modelPath, + Map labels, + int microBatchSize, + ComputeDevice? device, { + required bool withTools, + required Map> codes, + required bool Function() overBudget, + required _Journal journal, + required _NativeLog nativeLog, + required _LibraryLog logs, +}) async { + journal.log({'event': 'attempt_started', ...labels}); + final logStart = nativeLog.length; + final watch = Stopwatch()..start(); + final loaded = await _load( + modelPath, + profile.loadParams.copyWith(microBatchSize: microBatchSize), + device, + labels, + journal, + ); + final engine = loaded.engine; + // The validation engine sends the requests exactly as the validation suite + // does; it is handed a loaded engine because its own load has no + // micro-batch size and resets the log levels. + final validation = PublicValidationEngine(engineFactory: () => engine); + try { + final diagnostics = await validation.diagnostics(); + final loadLog = nativeLog.since(logStart); + final resolved = resolveModelContextBatchSizes( + loaded.params, + profile.contextSize, + ); + List? gpuDevices; + try { + gpuDevices = await engine.listGpuDevices(); + } on LlamaException catch (error) { + journal.log({ + 'event': 'gpu_devices_error', + ...labels, + 'error_type': '${error.runtimeType}', + 'message': error.message, + }); + } + final gpuLayers = diagnostics['reported_gpu_layers'] as int? ?? 0; + journal.log({ + 'event': 'load', + ...labels, + 'ms': watch.elapsedMilliseconds, + 'device': loaded.params.device.name, + 'resolved_batch': resolved.batchSize, + 'resolved_micro_batch': resolved.microBatchSize, + 'native_n_batch': _contextValue(loadLog, 'n_batch'), + 'native_n_ubatch': _contextValue(loadLog, 'n_ubatch'), + 'backend_name': diagnostics['backend_name'], + 'reported_gpu_layers': gpuLayers, + 'context_size': diagnostics['context_size'], + 'gpu_devices': gpuDevices == null + ? null + : [ + for (final gpu in gpuDevices) + { + 'name': gpu.name, + 'backend': gpu.backend.name, + 'description': gpu.description, + }, + ], + 'native_log_bytes': loadLog.length, + }); + for (final line in loadLog.split('\n')) { + if (line.startsWith('ggml_vulkan:')) { + journal.log({'event': 'native_device', ...labels, 'line': line.trim()}); + } + } + final vulkanDevices = gpuDevices + ?.where((gpu) => gpu.backend == GpuBackend.vulkan) + .length; + final vulkanRequested = + loaded.params.preferredBackend == GpuBackend.vulkan && gpuLayers > 0; + final decision = logs.decision; + final state = promptCapState( + logged: decision, + microBatchSize: microBatchSize, + isAndroid: Platform.isAndroid, + vulkanRequested: vulkanRequested, + registeredVulkanDevices: vulkanDevices, + ); + logs.capState = state.wireName; + journal.log({ + 'event': 'prompt_cap', + ...labels, + 'state': state.wireName, + 'cap_tokens': decision?.capTokens, + 'devices': [ + for (final vulkan in decision?.devices ?? const []) + { + 'name': vulkan.name, + 'api_version': vulkan.apiVersion, + 'loader_api_version': vulkan.loaderApiVersion, + 'subgroup_size': vulkan.subgroupSize, + }, + ], + 'detail': decision?.detail, + 'backend_name': diagnostics['backend_name'], + 'vulkan_requested': vulkanRequested, + 'registered_vulkan_devices': vulkanDevices, + }); + + LlamaChatMessage message( + LlamaChatRole role, + String fixture, + String field, + ) => LlamaChatMessage.fromText( + role: role, + text: profile.fixtureText(fixture, field), + ); + final cases = ?>{ + 'C03.raw': null, + 'C04.hello': [message(LlamaChatRole.user, 'hello', 'prompt')], + 'C04.arithmetic': [message(LlamaChatRole.user, 'arithmetic', 'prompt')], + _historyCase: [ + message(LlamaChatRole.system, 'history', 'system'), + message(LlamaChatRole.user, 'history', 'user'), + message(LlamaChatRole.assistant, 'history', 'assistant'), + message(LlamaChatRole.user, 'history', 'prompt'), + ], + _longCase: [ + for (final (role, text) in _longHistory) + LlamaChatMessage.fromText(role: role, text: text), + ], + if (withTools) + for (final id in _toolCases.keys) + id: [message(LlamaChatRole.user, 'tools', 'prompt')], + }; + final toolFixture = profile.fixtures['tools'] as Map; + final toolFunction = (toolFixture['tool'] as Map)['function'] as Map; + final tool = ToolDefinition( + name: toolFunction['name'] as String, + description: toolFunction['description'] as String, + parameters: [ToolParam.string('city', required: true)], + ); + final results = {}; + for (final MapEntry(key: id, value: messages) in cases.entries) { + if (overBudget()) { + journal.log({'event': 'budget_exhausted', ...labels, 'case_id': id}); + break; + } + journal.log({'event': 'case_started', ...labels, 'case_id': id}); + final rawPrompt = profile.fixtureText('raw', 'prompt'); + final toolChoice = _toolCases[id]; + final judged = toolChoice != null || codes.containsKey(id); + final Map output; + try { + output = messages == null + ? await validation.generate(rawPrompt, profile, raw: true) + : toolChoice != null + ? await validation.generate( + messages.last.content, + profile, + history: messages, + tools: [tool], + toolChoice: toolChoice, + enableThinking: false, + maxTokens: _toolMaxTokens, + ) + : await validation.generate( + messages.last.content, + profile, + history: messages, + maxTokens: id == _longCase ? _longMaxTokens : null, + streamBatchTokens: id == _longCase ? 1 : null, + ); + } on LlamaException catch (error) { + journal.log({ + 'event': 'case_error', + ...labels, + 'case_id': id, + 'error_type': '${error.runtimeType}', + 'message': error.message, + 'details': error.details?.toString(), + if (judged) 'passed': false, + }); + if (judged) { + results[id] = ( + passed: false, + description: 'threw ${error.runtimeType}: $error', + ); + } + continue; + } + // llama.cpp counts a decode of one token as generation, so at + // micro-batch size 1 its prompt counter leaves the prompt out. + final promptTokens = messages == null + ? (await engine.tokenize(rawPrompt)).length + : (await engine.chatTemplate( + messages, + enableThinking: toolChoice == null && profile.enableThinking, + tools: toolChoice == null ? null : [tool], + toolChoice: toolChoice ?? ToolChoice.auto, + )).tokenCount; + final content = output['content'] as String; + final finish = output['finish_reasons']; + final call = reconstructToolCall(output['tool_call_deltas'] as List); + final passed = toolChoice != null + ? toolCallMatches( + finishReasons: finish, + call: call, + name: tool.name, + arguments: toolFixture['expected_arguments'], + ) + : codes[id] == null + ? null + : answerIsCode(content, codes[id]!); + final metrics = output['metrics'] as Map; + final promptMs = metrics['native_prompt_ms'] as double?; + journal.log({ + 'event': 'case', + ...labels, + 'case_id': id, + 'passed': ?passed, + 'expected': ?codes[id], + 'prompt_tokens': promptTokens, + 'native_prompt_tokens': metrics['native_prompt_tokens'], + 'native_decode_tokens': metrics['native_decode_tokens'], + 'finish_reasons': finish, + 'content': content, + if (toolChoice != null) ...{ + 'tool_choice': toolChoice.name, + 'tool_call_name': call.name, + 'tool_call_arguments': call.arguments, + }, + 'chunks': output['chunks'], + 'max_tokens': output['max_tokens'], + 'stream_batch_tokens': output['stream_batch_tokens'], + 'wall_ms': metrics['wall_ms'], + 'ttfa_ms': metrics['ttfa_ms'], + 'native_prompt_ms': promptMs, + 'prompt_tps': promptTokens == null || promptMs == null || promptMs <= 0 + ? null + : promptTokens * 1000 / promptMs, + 'native_decode_ms': metrics['native_decode_ms'], + }); + if (passed != null) { + results[id] = ( + passed: passed, + description: toolChoice != null + ? 'ended as ${call.name}(${jsonEncode(call.arguments)}), ' + 'finish ${jsonEncode(finish)}, content ' + '${jsonEncode(_shorten(content))}' + : 'answered ${jsonEncode(_shorten(content))}, finish ' + '${jsonEncode(finish)}, wanted one of ' + '${jsonEncode(codes[id])}', + ); + } + } + return results; + } finally { + await validation.dispose(); + } +} + +/// The value llama.cpp logs for [name] when it creates a context +/// (`llama_context: n_ubatch = 512`), or null when the line is missing. +int? _contextValue(String log, String name) { + final match = RegExp( + '^llama_context: $name\\s*=\\s*(\\d+)', + multiLine: true, + ).firstMatch(log); + return match == null ? null : int.parse(match[1]!); +} + +String _shorten(String text) => text.length <= _maxLoggedText + ? text + : '${text.substring(0, _maxLoggedText)}...'; + +class _Journal { + _Journal(this._file) { + _file.writeAsStringSync('', flush: true); + } + + final File _file; + final _clock = Stopwatch()..start(); + + void log(Map record) { + final event = {...record, 't_ms': _clock.elapsedMilliseconds}; + _file.writeAsStringSync( + '${jsonEncode(event)}\n', + mode: FileMode.append, + flush: true, + ); + // Android truncates a log line near 1 kB, and debugPrint buffers, which + // loses the last records when the process dies. + // ignore: avoid_print + print( + '$_logTag ${jsonEncode({for (final MapEntry(:key, :value) in event.entries) key: value is String ? _shorten(value) : value})}', + ); + } +} + +/// Journals the `LlamaLogger` records and keeps the prompt cap decision the +/// library logged for the attempt that is running. +class _LibraryLog { + _LibraryLog(this._journal); + + final _Journal _journal; + Map _labels = const {}; + + /// The decision the library logged since [begin], or null. + PromptCapDecision? decision; + + /// The journal name of the attempt's `PromptCapState`, once it is known. + String? capState; + + /// Starts the records of the attempt [labels] name. + void begin(Map labels) { + _labels = labels; + decision = null; + capState = null; + } + + void record(LlamaLogRecord record) { + _journal.log({ + 'event': 'log', + ..._labels, + 'level': record.level.name, + 'message': record.message, + 'error': record.error?.toString(), + }); + decision = parsePromptCapDecision(record.message) ?? decision; + } +} + +typedef _CreatNative = Int32 Function(Pointer, Uint32); +typedef _Creat = int Function(Pointer, int); +typedef _DupNative = Int32 Function(Int32); +typedef _Dup = int Function(int); +typedef _Dup2Native = Int32 Function(Int32, Int32); +typedef _Dup2 = int Function(int, int); + +/// Standard error of this process, pointed at a file while the test runs. +class _NativeLog { + _NativeLog._(this._file, this._saved); + + /// Points descriptor 2 at [file]. Where that is not possible, the test + /// still runs and records that native output was not captured. + factory _NativeLog.capture(File file) { + file.writeAsStringSync('', flush: true); + if (Platform.isWindows) return _NativeLog._(file, null); + try { + final process = DynamicLibrary.process(); + final creat = process.lookupFunction<_CreatNative, _Creat>('creat'); + final dup = process.lookupFunction<_DupNative, _Dup>('dup'); + final path = file.path.toNativeUtf8(); + try { + final descriptor = creat(path, 420); + if (descriptor < 0) return _NativeLog._(file, null); + final saved = dup(2); + final redirected = _dup2(descriptor, 2) == 2; + _close(descriptor); + if (!redirected) { + if (saved >= 0) _close(saved); + return _NativeLog._(file, null); + } + return _NativeLog._(file, saved); + } finally { + malloc.free(path); + } + } on ArgumentError { + return _NativeLog._(file, null); + } + } + + static final _Dup2 _dup2 = DynamicLibrary.process() + .lookupFunction<_Dup2Native, _Dup2>('dup2'); + static final _Dup _close = DynamicLibrary.process() + .lookupFunction<_DupNative, _Dup>('close'); + + final File _file; + final int? _saved; + bool _restored = false; + + bool get captured => _saved != null; + + int get length => _file.lengthSync(); + + /// The output written after byte [offset]. + String since(int offset) => utf8.decode( + _file.readAsBytesSync().sublist(offset), + allowMalformed: true, + ); + + void restore() { + final saved = _saved; + if (saved == null || _restored) return; + _restored = true; + if (saved >= 0) { + _dup2(saved, 2); + _close(saved); + } + } +} diff --git a/example/chat_app/integration_test/support/micro_batch_sweep_support.dart b/example/chat_app/integration_test/support/micro_batch_sweep_support.dart new file mode 100644 index 000000000..7eb034189 --- /dev/null +++ b/example/chat_app/integration_test/support/micro_batch_sweep_support.dart @@ -0,0 +1,228 @@ +import 'dart:convert'; + +/// One Vulkan device as the prompt cap log line of llamadart describes it. +typedef PromptCapDevice = ({ + String name, + String apiVersion, + String loaderApiVersion, + int subgroupSize, +}); + +/// What llamadart logged about the Android Vulkan text prompt cap when it +/// created a context. +/// +/// [capTokens] is the most prompt tokens one decode call takes, or null when +/// the cap is lifted. [devices] are the Vulkan devices the decision was made +/// from; when the probe could not list them, [detail] holds its reason. +typedef PromptCapDecision = ({ + int? capTokens, + List devices, + String detail, +}); + +final _capLine = RegExp( + r'Android Vulkan text prompt decode is ' + r'(?:capped at (\d+) tokens per call|not capped) \((.*)\)', + dotAll: true, +); +// A device name is free text and may hold a quote, so it ends at the quote +// that the version list follows. +final _capDevice = RegExp( + r'"(.*?)" \(API (\d+\.\d+), loader (\d+\.\d+), subgroup size (\d+)\)', + dotAll: true, +); + +/// The decision in a `LlamaLogger` debug [message], or null when the message +/// is not the prompt cap line. +PromptCapDecision? parsePromptCapDecision(String message) { + final match = _capLine.firstMatch(message); + if (match == null) return null; + final cap = match[1]; + final detail = match[2]!; + return ( + capTokens: cap == null ? null : int.parse(cap), + devices: [ + for (final device in _capDevice.allMatches(detail)) + ( + name: device[1]!, + apiVersion: device[2]!, + loaderApiVersion: device[3]!, + subgroupSize: int.parse(device[4]!), + ), + ], + detail: detail, + ); +} + +/// What is known about the Android Vulkan text prompt cap of one context. +enum PromptCapState { + /// The library logged that it caps the prompt decode. + capped('capped'), + + /// The library logged that it leaves the prompt decode uncapped. + notCapped('not_capped'), + + /// An explicit micro-batch size, which makes the library leave the cap off + /// without logging. + explicitSize('explicit_size'), + + /// A platform other than Android, where there is no cap. + notAndroid('not_android'), + + /// An Android load that asks Vulkan for no GPU layer, which gets no cap. + vulkanNotRequested('vulkan_not_requested'), + + /// An Android load that asks Vulkan for GPU layers while ggml-vulkan + /// registered no device. The library logs nothing and applies the cap all + /// the same, although the context runs on the CPU. + noVulkanDevice('no_vulkan_device'), + + /// A Vulkan device is registered and the cap was to be decided, but no + /// decision reached the log: the record is missing. + notLogged('not_logged'); + + const PromptCapState(this.wireName); + + /// The value the journal carries. + final String wireName; +} + +/// The state of the prompt cap for a context created with [microBatchSize] +/// (0 for the library default), from the library's [logged] decision when it +/// logged one and otherwise from what the load reported. +/// +/// [vulkanRequested] is whether the load prefers Vulkan and kept a positive +/// GPU layer count. [registeredVulkanDevices] is the number of Vulkan devices +/// the runtime lists, or null when it cannot be read. +PromptCapState promptCapState({ + required PromptCapDecision? logged, + required int microBatchSize, + required bool isAndroid, + required bool vulkanRequested, + required int? registeredVulkanDevices, +}) { + if (logged != null) { + return logged.capTokens == null + ? PromptCapState.notCapped + : PromptCapState.capped; + } + if (microBatchSize > 0) return PromptCapState.explicitSize; + if (!isAndroid) return PromptCapState.notAndroid; + if (!vulkanRequested) return PromptCapState.vulkanNotRequested; + if (registeredVulkanDevices == 0) return PromptCapState.noVulkanDevice; + return PromptCapState.notLogged; +} + +/// Whether [content] is one of [codes] and nothing else: surrounding +/// whitespace, letter case and one closing `.` or `!` are ignored. +bool answerIsCode(String content, Iterable codes) { + final answer = content.trim().toLowerCase().replaceFirst( + RegExp(r'[.!]$'), + '', + ); + return codes.any((code) => code.toLowerCase() == answer); +} + +/// The tool call that streamed tool-call [deltas] add up to: the +/// concatenated name and the decoded arguments. `arguments` is null when the +/// argument text is not JSON, and `wellFormed` is false then, when there are +/// no deltas, and when the deltas name more than one call. +({String name, Object? arguments, bool wellFormed}) reconstructToolCall( + List deltas, +) { + final name = StringBuffer(); + final arguments = StringBuffer(); + var wellFormed = deltas.isNotEmpty; + String? id; + for (final delta in deltas.cast>()) { + if (delta['index'] != 0) wellFormed = false; + if (delta['id'] case final String next) { + if (id != null && id != next) wellFormed = false; + id = next; + } + final function = delta['function'] as Map?; + name.write(function?['name'] ?? ''); + arguments.write(function?['arguments'] ?? ''); + } + Object? decoded; + try { + decoded = jsonDecode(arguments.toString()); + } on FormatException { + wellFormed = false; + } + return (name: name.toString(), arguments: decoded, wellFormed: wellFormed); +} + +/// Whether a request that ended with [finishReasons] and the tool [call] is +/// exactly one call of [name] with [arguments]. +bool toolCallMatches({ + required Object? finishReasons, + required ({String name, Object? arguments, bool wellFormed}) call, + required String name, + required Object? arguments, +}) => + jsonEncode(finishReasons) == jsonEncode(['tool_calls']) && + call.wellFormed && + call.name == name && + _canonical(call.arguments) == _canonical(arguments); + +/// JSON text of [value] with the keys of every object in order. +String _canonical(Object? value) => jsonEncode(_sorted(value)); + +Object? _sorted(Object? value) => switch (value) { + final Map map => { + for (final key in map.keys.map((key) => '$key').toList()..sort()) + key: _sorted(map[key]), + }, + final List list => [for (final item in list) _sorted(item)], + _ => value, +}; + +/// How one judged request ended: whether it [passed], and what to print when +/// it did not. +typedef JudgedCase = ({bool passed, String description}); + +/// The verdict of one attempt at the judged size. +/// +/// It passes when the load succeeded ([loadError] is null) and every case in +/// [judgedCases] has a passing entry in [results]. `cases` holds the verdict +/// of each judged case, false for one that never ran. +({bool passed, Map cases, List failures}) judgeAttempt( + Iterable judgedCases, + Map results, { + String? loadError, +}) { + final failures = []; + if (loadError != null) { + failures.add('did not load: $loadError'); + } else { + for (final id in judgedCases) { + final result = results[id]; + if (result == null) { + failures.add('$id did not run'); + } else if (!result.passed) { + failures.add('$id ${result.description}'); + } + } + } + return ( + passed: failures.isEmpty, + cases: {for (final id in judgedCases) id: results[id]?.passed ?? false}, + failures: failures, + ); +} + +/// The attempts of a sweep over [arms] and [repeats], in running order: every +/// repeat of the [judgedArm] first, so that nothing a control arm does to the +/// process can cost a judged repeat, then the control arms repeat by repeat. +List<({int repeat, int arm})> sweepOrder( + List arms, + int repeats, { + required int judgedArm, +}) => [ + for (var repeat = 1; repeat <= repeats; repeat++) + (repeat: repeat, arm: judgedArm), + for (var repeat = 1; repeat <= repeats; repeat++) + for (final arm in arms) + if (arm != judgedArm) (repeat: repeat, arm: arm), +]; diff --git a/example/chat_app/test/micro_batch_sweep_support_test.dart b/example/chat_app/test/micro_batch_sweep_support_test.dart new file mode 100644 index 000000000..e065b54b8 --- /dev/null +++ b/example/chat_app/test/micro_batch_sweep_support_test.dart @@ -0,0 +1,366 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; + +import '../integration_test/support/micro_batch_sweep_support.dart'; + +void main() { + group('parsePromptCapDecision', () { + test('reads a capped decision and the device as llamadart formats it', () { + const device = VulkanDeviceFacts( + name: 'Mali-G715', + deviceType: 1, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 3 << 12 | 283, + subgroupSize: 16, + ); + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call ($device)', + )!; + + expect(decision.capTokens, 8); + expect(decision.devices, [ + ( + name: 'Mali-G715', + apiVersion: '1.3', + loaderApiVersion: '1.3', + subgroupSize: 16, + ), + ]); + }); + + test('reads a lifted cap and every device', () { + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is not capped ' + '("Adreno (TM) 750" (API 1.3, loader 1.4, subgroup size 64), ' + '"llvmpipe (LLVM 19.1, 256 bits)" (API 1.4, loader 1.4, subgroup ' + 'size 8))', + )!; + + expect(decision.capTokens, isNull); + expect( + [for (final device in decision.devices) device.name], + ['Adreno (TM) 750', 'llvmpipe (LLVM 19.1, 256 bits)'], + ); + expect( + [for (final device in decision.devices) device.subgroupSize], + [64, 8], + ); + expect(decision.devices.first.loaderApiVersion, '1.4'); + }); + + test('keeps the reason of a probe that listed no device', () { + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call (llama_dart_vulkan_get_device_count returned ' + 'LLAMA_DART_VULKAN_STATUS_NO_LOADER)', + )!; + + expect(decision.capTokens, 8); + expect(decision.devices, isEmpty); + expect( + decision.detail, + 'llama_dart_vulkan_get_device_count returned ' + 'LLAMA_DART_VULKAN_STATUS_NO_LOADER', + ); + }); + + test('reads a device whose name holds a quote', () { + const devices = [ + VulkanDeviceFacts( + name: 'Weird "GPU" 9000', + deviceType: 2, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 1 << 12, + subgroupSize: 4, + ), + VulkanDeviceFacts( + name: 'Mali-G715', + deviceType: 1, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 3 << 12, + subgroupSize: 16, + ), + ]; + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call (${devices.join(', ')})', + )!; + + expect( + [for (final device in decision.devices) device.name], + ['Weird "GPU" 9000', 'Mali-G715'], + ); + expect(decision.devices.first.apiVersion, '1.1'); + expect(decision.devices.first.subgroupSize, 4); + expect(decision.devices.last.subgroupSize, 16); + }); + + test('ignores other records', () { + expect( + parsePromptCapDecision( + 'llama_cpp_service: promoting flash_attn=enabled for non-F16 KV', + ), + isNull, + ); + }); + }); + + group('reconstructToolCall', () { + test('joins the name and the argument pieces of one call', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'id': 'call_1', + 'function': {'name': 'get_weather', 'arguments': '{"city":'}, + }, + { + 'index': 0, + 'function': {'arguments': '"Montréal"}'}, + }, + ]); + + expect(call.name, 'get_weather'); + expect(call.arguments, {'city': 'Montréal'}); + expect(call.wellFormed, isTrue); + }); + + test('is not well formed without deltas', () { + expect(reconstructToolCall(const []).wellFormed, isFalse); + }); + + test('is not well formed when the arguments are not JSON', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'function': {'name': 'get_weather', 'arguments': '8888'}, + }, + { + 'index': 0, + 'function': {'arguments': '{'}, + }, + ]); + + expect(call.name, 'get_weather'); + expect(call.arguments, isNull); + expect(call.wellFormed, isFalse); + }); + + test('is not well formed when the deltas name two calls', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'id': 'call_1', + 'function': {'name': 'get_weather', 'arguments': '{}'}, + }, + { + 'index': 1, + 'id': 'call_2', + 'function': {'name': 'get_weather', 'arguments': ''}, + }, + ]); + + expect(call.wellFormed, isFalse); + }); + }); + + group('promptCapState', () { + const capped = ( + capTokens: 8, + devices: [], + detail: 'probe unavailable', + ); + const lifted = ( + capTokens: null, + devices: [], + detail: '"Adreno" (API 1.3, loader 1.3, subgroup size 64)', + ); + PromptCapState state({ + PromptCapDecision? logged, + int microBatchSize = 0, + bool isAndroid = true, + bool vulkanRequested = true, + int? registeredVulkanDevices = 1, + }) => promptCapState( + logged: logged, + microBatchSize: microBatchSize, + isAndroid: isAndroid, + vulkanRequested: vulkanRequested, + registeredVulkanDevices: registeredVulkanDevices, + ); + + test('takes a logged decision over everything else', () { + expect(state(logged: capped), PromptCapState.capped); + expect(state(logged: lifted), PromptCapState.notCapped); + expect( + state(logged: capped, registeredVulkanDevices: 0), + PromptCapState.capped, + ); + }); + + test('names why the library logged nothing', () { + expect(state(microBatchSize: 512), PromptCapState.explicitSize); + expect(state(isAndroid: false), PromptCapState.notAndroid); + expect(state(vulkanRequested: false), PromptCapState.vulkanNotRequested); + }); + + test('tells a silent cap without a Vulkan device from a missing ' + 'record', () { + expect(state(registeredVulkanDevices: 0), PromptCapState.noVulkanDevice); + expect(state(registeredVulkanDevices: 1), PromptCapState.notLogged); + expect(state(registeredVulkanDevices: null), PromptCapState.notLogged); + }); + + test('an explicit size is not a silent cap even without a device', () { + expect( + state(microBatchSize: 512, registeredVulkanDevices: 0), + PromptCapState.explicitSize, + ); + }); + }); + + group('answerIsCode', () { + test('accepts the code alone, whatever its case and closing mark', () { + expect(answerIsCode('Cedar17', ['cedar17']), isTrue); + expect(answerIsCode(' cedar17.\n', ['cedar17']), isTrue); + expect(answerIsCode('42', ['42', 'maple42']), isTrue); + expect(answerIsCode('maple42!', ['42', 'maple42']), isTrue); + }); + + test('rejects an answer that only holds the code', () { + expect(answerIsCode('8888888842888', ['42', 'maple42']), isFalse); + expect(answerIsCode('1 2 3 42 5', ['42', 'maple42']), isFalse); + expect(answerIsCode('The code is cedar17', ['cedar17']), isFalse); + expect(answerIsCode('', ['cedar17']), isFalse); + }); + }); + + group('toolCallMatches', () { + const call = ( + name: 'get_weather', + arguments: {'city': 'Montréal'}, + wellFormed: true, + ); + bool matches({ + Object? finishReasons = const ['tool_calls'], + ({String name, Object? arguments, bool wellFormed}) call = call, + }) => toolCallMatches( + finishReasons: finishReasons, + call: call, + name: 'get_weather', + arguments: const {'city': 'Montréal'}, + ); + + test('accepts the one expected call', () { + expect(matches(), isTrue); + }); + + test('rejects another finish, name, argument or a malformed call', () { + expect(matches(finishReasons: const ['stop']), isFalse); + expect(matches(finishReasons: const ['length']), isFalse); + expect( + matches( + call: (name: 'get_time', arguments: call.arguments, wellFormed: true), + ), + isFalse, + ); + expect( + matches( + call: ( + name: 'get_weather', + arguments: const {'city': 'Toronto'}, + wellFormed: true, + ), + ), + isFalse, + ); + expect( + matches( + call: ( + name: 'get_weather', + arguments: call.arguments, + wellFormed: false, + ), + ), + isFalse, + ); + }); + }); + + group('judgeAttempt', () { + const cases = ['C06.history', 'X01.long_history', 'C07.tools.auto']; + const pass = (passed: true, description: 'ok'); + + test('passes when every judged case passed', () { + final verdict = judgeAttempt(cases, { + for (final id in cases) id: pass, + 'C04.hello': (passed: false, description: 'not judged'), + }); + + expect(verdict.passed, isTrue); + expect(verdict.failures, isEmpty); + expect(verdict.cases, {for (final id in cases) id: true}); + }); + + test('fails on a wrong answer and says what it was', () { + final verdict = judgeAttempt(cases, { + 'C06.history': pass, + 'X01.long_history': (passed: false, description: 'answered "8888"'), + 'C07.tools.auto': pass, + }); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['X01.long_history answered "8888"']); + expect(verdict.cases['X01.long_history'], isFalse); + expect(verdict.cases['C06.history'], isTrue); + }); + + test('fails on a judged case that never ran', () { + final verdict = judgeAttempt(cases, { + 'C06.history': pass, + 'X01.long_history': pass, + }); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['C07.tools.auto did not run']); + expect(verdict.cases['C07.tools.auto'], isFalse); + }); + + test('fails on a load error without listing the cases', () { + final verdict = judgeAttempt( + cases, + const {}, + loadError: 'LlamaModelException: no', + ); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['did not load: LlamaModelException: no']); + expect(verdict.cases.values, everyElement(isFalse)); + }); + }); + + group('sweepOrder', () { + test('runs every judged repeat before any control', () { + expect(sweepOrder([0, 512], 3, judgedArm: 0), [ + (repeat: 1, arm: 0), + (repeat: 2, arm: 0), + (repeat: 3, arm: 0), + (repeat: 1, arm: 512), + (repeat: 2, arm: 512), + (repeat: 3, arm: 512), + ]); + }); + + test('keeps the controls repeat by repeat, wherever the judged size is ' + 'listed', () { + expect(sweepOrder([512, 0, 1], 2, judgedArm: 0), [ + (repeat: 1, arm: 0), + (repeat: 2, arm: 0), + (repeat: 1, arm: 512), + (repeat: 1, arm: 1), + (repeat: 2, arm: 512), + (repeat: 2, arm: 1), + ]); + }); + }); +} diff --git a/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart b/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart new file mode 100644 index 000000000..09136ab8b --- /dev/null +++ b/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart @@ -0,0 +1,156 @@ +@TestOn('vm') +library; + +import 'dart:mirrors'; + +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/backends/llama_cpp/load_device_selection.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; +import 'package:llamadart/src/core/llama_logger.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; +import 'package:test/test.dart'; + +import '../../../../example/chat_app/integration_test/support/micro_batch_sweep_support.dart'; + +const _vulkan13 = 1 << 22 | 3 << 12; + +VulkanDeviceFacts _facts(String name, int subgroupSize) => VulkanDeviceFacts( + name: name, + deviceType: 1, + instanceApiVersion: _vulkan13, + apiVersion: _vulkan13 | 283, + subgroupSize: subgroupSize, +); + +/// The debug records and the result of the service's own cap decision for +/// an Android runtime that registered [registered] Vulkan devices and whose +/// probe answers [probe]. Nothing native is loaded: the registry and the +/// probe are the injected ones. +({bool defect, List debug}) _decide( + VulkanDeviceProbe probe, { + int registered = 1, +}) { + final service = LlamaCppService( + isAndroid: true, + vulkanDeviceProbe: () => probe, + registeredDevices: () => [ + for (var index = 0; index < registered; index++) + GgmlDeviceEntry(name: 'Vulkan$index', type: 1, registry: 'Vulkan'), + ], + ); + final logger = LlamaLogger.instance; + final level = logger.level; + final debug = []; + logger + ..setLevel(LlamaLogLevel.debug) + ..setHandler((record) { + if (record.level == LlamaLogLevel.debug) debug.add(record.message); + }); + try { + final owner = reflectClass(LlamaCppService).owner as LibraryMirror; + final defect = + reflect(service) + .invoke( + MirrorSystem.getSymbol( + '_androidVulkanHasSmallMatmulTileDefect', + owner, + ), + const [], + ) + .reflectee + as bool; + return (defect: defect, debug: debug); + } finally { + logger + ..setHandler(null) + ..setLevel(level); + } +} + +/// The micro-batch sweep E2E of the chat app reads the cap decision out of +/// the line the service logs. These tests take that line from the service +/// itself, so rewording it there fails here instead of turning the E2E's +/// record into `not_logged`. +void main() { + test('the sweep E2E reads the line the service logs for a capped ' + 'device', () { + final decided = _decide( + VulkanDeviceProbe.devices([_facts('Mali-G715', 16)]), + ); + + expect(decided.defect, isTrue); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect( + decision.capTokens, + LlamaCppService.androidVulkanPromptMicroBatchSize, + ); + expect(decision.devices, [ + ( + name: 'Mali-G715', + apiVersion: '1.3', + loaderApiVersion: '1.3', + subgroupSize: 16, + ), + ]); + }); + + test('the sweep E2E reads the line the service logs when it lifts the ' + 'cap', () { + final decided = _decide( + VulkanDeviceProbe.devices([ + _facts('Adreno (TM) 750', 64), + _facts('Odd "GPU"', 8), + ]), + registered: 2, + ); + + expect(decided.defect, isFalse); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect(decision.capTokens, isNull); + expect( + [for (final device in decision.devices) device.name], + ['Adreno (TM) 750', 'Odd "GPU"'], + ); + expect( + [for (final device in decision.devices) device.subgroupSize], + [64, 8], + ); + }); + + test('the sweep E2E reads the line the service logs when the probe is ' + 'unavailable', () { + final decided = _decide( + const VulkanDeviceProbe.unavailable('no Vulkan loader'), + ); + + expect(decided.defect, isTrue); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect( + decision.capTokens, + LlamaCppService.androidVulkanPromptMicroBatchSize, + ); + expect(decision.devices, isEmpty); + expect(decision.detail, 'no Vulkan loader'); + }); + + test('the service logs nothing and caps when no Vulkan device is ' + 'registered, which the sweep E2E records as no_vulkan_device', () { + final decided = _decide( + VulkanDeviceProbe.devices([_facts('Mali-G715', 16)]), + registered: 0, + ); + + expect(decided.defect, isTrue); + expect(decided.debug, isEmpty); + expect( + promptCapState( + logged: null, + microBatchSize: 0, + isAndroid: true, + vulkanRequested: true, + registeredVulkanDevices: 0, + ), + PromptCapState.noVulkanDevice, + ); + }); +} diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 8d9e7631e..54c745cab 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -233,6 +233,31 @@ void main() { expect(result.stdout, isNot(contains('LITERT_RELOAD_MODEL'))); }); + test('dry-runs the micro-batch sweep device scenario', () async { + final result = await runLocalE2e(const [ + '--scenario', + 'chat-app-micro-batch-sweep', + '--device', + 'android', + '--model-path', + '/data/local/tmp/Qwen3.5-0.8B-Q4_0.gguf', + '--dry-run', + ], projectRoot: '/repo'); + + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + 'cd /repo/example/chat_app && flutter test --run-skipped ' + '-t local-only ' + 'integration_test/micro_batch_sweep_e2e_test.dart ' + '-d android ' + '--dart-define=MICRO_BATCH_SWEEP_MODEL=' + '/data/local/tmp/Qwen3.5-0.8B-Q4_0.gguf', + ), + ); + }); + test('dry-runs Web Qwen3-ASR file and microphone transcription', () async { final result = await runLocalE2e(const [ '--scenario', diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index e6963f916..3d79be7c5 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -1031,6 +1031,33 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'chat-app-micro-batch-sweep', + group: LocalE2eScenarioGroup.flutterDevice, + description: + 'Answer history and tool prompts at the default and at explicit ' + 'micro-batch sizes in one process, and record the Android Vulkan ' + 'prompt cap decision with the Vulkan device facts.', + requiresDevice: true, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: context.chatAppDir, + executable: 'flutter', + arguments: [ + 'test', + '--run-skipped', + '-t', + 'local-only', + 'integration_test/micro_batch_sweep_e2e_test.dart', + '-d', + context.device, + if (context.modelPath != null) + '--dart-define=MICRO_BATCH_SWEEP_MODEL=${context.modelPath}', + ], + description: 'Flutter chat app micro-batch sweep E2E', + ), + ], + ), LocalE2eScenario( name: 'chat-app-macos-quit', group: LocalE2eScenarioGroup.flutterDevice, diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 6b9582225..67c0752ac 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -772,6 +772,28 @@ const List testMatrixRows = [ 'copy on the target device. Graphics memory needs the Test Lab ' 'arguments in example/chat_app/README.md.', ), + TestMatrixRow( + id: 'chat-app-micro-batch-sweep', + tier: 'targeted', + mode: 'local-only', + covers: + 'llama.cpp history, long-history and grammar-constrained tool ' + 'prompts at the default micro-batch and at explicit sizes in one ' + 'process on a device, with a flushed verdict per attempt, the ' + 'Android Vulkan prompt cap state (capped, not capped, or capped ' + 'without a Vulkan device), the Vulkan device name, API version and ' + 'subgroup size, and a typed load refusal recorded; the default size ' + 'must answer correctly, explicit sizes are controls', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'chat-app-micro-batch-sweep --device ', + useWhen: + 'llama.cpp native pin, Android Vulkan prompt cap, Vulkan device ' + 'facts or the Vulkan 1.2 load refusal changes. Downloads the locked ' + 'chat-gguf-vulkan model unless --model-path names a copy on the ' + 'target device. Only an Android Vulkan device exercises the cap; ' + 'the Test Lab arguments are in example/chat_app/README.md.', + ), TestMatrixRow( id: 'chat-app-macos-quit', tier: 'targeted', From 3cc796055357821359fd98841681887e6d403636 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 13:18:07 -0400 Subject: [PATCH 6/7] fix: put each media part's marker where the part is in its message, as llama-server does (#986) --- CHANGELOG.md | 20 + doc/litert_lm_templates.md | 6 +- doc/webgpu_bridge.md | 11 + lib/backend.dart | 1 + lib/src/backends/backend.dart | 28 + .../backends/llama_cpp/llama_cpp_backend.dart | 27 + .../backends/llama_cpp/llama_cpp_service.dart | 68 +- lib/src/backends/llama_cpp/worker.dart | 27 +- .../backends/llama_cpp/worker_messages.dart | 5 + lib/src/backends/native/native_backend.dart | 28 + lib/src/backends/web/web_backend.dart | 28 + lib/src/backends/webgpu/webgpu_backend.dart | 22 + .../core/engine/chat_template_renderer.dart | 32 +- lib/src/core/engine/engine.dart | 89 +- .../core/template/chat_template_engine.dart | 17 +- .../core/template/chat_template_handler.dart | 23 +- .../handlers/function_gemma_handler.dart | 10 +- .../template/handlers/gemma4_handler.dart | 7 + .../core/template/jinja/jinja_analyzer.dart | 11 +- lib/src/core/template/media_placeholders.dart | 88 +- .../template/template_render_context.dart | 31 +- .../media_marker_render_upstream.json | 1483 +++++++++++++++++ test/fixtures/media_marker_render_upstream.md | 64 + test/fixtures/media_templates/GLM-OCR.jinja | 140 ++ .../media_templates/LFM2-VL-450M.jinja | 4 + .../media_templates/Qwen2_5-Omni-3B.jinja | 7 + ...e_multimodal_browser_integration_test.dart | 66 + test/support/fake_mtmd.dart | 26 +- .../llama_cpp/llama_cpp_backend_test.dart | 29 + .../llama_cpp_service_media_prompt_test.dart | 242 +++ test/unit/backends/llama_cpp/worker_test.dart | 76 + .../backends/native/native_backend_test.dart | 87 + test/unit/backends/web/web_backend_test.dart | 88 + test/unit/core/engine/engine_test.dart | 168 ++ .../core/template/audio_transport_test.dart | 8 +- .../template/chat_template_engine_test.dart | 105 +- .../handlers/function_gemma_handler_test.dart | 25 + .../handlers/gemma4_handler_test.dart | 6 +- .../media_marker_render_parity_test.dart | 103 ++ .../template/media_placeholders_test.dart | 128 +- .../template_render_context_test.dart | 72 +- test/unit/public_entrypoints_test.dart | 1 + website/docs/changelog/recent-releases.md | 20 + .../docs/guides/template-engine-internals.md | 22 +- 44 files changed, 3446 insertions(+), 103 deletions(-) create mode 100644 test/fixtures/media_marker_render_upstream.json create mode 100644 test/fixtures/media_marker_render_upstream.md create mode 100644 test/fixtures/media_templates/GLM-OCR.jinja create mode 100644 test/fixtures/media_templates/LFM2-VL-450M.jinja create mode 100644 test/fixtures/media_templates/Qwen2_5-Omni-3B.jinja create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_media_prompt_test.dart create mode 100644 test/unit/core/template/media_marker_render_parity_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index d10f66bbf..93487976c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -120,6 +120,26 @@ not recognised as one and bundles it. Leaving the key unset, or setting `both`, still bundles only `llama_cpp` and `litert_lm` ([#856](https://github.com/leehack/llamadart/issues/856)). +- **Behavior change:** an image or audio part of a chat request to a GGUF + model takes the place it has in its message, as llama.cpp's `llama-server` + renders it ([#964](https://github.com/leehack/llamadart/issues/964)). For + Qwen3.5 and Qwen2.5-Omni it was attached before the whole prompt, and for + GLM-OCR it was wrapped in the image start and end tokens twice, so prompts + for media turns of these models change. A chat template no longer writes + its own text for a media part: Qwen's `Picture N: ` under `add_vision_id`, + the Kimi-K2 wrapper, Reka's run of image tokens and Cohere's + `<|IMG_PATCH|>` are gone, as on `llama-server`. A placeholder string that + a chat message quotes (``, ``, `[IMG]`, `<__media__>`) is text + instead of a part. Where the runtime would still read such a string as a + part, it reaches the model with a zero-width space (U+200B) after its + first character, which the model may repeat in its answer: a quoted + `<__media__>` in `create` on native; every placeholder the bridge + rewrites in `create` on Web; and every placeholder `generate` reads in the + prompt `chatTemplate` returns for messages with media and in `create` on + a custom backend without `BackendChatPromptGeneration`, which + `package:llamadart/backend.dart` now exports. A prompt written for + `generate` keeps its placeholders, and `chatTemplate` output for messages + without media is unchanged. ## 0.11.1 diff --git a/doc/litert_lm_templates.md b/doc/litert_lm_templates.md index 66e4d7a75..a5961628a 100644 --- a/doc/litert_lm_templates.md +++ b/doc/litert_lm_templates.md @@ -209,9 +209,9 @@ Templates are committed as jinja under `tool/litert_lm_templates/` and embedded into `lib/src/backends/litert_lm/litert_lm_chat_templates.dart` by a generator. Start from the canonical template llama.cpp uses. Keep any runtime content-shape adapter in this source and cover it with prompt-parity tests. -An adapter that reads content part lists either renders image and audio parts -or rejects both: the Dart renderer gives a template that reads part lists -media as typed parts unless it rejects both kinds. Pin the result in +The Dart renderer gives an adapter the media marker in the message text and +never an image or audio part. It still reports an adapter that reads content +part lists but rejects both kinds as reading strings only. Pin the result in `test/unit/core/template/template_caps_cache_fixtures_test.dart`. 1. Copy the canonical jinja into `tool/litert_lm_templates/.jinja` diff --git a/doc/webgpu_bridge.md b/doc/webgpu_bridge.md index 70960841f..f49378657 100644 --- a/doc/webgpu_bridge.md +++ b/doc/webgpu_bridge.md @@ -342,6 +342,17 @@ gates against real assets and models; its header lists the setup. exported from `package:llamadart`. - Large model URL loads can use a worker-thread fetch-backed path to reduce contiguous `ArrayBuffer` pressure, but only after an explicit opt-in. +- With media parts the bridge reads its marker `<__media__>` and the + placeholders it rewrites to it (``, `[IMG]`, `<|image|>`, ``, + `<|img|>`, `<|vision_start|><|image_pad|><|vision_end|>` and its + `video_pad` form, `