Skip to content
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,23 @@
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
([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)).
On Linux `ImageGenerationEngine.load` refuses, with `LlamaModelException`,
only a model that does not fit the discrete GPUs plus system memory. A
model larger than the memory of the GPU that computes still loads, with
one warning, and runs slower; on Windows it is warned about and never
refused. Not validated on a physical Vulkan GPU yet;
`ImageModelParams(checkMemory: false)` skips the check and the warning.
- Quote the errors stable-diffusion.cpp logged in the `LlamaModelException`
of an image model it cannot load, with files named by role
([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)).
- Send the image runtime's messages to the `LlamaLogging.configure` handler
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.

## 0.11.1

Expand Down
100 changes: 94 additions & 6 deletions doc/llama_cpp_exit_teardown.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,13 @@ stand-in:
`IsolateShutdownReleases` hold.
- `sd_dart_progress_enable` and `sd_dart_progress_read`: see "Image
progress".
- `sd_dart_log_enable`, `sd_dart_log_set_level`, `sd_dart_log_read`,
`sd_dart_log_dropped` and `sd_dart_last_error` (`v0.2.0-2`): see "Image
log".
- `sd_dart_gpu_device_count` and `sd_dart_gpu_device_memory` (`v0.2.0-2`)
read the memory of every GPU for the memory check of Vulkan GPUs. They run
in a short-lived isolate of their own (`readStableDiffusionGpuMemory`), not
in a worker.
- Upstream calls that return at once: `sd_ctx_params_init`,
`sd_ctx_supports_image_generation` and `sd_get_model_version_name` right
after the load, `sd_img_gen_params_init` and `free_sd_images`.
Expand All @@ -185,6 +192,16 @@ runtime: the hook downloads the pinned archives by checksum, this runtime has
no tag or path override, and the build rejects an Apple companion whose pin
differs from the core pin.

The functions `v0.2.0-2` added are optional: `StableDiffusionCalls.log` binds
the five log functions when the runtime exports all of them, and
`gpu` its two device queries, and each is `null` otherwise
(`StableDiffusionCalls.optionalNativeRelease`). On such a runtime image
generation works as it did on `v0.2.0-1`: no log call is made, a failed load
names the missing file roles and the release that reports reasons, and a
Vulkan GPU is not memory-checked. The same holds for the reason above: no
supported configuration reaches it, so the fallback is tested on the
stand-in and was run once by hand against the `v0.2.0-1` archive.

`sd_dart_exit_teardown`, `sd_dart_exit_call_begin`, `sd_dart_exit_call_end`,
`sd_dart_exit_track` and `sd_dart_exit_untrack` are excluded from the
bindings (`ffigen_stable_diffusion.yaml`): none is safe from an isolate that
Expand All @@ -203,6 +220,17 @@ runtime's default waits apply.
- It waits up to two seconds for an `sd_dart_exit_free` in flight, and gives
a thread 250 ms after its last such call, which covers the short upstream
calls after a load.
- A device query (`sd_dart_gpu_device_count`, `sd_dart_gpu_device_memory`)
in flight is waited for like a load, up to 15 seconds, also when nothing
is tracked: it reads ggml's device registry, which C `exit` destroys.
llamadart makes the queries only for Vulkan GPUs, on Linux and Windows,
where teardown runs only when a
native host calls it. The probe's `sd_list_devices`, which initializes the
devices first, is upstream's function and is not waited for.
- The log reads (`sd_dart_log_read`, `sd_dart_log_dropped`,
`sd_dart_last_error`) are not calls in flight and need no wait: they touch
no context and stay valid during and after teardown. Each can wait up to
100 ms for a thread that is copying a message.
- The two runtimes wait one after the other: with a llama.cpp call and an
image generation both in flight an exit can take about 17.5 seconds.

Expand Down Expand Up @@ -269,21 +297,81 @@ the reports in a ring, and Dart reads them:
generation ends, so it lands at most one poll interval after the runtime
started, whether or not a report arrives.

### Image log

stable-diffusion.cpp logs through a callback on whichever thread logs, with
a text that is only valid during the call, and returns only `NULL` from a
load that fails. From `v0.2.0-2` the runtime copies each message of
stable-diffusion.cpp and ggml into a 256 KiB buffer of its own, and Dart
reads them:

- `sd_dart_log_enable` and `sd_dart_log_set_level` run before anything that
logs: in the runtime probe before `sd_list_devices`, in the isolate that
asks a GPU for its memory before the query, and in
`StableDiffusionImageWorker.start` on the calling isolate before the worker
is spawned. The first registration is not synchronized, and none of the
three runs beside a load, a generation or a device query of the same
isolate. The recorder is registered at every log level, because
`sd_dart_last_error` is empty without it; at `LlamaLogLevel.none` the level
is `SD_LOG_ERROR + 1`, which records nothing. Once it is registered, ggml's
messages no longer go to stderr.
- The level is the stricter of `LlamaLogging.level` and
`LlamaLogging.nativeLevel` when the load starts
(`imageRuntimeLogLevel`), since a message reaches the app through
`LlamaLogger`. It is the process's: the last load sets it.
- The worker isolate reads the log, never the calling isolate: a read can
wait 100 ms. It cannot read while it is inside a load or a generation, so
it reads after each one and when it is disposed, up to 4096 messages a
time, and sends them to the calling isolate before the reply of that
operation. There is no timer, so an idle worker costs nothing, and at
`LlamaLogLevel.none` nothing is read. Reading the 27 messages of an SDXS
load at `info` took 84 microseconds on an M4 Max, and a read that finds
nothing 2 to 4.
- After a load the worker first makes its calls on the context
(`sd_ctx_supports_image_generation`, `sd_get_model_version_name`), which
have to fall into teardown's 250 ms, and reads the log afterwards. After a
failed load it reads `sd_dart_last_error` first, with no asynchronous gap,
because the errors belong to the thread until its next load.
- The calling isolate keeps the position the log was read to and gives it to
each worker with every command, so a second engine does not log the first
one's messages again. Two isolates that load image models each read the
whole log.
- `sd_dart_log_dropped` counts the messages that left the buffer unread. Its
increase since the last read is logged as one warning.
- Texts are decoded leniently and file paths are replaced by roles
(`stableDiffusionPathRedactor`), in forwarded records and in the reason of
a failed load.

A C `exit()` while an isolate executes Dart code, rather than waiting in its
event loop or inside a native call, aborts in the Dart VM
(`runtime/vm/handles_impl.h: unreachable code`) when a model is loaded: with
an image model idle on Metal and a second isolate that only decoded UTF-8 in
a loop, 5 of 5 exits aborted, and none did without the model, where the
exit takes no time. So the rows of the table above hold for isolates that
are idle or inside a native call, and what reads the log during an exit can
only be shown from native code, as the tests of `stable-diffusion-native` do.

### Tests

- `test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart`: the
lookup requests the six names and resolves nothing when one is missing;
each member calls the function exported under its own name; the generated
bindings leave out the five unbound functions and mark only
`sd_dart_progress_read` as a leaf call.
lookup requests the six required names and resolves nothing when one is
missing; the log and the device memory query are absent, each on its own,
when a name of theirs is missing; each member calls the function exported
under its own name; the generated bindings leave out the five unbound
functions and mark only `sd_dart_progress_read` as a leaf call.
- `test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart`:
the worker's two isolates on `test/support/fake_stable_diffusion_runtime.dart`,
with a progress timer the test fires by hand. The whole call sequence of
each isolate is compared for a load, a generation, a batch of three, a
cancel before the runtime starts and one during a generation, dispose, a
failed load, a model that cannot generate images and a runtime without the
functions.
functions; with a log level, for the reads after a load, a generation, a
failed load and dispose; and on a stand-in for `v0.2.0-1`, where no log
function is called.
- `test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart`: the
level mapping, lenient decoding, a drain's reads, position and dropped
count, and the reason of a failed load without paths.
- The root package does not bundle the runtime, so no default-CI test
resolves the real exports. `image-exit-teardown` in
`doc/testing_matrix.md` does, locally on Metal, along with the process
exits.
exits, three of them with the log forwarded at debug level.
13 changes: 10 additions & 3 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,9 @@ dart run tool/testing/run_local_e2e.dart \
# model cache directory) to load SDXS from its pinned Hugging Face file
# through the resolver, 683 MB on the first run, and
# LLAMADART_IMAGE_SPLIT_MODEL (a split model's files, comma separated in any
# order) to check role detection on a real split model.
# order) to check role detection on a real split model. It also checks the
# runtime's reason in the error of a rejected load, the runtime's messages in
# the log handler, and on macOS the runtime's GPU memory figure.
dart run tool/testing/run_local_e2e.dart --scenario image-generation-smoke \
--model-path /path/to/sdxs-512-tinySDdistilled_Q8_0.gguf

Expand Down Expand Up @@ -589,7 +591,11 @@ stable_diffusion runtime. It runs
ends it while an image model is alive on Metal: C `exit` through FFI from the
main isolate with the model idle, generating, loading, or already disposed;
an unhandled error while generating or loading; and an isolate killed inside
the native load. Each run must reach its exit point, print neither
the native load. The idle, generating and loading exits run a second time
with the runtime's log forwarded at debug level (`-logging`), so the worker
reads the log around the exit, and `quiet` loads, generates and disposes at
the default log levels and must leave no `ggml_` line on stderr. Each run
must reach its exit point, print neither
`GGML_ASSERT` nor `GetFfiCallbackMetadata`, and end with exit code 0, or 255
for the unhandled errors. The loading scenarios time a second load of the
model and exit halfway through a third, because the first load of a process
Expand All @@ -598,7 +604,8 @@ native host that exits without shutting Dart down, not a Flutter quit
([exit teardown](llama_cpp_exit_teardown.md#image-models)).

The row also checks that each `sd_dart_` function `StableDiffusionCalls`
looks up resolves to the runtime's own export of that name, which default CI
looks up, the optional log and device memory functions included, resolves to
the runtime's own export of that name, which default CI
cannot (the root package does not bundle the runtime), and that batches of
two and three images report every sampling step in order and end with the
`decoding` event.
Expand Down
55 changes: 49 additions & 6 deletions example/basic_app/test/fixtures/image_exit_probe.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Subprocess fixture: ends the process in one way while an image model is
// alive, or prints the progress events of a batch. Arguments: the scenario
// and an image checkpoint; `quit-both-loaded` also takes a GGUF chat model.
// A scenario whose name ends in `-logging` runs with the runtime's log
// forwarded at debug level, so the worker reads the log around the exit.
//
// The `quit-` scenarios call C `exit` through FFI from the main isolate while
// the worker isolate that owns the context is alive: what a native host that
Expand All @@ -25,16 +27,41 @@ import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_params.
import 'package:llamadart/src/core/image/image_generation_driver.dart';

Future<void> main(List<String> args) async {
final [scenario, modelPath, ...extra] = args;
final [requested, modelPath, ...extra] = args;
final logging = requested.endsWith(_loggingSuffix);
final scenario = logging
? requested.substring(0, requested.length - _loggingSuffix.length)
: requested;
if (logging) {
await LlamaLogging.configure(
level: LlamaLogLevel.debug,
handler: (_) => _logRecords++,
);
}
switch (scenario) {
case 'symbols':
await ImageGenerationEngine.checkRuntime();
for (final name in StableDiffusionCalls.wrapperSymbols) {
for (final name in [
...StableDiffusionCalls.wrapperSymbols,
...StableDiffusionCalls.logSymbols,
...StableDiffusionCalls.deviceMemorySymbols,
]) {
if (StableDiffusionCalls.symbolAddress(name) !=
DynamicLibrary.process().lookup(name)) {
throw StateError('$name does not resolve to the export of its name');
}
}
final calls = StableDiffusionCalls.tryResolve()!;
if (calls.log == null || calls.gpu == null) {
throw StateError('The pinned runtime lacks the log or the GPU queries');
}
_reached(scenario);
case 'quiet':
// At the default log levels the runtime prints nothing: the test reads
// this process's stderr.
final engine = await _load(modelPath);
await engine.generateImage(_request(steps: 1));
await engine.dispose();
_reached(scenario);
case 'events':
final engine = await _load(modelPath);
Expand Down Expand Up @@ -105,8 +132,16 @@ Future<void> main(List<String> args) async {
}
}

void _reached(String scenario) =>
stdout.writeln('IMAGE_PROBE_REACHED $scenario');
const _loggingSuffix = '-logging';

int _logRecords = 0;

void _reached(String scenario) {
if (_logRecords > 0) {
stdout.writeln('IMAGE_PROBE_LOG_RECORDS $_logRecords');
}
stdout.writeln('IMAGE_PROBE_REACHED $scenario');
}

void _reportTracked() =>
stdout.writeln('IMAGE_PROBE_TRACKED ${sd.sd_dart_exit_tracked_count()}');
Expand Down Expand Up @@ -177,7 +212,10 @@ Future<Duration> _loadTime(String modelPath) async {
load
..reset()
..start();
final worker = await StableDiffusionImageWorker.start(_config(modelPath));
final worker = await StableDiffusionImageWorker.start(
_config(modelPath),
logLevel: LlamaLogging.level,
);
load.stop();
await worker.dispose();
}
Expand All @@ -189,7 +227,12 @@ Future<Duration> _loadTime(String modelPath) async {
/// going by how long one load of it just took.
Future<void> _insideLoad(String modelPath) async {
final loadTime = await _loadTime(modelPath);
unawaited(StableDiffusionImageWorker.start(_config(modelPath)));
unawaited(
StableDiffusionImageWorker.start(
_config(modelPath),
logLevel: LlamaLogging.level,
),
);
await Future<void>.delayed(loadTime ~/ 2);
}

Expand Down
18 changes: 16 additions & 2 deletions example/basic_app/test/image_exit_teardown_e2e_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,13 @@ void main() {
// arguments (null skips it) and the exit code of a clean end.
for (final (scenario, arguments, exitCode) in <(String, List<String?>, int)>[
('symbols', [model], 0),
('quiet', [model], 0),
('quit-loaded', [model], 0),
('quit-generating', [model], 0),
('quit-loading', [model], 0),
('quit-loaded-logging', [model], 0),
('quit-generating-logging', [model], 0),
('quit-loading-logging', [model], 0),
('throw-generating', [model], 255),
('throw-loading', [model], 255),
('kill-loading', [model], 0),
Expand All @@ -48,18 +52,28 @@ void main() {
final seconds = <String>[];
for (var run = 0; run < runs; run++) {
final probe = await _runProbe([scenario, ...arguments.nonNulls]);
final reached = scenario.replaceFirst(RegExp(r'-logging$'), '');
expect(
probe.stdout,
contains('IMAGE_PROBE_REACHED $scenario'),
contains('IMAGE_PROBE_REACHED $reached'),
reason: probe.stderr,
);
if (scenario == 'quiet') {
// The recorder takes ggml's messages off stderr, and at the
// default levels nothing reads them.
expect(probe.stderr, isNot(contains('ggml_')));
expect(probe.stdout, isNot(contains('IMAGE_PROBE_LOG_RECORDS')));
}
if (scenario.endsWith('-logging')) {
expect(probe.stdout, contains('IMAGE_PROBE_LOG_RECORDS'));
}
if (probe.stdout.contains('IMAGE_PROBE_BACKEND')) {
expect(probe.stdout, contains('IMAGE_PROBE_BACKEND MTL'));
}
if (scenario == 'quit-both-loaded') {
expect(probe.stdout, contains('IMAGE_PROBE_CHAT_BACKEND Metal'));
}
if (scenario == 'quit-loaded') {
if (reached == 'quit-loaded') {
expect(probe.stdout, contains('IMAGE_PROBE_TRACKED 1'));
}
if (scenario == 'dispose-quit') {
Expand Down
Loading
Loading