From 6eff4a19424797e55f025e38e393f5ebf4a3fe55 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 18:00:41 -0400 Subject: [PATCH 1/2] fix: wait for the backend in untracked llama.cpp decode and encode Without the llamadart exit-teardown exports the service calls llama_decode directly. On an asynchronous backend such as Metal it returns before the GPU finishes, so the wait landed in the next sample and getPerformanceContext() reported decode about 10x too fast. The untracked decode and encode now synchronize before returning, as llama_dart_decode already does. Closes #671 --- CHANGELOG.md | 8 ++ .../backends/llama_cpp/exit_teardown_api.dart | 35 ++++++-- .../llama_cpp/exit_teardown_api_test.dart | 25 ++++++ .../llama_cpp_service_decode_timing_test.dart | 86 +++++++++++++++++++ website/docs/changelog/recent-releases.md | 8 ++ 5 files changed, 156 insertions(+), 6 deletions(-) create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index e09024cbf..fa8767108 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## Unreleased + +- Fix `getPerformanceContext()` decode and prompt-eval times on a native + runtime without the llamadart exit-teardown exports (`v0.5.0` or older), + where an asynchronous GPU backend such as Metal counted its work as sampling + time and decode speed read about 10x too high + ([#671](https://github.com/leehack/llamadart/issues/671)). + ## 0.13.0 - Pair this release with Apple companions `llamadart_llama_cpp_flutter`, diff --git a/lib/src/backends/llama_cpp/exit_teardown_api.dart b/lib/src/backends/llama_cpp/exit_teardown_api.dart index de2bf5452..4c899957d 100644 --- a/lib/src/backends/llama_cpp/exit_teardown_api.dart +++ b/lib/src/backends/llama_cpp/exit_teardown_api.dart @@ -749,7 +749,22 @@ final class LlamaCppObjectCalls { } /// The upstream llama.cpp functions; nothing is tracked. - static final LlamaCppObjectCalls upstream = LlamaCppObjectCalls._( + static final LlamaCppObjectCalls upstream = LlamaCppObjectCalls.untracked(); + + /// Calls llama.cpp directly, as [upstream] does; tests replace its + /// [decode], [encode] and [synchronize]. + /// + /// An asynchronous backend such as Metal may still be computing when + /// [decode] or [encode] returns. The calls made through these wait for it + /// with [synchronize] before they return, as the tracked calls do, so the + /// duration of an evaluation includes the backend's work. + factory LlamaCppObjectCalls.untracked({ + int Function(Pointer ctx, llama_batch batch) decode = + llama_decode, + int Function(Pointer ctx, llama_batch batch) encode = + llama_encode, + void Function(Pointer ctx) synchronize = llama_synchronize, + }) => LlamaCppObjectCalls._( exit: null, failures: NativeCallFailures(null, isWindows: false), loadModel: llama_model_load_from_file, @@ -764,9 +779,17 @@ final class LlamaCppObjectCalls { Native.addressOf)>>( llama_free, ).cast(), - decode: llama_decode, - encode: llama_encode, - synchronize: llama_synchronize, + decode: (ctx, batch) { + final status = decode(ctx, batch); + synchronize(ctx); + return status; + }, + encode: (ctx, batch) { + final status = encode(ctx, batch); + synchronize(ctx); + return status; + }, + synchronize: synchronize, samplerSample: llama_sampler_sample, samplerAccept: llama_sampler_accept, samplerInitGrammarLazyPatterns: llama_sampler_init_grammar_lazy_patterns, @@ -841,10 +864,10 @@ final class LlamaCppObjectCalls { /// The function `IsolateShutdownReleases` frees a context with. final Pointer contextFreeAddress; - /// `llama_decode`. + /// `llama_decode`, returning once the backend has finished the batch. final int Function(Pointer ctx, llama_batch batch) decode; - /// `llama_encode`. + /// `llama_encode`, returning once the backend has finished the batch. final int Function(Pointer ctx, llama_batch batch) encode; /// `llama_synchronize`. diff --git a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart index d082731ad..84af8ef08 100644 --- a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart +++ b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart @@ -718,6 +718,31 @@ void main() { llama_model_free(model); }); + test('untracked decode and encode return once the backend has finished', () { + final context = Pointer.fromAddress(0x10); + final batch = calloc(); + addTearDown(() => calloc.free(batch)); + final called = []; + final calls = LlamaCppObjectCalls.untracked( + decode: (ctx, batch) { + called.add('decode'); + return 1; + }, + encode: (ctx, batch) { + called.add('encode'); + return 2; + }, + synchronize: (ctx) { + expect(ctx, context); + called.add('synchronize'); + }, + ); + + expect(calls.decode(context, batch.ref), 1); + expect(calls.encode(context, batch.ref), 2); + expect(called, ['decode', 'synchronize', 'encode', 'synchronize']); + }); + test('upstream calls create objects the runtime does not track', () { final calls = LlamaCppObjectCalls.upstream; expect(calls.exit, isNull); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart new file mode 100644 index 000000000..703b8f352 --- /dev/null +++ b/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart @@ -0,0 +1,86 @@ +@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/models/inference/generation_params.dart'; +import 'package:llamadart/src/core/models/inference/model_params.dart'; +import 'package:test/test.dart'; + +import '../../../support/synthetic_embedding_gguf.dart'; + +const _params = ModelParams(gpuLayers: 0, contextSize: 64); +const _greedy = GenerationParams(maxTokens: 8, temp: 0, topK: 1, seed: 1); + +// The time the fake backend keeps computing after each llama_decode returns. +const _backendMicros = 5000; + +// Runs the real llama.cpp runtime on the CPU behind a decode that returns +// before its backend has finished, as Metal's does: the backend stays busy +// for _backendMicros after each llama_decode, until a synchronize waits for +// it. +void main() { + late Directory dir; + late LlamaCppService service; + late int context; + late List calls; + + setUp(() { + dir = Directory.systemTemp.createTempSync('llamadart_decode_timing_'); + writeSyntheticLlamaGguf('${dir.path}/model.gguf'); + calls = []; + final clock = Stopwatch()..start(); + var busyUntil = 0; + service = LlamaCppService( + objectCalls: LlamaCppObjectCalls.untracked( + decode: (ctx, batch) { + calls.add('decode'); + final status = llama_decode(ctx, batch); + busyUntil = clock.elapsedMicroseconds + _backendMicros; + return status; + }, + synchronize: (ctx) { + calls.add('synchronize'); + final remaining = busyUntil - clock.elapsedMicroseconds; + if (remaining > 0) sleep(Duration(microseconds: remaining)); + llama_synchronize(ctx); + }, + ), + )..initializeBackend(); + final model = service.loadModel('${dir.path}/model.gguf', _params); + context = service.createContext(model, _params); + }); + + tearDown(() { + service.dispose(); + dir.deleteSync(recursive: true); + }); + + test('getPerformanceContext counts the backend work of a decode as ' + 'decode time', () async { + final cancel = calloc(); + addTearDown(() => calloc.free(cancel)); + + await service + .generate(context, 'ab', _greedy, cancel.address) + .drain(); + final perf = service.getPerformanceContext(context); + + expect(perf.evalTokens, greaterThan(0)); + expect( + perf.decodeMs, + greaterThanOrEqualTo(perf.evalTokens * _backendMicros / 1000), + ); + expect(perf.promptEvalMs, greaterThanOrEqualTo(_backendMicros / 1000)); + // Every decode waits for its backend before the next call. + expect( + calls.join(' '), + matches(RegExp(r'^synchronize( decode synchronize)+$')), + ); + }); +} diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 978bdf0b3..c48c13a5e 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,14 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- Fix `getPerformanceContext()` decode and prompt-eval times on a native + runtime without the llamadart exit-teardown exports (`v0.5.0` or older), + where an asynchronous GPU backend such as Metal counted its work as sampling + time and decode speed read about 10x too high + ([#671](https://github.com/leehack/llamadart/issues/671)). + ## 0.13.0 - Pair this release with Apple companions `llamadart_llama_cpp_flutter`, From c62eb5a0d125964eae7f3c811fe80b833ea24a9c Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 15 Oct 2026 18:25:55 -0400 Subject: [PATCH 2/2] test: cover the upstream object calls and untracked media prompt timing Wait for an untracked media prompt evaluation before the prompt timing stops, since upstream libmtmd returns before an asynchronous backend has finished. Test the production upstream calls directly, and busy-wait the fake backend so its 5 ms bound does not depend on sleep rounding. --- .../backends/llama_cpp/llama_cpp_service.dart | 4 ++ .../llama_cpp/exit_teardown_api_test.dart | 28 ++++++++ .../llama_cpp_service_decode_timing_test.dart | 71 +++++++++++++------ 3 files changed, 83 insertions(+), 20 deletions(-) diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index c59b8e167..b9c439783 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -5966,6 +5966,10 @@ class LlamaCppService { } } if (evalResult == 0) { + // The tracked mtmd evaluations wait for the backend, as the + // object calls' decode does; upstream libmtmd returns before an + // asynchronous one has finished. + if (exitTeardown == null) _calls.synchronize(ctx.pointer); initialTokens = newPast.value; } else { throw Exception( diff --git a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart index 84af8ef08..54a836662 100644 --- a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart +++ b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart @@ -743,6 +743,34 @@ void main() { expect(called, ['decode', 'synchronize', 'encode', 'synchronize']); }); + test('upstream decode returns once llama.cpp has finished the batch', () { + final calls = LlamaCppObjectCalls.upstream; + final model = load(calls); + final context = calls.createContext( + model, + llama_context_default_params()..n_ctx = 64, + ); + final batch = llama_batch_init(2, 0, 1); + try { + batch.n_tokens = 2; + for (var i = 0; i < 2; i++) { + batch.token[i] = 1 + i; + batch.pos[i] = i; + batch.n_seq_id[i] = 1; + batch.seq_id[i][0] = 0; + batch.logits[i] = i; + } + + expect(calls.decode(context, batch), 0); + // llama.cpp counts queued prompt tokens when it synchronizes. + expect(llama_perf_context(context).n_p_eval, 2); + } finally { + llama_batch_free(batch); + calls.freeContext(context); + calls.freeModel(model); + } + }); + test('upstream calls create objects the runtime does not track', () { final calls = LlamaCppObjectCalls.upstream; expect(calls.exit, isNull); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart index 703b8f352..db3781606 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart @@ -8,10 +8,12 @@ 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/models/chat/content_part.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 _params = ModelParams(gpuLayers: 0, contextSize: 64); @@ -19,6 +21,7 @@ const _greedy = GenerationParams(maxTokens: 8, temp: 0, topK: 1, seed: 1); // The time the fake backend keeps computing after each llama_decode returns. const _backendMicros = 5000; +const _backendMs = _backendMicros / 1000; // Runs the real llama.cpp runtime on the CPU behind a decode that returns // before its backend has finished, as Metal's does: the backend stays busy @@ -27,8 +30,10 @@ const _backendMicros = 5000; void main() { late Directory dir; late LlamaCppService service; + late int model; late int context; late List calls; + late int Function(Pointer ctx, llama_batch batch) decode; setUp(() { dir = Directory.systemTemp.createTempSync('llamadart_decode_timing_'); @@ -36,23 +41,23 @@ void main() { calls = []; final clock = Stopwatch()..start(); var busyUntil = 0; + decode = (ctx, batch) { + calls.add('decode'); + final status = llama_decode(ctx, batch); + busyUntil = clock.elapsedMicroseconds + _backendMicros; + return status; + }; service = LlamaCppService( objectCalls: LlamaCppObjectCalls.untracked( - decode: (ctx, batch) { - calls.add('decode'); - final status = llama_decode(ctx, batch); - busyUntil = clock.elapsedMicroseconds + _backendMicros; - return status; - }, + decode: decode, synchronize: (ctx) { calls.add('synchronize'); - final remaining = busyUntil - clock.elapsedMicroseconds; - if (remaining > 0) sleep(Duration(microseconds: remaining)); + while (clock.elapsedMicroseconds < busyUntil) {} llama_synchronize(ctx); }, ), )..initializeBackend(); - final model = service.loadModel('${dir.path}/model.gguf', _params); + model = service.loadModel('${dir.path}/model.gguf', _params); context = service.createContext(model, _params); }); @@ -61,26 +66,52 @@ void main() { dir.deleteSync(recursive: true); }); - test('getPerformanceContext counts the backend work of a decode as ' - 'decode time', () async { + Future generate(String prompt, {List? parts}) async { final cancel = calloc(); - addTearDown(() => calloc.free(cancel)); + try { + await service + .generate(context, prompt, _greedy, cancel.address, parts: parts) + .drain(); + } finally { + calloc.free(cancel); + } + } - await service - .generate(context, 'ab', _greedy, cancel.address) - .drain(); + test('getPerformanceContext counts the backend work of a decode as ' + 'decode time', () async { + await generate('ab'); final perf = service.getPerformanceContext(context); expect(perf.evalTokens, greaterThan(0)); - expect( - perf.decodeMs, - greaterThanOrEqualTo(perf.evalTokens * _backendMicros / 1000), - ); - expect(perf.promptEvalMs, greaterThanOrEqualTo(_backendMicros / 1000)); + expect(perf.decodeMs, greaterThanOrEqualTo(perf.evalTokens * _backendMs)); + expect(perf.promptEvalMs, greaterThanOrEqualTo(_backendMs)); // Every decode waits for its backend before the next call. expect( calls.join(' '), matches(RegExp(r'^synchronize( decode synchronize)+$')), ); }); + + for (final chunkEval in [false, true]) { + test('getPerformanceContext counts the backend work of a media prompt ' + 'as prompt time (chunk-level eval: $chunkEval)', () async { + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + // libmtmd decodes the prompt with llama_decode itself. + final fake = FakeMtmd.install( + service, + tokens: service.tokenize(model, 'ab', true), + chunkEval: chunkEval, + decode: decode, + ); + addTearDown(fake.dispose); + service.createMultimodalContext(model, projectorPath); + + await generate('<__media__>', parts: fake.parts); + final perf = service.getPerformanceContext(context); + + expect(fake.evaluations, 1); + expect(perf.promptEvalMs, greaterThanOrEqualTo(_backendMs)); + }); + } }