From 28ca4eaf3a1c99081e48cebf717b40b3b8d71f2d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Wed, 7 Oct 2026 19:52:42 -0400 Subject: [PATCH 1/2] fix: release llama.cpp samplers, batches and media bitmaps on dispose and error paths LlamaCppService.dispose() freed each llama_context but left the context's sampler chain and token batch allocated; it now frees every open context through _freeContext, in the same contexts, projectors, models order (#610). Multimodal ingestion read its bitmap array back in cleanup although only the slots up to a failed media part had been written, so a later part that failed could pass uninitialised pointers to mtmd_bitmap_free. The array is now zeroed on allocation (#947). embed() allocated its batch before resolving the embedding dimension, so a model that reports none leaked the batch. The dimension is resolved first (#947). The service's token batch allocation goes through a constructor seam so tests can observe it; llama_batch_free has no native hook. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + .../backends/llama_cpp/llama_cpp_service.dart | 38 +-- test/support/fake_mtmd.dart | 18 +- ...llama_cpp_service_native_release_test.dart | 254 ++++++++++++++++++ website/docs/changelog/recent-releases.md | 9 + 5 files changed, 309 insertions(+), 19 deletions(-) create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index c86d4de36..d49f05096 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## Unreleased + +- Fix a possible llama.cpp crash when a later image or audio part of a + multimodal request fails to load, 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)). + ## 0.11.0 - Fix a Flutter macOS app aborting in ggml-metal when it quits while a diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 8f158c063..6fb408605 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -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, @@ -653,12 +654,16 @@ class LlamaCppService { findMissingWindowsLibraries, List 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; @@ -666,6 +671,8 @@ class LlamaCppService { final List Function(List names) _missingWindowsLibraries; final List 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; @@ -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; } @@ -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(); } @@ -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); @@ -4997,7 +5004,7 @@ class LlamaCppService { return _normalizeEmbeddingVector(vector); } finally { llama_set_embeddings(ctx.pointer, false); - llama_batch_free(batch); + _batchFree(batch); } } @@ -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); @@ -5171,7 +5178,7 @@ class LlamaCppService { } } finally { llama_set_embeddings(ctx.pointer, false); - llama_batch_free(batch); + _batchFree(batch); } } @@ -5448,7 +5455,8 @@ class LlamaCppService { Pointer cancelToken, ) { int initialTokens = 0; - final bitmaps = malloc>(mediaParts.length); + // Zeroed, so the cleanup of a part that failed skips the slots after it. + final bitmaps = calloc>(mediaParts.length); final chunks = _mtmdInputChunksInit(); Pointer inputText = nullptr; Pointer promptPtr = nullptr; @@ -5456,7 +5464,6 @@ class LlamaCppService { 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(); @@ -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; @@ -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); @@ -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 [ for (final sequence in sequences) _runDecisionSequence(head, batch, sequence), ]; } finally { - llama_batch_free(batch); + _batchFree(batch); } } diff --git a/test/support/fake_mtmd.dart b/test/support/fake_mtmd.dart index c8f59e9a4..da7cbc557 100644 --- a/test/support/fake_mtmd.dart +++ b/test/support/fake_mtmd.dart @@ -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 = @@ -55,12 +56,14 @@ final class FakeMtmd { #helperInitOptDefault: unused, #helperBitmapInitFromFile: unused, #helperBitmapInitFromBuf: unused, - #bitmapInitFromAudio: (int _, Pointer _) => - Pointer.fromAddress(0x20), + #bitmapInitFromAudio: (int sampleCount, Pointer _) => + audioBitmap(sampleCount), #supportsVision: (Pointer _) => false, #supportsAudio: (Pointer _) => true, #supportsVideo: (Pointer _) => false, - #bitmapFree: (Pointer _) {}, + #bitmapFree: (Pointer bitmap) { + freedBitmaps.add(bitmap.address); + }, #tokenize: ( Pointer _, @@ -110,9 +113,16 @@ final class FakeMtmd { /// The decode call the media evaluation makes. final int Function(Pointer 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 Function(int sampleCount) audioBitmap; + /// Upstream mtmd functions called on the projector so far, in order. final List calls = []; + /// Addresses passed to the fake `mtmd_bitmap_free` so far, in order. + final List freedBitmaps = []; + /// Media evaluations so far, through this fake or an `ExitTeardownApi` /// given [evalMedia]. int evaluations = 0; @@ -161,6 +171,8 @@ final class FakeMtmd { } } + static Pointer _audioBitmap(int _) => Pointer.fromAddress(0x20); + /// Frees the marker text; call after the service is disposed. void dispose() => malloc.free(_marker); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart new file mode 100644 index 000000000..e74273089 --- /dev/null +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart @@ -0,0 +1,254 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; +import 'dart:mirrors'; +import 'dart:typed_data'; + +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/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); + +// Runs the real llama.cpp runtime on the CPU and watches the native memory a +// service owns besides its tracked objects: a context's sampler chain, token +// batches and media bitmaps. +void main() { + late Directory dir; + late String modelPath; + + setUp(() { + dir = Directory.systemTemp.createTempSync('llamadart_native_release_'); + addTearDown(() => dir.deleteSync(recursive: true)); + modelPath = writeSyntheticLlamaGguf('${dir.path}/model.gguf').path; + }); + + test('dispose frees the sampler chain and the batch of a context that is ' + 'still open', () { + final samplerFrees = _SamplerFrees(); + addTearDown(samplerFrees.close); + final batches = _LiveBatches(); + final service = LlamaCppService( + batchInit: batches.init, + batchFree: batches.free, + )..initializeBackend(); + addTearDown(service.dispose); + final context = service.createContext( + service.loadModel(modelPath, _params), + _params, + ); + samplerFrees.watch(_samplerChain(service, context)); + expect(batches.live, hasLength(1)); + + service.dispose(); + + expect(samplerFrees.count, 1); + expect(batches.live, isEmpty); + }); + + test('frees only the bitmaps it created when a later media part ' + 'fails', () async { + // Part i has i + 1 samples, which is how the fake tells the parts apart. + const failingPart = 1; + Pointer bitmapOf(int part) => + Pointer.fromAddress(0x1000 + part); + final parts = [ + for (var part = 0; part < 8; part++) + LlamaAudioContent(samples: Float32List(part + 1)), + ]; + final service = LlamaCppService(objectCalls: LlamaCppObjectCalls.upstream) + ..initializeBackend(); + final fake = FakeMtmd.install( + service, + tokens: const [], + audioBitmap: (sampleCount) => + sampleCount - 1 == failingPart ? nullptr : bitmapOf(sampleCount - 1), + ); + addTearDown(fake.dispose); + addTearDown(service.dispose); + final model = service.loadModel(modelPath, _params); + final context = service.createContext(model, _params); + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + service.createMultimodalContext(model, projectorPath); + _scribbleFreedBlocks(parts.length * sizeOf>()); + + await expectLater( + _generate(service, context, '<__media__>' * parts.length, parts), + throwsA( + predicate( + (error) => + '$error'.contains('Failed to load media part $failingPart'), + ), + ), + ); + + expect(fake.freedBitmaps, [bitmapOf(0).address]); + }); + + test('embed leaves no batch allocated when the model reports no embedding ' + 'size', () { + final real = ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!; + final batches = _LiveBatches(); + final service = LlamaCppService( + objectCalls: LlamaCppObjectCalls.tracked( + _withModelLoad( + real, + // A vocabulary-only load reads no embedding size from the file. + (path, params) => + real.modelLoadFromFile(path, params..vocab_only = true), + ), + ), + batchInit: batches.init, + batchFree: batches.free, + )..initializeBackend(); + addTearDown(service.dispose); + final context = service.createContext( + service.loadModel(modelPath, _params), + _params, + ); + final liveBefore = batches.live.toList(); + + expect( + () => service.embed(context, 'no embedding size'), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Failed to resolve embedding dimension', + ), + ), + ); + + expect(batches.live, liveBefore); + }); +} + +/// Token batches that were allocated and not freed yet, by the address of +/// their token array. +final class _LiveBatches { + final List live = []; + + llama_batch init(int tokens, int embd, int sequences) { + final batch = llama_batch_init(tokens, embd, sequences); + live.add(batch.token.address); + return batch; + } + + void free(llama_batch batch) { + live.remove(batch.token.address); + llama_batch_free(batch); + } +} + +/// Counts the frees of the sampler chains it watches. llama.cpp frees a chain +/// by freeing each sampler in it, so a sampler added to the chain sees it. +final class _SamplerFrees { + _SamplerFrees() { + _interface.ref.free = _onFree.nativeFunction; + } + + int count = 0; + + final Pointer _interface = calloc(); + + late final _onFree = + NativeCallable)>.isolateLocal( + (Pointer _) => count++, + ); + + void watch(Pointer chain) => + llama_sampler_chain_add(chain, llama_sampler_init(_interface, nullptr)); + + void close() { + _onFree.close(); + calloc.free(_interface); + } +} + +Pointer _samplerChain(LlamaCppService service, int context) { + final owner = reflectClass(LlamaCppService).owner as LibraryMirror; + final samplers = + reflect( + service, + ).getField(MirrorSystem.getSymbol('_samplers', owner)).reflectee + as Map>; + return samplers[context]!; +} + +// Leaves non-null words in freed blocks of [byteCount]. An allocator that +// hands such a block out again as it is, as glibc does, then shows an array +// slot the service never wrote as a pointer. macOS clears freed blocks: run +// with MallocPreScribble=1 there for the same effect. +void _scribbleFreedBlocks(int byteCount) { + final blocks = [ + for (var block = 0; block < 64; block++) malloc(byteCount), + ]; + for (final block in blocks) { + block.asTypedList(byteCount).fillRange(0, byteCount, 0x5a); + } + blocks.forEach(malloc.free); +} + +Future _generate( + LlamaCppService service, + int context, + String prompt, + List parts, +) async { + final cancel = calloc(); + try { + await service + .generate( + context, + prompt, + const GenerationParams(maxTokens: 1), + cancel.address, + parts: parts, + ) + .drain(); + } finally { + calloc.free(cancel); + } +} + +ExitTeardownApi _withModelLoad( + ExitTeardownApi real, + Pointer Function(Pointer path, llama_model_params params) + modelLoadFromFile, +) => ExitTeardownApi( + track: real.track, + untrack: real.untrack, + free: real.free, + freeAddress: real.freeAddress, + modelLoadFromFile: modelLoadFromFile, + initFromModel: real.initFromModel, + mtmdInitFromFile: real.mtmdInitFromFile, + decode: real.decode, + encode: real.encode, + synchronize: real.synchronize, + samplerSample: real.samplerSample, + stateSaveFile: real.stateSaveFile, + stateLoadFile: real.stateLoadFile, + stateSeqGetSizeExt: real.stateSeqGetSizeExt, + stateSeqGetDataExt: real.stateSeqGetDataExt, + stateSeqSetDataExt: real.stateSeqSetDataExt, + adapterLoraInit: real.adapterLoraInit, + mtmdTokenize: real.mtmdTokenize, + mtmdEncodeChunk: real.mtmdEncodeChunk, + mtmdHelperEvalChunks: real.mtmdHelperEvalChunks, + mtmdHelperEvalChunkSingle: real.mtmdHelperEvalChunkSingle, + mtmdHelperDecodeImageChunk: real.mtmdHelperDecodeImageChunk, + schedGraphCompute: real.schedGraphCompute, +); diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index ae436dcf1..e68589cea 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,15 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- Fix a possible llama.cpp crash when a later image or audio part of a + multimodal request fails to load, 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)). + ## 0.11.0 - Fix a Flutter macOS app aborting in ggml-metal when it quits while a From 25d6850e606d6aba2288ee207237016ccc638035 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Wed, 7 Oct 2026 20:29:28 -0400 Subject: [PATCH 2/2] docs: tighten the multimodal crash changelog entry and the allocator note The crash needs a media part to fail while later parts remain. On macOS the bitmap test fails without the fix only under MallocScribble=1. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++---- .../llama_cpp/llama_cpp_service_native_release_test.dart | 4 ++-- website/docs/changelog/recent-releases.md | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ba87bdb9..74c659ba7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ ## Unreleased -- Fix a possible llama.cpp crash when a later image or audio part of a - multimodal request fails to load, 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 +- 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. diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart index e74273089..612257de3 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_release_test.dart @@ -189,8 +189,8 @@ Pointer _samplerChain(LlamaCppService service, int context) { // Leaves non-null words in freed blocks of [byteCount]. An allocator that // hands such a block out again as it is, as glibc does, then shows an array -// slot the service never wrote as a pointer. macOS clears freed blocks: run -// with MallocPreScribble=1 there for the same effect. +// slot the service never wrote as a pointer. On macOS the slot reads as null +// unless the test runs with MallocScribble=1. void _scribbleFreedBlocks(int byteCount) { final blocks = [ for (var block = 0; block < 64; block++) malloc(byteCount), diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 40430b724..0482b26d6 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -9,10 +9,10 @@ For canonical full release notes, use: ## Unreleased -- Fix a possible llama.cpp crash when a later image or audio part of a - multimodal request fails to load, 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 +- 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.