Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`,
Expand Down
35 changes: 29 additions & 6 deletions lib/src/backends/llama_cpp/exit_teardown_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<llama_context> ctx, llama_batch batch) decode =
llama_decode,
int Function(Pointer<llama_context> ctx, llama_batch batch) encode =
llama_encode,
void Function(Pointer<llama_context> ctx) synchronize = llama_synchronize,
}) => LlamaCppObjectCalls._(
exit: null,
failures: NativeCallFailures(null, isWindows: false),
loadModel: llama_model_load_from_file,
Expand All @@ -764,9 +779,17 @@ final class LlamaCppObjectCalls {
Native.addressOf<NativeFunction<Void Function(Pointer<llama_context>)>>(
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,
Expand Down Expand Up @@ -841,10 +864,10 @@ final class LlamaCppObjectCalls {
/// The function `IsolateShutdownReleases` frees a context with.
final Pointer<NativeFinalizerFunction> contextFreeAddress;

/// `llama_decode`.
/// `llama_decode`, returning once the backend has finished the batch.
final int Function(Pointer<llama_context> ctx, llama_batch batch) decode;

/// `llama_encode`.
/// `llama_encode`, returning once the backend has finished the batch.
final int Function(Pointer<llama_context> ctx, llama_batch batch) encode;

/// `llama_synchronize`.
Expand Down
4 changes: 4 additions & 0 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
53 changes: 53 additions & 0 deletions test/unit/backends/llama_cpp/exit_teardown_api_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,59 @@ void main() {
llama_model_free(model);
});

test('untracked decode and encode return once the backend has finished', () {
final context = Pointer<llama_context>.fromAddress(0x10);
final batch = calloc<llama_batch>();
addTearDown(() => calloc.free(batch));
final called = <String>[];
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 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);
Expand Down
117 changes: 117 additions & 0 deletions test/unit/backends/llama_cpp/llama_cpp_service_decode_timing_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
@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/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);
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
// for _backendMicros after each llama_decode, until a synchronize waits for
// it.
void main() {
late Directory dir;
late LlamaCppService service;
late int model;
late int context;
late List<String> calls;
late int Function(Pointer<llama_context> ctx, llama_batch batch) decode;

setUp(() {
dir = Directory.systemTemp.createTempSync('llamadart_decode_timing_');
writeSyntheticLlamaGguf('${dir.path}/model.gguf');
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: decode,
synchronize: (ctx) {
calls.add('synchronize');
while (clock.elapsedMicroseconds < busyUntil) {}
llama_synchronize(ctx);
},
),
)..initializeBackend();
model = service.loadModel('${dir.path}/model.gguf', _params);
context = service.createContext(model, _params);
});

tearDown(() {
service.dispose();
dir.deleteSync(recursive: true);
});

Future<void> generate(String prompt, {List<LlamaContentPart>? parts}) async {
final cancel = calloc<Int8>();
try {
await service
.generate(context, prompt, _greedy, cancel.address, parts: parts)
.drain<void>();
} finally {
calloc.free(cancel);
}
}

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 * _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));
});
}
}
8 changes: 8 additions & 0 deletions website/docs/changelog/recent-releases.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
Loading