Skip to content
Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
## Unreleased

- Fix a possible llama.cpp crash when an image or audio part of a multimodal
request fails to load while later parts remain, and native memory leaked
when a backend is disposed with a context still open or an embedding fails
because the model reports no embedding size
([#947](https://github.com/leehack/llamadart/issues/947),
[#610](https://github.com/leehack/llamadart/issues/610)).
- Fix Qwen 3 chat and tool-result history with LiteRT-LM runtimes that normalize message content to arrays.

## 0.11.0
Expand Down
38 changes: 22 additions & 16 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,8 @@ class LlamaCppService {
/// Creates the service; tests replace the runtime's first native call, the
/// host probes behind its Windows load diagnostics, the raw
/// `ggml_backend_dev_type` values a [ComputeDevice.gpu] load checks for a
/// backend, and the calls that create, free and run models and contexts.
/// backend, the calls that create, free and run models and contexts, and
/// the calls that allocate and free token batches.
LlamaCppService({
void Function()? backendInit,
Abi? abi,
Expand All @@ -653,19 +654,25 @@ class LlamaCppService {
findMissingWindowsLibraries,
List<int> Function(GpuBackend backend)? deviceTypes,
LlamaCppObjectCalls? objectCalls,
llama_batch Function(int tokens, int embd, int sequences)? batchInit,
void Function(llama_batch batch)? batchFree,
}) : _backendInit = backendInit ?? (() => llama_backend_init()),
_abi = abi ?? Abi.current(),
_isWindows = isWindows ?? Platform.isWindows,
_missingWindowsLibraries = missingWindowsLibraries,
_deviceTypesOverride = deviceTypes,
_objectCallsOverride = objectCalls;
_objectCallsOverride = objectCalls,
_batchInit = batchInit ?? llama_batch_init,
_batchFree = batchFree ?? llama_batch_free;

final void Function() _backendInit;
final Abi _abi;
final bool _isWindows;
final List<String> Function(List<String> names) _missingWindowsLibraries;
final List<int> Function(GpuBackend backend)? _deviceTypesOverride;
final LlamaCppObjectCalls? _objectCallsOverride;
final llama_batch Function(int tokens, int embd, int sequences) _batchInit;
final void Function(llama_batch batch) _batchFree;
late final LlamaCppObjectCalls _calls =
_objectCallsOverride ?? _resolveObjectCalls();
int _nextHandle = 1;
Expand Down Expand Up @@ -3931,7 +3938,7 @@ class LlamaCppService {
_samplers[handle] = llama_sampler_chain_init(
llama_sampler_chain_default_params(),
);
_batches[handle] = llama_batch_init(resolvedBatchSizes.batchSize, 0, 1);
_batches[handle] = _batchInit(resolvedBatchSizes.batchSize, 0, 1);

return handle;
}
Expand Down Expand Up @@ -3970,7 +3977,7 @@ class LlamaCppService {
final sampler = _samplers.remove(handle);
if (sampler != null && sampler != nullptr) llama_sampler_free(sampler);
final batch = _batches.remove(handle);
if (batch != null) llama_batch_free(batch);
if (batch != null) _batchFree(batch);
_contexts.remove(handle)?.dispose();
}

Expand Down Expand Up @@ -4931,8 +4938,8 @@ class LlamaCppService {
1,
math.min(configuredBatchSize, tokens.length),
);
final batch = llama_batch_init(batchCapacity, 0, 1);
final embeddingSize = _resolveEmbeddingDimension(model.pointer);
final batch = _batchInit(batchCapacity, 0, 1);

try {
_calls.synchronize(ctx.pointer);
Expand Down Expand Up @@ -4997,7 +5004,7 @@ class LlamaCppService {
return _normalizeEmbeddingVector(vector);
} finally {
llama_set_embeddings(ctx.pointer, false);
llama_batch_free(batch);
_batchFree(batch);
}
}

Expand Down Expand Up @@ -5121,7 +5128,7 @@ class LlamaCppService {
}

final groupSize = index - groupStart;
final batch = llama_batch_init(groupTokenCount, 0, groupSize);
final batch = _batchInit(groupTokenCount, 0, groupSize);
try {
_calls.synchronize(ctx.pointer);
_clearContextMemory(ctx.pointer, strict: false);
Expand Down Expand Up @@ -5171,7 +5178,7 @@ class LlamaCppService {
}
} finally {
llama_set_embeddings(ctx.pointer, false);
llama_batch_free(batch);
_batchFree(batch);
}
}

Expand Down Expand Up @@ -5448,15 +5455,15 @@ class LlamaCppService {
Pointer<Int8> cancelToken,
) {
int initialTokens = 0;
final bitmaps = malloc<Pointer<mtmd_bitmap>>(mediaParts.length);
// Zeroed, so the cleanup of a part that failed skips the slots after it.
final bitmaps = calloc<Pointer<mtmd_bitmap>>(mediaParts.length);
final chunks = _mtmdInputChunksInit();
Pointer<mtmd_input_text> inputText = nullptr;
Pointer<Utf8> promptPtr = nullptr;

try {
for (int i = 0; i < mediaParts.length; i++) {
final p = mediaParts[i];
bitmaps[i] = nullptr;
if (p is LlamaImageContent) {
if (p.path != null) {
final pathPtr = p.path!.toNativeUtf8();
Expand Down Expand Up @@ -5585,7 +5592,7 @@ class LlamaCppService {
for (int i = 0; i < mediaParts.length; i++) {
if (bitmaps[i] != nullptr) _mtmdBitmapFree(bitmaps[i]);
}
malloc.free(bitmaps);
calloc.free(bitmaps);
_mtmdInputChunksFree(chunks);
}
ctx.cachedPromptTokens = null;
Expand Down Expand Up @@ -7459,10 +7466,9 @@ class LlamaCppService {
/// Disposes of all resources managed by the service.
void dispose() {
_freeDecisionHeadsWhere((_) => true);
for (final c in _contexts.values) {
c.dispose();
for (final handle in _contexts.keys.toList()) {
_freeContext(handle);
}
_contexts.clear();
// A projector uses its model, so it goes first, as in freeModel.
for (final m in _mtmdContexts.values) {
_mtmdFree(m);
Expand Down Expand Up @@ -8564,14 +8570,14 @@ class LlamaCppService {
tokenLimit: head.tokenLimit,
vocabSize: head.vocabSize,
);
final batch = llama_batch_init(head.tokenLimit, 0, 1);
final batch = _batchInit(head.tokenLimit, 0, 1);
try {
return <BackendDecisionOutput>[
for (final sequence in sequences)
_runDecisionSequence(head, batch, sequence),
];
} finally {
llama_batch_free(batch);
_batchFree(batch);
}
}

Expand Down
18 changes: 15 additions & 3 deletions test/support/fake_mtmd.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ final class FakeMtmd {
required this.tokens,
this.chunkEval = false,
this.decode = llama_decode,
this.audioBitmap = _audioBitmap,
}) {
final owner = reflectClass(LlamaCppService).owner as LibraryMirror;
final apiClass =
Expand Down Expand Up @@ -55,12 +56,14 @@ final class FakeMtmd {
#helperInitOptDefault: unused,
#helperBitmapInitFromFile: unused,
#helperBitmapInitFromBuf: unused,
#bitmapInitFromAudio: (int _, Pointer<Float> _) =>
Pointer<mtmd_bitmap>.fromAddress(0x20),
#bitmapInitFromAudio: (int sampleCount, Pointer<Float> _) =>
audioBitmap(sampleCount),
#supportsVision: (Pointer<mtmd_context> _) => false,
#supportsAudio: (Pointer<mtmd_context> _) => true,
#supportsVideo: (Pointer<mtmd_context> _) => false,
#bitmapFree: (Pointer<mtmd_bitmap> _) {},
#bitmapFree: (Pointer<mtmd_bitmap> bitmap) {
freedBitmaps.add(bitmap.address);
},
#tokenize:
(
Pointer<mtmd_context> _,
Expand Down Expand Up @@ -110,9 +113,16 @@ final class FakeMtmd {
/// The decode call the media evaluation makes.
final int Function(Pointer<llama_context> context, llama_batch batch) decode;

/// The bitmap the fake `mtmd_bitmap_init_from_audio` returns for an audio
/// part of a sample count; a null pointer fails that part.
final Pointer<mtmd_bitmap> Function(int sampleCount) audioBitmap;

/// Upstream mtmd functions called on the projector so far, in order.
final List<String> calls = <String>[];

/// Addresses passed to the fake `mtmd_bitmap_free` so far, in order.
final List<int> freedBitmaps = <int>[];

/// Media evaluations so far, through this fake or an `ExitTeardownApi`
/// given [evalMedia].
int evaluations = 0;
Expand Down Expand Up @@ -161,6 +171,8 @@ final class FakeMtmd {
}
}

static Pointer<mtmd_bitmap> _audioBitmap(int _) => Pointer.fromAddress(0x20);

/// Frees the marker text; call after the service is disposed.
void dispose() => malloc.free(_marker);

Expand Down
Loading
Loading