diff --git a/AGENTS.md b/AGENTS.md index e8b9bd085..0c96cf668 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,6 +81,11 @@ dart test -p chrome --exclude-tags local-only through `LlamaCppObjectCalls` or `ExitTeardownApi`. Teardown waits only for those guarded calls; any other call in flight at a direct C `exit()` is unprotected (`doc/llama_cpp_exit_teardown.md`). +- In `lib/src/backends/stable_diffusion/`, every native call of an image + worker goes through `StableDiffusionCalls`, and Dart gives + stable-diffusion.cpp no callback. A call on an `sd_ctx_t` that can run + longer than 250 ms needs an `sd_dart_` wrapper in `stable-diffusion-native` + first (same doc, "Image models"). - Generated files that should not count toward coverage carry `// coverage:ignore-file`. - Tests close the ports, streams and controllers they open. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a61fb848..af2c112f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,12 +7,26 @@ heads still allocated at exit ([#813](https://github.com/leehack/llamadart/issues/813), [llamadart-native#96](https://github.com/leehack/llamadart-native/issues/96)). - Image models, and a native host's C `exit()` while llamadart is working, - are not covered. + A native host's C `exit()` while a llama.cpp call is running is not covered. - Update the default llama.cpp runtime to `leehack/llamadart-native@v0.5.0-2`, a rebuild of llama.cpp `v0.5.0` whose Apple XCFramework carries a privacy manifest (File Timestamp, reason `C617.1`). A runtime older than `v0.5.0-1` keeps the previous exit behavior and logs a warning at the first model load. +- Fix a process aborting when a Dart program dies of an error, or a Flutter + macOS app quits or hot restarts, while an image model loads or generates, + and a macOS Metal process aborting in ggml-metal when a native host exits + with an image model loaded: the stable_diffusion runtime now records + progress instead of calling back into Dart, and frees the image models + still allocated at exit + ([stable-diffusion-native#10](https://github.com/leehack/stable-diffusion-native/issues/10)). + Image progress events now arrive up to about 50 ms after the runtime + reports them. A quit during an image generation waits for the generation + to finish; dispose the engine first to quit at once. +- Update the stable_diffusion runtime to + `leehack/stable-diffusion-native@v0.2.0-1`, a rebuild of the same + stable-diffusion.cpp commit whose Apple XCFramework carries a privacy + manifest (File Timestamp, reasons `C617.1` and `3B52.1`). Image generation + needs this runtime or a later one. - Documented that LiteRT-LM on iOS has run on a device only on iOS 18.3.2; iOS 16.4 remains the declared, untested deployment floor ([#831](https://github.com/leehack/llamadart/issues/831)). diff --git a/README.md b/README.md index 67395d3f8..9a9dd16eb 100644 --- a/README.md +++ b/README.md @@ -224,8 +224,10 @@ An app bound for the App Store should use the companion for each runtime it ships: an Apple privacy manifest reaches an app inside a SwiftPM XCFramework, never in the dylibs the build hook bundles. The llama.cpp XCFramework carries one from `llamadart-native` `v0.5.0-1`, which `llamadart_llama_cpp_flutter` -releases after `0.0.20` link; the pinned stable_diffusion XCFramework carries -none. An app that runs llama.cpp or stable_diffusion on the hook path, or +releases after `0.0.20` link; the stable_diffusion XCFramework carries one +from `stable-diffusion-native` `v0.2.0-1`, which +`llamadart_stable_diffusion_flutter` releases after `0.0.1` link. An app that +runs llama.cpp or stable_diffusion on the hook path, or whose embedded `llama.framework` or `stable_diffusion.framework` has no `PrivacyInfo.xcprivacy`, declares `NSPrivacyAccessedAPICategoryFileTimestamp` in its own `PrivacyInfo.xcprivacy` diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index be6bd2c4b..11b98ab6f 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -80,7 +80,8 @@ since a projector points at its model. | `exit()` from `dart:io` | Runs no static destructors: no teardown and no abort. | | C `exit()` while an isolate is still running (through FFI, or a native host that skips the engine shutdown) | Covered only while the isolate is idle, freeing an object, or inside a guarded call that returns within two seconds. Inside an unguarded call it is a use after free; inside a longer guarded call ggml-metal aborts. | -Image models are not covered: stable-diffusion.cpp has no such teardown. +Image models have their own registry in `libstable-diffusion`: see +"Image models". ## Rule for new code @@ -90,6 +91,11 @@ must not race exit teardown goes through `LlamaCppObjectCalls` or in `llamadart-native` first; calling the upstream function leaves the call unprotected at a direct C `exit()`. +Every native call of an image worker goes through `StableDiffusionCalls`. A +new call on an `sd_ctx_t` that can run longer than the 250 ms settle time +(`generate_video`, `sd_ctx_load_control_net`, an upscaler) needs an +`sd_dart_` wrapper in `stable-diffusion-native` first. + ## Tests - `test/unit/backends/llama_cpp/exit_teardown_api_test.dart`: the stage @@ -120,3 +126,147 @@ unprotected at a direct C `exit()`. projector, model. - `native-exit-teardown` in `doc/testing_matrix.md`: local-only process exits on Metal, including a C `exit` while a service with a projector disposes. + +## Image models + +`libstable-diffusion` (`stable-diffusion-native` `v0.2.0-1` and later) keeps a +registry of its own and frees what is left of it during C `exit` on Apple +platforms, like libllamadart. The two libraries embed separate copies of +ggml and tear down independently. The native contract is +`src/sd_dart_wrapper.h` in `stable-diffusion-native`. + +### Dart side + +`lib/src/backends/stable_diffusion/stable_diffusion_calls.dart` holds every +native call an image worker makes, so a worker can run on a recording +stand-in: + +- `sd_dart_new_sd_ctx` creates the context and tracks it inside the call. + `sd_dart_generate_image` is the generation teardown cancels and waits for. + `sd_dart_cancel_generation` cancels from the calling isolate and does + nothing for a context that was already freed. `sd_dart_exit_free` frees a + tracked context once; it is also the free function of the worker's + `IsolateShutdownReleases` hold. +- `sd_dart_progress_enable` and `sd_dart_progress_read`: see "Image + progress". +- 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`. + +`StableDiffusionCalls.tryResolve` binds the six `sd_dart_` functions through +the addresses it resolves, all or nothing. There is no fallback to the +upstream functions, unlike the llama.cpp backend: without the recorder a +runtime reports progress only through a Dart callback, which is the abort the +recorder removes, and without the callback the engine would report a +generation as successful while it emits none of the documented progress +events. `probeStableDiffusionRuntime` therefore reports such a runtime as +unavailable and names `v0.2.0-1` +(`StableDiffusionCalls.minimumNativeRelease`), and +`StableDiffusionImageWorker.start` throws the same +`LlamaUnsupportedException`. No supported configuration reaches an older +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. + +`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 +can be killed. `sd_dart_exit_set_wait_ms` is bound and not called; the +runtime's default waits apply. + +### What teardown waits for + +- With no call in flight it frees the tracked contexts at once. +- While `sd_dart_new_sd_ctx` or `sd_dart_generate_image` is in flight it + waits up to 15 seconds and asks the generation to cancel every 20 ms. + stable-diffusion.cpp reads a cancel only before a sampling step and before + the decode of each image, and a load cannot be cancelled, so the wait is as + long as the phase that is running. A phase that outlasts the 15 seconds + makes teardown free nothing, and ggml-metal aborts as before. +- 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. +- 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. + +### Which exits are covered for image models + +Measured on an M4 Max on Metal with SDXS and SD-Turbo; "before" is native +`v0.2.0` with the Dart progress callback. + +| Exit | Before | Now | +| --- | --- | --- | +| Dart program returns from `main`, or dies of an unhandled error, with a model idle | Clean: the worker isolate's hold frees the context | The same | +| Dart program dies of an unhandled error while a model loads or generates | VM abort in the progress callback | Clean, once the native call returns. Nothing cancels the generation: the process ends when the generation does | +| Flutter macOS quit (`-[NSApplication terminate:]`) with a model idle | Clean | Clean | +| Flutter macOS quit while generating | VM abort in the progress callback | Clean, after the whole generation: the engine shuts the isolates down before C `exit`, so teardown's cancel never runs | +| Flutter macOS quit inside a load | VM abort in the progress callback | Clean: teardown frees the context the killed worker never held | +| Flutter hot restart inside a load, then quit | Crash at the restart (`Callback invoked after it has been deleted`) | Clean: the context of the discarded isolate stays tracked and teardown frees it | +| C `exit()` while the worker isolate is alive (through FFI, or a native host that skips the engine shutdown), model idle, loading or generating | ggml-metal abort | Clean within the waits above; a phase longer than 15 seconds aborts as before | +| `exit()` from `dart:io` | No static destructors run: no abort | The same | + +So the 15 second wait applies only to a direct C `exit()`. A Dart or Flutter +exit waits for the native call itself, however long the generation is, which +is why the guides still tell apps to dispose an `ImageGenerationEngine` from +`onExitRequested`. A Flutter hot restart during a generation waits the same +way: the restart happens once the generation has finished. The wait after a +quit, a hot restart or an unhandled error is the rest of the generation; the +times measured with SDXS and SD-Turbo are examples, not a bound. A +one-argument native cancel that could run as a `NativeFinalizer` of the +calling isolate would let llamadart cancel a generation on those paths; +`sd_dart_cancel_generation` takes two arguments. + +### Image progress + +stable-diffusion.cpp reports progress through one process-wide callback on +the thread that loads or generates. A Dart callback there cannot be made +safe: the VM may already be shutting down, and the process aborts with +`GetFfiCallbackMetadata called after shutdown`. The runtime instead records +the reports in a ring, and Dart reads them: + +- `StableDiffusionImageWorker.start` calls `sd_dart_progress_enable` on the + calling isolate before it spawns the worker. The first call registers the + recorder, unsynchronized, so it has to precede any load; it also keeps the + runtime from printing progress bars. Nothing in llamadart calls + `sd_set_progress_callback`, which would replace the recorder. +- `generate` asks for the newest sequence number before it sends the + request, reads the reports after it every 50 ms and once more after the + reply, and calls `onProgress(step, steps)` for each in order. One poll + makes at most 64 reads of 64 reports, which is the 4095 reports the runtime + keeps, so a runtime that reports faster than it is read cannot hold the + calling isolate. +- Reports are numbered. When the first report of a read does not follow the + last one read, the runtime dropped the ones in between: the worker delivers + what is left in order and logs one warning with the count. A request at + the limits (`maxCount` images of `maxSteps` steps) records 2416 reports, so + one generation cannot overflow on its own; a second isolate generating at + the same time could, and so could a tiled decode, which llamadart does not + request but stable-diffusion.cpp falls back to when a decode fails with + `GGML_STATUS_ALLOC_FAILED`. The effect is at most that warning and a gap + in the progress events. +- Reports are process-wide, loads included. The engine's one-operation guard + keeps one isolate from mixing two operations; two isolates that generate at + once each see both runs' reports. +- stable-diffusion.cpp clears a cancel request when a generation starts. A + cancel that arrived before then is applied again by each poll until the + generation ends, so it lands at most one poll interval after the runtime + started, whether or not a report arrives. + +### 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. +- `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. +- 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. diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index c4d50d263..f66fc9e9c 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -154,6 +154,7 @@ Pick targeted rows based on the touched surface: | Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | | Decision engine, decision head, or safetensors reader | `decision-model-smoke` | | Image generation API or `stable_diffusion` runtime | `image-generation-smoke`, `native-hook-bundles` | +| `stable_diffusion` runtime pin, image worker native calls, progress polling, exit or isolate shutdown | `image-exit-teardown`, `image-generation-smoke` | | Chat-app image screen or image model downloads | `chat-app-image-generation-smoke` | | Chat-app microphone transcription flow | `chat-app-microphone-transcription-smoke` | | Chat-app live LiteRT-LM dictation | `litert-lm-asr-smoke`, `chat-app-live-speech-smoke` | @@ -573,6 +574,38 @@ enables `quit-decision` (one with a decision head loaded). `dart:io`'s `exit` is not one of the scenarios: it does not run the static destructors that make ggml-metal abort. +### Image model exit teardown + +```bash +dart run tool/testing/run_local_e2e.dart --scenario image-exit-teardown \ + --model-path /path/to/sdxs-512-tinySDdistilled_Q8_0.gguf +``` + +This local-only macOS row runs in `example/basic_app`, which opts into the +stable_diffusion runtime. It runs +`example/basic_app/test/fixtures/image_exit_probe.dart` as a child process and +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 +`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 +also sets up Metal. As in the llama.cpp row, the C `exit` scenarios model a +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 +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. + +`IMAGE_EXIT_RUNS` sets the runs of each exit scenario (default 3). A run fails +when the process is still alive after two minutes. `quit-both-loaded`, a C +`exit` with a llama.cpp model loaded as well, is reported as skipped unless +`IMAGE_EXIT_GGUF` names a GGUF chat model the GPU loads. + ### Native prompt-evaluation cancel ```bash diff --git a/example/basic_app/pubspec.yaml b/example/basic_app/pubspec.yaml index c69f40b0d..89d3457ff 100644 --- a/example/basic_app/pubspec.yaml +++ b/example/basic_app/pubspec.yaml @@ -14,6 +14,7 @@ dependencies: sqlite_vector: ^0.9.85 dev_dependencies: + ffi: ^2.1.0 lints: ^6.1.0 test: ^1.26.3 diff --git a/example/basic_app/test/fixtures/image_exit_probe.dart b/example/basic_app/test/fixtures/image_exit_probe.dart new file mode 100644 index 000000000..c840049af --- /dev/null +++ b/example/basic_app/test/fixtures/image_exit_probe.dart @@ -0,0 +1,206 @@ +// 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. +// +// 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 +// skips the Dart shutdown does. `dart:io`'s `exit` does not run the static +// destructors that make ggml-metal abort. Each one exits while the worker is +// idle, loading or generating, which is what the runtime's exit teardown +// waits for (doc/llama_cpp_exit_teardown.md). +// ignore_for_file: implementation_imports +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_bindings.dart' + as sd; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_calls.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_image_worker.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_params.dart'; +import 'package:llamadart/src/core/image/image_generation_driver.dart'; + +Future main(List args) async { + final [scenario, modelPath, ...extra] = args; + switch (scenario) { + case 'symbols': + await ImageGenerationEngine.checkRuntime(); + for (final name in StableDiffusionCalls.wrapperSymbols) { + if (StableDiffusionCalls.symbolAddress(name) != + DynamicLibrary.process().lookup(name)) { + throw StateError('$name does not resolve to the export of its name'); + } + } + _reached(scenario); + case 'events': + final engine = await _load(modelPath); + final events = >{}; + for (final (count, steps) in [(2, 1), (3, 4), (2, 4)]) { + final task = await engine.generate( + _request(steps: steps, count: count), + ); + events['${count}x$steps'] = [ + await for (final event in task.events) + if (event is ImageGenerationProgressEvent) + '${event.phase.name} ${event.step}/${event.steps} ' + 'image ${event.imageIndex}/${event.imageCount}', + ]; + } + stdout.writeln('IMAGE_PROBE_EVENTS ${jsonEncode(events)}'); + await engine.dispose(); + _reached(scenario); + case 'quit-loaded': + final engine = await _load(modelPath); + await engine.generateImage(_request(steps: 1)); + _reportTracked(); + _quit(scenario); + case 'quit-generating': + await _firstStep(await _load(modelPath)); + _quit(scenario); + case 'throw-generating': + await _firstStep(await _load(modelPath)); + _reached(scenario); + throw StateError('unhandled error with a generation running'); + case 'quit-loading': + await _insideLoad(modelPath); + _quit(scenario); + case 'throw-loading': + await _insideLoad(modelPath); + _reached(scenario); + throw StateError('unhandled error with a model load running'); + case 'kill-loading': + // The kill lands when the native load returns, before the isolate + // holds the context for its own shutdown. + final loadTime = await _loadTime(modelPath); + final loading = ReceivePort(); + final isolate = await Isolate.spawn(_loadAfterNotice, ( + loading.sendPort, + modelPath, + )); + await loading.first; + await Future.delayed(loadTime ~/ 2); + isolate.kill(priority: Isolate.immediate); + _reached(scenario); + case 'dispose-quit': + final engine = await _load(modelPath); + await engine.generateImage(_request(steps: 1)); + await engine.dispose(); + _reportTracked(); + _quit(scenario); + case 'quit-both-loaded': + final chat = await LlamaEngine.load( + LlamaModel(ModelSource.path(extra.single)), + params: const ModelParams(contextSize: 2048), + ); + stdout.writeln('IMAGE_PROBE_CHAT_BACKEND ${await chat.getBackendName()}'); + final engine = await _load(modelPath); + await engine.generateImage(_request(steps: 1)); + _quit(scenario); + default: + throw ArgumentError.value(scenario, 'scenario'); + } +} + +void _reached(String scenario) => + stdout.writeln('IMAGE_PROBE_REACHED $scenario'); + +void _reportTracked() => + stdout.writeln('IMAGE_PROBE_TRACKED ${sd.sd_dart_exit_tracked_count()}'); + +Never _quit(String scenario) { + _reached(scenario); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +ImageGenerationRequest _request({required int steps, int count = 1}) => + ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + width: 256, + height: 256, + steps: steps, + guidanceScale: 1, + seed: 42, + count: count, + ); + +Future _load(String modelPath) async { + final engine = await ImageGenerationEngine.load( + ImageGenerationModel(ModelSource.path(modelPath)), + ); + stdout.writeln( + 'IMAGE_PROBE_BACKEND ${(await engine.capabilities).backendName}', + ); + return engine; +} + +// Leaves the generation running: the steps left take longer than the exit. +Future _firstStep(ImageGenerationEngine engine) async { + final task = await engine.generate( + const ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + steps: 40, + guidanceScale: 1, + seed: 42, + ), + ); + final sampling = Completer(); + task.events.listen((event) { + if (event case ImageGenerationProgressEvent( + phase: ImageGenerationPhase.sampling, + step: >= 1, + ) when !sampling.isCompleted) { + sampling.complete(); + } + }); + await sampling.future; +} + +ImageGenerationSessionConfig _config(String modelPath) => + ImageGenerationSessionConfig( + files: {'model': modelPath}, + backend: null, + threads: 0, + ); + +// Times the worker's load alone: an engine load also probes the runtime and +// reads the file headers first. The first load of a process also sets up +// Metal, so the second one is the measure of the next. +Future _loadTime(String modelPath) async { + final load = Stopwatch(); + for (var i = 0; i < 2; i++) { + load + ..reset() + ..start(); + final worker = await StableDiffusionImageWorker.start(_config(modelPath)); + load.stop(); + await worker.dispose(); + } + stdout.writeln('IMAGE_PROBE_LOAD_MS ${load.elapsedMilliseconds}'); + return load.elapsed; +} + +/// Leaves a worker halfway through the native call loading [modelPath], +/// going by how long one load of it just took. +Future _insideLoad(String modelPath) async { + final loadTime = await _loadTime(modelPath); + unawaited(StableDiffusionImageWorker.start(_config(modelPath))); + await Future.delayed(loadTime ~/ 2); +} + +void _loadAfterNotice((SendPort, String) message) { + final (loading, modelPath) = message; + final calls = StableDiffusionCalls.tryResolve()!; + using((arena) { + final params = arena(); + calls.contextParamsInit(params); + applyStableDiffusionContextParams(params, _config(modelPath), arena); + loading.send(null); + calls.newContext(params); + }); +} diff --git a/example/basic_app/test/image_exit_teardown_e2e_test.dart b/example/basic_app/test/image_exit_teardown_e2e_test.dart new file mode 100644 index 000000000..4f63da890 --- /dev/null +++ b/example/basic_app/test/image_exit_teardown_e2e_test.dart @@ -0,0 +1,140 @@ +@TestOn('mac-os') +@Tags(['local-only']) +@Timeout(Duration(minutes: 30)) +library; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:test/test.dart'; + +/// Ends a child process in each way that leaves an image model alive on +/// Metal, where ggml-metal aborts at exit while a buffer is still allocated +/// and a progress callback into a VM that is shutting down aborts it +/// (stable-diffusion-native#10). +/// +/// Set `IMAGE_EXIT_MODEL` to an image checkpoint such as SDXS; +/// `IMAGE_EXIT_RUNS` repeats each scenario (default 3). `IMAGE_EXIT_GGUF`, a +/// GGUF chat model, adds the scenario with both runtimes loaded. +void main() { + final environment = Platform.environment; + final model = environment['IMAGE_EXIT_MODEL']; + final chatModel = environment['IMAGE_EXIT_GGUF']; + final runs = int.parse(environment['IMAGE_EXIT_RUNS'] ?? '3'); + + // A scenario of test/fixtures/image_exit_probe.dart with its remaining + // arguments (null skips it) and the exit code of a clean end. + for (final (scenario, arguments, exitCode) in <(String, List, int)>[ + ('symbols', [model], 0), + ('quit-loaded', [model], 0), + ('quit-generating', [model], 0), + ('quit-loading', [model], 0), + ('throw-generating', [model], 255), + ('throw-loading', [model], 255), + ('kill-loading', [model], 0), + ('dispose-quit', [model], 0), + ('quit-both-loaded', [model, chatModel], 0), + ]) { + test('$scenario ends with exit code $exitCode', () async { + // Not `skip:`, which --run-skipped (needed for `local-only`) overrides. + if (arguments.contains(null)) { + markTestSkipped( + 'Set the IMAGE_EXIT_ variables of $scenario to run it.', + ); + return; + } + final codes = []; + final seconds = []; + for (var run = 0; run < runs; run++) { + final probe = await _runProbe([scenario, ...arguments.nonNulls]); + expect( + probe.stdout, + contains('IMAGE_PROBE_REACHED $scenario'), + reason: probe.stderr, + ); + 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') { + expect(probe.stdout, contains('IMAGE_PROBE_TRACKED 1')); + } + if (scenario == 'dispose-quit') { + expect(probe.stdout, contains('IMAGE_PROBE_TRACKED 0')); + } + expect(probe.stderr, isNot(contains('GGML_ASSERT'))); + expect(probe.stderr, isNot(contains('GetFfiCallbackMetadata'))); + codes.add(probe.exitCode); + seconds.add(probe.afterReached.toStringAsFixed(2)); + } + // ignore: avoid_print + print( + 'IMAGE_EXIT_E2E ${jsonEncode({ + scenario: {'exitCodes': codes, 'secondsAfterReached': seconds}, + })}', + ); + expect(codes, everyElement(exitCode)); + }); + } + + test('a batch of images reports every sampling step in order and ends with ' + 'the decoding event', () async { + if (model == null) { + markTestSkipped('Set IMAGE_EXIT_MODEL to run it.'); + return; + } + final probe = await _runProbe(['events', model]); + expect(probe.exitCode, 0, reason: probe.stderr); + final line = LineSplitter.split( + probe.stdout, + ).singleWhere((line) => line.startsWith('IMAGE_PROBE_EVENTS ')); + final events = jsonDecode(line.substring('IMAGE_PROBE_EVENTS '.length)); + + // ignore: avoid_print + print(line); + expect(events, { + for (final (count, steps) in [(2, 1), (3, 4), (2, 4)]) + '${count}x$steps': [ + 'encodingPrompt 0/$steps image 0/$count', + for (var image = 0; image < count; image++) + for (var step = 0; step <= steps; step++) + 'sampling $step/$steps image $image/$count', + 'decoding 0/$count image ${count - 1}/$count', + ], + }); + }); +} + +/// Runs the probe fixture with [arguments] and reports how it ended and how +/// long after its last line it took to exit. +Future<({int exitCode, String stdout, String stderr, double afterReached})> +_runProbe(List arguments) async { + final process = await Process.start(Platform.resolvedExecutable, [ + 'run', + 'test/fixtures/image_exit_probe.dart', + ...arguments, + ]); + final sinceReached = Stopwatch(); + final stdout = process.stdout.transform(utf8.decoder).map((chunk) { + if (chunk.contains('IMAGE_PROBE_REACHED')) sinceReached.start(); + return chunk; + }).join(); + final stderr = process.stderr.transform(utf8.decoder).join(); + final int code; + try { + code = await process.exitCode.timeout(const Duration(minutes: 2)); + } on TimeoutException { + process.kill(ProcessSignal.sigkill); + fail('${arguments.first} did not exit: ${await stderr}'); + } + sinceReached.stop(); + return ( + exitCode: code, + stdout: await stdout, + stderr: await stderr, + afterReached: sinceReached.elapsedMicroseconds / 1e6, + ); +} diff --git a/ffigen_stable_diffusion.yaml b/ffigen_stable_diffusion.yaml index 564d34a31..ac445ab6d 100644 --- a/ffigen_stable_diffusion.yaml +++ b/ffigen_stable_diffusion.yaml @@ -1,11 +1,29 @@ name: StableDiffusion -description: Bindings to stable-diffusion.cpp from stable-diffusion-native +description: Bindings to stable-diffusion.cpp and its sd_dart_ wrapper from stable-diffusion-native output: 'lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart' headers: entry-points: - '.dart_tool/llamadart/ffigen_headers_stable_diffusion/include/stable-diffusion.h' + - '.dart_tool/llamadart/ffigen_headers_stable_diffusion/include/sd_dart_wrapper.h' include-directives: - '.dart_tool/llamadart/ffigen_headers_stable_diffusion/include/stable-diffusion.h' + - '.dart_tool/llamadart/ffigen_headers_stable_diffusion/include/sd_dart_wrapper.h' +functions: + exclude: + # Not kill-safe from Dart: an isolate killed after a native call never + # reaches the track, untrack or call-end that would follow it, and a Dart + # program that returns from main after teardown waits forever for its + # blocked isolates. + - 'sd_dart_exit_call_begin' + - 'sd_dart_exit_call_end' + - 'sd_dart_exit_teardown' + - 'sd_dart_exit_track' + - 'sd_dart_exit_untrack' + leaf: + # Takes no lock, makes no system call and copies a bounded number of + # reports, so the calling isolate polls it without leaving Dart. + include: + - 'sd_dart_progress_read' # Incomplete `extern const char* x[]` arrays; ffigen would read the first element # as a pointer to the array. Use the *_name functions instead. globals: diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart b/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart index 5c55e12dc..92d50ca04 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart @@ -297,6 +297,68 @@ external bool sd_ctx_supports_video_generation(ffi.Pointer sd_ctx); @ffi.Native)>() external bool sd_ctx_unload_control_net(ffi.Pointer sd_ctx); +@ffi.Native, ffi.UnsignedInt)>( + symbol: 'sd_dart_cancel_generation', +) +external void _sd_dart_cancel_generation( + ffi.Pointer sd_ctx, + int mode, +); + +void sd_dart_cancel_generation( + ffi.Pointer sd_ctx, + sd_cancel_mode_t mode, +) { + return _sd_dart_cancel_generation(sd_ctx, mode.value); +} + +@ffi.Native)>() +external void sd_dart_exit_free(ffi.Pointer object); + +@ffi.Native() +external void sd_dart_exit_set_wait_ms(int wait_ms, int work_wait_ms); + +@ffi.Native() +external int sd_dart_exit_tracked_count(); + +@ffi.Native< + ffi.Bool Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer>, + ffi.Pointer, + ) +>() +external bool sd_dart_generate_image( + ffi.Pointer sd_ctx, + ffi.Pointer sd_img_gen_params, + ffi.Pointer> images_out, + ffi.Pointer num_images_out, +); + +@ffi.Native Function(ffi.Pointer)>() +external ffi.Pointer sd_dart_new_sd_ctx( + ffi.Pointer sd_ctx_params, +); + +@ffi.Native() +external void sd_dart_progress_enable(); + +@ffi.Native< + ffi.Size Function( + ffi.Uint64, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ) +>(isLeaf: true) +external int sd_dart_progress_read( + int after, + ffi.Pointer reports, + int capacity, + ffi.Pointer latest, +); + @ffi.Native)>( symbol: 'sd_get_default_sample_method', ) @@ -1245,6 +1307,48 @@ final class sd_ctx_params_t extends ffi.Struct { final class sd_ctx_t extends ffi.Opaque {} +enum sd_dart_exit_stage { + SD_DART_EXIT_STAGE_CONTEXT_USER(0), + SD_DART_EXIT_STAGE_CONTEXT(1), + SD_DART_EXIT_STAGE_RESOURCE(2); + + final int value; + const sd_dart_exit_stage(this.value); + + static sd_dart_exit_stage fromValue(int value) => switch (value) { + 0 => SD_DART_EXIT_STAGE_CONTEXT_USER, + 1 => SD_DART_EXIT_STAGE_CONTEXT, + 2 => SD_DART_EXIT_STAGE_RESOURCE, + _ => throw ArgumentError('Unknown value for sd_dart_exit_stage: $value'), + }; +} + +final class sd_dart_progress_t extends ffi.Struct { + @ffi.Uint64() + external int sequence; + + @ffi.Int32() + external int step; + + @ffi.Int32() + external int steps; + + @ffi.Float() + external double time; + + static ffi.Pointer $allocate( + ffi.Allocator $allocator, { + required int sequence, + required int step, + required int steps, + required double time, + }) => $allocator() + ..ref.sequence = sequence + ..ref.step = step + ..ref.steps = steps + ..ref.time = time; +} + final class sd_embedding_t extends ffi.Struct { external ffi.Pointer name; diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart new file mode 100644 index 000000000..4f78ebee8 --- /dev/null +++ b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart @@ -0,0 +1,258 @@ +import 'dart:ffi'; + +import '../../core/exceptions.dart'; +import '../../hook/native_release_pins.dart'; +import 'stable_diffusion_bindings.dart' as sd; + +const _stableDiffusionAsset = 'package:llamadart/stable_diffusion'; + +typedef _ProgressEnableNative = Void Function(); +typedef _ProgressReadNative = + Size Function( + Uint64, + Pointer, + Size, + Pointer, + ); +typedef _NewContextNative = + Pointer Function(Pointer); +typedef _GenerateImageNative = + Bool Function( + Pointer, + Pointer, + Pointer>, + Pointer, + ); +typedef _CancelGenerationNative = + Void Function(Pointer, UnsignedInt); +typedef _ExitFreeNative = Void Function(Pointer); + +/// Every native call an image worker makes. +/// +/// The `sd_dart_` members are stable-diffusion-native's wrapper functions +/// (`src/sd_dart_wrapper.h` there), which exist from +/// [minimumNativeRelease] on: +/// +/// - The library records progress reports itself and [progressRead] copies +/// them out, so Dart gives stable-diffusion.cpp no callback. A callback +/// into the VM from the generating thread aborts the process when the VM +/// is already shutting down. +/// - [newContext] tracks the context in a registry inside the creating call, +/// [generateImage] is a call that registry waits for, and on Apple +/// platforms the library frees what is still tracked during C `exit`, +/// before ggml-metal's static destructor, which aborts while a Metal buffer +/// is allocated. The registry waits only for those two calls and +/// [exitFree]: any other native call on a context that is in flight when +/// the process exits is freed under (`doc/llama_cpp_exit_teardown.md`). +/// +/// [tryResolve] binds the six of them through the addresses it resolves, so +/// the calls exist only when the runtime exports all six. An older runtime +/// has no way to report progress without a Dart callback, so image +/// generation is unsupported on it rather than falling back. +/// +/// `sd_dart_exit_teardown`, `sd_dart_exit_call_begin`, +/// `sd_dart_exit_call_end`, `sd_dart_exit_track` and `sd_dart_exit_untrack` +/// are left unbound: an isolate killed after a native call never reaches the +/// call that would follow it, and a Dart program that returns from `main` +/// after teardown waits forever for its blocked isolates. +/// +/// The remaining members are upstream functions that return at once. A new +/// call on a context that can run for longer than the registry's 250 ms +/// settle time needs an `sd_dart_` wrapper in stable-diffusion-native first. +final class StableDiffusionCalls { + /// Creates the calls from functions. + const StableDiffusionCalls({ + required this.progressEnable, + required this.progressRead, + required this.newContext, + required this.generateImage, + required this.cancelGeneration, + required this.exitFree, + required this.exitFreeAddress, + required this.contextParamsInit, + required this.supportsImageGeneration, + required this.modelVersionName, + required this.imageGenerationParamsInit, + required this.freeImages, + }); + + /// The oldest `stable-diffusion-native` release that exports the `sd_dart_` + /// functions. + static const String minimumNativeRelease = 'v0.2.0-1'; + + /// The `sd_dart_` functions [tryResolve] needs the runtime to export. + static const List wrapperSymbols = [ + 'sd_dart_progress_enable', + 'sd_dart_progress_read', + 'sd_dart_new_sd_ctx', + 'sd_dart_generate_image', + 'sd_dart_cancel_generation', + 'sd_dart_exit_free', + ]; + + /// Resolves the calls from the bundled runtime, or returns `null` when it + /// does not export every one of [wrapperSymbols]. + /// + /// [symbol] replaces the lookup: it returns the address of the function + /// exported under a name, and throws [ArgumentError] when there is none. + static StableDiffusionCalls? tryResolve({ + Pointer Function(String name)? symbol, + }) { + try { + return StableDiffusionCalls._fromSymbols(symbol ?? symbolAddress); + } on ArgumentError { + return null; + } + } + + /// The address of the function the bundled runtime exports as [name], one + /// of [wrapperSymbols]; throws [ArgumentError] when it exports none. + static Pointer symbolAddress(String name) => switch (name) { + 'sd_dart_progress_enable' => + Native.addressOf>( + sd.sd_dart_progress_enable, + ), + 'sd_dart_progress_read' => + Native.addressOf>( + sd.sd_dart_progress_read, + ), + 'sd_dart_new_sd_ctx' => Native.addressOf>( + sd.sd_dart_new_sd_ctx, + ), + 'sd_dart_generate_image' => + Native.addressOf>( + sd.sd_dart_generate_image, + ), + 'sd_dart_cancel_generation' => + Native.addressOf>( + _cancelGeneration, + ), + 'sd_dart_exit_free' => Native.addressOf>( + sd.sd_dart_exit_free, + ), + _ => throw ArgumentError.value(name, 'name', 'not bound'), + }; + + // Every wrapper is called through the address resolved here, so none can be + // bound without being part of the probe. + factory StableDiffusionCalls._fromSymbols( + Pointer Function(String name) symbol, + ) { + Pointer> function(String name) => + symbol(name).cast(); + final exitFree = function<_ExitFreeNative>('sd_dart_exit_free'); + final void Function(Pointer, int) cancelGeneration = + function<_CancelGenerationNative>( + 'sd_dart_cancel_generation', + ).asFunction(); + return StableDiffusionCalls( + progressEnable: function<_ProgressEnableNative>( + 'sd_dart_progress_enable', + ).asFunction(), + progressRead: function<_ProgressReadNative>( + 'sd_dart_progress_read', + ).asFunction(isLeaf: true), + newContext: function<_NewContextNative>( + 'sd_dart_new_sd_ctx', + ).asFunction(), + generateImage: function<_GenerateImageNative>( + 'sd_dart_generate_image', + ).asFunction(), + cancelGeneration: (context) => + cancelGeneration(context, sd.sd_cancel_mode_t.SD_CANCEL_ALL.value), + exitFree: exitFree.asFunction(), + exitFreeAddress: exitFree.cast(), + contextParamsInit: sd.sd_ctx_params_init, + supportsImageGeneration: sd.sd_ctx_supports_image_generation, + modelVersionName: sd.sd_get_model_version_name, + imageGenerationParamsInit: sd.sd_img_gen_params_init, + freeImages: sd.free_sd_images, + ); + } + + /// `sd_dart_progress_enable`: from then on the library records every + /// progress report in the process, loads included, and prints no progress + /// bars. Its first call is not synchronized with a load or generation on + /// another thread. + final void Function() progressEnable; + + /// `sd_dart_progress_read`: copies up to `capacity` reports whose sequence + /// is greater than `after` into `reports`, oldest first, returns how many, + /// and writes the newest recorded sequence to `latest`. The library keeps + /// the [progressHistory] most recent reports; when older ones are gone the + /// first report returned is not `after + 1`. A leaf call: it takes no lock + /// and never waits. + final int Function( + int after, + Pointer reports, + int capacity, + Pointer latest, + ) + progressRead; + + /// The number of reports [progressRead] keeps. + static const int progressHistory = 4095; + + /// `sd_dart_new_sd_ctx`: `new_sd_ctx` that tracks the context before it + /// returns; `nullptr` on failure. + final Pointer Function(Pointer params) + newContext; + + /// `sd_dart_generate_image`: `generate_image` as a call exit teardown + /// cancels and waits for. + final bool Function( + Pointer context, + Pointer params, + Pointer> imagesOut, + Pointer countOut, + ) + generateImage; + + /// `sd_dart_cancel_generation` with `SD_CANCEL_ALL`: callable from any + /// thread while another generates, and does nothing for a context that was + /// already freed. + final void Function(Pointer context) cancelGeneration; + + /// `sd_dart_exit_free`: frees a context [newContext] returned, once; does + /// nothing for one that exit teardown already freed. + final void Function(Pointer context) exitFree; + + /// The address of [exitFree], for `IsolateShutdownReleases`. + final Pointer exitFreeAddress; + + /// `sd_ctx_params_init`. + final void Function(Pointer params) contextParamsInit; + + /// `sd_ctx_supports_image_generation`. + final bool Function(Pointer context) supportsImageGeneration; + + /// `sd_get_model_version_name`: a static string, or `nullptr`. + final Pointer Function(Pointer context) modelVersionName; + + /// `sd_img_gen_params_init`. + final void Function(Pointer params) + imageGenerationParamsInit; + + /// `free_sd_images`. + final void Function(Pointer images, int count) freeImages; +} + +/// The error for a stable_diffusion runtime that does not export every +/// function of [StableDiffusionCalls]. +LlamaUnsupportedException stableDiffusionWrapperUnsupported() => + LlamaUnsupportedException( + 'The stable_diffusion runtime does not export the sd_dart_ functions ' + 'image generation needs for progress without a Dart callback and for ' + 'freeing its contexts at process exit ' + '(${StableDiffusionCalls.wrapperSymbols.join(', ')}): ' + 'stable-diffusion-native ${StableDiffusionCalls.minimumNativeRelease} ' + 'or later is required. Bundle the package-pinned release ' + '$stableDiffusionReleaseTag.', + ); + +// The generated binding takes the enum, so it has no address of its own. +@Native<_CancelGenerationNative>( + symbol: 'sd_dart_cancel_generation', + assetId: _stableDiffusionAsset, +) +external void _cancelGeneration(Pointer context, int mode); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart index 0d607f680..91f0d99b3 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart @@ -7,30 +7,52 @@ import 'package:ffi/ffi.dart'; import '../../core/exceptions.dart'; import '../../core/image/generated_image.dart'; import '../../core/image/image_generation_driver.dart'; +import '../../core/llama_logger.dart'; import '../isolate_shutdown_releases.dart'; import 'stable_diffusion_bindings.dart' as sd; +import 'stable_diffusion_calls.dart'; import 'stable_diffusion_params.dart'; -typedef _ProgressCallback = NativeCallable; +/// Resolves the native calls of a worker; `null` when the runtime lacks them. +typedef StableDiffusionCallsResolver = StableDiffusionCalls? Function(); + +/// Starts the timer that polls progress during a generation. +typedef StableDiffusionProgressTimer = + Timer Function(Duration interval, void Function(Timer timer) poll); /// One stable-diffusion.cpp context running in a dedicated worker isolate. /// -/// Loading and `generate_image` block, so both run in the worker. Progress -/// comes back through a [NativeCallable.listener] owned by the calling -/// isolate, which is safe to invoke from any runtime thread. Cancellation -/// calls `sd_cancel_generation` from the calling isolate, since the worker is -/// blocked inside `generate_image`; the runtime flag is atomic. +/// Loading and `generate_image` block, so both run in the worker. The runtime +/// records its progress reports and the calling isolate reads them on a +/// timer: Dart gives stable-diffusion.cpp no callback, because a callback +/// from the generating thread into a VM that is shutting down aborts the +/// process. Cancellation calls `sd_dart_cancel_generation` from the calling +/// isolate, since the worker is blocked inside the generation. /// /// Only a pending reply keeps the calling isolate alive, so a program that /// ends with a model loaded exits; the worker then frees the model as it shuts /// down. final class StableDiffusionImageWorker implements ImageGenerationSession { + /// How often a running [generate] reads the recorded progress. A cancel + /// that arrived before the runtime started generating is applied again at + /// the same rate. + static const Duration progressPollInterval = Duration(milliseconds: 50); + + /// Reports one read asks for. + static const int _reportsPerRead = 64; + + /// Reads one poll makes at most, so a runtime that reports faster than the + /// calling isolate reads cannot keep it in the poll. Together with + /// [_reportsPerRead] it covers the reports the runtime keeps. + static const int _readsPerPoll = 64; + final Isolate _isolate; final _Replies _replies; final SendPort _commands; - final _ProgressCallback _progress; + final StableDiffusionCalls _calls; + final StableDiffusionProgressTimer _progressTimer; final Pointer _context; - void Function(int step, int steps)? _onProgress; + bool _cancelRequested = false; bool _disposed = false; bool _stopped = false; @@ -41,48 +63,56 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { this._isolate, this._replies, this._commands, - this._progress, + this._calls, + this._progressTimer, this._context, this.modelVersion, ); /// Spawns a worker and loads [config] in it. /// + /// [resolveCalls] runs once in the calling isolate and once in the worker; + /// [progressTimer] starts the progress poll of each [generate]. Tests + /// replace both. + /// /// Throws [LlamaModelException] when the runtime cannot load the files as - /// an image model. + /// an image model, and [LlamaUnsupportedException] when the runtime does + /// not export the functions of [StableDiffusionCalls]. static Future start( - ImageGenerationSessionConfig config, - ) async { - void Function(int step, int steps)? route; - final progress = _ProgressCallback.listener( - (int step, int steps, double _, Pointer _) => - route?.call(step, steps), - )..keepIsolateAlive = false; + ImageGenerationSessionConfig config, { + StableDiffusionCallsResolver resolveCalls = StableDiffusionCalls.tryResolve, + StableDiffusionProgressTimer progressTimer = Timer.periodic, + }) async { + final calls = resolveCalls(); + if (calls == null) { + throw stableDiffusionWrapperUnsupported(); + } + // Registers the runtime's recorder, which is not synchronized with a + // load: it has to be in place before the worker starts one. + calls.progressEnable(); final replies = _Replies(); Isolate? isolate; try { isolate = await Isolate.spawn( _workerMain, - (replies.sendPort, config, progress.nativeFunction.address), + (replies.sendPort, config, resolveCalls), debugName: 'llamadart-image-generation', onExit: replies.sendPort, onError: replies.sendPort, ); final loaded = _unwrap(await replies.next()) as _Loaded; - final worker = StableDiffusionImageWorker._( + return StableDiffusionImageWorker._( isolate, replies, loaded.commands, - progress, + calls, + progressTimer, Pointer.fromAddress(loaded.context), loaded.modelVersion, ); - route = (step, steps) => worker._onProgress?.call(step, steps); - return worker; } catch (_) { isolate?.kill(priority: Isolate.immediate); await replies.close(); - progress.close(); rethrow; } } @@ -97,10 +127,52 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { 'The image-generation worker stopped; load the model again.', ); } - _onProgress = onProgress; + final reports = calloc(_reportsPerRead); + final latest = calloc(); + // Reports are process-wide and numbered: everything after the newest one + // recorded so far belongs to this generation. + _calls.progressRead(0, nullptr, 0, latest); + var after = latest.value; + var dropped = 0; + void readProgress() { + for (var reads = 0; reads < _readsPerPoll; reads++) { + final count = _calls.progressRead( + after, + reports, + _reportsPerRead, + latest, + ); + if (count == 0) { + return; + } + // The runtime dropped its oldest reports when the first one it + // returns does not follow the last one read. + dropped += reports[0].sequence - after - 1; + for (var i = 0; i < count; i++) { + final report = reports[i]; + after = report.sequence; + onProgress(report.step, report.steps); + } + if (after >= latest.value) { + return; + } + } + } + + _cancelRequested = false; + final timer = _progressTimer(progressPollInterval, (_) { + if (_cancelRequested) { + // stable-diffusion.cpp clears a cancel request when a generation + // starts, so one that arrived before then is applied again. + _calls.cancelGeneration(_context); + } + readProgress(); + }); try { _commands.send(request); final reply = await _reply() as _Generated; + // The runtime recorded the last reports before the reply was sent. + readProgress(); return reply.images == null ? null : [ @@ -113,15 +185,29 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { ), ]; } finally { - _onProgress = null; + timer.cancel(); + calloc.free(reports); + calloc.free(latest); + if (dropped > 0) { + LlamaLogger.instance.warning( + 'The stable_diffusion runtime dropped $dropped image-generation ' + 'progress reports: it keeps the ' + '${StableDiffusionCalls.progressHistory} most recent ones, and more ' + 'than that were recorded between two reads. Progress events of ' + 'this generation can be missing or mislabelled.', + ); + } } } @override void cancel() { - if (!_disposed) { - sd.sd_cancel_generation(_context, sd.sd_cancel_mode_t.SD_CANCEL_ALL); + // A stopped worker's shutdown already freed the context. + if (_disposed || _stopped) { + return; } + _cancelRequested = true; + _calls.cancelGeneration(_context); } @override @@ -138,8 +224,6 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { } finally { _isolate.kill(priority: Isolate.immediate); await _replies.close(); - // The worker cleared the callback before replying, so nothing calls it. - _progress.close(); } } @@ -254,7 +338,7 @@ final class _Loaded { } final class _LoadFailure { - final LlamaModelException error; + final LlamaException error; const _LoadFailure(this.error); } @@ -282,21 +366,25 @@ final class _Generated { const _Generated(this.images); } -void _workerMain((SendPort, ImageGenerationSessionConfig, int) arguments) { - final (replies, config, progressAddress) = arguments; - final progress = - Pointer>.fromAddress( - progressAddress, - ); +void _workerMain( + (SendPort, ImageGenerationSessionConfig, StableDiffusionCallsResolver) + arguments, +) { + final (replies, config, resolveCalls) = arguments; + final calls = resolveCalls(); + if (calls == null) { + replies.send(_LoadFailure(stableDiffusionWrapperUnsupported())); + return; + } - final context = _withProgress(progress, () => _newContext(config)); + final context = _newContext(calls, config); if (context == nullptr) { replies.send(_LoadFailure(stableDiffusionModelLoadFailure(config.files))); return; } - if (!sd.sd_ctx_supports_image_generation(context)) { + if (!calls.supportsImageGeneration(context)) { IsolateShutdownReleases.current.release(context); - sd.free_sd_ctx(context); + calls.exitFree(context.cast()); replies.send( _LoadFailure( LlamaModelException( @@ -308,7 +396,7 @@ void _workerMain((SendPort, ImageGenerationSessionConfig, int) arguments) { } final commands = ReceivePort('llamadart-image-generation-commands'); - final version = sd.sd_get_model_version_name(context); + final version = calls.modelVersionName(context); replies.send( _Loaded( commands.sendPort, @@ -319,54 +407,31 @@ void _workerMain((SendPort, ImageGenerationSessionConfig, int) arguments) { commands.listen((command) { switch (command) { case ImageGenerationSessionRequest(): - final _Generated generated; - try { - generated = _withProgress( - progress, - () => _generate(context, command), - ); - } catch (_) { - // The error ends this isolate, and the calling isolate may still - // call `sd_cancel_generation` on the context: leak it rather than - // free it at shutdown. - IsolateShutdownReleases.current.release(context); - rethrow; - } - replies.send(generated); + // An error here ends this isolate with the context still held, so + // its shutdown frees it; a later cancel from the calling isolate + // does nothing for a freed context. + replies.send(_generate(calls, context, command)); case _Dispose(): IsolateShutdownReleases.current.release(context); - sd.free_sd_ctx(context); + calls.exitFree(context.cast()); commands.close(); replies.send(const _Disposed()); } }); } -/// Runs [body] with the process-wide progress callback set, so the runtime -/// never prints progress bars to stdout, and clears it before returning. -T _withProgress( - Pointer> progress, - T Function() body, +Pointer _newContext( + StableDiffusionCalls calls, + ImageGenerationSessionConfig config, ) { - sd.sd_set_progress_callback(progress, nullptr); - try { - return body(); - } finally { - sd.sd_set_progress_callback(nullptr, nullptr); - } -} - -Pointer _newContext(ImageGenerationSessionConfig config) { return using((arena) { final params = arena(); - sd.sd_ctx_params_init(params); + calls.contextParamsInit(params); applyStableDiffusionContextParams(params, config, arena); - final context = sd.new_sd_ctx(params); + final context = calls.newContext(params); IsolateShutdownReleases.current.hold( ShutdownStage.model, - Native.addressOf)>>( - sd.free_sd_ctx, - ).cast(), + calls.exitFreeAddress, context, ); return context; @@ -374,17 +439,18 @@ Pointer _newContext(ImageGenerationSessionConfig config) { } _Generated _generate( + StableDiffusionCalls calls, Pointer context, ImageGenerationSessionRequest request, ) { return using((arena) { final params = arena(); - sd.sd_img_gen_params_init(params); + calls.imageGenerationParamsInit(params); applyStableDiffusionGenerationParams(params, request, arena); final imagesOut = arena>(); final countOut = arena(); - final ok = sd.generate_image(context, params, imagesOut, countOut); + final ok = calls.generateImage(context, params, imagesOut, countOut); final images = imagesOut.value; final count = countOut.value; try { @@ -397,7 +463,7 @@ _Generated _generate( ]); } finally { if (images != nullptr) { - sd.free_sd_images(images, count); + calls.freeImages(images, count); } } }); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart index 7650a95a6..23580a65c 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -6,6 +6,7 @@ import 'package:ffi/ffi.dart'; import '../../core/exceptions.dart'; import '../windows_runtime_libraries.dart'; import 'stable_diffusion_bindings.dart' as sd; +import 'stable_diffusion_calls.dart'; import 'stable_diffusion_runtime_status.dart'; /// The native calls the probe makes; tests substitute a fake. @@ -18,6 +19,9 @@ abstract interface class StableDiffusionNativeApi { /// `sd_list_devices()` output. String listDevices(); + + /// Whether the runtime exports every function of [StableDiffusionCalls]. + bool exportsWrapperCalls(); } /// ABIs stable-diffusion-native publishes a runtime for. `Abi.iosArm64` covers @@ -54,7 +58,10 @@ const Set stableDiffusionPublishedAbis = { /// cross-compiled without AVX, and macOS 13.3 runs only on Intel CPUs that /// have AVX2 anyway. /// -/// Then `sd_version`, `sd_commit` and `sd_list_devices` must answer. +/// Then `sd_version`, `sd_commit` and `sd_list_devices` must answer, and the +/// runtime must export the `sd_dart_` functions of [StableDiffusionCalls], +/// which a release older than [StableDiffusionCalls.minimumNativeRelease] +/// does not. /// /// [abi], [readCpuInfo], [windowsHasAvx2], [missingWindowsLibraries] and /// [api] default to the host and the bundled library; tests replace them. @@ -129,6 +136,11 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ final version = api.version(); final commit = api.commit(); final devices = parseStableDiffusionDeviceList(api.listDevices()); + if (!api.exportsWrapperCalls()) { + return StableDiffusionRuntimeStatus.unavailable( + stableDiffusionWrapperUnsupported(), + ); + } return StableDiffusionRuntimeStatus.available( version: version, commit: commit, @@ -317,6 +329,9 @@ final class _BundledStableDiffusionApi implements StableDiffusionNativeApi { } } + @override + bool exportsWrapperCalls() => StableDiffusionCalls.tryResolve() != null; + static String _string(Pointer value) => value == nullptr ? '' : value.cast().toDartString(); } diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index ffdd9e8ef..cd10b19af 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -502,7 +502,9 @@ class ImageGenerationEngine { /// an unset seed is picked at random and reported in the result. /// /// The task's [ImageGenerationTask.events] report each phase and sampling - /// step, then one [ImageGenerationFinalEvent]. [ImageGenerationTask.cancel] + /// step, then one [ImageGenerationFinalEvent]. The engine reads the + /// runtime's progress every 50 ms, so progress events arrive in groups, up + /// to that long after the runtime reported them. [ImageGenerationTask.cancel] /// takes effect before the runtime's next sampling step or before decoding, /// so the task can run up to one more step before it reports /// [ImageGenerationCompletionState.cancelled]. [dispose] cancels the task. diff --git a/lib/src/hook/native_release_pins.dart b/lib/src/hook/native_release_pins.dart index 63c771728..d14665680 100644 --- a/lib/src/hook/native_release_pins.dart +++ b/lib/src/hook/native_release_pins.dart @@ -144,11 +144,11 @@ const liteRtLmBundleSpecs = [ /// `leehack/stable-diffusion-native` release tag downloaded for the opt-in /// stable-diffusion.cpp runtime. -const stableDiffusionReleaseTag = 'v0.2.0'; +const stableDiffusionReleaseTag = 'v0.2.0-1'; /// stable_diffusion cache directory version derived from /// [stableDiffusionReleaseTag]. -const stableDiffusionVersion = '0.2.0'; +const stableDiffusionVersion = '0.2.0-1'; /// A published stable-diffusion-native runtime archive and the library it must /// contain under `lib/`. @@ -175,62 +175,62 @@ class StableDiffusionBundleSpec { const stableDiffusionBundleSpecs = [ StableDiffusionBundleSpec( 'android-arm64', - sha256: '8c8c270a99612a4d33e9be87ec5fe67be790bcac89cece43da50fc12c05eb003', + sha256: 'a0bef58480c213a87dffb72f02bd47a89366510b7ac24f64120e2cfd64ed2c76', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'ios-arm64', - sha256: 'bedcd95f4f670ab38bec2b5140e2b907ad08b28cb84371af6170756a679aaa80', + sha256: '82ebb318d695db75d6b384d84aaddb69a2dd369cf68e8411dc345c32e423a714', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'ios-arm64-sim', - sha256: 'e131e9d519b2c9bed64b596e5026877aae295c152dca0498c8c940bdc26c47f0', + sha256: 'b6fa5ac2d35503d4183bf083ce10ed7a6c54a5a8db2eabfbaed5bfda8686d397', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'ios-x64-sim', - sha256: '09323057b0941fd06edc08fb013d117661ba51457feda7ddddf39d57e7ebe9f5', + sha256: '1789de5de4c36821b677cff95307f5522d190c6621eeca86fccbc0880ebf27ed', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'macos-arm64', - sha256: '47c16a31bedbd755618f349b44a04605c4de504454dbc24a10ed581bb92c2652', + sha256: '931f53883c1a31092e28d565c23e5b23e16fba655e1dc000621996d69f8721b1', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'macos-x64', - sha256: '22bd8feea2cd05318c1e06f97663bb4c1301e97aef7979b6a084a9d038fc46c0', + sha256: '9c5c4d93c9ee6f4640f758a62ff3cfd4aa9ec28e0a6ae01aa12029a5104f7745', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'linux-arm64', - sha256: 'a6f8d8a2e4959d910ab8bb36088be71962a996de471570d429b2cdbec4b7681f', + sha256: 'a32fac5728322e4d3aa985868bae6dcc7a1eda41a2a7cb322021c7a3302bec4d', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-arm64-vulkan', - sha256: 'a64be0e2a1507d04844703bf1de08401c793060a8db555c77160a40fc95f19a4', + sha256: 'ff9383e61f183ce5fc005a5bede927c57df35e701f690e70d68b741d9ed06cae', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-x64', - sha256: 'af253cc4c4a17ca29f895c1c576d4aa92b35257df54832775d2ef6259463c07f', + sha256: 'acad806da58a9aedf9e549bd8f949b24cef0535fca0d7b0870b4093ef6bcb103', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-x64-vulkan', - sha256: 'ea22ecc84d418eaf8b9473117dcceaf6df527014d07722634b46200d0f337c5e', + sha256: '731008d6df747527ec91525d59ca44077f0b97ff0b16849ab77a410787336b0b', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'windows-x64', - sha256: 'cfef71403378a3555e7abbd15c10297dd24797548767cbd2a953b38af920ec47', + sha256: '3aa4028117330149cbb3c6b739841145381a9e0e9fba9e45c0a58c70c31d671a', requiredLibraries: {'stable-diffusion.dll'}, ), StableDiffusionBundleSpec( 'windows-x64-vulkan', - sha256: 'a114817a3d933ae55cf0f49940a2909d6be3025db3dbc55399b0c63fc3fc9982', + sha256: '127234dcce7ab84a8ba740dfdd57206a0587c2b54edf5683335bae7b06776de3', requiredLibraries: {'stable-diffusion.dll'}, ), ]; diff --git a/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md b/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md index 940cf7455..79310445d 100644 --- a/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md +++ b/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md @@ -1,3 +1,9 @@ +## Unreleased + +* Updated Apple SwiftPM native pin to `leehack/stable-diffusion-native@v0.2.0-1`, + whose XCFramework carries an Apple privacy manifest and frees image models + still allocated at process exit. + ## 0.0.1 * Initial Flutter Apple SwiftPM companion package for `llamadart` diff --git a/packages/llamadart_stable_diffusion_flutter/README.md b/packages/llamadart_stable_diffusion_flutter/README.md index d2cdefa16..e4cfd2372 100644 --- a/packages/llamadart_stable_diffusion_flutter/README.md +++ b/packages/llamadart_stable_diffusion_flutter/README.md @@ -28,14 +28,17 @@ macOS builds; `llamadart_native_runtimes` still decides the other platforms. This package has no runtime Dart API of its own. Import `package:llamadart` normally from the core package and use `ImageGenerationEngine` there. -The Apple SwiftPM manifest pins `leehack/stable-diffusion-native@v0.2.0`. - -An Apple privacy manifest for the stable-diffusion.cpp runtime can ship only -inside this XCFramework, never in the dylibs the native-assets hook bundles. -If the embedded `stable_diffusion.framework` in the built app has no -`PrivacyInfo.xcprivacy`, or the app uses the hook path, declare -`NSPrivacyAccessedAPICategoryFileTimestamp` with reasons `C617.1` and `3B52.1` -in the app's own `PrivacyInfo.xcprivacy`. +The Apple SwiftPM manifest pins `leehack/stable-diffusion-native@v0.2.0-1`. + +Apps bound for the App Store should use this package: an Apple privacy +manifest for the stable-diffusion.cpp runtime ships inside this XCFramework, +never in the dylibs the core package's native-assets hook bundles. The +`v0.2.0-1` XCFramework declares `NSPrivacyAccessedAPICategoryFileTimestamp` +with reasons `C617.1` and `3B52.1`; release `0.0.1` of this package links +`v0.2.0`, which has no manifest. If the embedded `stable_diffusion.framework` +in the built app has no `PrivacyInfo.xcprivacy`, or the app uses the hook +path, declare that category and those reasons in the app's own +`PrivacyInfo.xcprivacy`. Source for this package lives in `packages/llamadart_stable_diffusion_flutter` in the diff --git a/packages/llamadart_stable_diffusion_flutter/darwin/llamadart_stable_diffusion_flutter/Package.swift b/packages/llamadart_stable_diffusion_flutter/darwin/llamadart_stable_diffusion_flutter/Package.swift index 2162df704..37186f3ee 100644 --- a/packages/llamadart_stable_diffusion_flutter/darwin/llamadart_stable_diffusion_flutter/Package.swift +++ b/packages/llamadart_stable_diffusion_flutter/darwin/llamadart_stable_diffusion_flutter/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent() let artifactsRoot = packageRoot.appendingPathComponent("Artifacts") -let stableDiffusionTag = "v0.2.0" +let stableDiffusionTag = "v0.2.0-1" func localArtifactPath(_ name: String) -> String? { let path = artifactsRoot.appendingPathComponent(name).path @@ -47,7 +47,7 @@ let package = Package( repository: "leehack/stable-diffusion-native", artifactName: "stable-diffusion-native-apple-xcframework-\(stableDiffusionTag).zip", tag: stableDiffusionTag, - checksum: "a48a5fc1724dabc6fc6c32813221aaee25765b168d0267562354ed1b4c077de1" + checksum: "32c571e9c5204f1e8d2cdbae2371e3fac80bd1170715366e622d657cdca7a39b" ), .target( name: "llamadart_stable_diffusion_flutter", diff --git a/skills/llamadart-flutter-app/SKILL.md b/skills/llamadart-flutter-app/SKILL.md index 730643993..1a7e7e0a6 100644 --- a/skills/llamadart-flutter-app/SKILL.md +++ b/skills/llamadart-flutter-app/SKILL.md @@ -37,8 +37,10 @@ or shipping runtimes the app does not use. `AppLifecycleListener(onExitRequested: ...)`, awaiting them before returning `AppExitResponse.exit` (from `dart:ui`). On macOS Metal a model still loaded when the process exits aborts in `ggml_metal_rsets_free`. The - llama.cpp runtime (`llamadart-native` `v0.5.0-2` and later) frees a - llama.cpp model a quit caught mid-load, but never an image model, and an + llama.cpp runtime (`llamadart-native` `v0.5.0-2` and later) and the + stable_diffusion runtime (`stable-diffusion-native` `v0.2.0-1` and later) + free a model a quit caught mid-load, but a quit during an image generation + waits for the whole generation, and an AppKit quit (Cmd-Q, last window, `exitApplication`) is not guaranteed to run llamadart's Dart-side cleanup. When the engine's owner can be disposed before quit (a @@ -120,7 +122,9 @@ or shipping runtimes the app does not use. Apple privacy manifest reaches an app inside a companion's XCFramework, never in hook-bundled dylibs. The llama.cpp XCFramework has one from `llamadart-native` `v0.5.0-1` (`llamadart_llama_cpp_flutter` releases after - `0.0.20`); the pinned stable_diffusion one has none. When llama.cpp or + `0.0.20`), and the stable_diffusion one from `stable-diffusion-native` + `v0.2.0-1` (`llamadart_stable_diffusion_flutter` releases after `0.0.1`). + When llama.cpp or stable_diffusion runs on the hook path, or the embedded `llama.framework` or `stable_diffusion.framework` has no `PrivacyInfo.xcprivacy`, add `NSPrivacyAccessedAPICategoryFileTimestamp` to the app's own diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index bd30edc45..73c257532 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -185,18 +185,22 @@ description: >- `(await engine.generate(request)).result`. - `GeneratedImage` has `width`, `height`, `channels` (3) and row-major RGB `pixels`; `toPng()` returns PNG bytes (for `Image.memory` or a file). -- One generation or model load at a time per process (stable-diffusion.cpp's - progress callback is global): a second one throws `LlamaStateException`, +- One generation or model load at a time per process (stable-diffusion.cpp + reports progress for the whole process): a second one throws + `LlamaStateException`, even on another engine. Await `task.done` before the next request; disable the Generate button while one runs. Do not generate from several isolates. - `task.cancel()` stops before the next sampling step; `done` reports `cancelled`, `result` throws `LlamaStateException`, and the stream closes without a final event. `dispose()` cancels a running task, waits, then frees the model. -- Dispose before a Flutter app quits: on macOS Metal, quitting with a model - still loaded aborts the process. A plain Dart program that ends with the - model loaded frees it on the way out, unless it dies of an error while the - model loads or generates; a Flutter quit does not. Flutter +- Progress events arrive in groups, up to about 50 ms after the runtime + reports them (the engine polls the runtime), always in order and before + the final event. +- Dispose before a Flutter app quits. A process that ends with an image + model loaded no longer aborts on macOS Metal, but nothing cancels a running + generation when a Dart program ends or a Flutter app quits, so the process + stays until the generation finishes. Flutter desktop apps skip `State.dispose` on quit; await `dispose()` in `AppLifecycleListener.onExitRequested`. If `ImageGenerationEngine.load` is still running, await it there and dispose diff --git a/test/support/fake_stable_diffusion_runtime.dart b/test/support/fake_stable_diffusion_runtime.dart new file mode 100644 index 000000000..adb6eac81 --- /dev/null +++ b/test/support/fake_stable_diffusion_runtime.dart @@ -0,0 +1,437 @@ +import 'dart:async'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:ffi/ffi.dart'; +import 'package:llamadart/src/backends/isolate_shutdown_releases.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_bindings.dart' + as sd; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_calls.dart'; + +const _workerIsolateName = 'llamadart-image-generation'; + +// Byte offsets into the state block both isolates share. +const _enabled = 0; +const _cancelled = 1; +const _resume = 2; +const _missingInWorker = 3; +const _rejectLoad = 4; +const _videoOnly = 5; +const _throwInGenerate = 6; +const _holdStart = 7; +const _pauseAfter = 8; +const _loadReports = 12; +const _decodeReports = 16; +const _reportsPerRead = 20; +const _racingReads = 28; +const _latest = 32; +const _modelVersion = 40; +const _ring = 64; +const _ringSlots = 16384; +const _stateBytes = _ring + _ringSlots * 8; + +/// A stand-in for the stable_diffusion runtime, shared by the two isolates of +/// a `StableDiffusionImageWorker`. +/// +/// It records every call made through [resolver] with the isolate that made +/// it, and reports progress the way stable-diffusion.cpp does: a generation +/// clears a pending cancel when it starts, samples every image of a batch +/// (`0/steps` when a pass starts, `k/steps` after step `k`) and only then +/// decodes, and looks at a cancel before each step and before each decode. +/// Like the real recorder it numbers reports from 1 for the whole process and +/// keeps the [history] most recent ones. +final class FakeStableDiffusionRuntime { + /// Creates a runtime that keeps [history] progress reports. + FakeStableDiffusionRuntime({ + this.history = StableDiffusionCalls.progressHistory, + }) : _state = calloc(_stateBytes) { + _state.cast()[_pauseAfter ~/ 4] = -1; + final version = 'SD 2.x'.codeUnits; + for (var i = 0; i < version.length; i++) { + _state[_modelVersion + i] = version[i]; + } + _port = RawReceivePort(_received, 'fake-stable-diffusion-calls'); + } + + /// Reports the runtime keeps. + final int history; + + final Pointer _state; + late final RawReceivePort _port; + final List<(String, String)> _calls = []; + final List<(String, Completer)> _waiting = []; + final List _arrived = []; + int _flushes = 0; + + /// What a worker resolves its native calls with, in either isolate. + StableDiffusionCalls? Function() get resolver => + _FakeCalls(_state.address, _port.sendPort, history).resolve; + + /// Makes [resolver] return `null` in the worker isolate only. + set missingInWorker(bool value) => _state[_missingInWorker] = value ? 1 : 0; + + /// Makes the load fail. + set rejectLoad(bool value) => _state[_rejectLoad] = value ? 1 : 0; + + /// Makes the loaded model one that cannot generate images. + set videoOnly(bool value) => _state[_videoOnly] = value ? 1 : 0; + + /// Makes a generation throw a Dart error in the worker. The worker records + /// `uncaught generation error`, with how it holds its context, when the + /// error ends it. + set throwInGenerate(bool value) => _state[_throwInGenerate] = value ? 1 : 0; + + /// Keeps a generation from starting, so from clearing a pending cancel, + /// while it is set. + set holdStart(bool value) => _state[_holdStart] = value ? 1 : 0; + + /// Pauses a generation once it has reported this many times (0 pauses it + /// right after it starts), until [resume]; `-1` never pauses. + set pauseAfter(int reports) => + _state.cast()[_pauseAfter ~/ 4] = reports; + + /// Reports a load records. + set loadReports(int count) => _state.cast()[_loadReports ~/ 4] = count; + + /// Tile reports the decode of a batch records. + set decodeReports(int count) => + _state.cast()[_decodeReports ~/ 4] = count; + + /// Reports recorded during each of the next 200 reads that ask for some, + /// as a runtime that reports faster than its reader reads does. + set reportsPerRead(int count) { + _state.cast()[_reportsPerRead ~/ 4] = count; + _state.cast()[_racingReads ~/ 4] = 200; + } + + /// Whether a cancel is pending. + bool get cancelPending => _state[_cancelled] != 0; + + /// Lets a paused generation continue. + void resume() => _state[_resume] = 1; + + /// Names of the calls [isolate] (`caller` or `worker`) made so far that + /// have arrived here; await [flush] first. + List calls(String isolate) => [ + for (final (from, name) in _calls) + if (from == isolate) name, + ]; + + /// Forgets the calls recorded so far. + void clearCalls() => _calls.clear(); + + /// Completes when the worker reports that [generation] is paused, and + /// fails when it ends without pausing. + Future pausedIn(Future generation) => Future.any([ + _next('paused'), + generation.then( + (_) => throw StateError('The generation ended without pausing.'), + ), + ]); + + /// Completes once every call made before this one has arrived. + Future flush() { + final marker = 'flush-${_flushes++}'; + final arrived = _next(marker); + _port.sendPort.send(('signal', marker)); + return arrived; + } + + /// Frees the state. Call after the worker is disposed. + void close() { + _port.close(); + calloc.free(_state); + } + + Future _next(String name) { + if (_arrived.remove(name)) { + return Future.value(); + } + final completer = Completer(); + _waiting.add((name, completer)); + return completer.future.timeout(const Duration(seconds: 15)); + } + + void _received(Object? message) { + final (isolate, name) = message! as (String, String); + if (isolate != 'signal') { + _calls.add((isolate, name)); + return; + } + final waiting = _waiting.indexWhere((entry) => entry.$1 == name); + if (waiting >= 0) { + _waiting.removeAt(waiting).$2.complete(); + } else { + _arrived.add(name); + } + } +} + +final class _FakeCalls { + const _FakeCalls(this._stateAddress, this._log, this._history); + + final int _stateAddress; + final SendPort _log; + final int _history; + + Pointer get _state => Pointer.fromAddress(_stateAddress); + Pointer get _ints => _state.cast(); + Pointer get _latestSequence => + Pointer.fromAddress(_stateAddress + _latest); + + bool get _inWorker => Isolate.current.debugName == _workerIsolateName; + + void _record(String name) => + _log.send((_inWorker ? 'worker' : 'caller', name)); + + /// How the worker isolate holds its context for its own shutdown. + String get _held { + final held = IsolateShutdownReleases.current.debugHeldForTesting; + if (held.isEmpty) { + return ''; + } + final expected = + held.length == 1 && + held.single.free == malloc.nativeFree && + held.single.stage == ShutdownStage.model; + return expected ? '+held' : '+held-wrong'; + } + + void _report(int step, int steps) { + final sequence = _latestSequence.value + 1; + final slot = Pointer.fromAddress( + _stateAddress + _ring + (sequence % _ringSlots) * 8, + ); + slot[0] = step; + slot[1] = steps; + _latestSequence.value = sequence; + } + + StableDiffusionCalls? resolve() { + if (_inWorker && _state[_missingInWorker] != 0) { + return null; + } + return StableDiffusionCalls( + progressEnable: () { + _record('sd_dart_progress_enable'); + _state[_enabled] = 1; + }, + progressRead: _progressRead, + newContext: (params) { + _record( + _state[_enabled] != 0 + ? 'sd_dart_new_sd_ctx' + : 'sd_dart_new_sd_ctx:before-enable', + ); + if (_state[_rejectLoad] != 0) { + return nullptr; + } + final reports = _ints[_loadReports ~/ 4]; + for (var i = 1; i <= reports; i++) { + _report(i, reports); + } + return malloc(16).cast(); + }, + generateImage: _generateImage, + cancelGeneration: (context) { + _record('sd_dart_cancel_generation'); + _state[_cancelled] = 1; + }, + exitFree: (context) { + _record('sd_dart_exit_free$_held'); + malloc.free(context); + }, + exitFreeAddress: malloc.nativeFree, + contextParamsInit: (params) => _record('sd_ctx_params_init'), + supportsImageGeneration: (context) { + _record('sd_ctx_supports_image_generation$_held'); + return _state[_videoOnly] == 0; + }, + modelVersionName: (context) { + _record('sd_get_model_version_name$_held'); + return Pointer.fromAddress(_stateAddress + _modelVersion); + }, + imageGenerationParamsInit: (params) => + _record('sd_img_gen_params_init$_held'), + freeImages: (images, count) { + _record('free_sd_images$_held'); + for (var i = 0; i < count; i++) { + malloc.free(images[i].data); + } + malloc.free(images); + }, + ); + } + + int _progressRead( + int after, + Pointer reports, + int capacity, + Pointer latest, + ) { + if (capacity == 0) { + _record('sd_dart_progress_read:mark'); + } else { + _record('sd_dart_progress_read'); + final racing = _ints[_reportsPerRead ~/ 4]; + if (racing > 0 && _ints[_racingReads ~/ 4]-- > 0) { + for (var i = 1; i <= racing; i++) { + _report(i, racing); + } + } + } + final newest = _latestSequence.value; + if (latest != nullptr) { + latest.value = newest; + } + final oldest = newest - _history + 1; + var sequence = after + 1 > oldest ? after + 1 : oldest; + var count = 0; + while (count < capacity && sequence <= newest) { + final slot = Pointer.fromAddress( + _stateAddress + _ring + (sequence % _ringSlots) * 8, + ); + reports[count] + ..sequence = sequence + ..step = slot[0] + ..steps = slot[1] + ..time = 0; + count++; + sequence++; + } + return count; + } + + void _waitWhile(bool Function() blocked) { + final waited = Stopwatch()..start(); + while (blocked()) { + if (waited.elapsed > const Duration(seconds: 10)) { + throw StateError('The fake generation was never released.'); + } + sleep(const Duration(milliseconds: 1)); + } + } + + bool _generateImage( + Pointer context, + Pointer params, + Pointer> imagesOut, + Pointer countOut, + ) { + _record('sd_dart_generate_image$_held'); + imagesOut.value = nullptr; + countOut.value = 0; + _waitWhile(() => _state[_holdStart] != 0); + _state[_cancelled] = 0; + if (_state[_throwInGenerate] != 0) { + throw _GenerationFailure(this); + } + final steps = params.ref.sample_params.sample_steps; + final images = params.ref.batch_count; + final pauseAfter = _ints[_pauseAfter ~/ 4]; + var reported = 0; + void pauseAt(int count) { + if (count != pauseAfter) { + return; + } + _log.send(('signal', 'paused')); + _waitWhile(() => _state[_resume] == 0); + _state[_resume] = 0; + } + + void report(int step, int total) { + _report(step, total); + pauseAt(++reported); + } + + pauseAt(0); + for (var image = 0; image < images; image++) { + report(0, steps); + for (var step = 1; step <= steps; step++) { + if (_state[_cancelled] != 0) { + return false; + } + report(step, steps); + } + } + if (_state[_cancelled] != 0) { + return false; + } + final tiles = _ints[_decodeReports ~/ 4]; + for (var tile = 1; tile <= tiles; tile++) { + report(tile, tiles); + } + + final width = params.ref.width; + final height = params.ref.height; + final result = malloc(images); + for (var image = 0; image < images; image++) { + final length = width * height * 3; + final data = malloc(length); + data.asTypedList(length).fillRange(0, length, image + 1); + result[image] + ..width = width + ..height = height + ..channel = 3 + ..data = data; + } + imagesOut.value = result; + countOut.value = images; + return true; + } +} + +/// Records how the worker holds its context when the VM reports this error +/// as uncaught, which is after any handler of the worker ran. +final class _GenerationFailure extends Error { + _GenerationFailure(this._calls); + + final _FakeCalls _calls; + + @override + String toString() { + _calls._record('uncaught generation error${_calls._held}'); + return 'The fake generation failed.'; + } +} + +/// The progress timers a worker started, which a test fires by hand. +final class ManualProgressTimers { + /// Intervals of the timers started so far. + final List intervals = []; + + final List<_ManualTimer> _timers = []; + + /// Timers started and not cancelled. + int get active => _timers.where((timer) => timer.isActive).length; + + /// Starts a timer that fires only on [poll]. + Timer start(Duration interval, void Function(Timer timer) poll) { + intervals.add(interval); + final timer = _ManualTimer(poll); + _timers.add(timer); + return timer; + } + + /// Fires the one active timer once. + void poll() { + final timer = _timers.singleWhere((timer) => timer.isActive); + timer._poll(timer); + } +} + +final class _ManualTimer implements Timer { + _ManualTimer(this._poll); + + final void Function(Timer timer) _poll; + + @override + bool isActive = true; + + @override + int get tick => 0; + + @override + void cancel() => isActive = false; +} diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart new file mode 100644 index 000000000..c904821bc --- /dev/null +++ b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart @@ -0,0 +1,209 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:test/test.dart'; + +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_bindings.dart' + as sd; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_calls.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart'; +import 'package:llamadart/src/hook/native_release_pins.dart'; + +// The exports image generation depends on. +const _symbols = [ + 'sd_dart_progress_enable', + 'sd_dart_progress_read', + 'sd_dart_new_sd_ctx', + 'sd_dart_generate_image', + 'sd_dart_cancel_generation', + 'sd_dart_exit_free', +]; + +// The root package does not bundle the stable_diffusion runtime, so these +// tests resolve the functions from stand-ins. That each name resolves to the +// runtime's own export is checked against the real runtime by +// example/basic_app/test/image_exit_teardown_e2e_test.dart. +void main() { + test('binds every sd_dart_ function through the lookup, and resolves ' + 'nothing when one is missing', () { + final requested = []; + Pointer exported(String name) { + requested.add(name); + return Pointer.fromAddress(0x1000 + requested.length); + } + + expect(StableDiffusionCalls.tryResolve(symbol: exported), isNotNull); + expect(requested, unorderedEquals(_symbols)); + expect(StableDiffusionCalls.wrapperSymbols, unorderedEquals(_symbols)); + + for (final missing in _symbols) { + expect( + StableDiffusionCalls.tryResolve( + symbol: (name) => name == missing + ? throw ArgumentError("Couldn't resolve native function '$name'") + : exported(name), + ), + isNull, + reason: missing, + ); + } + }); + + test('calls the function exported under the name of each of its ' + 'members', () { + final exports = _RecordingExports(); + addTearDown(exports.close); + final calls = StableDiffusionCalls.tryResolve(symbol: exports.symbol)!; + + final members = { + 'sd_dart_progress_enable': calls.progressEnable, + 'sd_dart_new_sd_ctx': () => calls.newContext(nullptr), + 'sd_dart_generate_image': () => + calls.generateImage(nullptr, nullptr, nullptr, nullptr), + 'sd_dart_cancel_generation': () => calls.cancelGeneration(nullptr), + 'sd_dart_exit_free': () => calls.exitFree(nullptr), + }; + for (final MapEntry(key: name, value: call) in members.entries) { + exports.called.clear(); + call(); + expect(exports.called, [name]); + } + expect(exports.cancelMode, sd.sd_cancel_mode_t.SD_CANCEL_ALL.value); + expect(calls.exitFreeAddress, exports.symbol('sd_dart_exit_free')); + + // sd_dart_progress_read is a leaf call, which cannot call back into + // Dart, so memcpy stands in for it: called as + // (destination, source, length, ignored) it copies and returns its + // destination. + using((arena) { + final source = arena(4)..asTypedList(4).setAll(0, [9, 8, 7, 6]); + final destination = arena(4); + expect( + calls.progressRead(destination.address, source.cast(), 4, nullptr), + destination.address, + ); + expect(destination.asTypedList(4), [9, 8, 7, 6]); + }); + }); + + test( + 'resolves nothing from a process without the runtime', + () { + expect(StableDiffusionCalls.tryResolve(), isNull); + }, + skip: probeStableDiffusionRuntime().isAvailable + ? 'the stable_diffusion runtime is bundled here' + : false, + ); + + test('the unsupported error names the functions, the release that has them ' + 'and the pinned release', () { + final message = stableDiffusionWrapperUnsupported().message; + + for (final symbol in _symbols) { + expect(message, contains(symbol)); + } + expect(message, contains('stable-diffusion-native v0.2.0-1 or later')); + expect(message, contains('pinned release $stableDiffusionReleaseTag')); + }); + + group('generated bindings', () { + final bindings = File( + 'lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart', + ).readAsStringSync(); + + test('leave out the functions that are not safe from an isolate', () { + for (final name in const [ + 'sd_dart_exit_teardown', + 'sd_dart_exit_call_begin', + 'sd_dart_exit_call_end', + 'sd_dart_exit_track', + 'sd_dart_exit_untrack', + ]) { + expect(bindings, isNot(contains(RegExp('$name\\b'))), reason: name); + } + }); + + test('bind only sd_dart_progress_read as a leaf call', () { + final leaves = RegExp( + r'isLeaf: true\)\s*external \w[\w<>.]* (\w+)\(', + ).allMatches(bindings).map((match) => match.group(1)); + + expect(leaves, ['sd_dart_progress_read']); + expect('isLeaf'.allMatches(bindings), hasLength(1)); + }); + }); +} + +/// A stand-in export for each `sd_dart_` function, which records its name +/// when called. +final class _RecordingExports { + final List called = []; + int? cancelMode; + + late final Map> _functions = { + 'sd_dart_progress_enable': NativeCallable.isolateLocal( + () => _record('sd_dart_progress_enable', null), + ), + 'sd_dart_new_sd_ctx': + NativeCallable< + Pointer Function(Pointer) + >.isolateLocal( + (Pointer _) => + _record('sd_dart_new_sd_ctx', nullptr.cast()), + ), + 'sd_dart_generate_image': + NativeCallable< + Bool Function( + Pointer, + Pointer, + Pointer>, + Pointer, + ) + >.isolateLocal( + ( + Pointer _, + Pointer _, + Pointer> _, + Pointer _, + ) => _record('sd_dart_generate_image', false), + exceptionalReturn: false, + ), + 'sd_dart_cancel_generation': + NativeCallable< + Void Function(Pointer, UnsignedInt) + >.isolateLocal((Pointer _, int mode) { + cancelMode = mode; + _record('sd_dart_cancel_generation', null); + }), + 'sd_dart_exit_free': + NativeCallable)>.isolateLocal( + (Pointer _) => _record('sd_dart_exit_free', null), + ), + }; + + T _record(String name, T result) { + called.add(name); + return result; + } + + Pointer symbol(String name) => name == 'sd_dart_progress_read' + ? _memcpy + : _functions[name]!.nativeFunction; + + void close() { + for (final function in _functions.values) { + function.close(); + } + } +} + +final Pointer _memcpy = + (Platform.isWindows + ? DynamicLibrary.open('msvcrt.dll') + : DynamicLibrary.process()) + .lookup('memcpy'); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart index 8a5793f1a..5469b19d6 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart @@ -1,34 +1,77 @@ @TestOn('vm') library; +import 'dart:async'; + import 'package:test/test.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_calls.dart'; import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_image_worker.dart'; import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart'; import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/generated_image.dart'; import 'package:llamadart/src/core/image/image_generation_driver.dart'; +import 'package:llamadart/src/core/image/image_generation_events.dart'; +import 'package:llamadart/src/core/image/image_generation_progress.dart'; +import 'package:llamadart/src/core/image/image_generation_request.dart'; +import 'package:llamadart/src/core/llama_logger.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; + +import '../../../support/fake_stable_diffusion_runtime.dart'; + +const _config = ImageGenerationSessionConfig( + files: {'model': '/models/sdxs.gguf'}, + backend: null, + threads: 0, +); + +ImageGenerationSessionRequest _request({int steps = 2, int count = 1}) => + ImageGenerationSessionRequest( + prompt: 'a red fox', + negativePrompt: '', + width: 8, + height: 8, + steps: steps, + guidanceScale: 1, + seed: 7, + count: count, + ); + +/// The reports stable-diffusion.cpp makes for [count] images of [steps] +/// steps, then [tiles] tiles of a tiled decode. +List<(int, int)> _upstreamReports({ + required int steps, + required int count, + int tiles = 0, +}) => [ + for (var image = 0; image < count; image++) + for (var step = 0; step <= steps; step++) (step, steps), + for (var tile = 1; tile <= tiles; tile++) (tile, tiles), +]; + +const _loadCalls = [ + 'sd_ctx_params_init', + 'sd_dart_new_sd_ctx', + 'sd_ctx_supports_image_generation+held', + 'sd_get_model_version_name+held', +]; + +const _generateCalls = [ + 'sd_img_gen_params_init+held', + 'sd_dart_generate_image+held', + 'free_sd_images+held', +]; // Real generation needs the opt-in runtime, which the root package does not // bundle; example/basic_app/test/image_generation_e2e_test.dart covers it. +// The tests below run the worker's two isolates on a recording stand-in. void main() { test( 'a worker whose runtime is missing fails its start and exits', () async { await expectLater( - StableDiffusionImageWorker.start( - const ImageGenerationSessionConfig( - files: {'model': '/models/sdxs.gguf'}, - backend: null, - threads: 0, - ), - ), - throwsA( - isA().having( - (error) => '${error.details}', - 'details', - contains('stable_diffusion'), - ), - ), + StableDiffusionImageWorker.start(_config), + throwsA(isA()), ); }, skip: probeStableDiffusionRuntime().isAvailable @@ -36,6 +79,481 @@ void main() { : false, ); + group('on a recording runtime', () { + late FakeStableDiffusionRuntime runtime; + late ManualProgressTimers timers; + final workers = []; + + Future start() async { + final worker = await StableDiffusionImageWorker.start( + _config, + resolveCalls: runtime.resolver, + progressTimer: timers.start, + ); + workers.add(worker); + return worker; + } + + /// A started worker, with the calls of its load forgotten. + Future loaded() async { + final worker = await start(); + await runtime.flush(); + runtime.clearCalls(); + return worker; + } + + setUp(() { + runtime = FakeStableDiffusionRuntime(); + timers = ManualProgressTimers(); + }); + + tearDown(() async { + for (final worker in workers) { + await worker.dispose(); + } + workers.clear(); + runtime.close(); + }); + + test('a load enables the recorder before the worker creates its tracked ' + 'context, and holds the context for its exit-free', () async { + final worker = await start(); + await runtime.flush(); + + expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('worker'), _loadCalls); + expect(worker.modelVersion, 'SD 2.x'); + }); + + test('a generation marks its start, reads the reports after the reply ' + 'and stops its timer', () async { + runtime.loadReports = 3; + final worker = await loaded(); + final progress = <(int, int)>[]; + + final images = await worker.generate( + _request(), + (step, steps) => progress.add((step, steps)), + ); + await runtime.flush(); + + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + ]); + expect(runtime.calls('worker'), _generateCalls); + expect(progress, [(0, 2), (1, 2), (2, 2)]); + expect(timers.intervals, [const Duration(milliseconds: 50)]); + expect(timers.active, 0); + final GeneratedImage image = images!.single; + expect((image.width, image.height, image.channels), (8, 8, 3)); + expect(image.pixels, List.filled(8 * 8 * 3, 1)); + }); + + test('a poll during a generation delivers the reports so far, and the ' + 'events of a batch of three match the unpolled stream', () async { + final worker = await loaded(); + runtime.pauseAfter = 7; + const steps = 4; + const count = 3; + final tracker = ImageGenerationProgressTracker( + steps: steps, + imageCount: count, + ); + final events = []; + final generation = worker.generate( + _request(steps: steps, count: count), + (step, total) => + events.addAll(tracker.onNativeProgress(step, total).map(_describe)), + ); + await runtime.pausedIn(generation); + + expect(events, isEmpty); + timers.poll(); + expect(events, [ + 'sampling 0/4 image 0/3', + 'sampling 1/4 image 0/3', + 'sampling 2/4 image 0/3', + 'sampling 3/4 image 0/3', + 'sampling 4/4 image 0/3', + 'sampling 0/4 image 1/3', + 'sampling 1/4 image 1/3', + ]); + runtime.resume(); + final images = await generation; + await runtime.flush(); + + final reference = ImageGenerationProgressTracker( + steps: steps, + imageCount: count, + ); + expect(events, [ + for (final (step, total) in _upstreamReports( + steps: steps, + count: count, + )) + ...reference.onNativeProgress(step, total).map(_describe), + ]); + expect(events, hasLength(16)); + expect(events.last, 'decoding 0/3 image 2/3'); + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + 'sd_dart_progress_read', + ]); + expect([for (final image in images!) image.pixels.first], [1, 2, 3]); + }); + + test('a second generation reads only its own reports', () async { + final worker = await loaded(); + final first = <(int, int)>[]; + final second = <(int, int)>[]; + + await worker.generate(_request(steps: 3), (a, b) => first.add((a, b))); + await worker.generate( + _request(steps: 1, count: 2), + (a, b) => second.add((a, b)), + ); + + expect(first, _upstreamReports(steps: 3, count: 1)); + expect(second, _upstreamReports(steps: 1, count: 2)); + }); + + test('reads until it holds the newest report when there are more than ' + 'one read returns', () async { + final worker = await loaded(); + runtime.decodeReports = 200; + final progress = <(int, int)>[]; + + await worker.generate( + _request(steps: 4, count: 3), + (step, steps) => progress.add((step, steps)), + ); + await runtime.flush(); + + expect(progress, _upstreamReports(steps: 4, count: 3, tiles: 200)); + // 215 reports, 64 a read. + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + for (var read = 0; read < 4; read++) 'sd_dart_progress_read', + ]); + }); + + test('one poll stops after 64 reads of a runtime that reports faster ' + 'than it is read', () async { + final worker = await loaded(); + runtime.pauseAfter = 0; + var delivered = 0; + final generation = worker.generate(_request(), (_, _) => delivered++); + await runtime.pausedIn(generation); + runtime.reportsPerRead = 100; + + timers.poll(); + await runtime.flush(); + + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + for (var read = 0; read < 64; read++) 'sd_dart_progress_read', + ]); + expect(delivered, 64 * 64); + runtime.reportsPerRead = 0; + runtime.resume(); + await generation; + }); + + test('delivers the reports the runtime still has, in order, when it ' + 'dropped older ones, and warns once', () async { + runtime.close(); + runtime = FakeStableDiffusionRuntime(history: 8); + final warnings = []; + final logger = LlamaLogger.instance; + final level = logger.level; + logger + ..setLevel(LlamaLogLevel.warn) + ..setHandler((record) => warnings.add(record.message)); + addTearDown(() { + logger + ..setLevel(level) + ..setHandler(null); + }); + final worker = await loaded(); + runtime.pauseAfter = 3; + final progress = <(int, int)>[]; + final generation = worker.generate( + _request(steps: 9, count: 2), + (step, steps) => progress.add((step, steps)), + ); + await runtime.pausedIn(generation); + timers.poll(); + expect(progress, [(0, 9), (1, 9), (2, 9)]); + + runtime.resume(); + await generation; + + // 20 reports; the 17 after the poll leave the newest 8. + final all = _upstreamReports(steps: 9, count: 2); + expect(progress, [...all.take(3), ...all.skip(12)]); + expect(warnings, hasLength(1)); + expect(warnings.single, contains('dropped 9 image-generation')); + + warnings.clear(); + progress.clear(); + runtime.pauseAfter = -1; + await worker.generate( + _request(steps: 2), + (step, steps) => progress.add((step, steps)), + ); + expect(progress, _upstreamReports(steps: 2, count: 1)); + expect(warnings, isEmpty); + }); + + test('the largest request cannot record more reports than the runtime ' + 'keeps', () { + expect( + ImageGenerationRequest.maxCount * (ImageGenerationRequest.maxSteps + 1), + lessThanOrEqualTo(StableDiffusionCalls.progressHistory), + ); + }); + + test('a cancel that the starting generation cleared is applied again by ' + 'the next poll', () async { + final worker = await loaded(); + runtime + ..holdStart = true + ..pauseAfter = 0; + final progress = <(int, int)>[]; + final generation = worker.generate( + _request(steps: 4), + (step, steps) => progress.add((step, steps)), + ); + worker.cancel(); + expect(runtime.cancelPending, isTrue); + runtime.holdStart = false; + await runtime.pausedIn(generation); + expect(runtime.cancelPending, isFalse); + + timers.poll(); + expect(runtime.cancelPending, isTrue); + runtime.resume(); + + expect(await generation, isNull); + await runtime.flush(); + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + 'sd_dart_cancel_generation', + 'sd_dart_cancel_generation', + 'sd_dart_progress_read', + 'sd_dart_progress_read', + ]); + expect(runtime.calls('worker'), [ + 'sd_img_gen_params_init+held', + 'sd_dart_generate_image+held', + ]); + expect(progress, [(0, 4)]); + }); + + test('a cancel during a generation stops it before the next step, and ' + 'the next generation is not cancelled', () async { + final worker = await loaded(); + runtime.pauseAfter = 2; + final progress = <(int, int)>[]; + final generation = worker.generate( + _request(steps: 4), + (step, steps) => progress.add((step, steps)), + ); + await runtime.pausedIn(generation); + timers.poll(); + worker.cancel(); + runtime.resume(); + + expect(await generation, isNull); + await runtime.flush(); + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + 'sd_dart_cancel_generation', + 'sd_dart_progress_read', + ]); + expect(progress, [(0, 4), (1, 4)]); + + runtime.clearCalls(); + runtime.pauseAfter = 1; + final next = worker.generate(_request(), (_, _) {}); + await runtime.pausedIn(next); + timers.poll(); + runtime.resume(); + expect(await next, hasLength(1)); + await runtime.flush(); + expect(runtime.calls('caller'), [ + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + 'sd_dart_progress_read', + ]); + }); + + test('a cancel with no generation running is not applied to the next ' + 'one', () async { + final worker = await loaded(); + worker.cancel(); + runtime.pauseAfter = 0; + final generation = worker.generate(_request(), (_, _) {}); + await runtime.pausedIn(generation); + timers.poll(); + runtime.resume(); + + expect(await generation, hasLength(1)); + await runtime.flush(); + expect(runtime.calls('caller'), [ + 'sd_dart_cancel_generation', + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + 'sd_dart_progress_read', + ]); + }); + + test( + 'the default timer delivers progress while the generation runs', + () async { + final worker = await StableDiffusionImageWorker.start( + _config, + resolveCalls: runtime.resolver, + ); + workers.add(worker); + runtime.pauseAfter = 2; + final progress = <(int, int)>[]; + final polled = Completer(); + final generation = worker.generate(_request(steps: 4), (step, steps) { + progress.add((step, steps)); + if (progress.length == 2) polled.complete(); + }); + await runtime.pausedIn(generation); + + await polled.future.timeout(const Duration(seconds: 10)); + expect(progress, [(0, 4), (1, 4)]); + runtime.resume(); + await generation; + expect(progress, _upstreamReports(steps: 4, count: 1)); + }, + ); + + test('dispose frees the context through the exit-free after releasing ' + 'its hold, and a later cancel calls nothing', () async { + final worker = await loaded(); + + await worker.dispose(); + worker.cancel(); + await runtime.flush(); + + expect(runtime.calls('worker'), ['sd_dart_exit_free']); + expect(runtime.calls('caller'), isEmpty); + }); + + test('a failed load creates nothing to free', () async { + runtime.rejectLoad = true; + + await expectLater(start(), throwsA(isA())); + await runtime.flush(); + + expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('worker'), [ + 'sd_ctx_params_init', + 'sd_dart_new_sd_ctx', + ]); + }); + + test('a model that cannot generate images is freed through the ' + 'exit-free', () async { + runtime.videoOnly = true; + + await expectLater( + start(), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('does not support image generation'), + ), + ), + ); + await runtime.flush(); + + expect(runtime.calls('worker'), [ + 'sd_ctx_params_init', + 'sd_dart_new_sd_ctx', + 'sd_ctx_supports_image_generation+held', + 'sd_dart_exit_free', + ]); + }); + + test('a runtime without the sd_dart_ functions is unsupported, and ' + 'nothing is called on it', () async { + await expectLater( + StableDiffusionImageWorker.start(_config, resolveCalls: () => null), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('sd_dart_progress_read'), + contains('sd_dart_new_sd_ctx'), + contains('stable-diffusion-native v0.2.0-1 or later'), + ), + ), + ), + ); + + runtime.missingInWorker = true; + await expectLater(start(), throwsA(isA())); + await runtime.flush(); + expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('worker'), isEmpty); + }); + + test('a generation that fails leaves its context held, so the worker\'s ' + 'shutdown frees it through the exit-free', () async { + final worker = await loaded(); + runtime.throwInGenerate = true; + + await expectLater( + worker.generate(_request(), (_, _) {}), + throwsA(isA()), + ); + await runtime.flush(); + + expect(runtime.calls('worker'), [ + 'sd_img_gen_params_init+held', + 'sd_dart_generate_image+held', + 'uncaught generation error+held', + ]); + }); + + test('a worker that dies in a generation fails it, stops its timer and ' + 'stays safe to dispose, and a later cancel calls nothing', () async { + final worker = await loaded(); + runtime.throwInGenerate = true; + + await expectLater( + worker.generate(_request(), (_, _) {}), + throwsA(isA()), + ); + expect(timers.active, 0); + await expectLater( + worker.generate(_request(), (_, _) {}), + throwsA(isA()), + ); + worker.cancel(); + await worker.dispose(); + await runtime.flush(); + + expect(runtime.calls('worker'), [ + 'sd_img_gen_params_init+held', + 'sd_dart_generate_image+held', + 'uncaught generation error+held', + ]); + expect(runtime.calls('caller'), ['sd_dart_progress_read:mark']); + }); + }); + group('stableDiffusionModelLoadFailure', () { test('names a missing VAE when a diffusionModel has none', () { final error = stableDiffusionModelLoadFailure({ @@ -103,3 +621,7 @@ void main() { }); }); } + +String _describe(ImageGenerationProgressEvent event) => + '${event.phase.name} ${event.step}/${event.steps} ' + 'image ${event.imageIndex}/${event.imageCount}'; diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart index a922ae0da..26df527c1 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_io_test.dart @@ -27,6 +27,25 @@ void main() { expect(status.devices.map((device) => device.name), ['CPU', 'MTL0']); }); + test('a runtime without the sd_dart_ functions is unavailable, and the ' + 'reason names them and the release that has them', () { + final status = probeStableDiffusionRuntime( + abi: Abi.macosArm64, + api: _FakeApi(wrapperCalls: false), + ); + + expect(status.isAvailable, isFalse); + expect( + status.unavailableReason?.message, + allOf( + contains('does not export the sd_dart_ functions'), + contains('sd_dart_progress_read'), + contains('sd_dart_exit_free'), + contains('stable-diffusion-native v0.2.0-1 or later'), + ), + ); + }); + test('rejects an unpublished ABI before touching the library', () { for (final abi in [Abi.androidX64, Abi.windowsArm64, Abi.linuxArm]) { final api = _FakeApi(); @@ -445,10 +464,15 @@ void main() { } final class _FakeApi implements StableDiffusionNativeApi { - _FakeApi({this.devices = 'CPU\tHost CPU\n', this.error}); + _FakeApi({ + this.devices = 'CPU\tHost CPU\n', + this.error, + this.wrapperCalls = true, + }); final String devices; final ArgumentError? error; + final bool wrapperCalls; int calls = 0; T _call(T value) { @@ -468,4 +492,7 @@ final class _FakeApi implements StableDiffusionNativeApi { @override String listDevices() => _call(devices); + + @override + bool exportsWrapperCalls() => _call(wrapperCalls); } diff --git a/test/unit/hook/native_release_pins_test.dart b/test/unit/hook/native_release_pins_test.dart index 1c40c4af3..a202b6f6a 100644 --- a/test/unit/hook/native_release_pins_test.dart +++ b/test/unit/hook/native_release_pins_test.dart @@ -94,7 +94,10 @@ void main() { }); test('stable_diffusion cache version is the release tag without its v', () { - expect(stableDiffusionReleaseTag, matches(RegExp(r'^v\d+\.\d+\.\d+$'))); + expect( + stableDiffusionReleaseTag, + matches(RegExp(r'^v\d+\.\d+\.\d+(?:-[1-9]\d*)?$')), + ); expect(stableDiffusionVersion, stableDiffusionReleaseTag.substring(1)); }); diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 8199bef96..781e562f8 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -856,6 +856,33 @@ void main() { ); }); + test('dry-runs the image exit teardown in the opted-in example, and ' + 'requires its model', () async { + final missing = await runLocalE2e(const [ + '--scenario', + 'image-exit-teardown', + '--dry-run', + ], projectRoot: '/repo'); + expect(missing.exitCode, 64); + + final result = await runLocalE2e(const [ + '--scenario', + 'image-exit-teardown', + '--model-path', + '/sdxs.gguf', + '--dry-run', + ], projectRoot: '/repo'); + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + 'cd /repo/example/basic_app && IMAGE_EXIT_MODEL=/sdxs.gguf ' + 'dart test --run-skipped -t local-only ' + 'test/image_exit_teardown_e2e_test.dart', + ), + ); + }); + test('requires an SDXS model for image generation', () async { final result = await runLocalE2e(const [ '--scenario', diff --git a/test/unit/tooling/test_matrix_test.dart b/test/unit/tooling/test_matrix_test.dart index 6fc81a190..b5440945b 100644 --- a/test/unit/tooling/test_matrix_test.dart +++ b/test/unit/tooling/test_matrix_test.dart @@ -57,6 +57,7 @@ void main() { expect(ids, contains('physical-ios-speech-e2e')); expect(ids, contains('decision-model-smoke')); expect(ids, contains('image-generation-smoke')); + expect(ids, contains('image-exit-teardown')); expect(ids, contains('chat-app-image-generation-smoke')); }); @@ -94,6 +95,7 @@ void main() { } expect(referenced, contains('decision-model-smoke')); expect(referenced, contains('image-generation-smoke')); + expect(referenced, contains('image-exit-teardown')); }); test('speech-to-text rows take WAV, MP3 or FLAC fixtures', () { diff --git a/tool/native/sync_stable_diffusion_bindings.py b/tool/native/sync_stable_diffusion_bindings.py index 832b22b09..3aae7b724 100644 --- a/tool/native/sync_stable_diffusion_bindings.py +++ b/tool/native/sync_stable_diffusion_bindings.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 -"""Stage the pinned stable-diffusion.h and regenerate its Dart FFI bindings. +"""Stage the pinned stable-diffusion-native headers and regenerate their Dart +FFI bindings. -stable-diffusion-native ships its header inside every runtime archive, so the -header comes from the archive pinned in lib/src/hook/native_release_pins.dart, +stable-diffusion-native ships its headers inside every runtime archive, so +they come from the archive pinned in lib/src/hook/native_release_pins.dart, after its SHA-256 matches that pin. """ @@ -28,7 +29,10 @@ DEFAULT_FFIGEN_CONFIG = "ffigen_stable_diffusion.yaml" DEFAULT_BUNDLE = "linux-x64" RELEASE_BASE_URL = "https://github.com/leehack/stable-diffusion-native/releases/download" -HEADER_MEMBER = PurePosixPath("include/stable-diffusion.h") +HEADER_MEMBERS = ( + PurePosixPath("include/stable-diffusion.h"), + PurePosixPath("include/sd_dart_wrapper.h"), +) DOWNLOAD_TIMEOUT_SECONDS = 300 @@ -78,37 +82,41 @@ def sha256_file(path: Path) -> str: return digest.hexdigest() -def read_header(archive_path: Path) -> bytes: - """Return stable-diffusion.h from a validated runtime archive.""" +def read_headers(archive_path: Path) -> dict[PurePosixPath, bytes]: + """Return every HEADER_MEMBERS file from a validated runtime archive.""" try: with tarfile.open(archive_path, "r:gz") as archive: members = validate_members(archive.getmembers()) - matches = [ - member - for member, relative in members - if relative == HEADER_MEMBER and member.isfile() - ] - if len(matches) != 1: - raise SyncError(f"{archive_path.name} has no {HEADER_MEMBER}") - source = archive.extractfile(matches[0]) - if source is None: - raise SyncError(f"{archive_path.name} {HEADER_MEMBER} is unreadable") - with source: - return source.read() + headers = {} + for header in HEADER_MEMBERS: + matches = [ + member + for member, relative in members + if relative == header and member.isfile() + ] + if len(matches) != 1: + raise SyncError(f"{archive_path.name} has no {header}") + source = archive.extractfile(matches[0]) + if source is None: + raise SyncError(f"{archive_path.name} {header} is unreadable") + with source: + headers[header] = source.read() + return headers except (tarfile.TarError, OSError, EOFError) as error: raise SyncError(f"{archive_path.name} could not be read: {error}") from error -def publish_header(header: bytes, header_root: Path) -> None: - """Replace [header_root] with one holding include/stable-diffusion.h.""" +def publish_headers(headers: dict[PurePosixPath, bytes], header_root: Path) -> None: + """Replace [header_root] with one holding [headers].""" header_root.parent.mkdir(parents=True, exist_ok=True) staging = Path( tempfile.mkdtemp(prefix=f".{header_root.name}.", dir=header_root.parent) ) try: - target = staging / HEADER_MEMBER - target.parent.mkdir(parents=True) - target.write_bytes(header) + for member, content in headers.items(): + target = staging / member + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) if header_root.exists() or header_root.is_symlink(): if header_root.is_symlink() or not header_root.is_dir(): raise SyncError(f"Refusing to replace non-directory {header_root}") @@ -135,10 +143,11 @@ def main() -> int: f"{name} SHA-256 {actual_sha256} does not match the pinned " f"{expected_sha256}" ) - header = read_header(archive) + headers = read_headers(archive) header_root = repo_root / args.header_root - publish_header(header, header_root) - print(f"Staged {HEADER_MEMBER} from {name} in {header_root}") + publish_headers(headers, header_root) + staged = ", ".join(str(member) for member in HEADER_MEMBERS) + print(f"Staged {staged} from {name} in {header_root}") if not args.skip_ffigen: result = subprocess.run( @@ -157,7 +166,7 @@ def parse_args() -> argparse.Namespace: parser.add_argument( "--bundle", default=DEFAULT_BUNDLE, - help="Pinned runtime archive to take the header from.", + help="Pinned runtime archive to take the headers from.", ) parser.add_argument( "--archive", diff --git a/tool/native/test_sync_stable_diffusion_bindings.py b/tool/native/test_sync_stable_diffusion_bindings.py index 8c32de416..d51d2e65a 100644 --- a/tool/native/test_sync_stable_diffusion_bindings.py +++ b/tool/native/test_sync_stable_diffusion_bindings.py @@ -15,6 +15,7 @@ SCRIPT = Path(__file__).resolve().parent / "sync_stable_diffusion_bindings.py" REPO_ROOT = Path(__file__).resolve().parents[2] HEADER = b"// stable-diffusion.h\nint sd_version(void);\n" +WRAPPER_HEADER = b'#include "stable-diffusion.h"\nvoid sd_dart_progress_enable(void);\n' def write_archive(path: Path, members: dict[str, bytes | str]) -> None: @@ -94,22 +95,24 @@ def run_sync(self, members: dict[str, bytes | str], *, pin: str | None = None): check=False, ) - def staged_header(self) -> bytes: - return (self.header_root / "include" / "stable-diffusion.h").read_bytes() + def staged_header(self, name: str = "stable-diffusion.h") -> bytes: + return (self.header_root / "include" / name).read_bytes() - def test_stages_the_header_from_a_pinned_archive(self) -> None: + def test_stages_both_headers_from_a_pinned_archive(self) -> None: result = self.run_sync( { "./include/stable-diffusion.h": HEADER, + "./include/sd_dart_wrapper.h": WRAPPER_HEADER, "lib/libstable-diffusion.so": b"\x7fELF", "LICENSE": b"MIT", } ) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(self.staged_header(), HEADER) + self.assertEqual(self.staged_header("sd_dart_wrapper.h"), WRAPPER_HEADER) self.assertEqual( sorted(p.name for p in self.header_root.rglob("*") if p.is_file()), - ["stable-diffusion.h"], + ["sd_dart_wrapper.h", "stable-diffusion.h"], ) self.assertEqual( [p.name for p in self.root.iterdir() if p.name.startswith(".headers")], @@ -118,7 +121,11 @@ def test_stages_the_header_from_a_pinned_archive(self) -> None: def test_checksum_mismatch_leaves_the_header_root_unchanged(self) -> None: result = self.run_sync( - {"include/stable-diffusion.h": HEADER}, pin="0" * 64 + { + "include/stable-diffusion.h": HEADER, + "include/sd_dart_wrapper.h": WRAPPER_HEADER, + }, + pin="0" * 64, ) self.assertEqual(result.returncode, 1) self.assertIn("does not match the pinned", result.stderr) @@ -129,6 +136,10 @@ def test_rejects_link_entries_and_missing_headers(self) -> None: ({"include/stable-diffusion.h": "../../etc/passwd"}, "link entry"), ({"../include/stable-diffusion.h": HEADER}, "escapes"), ({"lib/libstable-diffusion.so": b"\x7fELF"}, "has no"), + ( + {"include/stable-diffusion.h": HEADER}, + "has no include/sd_dart_wrapper.h", + ), ): with self.subTest(message=message): result = self.run_sync(members) diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index fdf5e247f..4dc9397e9 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -649,6 +649,30 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'image-exit-teardown', + group: LocalE2eScenarioGroup.dartLocalOnly, + description: + 'End macOS processes with an image model alive on Metal and ' + 'require a clean exit; also compare the progress events of image ' + 'batches.', + requiresDevice: false, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: '${context.projectRoot}/example/basic_app', + executable: 'dart', + arguments: const [ + 'test', + '--run-skipped', + '-t', + 'local-only', + 'test/image_exit_teardown_e2e_test.dart', + ], + environment: {'IMAGE_EXIT_MODEL': context.modelPath!}, + description: 'Image model exit teardown', + ), + ], + ), LocalE2eScenario( name: 'decision-model-smoke', group: LocalE2eScenarioGroup.dartLocalOnly, @@ -1588,6 +1612,7 @@ Future runLocalE2e( scenario.name == 'litert-lm-chat-features-smoke' || scenario.name == 'native-prompt-cancel' || scenario.name == 'native-exit-teardown' || + scenario.name == 'image-exit-teardown' || scenario.name == 'gemma4-mtp-smoke' || scenario.name == 'native-embedding-benchmark' || scenario.name == 'native-embedding-sweep') && @@ -1866,6 +1891,10 @@ Direct environment for test/e2e/backends/llama_cpp_exit_teardown_e2e_test.dart: quit-decision. EXIT_TEARDOWN_DECISION_HEAD Decision head safetensors for that encoder. +Direct environment for example/basic_app/test/image_exit_teardown_e2e_test.dart: + IMAGE_EXIT_RUNS Runs of each exit scenario (default: 3). + IMAGE_EXIT_GGUF GGUF chat model; unset skips quit-both-loaded. + Direct environment for tool/litert_lm_chat_features_smoke.dart: LITERT_LM_IMAGE_PATH Optional local image fixture. LITERT_LM_AUDIO_PATH Optional local encoded audio fixture. diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index a63d43983..28761d4e9 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -474,6 +474,25 @@ const List testMatrixRows = [ 'Image generation API, stable_diffusion runtime pins, bindings, ' 'probe or hook changes.', ), + TestMatrixRow( + id: 'image-exit-teardown', + tier: 'targeted', + mode: 'local-only', + covers: + 'macOS Metal process ends with an image model alive: C exit through ' + 'FFI with the model idle, generating, loading, disposed and ' + 'optionally with a llama.cpp model loaded too, an unhandled error ' + 'while generating or loading, and an isolate killed inside a load; ' + 'the exports the sd_dart_ calls resolve to; and the progress events ' + 'of batches of two and three images; not a Flutter quit', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'image-exit-teardown --model-path ', + useWhen: + 'stable_diffusion runtime pin, image worker call sites, progress ' + 'polling, or isolate shutdown changes. Needs a Mac whose GPU loads ' + 'the model.', + ), TestMatrixRow( id: 'decision-model-smoke', tier: 'targeted', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 4e6c0fad1..1ca1f0171 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -16,12 +16,26 @@ For canonical full release notes, use: heads still allocated at exit ([#813](https://github.com/leehack/llamadart/issues/813), [llamadart-native#96](https://github.com/leehack/llamadart-native/issues/96)). - Image models, and a native host's C `exit()` while llamadart is working, - are not covered. + A native host's C `exit()` while a llama.cpp call is running is not covered. - Update the default llama.cpp runtime to `leehack/llamadart-native@v0.5.0-2`, a rebuild of llama.cpp `v0.5.0` whose Apple XCFramework carries a privacy manifest (File Timestamp, reason `C617.1`). A runtime older than `v0.5.0-1` keeps the previous exit behavior and logs a warning at the first model load. +- Fix a process aborting when a Dart program dies of an error, or a Flutter + macOS app quits or hot restarts, while an image model loads or generates, + and a macOS Metal process aborting in ggml-metal when a native host exits + with an image model loaded: the stable_diffusion runtime now records + progress instead of calling back into Dart, and frees the image models + still allocated at exit + ([stable-diffusion-native#10](https://github.com/leehack/stable-diffusion-native/issues/10)). + Image progress events now arrive up to about 50 ms after the runtime + reports them. A quit during an image generation waits for the generation + to finish; dispose the engine first to quit at once. +- Update the stable_diffusion runtime to + `leehack/stable-diffusion-native@v0.2.0-1`, a rebuild of the same + stable-diffusion.cpp commit whose Apple XCFramework carries a privacy + manifest (File Timestamp, reasons `C617.1` and `3B52.1`). Image generation + needs this runtime or a later one. - Documented that LiteRT-LM on iOS has run on a device only on iOS 18.3.2; iOS 16.4 remains the declared, untested deployment floor ([#831](https://github.com/leehack/llamadart/issues/831)). diff --git a/website/docs/getting-started/installation.md b/website/docs/getting-started/installation.md index a58ce7ab3..3d1af86ca 100644 --- a/website/docs/getting-started/installation.md +++ b/website/docs/getting-started/installation.md @@ -75,7 +75,8 @@ the build warning about it. An app bound for the App Store should use the companion for each runtime it ships, because an Apple privacy manifest reaches an app inside a companion's XCFramework and never through the hook path. The llama.cpp XCFramework has one -from `llamadart-native` `v0.5.0-1`; the pinned stable_diffusion one has none. +from `llamadart-native` `v0.5.0-1`, and the stable_diffusion one from +`stable-diffusion-native` `v0.2.0-1`. An app that runs llama.cpp or stable_diffusion on the hook path, or whose embedded `llama.framework` or `stable_diffusion.framework` has no `PrivacyInfo.xcprivacy`, declares the runtime's required-reason API use in its diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index df20f4adf..ce232e60c 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -102,11 +102,12 @@ rejects the iOS upload. The iOS build reports this as an Xcode build warning, which Xcode and `xcodebuild` show but plain `flutter build` and `flutter run` output does not. See [Flutter Apple apps](../platforms/native-build-hooks#flutter-apple-apps). -The hook-bundled runtime also cannot carry an Apple privacy manifest, and a -companion framework built before the manifest was added has none either; see +The hook-bundled runtime also cannot carry an Apple privacy manifest. The +companion's XCFramework carries one from `stable-diffusion-native` `v0.2.0-1`, +which `llamadart_stable_diffusion_flutter` releases after `0.0.1` link; see [Apple privacy manifest](../platforms/native-build-hooks#apple-privacy-manifest) -for the File Timestamp reasons (`C617.1`, `3B52.1`) the app then declares -itself. +for the File Timestamp reasons (`C617.1`, `3B52.1`) an app declares itself +when its `stable_diffusion.framework` has no manifest. ## Get a model @@ -608,8 +609,8 @@ probes the same way and does not block the caller either. ## Progress phases -The runtime reports all progress through one `(step, steps)` callback, so the -engine labels it from the call sequence: +The runtime reports all progress as `(step, steps)` pairs with no phase, so +the engine labels each report from the sequence: 1. `encodingPrompt` when the generation starts. 2. `sampling` with `0/steps` when each image's first step starts, then one @@ -620,17 +621,23 @@ engine labels it from the call sequence: `loading` appears only if the runtime loads weights lazily, which the engine avoids by loading them eagerly. +The runtime records its reports and the engine reads them every 50 ms, so +progress events arrive in groups, up to about 50 ms after the runtime made +the report. Every report still becomes its events, in order, and the last +ones arrive before the final event. A calling isolate that is busy delays +them further. + ## Cancellation, concurrency and disposal - `task.cancel()` stops before the next sampling step or before decoding; `task.done` then reports `cancelled` and `task.result` throws `LlamaStateException`. A cancel issued before the runtime starts is honored - too. -- stable-diffusion.cpp reports progress through one process-wide callback, so - one generation or model load runs at a time. Another `generate` or `load` - meanwhile throws `LlamaStateException`, even on a different engine. The guard - covers engines in one isolate; do not generate from several isolates at - once. + too, up to 50 ms after it starts. +- stable-diffusion.cpp reports progress for the whole process, not per + model, so one generation or model load runs at a time. Another `generate` + or `load` meanwhile throws `LlamaStateException`, even on a different + engine. The guard covers engines in one isolate; do not generate from + several isolates at once, or each sees the other's progress. - `dispose()` cancels a running generation, waits for it, and frees the model. The task reports `cancelled`, and its `result` and `generateImage` throw `LlamaStateException`, as does `generate` after `dispose()`. @@ -639,12 +646,20 @@ avoids by loading them eagerly. then reports the engine as unsupported. `capabilities` never throws and changes only on `dispose()`, so a Flutter app can read it once after `load` and keep it in its state for `build`. -- Free the model before a Flutter app quits: on macOS Metal, quitting with a - model still loaded aborts the process. A Dart program that ends with the - model loaded frees it on the way out and does not abort, unless it dies of - an error while the model loads or generates (see - [Model lifecycle](./model-lifecycle)); a Flutter app's quit skips that - cleanup. Flutter desktop apps do not run +- A process that ends with an image model loaded, loading or generating no + longer aborts on macOS Metal in the cases llamadart has run: a Dart program + that returns from `main` or dies of an error, a Flutter macOS quit, and a + native host's C `exit()` (see [Model lifecycle](./model-lifecycle) for what + each one waits for). Nothing cancels a running generation when a Dart + program ends or dies of an error, or a Flutter app quits or hot restarts, + so the process stays, and a hot restart waits, until the generation + finishes. The wait is the rest of the generation, with no upper bound: for + example 4.8 s for the rest of a 40-step SDXS generation and 11.2 s for + SD-Turbo in a Flutter macOS quit on an M4 Max. A native host's C `exit()` + cancels the generation and waits up to 15 seconds for it. +- Still dispose the engine before a Flutter app quits, so the quit does not + wait for a generation and does not depend on the cleanup at exit. Flutter + desktop apps do not run `State.dispose` on quit, so await `dispose()` in `AppLifecycleListener.onExitRequested`. If `ImageGenerationEngine.load` is still running, await it there and dispose the engine it returns. If the diff --git a/website/docs/guides/model-lifecycle.md b/website/docs/guides/model-lifecycle.md index 929cecd41..11d2d2ae4 100644 --- a/website/docs/guides/model-lifecycle.md +++ b/website/docs/guides/model-lifecycle.md @@ -79,28 +79,41 @@ isolate is still working: an exit during a call the runtime does not guard (tokenizing, detokenizing, reading metadata, building a sampler, decoding an image or audio file) can crash, and an exit during a guarded call that runs longer than two seconds (an image or audio evaluation, a long batch) aborts -as before. Image models are not covered at all: stable-diffusion.cpp has no -such teardown. +as before. + +The stable_diffusion runtime (`stable-diffusion-native` `v0.2.0-1` and later) +does the same for image models, and no longer calls back into Dart to report +progress. That covers: + +- a Dart program that dies of an unhandled error while an image model loads + or generates, which used to abort the VM with + `GetFfiCallbackMetadata called after shutdown`; +- a Flutter macOS quit while an image model loads or generates, and a hot + restart during a load, which also used to abort in the progress callback; +- a native host's C `exit()` while an image model is loaded, loading or + generating. The runtime then cancels the generation and waits for the load + or the generation up to 15 seconds: stable-diffusion.cpp stops only before + a sampling step or before decoding an image, and cannot interrupt a load. + A phase that takes longer than that is not freed, and ggml-metal aborts as + before. With a llama.cpp call running too, the exit can take about 17.5 + seconds. - A Dart program that returns from `main` or dies of an unhandled error does not need to dispose first: llamadart frees what its engines still hold as - the program ends, after any native call still running finishes. The exit - can still abort when the program dies of an error: - - while an image model is being created: the VM stops the worker as soon - as that native call returns, before llamadart can track the new object; - - while an image model loads or generates: stable-diffusion.cpp reports - progress through a Dart callback, which the shutting-down VM rejects; - - rarely, while `dispose()` is freeing an image model, which can leave it - unfreed. + the program ends, after any native call still running finishes. Nothing + cancels a running image generation on that path, so the process ends only + when the generation does: about 5 s for the rest of a 40-step SDXS + generation and 11.5 s for SD-Turbo on an M4 Max. Cancel the task or + dispose the engine first to end sooner. `exit()` from `dart:io` skips C++ static destructors and never aborts. - A Flutter app that quits through AppKit (Cmd-Q, closing its last window, or `ServicesBinding.exitApplication`) is not guaranteed to run llamadart's - Dart-side cleanup, and the runtime's exit teardown never frees an image - model, so still dispose every engine, including `DecisionEngine` and - `ImageGenerationEngine`, before the app quits. Desktop Flutter apps do not - run `State.dispose` on quit, so dispose from an exit request instead - (`AppExitResponse` comes from `dart:ui`): + Dart-side cleanup, and a quit during an image generation waits for the + whole generation, so still dispose every engine, including + `DecisionEngine` and `ImageGenerationEngine`, before the app quits. + Desktop Flutter apps do not run `State.dispose` on quit, so dispose from + an exit request instead (`AppExitResponse` comes from `dart:ui`): ```dart final listener = AppLifecycleListener( @@ -120,8 +133,8 @@ already in progress. The example chat app does this with [`AppExitCoordinator`](https://github.com/leehack/llamadart/blob/main/example/chat_app/lib/services/app_exit_coordinator.dart). A Flutter hot restart (debug builds only) discards the old isolates. A -llama.cpp model one of them was still loading is freed by the runtime when -the app quits; an image model a discarded isolate loaded still aborts the quit +llama.cpp or image model one of them was still loading is freed by the +runtime when the app quits ([#813](https://github.com/leehack/llamadart/issues/813)). `LlamaBackend()` routes GGUF to llama.cpp and `.litertlm` bundles to diff --git a/website/docs/maintainers/native-and-web-sync.md b/website/docs/maintainers/native-and-web-sync.md index 250521a0c..3bf0de19a 100644 --- a/website/docs/maintainers/native-and-web-sync.md +++ b/website/docs/maintainers/native-and-web-sync.md @@ -163,10 +163,10 @@ the tag explicitly, since `latest` skips GitHub prereleases. ```bash python3 tool/native/sync_native_release_pins.py \ - --stable-diffusion-tag v0.2.0 \ + --stable-diffusion-tag v0.2.0-1 \ --dry-run python3 tool/native/sync_native_release_pins.py \ - --stable-diffusion-tag v0.2.0 + --stable-diffusion-tag v0.2.0-1 python3 tool/native/sync_stable_diffusion_bindings.py ``` @@ -184,16 +184,22 @@ and a `stableDiffusionBundleForNativeBundle` mapping by hand. `sync_stable_diffusion_bindings.py` downloads the pinned `linux-x64` archive (or takes `--archive`), checks it against the pin, stages -`include/stable-diffusion.h` under +`include/stable-diffusion.h` and `include/sd_dart_wrapper.h` under `.dart_tool/llamadart/ffigen_headers_stable_diffusion/`, and regenerates `lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart` with `ffigen_stable_diffusion.yaml`. The bindings resolve the library through the `package:llamadart/stable_diffusion` native-asset id that the hook emits. +That config leaves five `sd_dart_exit_` functions unbound and marks +`sd_dart_progress_read` as the only leaf call. A new `sd_dart_` function the +image worker calls also goes into `StableDiffusionCalls`, whose probe decides +whether the runtime is supported +([exit teardown](https://github.com/leehack/llamadart/blob/main/doc/llama_cpp_exit_teardown.md#image-models)). After a sync, run `dart test --run-skipped -t local-only test/integration/stable_diffusion_runtime_hook_test.dart` on macOS: it builds a throwaway consumer against the new pin and probes the -runtime it bundles. +runtime it bundles. Then run the `image-generation-smoke` and +`image-exit-teardown` rows of `doc/testing_matrix.md`. ## Native version update checklist diff --git a/website/docs/platforms/native-build-hooks.md b/website/docs/platforms/native-build-hooks.md index f919eefdf..c172d94fe 100644 --- a/website/docs/platforms/native-build-hooks.md +++ b/website/docs/platforms/native-build-hooks.md @@ -327,7 +327,7 @@ Runtime releases built before the manifest was added do not contain it: | Runtime | XCFramework with a manifest | | --- | --- | | llama.cpp | `llamadart-native` `v0.5.0-1` and later, which `llamadart_llama_cpp_flutter` releases after `0.0.20` link; `0.0.20` and earlier link `v0.5.0` or older, without one | -| stable-diffusion.cpp | None yet: the pinned `stable-diffusion-native` `v0.2.0` has none | +| stable-diffusion.cpp | `stable-diffusion-native` `v0.2.0-1` and later, which `llamadart_stable_diffusion_flutter` releases after `0.0.1` link; `0.0.1` links `v0.2.0`, without one | | LiteRT-LM | `litert-lm-native` `v0.17.0-8` and later, which `llamadart_litert_lm_flutter` releases after `0.0.12` link; `0.0.12` and earlier link `v0.17.0-6` or older, without one | An app declares the use in its own `PrivacyInfo.xcprivacy` when it runs diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index f85a9100c..1c2252635 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -157,7 +157,7 @@ output and grammars, sampling controls and speculative decoding. Guides: | --- | --- | | llama.cpp native | `leehack/llamadart-native@v0.5.0-2` | | LiteRT-LM native | `leehack/litert-lm-native@v0.17.0-8` | -| stable-diffusion.cpp native (opt-in, Preview) | `leehack/stable-diffusion-native@v0.2.0`, for [image generation](../guides/image-generation); see [Opt-in stable_diffusion runtime](./native-build-hooks#opt-in-stable_diffusion-runtime-experimental). Flutter iOS/macOS apps link its XCFramework through `llamadart_stable_diffusion_flutter` | +| stable-diffusion.cpp native (opt-in, Preview) | `leehack/stable-diffusion-native@v0.2.0-1`, for [image generation](../guides/image-generation); see [Opt-in stable_diffusion runtime](./native-build-hooks#opt-in-stable_diffusion-runtime-experimental). Flutter iOS/macOS apps link its XCFramework through `llamadart_stable_diffusion_flutter` | | WebGPU bridge assets | `leehack/llama-web-bridge-assets`; see [Pinned bridge assets](./webgpu-bridge#pinned-bridge-assets) | The native-assets hook currently pins `llamadart-native` tag