diff --git a/CHANGELOG.md b/CHANGELOG.md
index a91f9b8fb..213632ec7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,11 +39,6 @@
`@litert-lm/core@0.18.0`. An app still chooses the module through
`window.__llamadartLiteRtLmModuleUrl`; the chat app's `web/index.html` and
the docs now name `0.18.0`.
-* Aligned the default WebGPU bridge assets to `v0.1.54`, unchanged from 0.11.1:
- they embed llama.cpp `v0.5.0`, are qualified against native `v0.5.0`, and keep
- Web/native llama.cpp `v0.5.0@7fe450e19305b828c199d602c23a8337aaa1f03b` parity;
- Web LiteRT-LM is `@litert-lm/core@0.18.0`. Immutable Web asset manifest:
- `8a9f83c15035eeb034a6563e6f753382d7d7f9be81503ef76902138da7841176`.
- Adopt `leehack/stable-diffusion-native@v0.2.0-2` for the opt-in
`stable_diffusion` image runtime.
- Check the memory of Vulkan GPUs before loading an image model
@@ -61,6 +56,37 @@
at the configured levels, after each load and generation. The runtime no
longer prints ggml's device messages to stderr: at the default level
`none` it logs nothing.
+- 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. 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; 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
+ llama.cpp `v0.6.0@d81235049384534c167caea52b85a694f6103d14` parity; Web
+ LiteRT-LM is `@litert-lm/core@0.18.0`. Immutable Web asset manifest:
+ `f823b10417b212ff1f66aa1c46bf78af7d9c393497dfcf0fa3a4f77adeb260eb`.
## 0.11.1
diff --git a/README.md b/README.md
index 911f20c77..ac7d9aaae 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.18.0` |
Native overrides accept stable `vMAJOR.MINOR.PATCH` releases and preserve
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 6b98e7c7f..39cfe32b4 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,88 @@ 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 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
+ `VkPhysicalDeviceVulkan12Features` the driver never filled in and calls
+ 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 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
+ 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
+ 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
+that cannot be matched all count as unknown: the cap stays, and no load is
+refused or narrowed.
+
## Which exits are covered
| Exit | What happens |
@@ -128,6 +219,31 @@ 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`,
+ `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.
- 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 9c2dd7826..70960841f 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, 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/example/chat_app/web/index.html b/example/chat_app/web/index.html
index 93fae1a4d..6246c6884 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..de2bf5452 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,39 @@ final class LlamaCppObjectCalls {
);
/// [LlamaCppObjectCalls.tracked] when the loaded runtime exports the whole
- /// [ExitTeardownApi], otherwise [upstream].
- static LlamaCppObjectCalls resolve({required bool isWindows}) {
- final exit = ExitTeardownApi.tryResolve(isWindows: isWindows);
- return exit == null ? upstream : LlamaCppObjectCalls.tracked(exit);
+ /// [ExitTeardownApi], with the [NativeBarrierApi] when it exports that too;
+ /// otherwise [upstream].
+ ///
+ /// [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,
+ symbol: symbol,
+ ),
+ 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 +858,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 +1329,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..1924bcf0f 100644
--- a/lib/src/backends/llama_cpp/llama_cpp_service.dart
+++ b/lib/src/backends/llama_cpp/llama_cpp_service.dart
@@ -31,14 +31,19 @@ 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';
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 +650,9 @@ 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, the read of the Vulkan device facts, and the registered
+ /// ggml devices a load selects from.
LlamaCppService({
void Function()? backendInit,
Abi? abi,
@@ -658,6 +664,8 @@ class LlamaCppService {
LlamaCppObjectCalls? objectCalls,
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,
@@ -666,7 +674,9 @@ class LlamaCppService {
_deviceTypesOverride = deviceTypes,
_objectCallsOverride = objectCalls,
_batchInit = batchInit ?? llama_batch_init,
- _batchFree = batchFree ?? llama_batch_free;
+ _batchFree = batchFree ?? llama_batch_free,
+ _vulkanDeviceProbeOverride = vulkanDeviceProbe,
+ _registeredDevicesOverride = registeredDevices;
final void Function() _backendInit;
final Abi _abi;
@@ -677,8 +687,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();
+
+ final List Function()? _registeredDevicesOverride;
+
+ // Reading the facts loads the system's GPU drivers into the process, so
+ // 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))();
int _nextHandle = 1;
String? _backendModuleDirectory;
final Set _loadedBackendModules = {};
@@ -898,31 +919,52 @@ 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);
+ }
+
/// Resolves effective context batch parameters.
///
/// Uses the shared non-FFI helper for consistent default resolution and
@@ -1872,10 +1914,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 +1992,32 @@ class LlamaCppService {
_noGpuMessage(effectiveBackend, forcedCpuFallback: forcedCpuFallback),
);
}
+ final vulkan = _resolveVulkanLoadDevices(
+ effectiveBackend,
+ gpuLayers: gpuLayers,
+ splitMode: modelParams.splitMode.llamaCppValue,
+ mainGpu: modelParams.mainGpu,
+ );
+ if (vulkan.refused) {
+ 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}: ${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,
gpuLayers,
@@ -1978,6 +2073,15 @@ class LlamaCppService {
_modelLoadParams[handle] = modelParams;
_activeBackendName = resolvedBackend;
_activeResolvedGpuLayers = gpuLayers;
+ if (vulkan.unsupported case final unsupported?) {
+ LlamaLogger.instance.warning(
+ 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) {
final requested = effectiveBackend.name;
LlamaLogger.instance.warning(
@@ -1992,6 +2096,78 @@ class LlamaCppService {
return handle;
}
+ /// 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 props = calloc();
+ try {
+ return [
+ for (var i = 0; i < _ggmlBackendDevCount(); i++)
+ if (_ggmlBackendDevGet(i) case final device when device != nullptr)
+ _describeDevice(device, props),
+ ];
+ } finally {
+ calloc.free(props);
+ }
+ }
+
+ GgmlDeviceEntry _describeDevice(
+ ggml_backend_dev_t device,
+ Pointer props,
+ ) {
+ final hasProps = _ggmlBackendDevGetProps(device, props);
+ return GgmlDeviceEntry(
+ name: _utf8OrEmpty(_ggmlBackendDevName(device)),
+ type: _ggmlBackendDevType(device),
+ 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
+ ? ''
+ : _utf8OrEmpty(_ggmlBackendRegName(registry));
+ }
+
+ int _registeredVulkanDeviceCount() =>
+ _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.
bool _hasGpuDevice(GpuBackend backend) {
@@ -2095,7 +2271,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;
@@ -3642,6 +3832,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 +3857,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 +4076,7 @@ class LlamaCppService {
if (model == null) {
throw Exception("Invalid model handle");
}
+ _ensureModelUsable(model);
params = resolveComputeDeviceParams(
params,
isAndroid: _isAndroid,
@@ -3971,6 +4166,7 @@ class LlamaCppService {
params,
resolvedGpuLayers: resolvedModelGpuLayers,
isAndroid: _isAndroid,
+ hasSmallMatmulTileDefect: _androidVulkanHasSmallMatmulTileDefect,
),
);
_contextToModel[handle] = modelHandle;
@@ -3984,6 +4180,25 @@ class LlamaCppService {
return handle;
}
+ 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: registeredDeviceCount,
+ );
+ 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 +4717,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 +4842,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 +4898,7 @@ class LlamaCppService {
tokensPtr,
promptTokenCount,
)) {
+ _throwIfSpeculativeCaught('llama_dart_speculative_begin', ctx.pointer);
throw Exception(
"Failed to initialize llama.cpp speculative prompt state",
);
@@ -4778,6 +5000,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 +5071,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 +5083,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 +5175,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 +5302,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 +5459,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 +5493,7 @@ class LlamaCppService {
final tokensPtr = malloc(requiredTokenCount);
try {
- final actualTokenCount = llama_tokenize(
+ final actualTokenCount = _calls.tokenize(
vocab,
textPtr.cast(),
textLength,
@@ -5337,7 +5568,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'];
@@ -5423,7 +5654,7 @@ class LlamaCppService {
return;
}
- llama_memory_clear(memory, true);
+ _calls.memoryClear(contextPointer, memory, true);
}
/// Ingests the prompt (text or multimodal).
@@ -5495,6 +5726,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 +5778,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 +5846,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 +5977,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 +6235,7 @@ class LlamaCppService {
speculativeSession,
batch,
speculativeConfig,
+ ctx.pointer,
)) {
throw Exception("Speculative prompt decode processing failed");
}
@@ -6001,13 +6250,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 +6358,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 +6409,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 +6445,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 +6512,7 @@ class LlamaCppService {
}
final pieceTick = Stopwatch()..start();
- final n = llama_token_to_piece(
+ final n = _calls.tokenToPiece(
vocab,
selectedToken,
pieceBuf.cast(),
@@ -6350,7 +6633,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 +6691,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 +6716,7 @@ class LlamaCppService {
speculativeSession,
batch,
speculativeConfig,
+ ctx.pointer,
)) {
throw Exception("Speculative decode processing failed");
}
@@ -6504,6 +6792,7 @@ class LlamaCppService {
speculativeSession,
batch,
speculativeConfig,
+ ctx.pointer,
)) {
throw Exception("Speculative decode processing failed");
}
@@ -6533,6 +6822,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 +6896,7 @@ class LlamaCppService {
speculativeSession,
batch,
speculativeConfig,
+ ctx.pointer,
)) {
throw Exception("Speculative replay processing failed");
}
@@ -6620,6 +6915,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 +6955,7 @@ class LlamaCppService {
}
final pieceTick = Stopwatch()..start();
- final n = llama_token_to_piece(
+ final n = _calls.tokenToPiece(
vocab,
token,
pieceBuf.cast(),
@@ -6775,7 +7074,7 @@ class LlamaCppService {
final (textPtr, textLength) = _toNativeUtf8WithLength(tokenText);
try {
- final required = -llama_tokenize(
+ final required = -_calls.tokenize(
vocab,
textPtr.cast(),
textLength,
@@ -6791,7 +7090,7 @@ class LlamaCppService {
final tokenIds = malloc(required);
try {
- final actual = llama_tokenize(
+ final actual = _calls.tokenize(
vocab,
textPtr.cast(),
textLength,
@@ -6835,48 +7134,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 +7197,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 +7222,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 +7252,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 +7287,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 +7511,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 +7885,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 +7997,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 +8016,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 +8066,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 +8122,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 +8157,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 +8190,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 +8231,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 +8273,7 @@ class LlamaCppService {
) {
final exitTeardown = _mtmdExitTeardown;
if (exitTeardown != null) {
- return exitTeardown.mtmdHelperEvalChunks(
+ final result = exitTeardown.mtmdHelperEvalChunks(
ctx,
lctx,
chunks,
@@ -7909,6 +8283,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 +8941,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 +8994,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 +9376,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 +9439,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 +9520,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 +9553,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 +9573,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 +9699,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 +10377,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/load_device_selection.dart b/lib/src/backends/llama_cpp/load_device_selection.dart
new file mode 100644
index 000000000..931028ad4
--- /dev/null
+++ b/lib/src/backends/llama_cpp/load_device_selection.dart
@@ -0,0 +1,215 @@
+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.description = '',
+ 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_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;
+
+ /// 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;
+}
+
+/// 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.
+///
+/// [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 whose facts
+/// [vulkanFactsOf] cannot tell 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,
+ );
+
+ if (!selected.any((device) => device.isVulkan)) {
+ return VulkanLoadDecision.unchanged;
+ }
+ final facts = probe().devices;
+ if (facts == null) return VulkanLoadDecision.unchanged;
+
+ String? unsupported;
+ final usable =