From 5a196f971b2b46723148623ed01ab0e03e7ca33e Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 21:08:41 -0400 Subject: [PATCH 1/6] feat: adopt llama.cpp native v0.6.0-1 with typed native exceptions and Vulkan device facts Move the llama.cpp runtime to llamadart-native v0.6.0-1 (llama.cpp v0.6.0) and the WebGPU bridge assets to v0.1.59, which embed the same llama.cpp release. - Sync the native pin, the regenerated bindings and the llamadart_llama_cpp_flutter SwiftPM pin. llama.cpp v0.6.0 changes mtmd_helper_post_decode_callback; libllamadart keeps the previous callback type for its own decode wrapper. - Resolve libllamadart's exception barrier (NativeBarrierApi) and throw the typed LlamaException of an operation when a call caught a C++ exception. Route tokenize, token to piece, sampler accept, the lazy-grammar constructor, memory clear, the mtmd bitmap constructors and the decision head's backend calls through the new wrappers. Objects a failed call leaves free-only are refused until freed. - Read the Vulkan device facts: keep the Android Vulkan 8-token prompt cap only on GPUs whose subgroup size ggml-vulkan mis-tiles or cannot be read, and stop a load on a Vulkan driver or loader below 1.2. - Name both session versions when a state file of another llama.cpp release is refused. --- CHANGELOG.md | 30 + README.md | 4 +- doc/llama_cpp_exit_teardown.md | 107 ++- doc/webgpu_bridge.md | 25 +- example/chat_app/web/index.html | 4 +- lib/src/backends/llama_cpp/bindings.dart | 494 +++++++++++- lib/src/backends/llama_cpp/decision_head.dart | 131 ++- .../backends/llama_cpp/exit_teardown_api.dart | 375 ++++++++- .../backends/llama_cpp/llama_cpp_service.dart | 520 +++++++++--- .../backends/llama_cpp/mtmd_chunk_eval.dart | 68 +- .../llama_cpp/native_barrier_api.dart | 690 ++++++++++++++++ .../llama_cpp/vulkan_device_probe.dart | 255 ++++++ lib/src/hook/native_release_pins.dart | 2 +- .../llamadart_llama_cpp_flutter/CHANGELOG.md | 4 + .../llamadart_llama_cpp_flutter/README.md | 2 +- .../llamadart_llama_cpp_flutter/Package.swift | 4 +- scripts/fetch_webgpu_bridge_assets.sh | 6 +- skills/llamadart-flutter-app/SKILL.md | 7 +- .../native_symbol_integration_test.dart | 90 ++- .../native_exception_barrier_test.dart | 88 +++ test/integration/state_persistence_test.dart | 19 +- test/support/fake_mtmd.dart | 2 +- test/support/fake_native_barrier.dart | 171 ++++ test/support/recording_exit_teardown.dart | 67 +- .../llama_cpp/decision_head_test.dart | 200 +++++ .../llama_cpp/exit_teardown_api_test.dart | 419 +++++++++- ...llama_cpp_service_native_failure_test.dart | 747 ++++++++++++++++++ .../llama_cpp/llama_cpp_service_test.dart | 407 ++++++++++ .../llama_cpp/mtmd_chunk_eval_test.dart | 25 +- .../llama_cpp/native_barrier_api_test.dart | 669 ++++++++++++++++ .../llama_cpp/vulkan_device_probe_test.dart | 278 +++++++ .../tooling/check_webgpu_bridge_tag_test.dart | 66 +- tool/testing/check_webgpu_bridge_tag.dart | 16 +- website/docs/changelog/recent-releases.md | 30 + website/docs/getting-started/installation.md | 4 +- website/docs/guides/backend-benchmarks.md | 3 +- website/docs/guides/model-lifecycle.md | 7 +- website/docs/guides/performance-tuning.md | 15 +- website/docs/guides/text-to-speech.md | 2 +- website/docs/platforms/native-build-hooks.md | 7 + website/docs/platforms/support-matrix.md | 26 +- website/docs/platforms/webgpu-bridge.md | 26 +- website/docs/troubleshooting/common-issues.md | 27 + 43 files changed, 5826 insertions(+), 313 deletions(-) create mode 100644 lib/src/backends/llama_cpp/native_barrier_api.dart create mode 100644 lib/src/backends/llama_cpp/vulkan_device_probe.dart create mode 100644 test/integration/native_exception_barrier_test.dart create mode 100644 test/support/fake_native_barrier.dart create mode 100644 test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart create mode 100644 test/unit/backends/llama_cpp/native_barrier_api_test.dart create mode 100644 test/unit/backends/llama_cpp/vulkan_device_probe_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index e3a5c009d..8f65c298d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,36 @@ `v0.18.0`, and names the upstream version when its prebuilt-override table is behind the runtime owner's ([#586](https://github.com/leehack/llamadart/issues/586)). +- Update the default llama.cpp runtime to + `leehack/llamadart-native@v0.6.0-1` (llama.cpp `v0.6.0`), and the + `llamadart_llama_cpp_flutter` Apple SwiftPM pin with it. +- **Behavior change:** a llama.cpp state file saved by llamadart 0.11.x or + earlier no longer loads: llama.cpp `v0.6.0` changed the session format. + On native, `stateLoadFile` throws `LlamaStateException` naming the file's + format version and the one the runtime reads; evaluate the prompt again and + save a new file ([Save and restore prompt state](https://llamadart.leehack.com/docs/guides/model-lifecycle#save-and-restore-prompt-state)). +- Fix a C++ exception inside llama.cpp ending the process on native. The + failed call now throws the typed `LlamaException` of its operation with + llama.cpp's message, such as `LlamaInferenceException` from `detokenize` + for a token outside the vocabulary, or from a lazy-grammar trigger pattern + that is not a regular expression. A context the failed call left undefined + then throws `LlamaStateException` until its model is loaded again + ([llamadart-native#102](https://github.com/leehack/llamadart-native/issues/102)). +- Android llama.cpp Vulkan: the 8-token text-prompt decode cap now applies + only on a GPU whose subgroup size llama.cpp `v0.6.0` mis-tiles (16, or below + 8) or cannot be read. Other GPUs decode a text prompt in full micro-batches + ([#948](https://github.com/leehack/llamadart/issues/948)). +- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. On a + registered Vulkan GPU whose driver reports less, `ComputeDevice.gpu` now + throws `LlamaUnsupportedException` naming the GPU and both versions, and + `ComputeDevice.auto` loads the model on the CPU with a warning, instead of + starting a driver llama.cpp cannot use + ([#782](https://github.com/leehack/llamadart/issues/782)). +* Aligned the default WebGPU bridge assets to `v0.1.59`: they embed llama.cpp + `v0.6.0`, are qualified against native `v0.6.0`, and keep Web/native + llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14` parity and Web + `@litert-lm/core@0.15.0`. Immutable Web asset manifest: + `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. ## 0.11.1 diff --git a/README.md b/README.md index 89e80cf38..fe96a56bb 100644 --- a/README.md +++ b/README.md @@ -319,9 +319,9 @@ Current default runtime pins: | Runtime | Pin | | --- | --- | -| Native llama.cpp / GGUF | `leehack/llamadart-native@v0.5.0-2` | +| Native llama.cpp / GGUF | `leehack/llamadart-native@v0.6.0-1` | | Native LiteRT-LM / `.litertlm` | `leehack/litert-lm-native@v0.18.0` | -| Web llama.cpp / GGUF | `leehack/llama-web-bridge-assets@v0.1.54` | +| Web llama.cpp / GGUF | `leehack/llama-web-bridge-assets@v0.1.59` | | Web LiteRT-LM / `.litertlm` | `@litert-lm/core@0.15.0` | Native overrides accept stable `vMAJOR.MINOR.PATCH` releases and preserve diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 127b8f315..2b703d7a6 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -27,6 +27,15 @@ runs at exit. The native contract is `src/llama_dart_wrapper.h` in warning at its first model load (visible at log level `warn` or lower) and exits behave as they did before exit teardown. +`lib/src/backends/llama_cpp/native_barrier_api.dart` holds the functions +`v0.6.0-1` adds (`NativeBarrierApi`): the last-error accessors, and wrappers +for the upstream functions the service used to call directly and that throw +(tokenize, token to piece, sampler accept, the lazy-grammar constructor, +memory clear, the three mtmd bitmap constructors, and the ggml device and +backend calls of the decision head). They are calls in flight for teardown +like the others, and are resolved all or nothing in the same way. See +"C++ exceptions". + One service uses one of the two for all of its calls. `IsolateShutdownReleases` still holds every object and frees it when its isolate shuts down; with exit teardown the hold's free function is @@ -41,10 +50,11 @@ Teardown waits up to two seconds for guarded calls in flight, then for a 250 ms settle after the end of the last guarded call, and frees the tracked objects. It knows nothing about other native calls: -- An unguarded call on a tracked object (tokenize, detokenize, metadata - reads, sampler construction, media decode) that is in flight when teardown - runs is not protected, however short it is. Teardown frees the object under - it. +- An unguarded call on a tracked object (metadata reads, sampler + construction other than the lazy-grammar one, and on a runtime older than + `v0.6.0-1` also tokenize, detokenize, sampler accept, memory clear and + media decode) that is in flight when teardown runs is not protected, + however short it is. Teardown frees the object under it. - A guarded call that is still running after two seconds (an image or audio evaluation, a long batch) makes teardown free nothing, and ggml-metal aborts as before. @@ -61,8 +71,7 @@ aborted when the object still had Metal buffers allocated. The a direct C `exit()` reached it; the exits that shut the isolates down wait for the free. -`v0.5.0-2`, which this package pins, fixes it: teardown waits for a free in -flight. An exit that lands during the last free now takes that free plus the +`v0.5.0-2` fixes it: teardown waits for a free in flight. An exit that lands during the last free now takes that free plus the rest of the 250 ms settle window, about 255 ms in the native measurements, where it used to return at once. @@ -71,6 +80,69 @@ then the projector, then the model, so the last object a service frees is a model and never a projector. That is also the lifetime order mtmd needs, since a projector points at its model. +## C++ exceptions + +llama.cpp reports some failures by throwing a C++ exception, which ends the +process when it crosses the C ABI into Dart. From `v0.6.0-1` every +`llama_dart_` function that calls llama.cpp catches it, records its message +for the calling thread (`llama_dart_last_error`) and returns a failure value. + +- `LlamaCppObjectCalls.tracked` checks for that after a call returned its + failure value (always, for a call that returns nothing) and throws the + typed error of the operation: `LlamaModelException` for a model, LoRA or + projector load, `LlamaContextException` for a context, + `LlamaStateException` for a state call, `LlamaInferenceException` + otherwise. The message names the upstream function and the details are + llama.cpp's message. A failure value without a caught exception is + returned as before. +- The message is per thread and the next call with a barrier clears it, so it + is read in the same synchronous run as the call, before any other + `llama_dart_` call. A call made outside `LlamaCppObjectCalls` (speculative + decoding, the reasoning-budget sampler, TTS, the mtmd calls and the decision + head's ggml calls) reads it with `NativeCallFailures.throwIfCaught` at the + place that sees the failure value. +- The native contract leaves a llama or mtmd context in no defined state + after a call on it caught an exception, and on Windows every object of the + call, a model included. `NativeCallFailures` records those objects by + address, the service refuses them with `LlamaStateException` at each entry + point (`_ensureContextUsable`, `_ensureModelUsable`), and freeing an object + forgets it. A decision head that caught an exception in one of its ggml + calls stops running the same way. +- A runtime older than `v0.6.0-1` exports none of this: `NativeBarrierApi` + does not resolve, the service calls the upstream functions as before and + logs one warning at its first model load, and an exception still ends the + process. + +A failed `GGML_ASSERT` still aborts: the barrier catches exceptions only. + +## Vulkan device facts + +`lib/src/backends/llama_cpp/vulkan_device_probe.dart` binds +`llama_dart_vulkan_get_device_count` and `llama_dart_vulkan_get_device_info` +(`v0.6.0-1`), which list the devices ggml-vulkan registers with their API +versions and subgroup size. Reading them makes the Vulkan loader load the +system's GPU drivers, so the service reads them once, and only after +ggml-vulkan has registered a device itself and a load or context is about to +use it: + +- A load on Vulkan stops when a device's driver or the loader is below + Vulkan 1.2, which llama.cpp `v0.6.0` needs (`ggml_vk_instance_init` refuses + an older loader; for an older driver it reads + `VkPhysicalDeviceVulkan12Features` the driver never filled in and calls + Vulkan 1.2 functions it lacks). `ComputeDevice.gpu` throws + `LlamaUnsupportedException`; `ComputeDevice.auto` loads on the CPU with a + warning. +- An Android Vulkan context keeps the 8-token text-prompt decode cap unless + the facts list exactly the registered devices and each has a subgroup size + ggml-vulkan tiles correctly (8, or 32 and above). llama.cpp `v0.6.0` gives + a warp of the small matmul tile 8 rows only at a subgroup size of exactly 8 + (`s_warptile_wm`), which is wrong at 16 and at every size below 8 + (https://github.com/ggml-org/llama.cpp/issues/28637). + +A runtime without the functions, a loader that cannot be queried and a device +list that does not match ggml's all count as unknown: the cap stays and no +load is refused. + ## Which exits are covered | Exit | What happens | @@ -128,6 +200,29 @@ new call on an `sd_ctx_t` that can run longer than the 250 ms settle time 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. +- `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 + own name; on the real runtime, a token outside the vocabulary, a trigger + pattern that is not a regular expression and a grammar that rejects an + accepted token are typed errors; `NativeCallFailures` marks and forgets + free-only objects. +- `test/unit/backends/llama_cpp/exit_teardown_api_test.dart` also pins, for + each tracked call, the error a caught exception throws and the objects it + leaves free-only on every platform and under the Windows rule. +- `test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart`: + a service on the real CPU runtime whose exit API and barrier fail the calls + a test names. Each failed call is the typed error of its operation, the + object it leaves undefined is refused afterwards and usable again once + freed and recreated, and nothing created stays unfreed. It also loads a + state file written by llama.cpp `v0.5.0`. +- `test/unit/backends/llama_cpp/vulkan_device_probe_test.dart` and the + "Vulkan" groups of `llama_cpp_service_test.dart`: the device facts, the + version check at load and the cap on each subgroup size, through injected + facts. No default-CI test reads a real Vulkan device. +- No test forces an exception through speculative decoding, the + reasoning-budget sampler or TTS: those functions are resolved inside the + service and have no stand-in. - Two cases of the service test do not run in default CI. The restore and replay of a rejected draft needs a model whose memory cannot drop a tail: set `LLAMADART_LFM2_MODEL` to an LFM2 GGUF. The decision head's device diff --git a/doc/webgpu_bridge.md b/doc/webgpu_bridge.md index d41d36849..cc21fd463 100644 --- a/doc/webgpu_bridge.md +++ b/doc/webgpu_bridge.md @@ -67,11 +67,11 @@ an earlier ` ``` -That release embeds llama.cpp `v0.5.0`, matching the `hook/build.dart` native pin -(`v0.5.0-2`, both built from upstream llama.cpp `v0.5.0@7fe450e19305b828c199d602c23a8337aaa1f03b`) -even though the bridge asset tag `v0.1.54` differs from the native runtime tag -`v0.5.0-2`. Provenance for this immutable consumer artifact: release `397350529`, -tag commit `e161182a09ac560d45ad5e65bb499574f913a466`, bridge source -`65622b297b83513db597a760fa067867755010b4`, and manifest SHA-256 -`8a9f83c15035eeb034a6563e6f753382d7d7f9be81503ef76902138da7841176`. The bridge -assets were qualified against native `v0.5.0`; `v0.5.0-2` rebuilds it from the -same upstream commit. They add the decision API +That release embeds llama.cpp `v0.6.0`, matching the `hook/build.dart` native pin +(`v0.6.0-1`, both built from upstream llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14`) +even though the bridge asset tag `v0.1.59` differs from the native runtime tag +`v0.6.0-1`. Provenance for this immutable consumer artifact: release `406130836`, +tag commit `189dde2798cb65a5ebe12d40068623e1873a6cd9`, bridge source +`c1f64536b9a4ea410066b711928c7cba03691fb0`, and manifest SHA-256 +`f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. The bridge +assets were qualified against native `v0.6.0`; `v0.6.0-1` rebuilds it from the +same upstream commit. Their bridge JavaScript is byte-identical to `v0.1.54`; +only the llama.cpp core changed. They add the decision API (apiVersion 1), next-token scoring (`scoreNextToken`), presence penalty, Min-P, thinking budgets, runtime LoRA adapters and speculative decoding, keep the Qwen3-ASR typed speech contract from `v0.1.30`, and diff --git a/example/chat_app/web/index.html b/example/chat_app/web/index.html index b7fcd2a82..5f9c9cd54 100644 --- a/example/chat_app/web/index.html +++ b/example/chat_app/web/index.html @@ -211,8 +211,8 @@ typeof configuredRepo === 'string' && configuredRepo.length > 0 ? configuredRepo : 'leehack/llama-web-bridge-assets'; - const defaultBridgeAssetsTag = 'v0.1.54'; - const defaultBridgeLlamaCppTag = 'v0.5.0'; + const defaultBridgeAssetsTag = 'v0.1.59'; + const defaultBridgeLlamaCppTag = 'v0.6.0'; const bridgeAssetsTag = typeof configuredTag === 'string' && configuredTag.length > 0 ? configuredTag diff --git a/lib/src/backends/llama_cpp/bindings.dart b/lib/src/backends/llama_cpp/bindings.dart index 521d12d28..9cb402be8 100644 --- a/lib/src/backends/llama_cpp/bindings.dart +++ b/lib/src/backends/llama_cpp/bindings.dart @@ -391,6 +391,19 @@ external ggml_backend_buffer_t ggml_backend_buft_alloc_buffer( int size, ); +@ffi.Native< + ggml_backend_buffer_t Function( + ggml_backend_buffer_type_t, + ffi.Pointer>, + ffi.Int, + ) +>() +external ggml_backend_buffer_t ggml_backend_buft_alloc_buffer_n( + ggml_backend_buffer_type_t buft, + ffi.Pointer> tensors, + int n_tensors, +); + @ffi.Native() external int ggml_backend_buft_get_alignment(ggml_backend_buffer_type_t buft); @@ -402,6 +415,19 @@ external int ggml_backend_buft_get_alloc_size( ffi.Pointer tensor, ); +@ffi.Native< + ffi.Size Function( + ggml_backend_buffer_type_t, + ffi.Pointer>, + ffi.Int, + ) +>() +external int ggml_backend_buft_get_alloc_size_n( + ggml_backend_buffer_type_t buft, + ffi.Pointer> tensors, + int n_tensors, +); + @ffi.Native() external ggml_backend_dev_t ggml_backend_buft_get_device( ggml_backend_buffer_type_t buft, @@ -5939,6 +5965,99 @@ external void llama_backend_free(); @ffi.Native() external void llama_backend_init(); +@ffi.Native, llama_seq_id)>() +external int llama_batch_ext_add( + ffi.Pointer batch, + int seq_id, +); + +@ffi.Native< + ffi.Int32 Function(ffi.Pointer, llama_seq_id, llama_embd) +>() +external int llama_batch_ext_add_embd( + ffi.Pointer batch, + int seq_id, + llama_embd embd, +); + +@ffi.Native< + ffi.Bool Function(ffi.Pointer, ffi.Int32, llama_seq_id) +>() +external bool llama_batch_ext_add_seq( + ffi.Pointer batch, + int idx, + int seq_id, +); + +@ffi.Native< + ffi.Int32 Function(ffi.Pointer, llama_seq_id, llama_token) +>() +external int llama_batch_ext_add_token( + ffi.Pointer batch, + int seq_id, + int id, +); + +@ffi.Native)>() +external void llama_batch_ext_clear(ffi.Pointer batch); + +@ffi.Native)>() +external void llama_batch_ext_free(ffi.Pointer batch); + +@ffi.Native Function(ffi.Pointer)>() +external ffi.Pointer llama_batch_ext_init( + ffi.Pointer ctx, +); + +@ffi.Native< + ffi.Bool Function(ffi.Pointer, ffi.Int32, llama_embd) +>() +external bool llama_batch_ext_set_embd_state( + ffi.Pointer batch, + int idx, + llama_embd embd, +); + +@ffi.Native< + ffi.Bool Function(ffi.Pointer, ffi.Int32, llama_embd) +>() +external bool llama_batch_ext_set_embd_token( + ffi.Pointer batch, + int idx, + llama_embd embd, +); + +@ffi.Native< + ffi.Bool Function(ffi.Pointer, ffi.Int32, ffi.Bool) +>() +external bool llama_batch_ext_set_output_embd( + ffi.Pointer batch, + int idx, + bool value, +); + +@ffi.Native< + ffi.Bool Function(ffi.Pointer, ffi.Int32, ffi.Bool) +>() +external bool llama_batch_ext_set_output_logits( + ffi.Pointer batch, + int idx, + bool value, +); + +@ffi.Native< + ffi.Bool Function( + ffi.Pointer, + ffi.Int32, + ffi.Pointer, + ) +>() +external bool llama_batch_ext_set_pos( + ffi.Pointer batch, + int idx, + ffi.Pointer pos, +); + @ffi.Native() external void llama_batch_free(llama_batch batch); @@ -6009,6 +6128,9 @@ external ffi.Pointer llama_dart_adapter_lora_init( ffi.Pointer path_lora, ); +@ffi.Native() +external void llama_dart_clear_last_error(); + @ffi.Native, llama_batch)>() external int llama_dart_decode( ffi.Pointer ctx, @@ -6047,6 +6169,49 @@ external int llama_dart_exit_tracked_count(); @ffi.Native)>() external bool llama_dart_exit_untrack(ffi.Pointer object); +@ffi.Native< + ggml_backend_buffer_t Function(ffi.Pointer, ggml_backend_t) +>() +external ggml_backend_buffer_t llama_dart_ggml_backend_alloc_ctx_tensors( + ffi.Pointer ctx, + ggml_backend_t backend, +); + +@ffi.Native< + ffi.Bool Function(ggml_backend_dev_t, ffi.Pointer) +>() +external bool llama_dart_ggml_backend_dev_get_props( + ggml_backend_dev_t device, + ffi.Pointer props, +); + +@ffi.Native< + ggml_backend_t Function(ggml_backend_dev_t, ffi.Pointer) +>() +external ggml_backend_t llama_dart_ggml_backend_dev_init( + ggml_backend_dev_t device, + ffi.Pointer params, +); + +@ffi.Native< + ffi.Bool Function( + ggml_backend_dev_t, + ffi.Pointer, + ffi.Pointer, + ) +>() +external bool llama_dart_ggml_backend_dev_memory( + ggml_backend_dev_t device, + ffi.Pointer free, + ffi.Pointer total, +); + +@ffi.Native)>() +external bool llama_dart_ggml_backend_sched_alloc_graph( + ggml_backend_sched_t sched, + ffi.Pointer graph, +); + @ffi.Native)>( symbol: 'llama_dart_ggml_backend_sched_graph_compute', ) @@ -6064,6 +6229,41 @@ ggml_status llama_dart_ggml_backend_sched_graph_compute( ); } +@ffi.Native() +external bool llama_dart_ggml_backend_sched_synchronize( + ggml_backend_sched_t sched, +); + +@ffi.Native< + ffi.Bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ffi.Size, + ) +>() +external bool llama_dart_ggml_backend_tensor_get( + ffi.Pointer tensor, + ffi.Pointer data, + int offset, + int size, +); + +@ffi.Native< + ffi.Bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ffi.Size, + ) +>() +external bool llama_dart_ggml_backend_tensor_set( + ffi.Pointer tensor, + ffi.Pointer data, + int offset, + int size, +); + @ffi.Native< ffi.Pointer Function( ffi.Pointer, @@ -6075,6 +6275,12 @@ external ffi.Pointer llama_dart_init_from_model( llama_context_params params, ); +@ffi.Native Function()>() +external ffi.Pointer llama_dart_last_error(); + +@ffi.Native() +external bool llama_dart_memory_clear(llama_memory_t mem, bool data); + @ffi.Native< ffi.Pointer Function(ffi.Pointer, llama_model_params) >() @@ -6083,6 +6289,38 @@ external ffi.Pointer llama_dart_model_load_from_file( llama_model_params params, ); +@ffi.Native< + ffi.Pointer Function(ffi.Size, ffi.Pointer) +>() +external ffi.Pointer llama_dart_mtmd_bitmap_init_from_audio( + int n_samples, + ffi.Pointer data, +); + +@ffi.Native< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Size, + ) +>() +external ffi.Pointer llama_dart_mtmd_bitmap_init_from_buf( + ffi.Pointer ctx, + ffi.Pointer buf, + int len, +); + +@ffi.Native< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ) +>() +external ffi.Pointer llama_dart_mtmd_bitmap_init_from_file( + ffi.Pointer ctx, + ffi.Pointer fname, +); + @ffi.Native< ffi.Int32 Function(ffi.Pointer, ffi.Pointer) >() @@ -6372,6 +6610,34 @@ external ffi.Pointer llama_dart_ngram_simple_init( int draft_token_max, ); +@ffi.Native, llama_token)>() +external bool llama_dart_sampler_accept( + ffi.Pointer smpl, + int token, +); + +@ffi.Native< + ffi.Pointer Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer>, + ffi.Size, + ffi.Pointer, + ffi.Size, + ) +>() +external ffi.Pointer +llama_dart_sampler_init_grammar_lazy_patterns( + ffi.Pointer vocab, + ffi.Pointer grammar_str, + ffi.Pointer grammar_root, + ffi.Pointer> trigger_patterns, + int num_trigger_patterns, + ffi.Pointer trigger_tokens, + int num_trigger_tokens, +); + @ffi.Native< ffi.Pointer Function( ffi.Pointer, @@ -6614,6 +6880,46 @@ external int llama_dart_state_seq_set_data_ext( @ffi.Native)>() external void llama_dart_synchronize(ffi.Pointer ctx); +@ffi.Native< + ffi.Int32 Function( + ffi.Pointer, + llama_token, + ffi.Pointer, + ffi.Int32, + ffi.Int32, + ffi.Bool, + ) +>() +external int llama_dart_token_to_piece( + ffi.Pointer vocab, + int token, + ffi.Pointer buf, + int length, + int lstrip, + bool special, +); + +@ffi.Native< + ffi.Int32 Function( + ffi.Pointer, + ffi.Pointer, + ffi.Int32, + ffi.Pointer, + ffi.Int32, + ffi.Bool, + ffi.Bool, + ) +>() +external int llama_dart_tokenize( + ffi.Pointer vocab, + ffi.Pointer text, + int text_len, + ffi.Pointer tokens, + int n_tokens_max, + bool add_special, + bool parse_special, +); + @ffi.Native() external int llama_dart_tts_api_version(); @@ -6789,6 +7095,17 @@ llama_dart_tts_status llama_dart_tts_step( ); } +@ffi.Native() +external int llama_dart_vulkan_get_device_count(); + +@ffi.Native< + ffi.Int32 Function(ffi.Int32, ffi.Pointer) +>() +external int llama_dart_vulkan_get_device_info( + int index, + ffi.Pointer out_info, +); + @ffi.Native, llama_batch)>() external int llama_decode(ffi.Pointer ctx, llama_batch batch); @@ -6852,6 +7169,9 @@ ffi.Pointer llama_ftype_name(llama_ftype ftype) { return _llama_ftype_name(ftype.value); } +@ffi.Native)>() +external bool llama_get_causal_attn(ffi.Pointer ctx); + @ffi.Native Function(ffi.Pointer)>() external ffi.Pointer llama_get_embeddings( ffi.Pointer ctx, @@ -7475,6 +7795,27 @@ llama_pooling_type llama_pooling_type$1(ffi.Pointer ctx) { @ffi.Native Function()>() external ffi.Pointer llama_print_system_info(); +@ffi.Native< + ffi.Int32 Function( + ffi.Pointer, + ffi.UnsignedInt, + ffi.Pointer, + ) +>(symbol: 'llama_process') +external int _llama_process( + ffi.Pointer ctx, + int type, + ffi.Pointer batch, +); + +int llama_process( + ffi.Pointer ctx, + llama_process_type type, + ffi.Pointer batch, +) { + return _llama_process(ctx, type.value, batch); +} + @ffi.Native, llama_token)>() external void llama_sampler_accept(ffi.Pointer smpl, int token); @@ -9129,7 +9470,7 @@ const int LLAMA_FILE_MAGIC_GGSQ = 1734833009; const int LLAMA_SESSION_MAGIC = 1734833006; -const int LLAMA_SESSION_VERSION = 10; +const int LLAMA_SESSION_VERSION = 11; const int LLAMA_STATE_SEQ_FLAGS_NONE = 0; @@ -9141,7 +9482,7 @@ const int LLAMA_STATE_SEQ_FLAGS_SWA_ONLY = 1; const int LLAMA_STATE_SEQ_MAGIC = 1734833009; -const int LLAMA_STATE_SEQ_VERSION = 3; +const int LLAMA_STATE_SEQ_VERSION = 4; const int LLAMA_TOKEN_NULL = -1; @@ -10687,6 +11028,8 @@ final class llama_batch extends ffi.Struct { ..ref.logits = logits; } +final class llama_batch_ext extends ffi.Opaque {} + final class llama_chat_message extends ffi.Struct { external ffi.Pointer role; @@ -11037,6 +11380,18 @@ final class llama_dart_speculative_params extends ffi.Struct { ..ref.ngram_cache_dynamic_path = ngram_cache_dynamic_path; } +enum llama_dart_status { + LLAMA_DART_STATUS_EXCEPTION(-2147483648); + + final int value; + const llama_dart_status(this.value); + + static llama_dart_status fromValue(int value) => switch (value) { + -2147483648 => LLAMA_DART_STATUS_EXCEPTION, + _ => throw ArgumentError('Unknown value for llama_dart_status: $value'), + }; +} + final class llama_dart_tts extends ffi.Opaque {} enum llama_dart_tts_capability { @@ -11285,6 +11640,82 @@ enum llama_dart_tts_status { }; } +final class llama_dart_vulkan_device_info extends ffi.Struct { + @ffi.Uint32() + external int struct_size; + + @ffi.Uint32() + external int instance_api_version; + + @ffi.Uint32() + external int physical_device_index; + + @ffi.Uint32() + external int api_version; + + @ffi.Uint32() + external int driver_version; + + @ffi.Uint32() + external int vendor_id; + + @ffi.Uint32() + external int device_id; + + @ffi.Uint32() + external int device_type; + + @ffi.Uint32() + external int subgroup_size; + + @ffi.Array.multi([256]) + external ffi.Array device_name; +} + +enum llama_dart_vulkan_status { + LLAMA_DART_VULKAN_STATUS_OK(0), + LLAMA_DART_VULKAN_STATUS_INVALID_ARGUMENT(-1), + LLAMA_DART_VULKAN_STATUS_UNSUPPORTED(-2), + LLAMA_DART_VULKAN_STATUS_NO_LOADER(-3), + LLAMA_DART_VULKAN_STATUS_LOADER_ERROR(-4), + LLAMA_DART_VULKAN_STATUS_NO_DEVICE(-5); + + final int value; + const llama_dart_vulkan_status(this.value); + + static llama_dart_vulkan_status fromValue(int value) => switch (value) { + 0 => LLAMA_DART_VULKAN_STATUS_OK, + -1 => LLAMA_DART_VULKAN_STATUS_INVALID_ARGUMENT, + -2 => LLAMA_DART_VULKAN_STATUS_UNSUPPORTED, + -3 => LLAMA_DART_VULKAN_STATUS_NO_LOADER, + -4 => LLAMA_DART_VULKAN_STATUS_LOADER_ERROR, + -5 => LLAMA_DART_VULKAN_STATUS_NO_DEVICE, + _ => throw ArgumentError( + 'Unknown value for llama_dart_vulkan_status: $value', + ), + }; +} + +final class llama_embd extends ffi.Struct { + external ffi.Pointer data; + + @ffi.Size() + external int n_rows; + + @ffi.Size() + external int n_embd; + + static ffi.Pointer $allocate( + ffi.Allocator $allocator, { + required ffi.Pointer data, + required int n_rows, + required int n_embd, + }) => $allocator() + ..ref.data = data + ..ref.n_rows = n_rows + ..ref.n_embd = n_embd; +} + enum llama_flash_attn_type { LLAMA_FLASH_ATTN_TYPE_AUTO(-1), LLAMA_FLASH_ATTN_TYPE_DISABLED(0), @@ -11894,6 +12325,21 @@ enum llama_pooling_type { typedef llama_pos = ffi.Int32; typedef Dartllama_pos = int; + +enum llama_process_type { + LLAMA_PROCESS_TYPE_ENCODE(0), + LLAMA_PROCESS_TYPE_DECODE(1); + + final int value; + const llama_process_type(this.value); + + static llama_process_type fromValue(int value) => switch (value) { + 0 => LLAMA_PROCESS_TYPE_ENCODE, + 1 => LLAMA_PROCESS_TYPE_DECODE, + _ => throw ArgumentError('Unknown value for llama_process_type: $value'), + }; +} + typedef llama_progress_callback = ffi.Pointer>; typedef llama_progress_callbackFunction = @@ -12705,6 +13151,40 @@ final class mtmd_helper_bitmap_wrapper extends ffi.Struct { ..ref.video_ctx = video_ctx; } +final class mtmd_helper_embd_batch extends ffi.Struct { + @ffi.Int32() + external int n_tokens; + + external ffi.Pointer embd; + + @ffi.Int32() + external int n_embd; + + external ffi.Pointer pos; + + @ffi.Int32() + external int n_pos; + + @llama_seq_id() + external int seq_id; + + static ffi.Pointer $allocate( + ffi.Allocator $allocator, { + required int n_tokens, + required ffi.Pointer embd, + required int n_embd, + required ffi.Pointer pos, + required int n_pos, + required int seq_id, + }) => $allocator() + ..ref.n_tokens = n_tokens + ..ref.embd = embd + ..ref.n_embd = n_embd + ..ref.pos = pos + ..ref.n_pos = n_pos + ..ref.seq_id = seq_id; +} + final class mtmd_helper_gen_audio extends ffi.Opaque {} final class mtmd_helper_gen_audio_inp extends ffi.Struct { @@ -12783,9 +13263,15 @@ final class mtmd_helper_init_opt extends ffi.Struct { typedef mtmd_helper_post_decode_callback = ffi.Pointer>; typedef mtmd_helper_post_decode_callbackFunction = - ffi.Int32 Function(llama_batch batch, ffi.Pointer user_data); + ffi.Int32 Function( + ffi.Pointer batch, + ffi.Pointer user_data, + ); typedef Dartmtmd_helper_post_decode_callbackFunction = - int Function(llama_batch batch, ffi.Pointer user_data); + int Function( + ffi.Pointer batch, + ffi.Pointer user_data, + ); final class mtmd_helper_video extends ffi.Opaque {} diff --git a/lib/src/backends/llama_cpp/decision_head.dart b/lib/src/backends/llama_cpp/decision_head.dart index ed8dc4e83..c1f196b97 100644 --- a/lib/src/backends/llama_cpp/decision_head.dart +++ b/lib/src/backends/llama_cpp/decision_head.dart @@ -12,6 +12,7 @@ import '../isolate_shutdown_releases.dart'; import 'bindings.dart'; import 'exit_teardown_api.dart'; import 'ggml_graph_api.dart'; +import 'native_barrier_api.dart'; import 'safetensors.dart'; const double _layerNormEpsilon = 1e-5; @@ -221,6 +222,7 @@ final class DecisionHeadRuntime { DecisionHeadRuntime._( this._api, this._exitTeardown, + this._failures, DecisionHeadWeights weights, ) : _hiddenSize = weights.hiddenSize, _heads = weights.heads, @@ -239,8 +241,10 @@ final class DecisionHeadRuntime { /// `ggml_backend_sched_new`. [api] is the ggml function table the head /// calls, [GgmlGraphApi.current] by default. With [exitTeardown], the /// backends, the weights buffer and the scheduler are tracked for exit - /// teardown, and the graph is computed as a call it waits for. What was - /// created before a failure is freed. Throws [ArgumentError] when + /// teardown, and the graph is computed as a call it waits for. With the + /// exception barrier of [failures], the calls that reach a backend go + /// through its wrappers and report a C++ exception as a typed error. What + /// was created before a failure is freed. Throws [ArgumentError] when /// [cpuThreads] is below 1, /// [LlamaUnsupportedException] when the native library does not export a /// ggml function the head calls, [LlamaModelException] when a backend, the @@ -253,6 +257,7 @@ final class DecisionHeadRuntime { required bool opOffload, GgmlGraphApi? api, ExitTeardownApi? exitTeardown, + NativeCallFailures? failures, }) { if (cpuThreads < 1) { throw ArgumentError.value(cpuThreads, 'cpuThreads', 'must be at least 1'); @@ -260,6 +265,7 @@ final class DecisionHeadRuntime { final runtime = DecisionHeadRuntime._( api ?? GgmlGraphApi.current, exitTeardown, + failures, weights, ); try { @@ -275,6 +281,8 @@ final class DecisionHeadRuntime { final GgmlGraphApi _api; final ExitTeardownApi? _exitTeardown; + final NativeCallFailures? _failures; + String? _failedCall; final int _hiddenSize; final int _heads; final int _graphSize; @@ -314,7 +322,7 @@ final class DecisionHeadRuntime { 'before loading a decision head.', ); } - _cpuBackend = api.devInit(cpuDevice, nullptr); + _cpuBackend = _devInit(cpuDevice); if (_cpuBackend == nullptr) { throw LlamaModelException( 'Could not start the ggml CPU backend for the decision head.', @@ -323,7 +331,7 @@ final class DecisionHeadRuntime { _own(ShutdownStage.backend, frees.backendFree, _cpuBackend); _setCpuThreads(cpuThreads); if (device != null && device != nullptr && device != cpuDevice) { - _deviceBackend = api.devInit(device, nullptr); + _deviceBackend = _devInit(device); _own(ShutdownStage.backend, frees.backendFree, _deviceBackend); if (_deviceBackend == nullptr) { throw LlamaModelException( @@ -402,7 +410,13 @@ final class DecisionHeadRuntime { _scorerOutWeight = matrix('scorer.3.weight', d, 1); _scorerOutBias = vector('scorer.3.bias', 1); - _weightsBuffer = api.allocCtxTensors(_weightsContext, primary); + final barrier = _failures?.barrier; + _weightsBuffer = barrier == null + ? api.allocCtxTensors(_weightsContext, primary) + : barrier.ggmlBackendAllocCtxTensors(_weightsContext, primary); + if (_weightsBuffer == nullptr) { + _throwIfCaught('ggml_backend_alloc_ctx_tensors', LlamaModelException.new); + } _own(ShutdownStage.modelUser, frees.bufferFree, _weightsBuffer); if (_weightsBuffer == nullptr) { throw LlamaModelException( @@ -425,7 +439,12 @@ final class DecisionHeadRuntime { staging.asTypedList(tensors.length * size), ); for (final (index, tensor) in tensors.indexed) { - api.tensorSet(tensor, (staging + index * size).cast(), 0, size * 4); + _tensorSet( + tensor, + (staging + index * size).cast(), + size * 4, + LlamaModelException.new, + ); } } } finally { @@ -457,6 +476,50 @@ final class DecisionHeadRuntime { } } + ggml_backend_t _devInit(ggml_backend_dev_t device) { + final barrier = _failures?.barrier; + if (barrier == null) return _api.devInit(device, nullptr); + final backend = barrier.ggmlBackendDevInit(device, nullptr); + if (backend == nullptr) { + _throwIfCaught('ggml_backend_dev_init', LlamaModelException.new); + } + return backend; + } + + void _tensorSet( + Pointer tensor, + Pointer data, + int size, + NativeCallError error, + ) { + final barrier = _failures?.barrier; + if (barrier == null) { + _api.tensorSet(tensor, data, 0, size); + } else if (!barrier.ggmlBackendTensorSet(tensor, data, 0, size)) { + _throwIfCaught('ggml_backend_tensor_set', error); + } + } + + void _tensorGet(Pointer tensor, Pointer data, int size) { + final barrier = _failures?.barrier; + if (barrier == null) { + _api.tensorGet(tensor, data, 0, size); + } else if (!barrier.ggmlBackendTensorGet(tensor, data, 0, size)) { + _throwIfCaught('ggml_backend_tensor_get', LlamaInferenceException.new); + } + } + + // The backends, the buffer and the scheduler of a failed call may only be + // freed, so the head stops running. + void _throwIfCaught(String call, NativeCallError error) { + try { + _failures?.throwIfCaught(call, error); + } on LlamaException { + _failedCall = call; + rethrow; + } + } + void _setCpuThreads(int threads) { final api = _api; final registry = api.devBackendReg(api.backendGetDevice(_cpuBackend)); @@ -497,7 +560,8 @@ final class DecisionHeadRuntime { /// logits. Throws [ArgumentError] for inputs outside these bounds, /// [LlamaInferenceException] when the graph cannot be allocated or computed, /// [LlamaUnsupportedException] when the native library does not export a - /// ggml function the head calls, and [LlamaStateException] after [dispose]. + /// ggml function the head calls, and [LlamaStateException] after [dispose] + /// or after a run that failed with a llama.cpp exception. BackendDecisionOutput run( Float32List hidden, int tokenCount, @@ -507,6 +571,13 @@ final class DecisionHeadRuntime { if (_disposed) { throw LlamaStateException('The decision head has been freed.'); } + final failedCall = _failedCall; + if (failedCall != null) { + throw LlamaStateException( + 'The decision head is unusable after a llama.cpp exception in ' + '$failedCall. Load it again.', + ); + } if (tokenCount < 1 || hidden.length != tokenCount * _hiddenSize) { throw ArgumentError( 'Decision head input has ${hidden.length} values for $tokenCount ' @@ -634,7 +705,15 @@ final class DecisionHeadRuntime { api.buildForwardExpand(graph, scores); api.buildForwardExpand(graph, rows); api.schedReset(_sched); - if (!api.schedAllocGraph(_sched, graph)) { + final barrier = _failures?.barrier; + final allocated = barrier == null + ? api.schedAllocGraph(_sched, graph) + : barrier.ggmlBackendSchedAllocGraph(_sched, graph); + if (!allocated) { + _throwIfCaught( + 'ggml_backend_sched_alloc_graph', + LlamaInferenceException.new, + ); throw LlamaInferenceException( 'Could not allocate decision head compute buffers on $_deviceName ' 'for $n tokens.', @@ -644,7 +723,12 @@ final class DecisionHeadRuntime { final staging = malloc(math.max(n * d, rowCount)); try { final values = staging.asTypedList(n * d)..setAll(0, hidden); - api.tensorSet(hiddenInput, staging.cast(), 0, values.lengthInBytes); + _tensorSet( + hiddenInput, + staging.cast(), + values.lengthInBytes, + LlamaInferenceException.new, + ); staging .asTypedList(d) .setAll( @@ -655,11 +739,21 @@ final class DecisionHeadRuntime { (questionType + 1) * d, ), ); - api.tensorSet(typeInput, staging.cast(), 0, d * 4); + _tensorSet( + typeInput, + staging.cast(), + d * 4, + LlamaInferenceException.new, + ); staging.cast().asTypedList(rowCount) ..[0] = 0 ..setAll(1, markers); - api.tensorSet(rowsInput, staging.cast(), 0, rowCount * 4); + _tensorSet( + rowsInput, + staging.cast(), + rowCount * 4, + LlamaInferenceException.new, + ); final status = (_exitTeardown?.schedGraphCompute ?? api.schedGraphCompute)( @@ -667,16 +761,20 @@ final class DecisionHeadRuntime { graph, ); if (status != ggml_status.GGML_STATUS_SUCCESS.value) { + _throwIfCaught( + 'ggml_backend_sched_graph_compute', + LlamaInferenceException.new, + ); throw LlamaInferenceException( 'Decision head compute failed on $_deviceName (ggml status ' '$status).', ); } - api.tensorGet(scores, staging.cast(), 0, rowCount * 4); + _tensorGet(scores, staging.cast(), rowCount * 4); final logits = Float32List.fromList( staging.asTypedList(rowCount).sublist(1), ); - api.tensorGet(rows, staging.cast(), 0, d * 4); + _tensorGet(rows, staging.cast(), d * 4); final cls = Float32List.fromList(staging.asTypedList(d)); return (logits, cls); } finally { @@ -726,7 +824,12 @@ final class DecisionHeadRuntime { _disposed = true; final api = _api; if (_sched != nullptr) { - api.schedSynchronize(_sched); + final barrier = _failures?.barrier; + if (barrier == null) { + api.schedSynchronize(_sched); + } else { + barrier.ggmlBackendSchedSynchronize(_sched); + } _disown(_sched, api.schedFree); _sched = nullptr; } diff --git a/lib/src/backends/llama_cpp/exit_teardown_api.dart b/lib/src/backends/llama_cpp/exit_teardown_api.dart index 6603bfbfc..eaa345303 100644 --- a/lib/src/backends/llama_cpp/exit_teardown_api.dart +++ b/lib/src/backends/llama_cpp/exit_teardown_api.dart @@ -1,11 +1,24 @@ import 'dart:ffi'; +import '../../core/exceptions.dart'; import '../isolate_shutdown_releases.dart'; import 'bindings.dart'; +import 'native_barrier_api.dart'; const _llamadartAsset = 'package:llamadart/llamadart'; const _wrapperAsset = 'package:llamadart/llamadart_wrapper'; +final int _statusException = + llama_dart_status.LLAMA_DART_STATUS_EXCEPTION.value; + +/// The embedding-batch callback of `llama_dart_mtmd_helper_decode_image_chunk`. +/// +/// libllamadart keeps this signature; upstream's +/// `mtmd_helper_post_decode_callback` takes an `mtmd_helper_embd_batch` since +/// llama.cpp v0.6.0. +typedef LlamaDartPostDecodeCallback = + Pointer)>>; + typedef _FreeNative = Void Function(Pointer); typedef _TrackNative = Bool Function(Pointer, Pointer>, Int32); @@ -93,7 +106,7 @@ typedef _MtmdDecodeImageChunkNative = llama_seq_id, Int32, Pointer, - mtmd_helper_post_decode_callback, + LlamaDartPostDecodeCallback, Pointer, ); typedef _SchedGraphComputeNative = @@ -425,7 +438,7 @@ final class ExitTeardownApi { int seqId, int nBatch, Pointer newNPast, - mtmd_helper_post_decode_callback callback, + LlamaDartPostDecodeCallback callback, Pointer userData, ) mtmdHelperDecodeImageChunk; @@ -443,9 +456,14 @@ final class ExitTeardownApi { /// [ExitTeardownApi.minimumNativeRelease] offers. One service uses one of /// them for all of its calls: exit teardown does not wait for an upstream /// call on a tracked object. +/// +/// With a [NativeBarrierApi], a call that caught a C++ exception throws the +/// typed error of its operation instead of returning its failure value, and +/// [failures] remembers the objects that call left free-only. final class LlamaCppObjectCalls { LlamaCppObjectCalls._({ required this.exit, + required this.failures, required this.loadModel, required this.freeModel, required this.modelFreeAddress, @@ -456,6 +474,11 @@ final class LlamaCppObjectCalls { required this.encode, required this.synchronize, required this.samplerSample, + required this.samplerAccept, + required this.samplerInitGrammarLazyPatterns, + required this.tokenize, + required this.tokenToPiece, + required this.memoryClear, required this.stateSaveFile, required this.stateLoadFile, required this.stateSeqGetSizeExt, @@ -465,30 +488,270 @@ final class LlamaCppObjectCalls { }); /// The tracked and guarded functions of [exit]. - factory LlamaCppObjectCalls.tracked(ExitTeardownApi exit) => - LlamaCppObjectCalls._( - exit: exit, - loadModel: exit.modelLoadFromFile, - freeModel: (model) => exit.free(model.cast()), - modelFreeAddress: exit.freeAddress, - createContext: exit.initFromModel, - freeContext: (context) => exit.free(context.cast()), - contextFreeAddress: exit.freeAddress, - decode: exit.decode, - encode: exit.encode, - synchronize: exit.synchronize, - samplerSample: exit.samplerSample, - stateSaveFile: exit.stateSaveFile, - stateLoadFile: exit.stateLoadFile, - stateSeqGetSizeExt: exit.stateSeqGetSizeExt, - stateSeqGetDataExt: exit.stateSeqGetDataExt, - stateSeqSetDataExt: exit.stateSeqSetDataExt, - adapterLoraInit: exit.adapterLoraInit, - ); + /// + /// With [barrier], the calls that used to reach an upstream function that + /// throws go through its wrappers, and every call reports a caught + /// exception as a typed error. [isWindows] selects the stricter rule for + /// the objects of a failed call (see [NativeCallFailures]). + factory LlamaCppObjectCalls.tracked( + ExitTeardownApi exit, { + NativeBarrierApi? barrier, + bool isWindows = false, + }) { + final failures = NativeCallFailures(barrier, isWindows: isWindows); + return LlamaCppObjectCalls._( + exit: exit, + failures: failures, + loadModel: (path, params) { + final model = exit.modelLoadFromFile(path, params); + if (model == nullptr) { + failures.throwIfCaught( + 'llama_model_load_from_file', + LlamaModelException.new, + ); + } + return model; + }, + freeModel: (model) { + failures.forget(model); + exit.free(model.cast()); + }, + modelFreeAddress: exit.freeAddress, + createContext: (model, params) { + final context = exit.initFromModel(model, params); + if (context == nullptr) { + failures.throwIfCaught( + 'llama_init_from_model', + LlamaContextException.new, + windowsFreeOnly: [model], + ); + } + return context; + }, + freeContext: (context) { + failures.forget(context); + exit.free(context.cast()); + }, + contextFreeAddress: exit.freeAddress, + decode: (ctx, batch) { + final status = exit.decode(ctx, batch); + if (status == _statusException) { + failures.throwIfCaught( + 'llama_decode', + LlamaInferenceException.new, + freeOnly: [ctx], + ); + } + return status; + }, + encode: (ctx, batch) { + final status = exit.encode(ctx, batch); + if (status == _statusException) { + failures.throwIfCaught( + 'llama_encode', + LlamaInferenceException.new, + freeOnly: [ctx], + ); + } + return status; + }, + synchronize: (ctx) { + exit.synchronize(ctx); + failures.throwIfCaught( + 'llama_synchronize', + LlamaInferenceException.new, + freeOnly: [ctx], + ); + }, + samplerSample: (sampler, ctx, index) { + final token = exit.samplerSample(sampler, ctx, index); + if (token == LLAMA_TOKEN_NULL) { + failures.throwIfCaught( + 'llama_sampler_sample', + LlamaInferenceException.new, + windowsFreeOnly: [ctx], + ); + } + return token; + }, + samplerAccept: barrier == null + ? llama_sampler_accept + : (sampler, token) { + if (!barrier.samplerAccept(sampler, token)) { + failures.throwIfCaught( + 'llama_sampler_accept', + LlamaInferenceException.new, + ); + } + }, + samplerInitGrammarLazyPatterns: barrier == null + ? llama_sampler_init_grammar_lazy_patterns + : ( + vocab, + grammar, + grammarRoot, + triggerPatterns, + triggerPatternCount, + triggerTokens, + triggerTokenCount, + ) { + final sampler = barrier.samplerInitGrammarLazyPatterns( + vocab, + grammar, + grammarRoot, + triggerPatterns, + triggerPatternCount, + triggerTokens, + triggerTokenCount, + ); + if (sampler == nullptr) { + failures.throwIfCaught( + 'llama_sampler_init_grammar_lazy_patterns', + LlamaInferenceException.new, + windowsFreeOnly: [vocab], + ); + } + return sampler; + }, + tokenize: barrier == null + ? llama_tokenize + : ( + vocab, + text, + textLength, + tokens, + tokenCapacity, + addSpecial, + parseSpecial, + ) { + final count = barrier.tokenize( + vocab, + text, + textLength, + tokens, + tokenCapacity, + addSpecial, + parseSpecial, + ); + if (count == _statusException) { + failures.throwIfCaught( + 'llama_tokenize', + LlamaInferenceException.new, + windowsFreeOnly: [vocab], + ); + } + return count; + }, + tokenToPiece: barrier == null + ? llama_token_to_piece + : (vocab, token, buffer, length, lstrip, special) { + final count = barrier.tokenToPiece( + vocab, + token, + buffer, + length, + lstrip, + special, + ); + if (count == _statusException) { + failures.throwIfCaught( + 'llama_token_to_piece', + LlamaInferenceException.new, + windowsFreeOnly: [vocab], + ); + } + return count; + }, + memoryClear: barrier == null + ? (ctx, memory, data) => llama_memory_clear(memory, data) + : (ctx, memory, data) { + if (!barrier.memoryClear(memory, data)) { + failures.throwIfCaught( + 'llama_memory_clear', + LlamaInferenceException.new, + freeOnly: [ctx], + ); + } + }, + stateSaveFile: (ctx, path, tokens, tokenCount) { + final saved = exit.stateSaveFile(ctx, path, tokens, tokenCount); + if (!saved) { + failures.throwIfCaught( + 'llama_state_save_file', + LlamaStateException.new, + freeOnly: [ctx], + ); + } + return saved; + }, + stateLoadFile: (ctx, path, tokensOut, tokenCapacity, tokenCountOut) { + final loaded = exit.stateLoadFile( + ctx, + path, + tokensOut, + tokenCapacity, + tokenCountOut, + ); + if (!loaded) { + failures.throwIfCaught( + 'llama_state_load_file', + LlamaStateException.new, + freeOnly: [ctx], + ); + } + return loaded; + }, + stateSeqGetSizeExt: (ctx, seqId, flags) { + final size = exit.stateSeqGetSizeExt(ctx, seqId, flags); + if (size == 0) { + failures.throwIfCaught( + 'llama_state_seq_get_size_ext', + LlamaStateException.new, + freeOnly: [ctx], + ); + } + return size; + }, + stateSeqGetDataExt: (ctx, dst, size, seqId, flags) { + final written = exit.stateSeqGetDataExt(ctx, dst, size, seqId, flags); + if (written == 0) { + failures.throwIfCaught( + 'llama_state_seq_get_data_ext', + LlamaStateException.new, + freeOnly: [ctx], + ); + } + return written; + }, + stateSeqSetDataExt: (ctx, src, size, seqId, flags) { + final read = exit.stateSeqSetDataExt(ctx, src, size, seqId, flags); + if (read == 0) { + failures.throwIfCaught( + 'llama_state_seq_set_data_ext', + LlamaStateException.new, + freeOnly: [ctx], + ); + } + return read; + }, + adapterLoraInit: (model, path) { + final adapter = exit.adapterLoraInit(model, path); + if (adapter == nullptr) { + failures.throwIfCaught( + 'llama_adapter_lora_init', + LlamaModelException.new, + freeOnly: [model], + ); + } + return adapter; + }, + ); + } /// The upstream llama.cpp functions; nothing is tracked. static final LlamaCppObjectCalls upstream = LlamaCppObjectCalls._( exit: null, + failures: NativeCallFailures(null, isWindows: false), loadModel: llama_model_load_from_file, freeModel: llama_model_free, modelFreeAddress: @@ -505,6 +768,11 @@ final class LlamaCppObjectCalls { encode: llama_encode, synchronize: llama_synchronize, samplerSample: llama_sampler_sample, + samplerAccept: llama_sampler_accept, + samplerInitGrammarLazyPatterns: llama_sampler_init_grammar_lazy_patterns, + tokenize: llama_tokenize, + tokenToPiece: llama_token_to_piece, + memoryClear: (ctx, memory, data) => llama_memory_clear(memory, data), stateSaveFile: llama_state_save_file, stateLoadFile: llama_state_load_file, stateSeqGetSizeExt: llama_state_seq_get_size_ext, @@ -514,16 +782,26 @@ final class LlamaCppObjectCalls { ); /// [LlamaCppObjectCalls.tracked] when the loaded runtime exports the whole - /// [ExitTeardownApi], otherwise [upstream]. + /// [ExitTeardownApi], with the [NativeBarrierApi] when it exports that too; + /// otherwise [upstream]. static LlamaCppObjectCalls resolve({required bool isWindows}) { final exit = ExitTeardownApi.tryResolve(isWindows: isWindows); - return exit == null ? upstream : LlamaCppObjectCalls.tracked(exit); + if (exit == null) return upstream; + return LlamaCppObjectCalls.tracked( + exit, + barrier: NativeBarrierApi.tryResolve(isWindows: isWindows), + isWindows: isWindows, + ); } /// The exit-teardown functions these calls go through, or `null` for /// [upstream]. final ExitTeardownApi? exit; + /// The C++ exceptions these calls caught and the objects they left + /// free-only. Reports nothing without an exception barrier. + final NativeCallFailures failures; + /// Loads a model; `nullptr` on failure. final Pointer Function( Pointer path, @@ -567,6 +845,53 @@ final class LlamaCppObjectCalls { ) samplerSample; + /// `llama_sampler_accept`. + final void Function(Pointer sampler, int token) samplerAccept; + + /// `llama_sampler_init_grammar_lazy_patterns`; `nullptr` for a grammar that + /// does not parse. + final Pointer Function( + Pointer vocab, + Pointer grammar, + Pointer grammarRoot, + Pointer> triggerPatterns, + int triggerPatternCount, + Pointer triggerTokens, + int triggerTokenCount, + ) + samplerInitGrammarLazyPatterns; + + /// `llama_tokenize`. + final int Function( + Pointer vocab, + Pointer text, + int textLength, + Pointer tokens, + int tokenCapacity, + bool addSpecial, + bool parseSpecial, + ) + tokenize; + + /// `llama_token_to_piece`. + final int Function( + Pointer vocab, + int token, + Pointer buffer, + int length, + int lstrip, + bool special, + ) + tokenToPiece; + + /// `llama_memory_clear` on the memory of [ctx]. + final void Function( + Pointer ctx, + llama_memory_t memory, + bool data, + ) + memoryClear; + /// `llama_state_save_file`. final bool Function( Pointer ctx, @@ -991,7 +1316,7 @@ external int _wrapperMtmdDecodeImageChunk( int seqId, int nBatch, Pointer newNPast, - mtmd_helper_post_decode_callback callback, + LlamaDartPostDecodeCallback callback, Pointer userData, ); diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 9944159c3..3142eb41a 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -37,8 +37,12 @@ import 'stop_sequence_buffer.dart'; import 'bindings.dart'; import 'llama_cpp_raw_bindings.dart' as raw_bindings; import 'mtmd_chunk_eval.dart'; +import 'native_barrier_api.dart'; +import 'vulkan_device_probe.dart'; const _llamadartWrapperAssetId = 'package:llamadart/llamadart_wrapper'; +final int _nativeStatusException = + llama_dart_status.LLAMA_DART_STATUS_EXCEPTION.value; typedef _GgmlBackendLoadNative = ggml_backend_reg_t Function(Pointer); typedef _GgmlBackendLoadDart = ggml_backend_reg_t Function(Pointer); @@ -645,8 +649,8 @@ class LlamaCppService { /// host probes behind its Windows load diagnostics, the Android check behind /// its backend and context policy, the raw `ggml_backend_dev_type` values a /// [ComputeDevice.gpu] load checks for a backend, the calls that create, - /// free and run models and contexts, and the calls that allocate and free - /// token batches. + /// free and run models and contexts, the calls that allocate and free + /// token batches, and the read of the Vulkan device facts. LlamaCppService({ void Function()? backendInit, Abi? abi, @@ -658,6 +662,7 @@ class LlamaCppService { LlamaCppObjectCalls? objectCalls, llama_batch Function(int tokens, int embd, int sequences)? batchInit, void Function(llama_batch batch)? batchFree, + VulkanDeviceProbe Function()? vulkanDeviceProbe, }) : _backendInit = backendInit ?? (() => llama_backend_init()), _abi = abi ?? Abi.current(), _isWindows = isWindows ?? Platform.isWindows, @@ -666,7 +671,8 @@ class LlamaCppService { _deviceTypesOverride = deviceTypes, _objectCallsOverride = objectCalls, _batchInit = batchInit ?? llama_batch_init, - _batchFree = batchFree ?? llama_batch_free; + _batchFree = batchFree ?? llama_batch_free, + _vulkanDeviceProbeOverride = vulkanDeviceProbe; final void Function() _backendInit; final Abi _abi; @@ -677,8 +683,19 @@ class LlamaCppService { final LlamaCppObjectCalls? _objectCallsOverride; final llama_batch Function(int tokens, int embd, int sequences) _batchInit; final void Function(llama_batch batch) _batchFree; + final VulkanDeviceProbe Function()? _vulkanDeviceProbeOverride; late final LlamaCppObjectCalls _calls = _objectCallsOverride ?? _resolveObjectCalls(); + + late final VulkanDeviceProbe _vulkanDeviceProbe = + (_vulkanDeviceProbeOverride ?? _probeVulkanDevices)(); + + // The read loads the system's GPU drivers into the process, so it is made + // once, and only after ggml-vulkan has registered a device itself. + VulkanDeviceProbe _probeVulkanDevices() => + _registeredDeviceTypes(GpuBackend.vulkan).isEmpty + ? const VulkanDeviceProbe.unavailable('ggml-vulkan registered no device') + : VulkanDeviceInfoApi.probeRuntime(isWindows: _isWindows); int _nextHandle = 1; String? _backendModuleDirectory; final Set _loadedBackendModules = {}; @@ -898,31 +915,69 @@ class LlamaCppService { /// micro-batch. /// /// An Android Vulkan context gets [androidVulkanPromptMicroBatchSize] - /// unless [ModelParams.microBatchSize] is set. + /// unless [ModelParams.microBatchSize] is set or + /// [hasSmallMatmulTileDefect] returns false. That is called only when the + /// cap would otherwise apply; without it the cap applies. static int? resolvePromptMicroBatchLimit( ModelParams modelParams, { int? resolvedGpuLayers, bool isAndroid = false, + bool Function()? hasSmallMatmulTileDefect, }) { // ggml-vulkan's small matmul tile gives wrong results for a micro-batch of - // more than 32 tokens on GPUs with a subgroup size of 16 - // (https://github.com/ggml-org/llama.cpp/issues/28637), and the subgroup - // size cannot be read here. The cap is 8 rather than 32 because 8-token - // calls evaluated a prompt about three times faster on the affected - // device (Pixel 9 Pro, Mali-G715). `n_ubatch` is left alone: a non-causal - // image decode and a one-pass embedding need their whole input in one - // micro-batch. + // more than 32 tokens on GPUs whose subgroup size it mis-tiles + // (https://github.com/ggml-org/llama.cpp/issues/28637). The cap is 8 + // rather than 32 because 8-token calls evaluated a prompt about three + // times faster on the affected device (Pixel 9 Pro, Mali-G715). + // `n_ubatch` is left alone: a non-causal image decode and a one-pass + // embedding need their whole input in one micro-batch. if (modelParams.microBatchSize > 0 || !shouldUseConservativeAndroidVulkanContextConfig( modelParams, resolvedGpuLayers: resolvedGpuLayers, isAndroid: isAndroid, - )) { + ) || + hasSmallMatmulTileDefect?.call() == false) { return null; } return androidVulkanPromptMicroBatchSize; } + /// Whether a Vulkan device ggml-vulkan registered may give wrong results + /// from its small matmul tile. + /// + /// True unless [probe] lists exactly [registeredDeviceCount] devices and + /// none of them has the defect: a runtime without the probe, a probe that + /// failed and a device list that does not match ggml's all count as + /// affected. + static bool vulkanSmallMatmulTileDefect( + VulkanDeviceProbe probe, { + required int registeredDeviceCount, + }) { + final devices = probe.devices; + return devices == null || + devices.isEmpty || + devices.length != registeredDeviceCount || + devices.any((device) => device.hasSmallMatmulTileDefect); + } + + /// Why ggml-vulkan cannot drive the devices of [probe], or `null` when it + /// can or the devices are unknown. + /// + /// llama.cpp v0.6.0 needs Vulkan 1.2 from the loader and from the driver + /// of every device it registers (see [VulkanDeviceFacts.meetsVulkan12]). + static String? vulkanUnsupportedReason(VulkanDeviceProbe probe) { + for (final device in probe.devices ?? const []) { + if (device.meetsVulkan12) continue; + String version(int value) => VulkanDeviceFacts.formatApiVersion(value); + return "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both " + 'the Vulkan loader and the GPU driver, and "${device.name}" ' + 'reports driver API ${version(device.apiVersion)} with loader API ' + '${version(device.instanceApiVersion)}'; + } + return null; + } + /// Resolves effective context batch parameters. /// /// Uses the shared non-FFI helper for consistent default resolution and @@ -1872,10 +1927,37 @@ class LlamaCppService { 'one still allocated on Metal aborts in ggml-metal. Use the ' 'package-pinned native runtime $llamaCppTag or a newer one.', ); + } else if (calls.failures.barrier == null) { + LlamaLogger.instance.warning( + 'The loaded llama.cpp runtime does not export the exception barrier ' + '(llama_dart_last_error and the llama_dart_ wrappers that go with ' + 'it; llamadart-native ${NativeBarrierApi.minimumNativeRelease} or ' + 'later is needed), so a C++ exception llama.cpp throws still ends ' + 'the process. Use the package-pinned native runtime $llamaCppTag or ' + 'a newer one.', + ); } return calls; } + /// Throws [LlamaStateException] when an earlier llama.cpp exception left + /// [model] free-only. + void _ensureModelUsable(_LlamaModelWrapper model) { + _calls.failures.ensureUsable(model.pointer, 'This model'); + _calls.failures.ensureUsable( + llama_model_get_vocab(model.pointer), + 'This model', + ); + } + + /// Throws [LlamaStateException] when an earlier llama.cpp exception left + /// the context of [contextHandle] or its model free-only. + void _ensureContextUsable(int contextHandle, _LlamaContextWrapper ctx) { + _calls.failures.ensureUsable(ctx.pointer, 'This context'); + final model = _models[_contextToModel[contextHandle]]; + if (model != null) _ensureModelUsable(model); + } + /// Loads a model from the specified [modelPath]. /// /// Returns a handle to the loaded model. @@ -1923,6 +2005,25 @@ class LlamaCppService { _noGpuMessage(effectiveBackend, forcedCpuFallback: forcedCpuFallback), ); } + final vulkanUnsupported = _vulkanUnsupportedReasonForLoad( + effectiveBackend, + gpuLayers, + ); + if (vulkanUnsupported != null) { + if (preferredDevices != null) { + malloc.free(preferredDevices); + } + if (modelParams.device == ComputeDevice.gpu) { + malloc.free(modelPathPtr); + throw LlamaUnsupportedException( + 'ComputeDevice.gpu is not available for llama.cpp on ' + '${Platform.operatingSystem}: $vulkanUnsupported. Use ' + 'ComputeDevice.auto to run on the CPU instead.', + ); + } + preferredDevices = _createPreferredDeviceList(GpuBackend.cpu); + gpuLayers = 0; + } final mtmdUseGpu = resolveMtmdUseGpuForLoad( modelParams, gpuLayers, @@ -1978,6 +2079,12 @@ class LlamaCppService { _modelLoadParams[handle] = modelParams; _activeBackendName = resolvedBackend; _activeResolvedGpuLayers = gpuLayers; + if (vulkanUnsupported != null) { + LlamaLogger.instance.warning( + '$vulkanUnsupported, so the model loaded on $resolvedBackend with 0 ' + 'GPU layers.', + ); + } if (forcedCpuFallback) { final requested = effectiveBackend.name; LlamaLogger.instance.warning( @@ -1992,6 +2099,26 @@ class LlamaCppService { return handle; } + /// Why a load on [backend] with [gpuLayers] layers must not use the Vulkan + /// devices ggml registered, or `null`. + /// + /// The device facts are read only when such a device would be used: for + /// [GpuBackend.vulkan], and for [GpuBackend.auto] when the Vulkan module is + /// the one that loaded. + String? _vulkanUnsupportedReasonForLoad(GpuBackend backend, int gpuLayers) { + if (gpuLayers <= 0 || + (backend != GpuBackend.vulkan && backend != GpuBackend.auto) || + _registeredVulkanDeviceCount() == 0) { + return null; + } + return vulkanUnsupportedReason(_vulkanDeviceProbe); + } + + int _registeredVulkanDeviceCount() => + (_deviceTypesOverride ?? _registeredDeviceTypes)( + GpuBackend.vulkan, + ).length; + /// Whether a GPU device of [backend], or any GPU device for /// [GpuBackend.auto], is registered after the backend modules load. bool _hasGpuDevice(GpuBackend backend) { @@ -3642,6 +3769,8 @@ class LlamaCppService { ggml_backend_dev_t dev, Pointer props, ) { + final barrier = _calls.failures.barrier; + if (barrier != null) return barrier.ggmlBackendDevGetProps(dev, props); return _ggmlRegistryFallbackOr( false, () { @@ -3665,6 +3794,8 @@ class LlamaCppService { Pointer free, Pointer total, ) { + final barrier = _calls.failures.barrier; + if (barrier != null) return barrier.ggmlBackendDevMemory(dev, free, total); return _ggmlRegistryFallbackOr( false, () { @@ -3882,6 +4013,7 @@ class LlamaCppService { if (model == null) { throw Exception("Invalid model handle"); } + _ensureModelUsable(model); params = resolveComputeDeviceParams( params, isAndroid: _isAndroid, @@ -3971,6 +4103,7 @@ class LlamaCppService { params, resolvedGpuLayers: resolvedModelGpuLayers, isAndroid: _isAndroid, + hasSmallMatmulTileDefect: _androidVulkanHasSmallMatmulTileDefect, ), ); _contextToModel[handle] = modelHandle; @@ -3984,6 +4117,21 @@ class LlamaCppService { return handle; } + bool _androidVulkanHasSmallMatmulTileDefect() { + final probe = _vulkanDeviceProbe; + final defect = vulkanSmallMatmulTileDefect( + probe, + registeredDeviceCount: _registeredVulkanDeviceCount(), + ); + LlamaLogger.instance.debug( + 'llama_cpp_service: Android Vulkan text prompt decode is ' + '${defect ? 'capped at $androidVulkanPromptMicroBatchSize tokens per ' + 'call' : 'not capped'} ' + '(${probe.devices?.join(', ') ?? probe.unavailableReason})', + ); + return defect; + } + void _applyConservativeAndroidVulkanContextConfig( llama_context_params ctxParams, int modelHandle, @@ -4502,6 +4650,7 @@ class LlamaCppService { }) async* { var ctx = _contexts[contextHandle]; if (ctx == null) throw Exception("Invalid context handle"); + _ensureContextUsable(contextHandle, ctx); if (_activeTtsContextHandle == contextHandle) { throw LlamaStateException( 'Cannot generate text while text-to-speech is active on this context.', @@ -4626,6 +4775,11 @@ class LlamaCppService { speculativeSession, ); if (speculativeSession == nullptr) { + _calls.failures.throwIfCaught( + 'llama_dart_speculative_init', + LlamaInferenceException.new, + windowsFreeOnly: [ctx.pointer], + ); throw _speculativeInitFailure(speculativeConfig); } if (speculativeApi.needEmbd(speculativeSession)) { @@ -4677,6 +4831,7 @@ class LlamaCppService { tokensPtr, promptTokenCount, )) { + _throwIfSpeculativeCaught('llama_dart_speculative_begin', ctx.pointer); throw Exception( "Failed to initialize llama.cpp speculative prompt state", ); @@ -4778,6 +4933,7 @@ class LlamaCppService { }) { var ctx = _contexts[contextHandle]; if (ctx == null) throw Exception('Invalid context handle'); + _ensureContextUsable(contextHandle, ctx); if (_activeTtsContextHandle == contextHandle) { throw LlamaStateException( 'Cannot score tokens while text-to-speech is active on this context.', @@ -4848,7 +5004,7 @@ class LlamaCppService { final logSum = maxLogit + math.log(sum); LlamaTokenLogprob scored(int token) { - var n = llama_token_to_piece( + var n = _calls.tokenToPiece( vocab, token, pieceBuf.cast(), @@ -4860,7 +5016,7 @@ class LlamaCppService { malloc.free(pieceBuf); pieceCapacity = -n; pieceBuf = malloc(pieceCapacity); - n = llama_token_to_piece( + n = _calls.tokenToPiece( vocab, token, pieceBuf.cast(), @@ -4952,6 +5108,7 @@ class LlamaCppService { if (contextParams == null) { throw Exception('Missing context parameters'); } + _ensureContextUsable(contextHandle, ctx); final hasEncoder = llama_model_has_encoder(model.pointer); final hasDecoder = llama_model_has_decoder(model.pointer); @@ -5078,6 +5235,7 @@ class LlamaCppService { if (contextParams == null) { throw Exception('Missing context parameters'); } + _ensureContextUsable(contextHandle, ctx); final hasEncoder = llama_model_has_encoder(model.pointer); final hasDecoder = llama_model_has_decoder(model.pointer); @@ -5234,15 +5392,21 @@ class LlamaCppService { final shouldAddSpecial = !_promptStartsWithBosToken(vocab, text); final (textPtr, textLength) = _toNativeUtf8WithLength(text); - final requiredTokenCount = -llama_tokenize( - vocab, - textPtr.cast(), - textLength, - nullptr, - 0, - shouldAddSpecial, - true, - ); + final int requiredTokenCount; + try { + requiredTokenCount = -_calls.tokenize( + vocab, + textPtr.cast(), + textLength, + nullptr, + 0, + shouldAddSpecial, + true, + ); + } catch (_) { + malloc.free(textPtr); + rethrow; + } if (requiredTokenCount <= 0) { malloc.free(textPtr); @@ -5262,7 +5426,7 @@ class LlamaCppService { final tokensPtr = malloc(requiredTokenCount); try { - final actualTokenCount = llama_tokenize( + final actualTokenCount = _calls.tokenize( vocab, textPtr.cast(), textLength, @@ -5423,7 +5587,7 @@ class LlamaCppService { return; } - llama_memory_clear(memory, true); + _calls.memoryClear(contextPointer, memory, true); } /// Ingests the prompt (text or multimodal). @@ -5495,6 +5659,7 @@ class LlamaCppService { llama_context_params modelParams, Pointer cancelToken, ) { + _calls.failures.ensureUsable(mmCtx, 'This multimodal projector'); int initialTokens = 0; // Zeroed, so the cleanup of a part that failed skips the slots after it. final bitmaps = calloc>(mediaParts.length); @@ -5546,6 +5711,11 @@ class LlamaCppService { } if (bitmaps[i] == nullptr) { + _calls.failures.throwIfCaught( + 'the mtmd bitmap constructor', + LlamaInferenceException.new, + windowsFreeOnly: [mmCtx], + ); throw Exception("Failed to load media part $i"); } } @@ -5609,6 +5779,13 @@ class LlamaCppService { cancelToken, ); evalResult = chunkFailure?.result ?? 0; + if (evalResult == _nativeStatusException) { + _calls.failures.throwIfCaught( + 'the mtmd chunk evaluation ($chunkFailure)', + LlamaInferenceException.new, + freeOnly: [mmCtx, ctx.pointer], + ); + } } if (evalResult == 0) { initialTokens = newPast.value; @@ -5733,16 +5910,20 @@ class LlamaCppService { }) { final (promptPtr, promptLength) = _toNativeUtf8WithLength(prompt); final shouldAddSpecial = !_promptStartsWithBosToken(vocab, prompt); - final nTokens = llama_tokenize( - vocab, - promptPtr.cast(), - promptLength, - tokensPtr, - nCtx, - shouldAddSpecial, - true, - ); - malloc.free(promptPtr); + final int nTokens; + try { + nTokens = _calls.tokenize( + vocab, + promptPtr.cast(), + promptLength, + tokensPtr, + nCtx, + shouldAddSpecial, + true, + ); + } finally { + malloc.free(promptPtr); + } if (nTokens < 0 || nTokens > nCtx) { throw Exception("Tokenization failed or prompt too long"); @@ -5987,6 +6168,7 @@ class LlamaCppService { speculativeSession, batch, speculativeConfig, + ctx.pointer, )) { throw Exception("Speculative prompt decode processing failed"); } @@ -6001,13 +6183,31 @@ class LlamaCppService { Pointer speculativeSession, llama_batch batch, _LlamaCppSpeculativeConfig? speculativeConfig, + Pointer context, ) { - return _withSuppressedBatchLogits( + final processed = _withSuppressedBatchLogits( batch.logits, batch.n_tokens, speculativeConfig?.suppressDraftProcessLogits == true, () => speculativeApi.processBatch(speculativeSession, batch), ); + if (!processed) { + _throwIfSpeculativeCaught( + 'llama_dart_speculative_process_batch', + context, + ); + } + return processed; + } + + // Speculative state is built on the target context, so a call on it that + // caught an exception leaves that context free-only too. + void _throwIfSpeculativeCaught(String call, Pointer context) { + _calls.failures.throwIfCaught( + call, + LlamaInferenceException.new, + freeOnly: [context], + ); } static T _withSuppressedBatchLogits( @@ -6091,15 +6291,20 @@ class LlamaCppService { final useLazyGrammar = params.grammarLazy && lazyGrammarConfig != null; if (grammarPtr != nullptr) { if (useLazyGrammar) { - grammarSampler = llama_sampler_init_grammar_lazy_patterns( - vocab, - grammarPtr.cast(), - rootPtr.cast(), - lazyGrammarConfig.triggerPatterns, - lazyGrammarConfig.numTriggerPatterns, - lazyGrammarConfig.triggerTokens, - lazyGrammarConfig.numTriggerTokens, - ); + try { + grammarSampler = _calls.samplerInitGrammarLazyPatterns( + vocab, + grammarPtr.cast(), + rootPtr.cast(), + lazyGrammarConfig.triggerPatterns, + lazyGrammarConfig.numTriggerPatterns, + lazyGrammarConfig.triggerTokens, + lazyGrammarConfig.numTriggerTokens, + ); + } on LlamaException { + llama_sampler_free(sampler); + rethrow; + } } else { grammarSampler = llama_sampler_init_grammar( vocab, @@ -6137,6 +6342,11 @@ class LlamaCppService { llama_sampler_free(grammarSampler); } llama_sampler_free(sampler); + _calls.failures.throwIfCaught( + 'llama_dart_sampler_init_reasoning_budget', + LlamaInferenceException.new, + windowsFreeOnly: [vocab], + ); throw LlamaUnsupportedException( 'llama.cpp could not initialize thinking-budget control. Verify ' 'that the configured thinking tags are supported by the loaded ' @@ -6168,17 +6378,23 @@ class LlamaCppService { } if (grammarPtr == nullptr && tokensPtr != nullptr && promptTokenCount > 0) { - if (thinkingBudgetConfig != null) { - // The composite sampler derives its reasoning state from the complete - // prompt rather than accepting it token by token, but prompt tokens - // still need to seed the repeat-penalty sampler as before. - for (int i = 0; i < promptTokenCount; i++) { - llama_sampler_accept(penaltiesSampler, tokensPtr[i]); - } - } else { - for (int i = 0; i < promptTokenCount; i++) { - llama_sampler_accept(sampler, tokensPtr[i]); + try { + if (thinkingBudgetConfig != null) { + // The composite sampler derives its reasoning state from the + // complete prompt rather than accepting it token by token, but + // prompt tokens still need to seed the repeat-penalty sampler as + // before. + for (int i = 0; i < promptTokenCount; i++) { + _calls.samplerAccept(penaltiesSampler, tokensPtr[i]); + } + } else { + for (int i = 0; i < promptTokenCount; i++) { + _calls.samplerAccept(sampler, tokensPtr[i]); + } } + } on LlamaException { + llama_sampler_free(sampler); + rethrow; } } @@ -6229,7 +6445,7 @@ class LlamaCppService { } final pieceTick = Stopwatch()..start(); - final n = llama_token_to_piece( + final n = _calls.tokenToPiece( vocab, selectedToken, pieceBuf.cast(), @@ -6350,7 +6566,7 @@ class LlamaCppService { if (llama_vocab_is_eog(vocab, selectedToken)) break; final pieceTick = Stopwatch()..start(); - final n = llama_token_to_piece( + final n = _calls.tokenToPiece( vocab, selectedToken, pieceBuf.cast(), @@ -6408,6 +6624,10 @@ class LlamaCppService { draftTick.stop(); draftMicros += draftTick.elapsedMicroseconds; if (draftCount < 0) { + _throwIfSpeculativeCaught( + 'llama_dart_speculative_draft', + ctx.pointer, + ); throw Exception("llama.cpp speculative draft failed"); } speculativeDraftTokens += draftCount; @@ -6429,6 +6649,7 @@ class LlamaCppService { speculativeSession, batch, speculativeConfig, + ctx.pointer, )) { throw Exception("Speculative decode processing failed"); } @@ -6504,6 +6725,7 @@ class LlamaCppService { speculativeSession, batch, speculativeConfig, + ctx.pointer, )) { throw Exception("Speculative decode processing failed"); } @@ -6533,6 +6755,11 @@ class LlamaCppService { verifyTick.stop(); verifyMicros += verifyTick.elapsedMicroseconds; if (acceptedCount <= 0) { + _calls.failures.throwIfCaught( + 'llama_dart_sampler_sample_and_accept_n', + LlamaInferenceException.new, + windowsFreeOnly: [ctx.pointer], + ); throw Exception("llama.cpp speculative draft verification failed"); } @@ -6602,6 +6829,7 @@ class LlamaCppService { speculativeSession, batch, speculativeConfig, + ctx.pointer, )) { throw Exception("Speculative replay processing failed"); } @@ -6620,6 +6848,10 @@ class LlamaCppService { speculativeAcceptedDraftTokens += acceptedDraftCount; speculativeApi.accept(speculativeSession, 0, acceptedDraftCount); + _throwIfSpeculativeCaught( + 'llama_dart_speculative_accept', + ctx.pointer, + ); final targetMemory = llama_get_memory(ctx.pointer); final targetRollbackOk = @@ -6656,7 +6888,7 @@ class LlamaCppService { } final pieceTick = Stopwatch()..start(); - final n = llama_token_to_piece( + final n = _calls.tokenToPiece( vocab, token, pieceBuf.cast(), @@ -6775,7 +7007,7 @@ class LlamaCppService { final (textPtr, textLength) = _toNativeUtf8WithLength(tokenText); try { - final required = -llama_tokenize( + final required = -_calls.tokenize( vocab, textPtr.cast(), textLength, @@ -6791,7 +7023,7 @@ class LlamaCppService { final tokenIds = malloc(required); try { - final actual = llama_tokenize( + final actual = _calls.tokenize( vocab, textPtr.cast(), textLength, @@ -6835,48 +7067,56 @@ class LlamaCppService { List tokenize(int modelHandle, String text, bool addSpecial) { final model = _models[modelHandle]; if (model == null) return []; + _ensureModelUsable(model); final vocab = llama_model_get_vocab(model.pointer); final (textPtr, textLength) = _toNativeUtf8WithLength(text); final shouldAddSpecial = addSpecial && !_promptStartsWithBosToken(vocab, text); - final n = -llama_tokenize( - vocab, - textPtr.cast(), - textLength, - nullptr, - 0, - shouldAddSpecial, - true, - ); - final tokensPtr = malloc(n); - final actual = llama_tokenize( - vocab, - textPtr.cast(), - textLength, - tokensPtr, - n, - shouldAddSpecial, - true, - ); - final result = List.generate(actual, (i) => tokensPtr[i]); - malloc.free(textPtr); - malloc.free(tokensPtr); - return result; + Pointer tokensPtr = nullptr; + try { + final n = -_calls.tokenize( + vocab, + textPtr.cast(), + textLength, + nullptr, + 0, + shouldAddSpecial, + true, + ); + tokensPtr = malloc(n); + final actual = _calls.tokenize( + vocab, + textPtr.cast(), + textLength, + tokensPtr, + n, + shouldAddSpecial, + true, + ); + return List.generate(actual, (i) => tokensPtr[i]); + } finally { + malloc.free(textPtr); + if (tokensPtr != nullptr) malloc.free(tokensPtr); + } } /// Detokenizes the given [tokens]. String detokenize(int modelHandle, List tokens, bool special) { final model = _models[modelHandle]; if (model == null) return ""; + _ensureModelUsable(model); final vocab = llama_model_get_vocab(model.pointer); // UTF-8 decoding requires unsigned bytes, including byte-fallback tokens. final buffer = malloc(256); final bytes = []; - for (final t in tokens) { - final n = llama_token_to_piece(vocab, t, buffer.cast(), 256, 0, special); - if (n > 0) bytes.addAll(buffer.asTypedList(n)); + try { + for (final t in tokens) { + final n = _calls.tokenToPiece(vocab, t, buffer.cast(), 256, 0, special); + if (n > 0) bytes.addAll(buffer.asTypedList(n)); + } + } finally { + malloc.free(buffer); } - malloc.free(buffer); return utf8.decode(bytes, allowMalformed: true); } @@ -6890,6 +7130,7 @@ class LlamaCppService { if (ctx == null) { throw LlamaStateException('Unknown context handle: $contextHandle'); } + _ensureContextUsable(contextHandle, ctx); if (_generatingContexts.containsKey(contextHandle)) { throw LlamaStateException( 'Cannot save state while generation is active on context $contextHandle', @@ -6914,6 +7155,26 @@ class LlamaCppService { } } + /// The llama.cpp session version in the header of the state file at + /// [path], or `null` when it cannot be read or is not a session file. + static int? readSessionFileVersion(String path) { + try { + final file = File(path).openSync(); + try { + final header = file.readSync(8); + if (header.length < 8) return null; + final words = ByteData.sublistView(header); + return words.getUint32(0, Endian.little) == LLAMA_FILE_MAGIC_GGSN + ? words.getUint32(4, Endian.little) + : null; + } finally { + file.closeSync(); + } + } on FileSystemException { + return null; + } + } + /// Restores a previously saved KV-cache state into [contextHandle]. /// [tokenCapacity] caps the number of tokens read back. /// @@ -6924,6 +7185,7 @@ class LlamaCppService { if (ctx == null) { throw LlamaStateException('Unknown context handle: $contextHandle'); } + _ensureContextUsable(contextHandle, ctx); if (_generatingContexts.containsKey(contextHandle)) { throw LlamaStateException( 'Cannot load state while generation is active on context $contextHandle', @@ -6958,6 +7220,16 @@ class LlamaCppService { countPtr, ); if (!ok) { + final fileVersion = readSessionFileVersion(path); + if (fileVersion != null && fileVersion != LLAMA_SESSION_VERSION) { + throw LlamaStateException( + 'The state file "$path" has llama.cpp session version ' + '$fileVersion, and this runtime reads version ' + '$LLAMA_SESSION_VERSION. A state file does not carry over to a ' + 'llama.cpp release that changed the format: evaluate the prompt ' + 'again and save a new one.', + ); + } throw LlamaStateException( 'llama_state_load_file failed for "$path" ' '(corrupt file, version mismatch, or capacity too small)', @@ -7172,6 +7444,7 @@ class LlamaCppService { final ctx = _contexts[contextHandle]; final modelHandle = _contextToModel[contextHandle]; if (ctx == null || modelHandle == null) return; + _ensureContextUsable(contextHandle, ctx); final modelAdapters = _loraAdapters[modelHandle]; final activeLoras = _activeLoras[contextHandle]; @@ -7545,6 +7818,7 @@ class LlamaCppService { if (model == null) { throw Exception("Invalid model handle"); } + _ensureModelUsable(model); if (!File(mmProjPath).existsSync()) { throw LlamaModelException('Multimodal projector file not found.'); } @@ -7656,6 +7930,11 @@ class LlamaCppService { return exitTeardown; } + /// The exception barrier the mtmd bitmap constructors go through; `null` + /// when the runtime has none or the mtmd calls are not guarded. + NativeBarrierApi? get _mtmdBarrier => + _mtmdExitTeardown == null ? null : _calls.failures.barrier; + Pointer _mtmdInitFromFile( Pointer mmProjPath, Pointer model, @@ -7670,6 +7949,13 @@ class LlamaCppService { model, params, ); + if (context == nullptr) { + _calls.failures.throwIfCaught( + 'mtmd_init_from_file', + LlamaModelException.new, + windowsFreeOnly: [model], + ); + } IsolateShutdownReleases.current.hold( ShutdownStage.modelUser, exitTeardown.freeAddress, @@ -7713,6 +7999,7 @@ class LlamaCppService { void _mtmdFree(Pointer ctx) { IsolateShutdownReleases.current.release(ctx); + _calls.failures.forget(ctx); final exitTeardown = _mtmdExitTeardown; if (exitTeardown != null) { exitTeardown.free(ctx.cast()); @@ -7768,6 +8055,8 @@ class LlamaCppService { Pointer ctx, Pointer pathPtr, ) { + final barrier = _mtmdBarrier; + if (barrier != null) return barrier.mtmdBitmapInitFromFile(ctx, pathPtr); if (!_mtmdPrimarySymbolsUnavailable) { try { return mtmd_helper_bitmap_init_from_file( @@ -7801,6 +8090,8 @@ class LlamaCppService { Pointer data, int size, ) { + final barrier = _mtmdBarrier; + if (barrier != null) return barrier.mtmdBitmapInitFromBuf(ctx, data, size); if (!_mtmdPrimarySymbolsUnavailable) { try { return mtmd_helper_bitmap_init_from_buf( @@ -7832,6 +8123,8 @@ class LlamaCppService { } Pointer _mtmdBitmapInitFromAudio(int n, Pointer samples) { + final barrier = _mtmdBarrier; + if (barrier != null) return barrier.mtmdBitmapInitFromAudio(n, samples); if (!_mtmdPrimarySymbolsUnavailable) { try { return mtmd_bitmap_init_from_audio(n, samples); @@ -7871,7 +8164,21 @@ class LlamaCppService { ) { final exitTeardown = _mtmdExitTeardown; if (exitTeardown != null) { - return exitTeardown.mtmdTokenize(ctx, output, text, bitmaps, nBitmaps); + final result = exitTeardown.mtmdTokenize( + ctx, + output, + text, + bitmaps, + nBitmaps, + ); + if (result == _nativeStatusException) { + _calls.failures.throwIfCaught( + 'mtmd_tokenize', + LlamaInferenceException.new, + freeOnly: [ctx], + ); + } + return result; } if (!_mtmdPrimarySymbolsUnavailable) { try { @@ -7899,7 +8206,7 @@ class LlamaCppService { ) { final exitTeardown = _mtmdExitTeardown; if (exitTeardown != null) { - return exitTeardown.mtmdHelperEvalChunks( + final result = exitTeardown.mtmdHelperEvalChunks( ctx, lctx, chunks, @@ -7909,6 +8216,14 @@ class LlamaCppService { logitsLast, newNPast, ); + if (result == _nativeStatusException) { + _calls.failures.throwIfCaught( + 'mtmd_helper_eval_chunks', + LlamaInferenceException.new, + freeOnly: [ctx, lctx], + ); + } + return result; } if (!_mtmdPrimarySymbolsUnavailable) { try { @@ -8559,6 +8874,7 @@ class LlamaCppService { cpuThreads: llama_n_threads_batch(context), opOffload: device != null && ctxParams.op_offload, exitTeardown: _calls.exit, + failures: _calls.failures, ); } catch (_) { IsolateShutdownReleases.current.release(context); @@ -8611,6 +8927,7 @@ class LlamaCppService { 'was unloaded. Load the decision head again.', ); } + _calls.failures.ensureUsable(head.context, 'This decision head'); validateDecisionSequences( sequences, tokenLimit: head.tokenLimit, @@ -8992,7 +9309,11 @@ class LlamaCppService { 'The loaded projector does not expose supported audio generation.', ); } - _throwForTtsStatus(status, operation: 'Text-to-speech capability probe'); + _throwForTtsStatus( + status, + operation: 'Text-to-speech capability probe', + barrierCall: 'llama_dart_tts_get_info', + ); if (info.ref.model_type != llama_dart_tts_model_type.LLAMA_DART_TTS_MODEL_TYPE_QWEN3.value) { return const BackendTextToSpeechCapabilities( @@ -9051,6 +9372,8 @@ class LlamaCppService { 'The loaded context and text-to-speech projector do not match.', ); } + _ensureContextUsable(contextHandle, context); + _calls.failures.ensureUsable(mtmd, 'This multimodal projector'); if (_activeTts != nullptr) { throw LlamaStateException('Text-to-speech synthesis is already active.'); } @@ -9130,6 +9453,8 @@ class LlamaCppService { _throwForTtsStatus( llama_dart_tts_status.fromValue(initStatus.value), operation: 'Text-to-speech initialization', + barrierCall: 'llama_dart_tts_init', + context: context.pointer, ); throw LlamaTextToSpeechException( 'Text-to-speech initialization returned no task.', @@ -9161,6 +9486,8 @@ class LlamaCppService { operation: 'Text-to-speech startup', api: api, task: task, + barrierCall: 'llama_dart_tts_start', + context: context.pointer, ); api.setCancelFlag?.call(task, cancelFlag); @@ -9179,6 +9506,8 @@ class LlamaCppService { operation: 'Text-to-speech generation', api: api, task: task, + barrierCall: 'llama_dart_tts_step', + context: context.pointer, ); framesGenerated = progress.ref.frames_generated; truncated = progress.ref.truncated; @@ -9303,10 +9632,20 @@ class LlamaCppService { required String operation, _TtsApi? api, Pointer? task, + String? barrierCall, + Pointer? context, }) { if (status == llama_dart_tts_status.LLAMA_DART_TTS_STATUS_OK) { return; } + if (barrierCall != null && + status == llama_dart_tts_status.LLAMA_DART_TTS_STATUS_UPSTREAM_ERROR) { + _calls.failures.throwIfCaught( + barrierCall, + LlamaTextToSpeechException.new, + freeOnly: [?context], + ); + } final details = api != null && task != null && task != nullptr ? _ttsLastError(api, task) : null; @@ -9971,6 +10310,7 @@ class _LlamaModelWrapper { }); void dispose() { IsolateShutdownReleases.current.release(pointer); + _calls.failures.forget(llama_model_get_vocab(pointer)); _calls.freeModel(pointer); } } diff --git a/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart b/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart index 15a26047d..327eee26a 100644 --- a/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart +++ b/lib/src/backends/llama_cpp/mtmd_chunk_eval.dart @@ -67,6 +67,28 @@ typedef _DecodeImageChunkDart = Pointer, ); +int _primaryDecodeImageChunk( + Pointer ctx, + Pointer lctx, + Pointer chunk, + Pointer encodedEmbd, + int nPast, + int seqId, + int nBatch, + Pointer newNPast, +) => mtmd_helper_decode_image_chunk( + ctx, + lctx, + chunk, + encodedEmbd, + nPast, + seqId, + nBatch, + newNPast, + nullptr, + nullptr, +); + /// The mtmd functions [evalMtmdChunksUntilCancelled] calls, resolved from one /// library. final class MtmdChunkEvalApi { @@ -89,13 +111,17 @@ final class MtmdChunkEvalApi { evalChunkSingle: mtmd_helper_eval_chunk_single, encodeChunk: mtmd_encode_chunk, outputEmbd: mtmd_get_output_embd, - decodeImageChunk: mtmd_helper_decode_image_chunk, + decodeImageChunk: _primaryDecodeImageChunk, ); /// Resolves every function from [library], or returns `null` if any symbol /// is missing. static MtmdChunkEvalApi? tryLoad(DynamicLibrary library) { try { + final decodeImageChunk = library + .lookupFunction<_DecodeImageChunkNative, _DecodeImageChunkDart>( + 'mtmd_helper_decode_image_chunk', + ); return MtmdChunkEvalApi( chunksSize: library.lookupFunction<_ChunksSizeNative, _ChunksSizeDart>( 'mtmd_input_chunks_size', @@ -117,10 +143,20 @@ final class MtmdChunkEvalApi { outputEmbd: library.lookupFunction<_OutputEmbdNative, _OutputEmbdDart>( 'mtmd_get_output_embd', ), - decodeImageChunk: library - .lookupFunction<_DecodeImageChunkNative, _DecodeImageChunkDart>( - 'mtmd_helper_decode_image_chunk', - ), + decodeImageChunk: + (ctx, lctx, chunk, encodedEmbd, nPast, seqId, nBatch, newNPast) => + decodeImageChunk( + ctx, + lctx, + chunk, + encodedEmbd, + nPast, + seqId, + nBatch, + newNPast, + nullptr, + nullptr, + ), ); } on ArgumentError { return null; @@ -136,7 +172,20 @@ final class MtmdChunkEvalApi { evalChunkSingle: exit.mtmdHelperEvalChunkSingle, encodeChunk: exit.mtmdEncodeChunk, outputEmbd: outputEmbd, - decodeImageChunk: exit.mtmdHelperDecodeImageChunk, + decodeImageChunk: + (ctx, lctx, chunk, encodedEmbd, nPast, seqId, nBatch, newNPast) => + exit.mtmdHelperDecodeImageChunk( + ctx, + lctx, + chunk, + encodedEmbd, + nPast, + seqId, + nBatch, + newNPast, + nullptr, + nullptr, + ), ); /// `mtmd_input_chunks_size`. @@ -172,7 +221,8 @@ final class MtmdChunkEvalApi { /// `mtmd_get_output_embd`. final Pointer Function(Pointer ctx) outputEmbd; - /// `mtmd_helper_decode_image_chunk`. + /// `mtmd_helper_decode_image_chunk` without a post-decode callback, whose + /// type differs between upstream and libllamadart. final int Function( Pointer ctx, Pointer lctx, @@ -182,8 +232,6 @@ final class MtmdChunkEvalApi { int seqId, int nBatch, Pointer newNPast, - mtmd_helper_post_decode_callback callback, - Pointer userData, ) decodeImageChunk; } @@ -277,8 +325,6 @@ MtmdChunkEvalFailure? evalMtmdChunksUntilCancelled( 0, nBatch, newNPast, - nullptr, - nullptr, ); } } else { diff --git a/lib/src/backends/llama_cpp/native_barrier_api.dart b/lib/src/backends/llama_cpp/native_barrier_api.dart new file mode 100644 index 000000000..ec1f712a3 --- /dev/null +++ b/lib/src/backends/llama_cpp/native_barrier_api.dart @@ -0,0 +1,690 @@ +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; + +import '../../core/exceptions.dart'; +import 'bindings.dart'; + +const _wrapperAsset = 'package:llamadart/llamadart_wrapper'; + +typedef _LastErrorNative = Pointer Function(); +typedef _ClearLastErrorNative = Void Function(); +typedef _SamplerAcceptNative = + Bool Function(Pointer, llama_token); +typedef _GrammarLazyPatternsNative = + Pointer Function( + Pointer, + Pointer, + Pointer, + Pointer>, + Size, + Pointer, + Size, + ); +typedef _TokenizeNative = + Int32 Function( + Pointer, + Pointer, + Int32, + Pointer, + Int32, + Bool, + Bool, + ); +typedef _TokenToPieceNative = + Int32 Function( + Pointer, + llama_token, + Pointer, + Int32, + Int32, + Bool, + ); +typedef _MemoryClearNative = Bool Function(llama_memory_t, Bool); +typedef _BitmapFromAudioNative = + Pointer Function(Size, Pointer); +typedef _BitmapFromBufNative = + Pointer Function( + Pointer, + Pointer, + Size, + ); +typedef _BitmapFromFileNative = + Pointer Function(Pointer, Pointer); +typedef _DevInitNative = + ggml_backend_t Function(ggml_backend_dev_t, Pointer); +typedef _DevMemoryNative = + Bool Function(ggml_backend_dev_t, Pointer, Pointer); +typedef _DevGetPropsNative = + Bool Function(ggml_backend_dev_t, Pointer); +typedef _AllocCtxTensorsNative = + ggml_backend_buffer_t Function(Pointer, ggml_backend_t); +typedef _TensorDataNative = + Bool Function(Pointer, Pointer, Size, Size); +typedef _SchedAllocGraphNative = + Bool Function(ggml_backend_sched_t, Pointer); +typedef _SchedSynchronizeNative = Bool Function(ggml_backend_sched_t); + +/// Builds the typed error of a native call that caught a C++ exception. +typedef NativeCallError = + LlamaException Function(String message, [dynamic details]); + +/// libllamadart's exception barrier, resolved from one library. +/// +/// llama.cpp reports some failures by throwing a C++ exception, which ends +/// the process when it crosses the C ABI into Dart. From `llamadart-native` +/// [minimumNativeRelease] every `llama_dart_` function that calls llama.cpp +/// catches it, records its message for the calling thread and returns a +/// failure value. These are the functions that release adds: the message +/// accessors, and wrappers for the upstream functions the service used to +/// call directly and that throw. +/// +/// Windows bundles export them from `llamadart.dll` rather than the default +/// `llama.dll` asset, so [tryResolve] resolves `@Native` declarations bound +/// to that asset on Windows. Elsewhere it resolves the generated bindings. +final class NativeBarrierApi { + /// Creates an API from resolved functions. + const NativeBarrierApi({ + required this.lastError, + required this.clearLastError, + required this.samplerAccept, + required this.samplerInitGrammarLazyPatterns, + required this.tokenize, + required this.tokenToPiece, + required this.memoryClear, + required this.mtmdBitmapInitFromAudio, + required this.mtmdBitmapInitFromBuf, + required this.mtmdBitmapInitFromFile, + required this.ggmlBackendDevInit, + required this.ggmlBackendDevMemory, + required this.ggmlBackendDevGetProps, + required this.ggmlBackendAllocCtxTensors, + required this.ggmlBackendTensorSet, + required this.ggmlBackendTensorGet, + required this.ggmlBackendSchedAllocGraph, + required this.ggmlBackendSchedSynchronize, + }); + + /// The oldest `llamadart-native` release that exports these functions. + static const String minimumNativeRelease = 'v0.6.0-1'; + + /// Resolves every function from the loaded runtime, or returns `null` when + /// it does not export all of them. + /// + /// [isWindows] selects the asset the functions are bound to. [symbol] + /// replaces that lookup: it returns the address of the function exported + /// under a name, and throws [ArgumentError] when there is none. + static NativeBarrierApi? tryResolve({ + required bool isWindows, + Pointer Function(String name)? symbol, + }) { + try { + return NativeBarrierApi._fromSymbols( + symbol ?? (name) => symbolAddress(name, isWindows: isWindows), + ); + } on ArgumentError { + return null; + } + } + + /// The address of the function the loaded runtime exports as [name], from + /// the asset [isWindows] selects; throws [ArgumentError] when it exports + /// none. + static Pointer symbolAddress( + String name, { + required bool isWindows, + }) => (isWindows ? _wrapperAssetSymbol : _bindingsSymbol)(name); + + // Every function is called through the address resolved here, so none can + // be bound without being part of the probe. + factory NativeBarrierApi._fromSymbols( + Pointer Function(String name) symbol, + ) { + Pointer> function(String name) => + symbol(name).cast(); + return NativeBarrierApi( + lastError: function<_LastErrorNative>( + 'llama_dart_last_error', + ).asFunction(), + clearLastError: function<_ClearLastErrorNative>( + 'llama_dart_clear_last_error', + ).asFunction(), + samplerAccept: function<_SamplerAcceptNative>( + 'llama_dart_sampler_accept', + ).asFunction(), + samplerInitGrammarLazyPatterns: function<_GrammarLazyPatternsNative>( + 'llama_dart_sampler_init_grammar_lazy_patterns', + ).asFunction(), + tokenize: function<_TokenizeNative>('llama_dart_tokenize').asFunction(), + tokenToPiece: function<_TokenToPieceNative>( + 'llama_dart_token_to_piece', + ).asFunction(), + memoryClear: function<_MemoryClearNative>( + 'llama_dart_memory_clear', + ).asFunction(), + mtmdBitmapInitFromAudio: function<_BitmapFromAudioNative>( + 'llama_dart_mtmd_bitmap_init_from_audio', + ).asFunction(), + mtmdBitmapInitFromBuf: function<_BitmapFromBufNative>( + 'llama_dart_mtmd_bitmap_init_from_buf', + ).asFunction(), + mtmdBitmapInitFromFile: function<_BitmapFromFileNative>( + 'llama_dart_mtmd_bitmap_init_from_file', + ).asFunction(), + ggmlBackendDevInit: function<_DevInitNative>( + 'llama_dart_ggml_backend_dev_init', + ).asFunction(), + ggmlBackendDevMemory: function<_DevMemoryNative>( + 'llama_dart_ggml_backend_dev_memory', + ).asFunction(), + ggmlBackendDevGetProps: function<_DevGetPropsNative>( + 'llama_dart_ggml_backend_dev_get_props', + ).asFunction(), + ggmlBackendAllocCtxTensors: function<_AllocCtxTensorsNative>( + 'llama_dart_ggml_backend_alloc_ctx_tensors', + ).asFunction(), + ggmlBackendTensorSet: function<_TensorDataNative>( + 'llama_dart_ggml_backend_tensor_set', + ).asFunction(), + ggmlBackendTensorGet: function<_TensorDataNative>( + 'llama_dart_ggml_backend_tensor_get', + ).asFunction(), + ggmlBackendSchedAllocGraph: function<_SchedAllocGraphNative>( + 'llama_dart_ggml_backend_sched_alloc_graph', + ).asFunction(), + ggmlBackendSchedSynchronize: function<_SchedSynchronizeNative>( + 'llama_dart_ggml_backend_sched_synchronize', + ).asFunction(), + ); + } + + /// `llama_dart_last_error`: the message of the exception the calling + /// thread's last call with a barrier caught, or `nullptr`. + final Pointer Function() lastError; + + /// `llama_dart_clear_last_error`. + final void Function() clearLastError; + + /// `llama_dart_sampler_accept`; `false` after a caught exception. + final bool Function(Pointer sampler, int token) samplerAccept; + + /// `llama_dart_sampler_init_grammar_lazy_patterns`; `nullptr` after a + /// caught exception and for a grammar that does not parse. + final Pointer Function( + Pointer vocab, + Pointer grammar, + Pointer grammarRoot, + Pointer> triggerPatterns, + int triggerPatternCount, + Pointer triggerTokens, + int triggerTokenCount, + ) + samplerInitGrammarLazyPatterns; + + /// `llama_dart_tokenize`; `LLAMA_DART_STATUS_EXCEPTION` after a caught + /// exception. + final int Function( + Pointer vocab, + Pointer text, + int textLength, + Pointer tokens, + int tokenCapacity, + bool addSpecial, + bool parseSpecial, + ) + tokenize; + + /// `llama_dart_token_to_piece`; `LLAMA_DART_STATUS_EXCEPTION` after a + /// caught exception. + final int Function( + Pointer vocab, + int token, + Pointer buffer, + int length, + int lstrip, + bool special, + ) + tokenToPiece; + + /// `llama_dart_memory_clear`; `false` after a caught exception. + final bool Function(llama_memory_t memory, bool data) memoryClear; + + /// `llama_dart_mtmd_bitmap_init_from_audio`. + final Pointer Function(int sampleCount, Pointer samples) + mtmdBitmapInitFromAudio; + + /// `llama_dart_mtmd_bitmap_init_from_buf`. + final Pointer Function( + Pointer ctx, + Pointer data, + int length, + ) + mtmdBitmapInitFromBuf; + + /// `llama_dart_mtmd_bitmap_init_from_file`. + final Pointer Function( + Pointer ctx, + Pointer path, + ) + mtmdBitmapInitFromFile; + + /// `llama_dart_ggml_backend_dev_init`. + final ggml_backend_t Function(ggml_backend_dev_t device, Pointer params) + ggmlBackendDevInit; + + /// `llama_dart_ggml_backend_dev_memory`; `false` with both outputs zero + /// after a caught exception. + final bool Function( + ggml_backend_dev_t device, + Pointer free, + Pointer total, + ) + ggmlBackendDevMemory; + + /// `llama_dart_ggml_backend_dev_get_props`; `false` with the properties + /// zeroed after a caught exception. + final bool Function( + ggml_backend_dev_t device, + Pointer props, + ) + ggmlBackendDevGetProps; + + /// `llama_dart_ggml_backend_alloc_ctx_tensors`. + final ggml_backend_buffer_t Function( + Pointer ctx, + ggml_backend_t backend, + ) + ggmlBackendAllocCtxTensors; + + /// `llama_dart_ggml_backend_tensor_set`; `false` after a caught exception. + final bool Function( + Pointer tensor, + Pointer data, + int offset, + int size, + ) + ggmlBackendTensorSet; + + /// `llama_dart_ggml_backend_tensor_get`; `false` after a caught exception. + final bool Function( + Pointer tensor, + Pointer data, + int offset, + int size, + ) + ggmlBackendTensorGet; + + /// `llama_dart_ggml_backend_sched_alloc_graph`. + final bool Function(ggml_backend_sched_t sched, Pointer graph) + ggmlBackendSchedAllocGraph; + + /// `llama_dart_ggml_backend_sched_synchronize`; `false` after a caught + /// exception. + final bool Function(ggml_backend_sched_t sched) ggmlBackendSchedSynchronize; + + /// The message of the C++ exception the calling thread's last call with a + /// barrier caught, or `null` when it caught none. + /// + /// The message is per thread, so read it in the same synchronous run as + /// the call: an isolate can resume on another thread after an `await`. + String? caughtException() { + final message = lastError(); + return message == nullptr ? null : message.cast().toDartString(); + } +} + +/// Turns the C++ exceptions libllamadart catches into typed errors, and +/// remembers which native objects a failed call left only fit to be freed. +/// +/// The native contract (`src/llama_dart_wrapper.h` in `llamadart-native`) +/// leaves a llama or mtmd context in no defined state after a call on it +/// caught an exception. On Windows that holds for every object of the call: +/// llama.cpp's own libraries assume their `extern "C"` functions never throw, +/// so an unwinding exception can skip their cleanups. +final class NativeCallFailures { + /// Reads caught exceptions from [barrier]; without one, nothing is ever + /// reported. + NativeCallFailures(this.barrier, {required this.isWindows}); + + /// The exception barrier, or `null` on a runtime older than + /// [NativeBarrierApi.minimumNativeRelease]. + final NativeBarrierApi? barrier; + + /// Whether the Windows rule applies: every object of a failed call is + /// free-only. + final bool isWindows; + + final Map _freeOnly = {}; + + /// Throws the [error] of the barrier call [call] when that call, which has + /// just returned on this thread, caught a C++ exception. + /// + /// The error's details are the exception's message as libllamadart recorded + /// it. [freeOnly] names the objects the failure leaves free-only on every + /// platform, [windowsFreeOnly] the ones only the Windows rule adds. + void throwIfCaught( + String call, + NativeCallError error, { + List> freeOnly = const [], + List> windowsFreeOnly = const [], + }) { + final message = barrier?.caughtException(); + if (message == null) return; + for (final object in [...freeOnly, if (isWindows) ...windowsFreeOnly]) { + if (object != nullptr) _freeOnly[object.address] = call; + } + throw error('llama.cpp raised an exception in $call.', message); + } + + /// Throws [LlamaStateException] when a failed call left [object], described + /// as [what], free-only. + void ensureUsable(Pointer object, String what) { + final call = _freeOnly[object.address]; + if (call == null) return; + throw LlamaStateException( + '$what is unusable after a llama.cpp exception in $call. Unload the ' + 'model and load it again.', + ); + } + + /// Forgets [object], which is about to be freed: its address may be reused. + void forget(Pointer object) => _freeOnly.remove(object.address); +} + +Pointer _bindingsSymbol(String symbol) => switch (symbol) { + 'llama_dart_last_error' => Native.addressOf>( + llama_dart_last_error, + ), + 'llama_dart_clear_last_error' => + Native.addressOf>( + llama_dart_clear_last_error, + ), + 'llama_dart_sampler_accept' => + Native.addressOf>( + llama_dart_sampler_accept, + ), + 'llama_dart_sampler_init_grammar_lazy_patterns' => + Native.addressOf>( + llama_dart_sampler_init_grammar_lazy_patterns, + ), + 'llama_dart_tokenize' => Native.addressOf>( + llama_dart_tokenize, + ), + 'llama_dart_token_to_piece' => + Native.addressOf>( + llama_dart_token_to_piece, + ), + 'llama_dart_memory_clear' => + Native.addressOf>( + llama_dart_memory_clear, + ), + 'llama_dart_mtmd_bitmap_init_from_audio' => + Native.addressOf>( + llama_dart_mtmd_bitmap_init_from_audio, + ), + 'llama_dart_mtmd_bitmap_init_from_buf' => + Native.addressOf>( + llama_dart_mtmd_bitmap_init_from_buf, + ), + 'llama_dart_mtmd_bitmap_init_from_file' => + Native.addressOf>( + llama_dart_mtmd_bitmap_init_from_file, + ), + 'llama_dart_ggml_backend_dev_init' => + Native.addressOf>( + llama_dart_ggml_backend_dev_init, + ), + 'llama_dart_ggml_backend_dev_memory' => + Native.addressOf>( + llama_dart_ggml_backend_dev_memory, + ), + 'llama_dart_ggml_backend_dev_get_props' => + Native.addressOf>( + llama_dart_ggml_backend_dev_get_props, + ), + 'llama_dart_ggml_backend_alloc_ctx_tensors' => + Native.addressOf>( + llama_dart_ggml_backend_alloc_ctx_tensors, + ), + 'llama_dart_ggml_backend_tensor_set' => + Native.addressOf>( + llama_dart_ggml_backend_tensor_set, + ), + 'llama_dart_ggml_backend_tensor_get' => + Native.addressOf>( + llama_dart_ggml_backend_tensor_get, + ), + 'llama_dart_ggml_backend_sched_alloc_graph' => + Native.addressOf>( + llama_dart_ggml_backend_sched_alloc_graph, + ), + 'llama_dart_ggml_backend_sched_synchronize' => + Native.addressOf>( + llama_dart_ggml_backend_sched_synchronize, + ), + _ => throw ArgumentError.value(symbol, 'symbol', 'not bound'), +}; + +Pointer _wrapperAssetSymbol(String symbol) => switch (symbol) { + 'llama_dart_last_error' => Native.addressOf>( + _wrapperLastError, + ), + 'llama_dart_clear_last_error' => + Native.addressOf>( + _wrapperClearLastError, + ), + 'llama_dart_sampler_accept' => + Native.addressOf>( + _wrapperSamplerAccept, + ), + 'llama_dart_sampler_init_grammar_lazy_patterns' => + Native.addressOf>( + _wrapperGrammarLazyPatterns, + ), + 'llama_dart_tokenize' => Native.addressOf>( + _wrapperTokenize, + ), + 'llama_dart_token_to_piece' => + Native.addressOf>(_wrapperTokenToPiece), + 'llama_dart_memory_clear' => + Native.addressOf>(_wrapperMemoryClear), + 'llama_dart_mtmd_bitmap_init_from_audio' => + Native.addressOf>( + _wrapperBitmapFromAudio, + ), + 'llama_dart_mtmd_bitmap_init_from_buf' => + Native.addressOf>( + _wrapperBitmapFromBuf, + ), + 'llama_dart_mtmd_bitmap_init_from_file' => + Native.addressOf>( + _wrapperBitmapFromFile, + ), + 'llama_dart_ggml_backend_dev_init' => + Native.addressOf>(_wrapperDevInit), + 'llama_dart_ggml_backend_dev_memory' => + Native.addressOf>(_wrapperDevMemory), + 'llama_dart_ggml_backend_dev_get_props' => + Native.addressOf>(_wrapperDevGetProps), + 'llama_dart_ggml_backend_alloc_ctx_tensors' => + Native.addressOf>( + _wrapperAllocCtxTensors, + ), + 'llama_dart_ggml_backend_tensor_set' => + Native.addressOf>(_wrapperTensorSet), + 'llama_dart_ggml_backend_tensor_get' => + Native.addressOf>(_wrapperTensorGet), + 'llama_dart_ggml_backend_sched_alloc_graph' => + Native.addressOf>( + _wrapperSchedAllocGraph, + ), + 'llama_dart_ggml_backend_sched_synchronize' => + Native.addressOf>( + _wrapperSchedSynchronize, + ), + _ => throw ArgumentError.value(symbol, 'symbol', 'not bound'), +}; + +@Native<_LastErrorNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_last_error', +) +external Pointer _wrapperLastError(); + +@Native<_ClearLastErrorNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_clear_last_error', +) +external void _wrapperClearLastError(); + +@Native<_SamplerAcceptNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_sampler_accept', +) +external bool _wrapperSamplerAccept(Pointer sampler, int token); + +@Native<_GrammarLazyPatternsNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_sampler_init_grammar_lazy_patterns', +) +external Pointer _wrapperGrammarLazyPatterns( + Pointer vocab, + Pointer grammar, + Pointer grammarRoot, + Pointer> triggerPatterns, + int triggerPatternCount, + Pointer triggerTokens, + int triggerTokenCount, +); + +@Native<_TokenizeNative>(assetId: _wrapperAsset, symbol: 'llama_dart_tokenize') +external int _wrapperTokenize( + Pointer vocab, + Pointer text, + int textLength, + Pointer tokens, + int tokenCapacity, + bool addSpecial, + bool parseSpecial, +); + +@Native<_TokenToPieceNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_token_to_piece', +) +external int _wrapperTokenToPiece( + Pointer vocab, + int token, + Pointer buffer, + int length, + int lstrip, + bool special, +); + +@Native<_MemoryClearNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_memory_clear', +) +external bool _wrapperMemoryClear(llama_memory_t memory, bool data); + +@Native<_BitmapFromAudioNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_mtmd_bitmap_init_from_audio', +) +external Pointer _wrapperBitmapFromAudio( + int sampleCount, + Pointer samples, +); + +@Native<_BitmapFromBufNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_mtmd_bitmap_init_from_buf', +) +external Pointer _wrapperBitmapFromBuf( + Pointer ctx, + Pointer data, + int length, +); + +@Native<_BitmapFromFileNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_mtmd_bitmap_init_from_file', +) +external Pointer _wrapperBitmapFromFile( + Pointer ctx, + Pointer path, +); + +@Native<_DevInitNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_dev_init', +) +external ggml_backend_t _wrapperDevInit( + ggml_backend_dev_t device, + Pointer params, +); + +@Native<_DevMemoryNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_dev_memory', +) +external bool _wrapperDevMemory( + ggml_backend_dev_t device, + Pointer free, + Pointer total, +); + +@Native<_DevGetPropsNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_dev_get_props', +) +external bool _wrapperDevGetProps( + ggml_backend_dev_t device, + Pointer props, +); + +@Native<_AllocCtxTensorsNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_alloc_ctx_tensors', +) +external ggml_backend_buffer_t _wrapperAllocCtxTensors( + Pointer ctx, + ggml_backend_t backend, +); + +@Native<_TensorDataNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_tensor_set', +) +external bool _wrapperTensorSet( + Pointer tensor, + Pointer data, + int offset, + int size, +); + +@Native<_TensorDataNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_tensor_get', +) +external bool _wrapperTensorGet( + Pointer tensor, + Pointer data, + int offset, + int size, +); + +@Native<_SchedAllocGraphNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_sched_alloc_graph', +) +external bool _wrapperSchedAllocGraph( + ggml_backend_sched_t sched, + Pointer graph, +); + +@Native<_SchedSynchronizeNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_ggml_backend_sched_synchronize', +) +external bool _wrapperSchedSynchronize(ggml_backend_sched_t sched); diff --git a/lib/src/backends/llama_cpp/vulkan_device_probe.dart b/lib/src/backends/llama_cpp/vulkan_device_probe.dart new file mode 100644 index 000000000..b2c3a1314 --- /dev/null +++ b/lib/src/backends/llama_cpp/vulkan_device_probe.dart @@ -0,0 +1,255 @@ +import 'dart:convert'; +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; + +import 'bindings.dart'; + +const _wrapperAsset = 'package:llamadart/llamadart_wrapper'; + +typedef _DeviceCountNative = Int32 Function(); +typedef _DeviceInfoNative = + Int32 Function(Int32, Pointer); + +/// One Vulkan device as libllamadart reads it from the Vulkan loader. +final class VulkanDeviceFacts { + /// Creates the facts of device [index]. + const VulkanDeviceFacts({ + required this.index, + required this.name, + required this.instanceApiVersion, + required this.apiVersion, + required this.subgroupSize, + }); + + /// Vulkan 1.2 as `VK_MAKE_API_VERSION` encodes it. + static const int vulkan12 = 1 << 22 | 2 << 12; + + /// The index ggml-vulkan gives the device: `Vulkan0` is index 0. + final int index; + + /// `VkPhysicalDeviceProperties.deviceName`. + final String name; + + /// `vkEnumerateInstanceVersion`: the Vulkan loader's version. + final int instanceApiVersion; + + /// `VkPhysicalDeviceProperties.apiVersion`: the driver's version. + final int apiVersion; + + /// `VkPhysicalDeviceSubgroupProperties.subgroupSize`, or 0 when the loader + /// or the driver is older than Vulkan 1.1 and cannot report it. + final int subgroupSize; + + /// Whether ggml-vulkan can drive the device. + /// + /// ggml-vulkan registers no device when the loader is below Vulkan 1.2 + /// (`ggml_vk_instance_init`). It does register a device whose driver is + /// below 1.2, then reads `VkPhysicalDeviceVulkan12Features` the driver + /// never filled in and calls Vulkan 1.2 functions it does not have. + bool get meetsVulkan12 => + instanceApiVersion >= vulkan12 && apiVersion >= vulkan12; + + /// Whether ggml-vulkan's small matmul tile gives wrong results on the + /// device (https://github.com/ggml-org/llama.cpp/issues/28637). + /// + /// The small tiles split a 32-row block between `max(size, 32) / + /// max(size, 8)` warps, but llama.cpp v0.6.0 gives each warp 8 rows only + /// for a subgroup size of exactly 8 and all 32 rows otherwise + /// (`s_warptile_wm` in `ggml_vk_load_shaders`). That is one warp too many + /// at 16, where it was found, and at every size below 8. An unknown size + /// counts as affected. + bool get hasSmallMatmulTileDefect => subgroupSize != 8 && subgroupSize < 32; + + /// `major.minor` of an encoded Vulkan [version]. + static String formatApiVersion(int version) => + '${(version >> 22) & 0x7f}.${(version >> 12) & 0x3ff}'; + + @override + String toString() => + 'Vulkan$index "$name" (API ${formatApiVersion(apiVersion)}, loader ' + '${formatApiVersion(instanceApiVersion)}, subgroup size $subgroupSize)'; +} + +/// What libllamadart reports about the Vulkan devices ggml-vulkan registers. +final class VulkanDeviceProbe { + /// The probe listed [devices]. + const VulkanDeviceProbe.devices(List this.devices) + : unavailableReason = null; + + /// The probe could not list the devices, for [unavailableReason]. + const VulkanDeviceProbe.unavailable(String this.unavailableReason) + : devices = null; + + /// The devices in ggml-vulkan's order, or `null` when they are unknown. + final List? devices; + + /// Why [devices] is `null`. + final String? unavailableReason; +} + +/// libllamadart's Vulkan device facts, resolved from one library. +/// +/// Reading them makes the Vulkan loader load the system's GPU drivers into +/// the process, and a driver that crashes there cannot be caught. Probe only +/// while the Vulkan backend is in use or about to be. +/// +/// Windows bundles export the functions from `llamadart.dll` rather than the +/// default `llama.dll` asset, so [tryResolve] resolves `@Native` declarations +/// bound to that asset on Windows. Elsewhere it resolves the generated +/// bindings. +final class VulkanDeviceInfoApi { + /// Creates an API from resolved functions. + const VulkanDeviceInfoApi({ + required this.getDeviceCount, + required this.getDeviceInfo, + }); + + /// The oldest `llamadart-native` release that exports these functions. + static const String minimumNativeRelease = 'v0.6.0-1'; + + /// Resolves both functions from the loaded runtime, or returns `null` when + /// it does not export them. + /// + /// [isWindows] selects the asset the functions are bound to. [symbol] + /// replaces that lookup: it returns the address of the function exported + /// under a name, and throws [ArgumentError] when there is none. + static VulkanDeviceInfoApi? tryResolve({ + required bool isWindows, + Pointer Function(String name)? symbol, + }) { + final lookup = + symbol ?? (name) => symbolAddress(name, isWindows: isWindows); + try { + return VulkanDeviceInfoApi( + getDeviceCount: lookup( + 'llama_dart_vulkan_get_device_count', + ).cast>().asFunction(), + getDeviceInfo: lookup( + 'llama_dart_vulkan_get_device_info', + ).cast>().asFunction(), + ); + } on ArgumentError { + return null; + } + } + + /// The address of the function the loaded runtime exports as [name], from + /// the asset [isWindows] selects; throws [ArgumentError] when it exports + /// none. + static Pointer symbolAddress( + String name, { + required bool isWindows, + }) => (isWindows ? _wrapperAssetSymbol : _bindingsSymbol)(name); + + /// Reads the devices from the loaded runtime; unavailable, with the + /// release that is needed, when it does not export the functions. + static VulkanDeviceProbe probeRuntime({required bool isWindows}) { + final api = tryResolve(isWindows: isWindows); + return api == null + ? const VulkanDeviceProbe.unavailable( + 'the loaded llama.cpp runtime does not export ' + 'llama_dart_vulkan_get_device_count (llamadart-native ' + '$minimumNativeRelease or later is needed)', + ) + : api.probe(); + } + + /// `llama_dart_vulkan_get_device_count`: the number of devices, or a + /// negative `llama_dart_vulkan_status`. + final int Function() getDeviceCount; + + /// `llama_dart_vulkan_get_device_info`: a `llama_dart_vulkan_status`. + final int Function(int index, Pointer info) + getDeviceInfo; + + /// Lists the devices; unavailable when the loader cannot be queried or a + /// device cannot be described. + VulkanDeviceProbe probe() { + final count = getDeviceCount(); + if (count < 0) { + return VulkanDeviceProbe.unavailable( + 'llama_dart_vulkan_get_device_count returned ${_statusName(count)}', + ); + } + final info = calloc(); + try { + final devices = []; + for (var index = 0; index < count; index++) { + info.ref.struct_size = sizeOf(); + final status = getDeviceInfo(index, info); + if (status != 0) { + return VulkanDeviceProbe.unavailable( + 'llama_dart_vulkan_get_device_info($index) returned ' + '${_statusName(status)}', + ); + } + devices.add( + VulkanDeviceFacts( + index: index, + name: _deviceName(info.ref), + instanceApiVersion: info.ref.instance_api_version, + apiVersion: info.ref.api_version, + subgroupSize: info.ref.subgroup_size, + ), + ); + } + return VulkanDeviceProbe.devices(List.unmodifiable(devices)); + } finally { + calloc.free(info); + } + } +} + +String _deviceName(llama_dart_vulkan_device_info info) { + const capacity = 256; + final bytes = []; + for (var i = 0; i < capacity; i++) { + final byte = info.device_name[i] & 0xff; + if (byte == 0) break; + bytes.add(byte); + } + return utf8.decode(bytes, allowMalformed: true); +} + +String _statusName(int status) { + for (final known in llama_dart_vulkan_status.values) { + if (known.value == status) return known.name; + } + return 'status $status'; +} + +Pointer _bindingsSymbol(String symbol) => switch (symbol) { + 'llama_dart_vulkan_get_device_count' => + Native.addressOf>( + llama_dart_vulkan_get_device_count, + ), + 'llama_dart_vulkan_get_device_info' => + Native.addressOf>( + llama_dart_vulkan_get_device_info, + ), + _ => throw ArgumentError.value(symbol, 'symbol', 'not bound'), +}; + +Pointer _wrapperAssetSymbol(String symbol) => switch (symbol) { + 'llama_dart_vulkan_get_device_count' => + Native.addressOf>(_wrapperDeviceCount), + 'llama_dart_vulkan_get_device_info' => + Native.addressOf>(_wrapperDeviceInfo), + _ => throw ArgumentError.value(symbol, 'symbol', 'not bound'), +}; + +@Native<_DeviceCountNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_vulkan_get_device_count', +) +external int _wrapperDeviceCount(); + +@Native<_DeviceInfoNative>( + assetId: _wrapperAsset, + symbol: 'llama_dart_vulkan_get_device_info', +) +external int _wrapperDeviceInfo( + int index, + Pointer info, +); diff --git a/lib/src/hook/native_release_pins.dart b/lib/src/hook/native_release_pins.dart index e6464ae05..231f8b8bc 100644 --- a/lib/src/hook/native_release_pins.dart +++ b/lib/src/hook/native_release_pins.dart @@ -5,7 +5,7 @@ library; /// `leehack/llamadart-native` release tag downloaded for the llama.cpp runtime. -const llamaCppTag = 'v0.5.0-2'; +const llamaCppTag = 'v0.6.0-1'; /// `leehack/litert-lm-native` release tag downloaded for the LiteRT-LM runtime. const liteRtLmReleaseTag = 'v0.18.0'; diff --git a/packages/llamadart_llama_cpp_flutter/CHANGELOG.md b/packages/llamadart_llama_cpp_flutter/CHANGELOG.md index 9a5669718..d82b3ba18 100644 --- a/packages/llamadart_llama_cpp_flutter/CHANGELOG.md +++ b/packages/llamadart_llama_cpp_flutter/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +* Updated Apple SwiftPM native pin to `leehack/llamadart-native@v0.6.0-1`. + ## 0.0.21 * Updated Apple SwiftPM native pin to `leehack/llamadart-native@v0.5.0-2`, diff --git a/packages/llamadart_llama_cpp_flutter/README.md b/packages/llamadart_llama_cpp_flutter/README.md index 10e72d89c..d1d16b5e6 100644 --- a/packages/llamadart_llama_cpp_flutter/README.md +++ b/packages/llamadart_llama_cpp_flutter/README.md @@ -21,7 +21,7 @@ dependencies: This package has no runtime Dart API of its own. Import `package:llamadart` normally from the core package and use `LlamaBackend()` / `LlamaEngine` there. -The Apple SwiftPM manifest pins `leehack/llamadart-native@v0.5.0-2`. +The Apple SwiftPM manifest pins `leehack/llamadart-native@v0.6.0-1`. Apps bound for the App Store should use this package: an Apple privacy manifest for the llama.cpp runtime ships inside this XCFramework, never in the diff --git a/packages/llamadart_llama_cpp_flutter/darwin/llamadart_llama_cpp_flutter/Package.swift b/packages/llamadart_llama_cpp_flutter/darwin/llamadart_llama_cpp_flutter/Package.swift index 000fb531f..3956dc7bf 100644 --- a/packages/llamadart_llama_cpp_flutter/darwin/llamadart_llama_cpp_flutter/Package.swift +++ b/packages/llamadart_llama_cpp_flutter/darwin/llamadart_llama_cpp_flutter/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent() let artifactsRoot = packageRoot.appendingPathComponent("Artifacts") -let llamaCppTag = "v0.5.0-2" +let llamaCppTag = "v0.6.0-1" func localArtifactPath(_ name: String) -> String? { let path = artifactsRoot.appendingPathComponent(name).path @@ -47,7 +47,7 @@ let package = Package( repository: "leehack/llamadart-native", artifactName: "llamadart-native-apple-xcframework-\(llamaCppTag).zip", tag: llamaCppTag, - checksum: "f903d355f3ba856571f46400fbc9787b6e4ab2d003d61dd6163b1527e000cb80" + checksum: "be84d0d37b27da8649396331fa84c469ac434aad2bbabd9688ebeacecb856c53" ), .target( name: "llamadart_llama_cpp_flutter", diff --git a/scripts/fetch_webgpu_bridge_assets.sh b/scripts/fetch_webgpu_bridge_assets.sh index 47126b187..11d324aab 100755 --- a/scripts/fetch_webgpu_bridge_assets.sh +++ b/scripts/fetch_webgpu_bridge_assets.sh @@ -4,7 +4,7 @@ set -euo pipefail ROOT_DIR="$(git rev-parse --show-toplevel)" OUT_DIR="${WEBGPU_BRIDGE_OUT_DIR:-$ROOT_DIR/example/chat_app/web/webgpu_bridge}" ASSETS_REPO="${WEBGPU_BRIDGE_ASSETS_REPO:-leehack/llama-web-bridge-assets}" -ASSETS_TAG="${WEBGPU_BRIDGE_ASSETS_TAG:-v0.1.54}" +ASSETS_TAG="${WEBGPU_BRIDGE_ASSETS_TAG:-v0.1.59}" CDN_BASE="${WEBGPU_BRIDGE_CDN_BASE:-https://cdn.jsdelivr.net/gh/${ASSETS_REPO}@${ASSETS_TAG}}" PATCH_SAFARI_COMPAT="${WEBGPU_BRIDGE_PATCH_SAFARI_COMPAT:-1}" MIN_SAFARI_VERSION="${WEBGPU_BRIDGE_MIN_SAFARI_VERSION:-170400}" @@ -21,7 +21,7 @@ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then Downloads prebuilt WebGPU bridge assets into the chat_app web directory. Default source: - https://cdn.jsdelivr.net/gh/leehack/llama-web-bridge-assets@v0.1.54 + https://cdn.jsdelivr.net/gh/leehack/llama-web-bridge-assets@v0.1.59 Environment variables: WEBGPU_BRIDGE_ASSETS_REPO Asset repo in owner/repo format @@ -35,7 +35,7 @@ Usage: ./scripts/fetch_webgpu_bridge_assets.sh Examples: - WEBGPU_BRIDGE_ASSETS_TAG=v0.1.54 ./scripts/fetch_webgpu_bridge_assets.sh + WEBGPU_BRIDGE_ASSETS_TAG=v0.1.59 ./scripts/fetch_webgpu_bridge_assets.sh WEBGPU_BRIDGE_ASSETS_REPO=acme/llama-web-bridge-assets WEBGPU_BRIDGE_ASSETS_TAG=v2 ./scripts/fetch_webgpu_bridge_assets.sh USAGE exit 0 diff --git a/skills/llamadart-flutter-app/SKILL.md b/skills/llamadart-flutter-app/SKILL.md index 4a515121e..9dcf69363 100644 --- a/skills/llamadart-flutter-app/SKILL.md +++ b/skills/llamadart-flutter-app/SKILL.md @@ -166,9 +166,10 @@ or shipping runtimes the app does not use. through `llamadart_native_backends`. llama.cpp `ComputeDevice.auto` stays on the CPU there; Vulkan is experimental and device-dependent, so request `ComputeDevice.gpu` only on devices the app has validated. Leave - `ModelParams.microBatchSize` unset on Android Vulkan: a text prompt is then - decoded at most 8 tokens at a time, and a value above 32 returns wrong text - on some GPUs. The cap applies to text-prompt decoding only: it does not + `ModelParams.microBatchSize` unset on Android Vulkan: on a GPU whose + subgroup size is 16, below 8 or unreadable a text prompt is then decoded at + most 8 tokens at a time, and a value above 32 returns wrong text there. The + cap applies to text-prompt decoding only: it does not cover prompts with image or audio input, embeddings, decision models, text-to-speech, or speculative-decoding verification batches during generation, which can exceed 32 tokens, so speculative decoding can still 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 e016e8841..97750f048 100644 --- a/test/integration/backends/llama_cpp/native_symbol_integration_test.dart +++ b/test/integration/backends/llama_cpp/native_symbol_integration_test.dart @@ -9,6 +9,8 @@ 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/backends/llama_cpp/native_barrier_api.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; import 'package:llamadart/src/core/models/inference/model_params.dart'; import 'package:test/test.dart'; @@ -98,6 +100,32 @@ const _exitTeardownSymbols = [ 'llama_dart_mtmd_helper_decode_image_chunk', ]; +const _barrierSymbols = [ + 'llama_dart_last_error', + 'llama_dart_clear_last_error', + 'llama_dart_sampler_accept', + 'llama_dart_sampler_init_grammar_lazy_patterns', + 'llama_dart_tokenize', + 'llama_dart_token_to_piece', + 'llama_dart_memory_clear', + 'llama_dart_mtmd_bitmap_init_from_audio', + 'llama_dart_mtmd_bitmap_init_from_buf', + 'llama_dart_mtmd_bitmap_init_from_file', + 'llama_dart_ggml_backend_dev_init', + 'llama_dart_ggml_backend_dev_memory', + 'llama_dart_ggml_backend_dev_get_props', + 'llama_dart_ggml_backend_alloc_ctx_tensors', + 'llama_dart_ggml_backend_tensor_set', + 'llama_dart_ggml_backend_tensor_get', + 'llama_dart_ggml_backend_sched_alloc_graph', + 'llama_dart_ggml_backend_sched_synchronize', +]; + +const _vulkanDeviceSymbols = [ + 'llama_dart_vulkan_get_device_count', + 'llama_dart_vulkan_get_device_info', +]; + // Returns an enum, so ffigen binds it under a private name behind a wrapper. const _exitTeardownGraphComputeSymbol = 'llama_dart_ggml_backend_sched_graph_compute'; @@ -517,8 +545,8 @@ void main() { llama_model_quantize_default_params().max_buf_size, 8 * 1024 * 1024 * 1024, ); - expect(LLAMA_SESSION_VERSION, 10); - expect(LLAMA_STATE_SEQ_VERSION, 3); + expect(LLAMA_SESSION_VERSION, 11); + expect(LLAMA_STATE_SEQ_VERSION, 4); }); test('Verify speculative symbols are declared in generated bindings', () { @@ -625,6 +653,64 @@ void main() { } }); + test('Verify the pinned wrapper exports the exception barrier and the ' + 'Vulkan device facts the service resolves', () { + final bindingsSource = File( + 'lib/src/backends/llama_cpp/bindings.dart', + ).readAsStringSync(); + for (final symbol in [..._barrierSymbols, ..._vulkanDeviceSymbols]) { + expect( + _declaresExternalFunction(bindingsSource, symbol), + isTrue, + reason: symbol, + ); + } + + final wrapper = _llamadartWrapperLibraryFileOrNull(); + expect( + wrapper, + isNotNull, + reason: 'Expected the llama.cpp wrapper library.', + ); + // Resolved through the package first: a raw open of the wrapper cannot + // find its sibling DLLs on Windows until the runtime is loaded. + expect( + NativeBarrierApi.tryResolve(isWindows: Platform.isWindows), + isNotNull, + ); + expect( + VulkanDeviceInfoApi.tryResolve(isWindows: Platform.isWindows), + isNotNull, + ); + _expectDynamicLibraryExports(wrapper!, [ + ..._barrierSymbols, + ..._vulkanDeviceSymbols, + ]); + // Each name resolves to the wrapper's own export of that name, not to + // another function with the same signature. + final library = ffi.DynamicLibrary.open(wrapper.path); + for (final symbol in _barrierSymbols) { + expect( + NativeBarrierApi.symbolAddress( + symbol, + isWindows: Platform.isWindows, + ).address, + library.lookup(symbol).address, + reason: symbol, + ); + } + for (final symbol in _vulkanDeviceSymbols) { + expect( + VulkanDeviceInfoApi.symbolAddress( + symbol, + isWindows: Platform.isWindows, + ).address, + library.lookup(symbol).address, + reason: symbol, + ); + } + }); + test('Verify pinned mtmd context parameter layout in bindings', () { final bindingsSource = File( 'lib/src/backends/llama_cpp/bindings.dart', diff --git a/test/integration/native_exception_barrier_test.dart b/test/integration/native_exception_barrier_test.dart new file mode 100644 index 000000000..77f66c0b0 --- /dev/null +++ b/test/integration/native_exception_barrier_test.dart @@ -0,0 +1,88 @@ +@TestOn('vm') +@Timeout(Duration(minutes: 5)) +library; + +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:test/test.dart'; + +import '../support/synthetic_embedding_gguf.dart'; + +/// llama.cpp throws a C++ exception for the inputs below. Through +/// [LlamaEngine] and the worker isolate that is a typed error and the engine +/// keeps working; before `llamadart-native` `v0.6.0-1` it ended the process. +void main() { + late Directory dir; + late LlamaEngine engine; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('llamadart_barrier_engine_'); + final model = writeSyntheticLlamaGguf('${dir.path}/model.gguf'); + engine = LlamaEngine(LlamaBackend()); + await engine.loadModel( + model.path, + modelParams: const ModelParams(contextSize: 64, gpuLayers: 0), + ); + }); + + tearDownAll(() async { + await engine.dispose(); + dir.deleteSync(recursive: true); + }); + + test('detokenize throws LlamaInferenceException for a token outside the ' + 'vocabulary', () async { + await expectLater( + engine.detokenize([-1]), + throwsA( + isA().having( + (e) => e.message, + 'message', + startsWith( + 'llama.cpp raised an exception in llama_token_to_piece. (', + ), + ), + ), + ); + }, skip: Platform.isWindows ? 'leaves the model free-only there' : false); + + test('a lazy-grammar trigger pattern that is not a regular expression ' + 'fails the generation with LlamaInferenceException', () async { + await expectLater( + engine + .generate( + 'ab', + params: const GenerationParams( + maxTokens: 2, + grammar: 'root ::= "a"', + grammarLazy: true, + grammarTriggers: [ + GenerationGrammarTrigger.typed( + type: GrammarTriggerType.pattern, + value: '(', + ), + ], + ), + ) + .drain(), + throwsA( + isA().having( + (e) => e.message, + 'message', + startsWith( + 'llama.cpp raised an exception in ' + 'llama_sampler_init_grammar_lazy_patterns. (', + ), + ), + ), + ); + }, skip: Platform.isWindows ? 'leaves the model free-only there' : false); + + test('the engine still tokenizes and generates afterwards', () async { + expect(await engine.tokenize('ab'), isNotEmpty); + await engine + .generate('ab', params: const GenerationParams(maxTokens: 2)) + .drain(); + }); +} diff --git a/test/integration/state_persistence_test.dart b/test/integration/state_persistence_test.dart index a15564bd3..d5f8827b0 100644 --- a/test/integration/state_persistence_test.dart +++ b/test/integration/state_persistence_test.dart @@ -81,7 +81,8 @@ void main() async { ); }); - test('rejects v0.3.0 session headers and can reload a valid state', () async { + test('rejects the session version of llama.cpp v0.5.0 by name and can ' + 'reload a valid state', () async { final tokens = await engine.tokenize('Once upon a time'); await engine .generate( @@ -93,13 +94,23 @@ void main() async { expect(await engine.stateSaveFile(validPath, tokens: tokens), isTrue); final bytes = File(validPath).readAsBytesSync(); final header = ByteData.sublistView(bytes); - expect(header.getUint32(4, Endian.host), 10); - header.setUint32(4, 9, Endian.host); + expect(header.getUint32(4, Endian.host), 11); + // llamadart 0.11.x wrote version 10 with llama.cpp v0.5.0. + header.setUint32(4, 10, Endian.host); final oldPath = '${tmpDir.path}/old-version.bin'; File(oldPath).writeAsBytesSync(bytes); await expectLater( engine.stateLoadFile(oldPath, tokenCapacity: 256), - throwsA(isA()), + throwsA( + isA().having( + (e) => e.message, + 'message', + allOf( + contains('has llama.cpp session version 10'), + contains('this runtime reads version 11'), + ), + ), + ), ); final restored = await engine.stateLoadFile(validPath, tokenCapacity: 256); expect(restored.tokens, tokens); diff --git a/test/support/fake_mtmd.dart b/test/support/fake_mtmd.dart index da7cbc557..aabea0465 100644 --- a/test/support/fake_mtmd.dart +++ b/test/support/fake_mtmd.dart @@ -144,7 +144,7 @@ final class FakeMtmd { }, encodeChunk: (_, _) => throw StateError('unexpected mtmd call'), outputEmbd: (_) => throw StateError('unexpected mtmd call'), - decodeImageChunk: (_, _, _, _, _, _, _, _, _, _) => + decodeImageChunk: (_, _, _, _, _, _, _, _) => throw StateError('unexpected mtmd call'), ); diff --git a/test/support/fake_native_barrier.dart b/test/support/fake_native_barrier.dart new file mode 100644 index 000000000..d290d15f5 --- /dev/null +++ b/test/support/fake_native_barrier.dart @@ -0,0 +1,171 @@ +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/src/backends/llama_cpp/native_barrier_api.dart'; + +/// A [NativeBarrierApi] that stands in for libllamadart's exception barrier. +/// +/// Every function records its native name in [calls] and clears the last +/// error, as a function with a barrier does. A name in [throwing] then +/// "catches an exception": the function sets the last error to [message] and +/// returns its failure value. A name in [failing] returns the failure value +/// without an exception. Other calls go on to [real], or without one succeed +/// with [object], `true` or [count]. +final class FakeNativeBarrier { + /// Fails the calls named in [throwing] and [failing]; the others go on to + /// [real]. + FakeNativeBarrier({this.real}); + + /// The functions that do the work of a call that does not fail. + final NativeBarrierApi? real; + + /// Native names of the functions that catch an exception. + final Set throwing = {}; + + /// Native names of the functions that fail without an exception. + final Set failing = {}; + + /// The message of the exception a [throwing] function catches. + String message = 'fake exception'; + + /// What `llama_dart_tokenize` and `llama_dart_token_to_piece` return when + /// they succeed without [real]. + int count = 0; + + /// Native names of the calls made so far, in order. + final List calls = []; + + /// The pointer the creating functions return when they succeed without + /// [real]. + static final Pointer object = Pointer.fromAddress(0x7000); + + static const int _statusException = -2147483648; + + Pointer _lastError = nullptr; + + /// Sets the last error to [message], as a function of another API that + /// has a barrier does when it catches an exception. + void catchException([String? message]) { + clear(); + _lastError = (message ?? this.message).toNativeUtf8(); + } + + /// Clears the last error, as a function with a barrier does on entry. + void clear() { + if (_lastError != nullptr) malloc.free(_lastError); + _lastError = nullptr; + real?.clearLastError(); + } + + /// Frees the last error. + void dispose() => clear(); + + bool _succeeds(String name) { + calls.add(name); + clear(); + if (throwing.contains(name)) { + catchException(); + return false; + } + return !failing.contains(name); + } + + /// The fake functions. + late final NativeBarrierApi api = NativeBarrierApi( + lastError: () => _lastError != nullptr + ? _lastError.cast() + : real?.lastError() ?? nullptr, + clearLastError: clear, + samplerAccept: (sampler, token) => + _succeeds('llama_dart_sampler_accept') && + (real?.samplerAccept(sampler, token) ?? true), + samplerInitGrammarLazyPatterns: + ( + vocab, + grammar, + grammarRoot, + triggerPatterns, + triggerPatternCount, + triggerTokens, + triggerTokenCount, + ) => !_succeeds('llama_dart_sampler_init_grammar_lazy_patterns') + ? nullptr + : real?.samplerInitGrammarLazyPatterns( + vocab, + grammar, + grammarRoot, + triggerPatterns, + triggerPatternCount, + triggerTokens, + triggerTokenCount, + ) ?? + object.cast(), + tokenize: + ( + vocab, + text, + textLength, + tokens, + tokenCapacity, + addSpecial, + parseSpecial, + ) => !_succeeds('llama_dart_tokenize') + ? _statusException + : real?.tokenize( + vocab, + text, + textLength, + tokens, + tokenCapacity, + addSpecial, + parseSpecial, + ) ?? + count, + tokenToPiece: (vocab, token, buffer, length, lstrip, special) => + !_succeeds('llama_dart_token_to_piece') + ? _statusException + : real?.tokenToPiece(vocab, token, buffer, length, lstrip, special) ?? + count, + memoryClear: (memory, data) => + _succeeds('llama_dart_memory_clear') && + (real?.memoryClear(memory, data) ?? true), + mtmdBitmapInitFromAudio: (sampleCount, samples) => + _succeeds('llama_dart_mtmd_bitmap_init_from_audio') + ? object.cast() + : nullptr, + mtmdBitmapInitFromBuf: (ctx, data, length) => + _succeeds('llama_dart_mtmd_bitmap_init_from_buf') + ? object.cast() + : nullptr, + mtmdBitmapInitFromFile: (ctx, path) => + _succeeds('llama_dart_mtmd_bitmap_init_from_file') + ? object.cast() + : nullptr, + ggmlBackendDevInit: (device, params) => + !_succeeds('llama_dart_ggml_backend_dev_init') + ? nullptr + : real?.ggmlBackendDevInit(device, params) ?? object.cast(), + ggmlBackendDevMemory: (device, free, total) => + _succeeds('llama_dart_ggml_backend_dev_memory') && + (real?.ggmlBackendDevMemory(device, free, total) ?? true), + ggmlBackendDevGetProps: (device, props) => + _succeeds('llama_dart_ggml_backend_dev_get_props') && + (real?.ggmlBackendDevGetProps(device, props) ?? true), + ggmlBackendAllocCtxTensors: (ctx, backend) => + !_succeeds('llama_dart_ggml_backend_alloc_ctx_tensors') + ? nullptr + : real?.ggmlBackendAllocCtxTensors(ctx, backend) ?? object.cast(), + ggmlBackendTensorSet: (tensor, data, offset, size) => + _succeeds('llama_dart_ggml_backend_tensor_set') && + (real?.ggmlBackendTensorSet(tensor, data, offset, size) ?? true), + ggmlBackendTensorGet: (tensor, data, offset, size) => + _succeeds('llama_dart_ggml_backend_tensor_get') && + (real?.ggmlBackendTensorGet(tensor, data, offset, size) ?? true), + ggmlBackendSchedAllocGraph: (sched, graph) => + _succeeds('llama_dart_ggml_backend_sched_alloc_graph') && + (real?.ggmlBackendSchedAllocGraph(sched, graph) ?? true), + ggmlBackendSchedSynchronize: (sched) => + _succeeds('llama_dart_ggml_backend_sched_synchronize') && + (real?.ggmlBackendSchedSynchronize(sched) ?? true), + ); +} diff --git a/test/support/recording_exit_teardown.dart b/test/support/recording_exit_teardown.dart index 7bb9a6fee..e3f4f0f39 100644 --- a/test/support/recording_exit_teardown.dart +++ b/test/support/recording_exit_teardown.dart @@ -33,6 +33,16 @@ final class RecordingExitTeardown { /// What the fake eval functions run; without it they evaluate nothing. final FakeMediaEval? evalMedia; + /// Called with the native name of each call before it is made. + void Function(String name)? onCall; + + /// Decides, for a call that reaches libllamadart or libmtmd, whether it + /// returns its failure value instead: `nullptr`, `false`, `0` for a size, + /// `LLAMA_TOKEN_NULL` for a sample, `GGML_STATUS_FAILED` for a graph compute + /// and `LLAMA_DART_STATUS_EXCEPTION` for another status. + /// `llama_dart_synchronize` then does nothing. + bool Function(String name)? fail; + /// Native names of the calls made so far, in order. final List calls = []; @@ -70,6 +80,15 @@ final class RecordingExitTeardown { ].join(); } + static const int _statusException = -2147483648; + + // Records [name] and returns whether the call goes on to do its work. + bool _proceeds(String name) { + onCall?.call(name); + calls.add(name); + return !(fail?.call(name) ?? false); + } + /// Forgets the calls recorded so far; [owned] and [freed] are kept. void clearCalls() { calls.clear(); @@ -83,7 +102,7 @@ final class RecordingExitTeardown { int nBatch, Pointer newNPast, ) { - calls.add(name); + if (!_proceeds(name)) return _statusException; final evalMedia = this.evalMedia; if (evalMedia == null) { newNPast.value = nPast; @@ -95,60 +114,59 @@ final class RecordingExitTeardown { /// The recording functions. late final ExitTeardownApi api = ExitTeardownApi( track: (object, free, stage) { - calls.add('llama_dart_exit_track'); + _proceeds('llama_dart_exit_track'); owned.add(object.address); return real.track(object, free, stage); }, untrack: (object) { - calls.add('llama_dart_exit_untrack'); + _proceeds('llama_dart_exit_untrack'); return real.untrack(object); }, free: (object) { - calls.add('llama_dart_exit_free'); + _proceeds('llama_dart_exit_free'); freed.add(object.address); real.free(object); }, freeAddress: real.freeAddress, modelLoadFromFile: (path, params) { - calls.add('llama_dart_model_load_from_file'); + if (!_proceeds('llama_dart_model_load_from_file')) return nullptr; final model = real.modelLoadFromFile(path, params); owned.add(model.address); return model; }, initFromModel: (model, params) { - calls.add('llama_dart_init_from_model'); + if (!_proceeds('llama_dart_init_from_model')) return nullptr; final context = real.initFromModel(model, params); owned.add(context.address); return context; }, mtmdInitFromFile: (path, model, params) { - calls.add('llama_dart_mtmd_init_from_file'); + if (!_proceeds('llama_dart_mtmd_init_from_file')) return nullptr; owned.add(projector.address); return projector; }, decode: (ctx, batch) { - calls.add('llama_dart_decode'); + final proceeds = _proceeds('llama_dart_decode'); decodedTokens.add(batch.n_tokens); - return real.decode(ctx, batch); + return proceeds ? real.decode(ctx, batch) : _statusException; }, encode: (ctx, batch) { - calls.add('llama_dart_encode'); + if (!_proceeds('llama_dart_encode')) return _statusException; return real.encode(ctx, batch); }, synchronize: (ctx) { - calls.add('llama_dart_synchronize'); - real.synchronize(ctx); + if (_proceeds('llama_dart_synchronize')) real.synchronize(ctx); }, samplerSample: (sampler, ctx, index) { - calls.add('llama_dart_sampler_sample'); + if (!_proceeds('llama_dart_sampler_sample')) return LLAMA_TOKEN_NULL; return real.samplerSample(sampler, ctx, index); }, stateSaveFile: (ctx, path, tokens, tokenCount) { - calls.add('llama_dart_state_save_file'); + if (!_proceeds('llama_dart_state_save_file')) return false; return real.stateSaveFile(ctx, path, tokens, tokenCount); }, stateLoadFile: (ctx, path, tokensOut, tokenCapacity, tokenCountOut) { - calls.add('llama_dart_state_load_file'); + if (!_proceeds('llama_dart_state_load_file')) return false; return real.stateLoadFile( ctx, path, @@ -158,27 +176,26 @@ final class RecordingExitTeardown { ); }, stateSeqGetSizeExt: (ctx, seqId, flags) { - calls.add('llama_dart_state_seq_get_size_ext'); + if (!_proceeds('llama_dart_state_seq_get_size_ext')) return 0; return real.stateSeqGetSizeExt(ctx, seqId, flags); }, stateSeqGetDataExt: (ctx, dst, size, seqId, flags) { - calls.add('llama_dart_state_seq_get_data_ext'); + if (!_proceeds('llama_dart_state_seq_get_data_ext')) return 0; return real.stateSeqGetDataExt(ctx, dst, size, seqId, flags); }, stateSeqSetDataExt: (ctx, src, size, seqId, flags) { - calls.add('llama_dart_state_seq_set_data_ext'); + if (!_proceeds('llama_dart_state_seq_set_data_ext')) return 0; return real.stateSeqSetDataExt(ctx, src, size, seqId, flags); }, adapterLoraInit: (model, path) { - calls.add('llama_dart_adapter_lora_init'); + if (!_proceeds('llama_dart_adapter_lora_init')) return nullptr; return real.adapterLoraInit(model, path); }, mtmdTokenize: (ctx, output, text, bitmaps, bitmapCount) { - calls.add('llama_dart_mtmd_tokenize'); - return 0; + return _proceeds('llama_dart_mtmd_tokenize') ? 0 : _statusException; }, mtmdEncodeChunk: (ctx, chunk) { - calls.add('llama_dart_mtmd_encode_chunk'); + _proceeds('llama_dart_mtmd_encode_chunk'); return 0; }, mtmdHelperEvalChunks: @@ -211,12 +228,14 @@ final class RecordingExitTeardown { callback, userData, ) { - calls.add('llama_dart_mtmd_helper_decode_image_chunk'); + _proceeds('llama_dart_mtmd_helper_decode_image_chunk'); newNPast.value = nPast; return 0; }, schedGraphCompute: (sched, graph) { - calls.add('llama_dart_ggml_backend_sched_graph_compute'); + if (!_proceeds('llama_dart_ggml_backend_sched_graph_compute')) { + return ggml_status.GGML_STATUS_FAILED.value; + } return real.schedGraphCompute(sched, graph); }, ); diff --git a/test/unit/backends/llama_cpp/decision_head_test.dart b/test/unit/backends/llama_cpp/decision_head_test.dart index 6108eecf6..1549baa88 100644 --- a/test/unit/backends/llama_cpp/decision_head_test.dart +++ b/test/unit/backends/llama_cpp/decision_head_test.dart @@ -10,15 +10,20 @@ import 'dart:typed_data'; import 'package:ffi/ffi.dart'; import 'package:llamadart/src/backends/isolate_shutdown_releases.dart'; import 'package:llamadart/src/backends/llama_cpp/bindings.dart'; +import 'package:llamadart/src/backends/backend.dart'; import 'package:llamadart/src/backends/llama_cpp/decision_head.dart'; +import 'package:llamadart/src/backends/llama_cpp/exit_teardown_api.dart'; import 'package:llamadart/src/backends/llama_cpp/ggml_graph_api.dart'; import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/backends/llama_cpp/native_barrier_api.dart'; import 'package:llamadart/src/backends/llama_cpp/safetensors.dart'; import 'package:llamadart/src/core/decision/decision_decoder.dart'; import 'package:llamadart/src/core/decision/decision_question.dart'; import 'package:llamadart/src/core/exceptions.dart'; import 'package:test/test.dart'; +import '../../../support/fake_native_barrier.dart'; +import '../../../support/recording_exit_teardown.dart'; import '../../../support/synthetic_decision_head.dart'; void main() { @@ -410,6 +415,201 @@ void main() { }); }); + group('DecisionHeadRuntime with the exception barrier', () { + late _GgmlLedger ledger; + late FakeNativeBarrier barrier; + late RecordingExitTeardown exit; + late SyntheticDecisionHead head; + + const devInit = 'llama_dart_ggml_backend_dev_init'; + const allocTensors = 'llama_dart_ggml_backend_alloc_ctx_tensors'; + const tensorSet = 'llama_dart_ggml_backend_tensor_set'; + const tensorGet = 'llama_dart_ggml_backend_tensor_get'; + const allocGraph = 'llama_dart_ggml_backend_sched_alloc_graph'; + const synchronize = 'llama_dart_ggml_backend_sched_synchronize'; + const compute = 'llama_dart_ggml_backend_sched_graph_compute'; + + setUp(() { + ledger = _GgmlLedger(); + final pinned = NativeBarrierApi.tryResolve( + isWindows: Platform.isWindows, + )!; + final api = ledger.api; + // The barrier's ggml functions create through the ledger, so it sees + // what a failed call leaves behind. + barrier = FakeNativeBarrier( + real: NativeBarrierApi( + lastError: pinned.lastError, + clearLastError: pinned.clearLastError, + samplerAccept: pinned.samplerAccept, + samplerInitGrammarLazyPatterns: pinned.samplerInitGrammarLazyPatterns, + tokenize: pinned.tokenize, + tokenToPiece: pinned.tokenToPiece, + memoryClear: pinned.memoryClear, + mtmdBitmapInitFromAudio: pinned.mtmdBitmapInitFromAudio, + mtmdBitmapInitFromBuf: pinned.mtmdBitmapInitFromBuf, + mtmdBitmapInitFromFile: pinned.mtmdBitmapInitFromFile, + ggmlBackendDevInit: api.devInit, + ggmlBackendDevMemory: pinned.ggmlBackendDevMemory, + ggmlBackendDevGetProps: pinned.ggmlBackendDevGetProps, + ggmlBackendAllocCtxTensors: api.allocCtxTensors, + ggmlBackendTensorSet: pinned.ggmlBackendTensorSet, + ggmlBackendTensorGet: pinned.ggmlBackendTensorGet, + ggmlBackendSchedAllocGraph: pinned.ggmlBackendSchedAllocGraph, + ggmlBackendSchedSynchronize: pinned.ggmlBackendSchedSynchronize, + ), + )..message = 'boom'; + addTearDown(barrier.dispose); + exit = RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + ); + head = SyntheticDecisionHead(d: 64, layers: 1, seed: 31); + }); + + DecisionHeadRuntime create() => DecisionHeadRuntime.create( + DecisionHeadWeights.read( + writeHead(head), + hiddenSize: head.d, + layers: head.layers, + ), + cpuThreads: 1, + opOffload: false, + api: ledger.api, + exitTeardown: exit.api, + failures: NativeCallFailures(barrier.api, isWindows: false), + ); + + BackendDecisionOutput run(DecisionHeadRuntime runtime) => runtime.run( + head.randomHidden(3), + 3, + DecisionQuestionType.choice, + Int32List.fromList([1, 2]), + ); + + // What create made and nothing freed: tracked objects are freed through + // the exit API, the rest through the ggml functions. + Set leaked() => ledger.live.difference(exit.freed.toSet()); + + Matcher caught(String call) => isA() + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in $call.', + ) + .having((e) => e.details, 'details', 'boom'); + + test('reaches the backends through the barrier and matches the ' + 'reference', () { + final runtime = create(); + addTearDown(runtime.dispose); + + expectMatchesReference( + runtime, + head, + tokens: 3, + questionType: DecisionQuestionType.choice, + markers: [1, 2], + ); + runtime.dispose(); + + expect(barrier.calls.toSet(), { + devInit, + allocTensors, + tensorSet, + allocGraph, + tensorGet, + synchronize, + }); + expect(leaked(), isEmpty); + }); + + for (final call in [devInit, allocTensors, tensorSet]) { + test('create throws the typed error of an exception in $call and ' + 'frees what it made', () { + barrier.throwing.add(call); + + expect( + create, + throwsA( + caught(call.replaceFirst('llama_dart_', '')), + ), + ); + expect(leaked(), isEmpty); + }); + } + + for (final call in [allocGraph, tensorSet, tensorGet]) { + test('a run that catches an exception in $call throws the typed error ' + 'and leaves the head unusable', () { + final runtime = create(); + addTearDown(runtime.dispose); + barrier.throwing.add(call); + final native = call.replaceFirst('llama_dart_', ''); + + expect( + () => run(runtime), + throwsA(caught(native)), + ); + + barrier.throwing.clear(); + expect( + () => run(runtime), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'The decision head is unusable after a llama.cpp exception in ' + '$native. Load it again.', + ), + ), + ); + runtime.dispose(); + expect(leaked(), isEmpty); + }); + } + + test('a graph compute that catches an exception throws the typed ' + 'error', () { + final runtime = create(); + addTearDown(runtime.dispose); + exit.fail = (name) { + if (name != compute) return false; + barrier.catchException('boom'); + return true; + }; + + expect( + () => run(runtime), + throwsA( + caught('ggml_backend_sched_graph_compute'), + ), + ); + exit.fail = null; + expect(() => run(runtime), throwsA(isA())); + }); + + test('a failure that caught nothing fails as before and leaves the head ' + 'usable', () { + final runtime = create(); + addTearDown(runtime.dispose); + barrier.failing.add(allocGraph); + + expect( + () => run(runtime), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('Could not allocate decision head compute buffers'), + ), + ), + ); + + barrier.failing.clear(); + expect(run(runtime).logits, hasLength(2)); + }); + }); + group('DecisionHeadWeights.read', () { Matcher modelError(List parts) => throwsA( isA().having( 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 09d6bbc56..d4f3bb677 100644 --- a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart +++ b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart @@ -9,8 +9,10 @@ import 'package:llamadart/src/backends/isolate_shutdown_releases.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:test/test.dart'; +import '../../../support/fake_native_barrier.dart'; import '../../../support/synthetic_embedding_gguf.dart'; // The exports a service on the tracked calls depends on. @@ -39,6 +41,8 @@ const _symbols = [ 'llama_dart_ggml_backend_sched_graph_compute', ]; +final _statusException = llama_dart_status.LLAMA_DART_STATUS_EXCEPTION.value; + // Runs the real llama.cpp runtime on the CPU. void main() { late Directory dir; @@ -213,22 +217,409 @@ void main() { symbol: exports.symbol, )!; final calls = LlamaCppObjectCalls.tracked(api); + final batch = llama_batch_init(1, 0, 1); + addTearDown(() => llama_batch_free(batch)); - expect(calls.loadModel, same(api.modelLoadFromFile)); - expect(calls.createContext, same(api.initFromModel)); - expect(calls.decode, same(api.decode)); - expect(calls.encode, same(api.encode)); - expect(calls.synchronize, same(api.synchronize)); - expect(calls.samplerSample, same(api.samplerSample)); - expect(calls.stateSaveFile, same(api.stateSaveFile)); - expect(calls.stateLoadFile, same(api.stateLoadFile)); - expect(calls.stateSeqGetSizeExt, same(api.stateSeqGetSizeExt)); - expect(calls.stateSeqGetDataExt, same(api.stateSeqGetDataExt)); - expect(calls.stateSeqSetDataExt, same(api.stateSeqSetDataExt)); - expect(calls.adapterLoraInit, same(api.adapterLoraInit)); + final members = { + 'llama_dart_model_load_from_file': () => + calls.loadModel(nullptr, llama_model_default_params()), + 'llama_dart_init_from_model': () => + calls.createContext(nullptr, llama_context_default_params()), + 'llama_dart_decode': () => calls.decode(nullptr, batch), + 'llama_dart_encode': () => calls.encode(nullptr, batch), + 'llama_dart_synchronize': () => calls.synchronize(nullptr), + 'llama_dart_sampler_sample': () => + calls.samplerSample(nullptr, nullptr, 0), + 'llama_dart_state_save_file': () => + calls.stateSaveFile(nullptr, nullptr, nullptr, 0), + 'llama_dart_state_load_file': () => + calls.stateLoadFile(nullptr, nullptr, nullptr, 0, nullptr), + 'llama_dart_state_seq_get_size_ext': () => + calls.stateSeqGetSizeExt(nullptr, 0, 0), + 'llama_dart_state_seq_get_data_ext': () => + calls.stateSeqGetDataExt(nullptr, nullptr, 0, 0, 0), + 'llama_dart_state_seq_set_data_ext': () => + calls.stateSeqSetDataExt(nullptr, nullptr, 0, 0, 0), + 'llama_dart_adapter_lora_init': () => + calls.adapterLoraInit(nullptr, nullptr), + }; + for (final MapEntry(key: name, value: call) in members.entries) { + exports.called.clear(); + call(); + expect(exports.called, [name]); + } + exports.called.clear(); calls.freeModel(nullptr); calls.freeContext(nullptr); expect(exports.called, ['llama_dart_exit_free', 'llama_dart_exit_free']); + expect(calls.failures.barrier, isNull); + }); + + group('tracked calls with the exception barrier', () { + late FakeNativeBarrier barrier; + late bool exitThrows; + + final model = Pointer.fromAddress(0x100); + final context = Pointer.fromAddress(0x200); + final vocab = Pointer.fromAddress(0x300); + final sampler = Pointer.fromAddress(0x400); + + setUp(() { + barrier = FakeNativeBarrier(); + exitThrows = true; + }); + tearDown(() => barrier.dispose()); + + // Every function returns its failure value, after catching an exception + // when [exitThrows] is set. + T fail(T failure) { + barrier.clear(); + if (exitThrows) barrier.catchException('boom'); + return failure; + } + + ExitTeardownApi failingExit() => ExitTeardownApi( + track: (_, _, _) => false, + untrack: (_) => false, + free: (_) {}, + freeAddress: nullptr, + modelLoadFromFile: (_, _) => fail(nullptr), + initFromModel: (_, _) => fail(nullptr), + mtmdInitFromFile: (_, _, _) => fail(nullptr), + decode: (_, _) => fail(_statusException), + encode: (_, _) => fail(_statusException), + synchronize: (_) => fail(null), + samplerSample: (_, _, _) => fail(LLAMA_TOKEN_NULL), + stateSaveFile: (_, _, _, _) => fail(false), + stateLoadFile: (_, _, _, _, _) => fail(false), + stateSeqGetSizeExt: (_, _, _) => fail(0), + stateSeqGetDataExt: (_, _, _, _, _) => fail(0), + stateSeqSetDataExt: (_, _, _, _, _) => fail(0), + adapterLoraInit: (_, _) => fail(nullptr), + mtmdTokenize: (_, _, _, _, _) => fail(_statusException), + mtmdEncodeChunk: (_, _) => fail(_statusException), + mtmdHelperEvalChunks: (_, _, _, _, _, _, _, _) => fail(_statusException), + mtmdHelperEvalChunkSingle: (_, _, _, _, _, _, _, _) => + fail(_statusException), + mtmdHelperDecodeImageChunk: (_, _, _, _, _, _, _, _, _, _) => + fail(_statusException), + schedGraphCompute: (_, _) => fail(-1), + ); + + LlamaCppObjectCalls tracked({bool isWindows = false}) => + LlamaCppObjectCalls.tracked( + failingExit(), + barrier: barrier.api, + isWindows: isWindows, + ); + + // Each call, the error it throws after a caught exception, and the + // objects that leaves free-only everywhere and on Windows only. + List< + ( + String, + void Function(LlamaCppObjectCalls, llama_batch), + TypeMatcher, + List>, + List>, + ) + > + cases() => [ + ( + 'llama_model_load_from_file', + (calls, _) => calls.loadModel(nullptr, llama_model_default_params()), + isA(), + [], + [], + ), + ( + 'llama_init_from_model', + (calls, _) => + calls.createContext(model, llama_context_default_params()), + isA(), + [], + [model], + ), + ( + 'llama_decode', + (calls, batch) => calls.decode(context, batch), + isA(), + [context], + [], + ), + ( + 'llama_encode', + (calls, batch) => calls.encode(context, batch), + isA(), + [context], + [], + ), + ( + 'llama_synchronize', + (calls, _) => calls.synchronize(context), + isA(), + [context], + [], + ), + ( + 'llama_sampler_sample', + (calls, _) => calls.samplerSample(sampler, context, -1), + isA(), + [], + [context], + ), + ( + 'llama_sampler_accept', + (calls, _) => calls.samplerAccept(sampler, 1), + isA(), + [], + [], + ), + ( + 'llama_sampler_init_grammar_lazy_patterns', + (calls, _) => calls.samplerInitGrammarLazyPatterns( + vocab, + nullptr, + nullptr, + nullptr, + 0, + nullptr, + 0, + ), + isA(), + [], + [vocab], + ), + ( + 'llama_tokenize', + (calls, _) => + calls.tokenize(vocab, nullptr, 0, nullptr, 0, false, false), + isA(), + [], + [vocab], + ), + ( + 'llama_token_to_piece', + (calls, _) => calls.tokenToPiece(vocab, 1, nullptr, 0, 0, false), + isA(), + [], + [vocab], + ), + ( + 'llama_memory_clear', + (calls, _) => calls.memoryClear(context, nullptr, true), + isA(), + [context], + [], + ), + ( + 'llama_state_save_file', + (calls, _) => calls.stateSaveFile(context, nullptr, nullptr, 0), + isA(), + [context], + [], + ), + ( + 'llama_state_load_file', + (calls, _) => + calls.stateLoadFile(context, nullptr, nullptr, 0, nullptr), + isA(), + [context], + [], + ), + ( + 'llama_state_seq_get_size_ext', + (calls, _) => calls.stateSeqGetSizeExt(context, 0, 0), + isA(), + [context], + [], + ), + ( + 'llama_state_seq_get_data_ext', + (calls, _) => calls.stateSeqGetDataExt(context, nullptr, 0, 0, 0), + isA(), + [context], + [], + ), + ( + 'llama_state_seq_set_data_ext', + (calls, _) => calls.stateSeqSetDataExt(context, nullptr, 0, 0, 0), + isA(), + [context], + [], + ), + ( + 'llama_adapter_lora_init', + (calls, _) => calls.adapterLoraInit(model, nullptr), + isA(), + [model], + [], + ), + ]; + + const barrierCalls = { + 'llama_sampler_accept', + 'llama_sampler_init_grammar_lazy_patterns', + 'llama_tokenize', + 'llama_token_to_piece', + 'llama_memory_clear', + }; + + for (final isWindows in [false, true]) { + test('a caught exception is the typed error of its call and leaves ' + 'the objects of the call free-only (Windows rule: $isWindows)', () { + final batch = llama_batch_init(1, 0, 1); + addTearDown(() => llama_batch_free(batch)); + barrier.throwing.addAll([ + for (final name in barrierCalls) + name.replaceFirst('llama_', 'llama_dart_'), + ]); + barrier.message = 'boom'; + + for (final (name, call, error, freeOnly, windowsFreeOnly) in cases()) { + final calls = tracked(isWindows: isWindows); + expect( + () => call(calls, batch), + throwsA( + error + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in $name.', + ) + .having((e) => e.details, 'details', 'boom'), + ), + reason: name, + ); + final expected = {...freeOnly, if (isWindows) ...windowsFreeOnly}; + for (final object in >[ + model, + context, + vocab, + sampler, + ]) { + expect( + () => calls.failures.ensureUsable(object, 'This object'), + expected.contains(object) + ? throwsA(isA()) + : returnsNormally, + reason: '$name ${object.address.toRadixString(16)}', + ); + } + } + }); + } + + test('a failure value without a caught exception is returned', () { + exitThrows = false; + barrier.failing.addAll([ + for (final name in barrierCalls) + name.replaceFirst('llama_', 'llama_dart_'), + ]); + final batch = llama_batch_init(1, 0, 1); + addTearDown(() => llama_batch_free(batch)); + final calls = tracked(isWindows: true); + + expect(calls.loadModel(nullptr, llama_model_default_params()), nullptr); + expect( + calls.createContext(model, llama_context_default_params()), + nullptr, + ); + expect(calls.decode(context, batch), _statusException); + expect(calls.encode(context, batch), _statusException); + calls.synchronize(context); + expect(calls.samplerSample(sampler, context, -1), LLAMA_TOKEN_NULL); + calls.samplerAccept(sampler, 1); + expect( + calls.samplerInitGrammarLazyPatterns( + vocab, + nullptr, + nullptr, + nullptr, + 0, + nullptr, + 0, + ), + nullptr, + ); + expect( + calls.tokenize(vocab, nullptr, 0, nullptr, 0, false, false), + _statusException, + ); + expect( + calls.tokenToPiece(vocab, 1, nullptr, 0, 0, false), + _statusException, + ); + calls.memoryClear(context, nullptr, true); + expect(calls.stateSaveFile(context, nullptr, nullptr, 0), isFalse); + expect( + calls.stateLoadFile(context, nullptr, nullptr, 0, nullptr), + isFalse, + ); + expect(calls.stateSeqGetSizeExt(context, 0, 0), 0); + expect(calls.stateSeqGetDataExt(context, nullptr, 0, 0, 0), 0); + expect(calls.stateSeqSetDataExt(context, nullptr, 0, 0, 0), 0); + expect(calls.adapterLoraInit(model, nullptr), nullptr); + for (final object in >[model, context, vocab]) { + calls.failures.ensureUsable(object, 'This object'); + } + }); + + test('routes the calls that used to reach an upstream function that ' + 'throws through the barrier wrappers', () { + final calls = tracked(); + + calls.samplerAccept(sampler, 1); + calls.samplerInitGrammarLazyPatterns( + vocab, + nullptr, + nullptr, + nullptr, + 0, + nullptr, + 0, + ); + calls.tokenize(vocab, nullptr, 0, nullptr, 0, false, false); + calls.tokenToPiece(vocab, 1, nullptr, 0, 0, false); + calls.memoryClear(context, nullptr, true); + + expect(barrier.calls, [ + 'llama_dart_sampler_accept', + 'llama_dart_sampler_init_grammar_lazy_patterns', + 'llama_dart_tokenize', + 'llama_dart_token_to_piece', + 'llama_dart_memory_clear', + ]); + }); + + test('freeing an object forgets that it was free-only', () { + final calls = tracked(); + final batch = llama_batch_init(1, 0, 1); + addTearDown(() => llama_batch_free(batch)); + expect( + () => calls.decode(context, batch), + throwsA(isA()), + ); + expect( + () => calls.adapterLoraInit(model, nullptr), + throwsA(isA()), + ); + + calls.freeContext(context); + calls.freeModel(model); + + calls.failures.ensureUsable(context, 'This context'); + calls.failures.ensureUsable(model, 'This model'); + }); + }); + + test('resolve adds the exception barrier of the pinned runtime', () { + final calls = LlamaCppObjectCalls.resolve(isWindows: Platform.isWindows); + + expect(calls.exit, isNotNull); + expect(calls.failures.barrier, isNotNull); + expect(calls.failures.isWindows, Platform.isWindows); + expect(LlamaCppObjectCalls.upstream.failures.barrier, isNull); }); test('frees a tracked object once, with the function it was tracked ' @@ -570,7 +961,7 @@ final class _RecordingExports { Int32, Int32, Pointer, - mtmd_helper_post_decode_callback, + LlamaDartPostDecodeCallback, Pointer, ) >.isolateLocal( @@ -583,7 +974,7 @@ final class _RecordingExports { int _, int _, Pointer _, - mtmd_helper_post_decode_callback _, + LlamaDartPostDecodeCallback _, Pointer _, ) => _record('llama_dart_mtmd_helper_decode_image_chunk', 0), exceptionalReturn: 0, diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart new file mode 100644 index 000000000..01f6f5d78 --- /dev/null +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart @@ -0,0 +1,747 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/src/backends/backend.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/backends/llama_cpp/native_barrier_api.dart'; +import 'package:llamadart/src/core/decision/decision_question.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/fake_native_barrier.dart'; +import '../../../support/recording_exit_teardown.dart'; +import '../../../support/synthetic_decision_head.dart'; +import '../../../support/synthetic_embedding_gguf.dart'; + +const _params = ModelParams(gpuLayers: 0, contextSize: 64); +const _greedy = GenerationParams(maxTokens: 4, temp: 0, topK: 1, seed: 1); + +const _load = 'llama_dart_model_load_from_file'; +const _create = 'llama_dart_init_from_model'; +const _decode = 'llama_dart_decode'; +const _encode = 'llama_dart_encode'; +const _sample = 'llama_dart_sampler_sample'; +const _synchronize = 'llama_dart_synchronize'; + +// A state file llamadart 0.11.1 wrote with llamadart-native v0.5.0-2 +// (llama.cpp v0.5.0, session version 10) for an empty context of the +// synthetic model. +const _v050StateFile = [ + 0x6e, 0x73, 0x67, 0x67, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, // + 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x6c, 0x6c, 0x61, 0x6d, 0x61, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, +]; + +TypeMatcher _caught( + String call, [ + Object details = 'boom', +]) => isA() + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in $call.', + ) + .having((e) => e.details, 'details', details); + +Matcher _unusable(String what, String call) => + isA().having( + (e) => e.message, + 'message', + '$what is unusable after a llama.cpp exception in $call. Unload the ' + 'model and load it again.', + ); + +// Runs the real llama.cpp runtime on the CPU. The exit API and the exception +// barrier fail the calls a test names, the first as a recorder around the +// real functions; everything else is the pinned runtime. +void main() { + late Directory dir; + late RecordingExitTeardown recorder; + late FakeNativeBarrier barrier; + late LlamaCppService service; + late int model; + late int context; + FakeMtmd? mtmd; + + // The exit-API calls that catch an exception, and the ones that fail + // without one. + final throwing = {}; + final failing = {}; + + void start({bool isWindows = false}) { + recorder = + RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + evalMedia: (context, nPast, nBatch, newNPast) => + mtmd!.evalMedia(context, nPast, nBatch, newNPast), + ) + // A function with a barrier clears the last error on entry; the + // exit registry functions have none. + ..onCall = (name) { + if (!name.startsWith('llama_dart_exit_')) barrier.clear(); + } + ..fail = (name) { + if (throwing.contains(name)) { + barrier.catchException('boom'); + return true; + } + return failing.contains(name); + }; + service = LlamaCppService( + objectCalls: LlamaCppObjectCalls.tracked( + recorder.api, + barrier: barrier.api, + isWindows: isWindows, + ), + )..initializeBackend(); + model = service.loadModel('${dir.path}/model.gguf', _params); + context = service.createContext(model, _params); + } + + setUp(() { + dir = Directory.systemTemp.createTempSync('llamadart_native_failure_'); + writeSyntheticLlamaGguf('${dir.path}/model.gguf'); + mtmd = null; + throwing.clear(); + failing.clear(); + barrier = FakeNativeBarrier( + real: NativeBarrierApi.tryResolve(isWindows: Platform.isWindows)!, + ); + }); + + tearDown(() { + throwing.clear(); + failing.clear(); + barrier.throwing.clear(); + barrier.failing.clear(); + service.dispose(); + final unfreed = recorder.unfreed; + for (final address in unfreed) { + recorder.real.untrack(Pointer.fromAddress(address)); + } + barrier.dispose(); + dir.deleteSync(recursive: true); + expect( + unfreed, + isEmpty, + reason: 'a failed call leaves nothing behind that dispose does not free', + ); + }); + + test('a prompt decode that throws is a typed error, and its context is ' + 'unusable until it is freed', () async { + start(); + throwing.add(_decode); + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_decode')), + ); + + throwing.clear(); + final unusable = _unusable('This context', 'llama_decode'); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(unusable), + ); + expect(() => service.embed(context, 'ab'), throwsA(unusable)); + expect( + () => service.stateSaveFile(context, '${dir.path}/state.bin', const []), + throwsA(unusable), + ); + expect( + () => service.stateLoadFile(context, '${dir.path}/state.bin', 8), + throwsA(unusable), + ); + expect( + () => service.scoreNextToken( + context, + 'ab', + candidates: const [], + topK: 1, + reusePromptPrefix: false, + ), + throwsA(unusable), + ); + + // The model is untouched: a new context of it generates. + service.freeContext(context); + context = service.createContext(model, _params); + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + }); + + test('a decode that throws during generation ends the stream with the ' + 'typed error', () async { + start(); + var decodes = 0; + final fail = recorder.fail!; + recorder.fail = (name) { + if (name == _decode && ++decodes == 2) { + barrier.catchException('boom'); + return true; + } + return fail(name); + }; + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_decode')), + ); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_unusable('This context', 'llama_decode')), + ); + }); + + test('a failed decode that caught nothing fails as before and leaves ' + 'the context usable', () async { + start(); + failing.add(_decode); + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA( + isA().having( + (e) => '$e', + 'text', + contains('Initial decode failed'), + ), + ), + ); + + failing.clear(); + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + }); + + for (final isWindows in [false, true]) { + test('a sample that throws is a typed error; the context stays usable ' + 'except under the Windows rule ($isWindows)', () async { + start(isWindows: isWindows); + throwing.add(_sample); + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_sampler_sample')), + ); + + throwing.clear(); + if (isWindows) { + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_unusable('This context', 'llama_sampler_sample')), + ); + } else { + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + } + }); + + test('a tokenize that throws is a typed error; the model stays usable ' + 'except under the Windows rule ($isWindows)', () async { + start(isWindows: isWindows); + barrier.throwing.add('llama_dart_tokenize'); + barrier.message = 'boom'; + + expect( + () => service.tokenize(model, 'ab', true), + throwsA(_caught('llama_tokenize')), + ); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA( + isWindows + ? _unusable('This model', 'llama_tokenize') + : _caught('llama_tokenize'), + ), + ); + + barrier.throwing.clear(); + if (isWindows) { + final unusable = _unusable('This model', 'llama_tokenize'); + expect(() => service.tokenize(model, 'ab', true), throwsA(unusable)); + expect( + () => service.detokenize(model, const [1], false), + throwsA(unusable), + ); + expect(() => service.createContext(model, _params), throwsA(unusable)); + // Loading the model again gives a usable one. + service.freeModel(model); + model = service.loadModel('${dir.path}/model.gguf', _params); + context = service.createContext(model, _params); + } + expect(service.tokenize(model, 'ab', true), isNotEmpty); + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + }); + } + + test('a token outside the vocabulary is a typed error from detokenize, ' + 'where llama.cpp used to end the process', () { + start(); + + expect( + () => service.detokenize(model, const [LLAMA_TOKEN_NULL], false), + throwsA( + _caught( + 'llama_token_to_piece', + isA().having((s) => s, 'message', isNotEmpty), + ), + ), + ); + if (!Platform.isWindows) { + expect(service.tokenize(model, 'ab', true), isNotEmpty); + } + }); + + test('a lazy-grammar trigger pattern that is not a regular expression is ' + 'a typed error, and the next generation runs', () async { + start(); + + await expectLater( + _generate( + service, + context, + 'ab', + _greedy.copyWith( + grammar: 'root ::= "a"', + grammarLazy: true, + grammarTriggers: const [ + GenerationGrammarTrigger.typed( + type: GrammarTriggerType.pattern, + value: '(', + ), + ], + ), + ), + throwsA( + _caught( + 'llama_sampler_init_grammar_lazy_patterns', + isA(), + ), + ), + ); + + if (!Platform.isWindows) { + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + } + }); + + test('an exception while the sampler accepts the prompt is a typed error, ' + 'and the next generation runs', () async { + start(); + barrier.throwing.add('llama_dart_sampler_accept'); + barrier.message = 'boom'; + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_sampler_accept')), + ); + + barrier.throwing.clear(); + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + }); + + test('an exception while the context memory clears is a typed error, and ' + 'the context is unusable', () async { + start(); + barrier.throwing.add('llama_dart_memory_clear'); + barrier.message = 'boom'; + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_memory_clear')), + ); + + barrier.throwing.clear(); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_unusable('This context', 'llama_memory_clear')), + ); + }); + + test('a synchronize that throws is a typed error, and the context is ' + 'unusable', () async { + start(); + throwing.add(_synchronize); + + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_caught('llama_synchronize')), + ); + + throwing.clear(); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_unusable('This context', 'llama_synchronize')), + ); + }); + + test('a state save or load that throws is a typed state error, and the ' + 'context is unusable', () { + start(); + final path = '${dir.path}/state.bin'; + expect(service.stateSaveFile(context, path, const [1, 2]), isTrue); + + throwing.add('llama_dart_state_load_file'); + expect( + () => service.stateLoadFile(context, path, 8), + throwsA(_caught('llama_state_load_file')), + ); + throwing.clear(); + expect( + () => service.stateLoadFile(context, path, 8), + throwsA(_unusable('This context', 'llama_state_load_file')), + ); + + service.freeContext(context); + context = service.createContext(model, _params); + throwing.add('llama_dart_state_save_file'); + expect( + () => service.stateSaveFile(context, path, const [1, 2]), + throwsA(_caught('llama_state_save_file')), + ); + }); + + test('a state file of llama.cpp v0.5.0 is refused with both session ' + 'versions, and the context still loads a current one', () { + start(); + final oldPath = '${dir.path}/v0.5.0.bin'; + File(oldPath).writeAsBytesSync(_v050StateFile); + final currentPath = '${dir.path}/current.bin'; + expect(service.stateSaveFile(context, currentPath, const [1, 2]), isTrue); + + expect(LlamaCppService.readSessionFileVersion(oldPath), 10); + expect( + LlamaCppService.readSessionFileVersion(currentPath), + LLAMA_SESSION_VERSION, + ); + expect( + () => service.stateLoadFile(context, oldPath, 8), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'The state file "$oldPath" has llama.cpp session version 10, and ' + 'this runtime reads version $LLAMA_SESSION_VERSION. A state ' + 'file does not carry over to a llama.cpp release that changed ' + 'the format: evaluate the prompt again and save a new one.', + ), + ), + ); + expect(service.stateLoadFile(context, currentPath, 8), [1, 2]); + }); + + test('a state file that is not a session file fails without a version', () { + start(); + final path = '${dir.path}/not-a-session.bin'; + File(path).writeAsStringSync('not a llama.cpp session file'); + final short = '${dir.path}/short.bin'; + File(short).writeAsBytesSync(const [0x6e, 0x73, 0x67, 0x67]); + + expect(LlamaCppService.readSessionFileVersion(path), isNull); + expect(LlamaCppService.readSessionFileVersion(short), isNull); + expect( + LlamaCppService.readSessionFileVersion('${dir.path}/missing.bin'), + isNull, + ); + expect( + () => service.stateLoadFile(context, path, 8), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('llama_state_load_file failed for'), + ), + ), + ); + }); + + for (final isWindows in [false, true]) { + test('a context creation that throws is a typed context error; the model ' + 'stays usable except under the Windows rule ($isWindows)', () { + start(isWindows: isWindows); + throwing.add(_create); + + expect( + () => service.createContext(model, _params), + throwsA(_caught('llama_init_from_model')), + ); + + throwing.clear(); + if (isWindows) { + expect( + () => service.createContext(model, _params), + throwsA(_unusable('This model', 'llama_init_from_model')), + ); + } else { + service.freeContext(service.createContext(model, _params)); + } + }); + } + + test('a model load that throws is a typed model error', () { + start(); + throwing.add(_load); + + expect( + () => service.loadModel('${dir.path}/model.gguf', _params), + throwsA(_caught('llama_model_load_from_file')), + ); + }); + + test('a LoRA load that throws is a typed model error, and the model is ' + 'unusable until it is loaded again', () { + start(); + final path = '${dir.path}/adapter.gguf'; + File(path).writeAsStringSync('not an adapter'); + throwing.add('llama_dart_adapter_lora_init'); + + expect( + () => service.handleLora(context, path, 1, 'set'), + throwsA(_caught('llama_adapter_lora_init')), + ); + + throwing.clear(); + final unusable = _unusable('This model', 'llama_adapter_lora_init'); + expect(() => service.tokenize(model, 'ab', true), throwsA(unusable)); + expect( + () => service.handleLora(context, path, 1, 'set'), + throwsA(unusable), + ); + service.freeModel(model); + model = service.loadModel('${dir.path}/model.gguf', _params); + expect(service.tokenize(model, 'ab', true), isNotEmpty); + }); + + group('with a projector', () { + late int projector; + + Future describe() => + _generate(service, context, '<__media__>', _greedy, parts: mtmd!.parts); + + void attach({bool chunkEval = false}) { + start(); + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + final fake = mtmd = FakeMtmd.install( + service, + tokens: service.tokenize(model, 'ab', true), + chunkEval: chunkEval, + decode: recorder.api.decode, + ); + addTearDown(fake.dispose); + projector = service.createMultimodalContext(model, projectorPath); + } + + test('a projector load that throws is a typed model error', () { + start(); + final projectorPath = '${dir.path}/mmproj.gguf'; + File(projectorPath).writeAsStringSync('GGUF'); + final fake = mtmd = FakeMtmd.install(service, tokens: const []); + addTearDown(fake.dispose); + throwing.add('llama_dart_mtmd_init_from_file'); + + expect( + () => service.createMultimodalContext(model, projectorPath), + throwsA(_caught('mtmd_init_from_file')), + ); + }); + + test('builds media bitmaps through the barrier, and a constructor that ' + 'throws is a typed error', () async { + attach(); + + expect(await describe(), BackendGenerationLimit.maxTokens); + expect(barrier.calls, contains('llama_dart_mtmd_bitmap_init_from_audio')); + expect(mtmd!.freedBitmaps, [FakeNativeBarrier.object.address]); + + barrier.throwing.add('llama_dart_mtmd_bitmap_init_from_audio'); + barrier.message = 'boom'; + await expectLater( + describe(), + throwsA( + _caught('the mtmd bitmap constructor'), + ), + ); + + barrier.throwing.clear(); + expect(await describe(), BackendGenerationLimit.maxTokens); + }); + + test('a media tokenize that throws is a typed error, and the projector ' + 'is unusable until it is freed', () async { + attach(); + throwing.add('llama_dart_mtmd_tokenize'); + + await expectLater( + describe(), + throwsA(_caught('mtmd_tokenize')), + ); + + throwing.clear(); + await expectLater( + describe(), + throwsA(_unusable('This multimodal projector', 'mtmd_tokenize')), + ); + // Text generation on the context is unaffected. + expect( + await _generate(service, context, 'ab', _greedy), + BackendGenerationLimit.maxTokens, + ); + service.freeMultimodalContext(projector); + }); + + test('a media evaluation that throws is a typed error, and the context ' + 'and the projector are unusable', () async { + attach(); + throwing.add('llama_dart_mtmd_helper_eval_chunks'); + + await expectLater( + describe(), + throwsA(_caught('mtmd_helper_eval_chunks')), + ); + + throwing.clear(); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA(_unusable('This context', 'mtmd_helper_eval_chunks')), + ); + service.freeContext(context); + context = service.createContext(model, _params); + await expectLater( + describe(), + throwsA( + _unusable('This multimodal projector', 'mtmd_helper_eval_chunks'), + ), + ); + }); + + test('a chunk evaluation that throws is a typed error naming the ' + 'chunk', () async { + attach(chunkEval: true); + throwing.add('llama_dart_mtmd_helper_eval_chunk_single'); + + await expectLater( + describe(), + throwsA( + _caught( + 'the mtmd chunk evaluation (failed to eval chunk 0)', + ), + ), + ); + + throwing.clear(); + await expectLater( + _generate(service, context, 'ab', _greedy), + throwsA( + _unusable( + 'This context', + 'the mtmd chunk evaluation (failed to eval chunk 0)', + ), + ), + ); + }); + }); + + test('a decision encoder pass that throws is a typed error, and the head ' + 'is unusable until it is loaded again', () { + start(); + writeSyntheticModernBertGguf( + '${dir.path}/encoder.gguf', + decisionTokens: true, + ); + final encoder = service.loadModel('${dir.path}/encoder.gguf', _params); + SyntheticDecisionHead( + d: 16, + layers: 1, + seed: 1, + ).write('${dir.path}/head.safetensors'); + File( + '${dir.path}/config.json', + ).writeAsStringSync('{"max_len": 64, "head_layers": 1}'); + int loadHead() => service + .loadDecisionHead( + encoder, + '${dir.path}/head.safetensors', + '${dir.path}/config.json', + ) + .handle; + List run(int head) => service.runDecision(head, [ + BackendDecisionSequence( + tokens: Int32List.fromList([1, 5, 0, 6, 0, 2]), + markers: Int32List.fromList([2, 4]), + questionType: DecisionQuestionType.choice, + ), + ]); + final head = loadHead(); + throwing.add(_encode); + + expect( + () => run(head), + throwsA(_caught('llama_encode')), + ); + + throwing.clear(); + expect( + () => run(head), + throwsA(_unusable('This decision head', 'llama_encode')), + ); + service.freeDecisionHead(head); + expect(run(loadHead()), hasLength(1)); + }); +} + +/// Generates to the end and returns the limit that ended it, if one did. +Future _generate( + LlamaCppService service, + int context, + String prompt, + GenerationParams params, { + List? parts, +}) async { + final cancel = calloc(); + BackendGenerationLimit? limit; + try { + await service + .generate( + context, + prompt, + params, + cancel.address, + parts: parts, + onLimit: (reached) => limit = reached, + ) + .drain(); + return limit; + } finally { + calloc.free(cancel); + } +} diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart index 9dcc3bb80..d14720e02 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart @@ -16,6 +16,7 @@ import 'package:llamadart/src/backends/llama_cpp/exit_teardown_api.dart'; import 'package:llamadart/src/backends/llama_cpp/llama_cpp_backend.dart'; import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; import 'package:llamadart/src/backends/llama_cpp/safetensors.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; import 'package:llamadart/src/backends/llama_cpp/worker.dart'; import 'package:llamadart/src/core/decision/decision_question.dart'; import 'package:llamadart/src/core/exceptions.dart'; @@ -5148,12 +5149,18 @@ void main() { /// The model loads with [loadParams] on this host. [loadedGpuLayers] /// replaces the GPU layer count that load recorded, as a load that kept /// its layers on a GPU backend this host does not have. + /// + /// [vulkanDevices] is what the Vulkan device facts report, for a ggml + /// registry of [registeredVulkanDevices] Vulkan devices; without it the + /// service reads them itself. Future<({List calls, int microBatch})> ingest( ModelParams params, { bool isAndroid = true, ModelParams loadParams = cpu, int? loadedGpuLayers, SpeculativeDecodingConfig? speculativeDecodingConfig, + VulkanDeviceProbe Function()? vulkanDevices, + int registeredVulkanDevices = 1, }) async { final recorder = RecordingExitTeardown( ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, @@ -5161,6 +5168,13 @@ void main() { final service = LlamaCppService( isAndroid: isAndroid, objectCalls: LlamaCppObjectCalls.tracked(recorder.api), + deviceTypes: vulkanDevices == null + ? null + : (backend) => List.filled( + backend == GpuBackend.vulkan ? registeredVulkanDevices : 0, + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value, + ), + vulkanDeviceProbe: vulkanDevices, ); addTearDown(service.dispose); final model = service.loadModel(modelPath, loadParams); @@ -5228,6 +5242,123 @@ void main() { ); }); + VulkanDeviceProbe Function() subgroups(List sizes) => + () => VulkanDeviceProbe.devices([ + for (final (index, size) in sizes.indexed) + VulkanDeviceFacts( + index: index, + name: 'GPU $index', + instanceApiVersion: VulkanDeviceFacts.vulkan12, + apiVersion: VulkanDeviceFacts.vulkan12, + subgroupSize: size, + ), + ]); + const capped = [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4]; + + test('decodes the whole prompt in one call on a GPU whose subgroup size ' + 'ggml-vulkan tiles correctly', () async { + for (final size in [8, 32, 64, 128]) { + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: subgroups([size]), + ), + decodes([100]), + reason: 'subgroup size $size', + ); + } + }); + + test('keeps the cap on a GPU whose subgroup size ggml-vulkan mis-tiles ' + 'or that does not report one', () async { + for (final size in [16, 4, 1, 0]) { + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: subgroups([size]), + ), + decodes(capped), + reason: 'subgroup size $size', + ); + } + }); + + test('keeps the cap when the device facts are unavailable, list no ' + 'device, or do not match the devices ggml registered', () async { + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: () => const VulkanDeviceProbe.unavailable( + 'the loaded llama.cpp runtime does not export ' + 'llama_dart_vulkan_get_device_count', + ), + ), + decodes(capped), + ); + expect( + await ingest(vulkan, loadedGpuLayers: 1, vulkanDevices: subgroups([])), + decodes(capped), + ); + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: subgroups([64]), + registeredVulkanDevices: 2, + ), + decodes(capped), + ); + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: subgroups([64, 16]), + registeredVulkanDevices: 2, + ), + decodes(capped), + reason: 'one affected device among the registered ones', + ); + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: subgroups([64, 32]), + registeredVulkanDevices: 2, + ), + decodes([100]), + ); + }); + + test('reads the device facts only for a context the cap would ' + 'apply to', () async { + var reads = 0; + VulkanDeviceProbe counted() { + reads++; + return subgroups([64])(); + } + + await ingest(cpu, vulkanDevices: counted); + await ingest(vulkan, vulkanDevices: counted); + await ingest( + vulkan.copyWith(microBatchSize: 64), + loadedGpuLayers: 1, + vulkanDevices: counted, + ); + await ingest( + vulkan, + isAndroid: false, + loadedGpuLayers: 1, + vulkanDevices: counted, + ); + expect(reads, 0); + + await ingest(vulkan, loadedGpuLayers: 1, vulkanDevices: counted); + expect(reads, 1); + }); + test('caps the calls of a speculative session too', () async { const ngram = SpeculativeDecodingConfig.ngramSimple( ngramSizeN: 1, @@ -5286,6 +5417,282 @@ void main() { }); }); + group('Vulkan device facts', () { + VulkanDeviceFacts device({ + String name = 'Mali-G68', + int? instanceApiVersion, + int? apiVersion, + int subgroupSize = 4, + }) => VulkanDeviceFacts( + index: 0, + name: name, + instanceApiVersion: instanceApiVersion ?? VulkanDeviceFacts.vulkan12, + apiVersion: apiVersion ?? VulkanDeviceFacts.vulkan12, + subgroupSize: subgroupSize, + ); + const vulkan11 = 1 << 22 | 1 << 12; + const vulkan = ModelParams( + preferredBackend: GpuBackend.vulkan, + gpuLayers: 16, + ); + + test('the cap resolver asks about the defect only when the cap would ' + 'apply, and lifts it for a device without it', () { + var asked = 0; + bool defect(bool value) { + asked++; + return value; + } + + expect( + LlamaCppService.resolvePromptMicroBatchLimit( + vulkan, + isAndroid: true, + hasSmallMatmulTileDefect: () => defect(true), + ), + LlamaCppService.androidVulkanPromptMicroBatchSize, + ); + expect( + LlamaCppService.resolvePromptMicroBatchLimit( + vulkan, + isAndroid: true, + hasSmallMatmulTileDefect: () => defect(false), + ), + isNull, + ); + expect(asked, 2); + expect( + LlamaCppService.resolvePromptMicroBatchLimit(vulkan, isAndroid: true), + LlamaCppService.androidVulkanPromptMicroBatchSize, + reason: 'without the facts the cap stays', + ); + + for (final (params, isAndroid, gpuLayers) in [ + (vulkan, false, null), + (vulkan, true, 0), + (vulkan.copyWith(microBatchSize: 64), true, null), + (const ModelParams(), true, null), + ]) { + expect( + LlamaCppService.resolvePromptMicroBatchLimit( + params, + isAndroid: isAndroid, + resolvedGpuLayers: gpuLayers, + hasSmallMatmulTileDefect: () => defect(true), + ), + isNull, + ); + } + expect(asked, 2); + }); + + test('unknown devices count as having the small matmul tile defect', () { + bool defect(VulkanDeviceProbe probe, {int registered = 1}) => + LlamaCppService.vulkanSmallMatmulTileDefect( + probe, + registeredDeviceCount: registered, + ); + + expect(defect(const VulkanDeviceProbe.unavailable('no loader')), isTrue); + expect(defect(const VulkanDeviceProbe.devices([])), isTrue); + expect( + defect(VulkanDeviceProbe.devices([device(subgroupSize: 64)])), + isFalse, + ); + expect( + defect(VulkanDeviceProbe.devices([device(subgroupSize: 16)])), + isTrue, + ); + expect( + defect( + VulkanDeviceProbe.devices([device(subgroupSize: 64)]), + registered: 2, + ), + isTrue, + ); + expect( + defect( + VulkanDeviceProbe.devices([ + device(subgroupSize: 64), + device(subgroupSize: 4), + ]), + registered: 2, + ), + isTrue, + ); + }); + + test('names the device and both versions when the driver or the loader ' + 'is below Vulkan 1.2', () { + expect( + LlamaCppService.vulkanUnsupportedReason( + VulkanDeviceProbe.devices([device(apiVersion: vulkan11)]), + ), + "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both the " + 'Vulkan loader and the GPU driver, and "Mali-G68" reports driver API ' + '1.1 with loader API 1.2', + ); + expect( + LlamaCppService.vulkanUnsupportedReason( + VulkanDeviceProbe.devices([ + device(name: 'Adreno 750'), + device(instanceApiVersion: vulkan11), + ]), + ), + contains('"Mali-G68" reports driver API 1.2 with loader API 1.1'), + ); + expect( + LlamaCppService.vulkanUnsupportedReason( + VulkanDeviceProbe.devices([device()]), + ), + isNull, + ); + expect( + LlamaCppService.vulkanUnsupportedReason( + const VulkanDeviceProbe.unavailable('no loader'), + ), + isNull, + reason: 'unknown devices are not refused', + ); + }); + + group('at model load', () { + late Directory tempDir; + late String modelPath; + late List warnings; + + setUpAll(() => LlamaCppService().initializeBackend()); + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('vulkan_api_version_'); + modelPath = path.join(tempDir.path, 'llama.gguf'); + writeSyntheticLlamaGguf(modelPath); + warnings = []; + LlamaLogger.instance.setLevel(LlamaLogLevel.warn); + LlamaLogger.instance.setHandler((record) { + if (record.level == LlamaLogLevel.warn) warnings.add(record.message); + }); + }); + + tearDown(() { + LlamaLogger.instance.setHandler(null); + LlamaLogger.instance.setLevel(LlamaLogLevel.none); + tempDir.deleteSync(recursive: true); + }); + + // A host whose ggml registry holds one Vulkan GPU that [probe] + // describes. + LlamaCppService serviceWith(VulkanDeviceProbe Function() probe) { + final service = LlamaCppService( + deviceTypes: (_) => [ + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value, + ], + vulkanDeviceProbe: probe, + ); + addTearDown(service.dispose); + return service; + } + + VulkanDeviceProbe below12() => + VulkanDeviceProbe.devices([device(apiVersion: vulkan11)]); + + test('ComputeDevice.gpu throws and loads nothing on a driver below ' + 'Vulkan 1.2', () { + final service = serviceWith(below12); + + expect( + () => service.loadModel( + modelPath, + const ModelParams(contextSize: 64, device: ComputeDevice.gpu), + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'ComputeDevice.gpu is not available for llama.cpp on ' + "${Platform.operatingSystem}: llama.cpp's Vulkan backend " + 'needs Vulkan 1.2 or later from both the Vulkan loader and ' + 'the GPU driver, and "Mali-G68" reports driver API 1.1 ' + 'with loader API 1.2. Use ComputeDevice.auto to run on the ' + 'CPU instead.', + ), + ), + ); + expect(_readPrivateForTesting(service, '_models'), isEmpty); + }); + + test('ComputeDevice.auto loads on the CPU with a warning on a driver ' + 'below Vulkan 1.2', () { + final service = serviceWith(below12); + + final model = service.loadModel( + modelPath, + const ModelParams(contextSize: 64), + ); + + expect(service.getResolvedGpuLayers(), 0); + expect(service.getActiveBackendName(), 'CPU'); + expect( + warnings, + contains( + allOf( + contains('needs Vulkan 1.2 or later'), + contains('"Mali-G68" reports driver API 1.1'), + contains('so the model loaded on CPU with 0 GPU layers.'), + ), + ), + ); + // The context follows the load: nothing of it is offloaded. + final context = service.createContext( + model, + const ModelParams(contextSize: 64), + ); + final contextParams = + _readPrivateForTesting>( + service, + '_contextParams', + )[context]!; + expect(contextParams.offload_kqv, isFalse); + expect(contextParams.op_offload, isFalse); + }); + + test('does not read the device facts for a CPU load', () { + var reads = 0; + final service = serviceWith(() { + reads++; + return below12(); + }); + + service.loadModel( + modelPath, + const ModelParams(contextSize: 64, device: ComputeDevice.cpu), + ); + service.loadModel( + modelPath, + const ModelParams(contextSize: 64, gpuLayers: 0), + ); + + expect(reads, 0); + expect(warnings, isNot(contains(contains('Vulkan 1.2')))); + }); + + test('loads on the GPU backend when the devices meet Vulkan 1.2 or ' + 'are unknown', () { + for (final probe in [ + () => VulkanDeviceProbe.devices([device()]), + () => const VulkanDeviceProbe.unavailable('no loader'), + ]) { + final service = serviceWith(probe); + + service.loadModel(modelPath, const ModelParams(contextSize: 64)); + + expect(service.getResolvedGpuLayers(), greaterThan(0)); + expect(warnings, isNot(contains(contains('Vulkan 1.2')))); + } + }); + }); + }); + group('shouldKeepAndroidVulkanKqvOffloadEnabled', () { test('keeps KQV offload enabled for Qwen3.5 architecture metadata', () { expect( 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 0ac3f0da3..f4d9a8dad 100644 --- a/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart +++ b/test/unit/backends/llama_cpp/mtmd_chunk_eval_test.dart @@ -81,25 +81,12 @@ class _FakeMtmd { calls.add('embd'); return _embd; }, - decodeImageChunk: - ( - ctx, - lctx, - chunk, - embd, - nPast, - seqId, - nBatch, - newNPast, - callback, - userData, - ) { - expect((ctx, lctx, embd), (_ctx, _lctx, _embd)); - expect((callback, userData), (nullptr, nullptr)); - final i = _index(chunk); - newNPast.value = nPast + prompt[i].nPos; - return _finish('decode $i nPast=$nPast seq=$seqId batch=$nBatch'); - }, + decodeImageChunk: (ctx, lctx, chunk, embd, nPast, seqId, nBatch, newNPast) { + expect((ctx, lctx, embd), (_ctx, _lctx, _embd)); + final i = _index(chunk); + newNPast.value = nPast + prompt[i].nPos; + return _finish('decode $i nPast=$nPast seq=$seqId batch=$nBatch'); + }, ); } diff --git a/test/unit/backends/llama_cpp/native_barrier_api_test.dart b/test/unit/backends/llama_cpp/native_barrier_api_test.dart new file mode 100644 index 000000000..1b2277476 --- /dev/null +++ b/test/unit/backends/llama_cpp/native_barrier_api_test.dart @@ -0,0 +1,669 @@ +@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/backends/llama_cpp/native_barrier_api.dart'; +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:test/test.dart'; + +import '../../../support/fake_native_barrier.dart'; +import '../../../support/synthetic_embedding_gguf.dart'; + +// The exports the exception barrier depends on. +const _symbols = [ + 'llama_dart_last_error', + 'llama_dart_clear_last_error', + 'llama_dart_sampler_accept', + 'llama_dart_sampler_init_grammar_lazy_patterns', + 'llama_dart_tokenize', + 'llama_dart_token_to_piece', + 'llama_dart_memory_clear', + 'llama_dart_mtmd_bitmap_init_from_audio', + 'llama_dart_mtmd_bitmap_init_from_buf', + 'llama_dart_mtmd_bitmap_init_from_file', + 'llama_dart_ggml_backend_dev_init', + 'llama_dart_ggml_backend_dev_memory', + 'llama_dart_ggml_backend_dev_get_props', + 'llama_dart_ggml_backend_alloc_ctx_tensors', + 'llama_dart_ggml_backend_tensor_set', + 'llama_dart_ggml_backend_tensor_get', + 'llama_dart_ggml_backend_sched_alloc_graph', + 'llama_dart_ggml_backend_sched_synchronize', +]; + +final _statusException = llama_dart_status.LLAMA_DART_STATUS_EXCEPTION.value; + +void main() { + group('NativeBarrierApi', () { + test('binds every function through the lookup, and resolves none when ' + 'one is missing', () { + final requested = []; + Pointer exported(String name) { + requested.add(name); + return Pointer.fromAddress(0x1000 + requested.length); + } + + expect( + NativeBarrierApi.tryResolve(isWindows: false, symbol: exported), + isNotNull, + ); + expect(requested, unorderedEquals(_symbols)); + + for (final missing in _symbols) { + expect( + NativeBarrierApi.tryResolve( + isWindows: false, + symbol: (name) => name == missing + ? throw ArgumentError( + "Couldn't resolve native function '$name'", + ) + : exported(name), + ), + isNull, + reason: missing, + ); + } + }); + + test('resolves nothing from a library that exports none of them', () { + final library = DynamicLibrary.open(switch (Platform.operatingSystem) { + 'macos' => '/usr/lib/libSystem.B.dylib', + 'windows' => 'kernel32.dll', + _ => 'libc.so.6', + }); + + expect( + NativeBarrierApi.tryResolve(isWindows: false, symbol: library.lookup), + isNull, + ); + }); + + test('calls the function exported under the name of each of its ' + 'members', () { + final exports = _RecordingExports(); + addTearDown(exports.close); + final api = NativeBarrierApi.tryResolve( + isWindows: false, + symbol: exports.symbol, + )!; + + final members = { + 'llama_dart_last_error': () => api.lastError(), + 'llama_dart_clear_last_error': () => api.clearLastError(), + 'llama_dart_sampler_accept': () => api.samplerAccept(nullptr, 0), + 'llama_dart_sampler_init_grammar_lazy_patterns': () => + api.samplerInitGrammarLazyPatterns( + nullptr, + nullptr, + nullptr, + nullptr, + 0, + nullptr, + 0, + ), + 'llama_dart_tokenize': () => + api.tokenize(nullptr, nullptr, 0, nullptr, 0, false, false), + 'llama_dart_token_to_piece': () => + api.tokenToPiece(nullptr, 0, nullptr, 0, 0, false), + 'llama_dart_memory_clear': () => api.memoryClear(nullptr, false), + 'llama_dart_mtmd_bitmap_init_from_audio': () => + api.mtmdBitmapInitFromAudio(0, nullptr), + 'llama_dart_mtmd_bitmap_init_from_buf': () => + api.mtmdBitmapInitFromBuf(nullptr, nullptr, 0), + 'llama_dart_mtmd_bitmap_init_from_file': () => + api.mtmdBitmapInitFromFile(nullptr, nullptr), + 'llama_dart_ggml_backend_dev_init': () => + api.ggmlBackendDevInit(nullptr, nullptr), + 'llama_dart_ggml_backend_dev_memory': () => + api.ggmlBackendDevMemory(nullptr, nullptr, nullptr), + 'llama_dart_ggml_backend_dev_get_props': () => + api.ggmlBackendDevGetProps(nullptr, nullptr), + 'llama_dart_ggml_backend_alloc_ctx_tensors': () => + api.ggmlBackendAllocCtxTensors(nullptr, nullptr), + 'llama_dart_ggml_backend_tensor_set': () => + api.ggmlBackendTensorSet(nullptr, nullptr, 0, 0), + 'llama_dart_ggml_backend_tensor_get': () => + api.ggmlBackendTensorGet(nullptr, nullptr, 0, 0), + 'llama_dart_ggml_backend_sched_alloc_graph': () => + api.ggmlBackendSchedAllocGraph(nullptr, nullptr), + 'llama_dart_ggml_backend_sched_synchronize': () => + api.ggmlBackendSchedSynchronize(nullptr), + }; + expect(members.keys, unorderedEquals(_symbols)); + for (final MapEntry(key: name, value: call) in members.entries) { + exports.called.clear(); + call(); + expect(exports.called, [name]); + } + }); + + test('reads no exception from a null last error', () { + final exports = _RecordingExports(); + addTearDown(exports.close); + final api = NativeBarrierApi.tryResolve( + isWindows: false, + symbol: exports.symbol, + )!; + + expect(api.caughtException(), isNull); + }); + }); + + // Runs the real llama.cpp runtime on the CPU. + group('the pinned runtime', () { + late Directory dir; + late Pointer model; + late LlamaCppObjectCalls calls; + late NativeBarrierApi barrier; + + setUpAll(() => LlamaCppService().initializeBackend()); + + setUp(() { + dir = Directory.systemTemp.createTempSync('llamadart_barrier_'); + final path = writeSyntheticLlamaGguf( + '${dir.path}/model.gguf', + ).path.toNativeUtf8(); + calls = LlamaCppObjectCalls.resolve(isWindows: Platform.isWindows); + barrier = calls.failures.barrier!; + try { + model = calls.loadModel( + path.cast(), + llama_model_default_params()..n_gpu_layers = 0, + ); + } finally { + malloc.free(path); + } + expect(model, isNot(nullptr)); + }); + + tearDown(() { + calls.freeModel(model); + dir.deleteSync(recursive: true); + }); + + test('exports the exception barrier', () { + expect( + NativeBarrierApi.tryResolve(isWindows: Platform.isWindows), + isNotNull, + ); + }); + + test('records the message of an exception llama.cpp throws, for the ' + 'next call to clear', () { + final vocab = llama_model_get_vocab(model); + final buffer = malloc(64); + addTearDown(() => malloc.free(buffer)); + final known = _tokenOf(calls, vocab, 'a'); + expect( + barrier.tokenToPiece(vocab, known, buffer, 64, 0, false), + greaterThan(0), + ); + expect(barrier.caughtException(), isNull); + + // llama.cpp throws std::out_of_range for a token outside the + // vocabulary; without the barrier that ends the process. + expect( + barrier.tokenToPiece(vocab, LLAMA_TOKEN_NULL, buffer, 64, 0, false), + _statusException, + ); + expect(barrier.caughtException(), isNotEmpty); + barrier.clearLastError(); + expect(barrier.caughtException(), isNull); + + // On Windows the vocabulary of a failed call is not used again. + if (Platform.isWindows) return; + barrier.tokenToPiece(vocab, LLAMA_TOKEN_NULL, buffer, 64, 0, false); + expect(barrier.caughtException(), isNotEmpty); + expect( + barrier.tokenToPiece(vocab, known, buffer, 64, 0, false), + greaterThan(0), + ); + expect(barrier.caughtException(), isNull); + }); + + test('a token outside the vocabulary is a typed error that leaves the ' + 'model usable', () { + final vocab = llama_model_get_vocab(model); + final buffer = malloc(64); + addTearDown(() => malloc.free(buffer)); + + expect( + () => calls.tokenToPiece(vocab, LLAMA_TOKEN_NULL, buffer, 64, 0, false), + throwsA( + isA() + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in llama_token_to_piece.', + ) + .having((e) => e.details, 'details', isA()), + ), + ); + if (Platform.isWindows) { + expect( + () => calls.failures.ensureUsable(vocab, 'This model'), + throwsA(isA()), + ); + return; + } + calls.failures.ensureUsable(vocab, 'This model'); + expect( + calls.tokenToPiece( + vocab, + _tokenOf(calls, vocab, 'a'), + buffer, + 64, + 0, + false, + ), + greaterThan(0), + ); + }); + + test('a trigger pattern that is not a regular expression is a typed ' + 'error', () { + final vocab = llama_model_get_vocab(model); + final grammar = 'root ::= "a"'.toNativeUtf8(); + final root = 'root'.toNativeUtf8(); + final pattern = '('.toNativeUtf8(); + final patterns = malloc>()..value = pattern.cast(); + addTearDown(() { + malloc.free(grammar); + malloc.free(root); + malloc.free(pattern); + malloc.free(patterns); + }); + + expect( + () => calls.samplerInitGrammarLazyPatterns( + vocab, + grammar.cast(), + root.cast(), + patterns, + 1, + nullptr, + 0, + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in ' + 'llama_sampler_init_grammar_lazy_patterns.', + ), + ), + ); + }); + + test('a grammar that rejects an accepted token is a typed error', () { + final vocab = llama_model_get_vocab(model); + final grammar = 'root ::= "a"'.toNativeUtf8(); + final root = 'root'.toNativeUtf8(); + addTearDown(() { + malloc.free(grammar); + malloc.free(root); + }); + final sampler = llama_sampler_init_grammar( + vocab, + grammar.cast(), + root.cast(), + ); + expect(sampler, isNot(nullptr)); + addTearDown(() => llama_sampler_free(sampler)); + final rejected = _tokenOf(calls, vocab, 'b'); + + expect( + () => calls.samplerAccept(sampler, rejected), + throwsA( + isA() + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in llama_sampler_accept.', + ) + .having( + (e) => e.details, + 'details', + contains('Unexpected empty grammar stack'), + ), + ), + ); + }); + }); + + group('NativeCallFailures', () { + late FakeNativeBarrier fake; + + setUp(() => fake = FakeNativeBarrier()); + tearDown(() => fake.dispose()); + + final context = Pointer.fromAddress(0x10); + final model = Pointer.fromAddress(0x20); + + test('reports nothing without a barrier', () { + final failures = NativeCallFailures(null, isWindows: true); + + failures.throwIfCaught( + 'llama_decode', + LlamaInferenceException.new, + freeOnly: [context], + windowsFreeOnly: [model], + ); + failures.ensureUsable(context, 'This context'); + failures.ensureUsable(model, 'This model'); + }); + + test('reports nothing when the barrier caught nothing', () { + final failures = NativeCallFailures(fake.api, isWindows: false); + + failures.throwIfCaught( + 'llama_decode', + LlamaInferenceException.new, + freeOnly: [context], + ); + failures.ensureUsable(context, 'This context'); + }); + + test('throws the typed error with the exception message as its ' + 'details', () { + final failures = NativeCallFailures(fake.api, isWindows: false); + fake.catchException('Unexpected empty grammar stack'); + + expect( + () => failures.throwIfCaught('llama_decode', LlamaStateException.new), + throwsA( + isA() + .having( + (e) => e.message, + 'message', + 'llama.cpp raised an exception in llama_decode.', + ) + .having( + (e) => e.details, + 'details', + 'Unexpected empty grammar stack', + ), + ), + ); + }); + + for (final isWindows in [false, true]) { + test('leaves the objects of a failed call free-only ' + '(Windows rule: $isWindows)', () { + final failures = NativeCallFailures(fake.api, isWindows: isWindows); + fake.catchException(); + + expect( + () => failures.throwIfCaught( + 'llama_decode', + LlamaInferenceException.new, + freeOnly: [context, nullptr], + windowsFreeOnly: [model], + ), + throwsA(isA()), + ); + + expect( + () => failures.ensureUsable(context, 'This context'), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'This context is unusable after a llama.cpp exception in ' + 'llama_decode. Unload the model and load it again.', + ), + ), + ); + failures.ensureUsable(nullptr, 'Nothing'); + if (isWindows) { + expect( + () => failures.ensureUsable(model, 'This model'), + throwsA(isA()), + ); + } else { + failures.ensureUsable(model, 'This model'); + } + + // A freed address can come back as a new object. + failures.forget(context); + failures.ensureUsable(context, 'This context'); + }); + } + }); +} + +/// The token of the one-byte [text] in [vocab]. +int _tokenOf( + LlamaCppObjectCalls calls, + Pointer vocab, + String text, +) { + final native = text.toNativeUtf8(); + final tokens = malloc(4); + try { + final count = calls.tokenize( + vocab, + native.cast(), + native.length, + tokens, + 4, + false, + false, + ); + expect(count, greaterThan(0)); + return tokens[count - 1]; + } finally { + malloc.free(native); + malloc.free(tokens); + } +} + +/// Stands in for a runtime's exports: one native function per name, each of +/// which records its name in [called] and returns zero. +final class _RecordingExports { + final List called = []; + + late final Map> _functions = { + 'llama_dart_last_error': + NativeCallable Function()>.isolateLocal( + () => _record('llama_dart_last_error', nullptr.cast()), + ), + 'llama_dart_clear_last_error': NativeCallable.isolateLocal( + () => _record('llama_dart_clear_last_error', null), + ), + 'llama_dart_sampler_accept': + NativeCallable< + Bool Function(Pointer, Int32) + >.isolateLocal( + (Pointer _, int _) => + _record('llama_dart_sampler_accept', false), + exceptionalReturn: false, + ), + 'llama_dart_sampler_init_grammar_lazy_patterns': + NativeCallable< + Pointer Function( + Pointer, + Pointer, + Pointer, + Pointer>, + Size, + Pointer, + Size, + ) + >.isolateLocal( + ( + Pointer _, + Pointer _, + Pointer _, + Pointer> _, + int _, + Pointer _, + int _, + ) => _record( + 'llama_dart_sampler_init_grammar_lazy_patterns', + nullptr.cast(), + ), + ), + 'llama_dart_tokenize': + NativeCallable< + Int32 Function( + Pointer, + Pointer, + Int32, + Pointer, + Int32, + Bool, + Bool, + ) + >.isolateLocal( + ( + Pointer _, + Pointer _, + int _, + Pointer _, + int _, + bool _, + bool _, + ) => _record('llama_dart_tokenize', 0), + exceptionalReturn: 0, + ), + 'llama_dart_token_to_piece': + NativeCallable< + Int32 Function( + Pointer, + Int32, + Pointer, + Int32, + Int32, + Bool, + ) + >.isolateLocal( + ( + Pointer _, + int _, + Pointer _, + int _, + int _, + bool _, + ) => _record('llama_dart_token_to_piece', 0), + exceptionalReturn: 0, + ), + 'llama_dart_memory_clear': + NativeCallable.isolateLocal( + (llama_memory_t _, bool _) => + _record('llama_dart_memory_clear', false), + exceptionalReturn: false, + ), + 'llama_dart_mtmd_bitmap_init_from_audio': + NativeCallable< + Pointer Function(Size, Pointer) + >.isolateLocal( + (int _, Pointer _) => _record( + 'llama_dart_mtmd_bitmap_init_from_audio', + nullptr.cast(), + ), + ), + 'llama_dart_mtmd_bitmap_init_from_buf': + NativeCallable< + Pointer Function( + Pointer, + Pointer, + Size, + ) + >.isolateLocal( + (Pointer _, Pointer _, int _) => _record( + 'llama_dart_mtmd_bitmap_init_from_buf', + nullptr.cast(), + ), + ), + 'llama_dart_mtmd_bitmap_init_from_file': + NativeCallable< + Pointer Function(Pointer, Pointer) + >.isolateLocal( + (Pointer _, Pointer _) => _record( + 'llama_dart_mtmd_bitmap_init_from_file', + nullptr.cast(), + ), + ), + 'llama_dart_ggml_backend_dev_init': + NativeCallable< + ggml_backend_t Function(ggml_backend_dev_t, Pointer) + >.isolateLocal( + (ggml_backend_dev_t _, Pointer _) => _record( + 'llama_dart_ggml_backend_dev_init', + nullptr.cast(), + ), + ), + 'llama_dart_ggml_backend_dev_memory': + NativeCallable< + Bool Function(ggml_backend_dev_t, Pointer, Pointer) + >.isolateLocal( + (ggml_backend_dev_t _, Pointer _, Pointer _) => + _record('llama_dart_ggml_backend_dev_memory', false), + exceptionalReturn: false, + ), + 'llama_dart_ggml_backend_dev_get_props': + NativeCallable< + Bool Function(ggml_backend_dev_t, Pointer) + >.isolateLocal( + (ggml_backend_dev_t _, Pointer _) => + _record('llama_dart_ggml_backend_dev_get_props', false), + exceptionalReturn: false, + ), + 'llama_dart_ggml_backend_alloc_ctx_tensors': + NativeCallable< + ggml_backend_buffer_t Function(Pointer, ggml_backend_t) + >.isolateLocal( + (Pointer _, ggml_backend_t _) => _record( + 'llama_dart_ggml_backend_alloc_ctx_tensors', + nullptr.cast(), + ), + ), + for (final name in [ + 'llama_dart_ggml_backend_tensor_set', + 'llama_dart_ggml_backend_tensor_get', + ]) + name: + NativeCallable< + Bool Function(Pointer, Pointer, Size, Size) + >.isolateLocal( + (Pointer _, Pointer _, int _, int _) => + _record(name, false), + exceptionalReturn: false, + ), + 'llama_dart_ggml_backend_sched_alloc_graph': + NativeCallable< + Bool Function(ggml_backend_sched_t, Pointer) + >.isolateLocal( + (ggml_backend_sched_t _, Pointer _) => + _record('llama_dart_ggml_backend_sched_alloc_graph', false), + exceptionalReturn: false, + ), + 'llama_dart_ggml_backend_sched_synchronize': + NativeCallable.isolateLocal( + (ggml_backend_sched_t _) => + _record('llama_dart_ggml_backend_sched_synchronize', false), + exceptionalReturn: false, + ), + }; + + T _record(String name, T result) { + called.add(name); + return result; + } + + /// The address of the function exported as [name]. + Pointer symbol(String name) => _functions[name]!.nativeFunction; + + void close() { + for (final function in _functions.values) { + function.close(); + } + } +} diff --git a/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart b/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart new file mode 100644 index 000000000..eac032361 --- /dev/null +++ b/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart @@ -0,0 +1,278 @@ +@TestOn('vm') +library; + +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; + +import 'package:llamadart/src/backends/llama_cpp/bindings.dart'; +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; +import 'package:test/test.dart'; + +const _symbols = [ + 'llama_dart_vulkan_get_device_count', + 'llama_dart_vulkan_get_device_info', +]; + +int _version(int major, int minor, [int patch = 0]) => + major << 22 | minor << 12 | patch; + +VulkanDeviceFacts _device({ + int index = 0, + String name = 'Mali-G715', + int? instanceApiVersion, + int? apiVersion, + int subgroupSize = 16, +}) => VulkanDeviceFacts( + index: index, + name: name, + instanceApiVersion: instanceApiVersion ?? _version(1, 3), + apiVersion: apiVersion ?? _version(1, 3), + subgroupSize: subgroupSize, +); + +void main() { + group('VulkanDeviceFacts', () { + test('needs Vulkan 1.2 from the loader and from the driver', () { + expect(VulkanDeviceFacts.vulkan12, _version(1, 2)); + expect(_device().meetsVulkan12, isTrue); + expect( + _device( + instanceApiVersion: _version(1, 2), + apiVersion: _version(1, 2), + ).meetsVulkan12, + isTrue, + ); + expect( + _device(apiVersion: _version(1, 1, 4095)).meetsVulkan12, + isFalse, + reason: 'a driver below 1.2 lacks the functions ggml-vulkan calls', + ); + expect( + _device(instanceApiVersion: _version(1, 1, 4095)).meetsVulkan12, + isFalse, + reason: 'ggml-vulkan registers no device on a loader below 1.2', + ); + }); + + test('has the small matmul tile defect at every subgroup size ' + 'ggml-vulkan mis-tiles', () { + // llama.cpp v0.6.0 gives a warp 8 rows of the 32-row block only at a + // subgroup size of exactly 8, where the block has max(size, 32) / + // max(size, 8) warps. + bool tiled(int size) { + final warps = (size < 32 ? 32 : size) ~/ (size < 8 ? 8 : size); + final rowsPerWarp = size == 8 ? 8 : 32; + return warps * rowsPerWarp == 32; + } + + for (final size in [0, 1, 2, 4, 8, 16, 32, 64, 128]) { + expect( + _device(subgroupSize: size).hasSmallMatmulTileDefect, + size == 0 || !tiled(size), + reason: 'subgroup size $size', + ); + } + expect(_device(subgroupSize: 16).hasSmallMatmulTileDefect, isTrue); + expect(_device(subgroupSize: 4).hasSmallMatmulTileDefect, isTrue); + expect(_device(subgroupSize: 0).hasSmallMatmulTileDefect, isTrue); + expect(_device(subgroupSize: 8).hasSmallMatmulTileDefect, isFalse); + expect(_device(subgroupSize: 64).hasSmallMatmulTileDefect, isFalse); + }); + + test('describes itself with its versions and subgroup size', () { + expect(VulkanDeviceFacts.formatApiVersion(_version(1, 3, 280)), '1.3'); + expect( + _device( + index: 1, + apiVersion: _version(1, 1, 177), + instanceApiVersion: _version(1, 3, 275), + ).toString(), + 'Vulkan1 "Mali-G715" (API 1.1, loader 1.3, subgroup size 16)', + ); + }); + }); + + group('VulkanDeviceInfoApi', () { + test('binds both functions through the lookup, and resolves nothing ' + 'when one is missing', () { + final requested = []; + Pointer exported(String name) { + requested.add(name); + return Pointer.fromAddress(0x1000 + requested.length); + } + + expect( + VulkanDeviceInfoApi.tryResolve(isWindows: false, symbol: exported), + isNotNull, + ); + expect(requested, _symbols); + + for (final missing in _symbols) { + expect( + VulkanDeviceInfoApi.tryResolve( + isWindows: false, + symbol: (name) => name == missing + ? throw ArgumentError( + "Couldn't resolve native function '$name'", + ) + : exported(name), + ), + isNull, + reason: missing, + ); + } + }); + + test('resolves nothing from a library that exports neither', () { + final library = DynamicLibrary.open(switch (Platform.operatingSystem) { + 'macos' => '/usr/lib/libSystem.B.dylib', + 'windows' => 'kernel32.dll', + _ => 'libc.so.6', + }); + + expect( + VulkanDeviceInfoApi.tryResolve( + isWindows: false, + symbol: library.lookup, + ), + isNull, + ); + }); + + test('calls the function exported under the name of each member', () { + final called = []; + final count = NativeCallable.isolateLocal(() { + called.add(_symbols[0]); + return 0; + }, exceptionalReturn: 0); + final info = + NativeCallable< + Int32 Function(Int32, Pointer) + >.isolateLocal((int _, Pointer _) { + called.add(_symbols[1]); + return 0; + }, exceptionalReturn: 0); + addTearDown(count.close); + addTearDown(info.close); + final api = VulkanDeviceInfoApi.tryResolve( + isWindows: false, + symbol: (name) => + name == _symbols[0] ? count.nativeFunction : info.nativeFunction, + )!; + + api.getDeviceCount(); + api.getDeviceInfo(0, nullptr); + + expect(called, _symbols); + }); + + test('lists each device with its name, versions and subgroup size', () { + final structSizes = []; + final api = VulkanDeviceInfoApi( + getDeviceCount: () => 2, + getDeviceInfo: (index, info) { + structSizes.add(info.ref.struct_size); + final name = utf8.encode(index == 0 ? 'Mali-G715' : 'Xclipse 940'); + for (var i = 0; i < name.length; i++) { + info.ref.device_name[i] = name[i]; + } + info.ref.device_name[name.length] = 0; + info.ref.instance_api_version = _version(1, 3, 275); + info.ref.api_version = _version(1, 3 - index, 7); + info.ref.subgroup_size = index == 0 ? 16 : 64; + return 0; + }, + ); + + final devices = api.probe().devices!; + + expect(structSizes, [ + sizeOf(), + sizeOf(), + ]); + expect(devices.map((device) => device.toString()), [ + 'Vulkan0 "Mali-G715" (API 1.3, loader 1.3, subgroup size 16)', + 'Vulkan1 "Xclipse 940" (API 1.2, loader 1.3, subgroup size 64)', + ]); + expect(api.probe().unavailableReason, isNull); + }); + + test('lists no device when the loader works and ggml would use none', () { + final api = VulkanDeviceInfoApi( + getDeviceCount: () => 0, + getDeviceInfo: (_, _) => fail('no device to describe'), + ); + + expect(api.probe().devices, isEmpty); + }); + + for (final status in llama_dart_vulkan_status.values.where( + (status) => status.value < 0, + )) { + test('is unavailable when the count is ${status.name}', () { + final api = VulkanDeviceInfoApi( + getDeviceCount: () => status.value, + getDeviceInfo: (_, _) => fail('no device to describe'), + ); + + final probe = api.probe(); + + expect(probe.devices, isNull); + expect( + probe.unavailableReason, + 'llama_dart_vulkan_get_device_count returned ${status.name}', + ); + }); + } + + test('is unavailable when a device cannot be described, or with a status ' + 'this package does not know', () { + expect( + VulkanDeviceInfoApi( + getDeviceCount: () => 2, + getDeviceInfo: (index, _) => index == 0 + ? 0 + : llama_dart_vulkan_status + .LLAMA_DART_VULKAN_STATUS_NO_DEVICE + .value, + ).probe().unavailableReason, + 'llama_dart_vulkan_get_device_info(1) returned ' + 'LLAMA_DART_VULKAN_STATUS_NO_DEVICE', + ); + expect( + VulkanDeviceInfoApi( + getDeviceCount: () => -99, + getDeviceInfo: (_, _) => 0, + ).probe().unavailableReason, + 'llama_dart_vulkan_get_device_count returned status -99', + ); + }); + + // Runs the real llama.cpp runtime. + test('the pinned runtime exports the probe', () { + LlamaCppService().initializeBackend(); + + expect( + VulkanDeviceInfoApi.tryResolve(isWindows: Platform.isWindows), + isNotNull, + ); + }); + + // Reading the facts loads the system's Vulkan drivers, so this only runs + // where there is no Vulkan to load. + test('the pinned runtime reports Apple platforms as unsupported', () { + LlamaCppService().initializeBackend(); + + final probe = VulkanDeviceInfoApi.probeRuntime(isWindows: false); + + expect(probe.devices, isNull); + expect( + probe.unavailableReason, + 'llama_dart_vulkan_get_device_count returned ' + 'LLAMA_DART_VULKAN_STATUS_UNSUPPORTED', + ); + }, testOn: 'mac-os'); + }); +} diff --git a/test/unit/tooling/check_webgpu_bridge_tag_test.dart b/test/unit/tooling/check_webgpu_bridge_tag_test.dart index 998edeeef..8ca878b36 100644 --- a/test/unit/tooling/check_webgpu_bridge_tag_test.dart +++ b/test/unit/tooling/check_webgpu_bridge_tag_test.dart @@ -79,25 +79,25 @@ const String _approvedManifestJson = ''' "size_bytes": 257 }, "llama_webgpu_core.js": { - "sha256": "a426cebdfc3c7e51ab267aac9f2f76b3dc92ea1152b0668b6416d47487a2a862", + "sha256": "e8d1d3b36eb88d87a0feb2793293bffe8331ad9b08e129867c3a917e239e2c3c", "size_bytes": 121082 }, "llama_webgpu_core.wasm": { - "sha256": "877633c9ba30714d3a72de6b25fd277beb90a39aebe2f2735fe9f26199892743", - "size_bytes": 9710458 + "sha256": "2171189421bfeea92ae023eb62fc5ea810e92493a9d37bff11ed2a332c871500", + "size_bytes": 9875080 }, "llama_webgpu_core_mem64.js": { - "sha256": "7cbc55d7e7d5bce60726d17b2c8c260387fc8a1a439e4e98296d5b26b5efc17e", + "sha256": "a265ec7d2f74965113f6067c9b65a45969d0955a2d97701e4095b98671b0f010", "size_bytes": 142469 }, "llama_webgpu_core_mem64.wasm": { - "sha256": "7038c99b95021de0eb81c6b344bb0407370fb9d54ab48565910d677f1ac30dbd", - "size_bytes": 9985188 + "sha256": "6a32324e983acd2ff06e8006885a33c4a56124839bc923d5877e54fb323583c1", + "size_bytes": 10150377 } }, "assets_repository": "leehack/llama-web-bridge-assets", - "bridge_assets_tag": "v0.1.54", - "bridge_commit": "65622b297b83513db597a760fa067867755010b4", + "bridge_assets_tag": "v0.1.59", + "bridge_commit": "c1f64536b9a4ea410066b711928c7cba03691fb0", "bridge_repository": "leehack/llama-web-bridge", "capabilities": { "memory64": true, @@ -140,31 +140,31 @@ const String _approvedManifestJson = ''' "size_bytes": 257 }, "llama_webgpu_core.js": { - "sha256": "a426cebdfc3c7e51ab267aac9f2f76b3dc92ea1152b0668b6416d47487a2a862", + "sha256": "e8d1d3b36eb88d87a0feb2793293bffe8331ad9b08e129867c3a917e239e2c3c", "size_bytes": 121082 }, "llama_webgpu_core.wasm": { - "sha256": "877633c9ba30714d3a72de6b25fd277beb90a39aebe2f2735fe9f26199892743", - "size_bytes": 9710458 + "sha256": "2171189421bfeea92ae023eb62fc5ea810e92493a9d37bff11ed2a332c871500", + "size_bytes": 9875080 }, "llama_webgpu_core_mem64.js": { - "sha256": "7cbc55d7e7d5bce60726d17b2c8c260387fc8a1a439e4e98296d5b26b5efc17e", + "sha256": "a265ec7d2f74965113f6067c9b65a45969d0955a2d97701e4095b98671b0f010", "size_bytes": 142469 }, "llama_webgpu_core_mem64.wasm": { - "sha256": "7038c99b95021de0eb81c6b344bb0407370fb9d54ab48565910d677f1ac30dbd", - "size_bytes": 9985188 + "sha256": "6a32324e983acd2ff06e8006885a33c4a56124839bc923d5877e54fb323583c1", + "size_bytes": 10150377 } }, - "github_run_id": "36260289055", - "github_run_url": "https://github.com/leehack/llama-web-bridge/actions/runs/36260289055", - "llama_cpp_commit": "7fe450e19305b828c199d602c23a8337aaa1f03b", - "llama_cpp_tag": "v0.5.0", - "native_commit": "aa8ceb95a99f299587a9b0ba5c0e9b6f829bcd64", - "native_manifest_sha256": "1ded54a5b3d687dfddde33586acd89bcd5b774ab4301197194b63a7e05541c4b", - "native_release_tag": "v0.5.0", + "github_run_id": "37675831575", + "github_run_url": "https://github.com/leehack/llama-web-bridge/actions/runs/37675831575", + "llama_cpp_commit": "d81235049384534c167caea52b85a694f6103d14", + "llama_cpp_tag": "v0.6.0", + "native_commit": "537e456fdbda841bbec00ff53a43b5879aa94384", + "native_manifest_sha256": "5a64a45cf1719963f70ac52c43ec820bdab2fbd2285d8979eb98619193f0d211", + "native_release_tag": "v0.6.0", "native_repository": "leehack/llamadart-native", - "orchestrator_correlation_id": "auto-stable-v0.5.0-1ded54a5b3d687df-build-65622b297b83513d", + "orchestrator_correlation_id": "maintainer-v060-recovery-v0159-20261007", "qualification_gates": { "multimodal": "passed", "speech_to_text": "required-automated-qualification", @@ -173,9 +173,9 @@ const String _approvedManifestJson = ''' }, "release_channel": "stable", "release_rebuild": 0, - "release_tag": "v0.1.54", + "release_tag": "v0.1.59", "schema_version": 2, - "source_commit": "65622b297b83513db597a760fa067867755010b4", + "source_commit": "c1f64536b9a4ea410066b711928c7cba03691fb0", "source_repository": "leehack/llama-web-bridge", "unproven_capabilities": { "hardware_gpu_acceleration": "unavailable-on-hosted-runners", @@ -184,9 +184,9 @@ const String _approvedManifestJson = ''' "speaker_reference_fidelity": "unproven", "wasm32_text_to_speech": "unsupported" }, - "upstream_commit": "7fe450e19305b828c199d602c23a8337aaa1f03b", + "upstream_commit": "d81235049384534c167caea52b85a694f6103d14", "upstream_repository": "ggml-org/llama.cpp", - "upstream_tag": "v0.5.0" + "upstream_tag": "v0.6.0" } '''; @@ -196,7 +196,7 @@ Future> _verifyManifestJson( }) { final bytes = utf8.encode(manifestJson); return verifyManifest( - expectedTag: 'v0.1.54', + expectedTag: 'v0.1.59', expectedLlamaCppTag: bridgeLlamaCppTag, expectedLlamaCppCommit: bridgeLlamaCppCommit, expectedBridgeCommit: bridgeSourceCommit, @@ -255,7 +255,7 @@ void main() { 'website/docs/changelog/recent-releases.md', ]) { final current = _currentReleaseNotes(path); - expect(current, contains('`v0.1.54`'), reason: path); + expect(current, contains('`v0.1.59`'), reason: path); expect(current, contains(bridgeManifestSha256), reason: path); expect( current, @@ -841,14 +841,14 @@ void main() { // bridgeNativeReleaseTag is a constant, so drive the mismatch from the // other side: a tree whose bridge and native pins agree on a family the // checked-in anchor does not belong to. - final root = _fakeRuntimeRepo(bridgeTag: 'v0.6.0', nativeTag: 'v0.6.0'); + final root = _fakeRuntimeRepo(bridgeTag: 'v0.7.0', nativeTag: 'v0.7.0'); expect( - findBridgeRuntimeDrift(root, 'v0.6.0'), + findBridgeRuntimeDrift(root, 'v0.7.0'), contains( contains( 'bridgeNativeReleaseTag $bridgeNativeReleaseTag does not belong to ' - 'the recorded upstream llama.cpp release v0.6.0', + 'the recorded upstream llama.cpp release v0.7.0', ), ), ); @@ -862,8 +862,8 @@ void main() { }); test('immutable release identity stays pinned to the approved release', () { - expect(bridgeAssetsReleaseId, '397350529'); - expect(bridgeAssetsTagCommit, 'e161182a09ac560d45ad5e65bb499574f913a466'); + expect(bridgeAssetsReleaseId, '406130836'); + expect(bridgeAssetsTagCommit, '189dde2798cb65a5ebe12d40068623e1873a6cd9'); }); test('accepts equivalent CRLF documentation passages', () { diff --git a/tool/testing/check_webgpu_bridge_tag.dart b/tool/testing/check_webgpu_bridge_tag.dart index 4333361a4..de9f62961 100644 --- a/tool/testing/check_webgpu_bridge_tag.dart +++ b/tool/testing/check_webgpu_bridge_tag.dart @@ -366,13 +366,13 @@ List findCurrentReleaseNotesDrift( } /// The llama.cpp upstream release tag embedded in the pinned bridge assets. -const String bridgeLlamaCppTag = 'v0.5.0'; +const String bridgeLlamaCppTag = 'v0.6.0'; /// The exact upstream llama.cpp commit embedded in the pinned bridge assets. -const String bridgeLlamaCppCommit = '7fe450e19305b828c199d602c23a8337aaa1f03b'; +const String bridgeLlamaCppCommit = 'd81235049384534c167caea52b85a694f6103d14'; /// The exact bridge source commit used to build the pinned bridge assets. -const String bridgeSourceCommit = '65622b297b83513db597a760fa067867755010b4'; +const String bridgeSourceCommit = 'c1f64536b9a4ea410066b711928c7cba03691fb0'; /// Canonical repository identities recorded in the approved manifest. const String bridgeAssetsRepository = 'leehack/llama-web-bridge-assets'; @@ -381,22 +381,22 @@ const String bridgeUpstreamRepository = 'ggml-org/llama.cpp'; const String bridgeNativeRepository = 'leehack/llamadart-native'; /// The native release tag the pinned bridge assets were qualified against. -const String bridgeNativeReleaseTag = 'v0.5.0'; +const String bridgeNativeReleaseTag = 'v0.6.0'; /// The native pin approved beside the pinned bridge assets: either /// [bridgeNativeReleaseTag] or a native wrapper rebuild of it from the same /// upstream llama.cpp commit. -const String bridgeApprovedNativePin = 'v0.5.0-2'; +const String bridgeApprovedNativePin = 'v0.6.0-1'; /// The asset repository release that published the pinned bridge assets. -const String bridgeAssetsReleaseId = '397350529'; +const String bridgeAssetsReleaseId = '406130836'; /// The asset repository commit the pinned bridge asset tag points at. -const String bridgeAssetsTagCommit = 'e161182a09ac560d45ad5e65bb499574f913a466'; +const String bridgeAssetsTagCommit = '189dde2798cb65a5ebe12d40068623e1873a6cd9'; /// SHA-256 hash of the exact approved published manifest.json. const String bridgeManifestSha256 = - '8a9f83c15035eeb034a6563e6f753382d7d7f9be81503ef76902138da7841176'; + 'f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb'; /// Where the native runtime's llama.cpp build is pinned. const String nativeLlamaCppTagPath = 'lib/src/hook/native_release_pins.dart'; diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 61e27e30f..9f4a99a33 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -40,6 +40,36 @@ For canonical full release notes, use: `v0.18.0`, and names the upstream version when its prebuilt-override table is behind the runtime owner's ([#586](https://github.com/leehack/llamadart/issues/586)). +- Update the default llama.cpp runtime to + `leehack/llamadart-native@v0.6.0-1` (llama.cpp `v0.6.0`), and the + `llamadart_llama_cpp_flutter` Apple SwiftPM pin with it. +- **Behavior change:** a llama.cpp state file saved by llamadart 0.11.x or + earlier no longer loads: llama.cpp `v0.6.0` changed the session format. + On native, `stateLoadFile` throws `LlamaStateException` naming the file's + format version and the one the runtime reads; evaluate the prompt again and + save a new file ([Save and restore prompt state](../guides/model-lifecycle#save-and-restore-prompt-state)). +- Fix a C++ exception inside llama.cpp ending the process on native. The + failed call now throws the typed `LlamaException` of its operation with + llama.cpp's message, such as `LlamaInferenceException` from `detokenize` + for a token outside the vocabulary, or from a lazy-grammar trigger pattern + that is not a regular expression. A context the failed call left undefined + then throws `LlamaStateException` until its model is loaded again + ([llamadart-native#102](https://github.com/leehack/llamadart-native/issues/102)). +- Android llama.cpp Vulkan: the 8-token text-prompt decode cap now applies + only on a GPU whose subgroup size llama.cpp `v0.6.0` mis-tiles (16, or below + 8) or cannot be read. Other GPUs decode a text prompt in full micro-batches + ([#948](https://github.com/leehack/llamadart/issues/948)). +- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. On a + registered Vulkan GPU whose driver reports less, `ComputeDevice.gpu` now + throws `LlamaUnsupportedException` naming the GPU and both versions, and + `ComputeDevice.auto` loads the model on the CPU with a warning, instead of + starting a driver llama.cpp cannot use + ([#782](https://github.com/leehack/llamadart/issues/782)). +- Aligned default WebGPU bridge assets to `v0.1.59`: they embed llama.cpp + `v0.6.0`, are qualified against native `v0.6.0`, and keep Web/native + llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14` parity and Web + `@litert-lm/core@0.15.0`. Immutable Web asset manifest: + `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. ## 0.11.1 diff --git a/website/docs/getting-started/installation.md b/website/docs/getting-started/installation.md index da06ee80b..26f2c2a87 100644 --- a/website/docs/getting-started/installation.md +++ b/website/docs/getting-started/installation.md @@ -136,7 +136,7 @@ hooks: llamadart: llamadart_native_runtimes: [llama_cpp] # or [litert_lm] # Compatibility testing only; omit to use the tested pin. - # llamadart_native_tag: v0.5.0-2 + # llamadart_native_tag: v0.6.0-1 ``` A `llamadart_native_backends` request that names any backend module the target @@ -151,7 +151,7 @@ rebuild counters start at 1. Build-hook overrides must always name an explicit tag; `latest` is limited to maintainer synchronization and header/binding regeneration. An override does not regenerate the Dart bindings, so its binary must stay ABI-compatible with the default -`leehack/llamadart-native@v0.5.0-2` runtime. +`leehack/llamadart-native@v0.6.0-1` runtime. Every key, per-target backend and Android CPU variant selection, local bundle paths, and fallback rules: diff --git a/website/docs/guides/backend-benchmarks.md b/website/docs/guides/backend-benchmarks.md index 5fc351613..f915cda9b 100644 --- a/website/docs/guides/backend-benchmarks.md +++ b/website/docs/guides/backend-benchmarks.md @@ -51,7 +51,8 @@ device (Mali-G715) a prompt longer than about 32 tokens evaluated in one batch returns wrong text, confirmed so far with one model (Qwen3.5-0.8B Q4_0) ([#948](https://github.com/leehack/llamadart/issues/948), [known limitations](../platforms/support-matrix#known-limitations)). -As a workaround, llamadart decodes text prompts on Android Vulkan in +As a workaround, llamadart decodes text prompts on an Android Vulkan GPU with +this defect (subgroup size 16 or below 8, or one it cannot read) in micro-batches of at most 8 tokens by default, so the wrong text needs an explicit `ModelParams.microBatchSize` above 32 or one of the paths the cap does not cover, listed in the known limitations. diff --git a/website/docs/guides/model-lifecycle.md b/website/docs/guides/model-lifecycle.md index c6dfdafd9..497fed00f 100644 --- a/website/docs/guides/model-lifecycle.md +++ b/website/docs/guides/model-lifecycle.md @@ -302,7 +302,12 @@ print('Restored ${restored.tokens.length} prompt tokens'); Important caveats: - State files are opaque llama.cpp artifacts. Treat them as tied to the same - model file and compatible runtime/build that created them. Web paths refer to + model file and compatible runtime/build that created them. A llama.cpp + release can change the format: llama.cpp `v0.6.0`, which llamadart pins + after 0.11.x, reads session version 11 and refuses the version 10 files + that 0.11.x and earlier wrote. On native, `stateLoadFile(...)` then throws + `LlamaStateException` naming both versions; catch it, evaluate the prompt + again and save a new file. Web paths refer to the bridge WASMFS virtual filesystem and are not durable across page reloads. Durable browser storage currently requires app-level export/import outside the Dart `stateSaveFile` / `stateLoadFile` helpers. diff --git a/website/docs/guides/performance-tuning.md b/website/docs/guides/performance-tuning.md index 5959b3246..08b9fbf9a 100644 --- a/website/docs/guides/performance-tuning.md +++ b/website/docs/guides/performance-tuning.md @@ -60,13 +60,14 @@ const modelParams = ModelParams( - `batchSize` / `microBatchSize`: native decoder models start at the llama.cpp-aligned caps of `2048` and `512`. Lower `microBatchSize` first (for example to `256` or `128`) when memory or GPU stability is tight; - bigger is not always faster. On Android Vulkan a text prompt is decoded at - most `8` tokens at a time while `microBatchSize` is `0`, and an explicit - value above `32` can return wrong text on some GPUs + bigger is not always faster. On an Android Vulkan GPU whose subgroup size + is 16, below 8 or unreadable, a text prompt is decoded at most `8` tokens at + a time while `microBatchSize` is `0`, and an explicit value above `32` can + return wrong text there ([known limitations](../platforms/support-matrix#known-limitations)). - On a GPU without that defect the `8`-token default can be slower than - decoding the prompt in one batch; an app that has validated Vulkan on its - target devices can set `microBatchSize` explicitly. + Other Android Vulkan GPUs decode the prompt in full micro-batches; an app + that has validated Vulkan on its target devices can set `microBatchSize` + explicitly. The cap applies to text-prompt decoding only: it does not cover prompts with image or audio input, embeddings, decision models, text-to-speech, or speculative-decoding verification batches during generation, which can @@ -265,7 +266,7 @@ unrelated reservations; it does not make recurrent/hybrid reservations safe. DSpark (`SpeculativeDecodingConfig.draftDspark(draftModel: ...)`) is an experimental, opt-in llama.cpp external-draft strategy mapped to upstream -`draft-dspark`. The default `v0.5.0-2` runtime supports it, including +`draft-dspark`. The default `v0.6.0-1` runtime supports it, including speculators-format checkpoints. Native recurrent/hybrid target pairs such as LFM2 remain subject to the rollback restriction above. It is never selected automatically, and support still depends on the target, draft and diff --git a/website/docs/guides/text-to-speech.md b/website/docs/guides/text-to-speech.md index ed34db8fb..7840a07f1 100644 --- a/website/docs/guides/text-to-speech.md +++ b/website/docs/guides/text-to-speech.md @@ -201,7 +201,7 @@ The [chat app](../examples/chat-app) has a Qwen3-TTS mode built on this API. - Web requires published bridge assets `v0.1.33+`, WebAssembly memory64 for the pinned roughly 1.48 GB model/projector pair, and a browser/device with enough memory. Older bridge assets fail capability discovery clearly. -- The chat example pins `v0.1.54`, whose bridge retries a synthesis once on +- The chat example pins `v0.1.59`, whose bridge retries a synthesis once on the main thread, more slowly, after eligible WebGPU errors and worker timeouts; see [WebGPU bridge fallback behavior](../platforms/webgpu-bridge#fallback-behavior). diff --git a/website/docs/platforms/native-build-hooks.md b/website/docs/platforms/native-build-hooks.md index c172d94fe..67fd98b03 100644 --- a/website/docs/platforms/native-build-hooks.md +++ b/website/docs/platforms/native-build-hooks.md @@ -270,6 +270,13 @@ teardown covers abort on Apple Metal as they did before ([Exiting with a model loaded](../guides/model-lifecycle#exiting-with-a-model-loaded)). `v0.5.0-1` has exit teardown but can still abort when a native host calls C `exit()` during the free of the last object; use `v0.5.0-2` or later. +A runtime older than `v0.6.0-1` has no exception barrier and no Vulkan device +facts: a C++ exception llama.cpp throws ends the process instead of becoming +a typed `LlamaException` (llamadart logs a warning at the first model load), +every Android Vulkan context keeps the 8-token text-prompt decode cap, and no +Vulkan GPU is refused for a driver below Vulkan 1.2. State files are tied to +the llama.cpp release of the runtime that wrote them +([Save and restore prompt state](../guides/model-lifecycle#save-and-restore-prompt-state)). Two checks fail closed: - LoRA adapters need both `llama_adapter_get_alora_n_invocation_tokens` and diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index b659ea11a..e10b5f851 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -164,13 +164,18 @@ output and grammars, sampling controls and speculative decoding. Guides: ([#782](https://github.com/leehack/llamadart/issues/782)); a Galaxy S24 (Adreno 750) crashes on the first generation ([llamadart-native#79](https://github.com/leehack/llamadart-native/issues/79)). - For the first of these, an Android Vulkan context decodes a text prompt in - micro-batches of at most 8 tokens by default. On a Pixel 9 Pro, prompt + The first of these is a llama.cpp defect at Vulkan subgroup sizes of 16 and + below 8 + ([llama.cpp#28637](https://github.com/ggml-org/llama.cpp/issues/28637)), + which llama.cpp `v0.6.0` still has. On Android, llamadart reads the + subgroup size of the Vulkan GPUs when it creates a context: on such a GPU, + and on any GPU whose subgroup size it cannot read, the context decodes a + text prompt in micro-batches of at most 8 tokens by default; on other GPUs + it decodes the prompt in full micro-batches. On a Pixel 9 Pro, prompt evaluation with 8-token micro-batches ran at about the speed uncapped decoding did (about 34 tokens/s against about 30 tokens/s for a 59-token - prompt); other GPUs are not measured. On a GPU without the defect, decoding - a prompt in 8-token micro-batches can be slower than decoding it in one - batch. An app that has validated Vulkan on its target devices can set + prompt); other GPUs are not measured. An app that has validated Vulkan on + its target devices can set `ModelParams.microBatchSize` to choose the micro-batch size itself: an explicit value is used as given, and one above 32 brings the wrong text back on affected GPUs. The cap applies to @@ -178,6 +183,13 @@ output and grammars, sampling controls and speculative decoding. Guides: input, embeddings, decision models, text-to-speech, or speculative-decoding verification batches during generation. Those batches can exceed 32 tokens, so speculative decoding can still produce wrong output on an affected GPU. + llama.cpp's Vulkan backend also needs Vulkan 1.2 from the Vulkan loader and + the GPU driver. When a registered Vulkan GPU's driver reports an older + version, `ComputeDevice.gpu` throws `LlamaUnsupportedException` naming the + GPU and both versions, and `ComputeDevice.auto` loads the model on the CPU + and logs a warning; on Linux and Windows, `GGML_VK_VISIBLE_DEVICES` can + hide such a GPU from llama.cpp. Whether this is what crashes the Galaxy A53 + is not confirmed. Keep `auto` or `cpu` on Android unless the app has validated Vulkan on its target devices. - Some Vulkan drivers crash in the cooperative-matrix path; see @@ -189,13 +201,13 @@ output and grammars, sampling controls and speculative decoding. Guides: | Runtime | Pinned release | | --- | --- | -| llama.cpp native | `leehack/llamadart-native@v0.5.0-2` | +| llama.cpp native | `leehack/llamadart-native@v0.6.0-1` | | LiteRT-LM native | `leehack/litert-lm-native@v0.18.0` | | stable-diffusion.cpp native (opt-in, Preview) | `leehack/stable-diffusion-native@v0.2.0-1`, for [image generation](../guides/image-generation); see [Opt-in stable_diffusion runtime](./native-build-hooks#opt-in-stable_diffusion-runtime-experimental). Flutter iOS/macOS apps link its XCFramework through `llamadart_stable_diffusion_flutter` | | WebGPU bridge assets | `leehack/llama-web-bridge-assets`; see [Pinned bridge assets](./webgpu-bridge#pinned-bridge-assets) | The native-assets hook currently pins `llamadart-native` tag -`v0.5.0-2` and +`v0.6.0-1` and `litert-lm-native` release `v0.18.0` (`lib/src/hook/native_release_pins.dart`). Apps can override the llama.cpp release with `llamadart_native_tag`, which takes a `vMAJOR.MINOR.PATCH`, `vMAJOR.MINOR.PATCH-N`, `bNNNN`, `bNNNN-N` or diff --git a/website/docs/platforms/webgpu-bridge.md b/website/docs/platforms/webgpu-bridge.md index 93fd48b3b..1649bed4d 100644 --- a/website/docs/platforms/webgpu-bridge.md +++ b/website/docs/platforms/webgpu-bridge.md @@ -297,23 +297,23 @@ first model load, for diagnosis or controlled deployments: ## Pinned bridge assets -The example currently pins bridge assets to `v0.1.54`, with local vendored assets -identified as `v0.1.54-local-v0.5.0`. - -- The pinned `v0.1.54` bridge assets embed llama.cpp `v0.5.0`, matching the native runtime - (`v0.5.0-2`, both built from upstream `v0.5.0@7fe450e19305b828c199d602c23a8337aaa1f03b`) - even though the bridge asset tag `v0.1.54` differs from the native runtime tag - `v0.5.0-2`. Pinned artifact provenance: release `397350529`, tag commit - `e161182a09ac560d45ad5e65bb499574f913a466`, bridge source - `65622b297b83513db597a760fa067867755010b4`, manifest SHA-256 - `8a9f83c15035eeb034a6563e6f753382d7d7f9be81503ef76902138da7841176`. The - bridge assets were qualified against native `v0.5.0`; `v0.5.0-2` rebuilds it +The example currently pins bridge assets to `v0.1.59`, with local vendored assets +identified as `v0.1.59-local-v0.6.0`. + +- The pinned `v0.1.59` bridge assets embed llama.cpp `v0.6.0`, matching the native runtime + (`v0.6.0-1`, both built from upstream `v0.6.0@d81235049384534c167caea52b85a694f6103d14`) + even though the bridge asset tag `v0.1.59` differs from the native runtime tag + `v0.6.0-1`. Pinned artifact provenance: release `406130836`, tag commit + `189dde2798cb65a5ebe12d40068623e1873a6cd9`, bridge source + `c1f64536b9a4ea410066b711928c7cba03691fb0`, manifest SHA-256 + `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. The + bridge assets were qualified against native `v0.6.0`; `v0.6.0-1` rebuilds it from the same upstream commit. In a llamadart checkout, vendor the pinned assets into the chat app with: ```bash -WEBGPU_BRIDGE_ASSETS_TAG=v0.1.54 ./scripts/fetch_webgpu_bridge_assets.sh +WEBGPU_BRIDGE_ASSETS_TAG=v0.1.59 ./scripts/fetch_webgpu_bridge_assets.sh ``` The chat app bootstrap takes its CDN source from these globals: @@ -321,7 +321,7 @@ The chat app bootstrap takes its CDN source from these globals: ```html ``` diff --git a/website/docs/troubleshooting/common-issues.md b/website/docs/troubleshooting/common-issues.md index 4bdab6114..3b4954bb0 100644 --- a/website/docs/troubleshooting/common-issues.md +++ b/website/docs/troubleshooting/common-issues.md @@ -116,6 +116,15 @@ fails, replace the file. The deprecated `liteRtLmBackend` still throws `LlamaModelException` for an unavailable backend; catch `LlamaException` to handle both. +### `ComputeDevice.gpu is not available ...: llama.cpp's Vulkan backend needs Vulkan 1.2` + +`LlamaUnsupportedException`: llama.cpp found a Vulkan GPU whose driver, or +the system's Vulkan loader, reports a version below 1.2, which llama.cpp +needs. The message names the GPU and both versions. Under +`ComputeDevice.auto` the same condition loads the model on the CPU and logs a +warning. Update the GPU driver, or on Linux and Windows hide that GPU from +llama.cpp with `GGML_VK_VISIBLE_DEVICES`. + ### Vulkan driver crashes in the cooperative-matrix path Some Vulkan drivers advertise cooperative matrix support but crash inside the @@ -242,6 +251,24 @@ With some models on the LiteRT-LM GPU backend, each engine create appends to files before each create; see [LiteRT-LM cache directory](../configuration/runtime-parameters#litert-lm-cache-directory). +## llama.cpp errors + +### `llama.cpp raised an exception in .` + +A typed `LlamaException` of the failed operation, such as +`LlamaInferenceException` for a decode or `LlamaStateException` for a state +file, whose `details` hold llama.cpp's own message. llama.cpp threw a C++ +exception inside that function: for example `detokenize` was given a token +outside the vocabulary, or a lazy-grammar trigger pattern is not a regular +expression. Fix the input the message points at. + +### `This context is unusable after a llama.cpp exception in .` + +`LlamaStateException`: an earlier call on that context, model or projector +threw inside llama.cpp and left it in an undefined state, so llamadart +refuses to use it again. Call `unloadModel()` and load the model again. On +Windows this follows any llama.cpp exception on the model. + ## API usage errors ### `Engine not ready: no model is loaded. Call LlamaEngine.load or setModel first.` From bbf5413786627faba6210c1bc8615474cb0b8d9b Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 21:12:26 -0400 Subject: [PATCH 2/6] docs: say the Vulkan subgroup sizes below 8 are not measured on a device --- website/docs/platforms/support-matrix.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index e10b5f851..0dc38a777 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -164,10 +164,10 @@ output and grammars, sampling controls and speculative decoding. Guides: ([#782](https://github.com/leehack/llamadart/issues/782)); a Galaxy S24 (Adreno 750) crashes on the first generation ([llamadart-native#79](https://github.com/leehack/llamadart-native/issues/79)). - The first of these is a llama.cpp defect at Vulkan subgroup sizes of 16 and - below 8 + The first of these is a llama.cpp defect at a Vulkan subgroup size of 16 ([llama.cpp#28637](https://github.com/ggml-org/llama.cpp/issues/28637)), - which llama.cpp `v0.6.0` still has. On Android, llamadart reads the + which llama.cpp `v0.6.0` still has; the same code mis-tiles subgroup sizes + below 8, which no device run has confirmed. On Android, llamadart reads the subgroup size of the Vulkan GPUs when it creates a context: on such a GPU, and on any GPU whose subgroup size it cannot read, the context decodes a text prompt in micro-batches of at most 8 tokens by default; on other GPUs From 9a8ec295515e871120feda6a11f004a2591ed39d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 21:19:33 -0400 Subject: [PATCH 3/6] docs: say where to regenerate the llama.cpp bindings --- website/docs/maintainers/native-and-web-sync.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/website/docs/maintainers/native-and-web-sync.md b/website/docs/maintainers/native-and-web-sync.md index 32bb8f7fb..a0e6b3a47 100644 --- a/website/docs/maintainers/native-and-web-sync.md +++ b/website/docs/maintainers/native-and-web-sync.md @@ -126,6 +126,11 @@ python3 tool/native/sync_native_release_pins.py \ --litert-lm-tag keep ``` +Run the header and bindings step on Linux, as the workflow does (Ubuntu with +`llvm-dev`, `libclang-dev` and `clang`): `ggml.h` pulls in the C library's +`FILE`, so a macOS run of the same `ffigen.yaml` rewrites that struct and +nothing else. + The pin sync rejects same-channel rollback and release/manifest version skew. After the default pin moves to the stable channel, an intentional compatibility test against a `bNNNN`, `bNNNN-N`, or legacy `bNNNN-llamadart.N` artifact must From 046c84f341ffe946c5daa68e0efc0c62cc5c11a7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 23:24:31 -0400 Subject: [PATCH 4/6] fix: judge a load's Vulkan devices by what llama.cpp would select A registered Vulkan device below Vulkan 1.2 turned every GPU load on the host into a CPU load or a refusal, although llama.cpp only initializes the devices a model uses. Mirror llama_prepare_model_devices and check the selected devices only: the devices of an explicit backend, otherwise the discrete GPUs by device id and integrated GPUs when there is no discrete one, and in single-device mode the one mainGpu indexes. When usable devices remain, list those for the load; refuse or fall back to the CPU only when none does. A draft model gets the same list. Also inject the Vulkan facts into the prompt-cap tests so none reads the host's GPUs, pin the Windows rule, the projector forget and the barrier routing of device queries and bitmap constructors with tests, and correct stale v0.5.0 wording. --- CHANGELOG.md | 7 +- doc/cross_platform_validation.md | 4 +- doc/llama_cpp_exit_teardown.md | 38 +- doc/webgpu_bridge.md | 6 +- .../backends/llama_cpp/exit_teardown_api.dart | 19 +- .../backends/llama_cpp/llama_cpp_service.dart | 160 ++++--- .../llama_cpp/load_device_selection.dart | 189 +++++++++ skills/llamadart-embeddings/SKILL.md | 2 +- test/support/recording_exit_teardown.dart | 11 + .../llama_cpp/exit_teardown_api_test.dart | 34 ++ ...llama_cpp_service_native_failure_test.dart | 59 +++ .../llama_cpp/llama_cpp_service_test.dart | 282 +++++++++---- .../llama_cpp/load_device_selection_test.dart | 389 ++++++++++++++++++ website/docs/changelog/recent-releases.md | 7 +- website/docs/guides/embeddings.md | 2 +- website/docs/platforms/support-matrix.md | 9 +- website/docs/troubleshooting/common-issues.md | 9 +- 17 files changed, 1066 insertions(+), 161 deletions(-) create mode 100644 lib/src/backends/llama_cpp/load_device_selection.dart create mode 100644 test/unit/backends/llama_cpp/load_device_selection_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 4153ad9c4..5af72c9d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,11 +54,12 @@ only on a GPU whose subgroup size llama.cpp `v0.6.0` mis-tiles (16, or below 8) or cannot be read. Other GPUs decode a text prompt in full micro-batches ([#948](https://github.com/leehack/llamadart/issues/948)). -- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. On a - registered Vulkan GPU whose driver reports less, `ComputeDevice.gpu` now +- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. When + the Vulkan GPU a load would run on reports less, `ComputeDevice.gpu` now throws `LlamaUnsupportedException` naming the GPU and both versions, and `ComputeDevice.auto` loads the model on the CPU with a warning, instead of - starting a driver llama.cpp cannot use + starting a driver llama.cpp cannot use; a load with other usable GPUs + leaves that one out ([#782](https://github.com/leehack/llamadart/issues/782)). * Aligned the default WebGPU bridge assets to `v0.1.59`: they embed llama.cpp `v0.6.0`, are qualified against native `v0.6.0`, and keep Web/native diff --git a/doc/cross_platform_validation.md b/doc/cross_platform_validation.md index da1cbf17d..021ddf9e5 100644 --- a/doc/cross_platform_validation.md +++ b/doc/cross_platform_validation.md @@ -1221,7 +1221,7 @@ still required for every actual run. ### Native video input -The pinned `llamadart-native` `v0.5.0` archive exports upstream video helper +The pinned `llamadart-native` `v0.6.0-1` archive exports upstream video helper symbols (`mtmd_helper_video_*`), but the release is not qualified for end-to-end video input. The companion build does not opt into `LLAMA_SUBPROCESS`/`MTMD_VIDEO` or package FFmpeg/ffprobe, so the public Dart @@ -1378,7 +1378,7 @@ any budget is exceeded: by more than 7 MiB in every one of the seven cycles after the first. A plateau passes; a steady leak fails. Slower growth passes this check. -With native `v0.4.1-1` (before the current `v0.5.0` pin), the pack has passed +With native `v0.4.1-1` (before the `v0.5.0` pin), the pack has passed on macOS arm64 with CPU and with Metal, and on Linux x64 with CPU (AMD EPYC 7B12). The Metal runs report the Metal backend; the pack does not verify GPU execution. diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 2b703d7a6..7a1443847 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -121,17 +121,27 @@ A failed `GGML_ASSERT` still aborts: the barrier catches exceptions only. `llama_dart_vulkan_get_device_count` and `llama_dart_vulkan_get_device_info` (`v0.6.0-1`), which list the devices ggml-vulkan registers with their API versions and subgroup size. Reading them makes the Vulkan loader load the -system's GPU drivers, so the service reads them once, and only after -ggml-vulkan has registered a device itself and a load or context is about to -use it: +system's GPU drivers, so the service reads them once, and only when a +registered Vulkan device is about to be used by a load or a context: -- A load on Vulkan stops when a device's driver or the loader is below - Vulkan 1.2, which llama.cpp `v0.6.0` needs (`ggml_vk_instance_init` refuses - an older loader; for an older driver it reads +- llama.cpp `v0.6.0` needs Vulkan 1.2 (`ggml_vk_instance_init` refuses an + older loader; for an older driver ggml-vulkan reads `VkPhysicalDeviceVulkan12Features` the driver never filled in and calls - Vulkan 1.2 functions it lacks). `ComputeDevice.gpu` throws - `LlamaUnsupportedException`; `ComputeDevice.auto` loads on the CPU with a - warning. + Vulkan 1.2 functions it lacks, once it initializes the device). A device + is initialized only when a model uses it, so a load is judged by the + devices llama.cpp would select for it, which + `lib/src/backends/llama_cpp/load_device_selection.dart` mirrors from + `llama_prepare_model_devices` (`src/llama.cpp`): the devices of an explicit + backend, which llamadart lists; otherwise the discrete GPUs, one per + device id, and integrated GPUs only when there is no discrete one; in + single-device mode the one `mainGpu` indexes. A CUDA device, an unselected + integrated GPU and a GPU of another backend never count. When every + selected device is below 1.2, `ComputeDevice.gpu` throws + `LlamaUnsupportedException` and `ComputeDevice.auto` loads on the CPU with + a warning. When usable devices remain, the load lists those and logs a + warning naming the device it left out. A speculative draft model gets the + same list. The projector and a decision head pick their own device and are + not covered. - An Android Vulkan context keeps the 8-token text-prompt decode cap unless the facts list exactly the registered devices and each has a subgroup size ggml-vulkan tiles correctly (8, or 32 and above). llama.cpp `v0.6.0` gives @@ -216,10 +226,12 @@ new call on an `sd_ctx_t` that can run longer than the 250 ms settle time object it leaves undefined is refused afterwards and usable again once freed and recreated, and nothing created stays unfreed. It also loads a state file written by llama.cpp `v0.5.0`. -- `test/unit/backends/llama_cpp/vulkan_device_probe_test.dart` and the - "Vulkan" groups of `llama_cpp_service_test.dart`: the device facts, the - version check at load and the cap on each subgroup size, through injected - facts. No default-CI test reads a real Vulkan device. +- `test/unit/backends/llama_cpp/vulkan_device_probe_test.dart`, + `load_device_selection_test.dart` and the "Vulkan" groups of + `llama_cpp_service_test.dart`: the device facts, the device selection and + version check of a load, and the cap on each subgroup size, through an + injected registry and injected facts. No default-CI test reads a real + Vulkan device. - No test forces an exception through speculative decoding, the reasoning-budget sampler or TTS: those functions are resolved inside the service and have no stand-in. diff --git a/doc/webgpu_bridge.md b/doc/webgpu_bridge.md index 4b8f72523..70960841f 100644 --- a/doc/webgpu_bridge.md +++ b/doc/webgpu_bridge.md @@ -93,8 +93,10 @@ tag commit `189dde2798cb65a5ebe12d40068623e1873a6cd9`, bridge source `c1f64536b9a4ea410066b711928c7cba03691fb0`, and manifest SHA-256 `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`. The bridge assets were qualified against native `v0.6.0`; `v0.6.0-1` rebuilds it from the -same upstream commit. Their bridge JavaScript is byte-identical to `v0.1.54`; -only the llama.cpp core changed. They add the decision API +same upstream commit. Their bridge JavaScript, type declarations and worker +are byte-identical to `v0.1.54`; the WebAssembly core changed, for llama.cpp +`v0.6.0` and for the bridge's own C++ on the batch and speculative-decoding +paths that adapts to it. They add the decision API (apiVersion 1), next-token scoring (`scoreNextToken`), presence penalty, Min-P, thinking budgets, runtime LoRA adapters and speculative decoding, keep the Qwen3-ASR typed speech contract from `v0.1.30`, and diff --git a/lib/src/backends/llama_cpp/exit_teardown_api.dart b/lib/src/backends/llama_cpp/exit_teardown_api.dart index eaa345303..de2bf5452 100644 --- a/lib/src/backends/llama_cpp/exit_teardown_api.dart +++ b/lib/src/backends/llama_cpp/exit_teardown_api.dart @@ -784,12 +784,25 @@ final class LlamaCppObjectCalls { /// [LlamaCppObjectCalls.tracked] when the loaded runtime exports the whole /// [ExitTeardownApi], with the [NativeBarrierApi] when it exports that too; /// otherwise [upstream]. - static LlamaCppObjectCalls resolve({required bool isWindows}) { - final exit = ExitTeardownApi.tryResolve(isWindows: isWindows); + /// + /// [isWindows] selects the asset the functions are bound to and the rule + /// for the objects of a failed call. [symbol] replaces the lookup of both + /// APIs, as in [ExitTeardownApi.tryResolve]. + static LlamaCppObjectCalls resolve({ + required bool isWindows, + Pointer Function(String name)? symbol, + }) { + final exit = ExitTeardownApi.tryResolve( + isWindows: isWindows, + symbol: symbol, + ); if (exit == null) return upstream; return LlamaCppObjectCalls.tracked( exit, - barrier: NativeBarrierApi.tryResolve(isWindows: isWindows), + barrier: NativeBarrierApi.tryResolve( + isWindows: isWindows, + symbol: symbol, + ), isWindows: isWindows, ); } diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 3142eb41a..973be5002 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -31,6 +31,7 @@ import '../../hook/native_release_pins.dart'; import 'decision_head.dart'; import 'exit_teardown_api.dart'; import 'lazy_grammar_triggers.dart'; +import 'load_device_selection.dart'; import 'load_param_helpers.dart'; import 'safetensors.dart'; import 'stop_sequence_buffer.dart'; @@ -650,7 +651,8 @@ class LlamaCppService { /// its backend and context policy, the raw `ggml_backend_dev_type` values a /// [ComputeDevice.gpu] load checks for a backend, the calls that create, /// free and run models and contexts, the calls that allocate and free - /// token batches, and the read of the Vulkan device facts. + /// token batches, the read of the Vulkan device facts, and the registered + /// ggml devices a load selects from. LlamaCppService({ void Function()? backendInit, Abi? abi, @@ -663,6 +665,7 @@ class LlamaCppService { llama_batch Function(int tokens, int embd, int sequences)? batchInit, void Function(llama_batch batch)? batchFree, VulkanDeviceProbe Function()? vulkanDeviceProbe, + List Function()? registeredDevices, }) : _backendInit = backendInit ?? (() => llama_backend_init()), _abi = abi ?? Abi.current(), _isWindows = isWindows ?? Platform.isWindows, @@ -672,7 +675,8 @@ class LlamaCppService { _objectCallsOverride = objectCalls, _batchInit = batchInit ?? llama_batch_init, _batchFree = batchFree ?? llama_batch_free, - _vulkanDeviceProbeOverride = vulkanDeviceProbe; + _vulkanDeviceProbeOverride = vulkanDeviceProbe, + _registeredDevicesOverride = registeredDevices; final void Function() _backendInit; final Abi _abi; @@ -687,15 +691,14 @@ class LlamaCppService { late final LlamaCppObjectCalls _calls = _objectCallsOverride ?? _resolveObjectCalls(); + final List Function()? _registeredDevicesOverride; + + // Reading the facts loads the system's GPU drivers into the process, so + // they are read once, and only when a registered Vulkan device is about to + // be used: ggml-vulkan has loaded the drivers by then. late final VulkanDeviceProbe _vulkanDeviceProbe = - (_vulkanDeviceProbeOverride ?? _probeVulkanDevices)(); - - // The read loads the system's GPU drivers into the process, so it is made - // once, and only after ggml-vulkan has registered a device itself. - VulkanDeviceProbe _probeVulkanDevices() => - _registeredDeviceTypes(GpuBackend.vulkan).isEmpty - ? const VulkanDeviceProbe.unavailable('ggml-vulkan registered no device') - : VulkanDeviceInfoApi.probeRuntime(isWindows: _isWindows); + (_vulkanDeviceProbeOverride ?? + () => VulkanDeviceInfoApi.probeRuntime(isWindows: _isWindows))(); int _nextHandle = 1; String? _backendModuleDirectory; final Set _loadedBackendModules = {}; @@ -961,23 +964,6 @@ class LlamaCppService { devices.any((device) => device.hasSmallMatmulTileDefect); } - /// Why ggml-vulkan cannot drive the devices of [probe], or `null` when it - /// can or the devices are unknown. - /// - /// llama.cpp v0.6.0 needs Vulkan 1.2 from the loader and from the driver - /// of every device it registers (see [VulkanDeviceFacts.meetsVulkan12]). - static String? vulkanUnsupportedReason(VulkanDeviceProbe probe) { - for (final device in probe.devices ?? const []) { - if (device.meetsVulkan12) continue; - String version(int value) => VulkanDeviceFacts.formatApiVersion(value); - return "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both " - 'the Vulkan loader and the GPU driver, and "${device.name}" ' - 'reports driver API ${version(device.apiVersion)} with loader API ' - '${version(device.instanceApiVersion)}'; - } - return null; - } - /// Resolves effective context batch parameters. /// /// Uses the shared non-FFI helper for consistent default resolution and @@ -2005,11 +1991,13 @@ class LlamaCppService { _noGpuMessage(effectiveBackend, forcedCpuFallback: forcedCpuFallback), ); } - final vulkanUnsupported = _vulkanUnsupportedReasonForLoad( + final vulkan = _resolveVulkanLoadDevices( effectiveBackend, - gpuLayers, + gpuLayers: gpuLayers, + splitMode: modelParams.splitMode.llamaCppValue, + mainGpu: modelParams.mainGpu, ); - if (vulkanUnsupported != null) { + if (vulkan.refused) { if (preferredDevices != null) { malloc.free(preferredDevices); } @@ -2017,12 +2005,17 @@ class LlamaCppService { malloc.free(modelPathPtr); throw LlamaUnsupportedException( 'ComputeDevice.gpu is not available for llama.cpp on ' - '${Platform.operatingSystem}: $vulkanUnsupported. Use ' + '${Platform.operatingSystem}: ${vulkan.unsupported}. Use ' 'ComputeDevice.auto to run on the CPU instead.', ); } preferredDevices = _createPreferredDeviceList(GpuBackend.cpu); gpuLayers = 0; + } else if (vulkan.devices case final usable?) { + if (preferredDevices != null) { + malloc.free(preferredDevices); + } + preferredDevices = _createDeviceList(usable); } final mtmdUseGpu = resolveMtmdUseGpuForLoad( modelParams, @@ -2079,10 +2072,13 @@ class LlamaCppService { _modelLoadParams[handle] = modelParams; _activeBackendName = resolvedBackend; _activeResolvedGpuLayers = gpuLayers; - if (vulkanUnsupported != null) { + if (vulkan.unsupported case final unsupported?) { LlamaLogger.instance.warning( - '$vulkanUnsupported, so the model loaded on $resolvedBackend with 0 ' - 'GPU layers.', + vulkan.refused + ? '$unsupported, so the model loaded on $resolvedBackend with 0 ' + 'GPU layers.' + : '$unsupported, so the model loaded without that device, on ' + '${vulkan.devices!.join(', ')}.', ); } if (forcedCpuFallback) { @@ -2099,25 +2095,73 @@ class LlamaCppService { return handle; } - /// Why a load on [backend] with [gpuLayers] layers must not use the Vulkan - /// devices ggml registered, or `null`. - /// - /// The device facts are read only when such a device would be used: for - /// [GpuBackend.vulkan], and for [GpuBackend.auto] when the Vulkan module is - /// the one that loaded. - String? _vulkanUnsupportedReasonForLoad(GpuBackend backend, int gpuLayers) { - if (gpuLayers <= 0 || - (backend != GpuBackend.vulkan && backend != GpuBackend.auto) || - _registeredVulkanDeviceCount() == 0) { - return null; + /// What a load on [backend] with [gpuLayers] layers does about Vulkan + /// devices below Vulkan 1.2 among the devices llama.cpp would use for it. + VulkanLoadDecision _resolveVulkanLoadDevices( + GpuBackend backend, { + required int gpuLayers, + required int splitMode, + required int mainGpu, + }) => resolveVulkanLoadDecision( + usesGpu: gpuLayers > 0 && backend != GpuBackend.cpu, + backendRegistry: ggmlGpuRegistryName(backend), + splitMode: splitMode, + mainGpu: mainGpu, + registered: _registeredDevices, + probe: () => _vulkanDeviceProbe, + ); + + /// The registered ggml devices, in registry order. + List _registeredDevices() { + final override = _registeredDevicesOverride; + if (override != null) return override(); + final gpu = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; + final props = calloc(); + try { + return [ + for (var i = 0; i < _ggmlBackendDevCount(); i++) + if (_ggmlBackendDevGet(i) case final device when device != nullptr) + GgmlDeviceEntry( + name: _utf8OrEmpty(_ggmlBackendDevName(device)), + type: _ggmlBackendDevType(device), + registry: _registryNameOf(device), + // llama.cpp compares the id of discrete GPUs only. + deviceId: + _ggmlBackendDevType(device) == gpu && + _ggmlBackendDevGetProps(device, props) && + props.ref.device_id != nullptr + ? _utf8OrEmpty(props.ref.device_id) + : null, + device: device, + ), + ]; + } finally { + calloc.free(props); } - return vulkanUnsupportedReason(_vulkanDeviceProbe); + } + + String _registryNameOf(ggml_backend_dev_t device) { + final registry = _ggmlBackendDevBackendReg(device); + return registry == nullptr + ? '' + : _utf8OrEmpty(_ggmlBackendRegName(registry)); } int _registeredVulkanDeviceCount() => - (_deviceTypesOverride ?? _registeredDeviceTypes)( - GpuBackend.vulkan, - ).length; + _registeredDevices().where((device) => device.isVulkan).length; + + Pointer _createDeviceList(List devices) { + final pointers = [ + for (final entry in devices) + if (entry.device case final device? when device != nullptr) device, + ]; + final list = malloc(pointers.length + 1); + for (final (index, device) in pointers.indexed) { + list[index] = device; + } + list[pointers.length] = nullptr; + return list; + } /// Whether a GPU device of [backend], or any GPU device for /// [GpuBackend.auto], is registered after the backend modules load. @@ -2222,7 +2266,21 @@ class LlamaCppService { final modelPathPtr = draftModelPath.toNativeUtf8(); final mparams = llama_model_default_params(); - final preferredDevices = _createPreferredDeviceList(draftBackend); + var preferredDevices = _createPreferredDeviceList(draftBackend); + // The target load already decided whether the GPU is usable; a draft + // only needs the same devices left out. + final vulkan = _resolveVulkanLoadDevices( + draftBackend, + gpuLayers: draftGpuLayers, + splitMode: targetModelParams.splitMode.llamaCppValue, + mainGpu: targetModelParams.mainGpu, + ); + if (vulkan.devices case final usable?) { + if (preferredDevices != null) { + malloc.free(preferredDevices); + } + preferredDevices = _createDeviceList(usable); + } mparams.n_gpu_layers = draftGpuLayers; mparams.split_modeAsInt = targetModelParams.splitMode.llamaCppValue; mparams.main_gpu = targetModelParams.mainGpu; @@ -5501,7 +5559,7 @@ class LlamaCppService { 'that exposes embedding model metadata before decoding.', ); } - // llama.cpp v0.5.0 (7fe450e1) forces this non-diffusion architecture's + // llama.cpp v0.6.0 (d8123504) forces this non-diffusion architecture's // attention to non-causal after loading the optional metadata override. if (architecture == 'gemma-embedding') return false; final causal = metadata['$architecture.attention.causal']; diff --git a/lib/src/backends/llama_cpp/load_device_selection.dart b/lib/src/backends/llama_cpp/load_device_selection.dart new file mode 100644 index 000000000..1f055baf4 --- /dev/null +++ b/lib/src/backends/llama_cpp/load_device_selection.dart @@ -0,0 +1,189 @@ +import 'bindings.dart'; +import 'vulkan_device_probe.dart'; + +/// One registered ggml device, as llama.cpp reads it when it picks the +/// devices of a model. +final class GgmlDeviceEntry { + /// Describes the registered [device]. + const GgmlDeviceEntry({ + required this.name, + required this.type, + required this.registry, + this.deviceId, + this.device, + }); + + /// `ggml_backend_dev_name`, such as `Vulkan0` or `CUDA1`. + final String name; + + /// The raw `ggml_backend_dev_type` value. + final int type; + + /// `ggml_backend_reg_name` of the device's backend, such as `Vulkan`. + final String registry; + + /// `ggml_backend_dev_props.device_id`, which names one physical GPU across + /// backends, or `null` when the backend reports none. + final String? deviceId; + + /// The device itself; `null` for a description that stands in for one. + final ggml_backend_dev_t? device; + + /// Whether the device belongs to ggml-vulkan. + bool get isVulkan => registry.toLowerCase() == 'vulkan'; + + @override + String toString() => name; +} + +final int _typeCpu = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_CPU.value; +final int _typeAccel = + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_ACCEL.value; +final int _typeGpu = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; +final int _typeIgpu = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU.value; +final int _splitNone = llama_split_mode.LLAMA_SPLIT_MODE_NONE.value; +final int _splitTensor = llama_split_mode.LLAMA_SPLIT_MODE_TENSOR.value; + +/// The devices llama.cpp `v0.6.0` uses for a model, in its order. +/// +/// Mirrors `llama_prepare_model_devices` (`src/llama.cpp`). With [listed] +/// (`llama_model_params.devices`) those devices are used. Without it the +/// [registered] devices are searched: in tensor split mode every device that +/// is not a CPU or an accelerator; otherwise RPC servers, then the discrete +/// GPUs, skipping one whose device id an earlier GPU has, and the integrated +/// GPUs of one backend only when there is no discrete GPU. In +/// `LLAMA_SPLIT_MODE_NONE` only the device [mainGpu] indexes is left, and +/// none for a negative or out-of-range [mainGpu]. +List selectModelDevices({ + required List registered, + required List? listed, + required int splitMode, + required int mainGpu, +}) { + final List devices; + if (listed != null) { + devices = listed; + } else if (splitMode == _splitTensor) { + devices = [ + for (final device in registered) + if (device.type != _typeCpu && device.type != _typeAccel) device, + ]; + } else { + final rpcServers = []; + final gpus = []; + final igpus = []; + for (final device in registered) { + if (device.type == _typeGpu) { + if (device.registry == 'RPC') { + rpcServers.add(device); + } else if (!gpus.any( + (gpu) => + gpu.deviceId != null && + device.deviceId != null && + gpu.deviceId == device.deviceId, + )) { + gpus.add(device); + } + } else if (device.type == _typeIgpu && + (igpus.isEmpty || igpus.last.registry == device.registry)) { + igpus.add(device); + } + } + devices = [...rpcServers, ...gpus, if (gpus.isEmpty) ...igpus]; + } + if (splitMode != _splitNone || devices.isEmpty) return devices; + return mainGpu >= 0 && mainGpu < devices.length + ? [devices[mainGpu]] + : const []; +} + +/// What a model load does about selected Vulkan devices ggml-vulkan cannot +/// drive. +final class VulkanLoadDecision { + const VulkanLoadDecision._({this.unsupported, this.devices}); + + /// Every selected device is usable or unknown: the load goes ahead as it + /// is. + static const VulkanLoadDecision unchanged = VulkanLoadDecision._(); + + /// Why the load must not start a device, or `null`. Names the first + /// unusable device and its versions. + final String? unsupported; + + /// The usable devices to list for the load in place of the selected ones; + /// `null` when no listed load can avoid the unusable devices, which is when + /// every selected device is one, and when nothing changes. + final List? devices; + + /// Whether no usable device is left, so the load cannot run on the GPU. + bool get refused => unsupported != null && devices == null; +} + +final RegExp _vulkanDeviceName = RegExp(r'^Vulkan(\d+)$'); + +/// Decides what a model load does about Vulkan devices below Vulkan 1.2. +/// +/// [usesGpu] is false for a load that offloads nothing, which never starts a +/// device. [backendRegistry] is the ggml registry of an explicit GPU backend, +/// whose devices the load lists (`llama_model_params.devices`) when it has +/// any, or `null` when llama.cpp selects among every registered device. +/// +/// Only the devices the load would use count: a registered device that is +/// not selected is never initialized (`ggml_backend_vk_reg_get_device` only +/// describes it). [registered] is read only for a load that [usesGpu], and +/// [probe] only when a Vulkan device is selected. A device the facts do not +/// cover is taken as usable. +VulkanLoadDecision resolveVulkanLoadDecision({ + required bool usesGpu, + required String? backendRegistry, + required int splitMode, + required int mainGpu, + required List Function() registered, + required VulkanDeviceProbe Function() probe, +}) { + if (!usesGpu) return VulkanLoadDecision.unchanged; + final devices = registered(); + final registry = backendRegistry?.toLowerCase(); + final ofBackend = [ + for (final device in devices) + if (device.registry.toLowerCase() == registry) device, + ]; + final selected = selectModelDevices( + registered: devices, + listed: ofBackend.isEmpty ? null : ofBackend, + splitMode: splitMode, + mainGpu: mainGpu, + ); + + final vulkanIndices = { + for (final device in selected) + if (device.isVulkan) + if (_vulkanDeviceName.firstMatch(device.name) case final match?) + device: int.parse(match.group(1)!), + }; + if (vulkanIndices.isEmpty) return VulkanLoadDecision.unchanged; + final facts = probe().devices; + if (facts == null) return VulkanLoadDecision.unchanged; + + String? unsupported; + final usable = []; + for (final device in selected) { + final index = vulkanIndices[device]; + final fact = index != null && index < facts.length ? facts[index] : null; + if (fact == null || fact.meetsVulkan12) { + usable.add(device); + continue; + } + String version(int value) => VulkanDeviceFacts.formatApiVersion(value); + unsupported ??= + "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both " + 'the Vulkan loader and the GPU driver, and "${fact.name}" ' + '(${device.name}) reports driver API ${version(fact.apiVersion)} ' + 'with loader API ${version(fact.instanceApiVersion)}'; + } + if (unsupported == null) return VulkanLoadDecision.unchanged; + return VulkanLoadDecision._( + unsupported: unsupported, + devices: usable.isEmpty ? null : usable, + ); +} diff --git a/skills/llamadart-embeddings/SKILL.md b/skills/llamadart-embeddings/SKILL.md index 943c63774..5e1c70485 100644 --- a/skills/llamadart-embeddings/SKILL.md +++ b/skills/llamadart-embeddings/SKILL.md @@ -46,7 +46,7 @@ description: >- together (and `contextSize` past its value). Causal LAST/unpooled models with memory retain chunked input support. - Native diffusion capability and EmbeddingGemma's forced non-causal mode - override attention metadata. Other models follow the pinned `v0.5.0` + override attention metadata. Other models follow the pinned `v0.6.0` boolean attention metadata, whose absent key defaults to causal. Missing architecture, invalid metadata or a missing required runtime probe fails with `LlamaUnsupportedException` before decoding; use a compatible runtime. diff --git a/test/support/recording_exit_teardown.dart b/test/support/recording_exit_teardown.dart index e3f4f0f39..97deeca11 100644 --- a/test/support/recording_exit_teardown.dart +++ b/test/support/recording_exit_teardown.dart @@ -52,6 +52,11 @@ final class RecordingExitTeardown { /// Addresses of the objects created or tracked through this API so far. final List owned = []; + /// The addresses in `llama_model_params.devices` of each + /// `llama_dart_model_load_from_file` so far; `null` for a load that listed + /// no devices. + final List?> loadDevices = ?>[]; + /// Token count of the batch of each `llama_dart_decode` so far. final List decodedTokens = []; @@ -129,6 +134,12 @@ final class RecordingExitTeardown { }, freeAddress: real.freeAddress, modelLoadFromFile: (path, params) { + final devices = params.devices; + loadDevices.add( + devices == nullptr + ? null + : [for (var i = 0; devices[i] != nullptr; i++) devices[i].address], + ); if (!_proceeds('llama_dart_model_load_from_file')) return nullptr; final model = real.modelLoadFromFile(path, params); owned.add(model.address); 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 d4f3bb677..d082731ad 100644 --- a/test/unit/backends/llama_cpp/exit_teardown_api_test.dart +++ b/test/unit/backends/llama_cpp/exit_teardown_api_test.dart @@ -613,6 +613,40 @@ void main() { }); }); + test('resolve picks the calls by what the runtime exports, and passes the ' + 'Windows rule on', () { + Pointer exported(String name) => Pointer.fromAddress(0x1000); + Never missing(String name) => + throw ArgumentError("Couldn't resolve native function '$name'"); + + for (final isWindows in [false, true]) { + // llamadart-native v0.6.0-1 and later: exit teardown and the barrier. + final current = LlamaCppObjectCalls.resolve( + isWindows: isWindows, + symbol: exported, + ); + expect(current.exit, isNotNull); + expect(current.failures.barrier, isNotNull); + expect(current.failures.isWindows, isWindows); + + // v0.5.0-1 to v0.6.0: exit teardown only. + final withoutBarrier = LlamaCppObjectCalls.resolve( + isWindows: isWindows, + symbol: (name) => + _symbols.contains(name) ? exported(name) : missing(name), + ); + expect(withoutBarrier.exit, isNotNull); + expect(withoutBarrier.failures.barrier, isNull); + expect(withoutBarrier.failures.isWindows, isWindows); + + // Older: the upstream functions. + expect( + LlamaCppObjectCalls.resolve(isWindows: isWindows, symbol: missing), + same(LlamaCppObjectCalls.upstream), + ); + } + }); + test('resolve adds the exception barrier of the pinned runtime', () { final calls = LlamaCppObjectCalls.resolve(isWindows: Platform.isWindows); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart index 01f6f5d78..9e5eeeb9b 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart @@ -616,7 +616,52 @@ void main() { await _generate(service, context, 'ab', _greedy), BackendGenerationLimit.maxTokens, ); + // A projector loaded afterwards is usable, at the same address too. service.freeMultimodalContext(projector); + projector = service.createMultimodalContext( + model, + '${dir.path}/mmproj.gguf', + ); + expect(await describe(), BackendGenerationLimit.maxTokens); + }); + + test('builds a bitmap of each media source through its own barrier ' + 'constructor', () async { + attach(); + final audioPath = '${dir.path}/clip.wav'; + File(audioPath).writeAsBytesSync(const [1, 2, 3]); + + for (final (part, constructor) in [ + ( + LlamaAudioContent(path: audioPath), + 'llama_dart_mtmd_bitmap_init_from_file', + ), + ( + LlamaAudioContent(bytes: Uint8List.fromList(const [1, 2, 3])), + 'llama_dart_mtmd_bitmap_init_from_buf', + ), + ( + LlamaAudioContent(samples: Float32List(1)), + 'llama_dart_mtmd_bitmap_init_from_audio', + ), + ]) { + barrier.calls.clear(); + + expect( + await _generate( + service, + context, + '<__media__>', + _greedy, + parts: [part], + ), + BackendGenerationLimit.maxTokens, + ); + + expect(barrier.calls.where((call) => call.contains('_mtmd_bitmap_')), [ + constructor, + ]); + } }); test('a media evaluation that throws is a typed error, and the context ' @@ -671,6 +716,20 @@ void main() { }); }); + test('reads device properties and memory through the barrier', () { + start(); + barrier.calls.clear(); + + // Every registered device is read, the CPU device included. + service.listGpuDevices(); + + expect(barrier.calls, contains('llama_dart_ggml_backend_dev_get_props')); + expect( + barrier.calls.where((call) => !call.contains('_ggml_backend_dev_')), + isEmpty, + ); + }); + test('a decision encoder pass that throws is a typed error, and the head ' 'is unusable until it is loaded again', () { start(); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart index d14720e02..b49039e26 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart @@ -15,6 +15,7 @@ import 'package:llamadart/src/backends/llama_cpp/decision_head.dart'; import 'package:llamadart/src/backends/llama_cpp/exit_teardown_api.dart'; import 'package:llamadart/src/backends/llama_cpp/llama_cpp_backend.dart'; 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/safetensors.dart'; import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; import 'package:llamadart/src/backends/llama_cpp/worker.dart'; @@ -5151,8 +5152,8 @@ void main() { /// its layers on a GPU backend this host does not have. /// /// [vulkanDevices] is what the Vulkan device facts report, for a ggml - /// registry of [registeredVulkanDevices] Vulkan devices; without it the - /// service reads them itself. + /// registry of [registeredVulkanDevices] Vulkan devices; without it they + /// are unavailable, so no case depends on the host's GPUs. Future<({List calls, int microBatch})> ingest( ModelParams params, { bool isAndroid = true, @@ -5168,13 +5169,17 @@ void main() { final service = LlamaCppService( isAndroid: isAndroid, objectCalls: LlamaCppObjectCalls.tracked(recorder.api), - deviceTypes: vulkanDevices == null - ? null - : (backend) => List.filled( - backend == GpuBackend.vulkan ? registeredVulkanDevices : 0, - ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value, - ), - vulkanDeviceProbe: vulkanDevices, + registeredDevices: () => [ + for (var index = 0; index < registeredVulkanDevices; index++) + GgmlDeviceEntry( + name: 'Vulkan$index', + type: ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value, + registry: 'Vulkan', + ), + ], + vulkanDeviceProbe: + vulkanDevices ?? + () => const VulkanDeviceProbe.unavailable('not read in this case'), ); addTearDown(service.dispose); final model = service.loadModel(modelPath, loadParams); @@ -5522,40 +5527,6 @@ void main() { ); }); - test('names the device and both versions when the driver or the loader ' - 'is below Vulkan 1.2', () { - expect( - LlamaCppService.vulkanUnsupportedReason( - VulkanDeviceProbe.devices([device(apiVersion: vulkan11)]), - ), - "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both the " - 'Vulkan loader and the GPU driver, and "Mali-G68" reports driver API ' - '1.1 with loader API 1.2', - ); - expect( - LlamaCppService.vulkanUnsupportedReason( - VulkanDeviceProbe.devices([ - device(name: 'Adreno 750'), - device(instanceApiVersion: vulkan11), - ]), - ), - contains('"Mali-G68" reports driver API 1.2 with loader API 1.1'), - ); - expect( - LlamaCppService.vulkanUnsupportedReason( - VulkanDeviceProbe.devices([device()]), - ), - isNull, - ); - expect( - LlamaCppService.vulkanUnsupportedReason( - const VulkanDeviceProbe.unavailable('no loader'), - ), - isNull, - reason: 'unknown devices are not refused', - ); - }); - group('at model load', () { late Directory tempDir; late String modelPath; @@ -5580,25 +5551,55 @@ void main() { tempDir.deleteSync(recursive: true); }); - // A host whose ggml registry holds one Vulkan GPU that [probe] - // describes. - LlamaCppService serviceWith(VulkanDeviceProbe Function() probe) { + final gpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; + final igpuType = + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU.value; + GgmlDeviceEntry entry(String name, {int? type, String? deviceId}) => + GgmlDeviceEntry( + name: name, + type: type ?? gpuType, + registry: name.replaceAll(RegExp(r'\d+$'), ''), + deviceId: deviceId, + ); + + // A host whose ggml registry holds [registered], one Vulkan GPU by + // default, and whose Vulkan device N has the driver API version + // [apiVersions][N]. [reads] counts the reads of the device facts. + var reads = 0; + LlamaCppService serviceWith( + List? apiVersions, { + List? registered, + }) { + reads = 0; final service = LlamaCppService( - deviceTypes: (_) => [ - ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value, - ], - vulkanDeviceProbe: probe, + deviceTypes: (_) => [gpuType], + registeredDevices: () => registered ?? [entry('Vulkan0')], + vulkanDeviceProbe: () { + reads++; + return apiVersions == null + ? const VulkanDeviceProbe.unavailable('no loader') + : VulkanDeviceProbe.devices([ + for (final (index, version) in apiVersions.indexed) + VulkanDeviceFacts( + index: index, + name: index == 0 ? 'Mali-G68' : 'UHD Graphics 630', + instanceApiVersion: VulkanDeviceFacts.vulkan12, + apiVersion: version, + subgroupSize: 32, + ), + ]); + }, ); addTearDown(service.dispose); return service; } - VulkanDeviceProbe below12() => - VulkanDeviceProbe.devices([device(apiVersion: vulkan11)]); + const vulkan13 = 1 << 22 | 3 << 12; + Matcher noVulkanWarning() => isNot(contains(contains('Vulkan 1.2'))); - test('ComputeDevice.gpu throws and loads nothing on a driver below ' - 'Vulkan 1.2', () { - final service = serviceWith(below12); + test('ComputeDevice.gpu throws and loads nothing when the only ' + 'selected device is below Vulkan 1.2', () { + final service = serviceWith([vulkan11]); expect( () => service.loadModel( @@ -5612,18 +5613,18 @@ void main() { 'ComputeDevice.gpu is not available for llama.cpp on ' "${Platform.operatingSystem}: llama.cpp's Vulkan backend " 'needs Vulkan 1.2 or later from both the Vulkan loader and ' - 'the GPU driver, and "Mali-G68" reports driver API 1.1 ' - 'with loader API 1.2. Use ComputeDevice.auto to run on the ' - 'CPU instead.', + 'the GPU driver, and "Mali-G68" (Vulkan0) reports driver ' + 'API 1.1 with loader API 1.2. Use ComputeDevice.auto to ' + 'run on the CPU instead.', ), ), ); expect(_readPrivateForTesting(service, '_models'), isEmpty); }); - test('ComputeDevice.auto loads on the CPU with a warning on a driver ' - 'below Vulkan 1.2', () { - final service = serviceWith(below12); + test('ComputeDevice.auto loads on the CPU with a warning when the only ' + 'selected device is below Vulkan 1.2', () { + final service = serviceWith([vulkan11]); final model = service.loadModel( modelPath, @@ -5637,7 +5638,7 @@ void main() { contains( allOf( contains('needs Vulkan 1.2 or later'), - contains('"Mali-G68" reports driver API 1.1'), + contains('"Mali-G68" (Vulkan0) reports driver API 1.1'), contains('so the model loaded on CPU with 0 GPU layers.'), ), ), @@ -5656,13 +5657,143 @@ void main() { expect(contextParams.op_offload, isFalse); }); - test('does not read the device facts for a CPU load', () { - var reads = 0; - final service = serviceWith(() { - reads++; - return below12(); + for (final device in [ComputeDevice.auto, ComputeDevice.gpu]) { + test('${device.name}: a capable discrete GPU is used although an ' + 'integrated GPU is on a driver below Vulkan 1.2', () { + for (final registered in [ + [entry('Vulkan0'), entry('Vulkan1', type: igpuType)], + // The discrete GPU also registered by CUDA, as the same device. + [ + entry('CUDA0', deviceId: '0000:01:00.0'), + entry('Vulkan0', deviceId: '0000:01:00.0'), + entry('Vulkan1', type: igpuType), + ], + ]) { + final service = serviceWith([ + vulkan13, + vulkan11, + ], registered: registered); + + service.loadModel( + modelPath, + ModelParams(contextSize: 64, device: device), + ); + + expect(service.getResolvedGpuLayers(), greaterThan(0)); + expect(warnings, noVulkanWarning()); + } }); + test('${device.name}: a CUDA GPU is used and a discrete Vulkan GPU ' + 'below 1.2 is left out of the load', () { + final service = serviceWith( + [vulkan11], + registered: [ + entry('CUDA0', deviceId: '0000:01:00.0'), + entry('Vulkan0', deviceId: '0000:02:00.0'), + ], + ); + + service.loadModel( + modelPath, + ModelParams(contextSize: 64, device: device), + ); + + expect(service.getResolvedGpuLayers(), greaterThan(0)); + expect( + warnings, + contains( + allOf( + contains('"Mali-G68" (Vulkan0) reports driver API 1.1'), + contains('so the model loaded without that device, on CUDA0.'), + ), + ), + ); + }); + } + + test('lists the usable devices for the load when it leaves one out, ' + 'and lists none otherwise', () { + // The load itself is stopped, so the stand-in devices are never + // used. + List? listedBy(List registered) { + final recorder = RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + )..fail = (name) => name == 'llama_dart_model_load_from_file'; + final service = LlamaCppService( + deviceTypes: (_) => [gpuType], + objectCalls: LlamaCppObjectCalls.tracked(recorder.api), + registeredDevices: () => registered, + vulkanDeviceProbe: () => VulkanDeviceProbe.devices([ + for (final (index, version) in [vulkan13, vulkan11].indexed) + VulkanDeviceFacts( + index: index, + name: 'GPU $index', + instanceApiVersion: VulkanDeviceFacts.vulkan12, + apiVersion: version, + subgroupSize: 32, + ), + ]), + ); + addTearDown(service.dispose); + expect( + () => service.loadModel( + modelPath, + const ModelParams(contextSize: 64), + ), + throwsA(isA()), + ); + return recorder.loadDevices.single; + } + + GgmlDeviceEntry standIn(String name, int address, {int? type}) => + GgmlDeviceEntry( + name: name, + type: type ?? gpuType, + registry: name.replaceAll(RegExp(r'\d+$'), ''), + device: Pointer.fromAddress(address), + ); + + expect( + listedBy([ + standIn('CUDA0', 0xC0DA), + standIn('Vulkan0', 0x1000), + standIn('Vulkan1', 0x2000), + ]), + [0xC0DA, 0x1000], + reason: 'Vulkan1 is below Vulkan 1.2', + ); + expect( + listedBy([ + standIn('Vulkan0', 0x1000), + standIn('Vulkan1', 0x2000, type: igpuType), + ]), + isNull, + reason: 'llama.cpp does not select the integrated GPU itself', + ); + }); + + test('an explicit CUDA backend does not read the Vulkan facts', () { + final service = serviceWith( + [vulkan11], + registered: [ + entry('CUDA0', deviceId: '0000:01:00.0'), + entry('Vulkan0', deviceId: '0000:02:00.0'), + ], + ); + + service.loadModel( + modelPath, + const ModelParams(contextSize: 64, preferredBackend: GpuBackend.cuda), + ); + + expect(reads, 0); + expect(warnings, noVulkanWarning()); + }); + + test('does not read the device facts for a CPU load', () { + final service = serviceWith([vulkan11]); + service.loadModel( modelPath, const ModelParams(contextSize: 64, device: ComputeDevice.cpu), @@ -5673,21 +5804,22 @@ void main() { ); expect(reads, 0); - expect(warnings, isNot(contains(contains('Vulkan 1.2')))); + expect(warnings, noVulkanWarning()); }); - test('loads on the GPU backend when the devices meet Vulkan 1.2 or ' - 'are unknown', () { - for (final probe in [ - () => VulkanDeviceProbe.devices([device()]), - () => const VulkanDeviceProbe.unavailable('no loader'), + test('loads on the GPU backend when the selected devices meet Vulkan ' + '1.2 or are unknown', () { + for (final apiVersions in [ + [vulkan13], + null, ]) { - final service = serviceWith(probe); + final service = serviceWith(apiVersions); service.loadModel(modelPath, const ModelParams(contextSize: 64)); + expect(reads, 1); expect(service.getResolvedGpuLayers(), greaterThan(0)); - expect(warnings, isNot(contains(contains('Vulkan 1.2')))); + expect(warnings, noVulkanWarning()); } }); }); diff --git a/test/unit/backends/llama_cpp/load_device_selection_test.dart b/test/unit/backends/llama_cpp/load_device_selection_test.dart new file mode 100644 index 000000000..74796ce86 --- /dev/null +++ b/test/unit/backends/llama_cpp/load_device_selection_test.dart @@ -0,0 +1,389 @@ +@TestOn('vm') +library; + +import 'package:llamadart/src/backends/llama_cpp/bindings.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:test/test.dart'; + +final _cpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_CPU.value; +final _accelType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_ACCEL.value; +final _gpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; +final _igpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU.value; + +const _none = 0; +const _layer = 1; +const _tensor = 3; + +const _vulkan11 = 1 << 22 | 1 << 12; +const _vulkan13 = 1 << 22 | 3 << 12; + +GgmlDeviceEntry _device( + String name, { + int? type, + String? registry, + String? deviceId, +}) => GgmlDeviceEntry( + name: name, + type: type ?? _gpuType, + registry: registry ?? name.replaceAll(RegExp(r'\d+$'), ''), + deviceId: deviceId, +); + +final _cpu = _device('CPU', type: _cpuType); +final _blas = _device('BLAS', type: _accelType); + +// Vulkan facts by device index: the driver API version of each. +VulkanDeviceProbe Function() _facts(List apiVersions) => + () => VulkanDeviceProbe.devices([ + for (final (index, version) in apiVersions.indexed) + VulkanDeviceFacts( + index: index, + name: 'GPU $index', + instanceApiVersion: _vulkan13, + apiVersion: version, + subgroupSize: 32, + ), + ]); + +void main() { + test('split modes match the llama_split_mode values', () { + expect(llama_split_mode.LLAMA_SPLIT_MODE_NONE.value, _none); + expect(llama_split_mode.LLAMA_SPLIT_MODE_LAYER.value, _layer); + expect(llama_split_mode.LLAMA_SPLIT_MODE_TENSOR.value, _tensor); + }); + + group('selectModelDevices', () { + List select( + List registered, { + List? listed, + int splitMode = _layer, + int mainGpu = 0, + }) => [ + for (final device in selectModelDevices( + registered: registered, + listed: listed, + splitMode: splitMode, + mainGpu: mainGpu, + )) + device.name, + ]; + + test('uses the listed devices as they are', () { + final listed = [_device('Vulkan1', type: _igpuType), _device('Vulkan0')]; + + expect(select([_cpu, _device('CUDA0')], listed: listed), [ + 'Vulkan1', + 'Vulkan0', + ]); + }); + + test('without a list takes the discrete GPUs and skips CPU and ' + 'accelerator devices', () { + expect(select([_cpu, _blas, _device('CUDA0'), _device('Vulkan0')]), [ + 'CUDA0', + 'Vulkan0', + ]); + }); + + test('takes integrated GPUs only when there is no discrete GPU, and ' + 'then those of one backend', () { + final igpu = _device('Vulkan1', type: _igpuType); + + expect(select([_cpu, _device('Vulkan0'), igpu]), ['Vulkan0']); + expect(select([_cpu, igpu]), ['Vulkan1']); + expect( + select([ + igpu, + _device('OpenCL0', type: _igpuType), + _device('Vulkan2', type: _igpuType), + ]), + ['Vulkan1', 'Vulkan2'], + reason: 'an integrated GPU of another backend is skipped', + ); + expect(select([igpu, _device('Vulkan2', type: _igpuType)]), [ + 'Vulkan1', + 'Vulkan2', + ]); + }); + + test('skips a discrete GPU whose device id an earlier one has', () { + expect( + select([ + _device('CUDA0', deviceId: '0000:01:00.0'), + _device('Vulkan0', deviceId: '0000:01:00.0'), + _device('Vulkan1', deviceId: '0000:02:00.0'), + _device('Vulkan2'), + _device('Vulkan3'), + ]), + ['CUDA0', 'Vulkan1', 'Vulkan2', 'Vulkan3'], + ); + }); + + test('puts RPC servers first, and they do not count as discrete ' + 'GPUs', () { + final igpu = _device('Vulkan0', type: _igpuType); + + expect(select([igpu, _device('RPC0')]), ['RPC0', 'Vulkan0']); + expect(select([_device('CUDA0'), igpu, _device('RPC0')]), [ + 'RPC0', + 'CUDA0', + ]); + }); + + test('tensor split mode takes every device that is not a CPU or an ' + 'accelerator', () { + expect( + select([ + _cpu, + _blas, + _device('Vulkan0'), + _device('Vulkan1', type: _igpuType), + ], splitMode: _tensor), + ['Vulkan0', 'Vulkan1'], + ); + }); + + test('single-device mode keeps the device mainGpu indexes, or none', () { + final registered = [_device('Vulkan0'), _device('Vulkan1')]; + + expect(select(registered, splitMode: _none), ['Vulkan0']); + expect(select(registered, splitMode: _none, mainGpu: 1), ['Vulkan1']); + expect(select(registered, splitMode: _none, mainGpu: 2), isEmpty); + expect(select(registered, splitMode: _none, mainGpu: -1), isEmpty); + expect( + select(const [], listed: registered, splitMode: _none, mainGpu: 1), + ['Vulkan1'], + ); + expect(select([_cpu], splitMode: _none), isEmpty); + }); + }); + + group('resolveVulkanLoadDecision', () { + late int registryReads; + late int probeReads; + + setUp(() { + registryReads = 0; + probeReads = 0; + }); + + VulkanLoadDecision decide( + List registered, + VulkanDeviceProbe Function() probe, { + String? backend, + bool usesGpu = true, + int splitMode = _layer, + int mainGpu = 0, + }) => resolveVulkanLoadDecision( + usesGpu: usesGpu, + backendRegistry: backend, + splitMode: splitMode, + mainGpu: mainGpu, + registered: () { + registryReads++; + return registered; + }, + probe: () { + probeReads++; + return probe(); + }, + ); + + Matcher unchanged() => isA() + .having((d) => d.unsupported, 'unsupported', isNull) + .having((d) => d.devices, 'devices', isNull) + .having((d) => d.refused, 'refused', isFalse); + + Matcher without(String excluded, List usable) => + isA() + .having((d) => d.unsupported, 'unsupported', contains(excluded)) + .having( + (d) => [for (final device in d.devices ?? const []) device.name], + 'devices', + usable, + ) + .having((d) => d.refused, 'refused', isFalse); + + Matcher refused(String device) => isA() + .having((d) => d.unsupported, 'unsupported', contains(device)) + .having((d) => d.devices, 'devices', isNull) + .having((d) => d.refused, 'refused', isTrue); + + final rtx = _device('Vulkan0', deviceId: '0000:01:00.0'); + final uhd = _device('Vulkan1', type: _igpuType); + final cuda = _device('CUDA0', deviceId: '0000:01:00.0'); + + test('a load that offloads nothing reads neither the registry nor the ' + 'facts', () { + expect( + decide([_device('Vulkan0')], _facts([_vulkan11]), usesGpu: false), + unchanged(), + ); + expect((registryReads, probeReads), (0, 0)); + }); + + test('refuses when the only selected device is below Vulkan 1.2, naming ' + 'it and its versions', () { + final decision = decide([_cpu, _device('Vulkan0')], _facts([_vulkan11])); + + expect(decision, refused('"GPU 0" (Vulkan0)')); + expect( + decision.unsupported, + "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both the " + 'Vulkan loader and the GPU driver, and "GPU 0" (Vulkan0) reports ' + 'driver API 1.1 with loader API 1.3', + ); + expect( + decide([_device('Vulkan0', type: _igpuType)], _facts([_vulkan11])), + refused('(Vulkan0)'), + reason: 'an integrated GPU is selected when it is the only GPU', + ); + }); + + test('a capable discrete GPU beside an integrated GPU on an old driver ' + 'changes nothing: the integrated one is not selected', () { + for (final registered in [ + [_cpu, rtx, uhd], + [_cpu, cuda, rtx, uhd], + ]) { + expect(decide(registered, _facts([_vulkan13, _vulkan11])), unchanged()); + } + }); + + test('a CUDA GPU beside an old Vulkan device does not read the Vulkan ' + 'facts when llama.cpp would not select that device', () { + // The same physical GPU through Vulkan, and an integrated GPU. + expect( + decide([cuda, rtx, uhd], () => fail('no Vulkan device is selected')), + unchanged(), + ); + expect(probeReads, 0); + }); + + test('leaves out a selected device below Vulkan 1.2 when usable devices ' + 'remain', () { + expect( + decide([ + _device('CUDA0', deviceId: '0000:01:00.0'), + _device('Vulkan0', deviceId: '0000:02:00.0'), + ], _facts([_vulkan11])), + without('(Vulkan0)', ['CUDA0']), + ); + expect( + decide([ + _device('Vulkan0'), + _device('Vulkan1'), + _device('Vulkan2'), + ], _facts([_vulkan13, _vulkan11, _vulkan13])), + without('"GPU 1" (Vulkan1)', ['Vulkan0', 'Vulkan2']), + ); + }); + + test('an explicit backend is judged by its own devices only', () { + final oldVulkan = _device('Vulkan0', deviceId: '0000:02:00.0'); + + expect( + decide( + [cuda, oldVulkan], + () => fail('CUDA lists no Vulkan device'), + backend: 'CUDA', + ), + unchanged(), + ); + expect(probeReads, 0); + + // The Vulkan backend lists every Vulkan device, integrated ones too. + expect( + decide( + [cuda, rtx, uhd], + _facts([_vulkan13, _vulkan11]), + backend: 'Vulkan', + ), + without('(Vulkan1)', ['Vulkan0']), + ); + expect( + decide( + [cuda, rtx, uhd], + _facts([_vulkan11, _vulkan11]), + backend: 'vulkan', + ), + refused('(Vulkan0)'), + ); + }); + + test('an explicit backend without a registered device falls back to ' + "llama.cpp's own selection", () { + expect( + decide([_device('Vulkan0')], _facts([_vulkan11]), backend: 'CUDA'), + refused('(Vulkan0)'), + ); + }); + + test('single-device mode judges the device mainGpu selects', () { + final registered = [_device('Vulkan0'), _device('Vulkan1')]; + final facts = _facts([_vulkan13, _vulkan11]); + + expect(decide(registered, facts, splitMode: _none), unchanged()); + expect( + decide(registered, facts, splitMode: _none, mainGpu: 1), + refused('(Vulkan1)'), + ); + expect( + decide(registered, facts, splitMode: _none, mainGpu: 5), + unchanged(), + reason: 'llama.cpp rejects the load before it starts a device', + ); + }); + + test('tensor split mode judges every GPU, integrated ones included', () { + expect( + decide([rtx, uhd], _facts([_vulkan13, _vulkan11]), splitMode: _tensor), + without('(Vulkan1)', ['Vulkan0']), + ); + }); + + test('unknown devices are not refused', () { + final registered = [_device('Vulkan0'), _device('Vulkan1')]; + + expect( + decide( + registered, + () => const VulkanDeviceProbe.unavailable('no loader'), + ), + unchanged(), + ); + expect( + decide(registered, _facts([_vulkan13])), + unchanged(), + reason: 'the facts do not cover Vulkan1', + ); + expect( + decide([_device('Renamed', registry: 'Vulkan')], _facts([_vulkan11])), + unchanged(), + reason: 'a name that is not VulkanN has no facts', + ); + expect(decide([_device('Vulkan0')], _facts([_vulkan13])), unchanged()); + }); + + test('a loader below Vulkan 1.2 counts like a driver below it', () { + expect( + decide( + [_device('Vulkan0')], + () => const VulkanDeviceProbe.devices([ + VulkanDeviceFacts( + index: 0, + name: 'Mali-G52', + instanceApiVersion: _vulkan11, + apiVersion: _vulkan13, + subgroupSize: 4, + ), + ]), + ).unsupported, + endsWith( + '"Mali-G52" (Vulkan0) reports driver API 1.3 with loader API 1.1', + ), + ); + }); + }); +} diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 3663b7fbc..d1dabd0ac 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -63,11 +63,12 @@ For canonical full release notes, use: only on a GPU whose subgroup size llama.cpp `v0.6.0` mis-tiles (16, or below 8) or cannot be read. Other GPUs decode a text prompt in full micro-batches ([#948](https://github.com/leehack/llamadart/issues/948)). -- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. On a - registered Vulkan GPU whose driver reports less, `ComputeDevice.gpu` now +- llama.cpp Vulkan needs Vulkan 1.2 from the loader and the GPU driver. When + the Vulkan GPU a load would run on reports less, `ComputeDevice.gpu` now throws `LlamaUnsupportedException` naming the GPU and both versions, and `ComputeDevice.auto` loads the model on the CPU with a warning, instead of - starting a driver llama.cpp cannot use + starting a driver llama.cpp cannot use; a load with other usable GPUs + leaves that one out ([#782](https://github.com/leehack/llamadart/issues/782)). - Aligned default WebGPU bridge assets to `v0.1.59`: they embed llama.cpp `v0.6.0`, are qualified against native `v0.6.0`, and keep Web/native diff --git a/website/docs/guides/embeddings.md b/website/docs/guides/embeddings.md index 17c613ecc..719270501 100644 --- a/website/docs/guides/embeddings.md +++ b/website/docs/guides/embeddings.md @@ -65,7 +65,7 @@ Future main() async { Causal models with a KV cache retain chunked LAST or unpooled embedding support. Batched one-pass inputs are grouped only within the micro-batch capacity, and every input is validated before any group is decoded. -- Native causal-attention detection follows the pinned llama.cpp `v0.5.0` +- Native causal-attention detection follows the pinned llama.cpp `v0.6.0` contract: the runtime's diffusion-model probe and EmbeddingGemma's forced non-causal attention take precedence over metadata. Other loaded models use their boolean `.attention.causal` value, defaulting to diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index 0dc38a777..5ffa202c8 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -184,11 +184,14 @@ output and grammars, sampling controls and speculative decoding. Guides: verification batches during generation. Those batches can exceed 32 tokens, so speculative decoding can still produce wrong output on an affected GPU. llama.cpp's Vulkan backend also needs Vulkan 1.2 from the Vulkan loader and - the GPU driver. When a registered Vulkan GPU's driver reports an older + the GPU driver. When the Vulkan GPU a load would run on reports an older version, `ComputeDevice.gpu` throws `LlamaUnsupportedException` naming the GPU and both versions, and `ComputeDevice.auto` loads the model on the CPU - and logs a warning; on Linux and Windows, `GGML_VK_VISIBLE_DEVICES` can - hide such a GPU from llama.cpp. Whether this is what crashes the Galaxy A53 + and logs a warning. A device that used to run Vulkan on a 1.1 driver now + takes that path. When other GPUs of the load are usable, such as a + discrete GPU beside an old one, the load leaves the old one out and logs a + warning; a GPU llama.cpp would not select, like an integrated GPU beside a + discrete one, changes nothing. Whether this is what crashes the Galaxy A53 is not confirmed. Keep `auto` or `cpu` on Android unless the app has validated Vulkan on its target devices. diff --git a/website/docs/troubleshooting/common-issues.md b/website/docs/troubleshooting/common-issues.md index 3b4954bb0..c9c3d9c12 100644 --- a/website/docs/troubleshooting/common-issues.md +++ b/website/docs/troubleshooting/common-issues.md @@ -118,12 +118,13 @@ backend; catch `LlamaException` to handle both. ### `ComputeDevice.gpu is not available ...: llama.cpp's Vulkan backend needs Vulkan 1.2` -`LlamaUnsupportedException`: llama.cpp found a Vulkan GPU whose driver, or -the system's Vulkan loader, reports a version below 1.2, which llama.cpp +`LlamaUnsupportedException`: every Vulkan GPU the load would run on has a +driver, or a Vulkan loader, that reports a version below 1.2, which llama.cpp needs. The message names the GPU and both versions. Under `ComputeDevice.auto` the same condition loads the model on the CPU and logs a -warning. Update the GPU driver, or on Linux and Windows hide that GPU from -llama.cpp with `GGML_VK_VISIBLE_DEVICES`. +warning. Update the GPU driver. A GPU the load would not use does not cause +this, and when another GPU of the load is usable the old one is only left +out. ### Vulkan driver crashes in the cooperative-matrix path From 5eb73ae63ae00ca2f72bdca5a384313d92417697 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 00:21:29 -0400 Subject: [PATCH 5/6] fix: match Vulkan device facts to ggml devices by name and kind The facts list is not ggml-vulkan's device list, so a registered device was judged by another device's facts when the two differed. A device is now matched by its Vulkan device name and whether it is integrated; a device that cannot be matched has unknown facts and changes nothing. The Android prompt cap no longer reads the facts when ggml-vulkan registered no device. --- doc/llama_cpp_exit_teardown.md | 23 +- .../backends/llama_cpp/llama_cpp_service.dart | 46 ++- .../llama_cpp/load_device_selection.dart | 50 ++- .../llama_cpp/vulkan_device_probe.dart | 21 +- ...llama_cpp_service_native_failure_test.dart | 23 ++ .../llama_cpp/llama_cpp_service_test.dart | 373 ++++++++++++++---- .../llama_cpp/load_device_selection_test.dart | 318 +++++++++++---- .../llama_cpp/vulkan_device_probe_test.dart | 69 ++-- 8 files changed, 699 insertions(+), 224 deletions(-) diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 7a1443847..f6e704288 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -119,10 +119,19 @@ A failed `GGML_ASSERT` still aborts: the barrier catches exceptions only. `lib/src/backends/llama_cpp/vulkan_device_probe.dart` binds `llama_dart_vulkan_get_device_count` and `llama_dart_vulkan_get_device_info` -(`v0.6.0-1`), which list the devices ggml-vulkan registers with their API -versions and subgroup size. Reading them makes the Vulkan loader load the -system's GPU drivers, so the service reads them once, and only when a -registered Vulkan device is about to be used by a load or a context: +(`v0.6.0-1`), which list the system's Vulkan devices with their name, type, +API versions and subgroup size. Reading them makes the Vulkan loader load +the system's GPU drivers, so the service reads them once, and only where +ggml-vulkan has registered a device: for a load that selects one, and for an +Android Vulkan context. + +The list follows ggml-vulkan's order but is not always its list: the two can +differ for a device below Vulkan 1.2 beside other GPUs and with more than 16 +devices, so `VulkanN` is not entry `N`. A registered device is matched to its +facts by what both sides report, the Vulkan device name +(`ggml_backend_dev_props` `description`) and integrated or discrete. A device +with no such entry, or with several that disagree on Vulkan 1.2, has unknown +facts. - llama.cpp `v0.6.0` needs Vulkan 1.2 (`ggml_vk_instance_init` refuses an older loader; for an older driver ggml-vulkan reads @@ -136,7 +145,7 @@ registered Vulkan device is about to be used by a load or a context: device id, and integrated GPUs only when there is no discrete one; in single-device mode the one `mainGpu` indexes. A CUDA device, an unselected integrated GPU and a GPU of another backend never count. When every - selected device is below 1.2, `ComputeDevice.gpu` throws + selected device is known to be below 1.2, `ComputeDevice.gpu` throws `LlamaUnsupportedException` and `ComputeDevice.auto` loads on the CPU with a warning. When usable devices remain, the load lists those and logs a warning naming the device it left out. A speculative draft model gets the @@ -150,8 +159,8 @@ registered Vulkan device is about to be used by a load or a context: (https://github.com/ggml-org/llama.cpp/issues/28637). A runtime without the functions, a loader that cannot be queried and a device -list that does not match ggml's all count as unknown: the cap stays and no -load is refused. +that cannot be matched all count as unknown: the cap stays, and no load is +refused or narrowed. ## Which exits are covered diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index 973be5002..b7087d8fa 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -694,8 +694,9 @@ class LlamaCppService { final List Function()? _registeredDevicesOverride; // Reading the facts loads the system's GPU drivers into the process, so - // they are read once, and only when a registered Vulkan device is about to - // be used: ggml-vulkan has loaded the drivers by then. + // they are read once, and only for a load that selects a registered + // ggml-vulkan device or an Android context of a registry that has one: + // ggml-vulkan has loaded the drivers by then. late final VulkanDeviceProbe _vulkanDeviceProbe = (_vulkanDeviceProbeOverride ?? () => VulkanDeviceInfoApi.probeRuntime(isWindows: _isWindows))(); @@ -2115,31 +2116,38 @@ class LlamaCppService { List _registeredDevices() { final override = _registeredDevicesOverride; if (override != null) return override(); - final gpu = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; final props = calloc(); try { return [ for (var i = 0; i < _ggmlBackendDevCount(); i++) if (_ggmlBackendDevGet(i) case final device when device != nullptr) - GgmlDeviceEntry( - name: _utf8OrEmpty(_ggmlBackendDevName(device)), - type: _ggmlBackendDevType(device), - registry: _registryNameOf(device), - // llama.cpp compares the id of discrete GPUs only. - deviceId: - _ggmlBackendDevType(device) == gpu && - _ggmlBackendDevGetProps(device, props) && - props.ref.device_id != nullptr - ? _utf8OrEmpty(props.ref.device_id) - : null, - device: device, - ), + _describeDevice(device, props), ]; } finally { calloc.free(props); } } + GgmlDeviceEntry _describeDevice( + ggml_backend_dev_t device, + Pointer props, + ) { + final type = _ggmlBackendDevType(device); + // The properties of a GPU are all llama.cpp and the Vulkan check read. + final hasProps = + _isGpuClassDevice(device) && _ggmlBackendDevGetProps(device, props); + return GgmlDeviceEntry( + name: _utf8OrEmpty(_ggmlBackendDevName(device)), + type: type, + registry: _registryNameOf(device), + description: hasProps ? _utf8OrEmpty(props.ref.description) : '', + deviceId: hasProps && props.ref.device_id != nullptr + ? _utf8OrEmpty(props.ref.device_id) + : null, + device: device, + ); + } + String _registryNameOf(ggml_backend_dev_t device) { final registry = _ggmlBackendDevBackendReg(device); return registry == nullptr @@ -4176,10 +4184,14 @@ class LlamaCppService { } bool _androidVulkanHasSmallMatmulTileDefect() { + final registeredDeviceCount = _registeredVulkanDeviceCount(); + // Without a ggml-vulkan device there is nothing to learn, and the facts + // are not to be read where Vulkan is ruled out. + if (registeredDeviceCount == 0) return true; final probe = _vulkanDeviceProbe; final defect = vulkanSmallMatmulTileDefect( probe, - registeredDeviceCount: _registeredVulkanDeviceCount(), + registeredDeviceCount: registeredDeviceCount, ); LlamaLogger.instance.debug( 'llama_cpp_service: Android Vulkan text prompt decode is ' diff --git a/lib/src/backends/llama_cpp/load_device_selection.dart b/lib/src/backends/llama_cpp/load_device_selection.dart index 1f055baf4..931028ad4 100644 --- a/lib/src/backends/llama_cpp/load_device_selection.dart +++ b/lib/src/backends/llama_cpp/load_device_selection.dart @@ -9,6 +9,7 @@ final class GgmlDeviceEntry { required this.name, required this.type, required this.registry, + this.description = '', this.deviceId, this.device, }); @@ -22,6 +23,10 @@ final class GgmlDeviceEntry { /// `ggml_backend_reg_name` of the device's backend, such as `Vulkan`. final String registry; + /// `ggml_backend_dev_description`: for a ggml-vulkan device the + /// `VkPhysicalDeviceProperties.deviceName`. Empty when it was not read. + final String description; + /// `ggml_backend_dev_props.device_id`, which names one physical GPU across /// backends, or `null` when the backend reports none. final String? deviceId; @@ -119,7 +124,33 @@ final class VulkanLoadDecision { bool get refused => unsupported != null && devices == null; } -final RegExp _vulkanDeviceName = RegExp(r'^Vulkan(\d+)$'); +/// The facts of the ggml-vulkan [device] among [facts], or `null` when they +/// cannot be told. +/// +/// The two lists are not matched by position: ggml-vulkan and the facts can +/// disagree on which devices exist, as for a device below Vulkan 1.2 beside +/// other GPUs. What both report of a device is its Vulkan device name, which +/// is ggml's description, and whether it is an integrated GPU. Facts of that +/// name and kind are the device's only when all of them agree on whether +/// they meet Vulkan 1.2, as identical GPUs on one driver do; otherwise, and +/// without any, the device is unknown. +VulkanDeviceFacts? vulkanFactsOf( + GgmlDeviceEntry device, + List facts, +) { + if (!device.isVulkan || device.description.isEmpty) return null; + final integrated = device.type == _typeIgpu; + final named = [ + for (final fact in facts) + if (fact.name == device.description && fact.isIntegratedGpu == integrated) + fact, + ]; + if (named.isEmpty || + named.any((fact) => fact.meetsVulkan12 != named.first.meetsVulkan12)) { + return null; + } + return named.first; +} /// Decides what a model load does about Vulkan devices below Vulkan 1.2. /// @@ -131,8 +162,8 @@ final RegExp _vulkanDeviceName = RegExp(r'^Vulkan(\d+)$'); /// Only the devices the load would use count: a registered device that is /// not selected is never initialized (`ggml_backend_vk_reg_get_device` only /// describes it). [registered] is read only for a load that [usesGpu], and -/// [probe] only when a Vulkan device is selected. A device the facts do not -/// cover is taken as usable. +/// [probe] only when a Vulkan device is selected. A device whose facts +/// [vulkanFactsOf] cannot tell is taken as usable. VulkanLoadDecision resolveVulkanLoadDecision({ required bool usesGpu, required String? backendRegistry, @@ -155,21 +186,16 @@ VulkanLoadDecision resolveVulkanLoadDecision({ mainGpu: mainGpu, ); - final vulkanIndices = { - for (final device in selected) - if (device.isVulkan) - if (_vulkanDeviceName.firstMatch(device.name) case final match?) - device: int.parse(match.group(1)!), - }; - if (vulkanIndices.isEmpty) return VulkanLoadDecision.unchanged; + if (!selected.any((device) => device.isVulkan)) { + return VulkanLoadDecision.unchanged; + } final facts = probe().devices; if (facts == null) return VulkanLoadDecision.unchanged; String? unsupported; final usable = []; for (final device in selected) { - final index = vulkanIndices[device]; - final fact = index != null && index < facts.length ? facts[index] : null; + final fact = vulkanFactsOf(device, facts); if (fact == null || fact.meetsVulkan12) { usable.add(device); continue; diff --git a/lib/src/backends/llama_cpp/vulkan_device_probe.dart b/lib/src/backends/llama_cpp/vulkan_device_probe.dart index b2c3a1314..aa767ec90 100644 --- a/lib/src/backends/llama_cpp/vulkan_device_probe.dart +++ b/lib/src/backends/llama_cpp/vulkan_device_probe.dart @@ -13,10 +13,10 @@ typedef _DeviceInfoNative = /// One Vulkan device as libllamadart reads it from the Vulkan loader. final class VulkanDeviceFacts { - /// Creates the facts of device [index]. + /// Creates the facts of the device called [name]. const VulkanDeviceFacts({ - required this.index, required this.name, + required this.deviceType, required this.instanceApiVersion, required this.apiVersion, required this.subgroupSize, @@ -25,12 +25,17 @@ final class VulkanDeviceFacts { /// Vulkan 1.2 as `VK_MAKE_API_VERSION` encodes it. static const int vulkan12 = 1 << 22 | 2 << 12; - /// The index ggml-vulkan gives the device: `Vulkan0` is index 0. - final int index; - - /// `VkPhysicalDeviceProperties.deviceName`. + /// `VkPhysicalDeviceProperties.deviceName`, which ggml-vulkan gives its + /// device as `ggml_backend_dev_description`. final String name; + /// `VkPhysicalDeviceProperties.deviceType`, a `VkPhysicalDeviceType`. + final int deviceType; + + /// Whether the device is `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`, which + /// ggml-vulkan registers as an integrated GPU. + bool get isIntegratedGpu => deviceType == 1; + /// `vkEnumerateInstanceVersion`: the Vulkan loader's version. final int instanceApiVersion; @@ -67,7 +72,7 @@ final class VulkanDeviceFacts { @override String toString() => - 'Vulkan$index "$name" (API ${formatApiVersion(apiVersion)}, loader ' + '"$name" (API ${formatApiVersion(apiVersion)}, loader ' '${formatApiVersion(instanceApiVersion)}, subgroup size $subgroupSize)'; } @@ -186,8 +191,8 @@ final class VulkanDeviceInfoApi { } devices.add( VulkanDeviceFacts( - index: index, name: _deviceName(info.ref), + deviceType: info.ref.device_type, instanceApiVersion: info.ref.instance_api_version, apiVersion: info.ref.api_version, subgroupSize: info.ref.subgroup_size, diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart index 9e5eeeb9b..e375088ee 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart @@ -3,6 +3,7 @@ library; import 'dart:ffi'; import 'dart:io'; +import 'dart:mirrors'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; @@ -728,6 +729,28 @@ void main() { barrier.calls.where((call) => !call.contains('_ggml_backend_dev_')), isEmpty, ); + + // The memory read is the fallback of a GPU that reports none in its + // properties, which a CPU host has no device for. + barrier.calls.clear(); + final owner = reflectClass(LlamaCppService).owner as LibraryMirror; + final free = calloc(); + final total = calloc(); + addTearDown(() { + calloc.free(free); + calloc.free(total); + }); + bool readMemory() => + reflect(service).invoke( + MirrorSystem.getSymbol('_ggmlBackendDevMemory', owner), + [ggml_backend_dev_get(0), free, total], + ).reflectee + as bool; + + expect(readMemory(), isTrue); + expect(barrier.calls, ['llama_dart_ggml_backend_dev_memory']); + barrier.failing.add('llama_dart_ggml_backend_dev_memory'); + expect(readMemory(), isFalse); }); test('a decision encoder pass that throws is a typed error, and the head ' diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart index b49039e26..63b92614f 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart @@ -5251,8 +5251,8 @@ void main() { () => VulkanDeviceProbe.devices([ for (final (index, size) in sizes.indexed) VulkanDeviceFacts( - index: index, name: 'GPU $index', + deviceType: 2, instanceApiVersion: VulkanDeviceFacts.vulkan12, apiVersion: VulkanDeviceFacts.vulkan12, subgroupSize: size, @@ -5360,6 +5360,18 @@ void main() { ); expect(reads, 0); + // Vulkan was asked for, but ggml-vulkan registered no device. + expect( + await ingest( + vulkan, + loadedGpuLayers: 1, + vulkanDevices: counted, + registeredVulkanDevices: 0, + ), + decodes(capped), + ); + expect(reads, 0); + await ingest(vulkan, loadedGpuLayers: 1, vulkanDevices: counted); expect(reads, 1); }); @@ -5429,8 +5441,8 @@ void main() { int? apiVersion, int subgroupSize = 4, }) => VulkanDeviceFacts( - index: 0, name: name, + deviceType: 2, instanceApiVersion: instanceApiVersion ?? VulkanDeviceFacts.vulkan12, apiVersion: apiVersion ?? VulkanDeviceFacts.vulkan12, subgroupSize: subgroupSize, @@ -5554,52 +5566,78 @@ void main() { final gpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU.value; final igpuType = ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU.value; - GgmlDeviceEntry entry(String name, {int? type, String? deviceId}) => - GgmlDeviceEntry( - name: name, - type: type ?? gpuType, - registry: name.replaceAll(RegExp(r'\d+$'), ''), - deviceId: deviceId, - ); + const vulkan13 = 1 << 22 | 3 << 12; - // A host whose ggml registry holds [registered], one Vulkan GPU by - // default, and whose Vulkan device N has the driver API version - // [apiVersions][N]. [reads] counts the reads of the device facts. + // A registered ggml device; [description] is the Vulkan device name + // its facts are found by. + GgmlDeviceEntry entry( + String name, { + String description = '', + int? type, + String? deviceId, + int? address, + }) => GgmlDeviceEntry( + name: name, + type: type ?? gpuType, + registry: name.replaceAll(RegExp(r'\d+$'), ''), + description: description, + deviceId: deviceId, + device: address == null ? null : Pointer.fromAddress(address), + ); + + VulkanDeviceFacts fact( + String name, + int apiVersion, { + bool integrated = false, + }) => VulkanDeviceFacts( + name: name, + deviceType: integrated ? 1 : 2, + instanceApiVersion: VulkanDeviceFacts.vulkan12, + apiVersion: apiVersion, + subgroupSize: 32, + ); + + final mali = entry('Vulkan0', description: 'Mali-G68'); + final maliOld = fact('Mali-G68', vulkan11); + final rtx = entry('Vulkan0', description: 'RTX 4090'); + final rtxOk = fact('RTX 4090', vulkan13); + final uhd = entry( + 'Vulkan1', + description: 'UHD Graphics 630', + type: igpuType, + ); + final uhdOld = fact('UHD Graphics 630', vulkan11, integrated: true); + + // A host whose ggml registry holds [registered] and whose Vulkan + // devices report [facts], or no facts at all. [reads] counts the reads + // of the facts. var reads = 0; LlamaCppService serviceWith( - List? apiVersions, { - List? registered, + List registered, + List? facts, { + LlamaCppObjectCalls? objectCalls, }) { reads = 0; final service = LlamaCppService( deviceTypes: (_) => [gpuType], - registeredDevices: () => registered ?? [entry('Vulkan0')], + objectCalls: objectCalls, + registeredDevices: () => registered, vulkanDeviceProbe: () { reads++; - return apiVersions == null + return facts == null ? const VulkanDeviceProbe.unavailable('no loader') - : VulkanDeviceProbe.devices([ - for (final (index, version) in apiVersions.indexed) - VulkanDeviceFacts( - index: index, - name: index == 0 ? 'Mali-G68' : 'UHD Graphics 630', - instanceApiVersion: VulkanDeviceFacts.vulkan12, - apiVersion: version, - subgroupSize: 32, - ), - ]); + : VulkanDeviceProbe.devices(facts); }, ); addTearDown(service.dispose); return service; } - const vulkan13 = 1 << 22 | 3 << 12; Matcher noVulkanWarning() => isNot(contains(contains('Vulkan 1.2'))); test('ComputeDevice.gpu throws and loads nothing when the only ' 'selected device is below Vulkan 1.2', () { - final service = serviceWith([vulkan11]); + final service = serviceWith([mali], [maliOld]); expect( () => service.loadModel( @@ -5624,7 +5662,7 @@ void main() { test('ComputeDevice.auto loads on the CPU with a warning when the only ' 'selected device is below Vulkan 1.2', () { - final service = serviceWith([vulkan11]); + final service = serviceWith([mali], [maliOld]); final model = service.loadModel( modelPath, @@ -5661,18 +5699,19 @@ void main() { test('${device.name}: a capable discrete GPU is used although an ' 'integrated GPU is on a driver below Vulkan 1.2', () { for (final registered in [ - [entry('Vulkan0'), entry('Vulkan1', type: igpuType)], + [rtx, uhd], // The discrete GPU also registered by CUDA, as the same device. [ entry('CUDA0', deviceId: '0000:01:00.0'), - entry('Vulkan0', deviceId: '0000:01:00.0'), - entry('Vulkan1', type: igpuType), + entry( + 'Vulkan0', + description: 'RTX 4090', + deviceId: '0000:01:00.0', + ), + uhd, ], ]) { - final service = serviceWith([ - vulkan13, - vulkan11, - ], registered: registered); + final service = serviceWith(registered, [rtxOk, uhdOld]); service.loadModel( modelPath, @@ -5687,11 +5726,15 @@ void main() { test('${device.name}: a CUDA GPU is used and a discrete Vulkan GPU ' 'below 1.2 is left out of the load', () { final service = serviceWith( - [vulkan11], - registered: [ + [ entry('CUDA0', deviceId: '0000:01:00.0'), - entry('Vulkan0', deviceId: '0000:02:00.0'), + entry( + 'Vulkan0', + description: 'Mali-G68', + deviceId: '0000:02:00.0', + ), ], + [maliOld], ); service.loadModel( @@ -5710,32 +5753,88 @@ void main() { ), ); }); + + // ggml-vulkan and the facts can list different devices. + test('${device.name}: facts that also list a device ggml did not ' + 'register are matched by device name, not by position', () { + final rx = entry('Vulkan1', description: 'RX 7900'); + final rxOk = fact('RX 7900', vulkan13); + final gtxOld = fact('GTX 660', vulkan11); + + for (final (registered, facts) in [ + ([rtx], [uhdOld, rtxOk]), + ([rtx, rx], [gtxOld, rtxOk, rxOk]), + ([rtx, rx], [rtxOk, rxOk, gtxOld]), + // No facts for one registered device. + ([rtx, rx], [rtxOk]), + // Identical GPUs. + ([rtx, entry('Vulkan1', description: 'RTX 4090')], [rtxOk, rtxOk]), + ]) { + warnings.clear(); + final service = serviceWith(registered, facts); + + service.loadModel( + modelPath, + ModelParams(contextSize: 64, device: device), + ); + + expect(reads, 1); + expect(service.getResolvedGpuLayers(), greaterThan(0)); + expect(warnings, noVulkanWarning()); + } + }); } + test('an explicit Vulkan backend is matched by device name too', () { + final service = serviceWith([rtx], [uhdOld, rtxOk]); + + service.loadModel( + modelPath, + const ModelParams( + contextSize: 64, + preferredBackend: GpuBackend.vulkan, + ), + ); + + expect(warnings, noVulkanWarning()); + }); + + test('names the registered device that is below Vulkan 1.2, wherever ' + 'its facts are listed', () { + final service = serviceWith( + [entry('Vulkan0', description: 'GTX 660')], + [rtxOk, fact('GTX 660', vulkan11)], + ); + + expect( + () => service.loadModel( + modelPath, + const ModelParams(contextSize: 64, device: ComputeDevice.gpu), + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('"GTX 660" (Vulkan0) reports driver API 1.1'), + ), + ), + ); + }); + + // The load itself is stopped, so the stand-in devices are never used. + RecordingExitTeardown stoppedLoads() => RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + )..fail = (name) => name == 'llama_dart_model_load_from_file'; + test('lists the usable devices for the load when it leaves one out, ' 'and lists none otherwise', () { - // The load itself is stopped, so the stand-in devices are never - // used. List? listedBy(List registered) { - final recorder = RecordingExitTeardown( - ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, - )..fail = (name) => name == 'llama_dart_model_load_from_file'; - final service = LlamaCppService( - deviceTypes: (_) => [gpuType], - objectCalls: LlamaCppObjectCalls.tracked(recorder.api), - registeredDevices: () => registered, - vulkanDeviceProbe: () => VulkanDeviceProbe.devices([ - for (final (index, version) in [vulkan13, vulkan11].indexed) - VulkanDeviceFacts( - index: index, - name: 'GPU $index', - instanceApiVersion: VulkanDeviceFacts.vulkan12, - apiVersion: version, - subgroupSize: 32, - ), - ]), - ); - addTearDown(service.dispose); + final recorder = stoppedLoads(); + final service = serviceWith(registered, [ + rtxOk, + fact('GTX 660', vulkan11), + uhdOld, + ], objectCalls: LlamaCppObjectCalls.tracked(recorder.api)); expect( () => service.loadModel( modelPath, @@ -5746,40 +5845,105 @@ void main() { return recorder.loadDevices.single; } - GgmlDeviceEntry standIn(String name, int address, {int? type}) => - GgmlDeviceEntry( - name: name, - type: type ?? gpuType, - registry: name.replaceAll(RegExp(r'\d+$'), ''), - device: Pointer.fromAddress(address), - ); - expect( listedBy([ - standIn('CUDA0', 0xC0DA), - standIn('Vulkan0', 0x1000), - standIn('Vulkan1', 0x2000), + entry('CUDA0', address: 0xC0DA), + entry('Vulkan0', description: 'RTX 4090', address: 0x1000), + entry('Vulkan1', description: 'GTX 660', address: 0x2000), ]), [0xC0DA, 0x1000], reason: 'Vulkan1 is below Vulkan 1.2', ); expect( listedBy([ - standIn('Vulkan0', 0x1000), - standIn('Vulkan1', 0x2000, type: igpuType), + entry('Vulkan0', description: 'RTX 4090', address: 0x1000), + entry( + 'Vulkan1', + description: 'UHD Graphics 630', + type: igpuType, + address: 0x2000, + ), ]), isNull, reason: 'llama.cpp does not select the integrated GPU itself', ); }); + test('a speculative draft model is loaded on the same usable ' + 'devices', () async { + final recorder = RecordingExitTeardown( + ExitTeardownApi.tryResolve(isWindows: Platform.isWindows)!, + ); + var registered = []; + final service = LlamaCppService( + deviceTypes: (_) => [gpuType], + objectCalls: LlamaCppObjectCalls.tracked(recorder.api), + registeredDevices: () => registered, + vulkanDeviceProbe: () => + VulkanDeviceProbe.devices([fact('GTX 660', vulkan11)]), + ); + addTearDown(service.dispose); + const params = ModelParams(contextSize: 64, gpuLayers: 0); + final model = service.loadModel(modelPath, params); + final context = service.createContext(model, params); + // The target as a load that kept its layers on a GPU backend this + // host may not have. + _readPrivateForTesting>( + service, + '_modelBackendNames', + )[model] = 'CUDA'; + _readPrivateForTesting>( + service, + '_modelResolvedGpuLayers', + )[model] = 1; + _readPrivateForTesting>( + service, + '_modelLoadParams', + )[model] = const ModelParams( + contextSize: 64, + ); + registered = [ + entry('CUDA0', address: 0xC0DA), + entry('Vulkan0', description: 'GTX 660', address: 0x2000), + ]; + recorder.fail = (name) => name == 'llama_dart_model_load_from_file'; + + final cancel = calloc(); + addTearDown(() => calloc.free(cancel)); + await expectLater( + service + .generate( + context, + 'ab', + GenerationParams( + maxTokens: 2, + temp: 0, + speculativeDecodingConfig: + SpeculativeDecodingConfig.draftSimple( + // ignore: deprecated_member_use_from_same_package + draftModelPath: modelPath, + draftTokenMax: 4, + ), + ), + cancel.address, + ) + .drain(), + throwsA(isA()), + ); + + expect(recorder.loadDevices, [ + null, + [0xC0DA], + ], reason: 'the target load, then the draft load'); + }); + test('an explicit CUDA backend does not read the Vulkan facts', () { final service = serviceWith( - [vulkan11], - registered: [ + [ entry('CUDA0', deviceId: '0000:01:00.0'), - entry('Vulkan0', deviceId: '0000:02:00.0'), + entry('Vulkan0', description: 'Mali-G68', deviceId: '0000:02:00.0'), ], + [maliOld], ); service.loadModel( @@ -5792,7 +5956,7 @@ void main() { }); test('does not read the device facts for a CPU load', () { - final service = serviceWith([vulkan11]); + final service = serviceWith([mali], [maliOld]); service.loadModel( modelPath, @@ -5809,11 +5973,11 @@ void main() { test('loads on the GPU backend when the selected devices meet Vulkan ' '1.2 or are unknown', () { - for (final apiVersions in [ - [vulkan13], + for (final facts in [ + [fact('Mali-G68', vulkan13)], null, ]) { - final service = serviceWith(apiVersions); + final service = serviceWith([mali], facts); service.loadModel(modelPath, const ModelParams(contextSize: 64)); @@ -5823,6 +5987,55 @@ void main() { } }); }); + + // Runs the real llama.cpp runtime: its registry has a CPU device. + test('reads each registered device with its name, type and registry', () { + final service = LlamaCppService()..initializeBackend(); + addTearDown(service.dispose); + + final registered = _invokePrivateForTesting>( + service, + '_registeredDevices', + const [], + ); + + expect(registered, isNotEmpty); + for (final (index, device) in registered.indexed) { + expect(device.device, ggml_backend_dev_get(index)); + expect( + device.name, + ggml_backend_dev_name(device.device!).cast().toDartString(), + ); + expect(device.type, ggml_backend_dev_type$1(device.device!).value); + expect( + device.registry, + ggml_backend_reg_name( + ggml_backend_dev_backend_reg(device.device!), + ).cast().toDartString(), + ); + expect(device.registry, isNotEmpty); + final isGpu = const [ + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU, + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU, + ].any((type) => type.value == device.type); + expect( + device.description, + isGpu + ? ggml_backend_dev_description( + device.device!, + ).cast().toDartString() + : isEmpty, + ); + } + expect( + registered.where( + (device) => + device.type == + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_CPU.value, + ), + isNotEmpty, + ); + }); }); group('shouldKeepAndroidVulkanKqvOffloadEnabled', () { diff --git a/test/unit/backends/llama_cpp/load_device_selection_test.dart b/test/unit/backends/llama_cpp/load_device_selection_test.dart index 74796ce86..b80dc68f3 100644 --- a/test/unit/backends/llama_cpp/load_device_selection_test.dart +++ b/test/unit/backends/llama_cpp/load_device_selection_test.dart @@ -23,28 +23,35 @@ GgmlDeviceEntry _device( int? type, String? registry, String? deviceId, + String description = '', }) => GgmlDeviceEntry( name: name, type: type ?? _gpuType, registry: registry ?? name.replaceAll(RegExp(r'\d+$'), ''), + description: description, deviceId: deviceId, ); final _cpu = _device('CPU', type: _cpuType); final _blas = _device('BLAS', type: _accelType); -// Vulkan facts by device index: the driver API version of each. -VulkanDeviceProbe Function() _facts(List apiVersions) => - () => VulkanDeviceProbe.devices([ - for (final (index, version) in apiVersions.indexed) - VulkanDeviceFacts( - index: index, - name: 'GPU $index', - instanceApiVersion: _vulkan13, - apiVersion: version, - subgroupSize: 32, - ), - ]); +// A Vulkan device as the facts report it: its Vulkan device name, which is +// the description of the ggml device, and the driver API version. +VulkanDeviceFacts _fact( + String name, + int apiVersion, { + bool integrated = false, + int instanceApiVersion = _vulkan13, +}) => VulkanDeviceFacts( + name: name, + deviceType: integrated ? 1 : 2, + instanceApiVersion: instanceApiVersion, + apiVersion: apiVersion, + subgroupSize: 32, +); + +VulkanDeviceProbe Function() _facts(List facts) => + () => VulkanDeviceProbe.devices(facts); void main() { test('split modes match the llama_split_mode values', () { @@ -159,6 +166,74 @@ void main() { }); }); + group('vulkanFactsOf', () { + final rtx = _device('Vulkan0', description: 'RTX 4090'); + + test('finds the facts by the Vulkan device name and kind, not by ' + 'position', () { + final facts = [ + _fact('UHD Graphics 630', _vulkan11, integrated: true), + _fact('RTX 4090', _vulkan13), + ]; + + expect(vulkanFactsOf(rtx, facts), same(facts[1])); + expect( + vulkanFactsOf( + _device('Vulkan1', type: _igpuType, description: 'UHD Graphics 630'), + facts, + ), + same(facts[0]), + ); + }); + + test('knows nothing of a device without facts of its name and kind', () { + expect(vulkanFactsOf(rtx, [_fact('RX 7900', _vulkan11)]), isNull); + expect( + vulkanFactsOf(rtx, [_fact('RTX 4090', _vulkan11, integrated: true)]), + isNull, + reason: 'the same name on an integrated GPU is another device', + ); + expect(vulkanFactsOf(rtx, const []), isNull); + expect( + vulkanFactsOf(_device('Vulkan0'), [_fact('', _vulkan11)]), + isNull, + reason: 'a device whose description was not read', + ); + expect( + vulkanFactsOf(_device('CUDA0', description: 'RTX 4090'), [ + _fact('RTX 4090', _vulkan11), + ]), + isNull, + reason: 'not a ggml-vulkan device', + ); + }); + + test('takes identical devices together when they agree, and knows ' + 'nothing when they do not', () { + expect( + vulkanFactsOf(rtx, [ + _fact('RTX 4090', _vulkan13), + _fact('RTX 4090', _vulkan13), + ])?.meetsVulkan12, + isTrue, + ); + expect( + vulkanFactsOf(rtx, [ + _fact('RTX 4090', _vulkan11), + _fact('RTX 4090', _vulkan11), + ])?.meetsVulkan12, + isFalse, + ); + expect( + vulkanFactsOf(rtx, [ + _fact('RTX 4090', _vulkan13), + _fact('RTX 4090', _vulkan11), + ]), + isNull, + ); + }); + }); + group('resolveVulkanLoadDecision', () { late int registryReads; late int probeReads; @@ -210,33 +285,44 @@ void main() { .having((d) => d.devices, 'devices', isNull) .having((d) => d.refused, 'refused', isTrue); - final rtx = _device('Vulkan0', deviceId: '0000:01:00.0'); - final uhd = _device('Vulkan1', type: _igpuType); + final rtx = _device( + 'Vulkan0', + deviceId: '0000:01:00.0', + description: 'RTX 4090', + ); + final uhd = _device( + 'Vulkan1', + type: _igpuType, + description: 'UHD Graphics 630', + ); final cuda = _device('CUDA0', deviceId: '0000:01:00.0'); + final rtxOk = _fact('RTX 4090', _vulkan13); + final uhdOld = _fact('UHD Graphics 630', _vulkan11, integrated: true); + final maliOld = _fact('Mali-G68', _vulkan11); + final mali = _device('Vulkan0', description: 'Mali-G68'); test('a load that offloads nothing reads neither the registry nor the ' 'facts', () { - expect( - decide([_device('Vulkan0')], _facts([_vulkan11]), usesGpu: false), - unchanged(), - ); + expect(decide([mali], _facts([maliOld]), usesGpu: false), unchanged()); expect((registryReads, probeReads), (0, 0)); }); test('refuses when the only selected device is below Vulkan 1.2, naming ' 'it and its versions', () { - final decision = decide([_cpu, _device('Vulkan0')], _facts([_vulkan11])); + final decision = decide([_cpu, mali], _facts([maliOld])); - expect(decision, refused('"GPU 0" (Vulkan0)')); + expect(decision, refused('"Mali-G68" (Vulkan0)')); expect( decision.unsupported, "llama.cpp's Vulkan backend needs Vulkan 1.2 or later from both the " - 'Vulkan loader and the GPU driver, and "GPU 0" (Vulkan0) reports ' + 'Vulkan loader and the GPU driver, and "Mali-G68" (Vulkan0) reports ' 'driver API 1.1 with loader API 1.3', ); expect( - decide([_device('Vulkan0', type: _igpuType)], _facts([_vulkan11])), - refused('(Vulkan0)'), + decide([ + _device('Vulkan0', type: _igpuType, description: 'UHD Graphics 630'), + ], _facts([uhdOld])), + refused('"UHD Graphics 630" (Vulkan0)'), reason: 'an integrated GPU is selected when it is the only GPU', ); }); @@ -247,7 +333,7 @@ void main() { [_cpu, rtx, uhd], [_cpu, cuda, rtx, uhd], ]) { - expect(decide(registered, _facts([_vulkan13, _vulkan11])), unchanged()); + expect(decide(registered, _facts([rtxOk, uhdOld])), unchanged()); } }); @@ -266,22 +352,134 @@ void main() { expect( decide([ _device('CUDA0', deviceId: '0000:01:00.0'), - _device('Vulkan0', deviceId: '0000:02:00.0'), - ], _facts([_vulkan11])), - without('(Vulkan0)', ['CUDA0']), + _device('Vulkan0', deviceId: '0000:02:00.0', description: 'Mali-G68'), + ], _facts([maliOld])), + without('"Mali-G68" (Vulkan0)', ['CUDA0']), ); expect( - decide([ - _device('Vulkan0'), - _device('Vulkan1'), - _device('Vulkan2'), - ], _facts([_vulkan13, _vulkan11, _vulkan13])), - without('"GPU 1" (Vulkan1)', ['Vulkan0', 'Vulkan2']), + decide( + [ + _device('Vulkan0', description: 'RTX 4090'), + _device('Vulkan1', description: 'GTX 660'), + _device('Vulkan2', description: 'RX 7900'), + ], + _facts([ + rtxOk, + _fact('GTX 660', _vulkan11), + _fact('RX 7900', _vulkan13), + ]), + ), + without('"GTX 660" (Vulkan1)', ['Vulkan0', 'Vulkan2']), ); }); + // ggml-vulkan and the facts can list different devices: whether ggml + // registers a device below Vulkan 1.2 is undefined. + for (final backend in [null, 'Vulkan']) { + final how = backend == null ? "llama.cpp's selection" : 'explicit Vulkan'; + + test('$how: facts that list a device ggml did not register do not ' + 'shift onto the registered ones', () { + final a = _device('Vulkan0', description: 'RTX 4090'); + final b = _device('Vulkan1', description: 'RX 7900'); + final bOk = _fact('RX 7900', _vulkan13); + final old = _fact('GTX 660', _vulkan11); + + expect( + decide([a], _facts([uhdOld, rtxOk]), backend: backend), + unchanged(), + reason: 'Vulkan0 is the RTX, not the first entry of the facts', + ); + for (final facts in [ + [old, rtxOk, bOk], + [rtxOk, bOk, old], + [rtxOk, old, bOk], + ]) { + expect( + decide([a, b], _facts(facts), backend: backend), + unchanged(), + reason: '${facts.map((fact) => fact.name)}', + ); + } + }); + + test('$how: names the device that is below Vulkan 1.2, wherever its ' + 'facts are listed', () { + final onlyOld = _device('Vulkan0', description: 'GTX 660'); + + expect( + decide( + [onlyOld], + _facts([rtxOk, _fact('GTX 660', _vulkan11)]), + backend: backend, + ), + refused('"GTX 660" (Vulkan0)'), + ); + }); + + test('$how: identical GPUs are judged together', () { + final twins = [ + _device('Vulkan0', description: 'RTX 4090'), + _device('Vulkan1', description: 'RTX 4090'), + ]; + + expect( + decide(twins, _facts([rtxOk, rtxOk]), backend: backend), + unchanged(), + ); + expect( + decide( + twins, + _facts([ + _fact('RTX 4090', _vulkan11), + _fact('RTX 4090', _vulkan11), + ]), + backend: backend, + ), + refused('"RTX 4090" (Vulkan0)'), + ); + expect( + decide( + twins, + _facts([rtxOk, _fact('RTX 4090', _vulkan11)]), + backend: backend, + ), + unchanged(), + reason: 'which twin is on the old driver cannot be told', + ); + }); + + test('$how: a device without a facts entry is unknown, and the others ' + 'are still judged', () { + final a = _device('Vulkan0', description: 'GTX 660'); + final b = _device('Vulkan1', description: 'RX 7900'); + + expect( + decide( + [a, b], + _facts([_fact('GTX 660', _vulkan11)]), + backend: backend, + ), + without('"GTX 660" (Vulkan0)', ['Vulkan1']), + ); + expect( + decide( + [a, b], + _facts([_fact('RX 7900', _vulkan13)]), + backend: backend, + ), + unchanged(), + ); + expect(decide([a, b], _facts(const []), backend: backend), unchanged()); + }); + } + test('an explicit backend is judged by its own devices only', () { - final oldVulkan = _device('Vulkan0', deviceId: '0000:02:00.0'); + final oldVulkan = _device( + 'Vulkan0', + deviceId: '0000:02:00.0', + description: 'Mali-G68', + ); expect( decide( @@ -295,39 +493,38 @@ void main() { // The Vulkan backend lists every Vulkan device, integrated ones too. expect( - decide( - [cuda, rtx, uhd], - _facts([_vulkan13, _vulkan11]), - backend: 'Vulkan', - ), - without('(Vulkan1)', ['Vulkan0']), + decide([cuda, rtx, uhd], _facts([rtxOk, uhdOld]), backend: 'Vulkan'), + without('"UHD Graphics 630" (Vulkan1)', ['Vulkan0']), ); expect( decide( [cuda, rtx, uhd], - _facts([_vulkan11, _vulkan11]), + _facts([_fact('RTX 4090', _vulkan11), uhdOld]), backend: 'vulkan', ), - refused('(Vulkan0)'), + refused('"RTX 4090" (Vulkan0)'), ); }); test('an explicit backend without a registered device falls back to ' "llama.cpp's own selection", () { expect( - decide([_device('Vulkan0')], _facts([_vulkan11]), backend: 'CUDA'), + decide([mali], _facts([maliOld]), backend: 'CUDA'), refused('(Vulkan0)'), ); }); test('single-device mode judges the device mainGpu selects', () { - final registered = [_device('Vulkan0'), _device('Vulkan1')]; - final facts = _facts([_vulkan13, _vulkan11]); + final registered = [ + _device('Vulkan0', description: 'RTX 4090'), + _device('Vulkan1', description: 'GTX 660'), + ]; + final facts = _facts([rtxOk, _fact('GTX 660', _vulkan11)]); expect(decide(registered, facts, splitMode: _none), unchanged()); expect( decide(registered, facts, splitMode: _none, mainGpu: 1), - refused('(Vulkan1)'), + refused('"GTX 660" (Vulkan1)'), ); expect( decide(registered, facts, splitMode: _none, mainGpu: 5), @@ -338,47 +535,32 @@ void main() { test('tensor split mode judges every GPU, integrated ones included', () { expect( - decide([rtx, uhd], _facts([_vulkan13, _vulkan11]), splitMode: _tensor), + decide([rtx, uhd], _facts([rtxOk, uhdOld]), splitMode: _tensor), without('(Vulkan1)', ['Vulkan0']), ); }); test('unknown devices are not refused', () { - final registered = [_device('Vulkan0'), _device('Vulkan1')]; - expect( - decide( - registered, - () => const VulkanDeviceProbe.unavailable('no loader'), - ), + decide([mali], () => const VulkanDeviceProbe.unavailable('no loader')), unchanged(), ); expect( - decide(registered, _facts([_vulkan13])), + decide([_device('Vulkan0')], _facts([maliOld])), unchanged(), - reason: 'the facts do not cover Vulkan1', + reason: 'a device whose description was not read has no facts', ); expect( - decide([_device('Renamed', registry: 'Vulkan')], _facts([_vulkan11])), + decide([_device('Vulkan0', description: 'RTX 4090')], _facts([rtxOk])), unchanged(), - reason: 'a name that is not VulkanN has no facts', ); - expect(decide([_device('Vulkan0')], _facts([_vulkan13])), unchanged()); }); test('a loader below Vulkan 1.2 counts like a driver below it', () { expect( decide( - [_device('Vulkan0')], - () => const VulkanDeviceProbe.devices([ - VulkanDeviceFacts( - index: 0, - name: 'Mali-G52', - instanceApiVersion: _vulkan11, - apiVersion: _vulkan13, - subgroupSize: 4, - ), - ]), + [_device('Vulkan0', description: 'Mali-G52')], + _facts([_fact('Mali-G52', _vulkan13, instanceApiVersion: _vulkan11)]), ).unsupported, endsWith( '"Mali-G52" (Vulkan0) reports driver API 1.3 with loader API 1.1', diff --git a/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart b/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart index eac032361..d42841fe8 100644 --- a/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart +++ b/test/unit/backends/llama_cpp/vulkan_device_probe_test.dart @@ -19,14 +19,14 @@ int _version(int major, int minor, [int patch = 0]) => major << 22 | minor << 12 | patch; VulkanDeviceFacts _device({ - int index = 0, String name = 'Mali-G715', + int deviceType = 1, int? instanceApiVersion, int? apiVersion, int subgroupSize = 16, }) => VulkanDeviceFacts( - index: index, name: name, + deviceType: deviceType, instanceApiVersion: instanceApiVersion ?? _version(1, 3), apiVersion: apiVersion ?? _version(1, 3), subgroupSize: subgroupSize, @@ -85,11 +85,10 @@ void main() { expect(VulkanDeviceFacts.formatApiVersion(_version(1, 3, 280)), '1.3'); expect( _device( - index: 1, apiVersion: _version(1, 1, 177), instanceApiVersion: _version(1, 3, 275), ).toString(), - 'Vulkan1 "Mali-G715" (API 1.1, loader 1.3, subgroup size 16)', + '"Mali-G715" (API 1.1, loader 1.3, subgroup size 16)', ); }); }); @@ -168,36 +167,42 @@ void main() { expect(called, _symbols); }); - test('lists each device with its name, versions and subgroup size', () { - final structSizes = []; - final api = VulkanDeviceInfoApi( - getDeviceCount: () => 2, - getDeviceInfo: (index, info) { - structSizes.add(info.ref.struct_size); - final name = utf8.encode(index == 0 ? 'Mali-G715' : 'Xclipse 940'); - for (var i = 0; i < name.length; i++) { - info.ref.device_name[i] = name[i]; - } - info.ref.device_name[name.length] = 0; - info.ref.instance_api_version = _version(1, 3, 275); - info.ref.api_version = _version(1, 3 - index, 7); - info.ref.subgroup_size = index == 0 ? 16 : 64; - return 0; - }, - ); + test( + 'lists each device with its name, type, versions and subgroup size', + () { + final structSizes = []; + final api = VulkanDeviceInfoApi( + getDeviceCount: () => 2, + getDeviceInfo: (index, info) { + structSizes.add(info.ref.struct_size); + final name = utf8.encode(index == 0 ? 'Mali-G715' : 'Xclipse 940'); + for (var i = 0; i < name.length; i++) { + info.ref.device_name[i] = name[i]; + } + info.ref.device_name[name.length] = 0; + info.ref.device_type = index == 0 ? 1 : 2; + info.ref.instance_api_version = _version(1, 3, 275); + info.ref.api_version = _version(1, 3 - index, 7); + info.ref.subgroup_size = index == 0 ? 16 : 64; + return 0; + }, + ); - final devices = api.probe().devices!; + final devices = api.probe().devices!; - expect(structSizes, [ - sizeOf(), - sizeOf(), - ]); - expect(devices.map((device) => device.toString()), [ - 'Vulkan0 "Mali-G715" (API 1.3, loader 1.3, subgroup size 16)', - 'Vulkan1 "Xclipse 940" (API 1.2, loader 1.3, subgroup size 64)', - ]); - expect(api.probe().unavailableReason, isNull); - }); + expect(structSizes, [ + sizeOf(), + sizeOf(), + ]); + expect(devices.map((device) => device.toString()), [ + '"Mali-G715" (API 1.3, loader 1.3, subgroup size 16)', + '"Xclipse 940" (API 1.2, loader 1.3, subgroup size 64)', + ]); + expect(devices.map((device) => device.isIntegratedGpu), [true, false]); + expect(devices.map((device) => device.deviceType), [1, 2]); + expect(api.probe().unavailableReason, isNull); + }, + ); test('lists no device when the loader works and ggml would use none', () { final api = VulkanDeviceInfoApi( From 47c99441aa3640dc98f59baba06484832ec02cd1 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 00:42:42 -0400 Subject: [PATCH 6/6] test: read the device registry through the service on Windows The Windows runtime does not export ggml_backend_dev_get from the wrapper library, so the two real-runtime tests now go through the service's own registry calls and the public device listings. The registry read describes every device, which pins the description on a host without a GPU. --- .../backends/llama_cpp/llama_cpp_service.dart | 7 +-- ...llama_cpp_service_native_failure_test.dart | 10 ++-- .../llama_cpp/llama_cpp_service_test.dart | 60 ++++++++----------- 3 files changed, 32 insertions(+), 45 deletions(-) diff --git a/lib/src/backends/llama_cpp/llama_cpp_service.dart b/lib/src/backends/llama_cpp/llama_cpp_service.dart index b7087d8fa..1924bcf0f 100644 --- a/lib/src/backends/llama_cpp/llama_cpp_service.dart +++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart @@ -2132,13 +2132,10 @@ class LlamaCppService { ggml_backend_dev_t device, Pointer props, ) { - final type = _ggmlBackendDevType(device); - // The properties of a GPU are all llama.cpp and the Vulkan check read. - final hasProps = - _isGpuClassDevice(device) && _ggmlBackendDevGetProps(device, props); + final hasProps = _ggmlBackendDevGetProps(device, props); return GgmlDeviceEntry( name: _utf8OrEmpty(_ggmlBackendDevName(device)), - type: type, + type: _ggmlBackendDevType(device), registry: _registryNameOf(device), description: hasProps ? _utf8OrEmpty(props.ref.description) : '', deviceId: hasProps && props.ref.device_id != nullptr diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart index e375088ee..b0d9eae6e 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_native_failure_test.dart @@ -740,12 +740,12 @@ void main() { calloc.free(free); calloc.free(total); }); + Object? invoke(String member, List arguments) => reflect( + service, + ).invoke(MirrorSystem.getSymbol(member, owner), arguments).reflectee; + final device = invoke('_ggmlBackendDevGet', [0]); bool readMemory() => - reflect(service).invoke( - MirrorSystem.getSymbol('_ggmlBackendDevMemory', owner), - [ggml_backend_dev_get(0), free, total], - ).reflectee - as bool; + invoke('_ggmlBackendDevMemory', [device, free, total])! as bool; expect(readMemory(), isTrue); expect(barrier.calls, ['llama_dart_ggml_backend_dev_memory']); diff --git a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart index 63b92614f..16d945b15 100644 --- a/test/unit/backends/llama_cpp/llama_cpp_service_test.dart +++ b/test/unit/backends/llama_cpp/llama_cpp_service_test.dart @@ -5989,7 +5989,8 @@ void main() { }); // Runs the real llama.cpp runtime: its registry has a CPU device. - test('reads each registered device with its name, type and registry', () { + test('reads each registered device with its name, type, registry and ' + 'description', () { final service = LlamaCppService()..initializeBackend(); addTearDown(service.dispose); @@ -5999,42 +6000,31 @@ void main() { const [], ); - expect(registered, isNotEmpty); - for (final (index, device) in registered.indexed) { - expect(device.device, ggml_backend_dev_get(index)); - expect( - device.name, - ggml_backend_dev_name(device.device!).cast().toDartString(), - ); - expect(device.type, ggml_backend_dev_type$1(device.device!).value); - expect( - device.registry, - ggml_backend_reg_name( - ggml_backend_dev_backend_reg(device.device!), - ).cast().toDartString(), - ); - expect(device.registry, isNotEmpty); - final isGpu = const [ - ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_GPU, - ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_IGPU, - ].any((type) => type.value == device.type); - expect( - device.description, - isGpu - ? ggml_backend_dev_description( - device.device!, - ).cast().toDartString() - : isEmpty, + final cpu = registered.firstWhere( + (device) => + device.type == + ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_CPU.value, + ); + expect(cpu.name, 'CPU'); + expect(cpu.registry, 'CPU'); + expect(cpu.description, isNotEmpty); + expect(cpu.deviceId, isNull); + expect(cpu.device, isNot(nullptr)); + expect(cpu.isVulkan, isFalse); + // The public listings read the same registry. + expect({ + for (final device in registered) + device.registry.toLowerCase() == device.name.toLowerCase() + ? device.registry + : '${device.registry} (${device.name})', + }, service.getBackendInfo().toSet()); + for (final gpu in service.listGpuDevices()) { + final device = registered.singleWhere( + (entry) => entry.name == gpu.name, ); + expect(device.description, gpu.description); + expect(device.deviceId ?? '', gpu.deviceId); } - expect( - registered.where( - (device) => - device.type == - ggml_backend_dev_type.GGML_BACKEND_DEVICE_TYPE_CPU.value, - ), - isNotEmpty, - ); }); });