From b1b8396af627309fef6a1b2756e9f356710f54e2 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 19:20:27 -0400 Subject: [PATCH 1/4] feat: adopt stable-diffusion-native v0.2.0-2 with a Vulkan memory check, load-failure reasons and runtime logs Pin the stable_diffusion runtime to leehack/stable-diffusion-native@v0.2.0-2 (hook archives, Apple SwiftPM companion, bindings) and use its new exports where the runtime has them. - Memory check: on a Vulkan GPU the engine compares the model's estimate with the GPU's free memory when its driver reports a budget, with its total memory otherwise, and with host memory for an integrated GPU. The query runs in a short-lived isolate. Apple keeps its existing check. - Load errors: a load the runtime rejects quotes the errors it logged, read from sd_dart_last_error on the loading thread, with files named by role. - Logs: the runtime records its messages and the worker isolate reads them after each load and generation and at dispose, then the calling isolate logs them through LlamaLogger at the configured levels. ggml's device messages no longer go to stderr. - The seven new functions are optional: on a runtime of v0.2.0-1 none is called and image generation works as before. - Default CI now shows that the runtime probe runs in another isolate and that a load writes its files after sd_ctx_params_init. Refs #966, #803, #811, leehack/stable-diffusion-native#9, leehack/stable-diffusion-native#3. --- CHANGELOG.md | 19 + doc/llama_cpp_exit_teardown.md | 98 ++++- doc/testing_matrix.md | 13 +- .../test/fixtures/image_exit_probe.dart | 55 ++- .../test/image_exit_teardown_e2e_test.dart | 18 +- .../test/image_generation_e2e_test.dart | 150 +++++++ .../stable_diffusion_bindings.dart | 97 +++++ .../stable_diffusion_calls.dart | 159 ++++++- .../stable_diffusion_image_worker.dart | 209 +++++++-- .../stable_diffusion_log.dart | 196 +++++++++ .../stable_diffusion_memory.dart | 143 +++++- .../stable_diffusion_runtime_io.dart | 23 + .../core/image/image_generation_driver.dart | 16 +- .../image/image_generation_driver_io.dart | 69 ++- .../image/image_generation_driver_stub.dart | 4 +- .../core/image/image_generation_engine.dart | 29 +- lib/src/core/llama_logging.dart | 5 + lib/src/hook/native_release_pins.dart | 28 +- .../CHANGELOG.md | 4 + .../README.md | 2 +- .../Package.swift | 4 +- skills/llamadart-image-generation/SKILL.md | 20 +- .../fake_stable_diffusion_runtime.dart | 249 ++++++++++- .../stable_diffusion_calls_test.dart | 116 ++++- .../stable_diffusion_image_worker_test.dart | 407 +++++++++++++++++- .../stable_diffusion_log_test.dart | 320 ++++++++++++++ .../stable_diffusion_memory_test.dart | 162 +++++++ .../stable_diffusion_runtime_io_test.dart | 31 +- .../image_generation_driver_io_test.dart | 133 +++++- .../image_generation_driver_stub_test.dart | 2 +- .../image/image_generation_engine_test.dart | 34 +- tool/testing/test_matrix.dart | 17 +- website/docs/changelog/recent-releases.md | 19 + website/docs/configuration/logging.md | 9 + website/docs/guides/image-generation.md | 91 +++- .../docs/maintainers/native-and-web-sync.md | 10 +- website/docs/platforms/support-matrix.md | 2 +- 37 files changed, 2808 insertions(+), 155 deletions(-) create mode 100644 lib/src/backends/stable_diffusion/stable_diffusion_log.dart create mode 100644 test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ce693705..e15ba67af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,22 @@ +## Unreleased + +- Adopt `leehack/stable-diffusion-native@v0.2.0-2` for the opt-in + `stable_diffusion` image runtime. +- Check the memory of a Vulkan GPU before loading an image model on Linux and + Windows: `ImageGenerationEngine.load` refuses a model whose estimate + exceeds the GPU's free memory, or its total memory when the driver reports + no free figure, with `LlamaModelException` + ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)). + The check has not run on a physical Vulkan GPU yet, and + `ImageModelParams(checkMemory: false)` loads anyway. +- Quote the errors stable-diffusion.cpp logged in the `LlamaModelException` + of an image model it cannot load, with files named by role + ([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)). +- Send the image runtime's messages to the `LlamaLogging.configure` handler + at the configured levels, after each load and generation. The runtime no + longer prints ggml's device messages to stderr: at the default level + `none` it logs nothing. + ## 0.11.1 - Give a chat template that reads content part lists but rejects image and diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 127b8f315..6c19cc43f 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -166,6 +166,12 @@ stand-in: `IsolateShutdownReleases` hold. - `sd_dart_progress_enable` and `sd_dart_progress_read`: see "Image progress". +- `sd_dart_log_enable`, `sd_dart_log_set_level`, `sd_dart_log_read`, + `sd_dart_log_dropped` and `sd_dart_last_error` (`v0.2.0-2`): see "Image + log". +- `sd_dart_gpu_device_memory` (`v0.2.0-2`) reads the memory of the default + GPU for the memory check of a Vulkan GPU. It runs in a short-lived isolate + of its own (`readStableDiffusionGpuMemory`), not in a worker. - Upstream calls that return at once: `sd_ctx_params_init`, `sd_ctx_supports_image_generation` and `sd_get_model_version_name` right after the load, `sd_img_gen_params_init` and `free_sd_images`. @@ -185,6 +191,16 @@ runtime: the hook downloads the pinned archives by checksum, this runtime has no tag or path override, and the build rejects an Apple companion whose pin differs from the core pin. +The functions `v0.2.0-2` added are optional: `StableDiffusionCalls.log` binds +the five log functions when the runtime exports all of them, and +`gpuDeviceMemory` its one, and each is `null` otherwise +(`StableDiffusionCalls.optionalNativeRelease`). On such a runtime image +generation works as it did on `v0.2.0-1`: no log call is made, a failed load +names the missing file roles and the release that reports reasons, and a +Vulkan GPU is not memory-checked. The same holds for the reason above: no +supported configuration reaches it, so the fallback is tested on the +stand-in and was run once by hand against the `v0.2.0-1` archive. + `sd_dart_exit_teardown`, `sd_dart_exit_call_begin`, `sd_dart_exit_call_end`, `sd_dart_exit_track` and `sd_dart_exit_untrack` are excluded from the bindings (`ffigen_stable_diffusion.yaml`): none is safe from an isolate that @@ -203,6 +219,16 @@ runtime's default waits apply. - It waits up to two seconds for an `sd_dart_exit_free` in flight, and gives a thread 250 ms after its last such call, which covers the short upstream calls after a load. +- A device query (`sd_dart_gpu_device_memory`) in flight is waited for like a + load, up to 15 seconds, also when nothing is tracked: it reads ggml's + device registry, which C `exit` destroys. llamadart makes the query only + for a Vulkan GPU, on Linux and Windows, where teardown runs only when a + native host calls it. The probe's `sd_list_devices`, which initializes the + devices first, is upstream's function and is not waited for. +- The log reads (`sd_dart_log_read`, `sd_dart_log_dropped`, + `sd_dart_last_error`) are not calls in flight and need no wait: they touch + no context and stay valid during and after teardown. Each can wait up to + 100 ms for a thread that is copying a message. - The two runtimes wait one after the other: with a llama.cpp call and an image generation both in flight an exit can take about 17.5 seconds. @@ -269,21 +295,81 @@ the reports in a ring, and Dart reads them: generation ends, so it lands at most one poll interval after the runtime started, whether or not a report arrives. +### Image log + +stable-diffusion.cpp logs through a callback on whichever thread logs, with +a text that is only valid during the call, and returns only `NULL` from a +load that fails. From `v0.2.0-2` the runtime copies each message of +stable-diffusion.cpp and ggml into a 256 KiB buffer of its own, and Dart +reads them: + +- `sd_dart_log_enable` and `sd_dart_log_set_level` run before anything that + logs: in the runtime probe before `sd_list_devices`, in the isolate that + asks a GPU for its memory before the query, and in + `StableDiffusionImageWorker.start` on the calling isolate before the worker + is spawned. The first registration is not synchronized, and none of the + three runs beside a load, a generation or a device query of the same + isolate. The recorder is registered at every log level, because + `sd_dart_last_error` is empty without it; at `LlamaLogLevel.none` the level + is `SD_LOG_ERROR + 1`, which records nothing. Once it is registered, ggml's + messages no longer go to stderr. +- The level is the stricter of `LlamaLogging.level` and + `LlamaLogging.nativeLevel` when the load starts + (`imageRuntimeLogLevel`), since a message reaches the app through + `LlamaLogger`. It is the process's: the last load sets it. +- The worker isolate reads the log, never the calling isolate: a read can + wait 100 ms. It cannot read while it is inside a load or a generation, so + it reads after each one and when it is disposed, up to 4096 messages a + time, and sends them to the calling isolate before the reply of that + operation. There is no timer, so an idle worker costs nothing, and at + `LlamaLogLevel.none` nothing is read. Reading the 27 messages of an SDXS + load at `info` took 84 microseconds on an M4 Max, and a read that finds + nothing 2 to 4. +- After a load the worker first makes its calls on the context + (`sd_ctx_supports_image_generation`, `sd_get_model_version_name`), which + have to fall into teardown's 250 ms, and reads the log afterwards. After a + failed load it reads `sd_dart_last_error` first, with no asynchronous gap, + because the errors belong to the thread until its next load. +- The calling isolate keeps the position the log was read to and gives it to + each worker with every command, so a second engine does not log the first + one's messages again. Two isolates that load image models each read the + whole log. +- `sd_dart_log_dropped` counts the messages that left the buffer unread. Its + increase since the last read is logged as one warning. +- Texts are decoded leniently and file paths are replaced by roles + (`stableDiffusionPathRedactor`), in forwarded records and in the reason of + a failed load. + +A C `exit()` while an isolate executes Dart code, rather than waiting in its +event loop or inside a native call, aborts in the Dart VM +(`runtime/vm/handles_impl.h: unreachable code`) when a model is loaded: with +an image model idle on Metal and a second isolate that only decoded UTF-8 in +a loop, 5 of 5 exits aborted, and none did without the model, where the +exit takes no time. So the rows of the table above hold for isolates that +are idle or inside a native call, and what reads the log during an exit can +only be shown from native code, as the tests of `stable-diffusion-native` do. + ### Tests - `test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart`: the - lookup requests the six names and resolves nothing when one is missing; - each member calls the function exported under its own name; the generated - bindings leave out the five unbound functions and mark only - `sd_dart_progress_read` as a leaf call. + lookup requests the six required names and resolves nothing when one is + missing; the log and the device memory query are absent, each on its own, + when a name of theirs is missing; each member calls the function exported + under its own name; the generated bindings leave out the five unbound + functions and mark only `sd_dart_progress_read` as a leaf call. - `test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart`: the worker's two isolates on `test/support/fake_stable_diffusion_runtime.dart`, with a progress timer the test fires by hand. The whole call sequence of each isolate is compared for a load, a generation, a batch of three, a cancel before the runtime starts and one during a generation, dispose, a failed load, a model that cannot generate images and a runtime without the - functions. + functions; with a log level, for the reads after a load, a generation, a + failed load and dispose; and on a stand-in for `v0.2.0-1`, where no log + function is called. +- `test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart`: the + level mapping, lenient decoding, a drain's reads, position and dropped + count, and the reason of a failed load without paths. - The root package does not bundle the runtime, so no default-CI test resolves the real exports. `image-exit-teardown` in `doc/testing_matrix.md` does, locally on Metal, along with the process - exits. + exits, three of them with the log forwarded at debug level. diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 40bd74088..8c154ddae 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -299,7 +299,9 @@ dart run tool/testing/run_local_e2e.dart \ # model cache directory) to load SDXS from its pinned Hugging Face file # through the resolver, 683 MB on the first run, and # LLAMADART_IMAGE_SPLIT_MODEL (a split model's files, comma separated in any -# order) to check role detection on a real split model. +# order) to check role detection on a real split model. It also checks the +# runtime's reason in the error of a rejected load, the runtime's messages in +# the log handler, and on macOS the runtime's GPU memory figure. dart run tool/testing/run_local_e2e.dart --scenario image-generation-smoke \ --model-path /path/to/sdxs-512-tinySDdistilled_Q8_0.gguf @@ -589,7 +591,11 @@ stable_diffusion runtime. It runs ends it while an image model is alive on Metal: C `exit` through FFI from the main isolate with the model idle, generating, loading, or already disposed; an unhandled error while generating or loading; and an isolate killed inside -the native load. Each run must reach its exit point, print neither +the native load. The idle, generating and loading exits run a second time +with the runtime's log forwarded at debug level (`-logging`), so the worker +reads the log around the exit, and `quiet` loads, generates and disposes at +the default log levels and must leave no `ggml_` line on stderr. Each run +must reach its exit point, print neither `GGML_ASSERT` nor `GetFfiCallbackMetadata`, and end with exit code 0, or 255 for the unhandled errors. The loading scenarios time a second load of the model and exit halfway through a third, because the first load of a process @@ -598,7 +604,8 @@ native host that exits without shutting Dart down, not a Flutter quit ([exit teardown](llama_cpp_exit_teardown.md#image-models)). The row also checks that each `sd_dart_` function `StableDiffusionCalls` -looks up resolves to the runtime's own export of that name, which default CI +looks up, the optional log and device memory functions included, resolves to +the runtime's own export of that name, which default CI cannot (the root package does not bundle the runtime), and that batches of two and three images report every sampling step in order and end with the `decoding` event. diff --git a/example/basic_app/test/fixtures/image_exit_probe.dart b/example/basic_app/test/fixtures/image_exit_probe.dart index c840049af..6e3afa5a2 100644 --- a/example/basic_app/test/fixtures/image_exit_probe.dart +++ b/example/basic_app/test/fixtures/image_exit_probe.dart @@ -1,6 +1,8 @@ // Subprocess fixture: ends the process in one way while an image model is // alive, or prints the progress events of a batch. Arguments: the scenario // and an image checkpoint; `quit-both-loaded` also takes a GGUF chat model. +// A scenario whose name ends in `-logging` runs with the runtime's log +// forwarded at debug level, so the worker reads the log around the exit. // // The `quit-` scenarios call C `exit` through FFI from the main isolate while // the worker isolate that owns the context is alive: what a native host that @@ -25,16 +27,41 @@ import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_params. import 'package:llamadart/src/core/image/image_generation_driver.dart'; Future main(List args) async { - final [scenario, modelPath, ...extra] = args; + final [requested, modelPath, ...extra] = args; + final logging = requested.endsWith(_loggingSuffix); + final scenario = logging + ? requested.substring(0, requested.length - _loggingSuffix.length) + : requested; + if (logging) { + await LlamaLogging.configure( + level: LlamaLogLevel.debug, + handler: (_) => _logRecords++, + ); + } switch (scenario) { case 'symbols': await ImageGenerationEngine.checkRuntime(); - for (final name in StableDiffusionCalls.wrapperSymbols) { + for (final name in [ + ...StableDiffusionCalls.wrapperSymbols, + ...StableDiffusionCalls.logSymbols, + ...StableDiffusionCalls.deviceMemorySymbols, + ]) { if (StableDiffusionCalls.symbolAddress(name) != DynamicLibrary.process().lookup(name)) { throw StateError('$name does not resolve to the export of its name'); } } + final calls = StableDiffusionCalls.tryResolve()!; + if (calls.log == null || calls.gpuDeviceMemory == null) { + throw StateError('The pinned runtime lacks the log or device memory'); + } + _reached(scenario); + case 'quiet': + // At the default log levels the runtime prints nothing: the test reads + // this process's stderr. + final engine = await _load(modelPath); + await engine.generateImage(_request(steps: 1)); + await engine.dispose(); _reached(scenario); case 'events': final engine = await _load(modelPath); @@ -105,8 +132,16 @@ Future main(List args) async { } } -void _reached(String scenario) => - stdout.writeln('IMAGE_PROBE_REACHED $scenario'); +const _loggingSuffix = '-logging'; + +int _logRecords = 0; + +void _reached(String scenario) { + if (_logRecords > 0) { + stdout.writeln('IMAGE_PROBE_LOG_RECORDS $_logRecords'); + } + stdout.writeln('IMAGE_PROBE_REACHED $scenario'); +} void _reportTracked() => stdout.writeln('IMAGE_PROBE_TRACKED ${sd.sd_dart_exit_tracked_count()}'); @@ -177,7 +212,10 @@ Future _loadTime(String modelPath) async { load ..reset() ..start(); - final worker = await StableDiffusionImageWorker.start(_config(modelPath)); + final worker = await StableDiffusionImageWorker.start( + _config(modelPath), + logLevel: LlamaLogging.level, + ); load.stop(); await worker.dispose(); } @@ -189,7 +227,12 @@ Future _loadTime(String modelPath) async { /// 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))); + unawaited( + StableDiffusionImageWorker.start( + _config(modelPath), + logLevel: LlamaLogging.level, + ), + ); await Future.delayed(loadTime ~/ 2); } diff --git a/example/basic_app/test/image_exit_teardown_e2e_test.dart b/example/basic_app/test/image_exit_teardown_e2e_test.dart index 4f63da890..997ad6d6f 100644 --- a/example/basic_app/test/image_exit_teardown_e2e_test.dart +++ b/example/basic_app/test/image_exit_teardown_e2e_test.dart @@ -27,9 +27,13 @@ void main() { // arguments (null skips it) and the exit code of a clean end. for (final (scenario, arguments, exitCode) in <(String, List, int)>[ ('symbols', [model], 0), + ('quiet', [model], 0), ('quit-loaded', [model], 0), ('quit-generating', [model], 0), ('quit-loading', [model], 0), + ('quit-loaded-logging', [model], 0), + ('quit-generating-logging', [model], 0), + ('quit-loading-logging', [model], 0), ('throw-generating', [model], 255), ('throw-loading', [model], 255), ('kill-loading', [model], 0), @@ -48,18 +52,28 @@ void main() { final seconds = []; for (var run = 0; run < runs; run++) { final probe = await _runProbe([scenario, ...arguments.nonNulls]); + final reached = scenario.replaceFirst(RegExp(r'-logging$'), ''); expect( probe.stdout, - contains('IMAGE_PROBE_REACHED $scenario'), + contains('IMAGE_PROBE_REACHED $reached'), reason: probe.stderr, ); + if (scenario == 'quiet') { + // The recorder takes ggml's messages off stderr, and at the + // default levels nothing reads them. + expect(probe.stderr, isNot(contains('ggml_'))); + expect(probe.stdout, isNot(contains('IMAGE_PROBE_LOG_RECORDS'))); + } + if (scenario.endsWith('-logging')) { + expect(probe.stdout, contains('IMAGE_PROBE_LOG_RECORDS')); + } if (probe.stdout.contains('IMAGE_PROBE_BACKEND')) { expect(probe.stdout, contains('IMAGE_PROBE_BACKEND MTL')); } if (scenario == 'quit-both-loaded') { expect(probe.stdout, contains('IMAGE_PROBE_CHAT_BACKEND Metal')); } - if (scenario == 'quit-loaded') { + if (reached == 'quit-loaded') { expect(probe.stdout, contains('IMAGE_PROBE_TRACKED 1')); } if (scenario == 'dispose-quit') { diff --git a/example/basic_app/test/image_generation_e2e_test.dart b/example/basic_app/test/image_generation_e2e_test.dart index 5129e761e..4fc241231 100644 --- a/example/basic_app/test/image_generation_e2e_test.dart +++ b/example/basic_app/test/image_generation_e2e_test.dart @@ -1,11 +1,16 @@ +// ignore_for_file: implementation_imports @Tags(['local-only']) @Timeout(Duration(minutes: 10)) library; import 'dart:async'; import 'dart:io'; +import 'dart:isolate'; import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_image_worker.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_memory.dart'; +import 'package:llamadart/src/core/image/image_generation_driver.dart'; import 'package:test/test.dart'; // Real image generation through the stable_diffusion runtime this example @@ -113,6 +118,151 @@ void main() { ); }, skip: sdxsPath == null ? 'Set LLAMADART_SDXS_MODEL' : false); + test('a load the runtime rejects carries the reason the runtime logged, ' + 'with files named by role', () async { + final directory = await Directory.systemTemp.createTemp('llamadart-img-'); + addTearDown(() => directory.delete(recursive: true)); + // The header and the first tensors: the roles are detected, and the + // runtime finds tensors past the end of the file. + final truncated = File('${directory.path}/truncated.gguf'); + final source = await File(sdxsPath!).open(); + try { + await truncated.writeAsBytes(await source.read(64 << 20)); + } finally { + await source.close(); + } + final missing = '${directory.path}/missing.gguf'; + + Future reasonOf(Future load) async { + try { + await load; + } on LlamaModelException catch (error) { + expect('$error', isNot(contains(directory.path))); + expect('$error', isNot(contains(sdxsPath))); + return RegExp( + r'The runtime reported: "(.*)"\.', + ).firstMatch(error.message)!.group(1)!; + } + fail('The load succeeded.'); + } + + final reasons = { + 'truncated file': await reasonOf( + ImageGenerationEngine.load(_sdxs(ModelSource.path(truncated.path))), + ), + // The engine refuses a missing file itself, so this one goes straight + // to the worker. + 'missing file': await reasonOf( + StableDiffusionImageWorker.start( + ImageGenerationSessionConfig( + files: {'model': missing}, + backend: null, + threads: 0, + ), + ), + ), + 'wrong role': await reasonOf( + ImageGenerationEngine.load( + ImageGenerationModel( + ModelSource.path(sdxsPath), + role: ImageModelRole.diffusionModel, + ), + ), + ), + }; + + print('IMAGE_LOAD_FAILURE_REASONS $reasons'); + expect(reasons['truncated file'], contains('')); + expect(reasons['missing file'], contains('')); + expect(reasons.values.toSet(), hasLength(3)); + + // The engine still loads afterwards. + final engine = await ImageGenerationEngine.load( + _sdxs(ModelSource.path(sdxsPath)), + ); + await engine.dispose(); + }, skip: sdxsPath == null ? 'Set LLAMADART_SDXS_MODEL' : false); + + test('the runtime\'s messages reach the log handler at the configured ' + 'levels, by level and without paths, and none do by default', () async { + Future> recordsAt(LlamaLogLevel level) async { + final records = []; + await LlamaLogging.configure(level: level, handler: records.add); + try { + final engine = await ImageGenerationEngine.load( + _sdxs(ModelSource.path(sdxsPath!)), + ); + final loaded = records.length; + await engine.generateImage( + const ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + width: 256, + height: 256, + steps: 1, + guidanceScale: 1, + seed: 42, + ), + ); + final generated = records.length; + await engine.dispose(); + print( + 'IMAGE_LOG ${level.name}: ${records.length} records ($loaded after ' + 'the load, ${generated - loaded} after the generation, ' + '${records.length - generated} at dispose); by level ' + '${{for (final l in LlamaLogLevel.values) l.name: records.where((r) => r.level == l).length}}', + ); + } finally { + await LlamaLogging.configure(); + } + return records; + } + + final silent = await recordsAt(LlamaLogLevel.none); + final info = await recordsAt(LlamaLogLevel.info); + final debug = await recordsAt(LlamaLogLevel.debug); + final error = await recordsAt(LlamaLogLevel.error); + + expect(silent, isEmpty); + expect(error, isEmpty); + expect(info, isNotEmpty); + for (final record in info.take(6)) { + print('IMAGE_LOG_RECORD [${record.level.name}] ${record.message}'); + } + expect( + info.map((record) => record.level), + everyElement(isIn([LlamaLogLevel.info, LlamaLogLevel.warn])), + ); + expect(debug.length, greaterThan(info.length)); + expect(debug.map((record) => record.level), contains(LlamaLogLevel.debug)); + for (final record in debug) { + expect(record.message, startsWith('stable_diffusion: ')); + expect(record.message, isNot(contains(sdxsPath!))); + } + expect( + debug.map((record) => record.message), + contains(contains('')), + ); + }, skip: sdxsPath == null ? 'Set LLAMADART_SDXS_MODEL' : false); + + test('the GPU memory the runtime reports for Metal is the working set ' + 'the memory check reads itself', () async { + final memory = await Isolate.run(readStableDiffusionGpuMemory); + final workingSet = readStableDiffusionMemoryBudget( + device: ImageGenerationComputeDevice.metal, + )!; + + print( + 'IMAGE_GPU_MEMORY ${memory!.name}: total ${memory.totalBytes}, free ' + '${memory.freeBytes}, integrated ${memory.integrated}; ' + '${workingSet.source}: ${workingSet.bytes}', + ); + expect(memory.name, startsWith('MTL')); + expect(memory.integrated, isFalse); + expect(memory.freeBytes, inInclusiveRange(1, memory.totalBytes)); + expect(workingSet.source, "Metal's recommended GPU working set"); + expect(memory.totalBytes, workingSet.bytes); + }, skip: Platform.isMacOS ? false : 'macOS only'); + group('SDXS', () { late ImageGenerationEngine engine; diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart b/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart index 92d50ca04..ee7fb07e9 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_bindings.dart @@ -336,6 +336,46 @@ external bool sd_dart_generate_image( ffi.Pointer num_images_out, ); +@ffi.Native() +external int sd_dart_gpu_device_count(); + +@ffi.Native< + ffi.Int32 Function(ffi.Int32, ffi.Pointer) +>() +external int sd_dart_gpu_device_memory( + int device_index, + ffi.Pointer out, +); + +@ffi.Native, ffi.Size)>() +external int sd_dart_last_error(ffi.Pointer text, int capacity); + +@ffi.Native() +external int sd_dart_log_dropped(); + +@ffi.Native() +external void sd_dart_log_enable(); + +@ffi.Native< + ffi.Uint64 Function( + ffi.Uint64, + ffi.Pointer, + ffi.Size, + ffi.Pointer, + ffi.Pointer, + ) +>() +external int sd_dart_log_read( + int after, + ffi.Pointer text, + int capacity, + ffi.Pointer level, + ffi.Pointer length, +); + +@ffi.Native() +external void sd_dart_log_set_level(int level); + @ffi.Native Function(ffi.Pointer)>() external ffi.Pointer sd_dart_new_sd_ctx( ffi.Pointer sd_ctx_params, @@ -648,6 +688,10 @@ external bool upscale( ffi.Pointer num_images_out, ); +const int SD_DART_GPU_DEFAULT_DEVICE = -1; + +const int SD_DART_LOG_TEXT_SIZE = 4096; + final class adetailer_ctx_t extends ffi.Opaque {} final class ggml_tensor extends ffi.Opaque {} @@ -1323,6 +1367,59 @@ enum sd_dart_exit_stage { }; } +final class sd_dart_gpu_device_memory_t extends ffi.Struct { + @ffi.Uint64() + external int total_bytes; + + @ffi.Uint64() + external int free_bytes; + + @ffi.Int32() + external int type; + + @ffi.Array.multi([64]) + external ffi.Array name; + + @ffi.Array.multi([256]) + external ffi.Array description; +} + +enum sd_dart_gpu_device_type { + SD_DART_GPU_DEVICE_DISCRETE(1), + SD_DART_GPU_DEVICE_INTEGRATED(2); + + final int value; + const sd_dart_gpu_device_type(this.value); + + static sd_dart_gpu_device_type fromValue(int value) => switch (value) { + 1 => SD_DART_GPU_DEVICE_DISCRETE, + 2 => SD_DART_GPU_DEVICE_INTEGRATED, + _ => throw ArgumentError( + 'Unknown value for sd_dart_gpu_device_type: $value', + ), + }; +} + +enum sd_dart_gpu_status { + SD_DART_GPU_OK(0), + SD_DART_GPU_INVALID_ARGUMENT(-1), + SD_DART_GPU_NO_BACKEND(-2), + SD_DART_GPU_NO_DEVICE(-3), + SD_DART_GPU_UNAVAILABLE(-4); + + final int value; + const sd_dart_gpu_status(this.value); + + static sd_dart_gpu_status fromValue(int value) => switch (value) { + 0 => SD_DART_GPU_OK, + -1 => SD_DART_GPU_INVALID_ARGUMENT, + -2 => SD_DART_GPU_NO_BACKEND, + -3 => SD_DART_GPU_NO_DEVICE, + -4 => SD_DART_GPU_UNAVAILABLE, + _ => throw ArgumentError('Unknown value for sd_dart_gpu_status: $value'), + }; +} + final class sd_dart_progress_t extends ffi.Struct { @ffi.Uint64() external int sequence; diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart index 4f78ebee8..ad7ce0619 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart @@ -26,6 +26,14 @@ typedef _GenerateImageNative = typedef _CancelGenerationNative = Void Function(Pointer, UnsignedInt); typedef _ExitFreeNative = Void Function(Pointer); +typedef _GpuDeviceMemoryNative = + Int32 Function(Int32, Pointer); +typedef _LogEnableNative = Void Function(); +typedef _LogSetLevelNative = Void Function(Int32); +typedef _LogReadNative = + Uint64 Function(Uint64, Pointer, Size, Pointer, Pointer); +typedef _LogDroppedNative = Uint64 Function(); +typedef _LastErrorNative = Size Function(Pointer, Size); /// Every native call an image worker makes. /// @@ -50,6 +58,12 @@ typedef _ExitFreeNative = Void Function(Pointer); /// has no way to report progress without a Dart callback, so image /// generation is unsupported on it rather than falling back. /// +/// [log] and [gpuDeviceMemory] are the functions [optionalNativeRelease] +/// added. Each group is bound only when the runtime exports all of it, and is +/// `null` otherwise: a runtime between the two releases still generates +/// images, without the runtime's log and its reason for a failed load, and +/// without the memory check of a Vulkan GPU. +/// /// `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 @@ -74,6 +88,8 @@ final class StableDiffusionCalls { required this.modelVersionName, required this.imageGenerationParamsInit, required this.freeImages, + this.log, + this.gpuDeviceMemory, }); /// The oldest `stable-diffusion-native` release that exports the `sd_dart_` @@ -90,8 +106,25 @@ final class StableDiffusionCalls { 'sd_dart_exit_free', ]; + /// The `stable-diffusion-native` release that added [logSymbols] and + /// [deviceMemorySymbols]. + static const String optionalNativeRelease = 'v0.2.0-2'; + + /// The `sd_dart_` functions of [log]. + static const List logSymbols = [ + 'sd_dart_log_enable', + 'sd_dart_log_set_level', + 'sd_dart_log_read', + 'sd_dart_log_dropped', + 'sd_dart_last_error', + ]; + + /// The `sd_dart_` function of [gpuDeviceMemory]. + static const List deviceMemorySymbols = ['sd_dart_gpu_device_memory']; + /// Resolves the calls from the bundled runtime, or returns `null` when it - /// does not export every one of [wrapperSymbols]. + /// does not export every one of [wrapperSymbols]. [log] and + /// [gpuDeviceMemory] are `null` when it does not export theirs. /// /// [symbol] replaces the lookup: it returns the address of the function /// exported under a name, and throws [ArgumentError] when there is none. @@ -106,7 +139,8 @@ final class StableDiffusionCalls { } /// The address of the function the bundled runtime exports as [name], one - /// of [wrapperSymbols]; throws [ArgumentError] when it exports none. + /// of [wrapperSymbols], [logSymbols] or [deviceMemorySymbols]; throws + /// [ArgumentError] when it exports none. static Pointer symbolAddress(String name) => switch (name) { 'sd_dart_progress_enable' => Native.addressOf>( @@ -130,6 +164,27 @@ final class StableDiffusionCalls { 'sd_dart_exit_free' => Native.addressOf>( sd.sd_dart_exit_free, ), + 'sd_dart_log_enable' => Native.addressOf>( + sd.sd_dart_log_enable, + ), + 'sd_dart_log_set_level' => + Native.addressOf>( + sd.sd_dart_log_set_level, + ), + 'sd_dart_log_read' => Native.addressOf>( + sd.sd_dart_log_read, + ), + 'sd_dart_log_dropped' => + Native.addressOf>( + sd.sd_dart_log_dropped, + ), + 'sd_dart_last_error' => Native.addressOf>( + sd.sd_dart_last_error, + ), + 'sd_dart_gpu_device_memory' => + Native.addressOf>( + sd.sd_dart_gpu_device_memory, + ), _ => throw ArgumentError.value(name, 'name', 'not bound'), }; @@ -140,6 +195,15 @@ final class StableDiffusionCalls { ) { Pointer> function(String name) => symbol(name).cast(); + // A group whose functions the runtime does not all export. + T? optional(T Function() bind) { + try { + return bind(); + } on ArgumentError { + return null; + } + } + final exitFree = function<_ExitFreeNative>('sd_dart_exit_free'); final void Function(Pointer, int) cancelGeneration = function<_CancelGenerationNative>( @@ -167,6 +231,26 @@ final class StableDiffusionCalls { modelVersionName: sd.sd_get_model_version_name, imageGenerationParamsInit: sd.sd_img_gen_params_init, freeImages: sd.free_sd_images, + log: optional( + () => StableDiffusionLogCalls( + enable: function<_LogEnableNative>('sd_dart_log_enable').asFunction(), + setLevel: function<_LogSetLevelNative>( + 'sd_dart_log_set_level', + ).asFunction(), + read: function<_LogReadNative>('sd_dart_log_read').asFunction(), + dropped: function<_LogDroppedNative>( + 'sd_dart_log_dropped', + ).asFunction(), + lastError: function<_LastErrorNative>( + 'sd_dart_last_error', + ).asFunction(), + ), + ), + gpuDeviceMemory: optional( + () => function<_GpuDeviceMemoryNative>( + 'sd_dart_gpu_device_memory', + ).asFunction(), + ), ); } @@ -235,6 +319,77 @@ final class StableDiffusionCalls { /// `free_sd_images`. final void Function(Pointer images, int count) freeImages; + + /// The runtime's log recorder, or `null` on a runtime older than + /// [optionalNativeRelease]. + final StableDiffusionLogCalls? log; + + /// `sd_dart_gpu_device_memory`, or `null` on a runtime older than + /// [optionalNativeRelease]: writes the memory of GPU `deviceIndex`, or of + /// the device a context with no backend uses for + /// `SD_DART_GPU_DEFAULT_DEVICE`, to `out` and returns an + /// `sd_dart_gpu_status`. + /// + /// The first query in a process initializes the GPU backend, which on Metal + /// with an empty shader cache takes many seconds, so it never runs on a UI + /// isolate. It is a call exit teardown waits for, with the bound of a load. + final int Function( + int deviceIndex, + Pointer out, + )? + gpuDeviceMemory; +} + +/// The log recorder of the stable_diffusion runtime: the library copies each +/// message of stable-diffusion.cpp and ggml into a buffer of its own and Dart +/// reads them, so Dart gives the runtime no log callback either. +/// +/// [read] and [lastError] wait up to 100 ms for a thread that is copying a +/// message, so they are not leaf calls and run in the worker isolate. All of +/// them stay valid during and after exit teardown. +final class StableDiffusionLogCalls { + /// Creates the calls from functions. + const StableDiffusionLogCalls({ + required this.enable, + required this.setLevel, + required this.read, + required this.dropped, + required this.lastError, + }); + + /// `sd_dart_log_enable`: from then on the library records the messages of + /// every call in the process, and ggml's no longer go to stderr. Its first + /// call is not synchronized with a load, a generation or a device query on + /// another thread. + final void Function() enable; + + /// `sd_dart_log_set_level`: the lowest `sd_log_level_t` recorded; + /// `SD_LOG_ERROR + 1` records nothing. + final void Function(int level) setLevel; + + /// `sd_dart_log_read`: copies the oldest message whose sequence is greater + /// than `after` to `text` and returns its sequence, or 0 when there is + /// none. A sequence other than `after + 1` means the messages in between + /// left the buffer. + final int Function( + int after, + Pointer text, + int capacity, + Pointer level, + Pointer length, + ) + read; + + /// `sd_dart_log_dropped`: messages that left the buffer unread, or could + /// not be recorded. + final int Function() dropped; + + /// `sd_dart_last_error`: the error messages recorded while the calling + /// thread's most recent [StableDiffusionCalls.newContext] or + /// [StableDiffusionCalls.generateImage] ran, joined by line breaks; returns + /// the bytes of the whole text. Empty unless [enable] was called before + /// that call. + final int Function(Pointer text, int capacity) lastError; } /// The error for a stable_diffusion runtime that does not export every 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 91f0d99b3..8b9025700 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart @@ -8,9 +8,12 @@ import '../../core/exceptions.dart'; import '../../core/image/generated_image.dart'; import '../../core/image/image_generation_driver.dart'; import '../../core/llama_logger.dart'; +import '../../core/models/config/log_level.dart'; import '../isolate_shutdown_releases.dart'; +import '../worker_log_message.dart'; import 'stable_diffusion_bindings.dart' as sd; import 'stable_diffusion_calls.dart'; +import 'stable_diffusion_log.dart'; import 'stable_diffusion_params.dart'; /// Resolves the native calls of a worker; `null` when the runtime lacks them. @@ -29,6 +32,13 @@ typedef StableDiffusionProgressTimer = /// process. Cancellation calls `sd_dart_cancel_generation` from the calling /// isolate, since the worker is blocked inside the generation. /// +/// The runtime's log is read without a callback too, but by the worker: a +/// read can wait 100 ms, which the calling isolate must not. The worker reads +/// what the runtime recorded after its load, after each generation and when +/// it is disposed, and sends it to the calling isolate, which logs it through +/// [LlamaLogger]. On a runtime without [StableDiffusionCalls.log] nothing is +/// read. +/// /// 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. @@ -46,6 +56,15 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { /// [_reportsPerRead] it covers the reports the runtime keeps. static const int _readsPerPoll = 64; + /// Where the workers of this isolate have read the runtime's log to. The + /// log is the process's, so each read continues where the last one ended. + static StableDiffusionLogPosition _logPosition = (after: 0, dropped: 0); + + /// Starts reading the log from its beginning again, for a test that + /// replaces the runtime. + static void debugResetLogPositionForTesting() => + _logPosition = (after: 0, dropped: 0); + final Isolate _isolate; final _Replies _replies; final SendPort _commands; @@ -75,27 +94,40 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { /// [progressTimer] starts the progress poll of each [generate]. Tests /// replace both. /// + /// The runtime records its messages from [logLevel] up, and the worker + /// forwards them to this isolate's [LlamaLogger]; at [LlamaLogLevel.none] + /// nothing is recorded or read. The level is the process's: the worker + /// started last sets it. + /// /// Throws [LlamaModelException] when the runtime cannot load the files as - /// an image model, and [LlamaUnsupportedException] when the runtime does - /// not export the functions of [StableDiffusionCalls]. + /// an image model, with the runtime's reason when it gives one, and + /// [LlamaUnsupportedException] when the runtime does not export the + /// functions of [StableDiffusionCalls]. static Future start( ImageGenerationSessionConfig config, { StableDiffusionCallsResolver resolveCalls = StableDiffusionCalls.tryResolve, StableDiffusionProgressTimer progressTimer = Timer.periodic, + LlamaLogLevel logLevel = LlamaLogLevel.none, }) 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. + // Registers the runtime's recorders, which is not synchronized with a + // load: they have to be in place before the worker starts one. The log + // recorder is registered at every level, because the reason of a failed + // load comes from it. + final log = calls.log; + if (log != null) { + recordStableDiffusionLog(log, logLevel); + } calls.progressEnable(); final replies = _Replies(); Isolate? isolate; try { isolate = await Isolate.spawn( _workerMain, - (replies.sendPort, config, resolveCalls), + (replies.sendPort, config, resolveCalls, logLevel, _logPosition), debugName: 'llamadart-image-generation', onExit: replies.sendPort, onError: replies.sendPort, @@ -169,7 +201,7 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { readProgress(); }); try { - _commands.send(request); + _commands.send(_Generate(request, _logPosition)); final reply = await _reply() as _Generated; // The runtime recorded the last reports before the reply was sent. readProgress(); @@ -218,7 +250,7 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { _disposed = true; try { if (!_stopped) { - _commands.send(const _Dispose()); + _commands.send(_Dispose(_logPosition)); await _reply(); } } finally { @@ -255,10 +287,17 @@ final class StableDiffusionImageWorker implements ImageGenerationSession { /// role as in `ImageGenerationSessionConfig.files`. Its message and details /// name the files by their `ImageModelRole`, never by path. /// -/// The runtime logs its reason only through a callback whose text is gone by -/// the time Dart can read it (stable-diffusion-native#3), so the message -/// names the file roles a split checkpoint is missing. -LlamaModelException stableDiffusionModelLoadFailure(Map files) { +/// [reason] is what the runtime logged as errors during the load, already +/// free of paths (`stableDiffusionFailureReason`); `null` when it logged +/// none, or when the runtime cannot report it, which [runtimeReportsReason] +/// tells apart. The runtime's reason for a file in the wrong role says +/// little, so the message also names the file roles a split checkpoint is +/// missing, with or without a reason. +LlamaModelException stableDiffusionModelLoadFailure( + Map files, { + String? reason, + bool runtimeReportsReason = false, +}) { final hints = [ if (!files.containsKey('model')) ...[ if (!files.containsKey('vae') && !files.containsKey('taesd')) @@ -273,15 +312,20 @@ LlamaModelException stableDiffusionModelLoadFailure(Map files) { ]; final message = [ 'stable-diffusion.cpp could not load the image model files.', - if (hints.isEmpty) + if (reason != null) 'The runtime reported: "$reason".', + ...hints, + if (reason == null && hints.isEmpty) 'Check that they form a model the runtime supports, that each file has ' 'its role (ImageModelRole.checkpoint for a single file with ' 'diffusion weights, ImageModelRole.diffusionModel for standalone ' 'ones; set one with ImageModelComponent(source, role: ...)), and ' - 'that the device has enough memory.' - else - ...hints, - 'The runtime does not report its reason to llamadart yet.', + 'that the device has enough memory.', + if (reason == null) + runtimeReportsReason + ? 'The runtime logged no reason.' + : 'This stable_diffusion runtime does not report its reason: that ' + 'needs stable-diffusion-native ' + '${StableDiffusionCalls.optionalNativeRelease} or later.', ].join(' '); final roles = [ for (final role in files.keys) role == 'model' ? 'checkpoint' : role, @@ -295,8 +339,15 @@ const List _textEncoderRoles = ['clipL', 'clipG', 't5xxl', 'llm']; /// is awaited. final class _Replies { _Replies() { - _port = RawReceivePort(_messages.add, 'llamadart-image-generation-replies') - ..keepIsolateAlive = false; + _port = RawReceivePort((Object? message) { + // The worker sends what it read of the log before the reply of the + // operation that recorded it. + if (message is _LogBatch) { + message.deliver(); + } else { + _messages.add(message); + } + }, 'llamadart-image-generation-replies')..keepIsolateAlive = false; } final StreamController _messages = StreamController(); @@ -343,8 +394,93 @@ final class _LoadFailure { const _LoadFailure(this.error); } +final class _Generate { + final ImageGenerationSessionRequest request; + final StableDiffusionLogPosition logPosition; + + const _Generate(this.request, this.logPosition); +} + final class _Dispose { - const _Dispose(); + final StableDiffusionLogPosition logPosition; + + const _Dispose(this.logPosition); +} + +/// Messages the worker read from the runtime's log, for the calling isolate. +final class _LogBatch { + final List records; + final StableDiffusionLogPosition position; + final int dropped; + + const _LogBatch(this.records, this.position, this.dropped); + + void deliver() { + final known = StableDiffusionImageWorker._logPosition; + // Two workers that read at once can finish out of order. + if (position.after > known.after) { + StableDiffusionImageWorker._logPosition = position; + } + // No caller awaits these records, so `emit` prints an error of the log + // handler instead of throwing it into the port. + for (final record in records) { + record.emit(); + } + if (dropped > 0) { + WorkerLogMessage( + LlamaLogLevel.warn, + 'The stable_diffusion runtime dropped $dropped log messages: it ' + 'keeps the most recent 256 KiB of them, and more than that were ' + 'recorded during one load or generation. Raise ' + 'LlamaLogging.nativeLevel to record fewer.', + ).emit(); + } + } +} + +/// The runtime's log in the worker isolate: nothing on a runtime that has no +/// recorder. +final class _WorkerLog { + _WorkerLog(this._log, this._level, this._replies, Map files) + : _redact = stableDiffusionPathRedactor(files); + + final StableDiffusionLogCalls? _log; + final LlamaLogLevel _level; + final SendPort _replies; + final String Function(String text) _redact; + + /// Why the load this thread just made failed, or `null`. + String? failureReason() { + final log = _log; + return log == null + ? null + : stableDiffusionFailureReason( + readStableDiffusionLastError(log), + _redact, + ); + } + + /// Sends what the runtime recorded after [position] to the calling + /// isolate. The reads touch no context, so they are safe whenever the + /// process exits; calls on a context come before them, inside the time + /// exit teardown gives a thread after a load. + void forward(StableDiffusionLogPosition position) { + final log = _log; + if (log == null || _level == LlamaLogLevel.none) { + return; + } + final drain = drainStableDiffusionLog(log, position); + _replies.send( + _LogBatch( + [ + for (final (level, text) in drain.messages) + WorkerLogMessage(level, 'stable_diffusion: ${_redact(text)}'), + ], + drain.position, + drain.dropped, + ), + ); + } } final class _Disposed { @@ -367,24 +503,43 @@ final class _Generated { } void _workerMain( - (SendPort, ImageGenerationSessionConfig, StableDiffusionCallsResolver) + ( + SendPort, + ImageGenerationSessionConfig, + StableDiffusionCallsResolver, + LlamaLogLevel, + StableDiffusionLogPosition, + ) arguments, ) { - final (replies, config, resolveCalls) = arguments; + final (replies, config, resolveCalls, logLevel, logPosition) = arguments; final calls = resolveCalls(); if (calls == null) { replies.send(_LoadFailure(stableDiffusionWrapperUnsupported())); return; } + final log = _WorkerLog(calls.log, logLevel, replies, config.files); final context = _newContext(calls, config); if (context == nullptr) { - replies.send(_LoadFailure(stableDiffusionModelLoadFailure(config.files))); + // The errors of the load belong to this thread until its next load. + final reason = log.failureReason(); + log.forward(logPosition); + replies.send( + _LoadFailure( + stableDiffusionModelLoadFailure( + config.files, + reason: reason, + runtimeReportsReason: calls.log != null, + ), + ), + ); return; } if (!calls.supportsImageGeneration(context)) { IsolateShutdownReleases.current.release(context); calls.exitFree(context.cast()); + log.forward(logPosition); replies.send( _LoadFailure( LlamaModelException( @@ -397,6 +552,7 @@ void _workerMain( final commands = ReceivePort('llamadart-image-generation-commands'); final version = calls.modelVersionName(context); + log.forward(logPosition); replies.send( _Loaded( commands.sendPort, @@ -406,15 +562,18 @@ void _workerMain( ); commands.listen((command) { switch (command) { - case ImageGenerationSessionRequest(): + case _Generate(:final request, :final logPosition): // 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(): + final generated = _generate(calls, context, request); + log.forward(logPosition); + replies.send(generated); + case _Dispose(:final logPosition): IsolateShutdownReleases.current.release(context); calls.exitFree(context.cast()); commands.close(); + log.forward(logPosition); replies.send(const _Disposed()); } }); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_log.dart b/lib/src/backends/stable_diffusion/stable_diffusion_log.dart new file mode 100644 index 000000000..708dc1913 --- /dev/null +++ b/lib/src/backends/stable_diffusion/stable_diffusion_log.dart @@ -0,0 +1,196 @@ +import 'dart:convert'; +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; + +import '../../core/models/config/log_level.dart'; +import 'stable_diffusion_bindings.dart' as sd; +import 'stable_diffusion_calls.dart'; + +/// Where a reader of the runtime's log stands: the sequence of the last +/// message it read, and the runtime's count of dropped messages at that time. +typedef StableDiffusionLogPosition = ({int after, int dropped}); + +/// The messages one [drainStableDiffusionLog] read, where the next one +/// continues, and how many messages the runtime dropped since [position]'s +/// predecessor. +typedef StableDiffusionLogDrain = ({ + List<(LlamaLogLevel, String)> messages, + StableDiffusionLogPosition position, + int dropped, +}); + +/// Messages one [drainStableDiffusionLog] reads at most. The runtime keeps +/// 256 KiB of messages, about 2500 lines of 100 bytes, so one drain takes +/// what a load or a generation recorded; a thread that logs faster than it is +/// read cannot hold the reader. +const int stableDiffusionLogReadsPerDrain = 4096; + +/// `sd_dart_last_error` keeps the 32 most recent errors of a call, cut to +/// 511 bytes each and joined by line breaks. +const int _lastErrorCapacity = 32 * 512; + +/// Characters of the runtime's reason an exception message carries. +const int _reasonLimit = 1000; + +/// The lowest `sd_log_level_t` the runtime records for [level]: +/// `SD_LOG_ERROR + 1`, which records nothing, for [LlamaLogLevel.none]. +int stableDiffusionLogThreshold(LlamaLogLevel level) => switch (level) { + LlamaLogLevel.none => sd.sd_log_level_t.SD_LOG_ERROR.value + 1, + LlamaLogLevel.debug => sd.sd_log_level_t.SD_LOG_DEBUG.value, + LlamaLogLevel.info => sd.sd_log_level_t.SD_LOG_INFO.value, + LlamaLogLevel.warn => sd.sd_log_level_t.SD_LOG_WARN.value, + LlamaLogLevel.error => sd.sd_log_level_t.SD_LOG_ERROR.value, +}; + +/// The level of a message the runtime recorded at `sd_log_level_t` +/// [runtimeLevel]. `SD_LOG_DEBUG` and `SD_LOG_VERBOSE` are both +/// [LlamaLogLevel.debug]; a value above `SD_LOG_ERROR` is an error. +LlamaLogLevel stableDiffusionLogLevel(int runtimeLevel) { + if (runtimeLevel >= sd.sd_log_level_t.SD_LOG_ERROR.value) { + return LlamaLogLevel.error; + } + if (runtimeLevel == sd.sd_log_level_t.SD_LOG_WARN.value) { + return LlamaLogLevel.warn; + } + if (runtimeLevel == sd.sd_log_level_t.SD_LOG_INFO.value) { + return LlamaLogLevel.info; + } + return LlamaLogLevel.debug; +} + +/// Starts the recorder of [log] at [level]. Not synchronized with a load, a +/// generation or a device query on another thread, so it has to return before +/// one starts. +void recordStableDiffusionLog( + StableDiffusionLogCalls log, + LlamaLogLevel level, +) { + log.enable(); + log.setLevel(stableDiffusionLogThreshold(level)); +} + +/// The text the runtime wrote to the [capacity] bytes at [text], up to its +/// terminator. The runtime cuts a text between two UTF-8 sequences; a byte +/// sequence that is malformed all the same decodes to U+FFFD. +String stableDiffusionText(Pointer text, int capacity) { + final bytes = text.cast().asTypedList(capacity); + final end = bytes.indexOf(0); + return utf8.decode( + end < 0 ? bytes : bytes.sublist(0, end), + allowMalformed: true, + ); +} + +/// Reads the messages of [log] after [position], oldest first, at most +/// [maxReads] of them. +/// +/// Each read is a native call that can wait up to 100 ms for a thread that is +/// copying a message, so this runs in the worker isolate, never on a UI +/// isolate. +StableDiffusionLogDrain drainStableDiffusionLog( + StableDiffusionLogCalls log, + StableDiffusionLogPosition position, { + int maxReads = stableDiffusionLogReadsPerDrain, +}) => using((arena) { + final text = arena(sd.SD_DART_LOG_TEXT_SIZE); + final level = arena(); + final messages = <(LlamaLogLevel, String)>[]; + var after = position.after; + for (var reads = 0; reads < maxReads; reads++) { + final sequence = log.read( + after, + text, + sd.SD_DART_LOG_TEXT_SIZE, + level, + nullptr, + ); + if (sequence == 0) { + break; + } + after = sequence; + messages.add(( + stableDiffusionLogLevel(level.value), + stableDiffusionText(text, sd.SD_DART_LOG_TEXT_SIZE), + )); + } + final dropped = log.dropped(); + return ( + messages: messages, + position: (after: after, dropped: dropped), + // The count restarts with the process, and so does a reader's position. + dropped: dropped > position.dropped ? dropped - position.dropped : 0, + ); +}); + +/// The errors the runtime logged during the calling thread's most recent +/// load or generation, one per line, or an empty string when it logged none +/// or [StableDiffusionLogCalls.enable] was not called before it. +/// +/// Read it right after the call, with no asynchronous gap: the errors belong +/// to the thread, and an isolate stays on its thread only that long. +String readStableDiffusionLastError(StableDiffusionLogCalls log) => + using((arena) { + final text = arena(_lastErrorCapacity); + if (log.lastError(text, _lastErrorCapacity) == 0) { + return ''; + } + return stableDiffusionText(text, _lastErrorCapacity); + }); + +/// Replaces the paths of [files], keyed by runtime role as in +/// `ImageGenerationSessionConfig.files`, and their directories in a text of +/// the runtime, so that errors and log records name image model files by +/// role, as the rest of the image API does, and never by path. +String Function(String text) stableDiffusionPathRedactor( + Map files, +) { + final replacements = { + for (final MapEntry(key: role, value: path) in files.entries) + if (path.isNotEmpty) path: '<${_roleName(role)} file>', + }; + for (final path in files.values) { + final separator = path.lastIndexOf(RegExp(r'[/\\]')); + if (separator > 0) { + replacements.putIfAbsent( + path.substring(0, separator), + () => '', + ); + } + } + // Longest first, so a path goes before the directory it starts with. + final ordered = replacements.keys.toList() + ..sort((a, b) => b.length.compareTo(a.length)); + return (text) { + for (final path in ordered) { + text = text.replaceAll(path, replacements[path]!); + } + return text; + }; +} + +/// The runtime's reason for a failed call as one line an exception message +/// can carry: [lastError] with [redact] applied, control characters removed +/// and runs of spaces collapsed, its lines joined by `; ` and cut to 1000 +/// characters. `null` when there is nothing left. +String? stableDiffusionFailureReason( + String lastError, + String Function(String text) redact, +) { + final lines = [ + for (final line in redact(lastError).split('\n')) + line.replaceAll(_blanks, ' ').trim(), + ].where((line) => line.isNotEmpty); + if (lines.isEmpty) { + return null; + } + final reason = lines.join('; '); + return reason.length <= _reasonLimit + ? reason + : '${reason.substring(0, _reasonLimit)}...'; +} + +String _roleName(String runtimeRole) => + runtimeRole == 'model' ? 'checkpoint' : runtimeRole; + +final RegExp _blanks = RegExp(r'[\x00-\x20\x7f]+'); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart index 08323b2bc..4ed219e9b 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:ffi'; import 'dart:io'; import 'dart:typed_data'; @@ -5,6 +6,10 @@ import 'dart:typed_data'; import 'package:ffi/ffi.dart'; import '../../core/image/image_generation_driver.dart'; +import '../../core/models/config/log_level.dart'; +import 'stable_diffusion_bindings.dart' as sd; +import 'stable_diffusion_calls.dart'; +import 'stable_diffusion_log.dart'; /// Up to [length] bytes of the file at [path] from [offset]; fewer at its end. Future readStableDiffusionFileRange( @@ -57,8 +62,8 @@ int? stableDiffusionFileSize(String path) { /// physical memory, beyond which Metal buffers page. /// /// On other GPUs, such as Vulkan, `null`: the weights live in device memory, -/// which the runtime does not report (stable-diffusion-native#9), so host -/// memory would be the wrong figure. +/// so host memory would be the wrong figure. [readStableDiffusionGpuMemory] +/// and [stableDiffusionGpuMemoryBudget] give theirs. /// /// [abi], [readMemInfo], [readProcessStatus], [iosAvailableMemory], /// [macosPhysicalMemory] and [metalRecommendedWorkingSet] default to the @@ -103,6 +108,140 @@ int? stableDiffusionFileSize(String path) { return (bytes: bytes, source: reading.$2); } +/// The memory of a GPU as the stable_diffusion runtime reports it, in bytes. +/// [name] is the device name with its description, such as +/// `Vulkan0 (NVIDIA L4)`. +typedef StableDiffusionGpuMemory = ({ + String name, + int totalBytes, + int freeBytes, + bool integrated, +}); + +/// The memory of the GPU a context with no named device loads on (the first +/// discrete GPU, or else the first integrated one), from +/// `sd_dart_gpu_device_memory`, or `null` when it is not known: +/// +/// - the runtime is older than `StableDiffusionCalls.optionalNativeRelease` +/// and does not export the query; +/// - the runtime has no GPU backend or found no GPU, or the device does not +/// report its memory; +/// - `SD_VK_DEVICE` is set: such a context then loads on the Vulkan device of +/// that number if it initializes, which the query does not follow. +/// +/// The first query in a process initializes the GPU backend, as a load +/// otherwise does, which can take many seconds, and exit teardown waits for +/// a query in flight: call it from an isolate that may block, never from a UI +/// isolate. The runtime's recorder is registered first at [logLevel], because +/// a query logs through ggml and the registration is not synchronized with +/// it. +/// +/// [resolveCalls] and [environment] default to the bundled runtime and the +/// process environment; tests replace them. +StableDiffusionGpuMemory? readStableDiffusionGpuMemory({ + StableDiffusionCalls? Function() resolveCalls = + StableDiffusionCalls.tryResolve, + LlamaLogLevel logLevel = LlamaLogLevel.none, + String? Function(String name) environment = _environmentVariable, +}) { + if (environment('SD_VK_DEVICE') != null) { + return null; + } + final calls = resolveCalls(); + final query = calls?.gpuDeviceMemory; + if (calls == null || query == null) { + return null; + } + final log = calls.log; + if (log != null) { + recordStableDiffusionLog(log, logLevel); + } + return using((arena) { + final out = arena(); + final status = query(sd.SD_DART_GPU_DEFAULT_DEVICE, out); + if (status != sd.sd_dart_gpu_status.SD_DART_GPU_OK.value) { + return null; + } + final memory = out.ref; + final name = _text(memory.name, 64); + final description = _text(memory.description, 256); + return ( + name: description.isEmpty ? name : '$name ($description)', + totalBytes: memory.total_bytes, + freeBytes: memory.free_bytes, + integrated: + memory.type == + sd.sd_dart_gpu_device_type.SD_DART_GPU_DEVICE_INTEGRATED.value, + ); + }); +} + +/// The memory a new image model can use on the GPU [memory] describes, or +/// `null` when it is not known. +/// +/// - A discrete GPU whose driver reports a budget (`VK_EXT_memory_budget`): +/// its free memory, which is what this process can still allocate there +/// and so accounts for other processes and for models already loaded. +/// - A discrete GPU without one: its total memory. The runtime then reports +/// the total as free, so equal figures mean "not reported", and so does a +/// free figure of 0, which a driver whose budget is below the process's use +/// gives. Only a model that cannot fit the device at all is refused. +/// - An integrated GPU: [hostBudget], the figure the CPU gets. Its memory is +/// host memory, and a driver that exposes that as several heaps has it +/// counted more than once in the device's figures, so they are not used. +/// `null` where host memory is not read, as on Windows. +ImageGenerationMemoryBudget? stableDiffusionGpuMemoryBudget( + StableDiffusionGpuMemory? memory, { + required ImageGenerationMemoryBudget? Function() hostBudget, +}) { + if (memory == null || memory.totalBytes <= 0) { + return null; + } + if (memory.integrated) { + final host = hostBudget(); + return host == null + ? null + : ( + bytes: host.bytes, + source: + '${host.source}; ${memory.name} is an integrated GPU, which ' + 'uses host memory', + ); + } + final total = '${_gib(memory.totalBytes)} GiB'; + if (memory.freeBytes > 0 && memory.freeBytes < memory.totalBytes) { + return ( + bytes: memory.freeBytes, + source: 'free GPU memory of ${memory.name}, out of $total', + ); + } + return ( + bytes: memory.totalBytes, + source: + 'the GPU memory of ${memory.name}, whose driver does not report how ' + 'much of it is free', + ); +} + +String _gib(int bytes) { + final gib = bytes / (1 << 30); + return gib.toStringAsFixed(gib < 10 ? 2 : 1); +} + +String _text(Array characters, int length) { + final bytes = []; + for (var i = 0; i < length; i++) { + final byte = characters[i] & 0xff; + if (byte == 0) { + break; + } + bytes.add(byte); + } + return utf8.decode(bytes, allowMalformed: true); +} + +String? _environmentVariable(String name) => Platform.environment[name]; + const String _memAvailableSource = 'MemAvailable in /proc/meminfo'; (int?, String) _androidMemoryBudget(String? memInfo, String? status) { 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 23580a65c..8cd51da68 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -4,9 +4,11 @@ import 'dart:io'; import 'package:ffi/ffi.dart'; import '../../core/exceptions.dart'; +import '../../core/models/config/log_level.dart'; import '../windows_runtime_libraries.dart'; import 'stable_diffusion_bindings.dart' as sd; import 'stable_diffusion_calls.dart'; +import 'stable_diffusion_log.dart'; import 'stable_diffusion_runtime_status.dart'; /// The native calls the probe makes; tests substitute a fake. @@ -17,6 +19,11 @@ abstract interface class StableDiffusionNativeApi { /// `sd_commit()`. String commit(); + /// Starts the runtime's log recorder at [level], where the runtime has + /// one: from then on its messages, ggml's among them, are recorded and not + /// printed to stderr. + void recordLog(LlamaLogLevel level); + /// `sd_list_devices()` output. String listDevices(); @@ -63,6 +70,12 @@ const Set stableDiffusionPublishedAbis = { /// which a release older than [StableDiffusionCalls.minimumNativeRelease] /// does not. /// +/// `sd_list_devices` initializes the GPU backend, which logs through ggml. +/// The runtime's log recorder is registered before it, at [logLevel], so +/// those messages are recorded for the next image worker to forward instead +/// of going to stderr, and the registration, which is not synchronized, +/// never runs beside a device initialization. +/// /// [abi], [readCpuInfo], [windowsHasAvx2], [missingWindowsLibraries] and /// [api] default to the host and the bundled library; tests replace them. StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ @@ -72,6 +85,7 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ List Function(List names) missingWindowsLibraries = findMissingWindowsLibraries, StableDiffusionNativeApi api = const _BundledStableDiffusionApi(), + LlamaLogLevel logLevel = LlamaLogLevel.none, }) { final targetAbi = abi ?? Abi.current(); final platform = _abiLabel(targetAbi); @@ -135,6 +149,7 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ try { final version = api.version(); final commit = api.commit(); + api.recordLog(logLevel); final devices = parseStableDiffusionDeviceList(api.listDevices()); if (!api.exportsWrapperCalls()) { return StableDiffusionRuntimeStatus.unavailable( @@ -314,6 +329,14 @@ final class _BundledStableDiffusionApi implements StableDiffusionNativeApi { @override String commit() => _string(sd.sd_commit()); + @override + void recordLog(LlamaLogLevel level) { + final log = StableDiffusionCalls.tryResolve()?.log; + if (log != null) { + recordStableDiffusionLog(log, level); + } + } + @override String listDevices() { final size = sd.sd_list_devices(nullptr, 0); diff --git a/lib/src/core/image/image_generation_driver.dart b/lib/src/core/image/image_generation_driver.dart index 33c5a7af9..819748f95 100644 --- a/lib/src/core/image/image_generation_driver.dart +++ b/lib/src/core/image/image_generation_driver.dart @@ -96,8 +96,8 @@ enum ImageGenerationComputeDevice { /// recommended working set. metal, - /// Any other GPU, such as Vulkan: its own device memory, which the runtime - /// does not report. + /// Any other GPU, such as Vulkan: its own device memory as the runtime + /// reports it, or host memory when the GPU is an integrated one. otherGpu, } @@ -142,14 +142,18 @@ abstract interface class ImageGenerationDriver { Future readFileRange(String path, int offset, int length); /// Memory available to a new model on [device], or `null` when it is not - /// known. - ImageGenerationMemoryBudget? memoryBudget( + /// known. Asking a GPU other than Metal is a native call that can block, so + /// on native platforms it runs in a short-lived isolate. + Future memoryBudget( ImageGenerationComputeDevice device, ); - /// Loads a native context. + /// Loads a native context. On native platforms the runtime's messages + /// reach `LlamaLogger` from then on, at the levels `LlamaLogging` has when + /// this is called. /// - /// Throws `LlamaModelException` when the runtime rejects the files. + /// Throws `LlamaModelException` when the runtime rejects the files, with + /// the runtime's reason when it gives one. Future start(ImageGenerationSessionConfig config); } diff --git a/lib/src/core/image/image_generation_driver_io.dart b/lib/src/core/image/image_generation_driver_io.dart index c45616a92..b5a8a13ec 100644 --- a/lib/src/core/image/image_generation_driver_io.dart +++ b/lib/src/core/image/image_generation_driver_io.dart @@ -5,21 +5,57 @@ import '../../backends/stable_diffusion/stable_diffusion_image_worker.dart'; import '../../backends/stable_diffusion/stable_diffusion_memory.dart'; import '../../backends/stable_diffusion/stable_diffusion_runtime_io.dart'; import '../../backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import '../llama_logging.dart'; +import '../models/config/log_level.dart'; import 'image_generation_driver.dart'; +/// Probes the runtime, recording its log at a level. +typedef ImageRuntimeProbe = + StableDiffusionRuntimeStatus Function({LlamaLogLevel logLevel}); + +/// Reads the memory of the default GPU, recording the runtime's log at a +/// level. +typedef ImageGpuMemoryReader = + StableDiffusionGpuMemory? Function({LlamaLogLevel logLevel}); + /// Creates the driver for the bundled stable_diffusion runtime. -ImageGenerationDriver createImageGenerationDriver() => - const _NativeImageGenerationDriver(); +/// +/// [probe] and [readGpuMemory] run in a short-lived isolate, so they have to +/// be top-level or static functions; tests replace them. +ImageGenerationDriver createImageGenerationDriver({ + ImageRuntimeProbe probe = probeStableDiffusionRuntime, + ImageGpuMemoryReader readGpuMemory = readStableDiffusionGpuMemory, +}) => _NativeImageGenerationDriver(probe, readGpuMemory); + +/// The level the runtime records its messages at. They reach the app +/// through `LlamaLogger`, so one has to pass both [LlamaLogging.nativeLevel] +/// and [LlamaLogging.level]: the runtime records from the stricter of the +/// two, and nothing when either is [LlamaLogLevel.none]. +LlamaLogLevel imageRuntimeLogLevel() { + final dart = LlamaLogging.level; + final native = LlamaLogging.nativeLevel; + if (dart == LlamaLogLevel.none || native == LlamaLogLevel.none) { + return LlamaLogLevel.none; + } + return dart.index > native.index ? dart : native; +} class _NativeImageGenerationDriver implements ImageGenerationDriver { - const _NativeImageGenerationDriver(); + const _NativeImageGenerationDriver(this._probe, this._readGpuMemory); + + final ImageRuntimeProbe _probe; + final ImageGpuMemoryReader _readGpuMemory; @override - StableDiffusionRuntimeStatus probe() => probeStableDiffusionRuntime(); + StableDiffusionRuntimeStatus probe() => + _probe(logLevel: imageRuntimeLogLevel()); @override - Future probeInBackground() => - Isolate.run(probeStableDiffusionRuntime); + Future probeInBackground() { + final probe = _probe; + final logLevel = imageRuntimeLogLevel(); + return Isolate.run(() => probe(logLevel: logLevel)); + } @override int? fileSize(String path) => stableDiffusionFileSize(path); @@ -29,11 +65,26 @@ class _NativeImageGenerationDriver implements ImageGenerationDriver { readStableDiffusionFileRange(path, offset, length); @override - ImageGenerationMemoryBudget? memoryBudget( + Future memoryBudget( ImageGenerationComputeDevice device, - ) => readStableDiffusionMemoryBudget(device: device); + ) async { + if (device != ImageGenerationComputeDevice.otherGpu) { + return readStableDiffusionMemoryBudget(device: device); + } + final readGpuMemory = _readGpuMemory; + final logLevel = imageRuntimeLogLevel(); + return stableDiffusionGpuMemoryBudget( + // The query is a native call that can block: the first one in a + // process initializes the GPU backend. + await Isolate.run(() => readGpuMemory(logLevel: logLevel)), + hostBudget: readStableDiffusionMemoryBudget, + ); + } @override Future start(ImageGenerationSessionConfig config) => - StableDiffusionImageWorker.start(config); + StableDiffusionImageWorker.start( + config, + logLevel: imageRuntimeLogLevel(), + ); } diff --git a/lib/src/core/image/image_generation_driver_stub.dart b/lib/src/core/image/image_generation_driver_stub.dart index bd212537c..f3e0fa1fa 100644 --- a/lib/src/core/image/image_generation_driver_stub.dart +++ b/lib/src/core/image/image_generation_driver_stub.dart @@ -26,9 +26,9 @@ class _UnsupportedImageGenerationDriver implements ImageGenerationDriver { Future.error(probe().unavailableReason!); @override - ImageGenerationMemoryBudget? memoryBudget( + Future memoryBudget( ImageGenerationComputeDevice device, - ) => null; + ) async => null; @override Future start(ImageGenerationSessionConfig config) => diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index cd10b19af..6430864d8 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -157,9 +157,11 @@ class ImageGenerationTask { /// in the same isolate; do not generate from engines in different isolates /// at the same time. /// -/// Runtime logs are not forwarded to `LlamaLogger` yet: stable-diffusion.cpp -/// passes log text that is only valid during a call made from its own -/// threads. +/// The runtime's messages reach the handler of `LlamaLogging.configure` when +/// both of its levels admit them; a load takes the levels it finds. They +/// arrive after each load and generation and at [dispose], not while one +/// runs, and name model files by role. At the default levels the runtime +/// logs nothing, to stderr either. /// /// ```dart /// final engine = await ImageGenerationEngine.load( @@ -308,10 +310,15 @@ class ImageGenerationEngine { /// available: on Android the larger of `MemAvailable` and half of physical /// memory less what the app already holds, `MemAvailable` on Linux, the /// app's remaining memory limit on iOS, and physical memory on macOS, - /// capped on Metal by the GPU's recommended working set. Windows, and GPUs - /// other than Metal (whose device memory the runtime does not report), are - /// not checked. A model that does not fit throws [LlamaModelException] - /// naming both figures, instead of letting the system kill the app. + /// capped on Metal by the GPU's recommended working set. On a Vulkan GPU + /// it is the GPU's free memory when its driver reports that, its total + /// memory otherwise, and for an integrated GPU the host figure of its + /// platform; the GPU is asked off the calling isolate. The Windows CPU, an + /// integrated GPU on Windows, a GPU that does not report its memory and a + /// load with the `SD_VK_DEVICE` environment variable set are not checked. A + /// model that does not fit throws [LlamaModelException] naming both + /// figures, instead of letting the system kill the app or, on a Vulkan + /// GPU, the runtime keep the weights that do not fit in host memory. /// /// [download]'s cancel token stops a download at once and is checked again /// after classification and after the native load; the native load itself @@ -335,8 +342,8 @@ class ImageGenerationEngine { /// component (such as a LoRA or ControlNet), shares a role with another /// file, or does not match the diffusion model; when no file holds /// diffusion weights; when the model does not fit; when the runtime - /// cannot load it; and what the download manager throws for a failed - /// download. + /// cannot load it, with the reason the runtime logged when it logged + /// one; and what the download manager throws for a failed download. /// - [LlamaStateException] when [download]'s cancel token cancels the /// load, and while another generation or load is running. /// - [LlamaArgumentException] when [download] sets a bearer token or @@ -409,7 +416,7 @@ class ImageGenerationEngine { if (params.checkMemory) { _checkMemory( weightBytes, - driver.memoryBudget(switch (backendName) { + await driver.memoryBudget(switch (backendName) { _ when _isMetal(backendName) => ImageGenerationComputeDevice.metal, _ when _isGpu(backendName) => ImageGenerationComputeDevice.otherGpu, _ => ImageGenerationComputeDevice.cpu, @@ -561,7 +568,7 @@ class ImageGenerationEngine { /// one sampling step and a decode at that size: about 2 to 4 s for /// SDXL-Lightning with TAESDXL on an M4 Max, and the same peak memory as /// an image, which the memory check in [load] covers where it runs (not - /// on Vulkan or the Windows CPU). + /// on the Windows CPU). /// /// On the CPU there is nothing to compile, so this returns at once. /// diff --git a/lib/src/core/llama_logging.dart b/lib/src/core/llama_logging.dart index 799ad6bbf..42b1304c0 100644 --- a/lib/src/core/llama_logging.dart +++ b/lib/src/core/llama_logging.dart @@ -37,6 +37,11 @@ abstract final class LlamaLogging { /// printed, not thrown. Some native output, such as the LiteRT-LM WebGPU /// accelerator's, ignores [nativeLevel]; see /// https://llamadart.leehack.com/docs/configuration/logging. + /// + /// The stable_diffusion runtime of `ImageGenerationEngine` records its + /// messages from the stricter of the two levels and hands them to + /// [handler] after each load and generation. It takes the levels when a + /// model loads, so a later call applies to the next load. static Future configure({ LlamaLogLevel level = LlamaLogLevel.none, LlamaLogLevel? nativeLevel, diff --git a/lib/src/hook/native_release_pins.dart b/lib/src/hook/native_release_pins.dart index d14665680..a31840ccb 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-1'; +const stableDiffusionReleaseTag = 'v0.2.0-2'; /// stable_diffusion cache directory version derived from /// [stableDiffusionReleaseTag]. -const stableDiffusionVersion = '0.2.0-1'; +const stableDiffusionVersion = '0.2.0-2'; /// 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: 'a0bef58480c213a87dffb72f02bd47a89366510b7ac24f64120e2cfd64ed2c76', + sha256: 'd20f4b32a7dbf391c6b1f88f04151410e27ea4b331af6c17d8aba5508c7dfe99', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'ios-arm64', - sha256: '82ebb318d695db75d6b384d84aaddb69a2dd369cf68e8411dc345c32e423a714', + sha256: 'b4bcd75f314ee578f18217cbe9cdc505c93318acf4364fc45d01d99fa7ec2ee9', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'ios-arm64-sim', - sha256: 'b6fa5ac2d35503d4183bf083ce10ed7a6c54a5a8db2eabfbaed5bfda8686d397', + sha256: '2776e5d8ca5f02fad338267eaa644cfa73240d3ec982f979e5b5be46a9a74ae5', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'ios-x64-sim', - sha256: '1789de5de4c36821b677cff95307f5522d190c6621eeca86fccbc0880ebf27ed', + sha256: '7f304084fc47bc97c91613046a93d497f22a3b9669eeaf2e75dc5bdf4c4e1341', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'macos-arm64', - sha256: '931f53883c1a31092e28d565c23e5b23e16fba655e1dc000621996d69f8721b1', + sha256: '04352812a03e403fa110aec788c1e25f133fff9e33b4617877e6434c2c881a60', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'macos-x64', - sha256: '9c5c4d93c9ee6f4640f758a62ff3cfd4aa9ec28e0a6ae01aa12029a5104f7745', + sha256: '317a908c3903af35f588ca2e077ac6c3bfcfbd9ba5dc0d56dcf2afc999f9af67', requiredLibraries: {'libstable-diffusion.dylib'}, ), StableDiffusionBundleSpec( 'linux-arm64', - sha256: 'a32fac5728322e4d3aa985868bae6dcc7a1eda41a2a7cb322021c7a3302bec4d', + sha256: '355d582709bc01d4ea7ec1683160e84eceaf8906aa1fbadbb633f72426d78a55', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-arm64-vulkan', - sha256: 'ff9383e61f183ce5fc005a5bede927c57df35e701f690e70d68b741d9ed06cae', + sha256: '2af80b1a7b8e14e503bc2295e462f888f521e6a429e331b4bf4b7d081b251785', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-x64', - sha256: 'acad806da58a9aedf9e549bd8f949b24cef0535fca0d7b0870b4093ef6bcb103', + sha256: '2c850bd7f06abd562416049daca3b141968a2bd967d88c194ce20b249b9971fc', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'linux-x64-vulkan', - sha256: '731008d6df747527ec91525d59ca44077f0b97ff0b16849ab77a410787336b0b', + sha256: '97e684a0c89b069fbae289dcf19d40aad9c803b545c8c391cbb739eab7eb15a9', requiredLibraries: {'libstable-diffusion.so'}, ), StableDiffusionBundleSpec( 'windows-x64', - sha256: '3aa4028117330149cbb3c6b739841145381a9e0e9fba9e45c0a58c70c31d671a', + sha256: '8b0a1d79ee6888e92cf41ccaa6a2a49ab88d086df3701cdd3a7b4bf36fa08f4b', requiredLibraries: {'stable-diffusion.dll'}, ), StableDiffusionBundleSpec( 'windows-x64-vulkan', - sha256: '127234dcce7ab84a8ba740dfdd57206a0587c2b54edf5683335bae7b06776de3', + sha256: 'ccd0c3c7b6508d9af136e061cc5bce7cd78a1e9a45837aaeddc9f1233303dcc1', requiredLibraries: {'stable-diffusion.dll'}, ), ]; diff --git a/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md b/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md index 0eb060e05..4bbc39e25 100644 --- a/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md +++ b/packages/llamadart_stable_diffusion_flutter/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +* Updated Apple SwiftPM native pin to `leehack/stable-diffusion-native@v0.2.0-2`. + ## 0.0.2 * Updated Apple SwiftPM native pin to `leehack/stable-diffusion-native@v0.2.0-1`, diff --git a/packages/llamadart_stable_diffusion_flutter/README.md b/packages/llamadart_stable_diffusion_flutter/README.md index f5d00e83f..b8a724347 100644 --- a/packages/llamadart_stable_diffusion_flutter/README.md +++ b/packages/llamadart_stable_diffusion_flutter/README.md @@ -28,7 +28,7 @@ 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-1`. +The Apple SwiftPM manifest pins `leehack/stable-diffusion-native@v0.2.0-2`. Apps bound for the App Store should use this package: an Apple privacy manifest for the stable-diffusion.cpp runtime ships inside this XCFramework, 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 37186f3ee..c0f625505 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-1" +let stableDiffusionTag = "v0.2.0-2" 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: "32c571e9c5204f1e8d2cdbae2371e3fac80bd1170715366e622d657cdca7a39b" + checksum: "e82716cea4f747c68b8e9565bf08848f827939810ce550eadc8e1c1bcadb3ae3" ), .target( name: "llamadart_stable_diffusion_flutter", diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index 91fa89e81..a558266e3 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -135,8 +135,11 @@ description: >- exceeds the device figure with `LlamaModelException`: on Android the larger of `MemAvailable` and half of `MemTotal` less the app's own memory, `MemAvailable` on Linux CPU, the app's limit on iOS, physical memory on - macOS, capped on Metal by the GPU's recommended working set. Vulkan GPUs and - Windows are not checked (GPU memory is not reported). SD-Turbo usually + macOS, capped on Metal by the GPU's recommended working set. On a Vulkan + GPU (Linux, Windows) it is the GPU's free memory when the driver reports + one, otherwise its total; an integrated GPU gets the host figure. The + Windows CPU and integrated GPUs on Windows are not checked, and the Vulkan + check has not run on a physical GPU yet. SD-Turbo usually loads on 8 GB Android phones when no chat model is loaded, and is usually refused on 6 GB ones; offer SDXS there. - `ImageModelParams(device: ComputeDevice.auto | cpu | gpu, threads: 0)`. @@ -211,10 +214,15 @@ description: >- - A runtime failure (for example an aborted Metal command buffer or out of memory) fails the task with `LlamaInferenceException`; the engine stays usable for the next request. -- Runtime logs are not forwarded to `LlamaLogger`, so a runtime load - failure (`LlamaModelException`) cannot quote stable-diffusion.cpp's reason. - For a split checkpoint it names the missing roles (no `vae`/`taesd`, no - text encoder); otherwise check that each file is in its role. +- A load the runtime rejects (`LlamaModelException`) quotes the errors + stable-diffusion.cpp logged, with files named by role, such as + ``. For a split checkpoint it also names the missing roles + (no `vae`/`taesd`, no text encoder); a file in the wrong role only gets + `get sd version from file failed`, so check that each file is in its role. +- Runtime messages reach the `LlamaLogging.configure` handler when both + `level` and `nativeLevel` admit them (default `none`: nothing is logged, + to stderr either). Configure before `load`; messages arrive after each + load and generation, not during one. ## Examples diff --git a/test/support/fake_stable_diffusion_runtime.dart b/test/support/fake_stable_diffusion_runtime.dart index adb6eac81..449d121d9 100644 --- a/test/support/fake_stable_diffusion_runtime.dart +++ b/test/support/fake_stable_diffusion_runtime.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:ffi'; import 'dart:io'; import 'dart:isolate'; @@ -24,12 +25,38 @@ const _pauseAfter = 8; const _loadReports = 12; const _decodeReports = 16; const _reportsPerRead = 20; +const _olderRelease = 24; +const _logEnabled = 25; +const _quietReject = 26; const _racingReads = 28; const _latest = 32; const _modelVersion = 40; const _ring = 64; const _ringSlots = 16384; -const _stateBytes = _ring + _ringSlots * 8; +const _logState = _ring + _ringSlots * 8; +const _logThreshold = _logState; +const _logHistory = _logState + 4; +const _logLatest = _logState + 8; +const _logReadTo = _logState + 16; +const _logDropped = _logState + 24; +const _gpuStatus = _logState + 32; +const _gpuType = _logState + 36; +const _gpuTotal = _logState + 40; +const _gpuFree = _logState + 48; +const _lastErrorLength = _logState + 56; +const _lastError = _logState + 64; +const _lastErrorBytes = 1024; +const _modelPath = _lastError + _lastErrorBytes; +const _modelPathBytes = 512; +const _logSlots = _modelPath + _modelPathBytes; +const _logSlotCount = 256; +const _logSlotBytes = 512; +const _stateBytes = _logSlots + _logSlotCount * _logSlotBytes; + +// sd_log_level_t. +const _sdLogDebug = 0; +const _sdLogInfo = 2; +const _sdLogError = 4; /// A stand-in for the stable_diffusion runtime, shared by the two isolates of /// a `StableDiffusionImageWorker`. @@ -41,12 +68,24 @@ const _stateBytes = _ring + _ringSlots * 8; /// 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. +/// +/// It logs the way the runtime of `StableDiffusionCalls.optionalNativeRelease` +/// does once its recorder is enabled: a load logs the file it loads at +/// `SD_LOG_INFO` and why it failed at `SD_LOG_ERROR`, and a generation logs +/// one `SD_LOG_DEBUG` and one `SD_LOG_INFO` message. Messages below the level +/// set are not recorded, and the oldest ones leave when more than +/// `logHistory` are kept. final class FakeStableDiffusionRuntime { - /// Creates a runtime that keeps [history] progress reports. + /// Creates a runtime that keeps [history] progress reports and [logHistory] + /// log messages. FakeStableDiffusionRuntime({ this.history = StableDiffusionCalls.progressHistory, + int logHistory = 64, }) : _state = calloc(_stateBytes) { _state.cast()[_pauseAfter ~/ 4] = -1; + _state.cast()[_logThreshold ~/ 4] = _sdLogInfo; + _state.cast()[_logHistory ~/ 4] = logHistory; + _state.cast()[_gpuStatus ~/ 4] = -2; final version = 'SD 2.x'.codeUnits; for (var i = 0; i < version.length; i++) { _state[_modelVersion + i] = version[i]; @@ -74,6 +113,42 @@ final class FakeStableDiffusionRuntime { /// Makes the load fail. set rejectLoad(bool value) => _state[_rejectLoad] = value ? 1 : 0; + /// Makes a failed load log no error. + set quietReject(bool value) => _state[_quietReject] = value ? 1 : 0; + + /// Makes [resolver] return the calls of a runtime older than + /// `StableDiffusionCalls.optionalNativeRelease`: no log and no device + /// memory. + set olderRelease(bool value) => _state[_olderRelease] = value ? 1 : 0; + + /// What `sd_dart_gpu_device_memory` answers for the default device: a + /// [status] other than 0 (`SD_DART_GPU_NO_BACKEND` at first) and nothing + /// else, or `Vulkan0`, a `Fake GPU`, with [total] and [free] bytes. + void setGpuMemory({ + int status = 0, + int total = 0, + int free = 0, + bool integrated = false, + }) { + _state.cast()[_gpuStatus ~/ 4] = status; + _state.cast()[_gpuType ~/ 4] = integrated ? 2 : 1; + _state.cast()[_gpuTotal ~/ 8] = total; + _state.cast()[_gpuFree ~/ 8] = free; + } + + /// The model path the last load read from its context parameters, or an + /// empty string when they had none. + String get loadedModelPath => + Pointer.fromAddress(_state.address + _modelPath).toDartString(); + + /// Records [bytes] as a log message at `sd_log_level_t` [level], as a + /// thread of the runtime does. + void log(int level, List bytes) => _FakeCalls( + _state.address, + _port.sendPort, + history, + )._logMessage(level, bytes); + /// Makes the loaded model one that cannot generate images. set videoOnly(bool value) => _state[_videoOnly] = value ? 1 : 0; @@ -198,6 +273,133 @@ final class _FakeCalls { return expected ? '+held' : '+held-wrong'; } + Pointer get _longs => _state.cast(); + + Pointer _logSlot(int sequence) => + _state + _logSlots + (sequence % _logSlotCount) * _logSlotBytes; + + /// Records a message when the recorder is enabled and [level] reaches the + /// level set. The oldest message kept leaves when there are too many, and + /// counts as dropped when no read had reached it. + void _logMessage(int level, List bytes) { + if (_state[_logEnabled] == 0 || level < _ints[_logThreshold ~/ 4]) { + return; + } + final sequence = ++_longs[_logLatest ~/ 8]; + final slot = _logSlot(sequence); + slot.cast()[0] = level; + slot.cast()[1] = bytes.length; + (slot + 8).asTypedList(bytes.length).setAll(0, bytes); + final gone = sequence - _ints[_logHistory ~/ 4]; + if (gone > _longs[_logReadTo ~/ 8]) { + _longs[_logDropped ~/ 8]++; + } + } + + void _logText(int level, String text) => + _logMessage(level, utf8.encode(text)); + + int _logRead( + int after, + Pointer text, + int capacity, + Pointer level, + Pointer length, + ) { + _record('sd_dart_log_read'); + final newest = _longs[_logLatest ~/ 8]; + final oldest = newest - _ints[_logHistory ~/ 4] + 1; + final sequence = after + 1 > oldest ? after + 1 : oldest; + if (sequence > newest) { + return 0; + } + final slot = _logSlot(sequence); + final size = slot.cast()[1]; + final copied = size < capacity ? size : capacity - 1; + text.cast().asTypedList(capacity) + ..setRange(0, copied, (slot + 8).asTypedList(copied)) + ..[copied] = 0; + level.value = slot.cast()[0]; + if (length != nullptr) { + length.value = size; + } + if (sequence > _longs[_logReadTo ~/ 8]) { + _longs[_logReadTo ~/ 8] = sequence; + } + return sequence; + } + + int _readLastError(Pointer text, int capacity) { + _record('sd_dart_last_error'); + final size = _ints[_lastErrorLength ~/ 4]; + text.cast().asTypedList(capacity) + ..setRange(0, size, (_state + _lastError).asTypedList(size)) + ..[size] = 0; + return size; + } + + int _gpuDeviceMemory( + int deviceIndex, + Pointer out, + ) { + _record( + _state[_logEnabled] != 0 + ? 'sd_dart_gpu_device_memory:$deviceIndex' + : 'sd_dart_gpu_device_memory:$deviceIndex:before-log-enable', + ); + final status = _ints[_gpuStatus ~/ 4]; + if (status != 0) { + return status; + } + out.ref + ..total_bytes = _longs[_gpuTotal ~/ 8] + ..free_bytes = _longs[_gpuFree ~/ 8] + ..type = _ints[_gpuType ~/ 4]; + for (final (index, unit) in 'Vulkan0'.codeUnits.indexed) { + out.ref.name[index] = unit; + } + for (final (index, unit) in 'Fake GPU'.codeUnits.indexed) { + out.ref.description[index] = unit; + } + return 0; + } + + Pointer _newContext(Pointer params) { + _record( + _state[_enabled] != 0 + ? 'sd_dart_new_sd_ctx' + : 'sd_dart_new_sd_ctx:before-enable', + ); + final modelPath = params.ref.model_path == nullptr + ? '' + : params.ref.model_path.cast().toDartString(); + (_state + _modelPath).asTypedList(_modelPathBytes) + ..fillRange(0, _modelPathBytes, 0) + ..setAll(0, utf8.encode(modelPath)); + _ints[_lastErrorLength ~/ 4] = 0; + _logText( + _sdLogInfo, + "stable-diffusion.cpp:262 - loading model from '$modelPath'", + ); + if (_state[_rejectLoad] != 0) { + if (_state[_quietReject] == 0 && _state[_logEnabled] != 0) { + final error = utf8.encode( + "model_loader.cpp:1061 - cannot inspect model source '$modelPath': " + 'No such file or directory', + ); + _logMessage(_sdLogError, error); + _ints[_lastErrorLength ~/ 4] = error.length; + (_state + _lastError).asTypedList(error.length).setAll(0, error); + } + return nullptr; + } + final reports = _ints[_loadReports ~/ 4]; + for (var i = 1; i <= reports; i++) { + _report(i, reports); + } + return malloc(16).cast(); + } + void _report(int step, int steps) { final sequence = _latestSequence.value + 1; final slot = Pointer.fromAddress( @@ -218,21 +420,7 @@ final class _FakeCalls { _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(); - }, + newContext: _newContext, generateImage: _generateImage, cancelGeneration: (context) { _record('sd_dart_cancel_generation'); @@ -243,7 +431,11 @@ final class _FakeCalls { malloc.free(context); }, exitFreeAddress: malloc.nativeFree, - contextParamsInit: (params) => _record('sd_ctx_params_init'), + contextParamsInit: (params) { + _record('sd_ctx_params_init'); + // What sd_ctx_params_init leaves, whatever the caller wrote before. + params.ref.model_path = nullptr; + }, supportsImageGeneration: (context) { _record('sd_ctx_supports_image_generation$_held'); return _state[_videoOnly] == 0; @@ -261,6 +453,25 @@ final class _FakeCalls { } malloc.free(images); }, + log: _state[_olderRelease] != 0 + ? null + : StableDiffusionLogCalls( + enable: () { + _record('sd_dart_log_enable'); + _state[_logEnabled] = 1; + }, + setLevel: (level) { + _record('sd_dart_log_set_level:$level'); + _ints[_logThreshold ~/ 4] = level; + }, + read: _logRead, + dropped: () { + _record('sd_dart_log_dropped'); + return _longs[_logDropped ~/ 8]; + }, + lastError: _readLastError, + ), + gpuDeviceMemory: _state[_olderRelease] != 0 ? null : _gpuDeviceMemory, ); } @@ -320,6 +531,8 @@ final class _FakeCalls { Pointer countOut, ) { _record('sd_dart_generate_image$_held'); + _logText(_sdLogDebug, 'stable-diffusion.cpp:3120 - sampling'); + _logText(_sdLogInfo, 'stable-diffusion.cpp:3391 - generating'); imagesOut.value = nullptr; countOut.value = 0; _waitWhile(() => _state[_holdStart] != 0); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart index c904821bc..1daaf2476 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart @@ -23,6 +23,16 @@ const _symbols = [ 'sd_dart_exit_free', ]; +// The exports of stable-diffusion-native v0.2.0-2 it works without. +const _logSymbols = [ + 'sd_dart_log_enable', + 'sd_dart_log_set_level', + 'sd_dart_log_read', + 'sd_dart_log_dropped', + 'sd_dart_last_error', +]; +const _deviceMemorySymbols = ['sd_dart_gpu_device_memory']; + // 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 @@ -37,7 +47,10 @@ void main() { } expect(StableDiffusionCalls.tryResolve(symbol: exported), isNotNull); - expect(requested, unorderedEquals(_symbols)); + expect( + requested, + unorderedEquals([..._symbols, ..._logSymbols, ..._deviceMemorySymbols]), + ); expect(StableDiffusionCalls.wrapperSymbols, unorderedEquals(_symbols)); for (final missing in _symbols) { @@ -53,6 +66,45 @@ void main() { } }); + test('a runtime of v0.2.0-1, without the log and device memory functions, ' + 'resolves with both absent', () { + final calls = StableDiffusionCalls.tryResolve( + symbol: (name) => _symbols.contains(name) + ? Pointer.fromAddress(0x1000) + : throw ArgumentError("Couldn't resolve native function '$name'"), + ); + + expect(calls, isNotNull); + expect(calls!.log, isNull); + expect(calls.gpuDeviceMemory, isNull); + }); + + test('the log is bound only when the runtime exports all of its ' + 'functions, and the device memory query on its own', () { + expect(StableDiffusionCalls.logSymbols, unorderedEquals(_logSymbols)); + expect( + StableDiffusionCalls.deviceMemorySymbols, + unorderedEquals(_deviceMemorySymbols), + ); + expect(StableDiffusionCalls.optionalNativeRelease, 'v0.2.0-2'); + + StableDiffusionCalls without(String missing) => + StableDiffusionCalls.tryResolve( + symbol: (name) => name == missing + ? throw ArgumentError("Couldn't resolve native function '$name'") + : Pointer.fromAddress(0x1000), + )!; + + for (final missing in _logSymbols) { + final calls = without(missing); + expect(calls.log, isNull, reason: missing); + expect(calls.gpuDeviceMemory, isNotNull, reason: missing); + } + final calls = without(_deviceMemorySymbols.single); + expect(calls.gpuDeviceMemory, isNull); + expect(calls.log, isNotNull); + }); + test('calls the function exported under the name of each of its ' 'members', () { final exports = _RecordingExports(); @@ -66,6 +118,14 @@ void main() { calls.generateImage(nullptr, nullptr, nullptr, nullptr), 'sd_dart_cancel_generation': () => calls.cancelGeneration(nullptr), 'sd_dart_exit_free': () => calls.exitFree(nullptr), + 'sd_dart_log_enable': calls.log!.enable, + 'sd_dart_log_set_level': () => calls.log!.setLevel(3), + 'sd_dart_log_read': () => + expect(calls.log!.read(41, nullptr, 0, nullptr, nullptr), 42), + 'sd_dart_log_dropped': () => expect(calls.log!.dropped(), 7), + 'sd_dart_last_error': () => expect(calls.log!.lastError(nullptr, 9), 9), + 'sd_dart_gpu_device_memory': () => + expect(calls.gpuDeviceMemory!(-1, nullptr), -3), }; for (final MapEntry(key: name, value: call) in members.entries) { exports.called.clear(); @@ -73,6 +133,8 @@ void main() { expect(exports.called, [name]); } expect(exports.cancelMode, sd.sd_cancel_mode_t.SD_CANCEL_ALL.value); + expect(exports.logLevel, 3); + expect(exports.deviceIndex, -1); expect(calls.exitFreeAddress, exports.symbol('sd_dart_exit_free')); // sd_dart_progress_read is a leaf call, which cannot call back into @@ -107,6 +169,9 @@ void main() { for (final symbol in _symbols) { expect(message, contains(symbol)); } + for (final symbol in [..._logSymbols, ..._deviceMemorySymbols]) { + expect(message, isNot(contains(symbol))); + } expect(message, contains('stable-diffusion-native v0.2.0-1 or later')); expect(message, contains('pinned release $stableDiffusionReleaseTag')); }); @@ -128,6 +193,8 @@ void main() { } }); + // sd_dart_log_read and sd_dart_last_error can wait 100 ms for another + // thread, and the first device query initializes the GPU backend. test('bind only sd_dart_progress_read as a leaf call', () { final leaves = RegExp( r'isLeaf: true\)\s*external \w[\w<>.]* (\w+)\(', @@ -144,6 +211,8 @@ void main() { final class _RecordingExports { final List called = []; int? cancelMode; + int? logLevel; + int? deviceIndex; late final Map> _functions = { 'sd_dart_progress_enable': NativeCallable.isolateLocal( @@ -184,6 +253,51 @@ final class _RecordingExports { NativeCallable)>.isolateLocal( (Pointer _) => _record('sd_dart_exit_free', null), ), + 'sd_dart_log_enable': NativeCallable.isolateLocal( + () => _record('sd_dart_log_enable', null), + ), + 'sd_dart_log_set_level': NativeCallable.isolateLocal(( + int level, + ) { + logLevel = level; + _record('sd_dart_log_set_level', null); + }), + 'sd_dart_log_read': + NativeCallable< + Uint64 Function( + Uint64, + Pointer, + Size, + Pointer, + Pointer, + ) + >.isolateLocal( + ( + int after, + Pointer _, + int _, + Pointer _, + Pointer _, + ) => _record('sd_dart_log_read', after + 1), + exceptionalReturn: 0, + ), + 'sd_dart_log_dropped': NativeCallable.isolateLocal( + () => _record('sd_dart_log_dropped', 7), + exceptionalReturn: 0, + ), + 'sd_dart_last_error': + NativeCallable, Size)>.isolateLocal( + (Pointer _, int capacity) => + _record('sd_dart_last_error', capacity), + exceptionalReturn: 0, + ), + 'sd_dart_gpu_device_memory': + NativeCallable< + Int32 Function(Int32, Pointer) + >.isolateLocal((int index, Pointer _) { + deviceIndex = index; + return _record('sd_dart_gpu_device_memory', -3); + }, exceptionalReturn: 0), }; T _record(String name, T result) { 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 5469b19d6..b5b0f949d 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 @@ -2,6 +2,7 @@ library; import 'dart:async'; +import 'dart:convert'; import 'package:test/test.dart'; @@ -49,6 +50,20 @@ List<(int, int)> _upstreamReports({ for (var tile = 1; tile <= tiles; tile++) (tile, tiles), ]; +// What a start calls in the calling isolate with no log level: the log +// recorder is registered, recording nothing, before the progress recorder. +const _startCalls = [ + 'sd_dart_log_enable', + 'sd_dart_log_set_level:5', + 'sd_dart_progress_enable', +]; + +// A drain of the log that finds [messages] messages. +List _logReads(int messages) => [ + for (var read = 0; read <= messages; read++) 'sd_dart_log_read', + 'sd_dart_log_dropped', +]; + const _loadCalls = [ 'sd_ctx_params_init', 'sd_dart_new_sd_ctx', @@ -84,27 +99,52 @@ void main() { late ManualProgressTimers timers; final workers = []; - Future start() async { + Future start({ + LlamaLogLevel logLevel = LlamaLogLevel.none, + }) async { final worker = await StableDiffusionImageWorker.start( _config, resolveCalls: runtime.resolver, progressTimer: timers.start, + logLevel: logLevel, ); workers.add(worker); return worker; } /// A started worker, with the calls of its load forgotten. - Future loaded() async { - final worker = await start(); + Future loaded({ + LlamaLogLevel logLevel = LlamaLogLevel.none, + }) async { + final worker = await start(logLevel: logLevel); await runtime.flush(); runtime.clearCalls(); return worker; } + /// The records the calling isolate's logger hands its handler from now + /// on, at [level]. + List<(LlamaLogLevel, String)> records({ + LlamaLogLevel level = LlamaLogLevel.debug, + }) { + final records = <(LlamaLogLevel, String)>[]; + final logger = LlamaLogger.instance; + final previous = logger.level; + logger + ..setLevel(level) + ..setHandler((record) => records.add((record.level, record.message))); + addTearDown(() { + logger + ..setLevel(previous) + ..setHandler(null); + }); + return records; + } + setUp(() { runtime = FakeStableDiffusionRuntime(); timers = ManualProgressTimers(); + StableDiffusionImageWorker.debugResetLogPositionForTesting(); }); tearDown(() async { @@ -120,11 +160,18 @@ void main() { final worker = await start(); await runtime.flush(); - expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('caller'), _startCalls); expect(runtime.calls('worker'), _loadCalls); expect(worker.modelVersion, 'SD 2.x'); }); + test('a load writes its files into the parameters after the runtime ' + 'initialized them', () async { + await start(); + + expect(runtime.loadedModelPath, '/models/sdxs.gguf'); + }); + test('a generation marks its start, reads the reports after the reply ' 'and stops its timer', () async { runtime.loadReports = 3; @@ -448,19 +495,69 @@ void main() { expect(runtime.calls('caller'), isEmpty); }); - test('a failed load creates nothing to free', () async { + test('a failed load creates nothing to free, and its error carries the ' + 'reason the runtime logged, read right after the load, with the ' + 'file named by role', () async { runtime.rejectLoad = true; - await expectLater(start(), throwsA(isA())); + await expectLater( + start(), + throwsA( + isA() + .having( + (error) => error.message, + 'message', + allOf( + startsWith( + 'stable-diffusion.cpp could not load the image model ' + 'files. The runtime reported: "model_loader.cpp:1061 - ' + "cannot inspect model source '': No " + 'such file or directory".', + ), + isNot(contains('Check that they form a model')), + isNot(contains('no reason')), + ), + ) + .having((error) => error.details, 'details', 'files: checkpoint') + .having( + (error) => '$error', + 'toString', + isNot(contains('/models')), + ), + ), + ); await runtime.flush(); - expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('caller'), _startCalls); expect(runtime.calls('worker'), [ 'sd_ctx_params_init', 'sd_dart_new_sd_ctx', + 'sd_dart_last_error', ]); }); + test('a failed load for which the runtime logged no error says so and ' + 'keeps the general advice', () async { + runtime + ..rejectLoad = true + ..quietReject = true; + + await expectLater( + start(), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('Check that they form a model the runtime supports'), + endsWith('The runtime logged no reason.'), + isNot(contains('reported:')), + ), + ), + ), + ); + }); + test('a model that cannot generate images is freed through the ' 'exit-free', () async { runtime.videoOnly = true; @@ -505,7 +602,7 @@ void main() { runtime.missingInWorker = true; await expectLater(start(), throwsA(isA())); await runtime.flush(); - expect(runtime.calls('caller'), ['sd_dart_progress_enable']); + expect(runtime.calls('caller'), _startCalls); expect(runtime.calls('worker'), isEmpty); }); @@ -552,9 +649,303 @@ void main() { ]); expect(runtime.calls('caller'), ['sd_dart_progress_read:mark']); }); + + group('with a log level', () { + test('the recorder is set to the level before the worker starts, and ' + 'the worker reads what the load recorded after its calls on the ' + 'context', () async { + final logged = records(); + + await start(logLevel: LlamaLogLevel.info); + await runtime.flush(); + + expect(runtime.calls('caller'), [ + 'sd_dart_log_enable', + 'sd_dart_log_set_level:2', + 'sd_dart_progress_enable', + ]); + expect(runtime.calls('worker'), [..._loadCalls, ..._logReads(1)]); + expect(logged, [ + ( + LlamaLogLevel.info, + 'stable_diffusion: stable-diffusion.cpp:262 - loading model from ' + "''", + ), + ]); + }); + + test('each level sets its own sd_log_level_t', () async { + for (final (level, threshold) in [ + (LlamaLogLevel.debug, 0), + (LlamaLogLevel.warn, 3), + (LlamaLogLevel.error, 4), + ]) { + final worker = await loaded(logLevel: level); + await worker.dispose(); + workers.remove(worker); + runtime.clearCalls(); + await start(logLevel: level); + await runtime.flush(); + + expect( + runtime.calls('caller')[1], + 'sd_dart_log_set_level:$threshold', + ); + } + }); + + test('a generation is followed by a read of what it recorded, after ' + 'its images are freed', () async { + final worker = await loaded(logLevel: LlamaLogLevel.debug); + final logged = records(); + + await worker.generate(_request(), (_, _) {}); + await runtime.flush(); + + expect(runtime.calls('worker'), [..._generateCalls, ..._logReads(2)]); + expect(logged, [ + ( + LlamaLogLevel.debug, + 'stable_diffusion: stable-diffusion.cpp:3120 - sampling', + ), + ( + LlamaLogLevel.info, + 'stable_diffusion: stable-diffusion.cpp:3391 - generating', + ), + ]); + }); + + test('the runtime records nothing below the level, and the logger of ' + 'the calling isolate applies its own level again', () async { + final worker = await loaded(logLevel: LlamaLogLevel.info); + final logged = records(level: LlamaLogLevel.warn); + runtime.log(3, utf8.encode('ggml - a warning')); + + await worker.generate(_request(), (_, _) {}); + await runtime.flush(); + + // The warning and "generating"; "sampling" was not recorded. + expect(runtime.calls('worker'), [..._generateCalls, ..._logReads(2)]); + expect(logged, [ + (LlamaLogLevel.warn, 'stable_diffusion: ggml - a warning'), + ]); + }); + + test('dispose reads what was recorded since the last read, after the ' + 'context is freed', () async { + final worker = await loaded(logLevel: LlamaLogLevel.info); + final logged = records(); + runtime.log(4, utf8.encode('ggml - late error')); + + await worker.dispose(); + await runtime.flush(); + + expect(runtime.calls('worker'), ['sd_dart_exit_free', ..._logReads(1)]); + expect(logged, [ + (LlamaLogLevel.error, 'stable_diffusion: ggml - late error'), + ]); + }); + + test('a second worker continues where the first one stopped ' + 'reading', () async { + final logged = records(); + final first = await start(logLevel: LlamaLogLevel.info); + await first.generate(_request(), (_, _) {}); + await first.dispose(); + expect(logged, hasLength(2)); + logged.clear(); + runtime.clearCalls(); + + await start(logLevel: LlamaLogLevel.info); + await runtime.flush(); + + expect(runtime.calls('worker'), [..._loadCalls, ..._logReads(1)]); + expect(logged.single.$2, contains('loading model from')); + }); + + test('messages the runtime dropped are reported in one warning, after ' + 'the ones it kept', () async { + runtime.close(); + runtime = FakeStableDiffusionRuntime(logHistory: 2); + final worker = await loaded(logLevel: LlamaLogLevel.info); + final logged = records(); + for (var i = 1; i <= 5; i++) { + runtime.log(2, utf8.encode('message $i')); + } + + await worker.generate(_request(), (_, _) {}); + + // Six were recorded since the last read, and the newest two kept. + expect(logged.take(2), [ + (LlamaLogLevel.info, 'stable_diffusion: message 5'), + ( + LlamaLogLevel.info, + 'stable_diffusion: stable-diffusion.cpp:3391 - generating', + ), + ]); + expect(logged, hasLength(3)); + expect(logged.last.$1, LlamaLogLevel.warn); + expect( + logged.last.$2, + startsWith('The stable_diffusion runtime dropped 4 log messages'), + ); + + logged.clear(); + await worker.generate(_request(), (_, _) {}); + expect(logged, hasLength(1)); + }); + + test('text that is not valid UTF-8 is delivered, not thrown', () async { + final worker = await loaded(logLevel: LlamaLogLevel.info); + final logged = records(); + runtime.log(2, [0x62, 0x61, 0x64, 0xff, 0x21]); + + await worker.generate(_request(), (_, _) {}); + + expect(logged.first, ( + LlamaLogLevel.info, + 'stable_diffusion: bad\u{fffd}!', + )); + }); + + test('a failed load forwards what the runtime logged before it ' + 'fails', () async { + runtime.rejectLoad = true; + final logged = records(); + + await expectLater( + start(logLevel: LlamaLogLevel.error), + throwsA(isA()), + ); + await runtime.flush(); + + expect(runtime.calls('worker'), [ + 'sd_ctx_params_init', + 'sd_dart_new_sd_ctx', + 'sd_dart_last_error', + ..._logReads(1), + ]); + expect(logged, [ + ( + LlamaLogLevel.error, + 'stable_diffusion: model_loader.cpp:1061 - cannot inspect model ' + "source '': No such file or directory", + ), + ]); + }); + + test('a model that cannot generate images is freed before the log is ' + 'read', () async { + runtime.videoOnly = true; + + await expectLater( + start(logLevel: LlamaLogLevel.info), + throwsA(isA()), + ); + 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', + ..._logReads(1), + ]); + }); + }); + + group('on a runtime older than the log, v0.2.0-1', () { + setUp(() => runtime.olderRelease = true); + + test('a worker loads, generates and disposes without any log call, ' + 'whatever the log level', () async { + final logged = records(); + + final worker = await start(logLevel: LlamaLogLevel.debug); + final images = await worker.generate(_request(), (_, _) {}); + await worker.dispose(); + await runtime.flush(); + + expect(images, hasLength(1)); + expect(runtime.calls('caller'), [ + 'sd_dart_progress_enable', + 'sd_dart_progress_read:mark', + 'sd_dart_progress_read', + ]); + expect(runtime.calls('worker'), [ + ..._loadCalls, + ..._generateCalls, + 'sd_dart_exit_free', + ]); + expect(logged, isEmpty); + }); + + test('a failed load names the roles and the release that reports the ' + 'reason', () async { + runtime.rejectLoad = true; + + await expectLater( + start(logLevel: LlamaLogLevel.debug), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('Check that they form a model the runtime supports'), + endsWith( + 'This stable_diffusion runtime does not report its reason: ' + 'that needs stable-diffusion-native v0.2.0-2 or later.', + ), + ), + ), + ), + ); + await runtime.flush(); + + expect(runtime.calls('worker'), [ + 'sd_ctx_params_init', + 'sd_dart_new_sd_ctx', + ]); + }); + }); }); group('stableDiffusionModelLoadFailure', () { + test('puts the runtime\'s reason first and keeps the roles a split ' + 'checkpoint lacks', () { + final error = stableDiffusionModelLoadFailure( + {'diffusionModel': '/m/sdxs.gguf'}, + reason: "get sd version from file failed: ''", + runtimeReportsReason: true, + ); + + expect( + error.message, + allOf( + startsWith( + 'stable-diffusion.cpp could not load the image model files. The ' + 'runtime reported: "get sd version from file failed: \'\'". ' + 'Standalone diffusion weights', + ), + contains('need a vae or taesd file'), + contains('need their text encoders'), + isNot(contains('Check that they form a model')), + isNot(contains('no reason')), + isNot(contains('does not report')), + ), + ); + expect(error.details, 'files: diffusionModel'); + }); + + test('says that the runtime logged no reason when it could have', () { + final error = stableDiffusionModelLoadFailure({ + 'model': '/m/sd_turbo.gguf', + }, runtimeReportsReason: true); + + expect(error.message, contains('enough memory')); + expect(error.message, endsWith('The runtime logged no reason.')); + }); + test('names a missing VAE when a diffusionModel has none', () { final error = stableDiffusionModelLoadFailure({ 'diffusionModel': '/m/sd3.5_medium-Q8_0.gguf', diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart new file mode 100644 index 000000000..67d561fb6 --- /dev/null +++ b/test/unit/backends/stable_diffusion/stable_diffusion_log_test.dart @@ -0,0 +1,320 @@ +@TestOn('vm') +library; + +import 'dart:convert'; +import 'dart:ffi'; + +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_log.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; + +/// A recorder that keeps the messages it is given, numbered from +/// [firstSequence], and answers like `sd_dart_log_read`. +final class _Recorder { + _Recorder(this.messages, {this.firstSequence = 1, this.dropped = 0}); + + final List<(int, List)> messages; + final int firstSequence; + int dropped; + final List calls = []; + final List capacities = []; + List lastError = const []; + + late final StableDiffusionLogCalls log = StableDiffusionLogCalls( + enable: () => calls.add('enable'), + setLevel: (level) => calls.add('setLevel $level'), + read: (after, text, capacity, level, length) { + calls.add('read $after'); + capacities.add(capacity); + final index = after < firstSequence ? 0 : after - firstSequence + 1; + if (index >= messages.length) { + return 0; + } + final (messageLevel, bytes) = messages[index]; + text.cast().asTypedList(capacity) + ..setAll(0, bytes) + ..[bytes.length] = 0; + level.value = messageLevel; + return firstSequence + index; + }, + dropped: () { + calls.add('dropped'); + return dropped; + }, + lastError: (text, capacity) { + calls.add('lastError'); + capacities.add(capacity); + text.cast().asTypedList(capacity) + ..setAll(0, lastError) + ..[lastError.length] = 0; + return lastError.length; + }, + ); +} + +void main() { + test('each log level records from its own sd_log_level_t, and none ' + 'records nothing', () { + expect( + { + for (final level in LlamaLogLevel.values) + level: stableDiffusionLogThreshold(level), + }, + { + LlamaLogLevel.none: 5, + LlamaLogLevel.debug: 0, + LlamaLogLevel.info: 2, + LlamaLogLevel.warn: 3, + LlamaLogLevel.error: 4, + }, + ); + expect( + stableDiffusionLogThreshold(LlamaLogLevel.none), + greaterThan(sd.sd_log_level_t.SD_LOG_ERROR.value), + ); + }); + + test('a recorded message gets the level of its sd_log_level_t, with ' + 'verbose as debug and anything above error as an error', () { + expect( + [ + for (var level = -1; level <= 6; level++) + stableDiffusionLogLevel(level), + ], + [ + LlamaLogLevel.debug, + LlamaLogLevel.debug, + LlamaLogLevel.debug, + LlamaLogLevel.info, + LlamaLogLevel.warn, + LlamaLogLevel.error, + LlamaLogLevel.error, + LlamaLogLevel.error, + ], + ); + for (final level in LlamaLogLevel.values.skip(1)) { + expect( + stableDiffusionLogLevel(stableDiffusionLogThreshold(level)), + level, + ); + } + }); + + test('recording enables the recorder, then sets its level', () { + final recorder = _Recorder([]); + + recordStableDiffusionLog(recorder.log, LlamaLogLevel.warn); + recordStableDiffusionLog(recorder.log, LlamaLogLevel.none); + + expect(recorder.calls, ['enable', 'setLevel 3', 'enable', 'setLevel 5']); + }); + + test('text ends at its terminator, and malformed UTF-8 decodes instead of ' + 'throwing', () { + using((arena) { + final text = arena(16); + final bytes = text.cast().asTypedList(16); + + bytes.setAll(0, [...utf8.encode('héllo'), 0, 0x41]); + expect(stableDiffusionText(text, 16), 'héllo'); + + // A lone continuation byte, and a sequence cut after its first byte. + bytes.setAll(0, [0x61, 0x80, 0x62, 0xe2, 0]); + expect(stableDiffusionText(text, 16), 'a\u{fffd}b\u{fffd}'); + + bytes.fillRange(0, 16, 0x78); + expect(stableDiffusionText(text, 16), 'x' * 16); + }); + }); + + group('drainStableDiffusionLog', () { + test('reads the messages after the position in order until there are ' + 'none, with a buffer that holds the longest message', () { + final recorder = _Recorder([ + (2, utf8.encode('first')), + (0, utf8.encode('second')), + (4, utf8.encode('third')), + ]); + + final drain = drainStableDiffusionLog(recorder.log, ( + after: 1, + dropped: 0, + )); + + expect(drain.messages, [ + (LlamaLogLevel.debug, 'second'), + (LlamaLogLevel.error, 'third'), + ]); + expect(drain.position, (after: 3, dropped: 0)); + expect(drain.dropped, 0); + expect(recorder.calls, ['read 1', 'read 2', 'read 3', 'dropped']); + expect(recorder.capacities, everyElement(sd.SD_DART_LOG_TEXT_SIZE)); + }); + + test('an empty log costs one read', () { + final recorder = _Recorder([], dropped: 2); + + final drain = drainStableDiffusionLog(recorder.log, ( + after: 7, + dropped: 2, + )); + + expect(drain.messages, isEmpty); + expect(drain.position, (after: 7, dropped: 2)); + expect(recorder.calls, ['read 7', 'dropped']); + }); + + test('continues behind the messages that left the buffer, and reports ' + 'how many the runtime dropped since the last drain', () { + final recorder = _Recorder( + [(2, utf8.encode('kept'))], + firstSequence: 40, + dropped: 37, + ); + + final drain = drainStableDiffusionLog(recorder.log, ( + after: 3, + dropped: 1, + )); + + expect(drain.messages, [(LlamaLogLevel.info, 'kept')]); + expect(drain.position, (after: 40, dropped: 37)); + expect(drain.dropped, 36); + }); + + test('stops at its read limit and leaves the rest for the next drain', () { + final recorder = _Recorder([ + for (var i = 1; i <= 5; i++) (2, utf8.encode('message $i')), + ]); + + final first = drainStableDiffusionLog(recorder.log, ( + after: 0, + dropped: 0, + ), maxReads: 2); + final second = drainStableDiffusionLog(recorder.log, first.position); + + expect(first.messages.map((message) => message.$2), [ + 'message 1', + 'message 2', + ]); + expect(second.messages.map((message) => message.$2), [ + 'message 3', + 'message 4', + 'message 5', + ]); + expect(stableDiffusionLogReadsPerDrain, 4096); + }); + }); + + group('readStableDiffusionLastError', () { + test('reads the errors with a buffer that holds all 32 of them', () { + final recorder = _Recorder([]) + ..lastError = utf8.encode('first error\nsecond error'); + + expect( + readStableDiffusionLastError(recorder.log), + 'first error\nsecond error', + ); + expect(recorder.capacities, [32 * 512]); + }); + + test('is empty when the runtime kept no error', () { + expect(readStableDiffusionLastError(_Recorder([]).log), ''); + }); + + test('decodes malformed UTF-8 instead of throwing', () { + final recorder = _Recorder([])..lastError = [0x62, 0x61, 0x64, 0xff]; + + expect(readStableDiffusionLastError(recorder.log), 'bad\u{fffd}'); + }); + }); + + group('stableDiffusionPathRedactor', () { + final redact = stableDiffusionPathRedactor({ + 'model': '/Users/ada/models/sd/sdxs.gguf', + 'taesd': '/Users/ada/models/taesd.safetensors', + 'clipL': r'C:\Users\ada\cache\clip_l.gguf', + }); + + test('names each file by its role', () { + expect( + redact( + "cannot inspect model source '/Users/ada/models/sd/sdxs.gguf': " + 'No such file or directory', + ), + "cannot inspect model source '': " + 'No such file or directory', + ); + expect( + redact( + 'loading /Users/ada/models/taesd.safetensors and ' + r'C:\Users\ada\cache\clip_l.gguf', + ), + 'loading and ', + ); + }); + + test('hides the directories of the files in other paths', () { + expect( + redact( + 'no /Users/ada/models/sd/sdxs.gguf.tmp beside ' + r'/Users/ada/models/other.bin or C:\Users\ada\cache\vae.bin', + ), + 'no .tmp beside /other.bin or ' + r'\vae.bin', + ); + }); + + test('leaves a text without those paths alone', () { + expect( + redact("get sd version from file failed: ''"), + "get sd version from file failed: ''", + ); + expect(stableDiffusionPathRedactor({})('/any/path'), '/any/path'); + }); + }); + + group('stableDiffusionFailureReason', () { + String redact(String text) => text.replaceAll('/m/x.gguf', ''); + + test('joins the errors on one line without their paths', () { + expect( + stableDiffusionFailureReason( + "model_loader.cpp:1061 - cannot inspect '/m/x.gguf'\n" + 'stable-diffusion.cpp:300 - init model loader from file failed', + redact, + ), + "model_loader.cpp:1061 - cannot inspect ''; " + 'stable-diffusion.cpp:300 - init model loader from file failed', + ); + }); + + test('removes control characters, empty lines and the padding of ' + 'upstream\'s source locations', () { + expect( + stableDiffusionFailureReason( + '\n first\ttab\r\n\n\x1b[31msecond\x00\n' + 'diffusion_engine.cpp:727 - failed', + redact, + ), + 'first tab; [31msecond; diffusion_engine.cpp:727 - failed', + ); + }); + + test('is null when nothing is left', () { + expect(stableDiffusionFailureReason('', redact), isNull); + expect(stableDiffusionFailureReason(' \n\t\n', redact), isNull); + }); + + test('cuts a long reason to 1000 characters', () { + final reason = stableDiffusionFailureReason('e' * 5000, redact)!; + + expect(reason, '${'e' * 1000}...'); + }); + }); +} diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart index df6c6a4a1..f720776b3 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart @@ -8,6 +8,11 @@ import 'package:test/test.dart'; import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_memory.dart'; import 'package:llamadart/src/core/image/image_generation_driver.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; + +import '../../../support/fake_stable_diffusion_runtime.dart'; + +const _gib = 1 << 30; /// Whether `MTLCreateSystemDefaultDevice` returns a device, checked apart /// from the code under test. @@ -282,6 +287,163 @@ void main() { }, skip: Platform.isMacOS ? false : 'macOS only'); }); + group('readStableDiffusionGpuMemory', () { + late FakeStableDiffusionRuntime runtime; + + setUp(() => runtime = FakeStableDiffusionRuntime()); + + tearDown(() => runtime.close()); + + StableDiffusionGpuMemory? read({ + LlamaLogLevel logLevel = LlamaLogLevel.none, + String? vulkanDevice, + }) => readStableDiffusionGpuMemory( + resolveCalls: runtime.resolver, + logLevel: logLevel, + environment: (name) => name == 'SD_VK_DEVICE' ? vulkanDevice : null, + ); + + test('asks the default device, after the recorder is registered at the ' + 'log level', () async { + runtime.setGpuMemory(total: 24 * _gib, free: 21 * _gib); + + final memory = read(logLevel: LlamaLogLevel.warn); + await runtime.flush(); + + expect(memory, ( + name: 'Vulkan0 (Fake GPU)', + totalBytes: 24 * _gib, + freeBytes: 21 * _gib, + integrated: false, + )); + expect(runtime.calls('caller'), [ + 'sd_dart_log_enable', + 'sd_dart_log_set_level:3', + 'sd_dart_gpu_device_memory:-1', + ]); + }); + + test('reports an integrated GPU as one', () { + runtime.setGpuMemory(total: 16 * _gib, free: 12 * _gib, integrated: true); + + expect(read()?.integrated, isTrue); + }); + + test('is null for every status but OK: no backend, no device, memory ' + 'unavailable, an invalid argument', () { + for (final status in [-1, -2, -3, -4]) { + runtime.setGpuMemory(status: status, total: 8 * _gib, free: _gib); + + expect(read(), isNull, reason: '$status'); + } + }); + + test('a runtime older than the query is not asked', () async { + runtime + ..olderRelease = true + ..setGpuMemory(total: 8 * _gib, free: _gib); + + expect(read(), isNull); + await runtime.flush(); + expect(runtime.calls('caller'), isEmpty); + }); + + test('is null without a runtime', () { + expect(readStableDiffusionGpuMemory(resolveCalls: () => null), isNull); + }); + + test('SD_VK_DEVICE, which makes the runtime pick the device, skips the ' + 'query', () async { + runtime.setGpuMemory(total: 8 * _gib, free: _gib); + + expect(read(vulkanDevice: '1'), isNull); + await runtime.flush(); + expect(runtime.calls('caller'), isEmpty); + expect(read(), isNotNull); + }); + }); + + group('stableDiffusionGpuMemoryBudget', () { + const host = (bytes: 5 * _gib, source: 'MemAvailable in /proc/meminfo'); + + ImageGenerationMemoryBudget? budget( + StableDiffusionGpuMemory? memory, { + ImageGenerationMemoryBudget? hostBudget = host, + }) => stableDiffusionGpuMemoryBudget(memory, hostBudget: () => hostBudget); + + StableDiffusionGpuMemory gpu({ + required int total, + required int free, + bool integrated = false, + }) => ( + name: 'Vulkan0 (NVIDIA L4)', + totalBytes: total, + freeBytes: free, + integrated: integrated, + ); + + test('a discrete GPU whose driver reports a budget gives its free ' + 'memory', () { + expect(budget(gpu(total: 24 * _gib, free: 9 * _gib)), ( + bytes: 9 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + )); + expect( + budget(gpu(total: 8 * _gib, free: 8 * _gib - 1))?.bytes, + 8 * _gib - 1, + ); + expect(budget(gpu(total: 8 * _gib, free: 1))?.bytes, 1); + }); + + test('a discrete GPU that reports its total as free, or nothing as free, ' + 'gives its total memory and says that free memory is unknown', () { + for (final free in [8 * _gib, 0]) { + expect(budget(gpu(total: 8 * _gib, free: free)), ( + bytes: 8 * _gib, + source: + 'the GPU memory of Vulkan0 (NVIDIA L4), whose driver does not ' + 'report how much of it is free', + ), reason: '$free'); + } + }); + + test('an integrated GPU gives the host figure, never its own', () { + for (final (total, free) in [(64 * _gib, 60 * _gib), (2 * _gib, _gib)]) { + expect(budget(gpu(total: total, free: free, integrated: true)), ( + bytes: 5 * _gib, + source: + 'MemAvailable in /proc/meminfo; Vulkan0 (NVIDIA L4) is an ' + 'integrated GPU, which uses host memory', + )); + } + }); + + test('an integrated GPU has no budget where host memory is not read', () { + expect( + budget( + gpu(total: 16 * _gib, free: 8 * _gib, integrated: true), + hostBudget: null, + ), + isNull, + ); + }); + + test('unknown memory has no budget, and the host is not asked for a ' + 'discrete GPU', () { + ImageGenerationMemoryBudget? unasked() => fail('asked the host'); + + expect(budget(null), isNull); + expect(budget(gpu(total: 0, free: 0)), isNull); + expect( + stableDiffusionGpuMemoryBudget( + gpu(total: 8 * _gib, free: _gib), + hostBudget: unasked, + )?.bytes, + _gib, + ); + }); + }); + test('readStableDiffusionFileRange reads a range and stops at the end of ' 'the file', () async { final directory = await Directory.systemTemp.createTemp('llamadart-sd-'); 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 26df527c1..312fa41c4 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 @@ -8,6 +8,7 @@ import 'package:test/test.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/models/config/log_level.dart'; const _dotProductCpuInfo = 'Features\t: fp asimd atomics fphp asimdhp asimddp\n'; @@ -27,6 +28,24 @@ void main() { expect(status.devices.map((device) => device.name), ['CPU', 'MTL0']); }); + test('records the log at the given level before the device list, which ' + 'initializes the GPU backend and logs', () { + for (final level in [LlamaLogLevel.none, LlamaLogLevel.info]) { + final api = _FakeApi(); + + probeStableDiffusionRuntime( + abi: Abi.macosArm64, + api: api, + logLevel: level, + ); + + expect(api.order, ['recordLog ${level.name}', 'listDevices']); + } + final api = _FakeApi(); + probeStableDiffusionRuntime(abi: Abi.macosArm64, api: api); + expect(api.order.first, 'recordLog none'); + }); + test('a runtime without the sd_dart_ functions is unavailable, and the ' 'reason names them and the release that has them', () { final status = probeStableDiffusionRuntime( @@ -474,6 +493,7 @@ final class _FakeApi implements StableDiffusionNativeApi { final ArgumentError? error; final bool wrapperCalls; int calls = 0; + final List order = []; T _call(T value) { calls++; @@ -491,7 +511,16 @@ final class _FakeApi implements StableDiffusionNativeApi { String commit() => _call('c0ffee'); @override - String listDevices() => _call(devices); + void recordLog(LlamaLogLevel level) { + order.add('recordLog ${level.name}'); + _call(null); + } + + @override + String listDevices() { + order.add('listDevices'); + return _call(devices); + } @override bool exportsWrapperCalls() => _call(wrapperCalls); diff --git a/test/unit/core/image/image_generation_driver_io_test.dart b/test/unit/core/image/image_generation_driver_io_test.dart index 310383eab..0ec3942c5 100644 --- a/test/unit/core/image/image_generation_driver_io_test.dart +++ b/test/unit/core/image/image_generation_driver_io_test.dart @@ -5,10 +5,44 @@ import 'dart:io'; import 'package:test/test.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_memory.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import 'package:llamadart/src/core/exceptions.dart'; import 'package:llamadart/src/core/image/image_generation_driver.dart'; import 'package:llamadart/src/core/image/image_generation_driver_io.dart'; +import 'package:llamadart/src/core/llama_logging.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; + +/// Set in the test isolate only: an isolate the driver spawns starts with the +/// initial value. +String _isolate = 'spawned'; + +StableDiffusionRuntimeStatus _probeNamingItsIsolate({ + LlamaLogLevel logLevel = LlamaLogLevel.none, +}) => StableDiffusionRuntimeStatus.unavailable( + LlamaUnsupportedException('$_isolate isolate, log level ${logLevel.name}'), +); + +StableDiffusionGpuMemory? _gpuMemoryNamingItsIsolate({ + LlamaLogLevel logLevel = LlamaLogLevel.none, +}) => ( + name: '$_isolate isolate, log level ${logLevel.name}', + totalBytes: 8 << 30, + freeBytes: 6 << 30, + integrated: false, +); + +StableDiffusionGpuMemory? _noGpuMemory({ + LlamaLogLevel logLevel = LlamaLogLevel.none, +}) => null; void main() { + setUp(() => _isolate = 'calling'); + + tearDown( + () => applyLogLevels(dart: LlamaLogLevel.none, native: LlamaLogLevel.none), + ); + test('sizes regular files only', () async { final directory = await Directory.systemTemp.createTemp('llamadart-img-'); addTearDown(() => directory.delete(recursive: true)); @@ -40,15 +74,68 @@ void main() { ); }); + test('the background probe runs in another isolate, and probe on the ' + 'calling one', () async { + final driver = createImageGenerationDriver(probe: _probeNamingItsIsolate); + + expect( + (await driver.probeInBackground()).unavailableReason?.message, + startsWith('spawned isolate'), + ); + expect( + driver.probe().unavailableReason?.message, + startsWith('calling isolate'), + ); + }); + + test('the runtime records its log at the stricter of the two configured ' + 'levels, and not at all when either is none', () async { + final driver = createImageGenerationDriver( + probe: _probeNamingItsIsolate, + readGpuMemory: _gpuMemoryNamingItsIsolate, + ); + + for (final (dart, native, expected) in [ + (LlamaLogLevel.none, LlamaLogLevel.none, LlamaLogLevel.none), + (LlamaLogLevel.debug, LlamaLogLevel.none, LlamaLogLevel.none), + (LlamaLogLevel.none, LlamaLogLevel.debug, LlamaLogLevel.none), + (LlamaLogLevel.debug, LlamaLogLevel.warn, LlamaLogLevel.warn), + (LlamaLogLevel.error, LlamaLogLevel.info, LlamaLogLevel.error), + (LlamaLogLevel.info, LlamaLogLevel.info, LlamaLogLevel.info), + ]) { + await applyLogLevels(dart: dart, native: native); + final reason = '${dart.name}/${native.name}'; + + expect(imageRuntimeLogLevel(), expected, reason: reason); + expect( + (await driver.probeInBackground()).unavailableReason?.message, + endsWith('log level ${expected.name}'), + reason: reason, + ); + expect( + driver.probe().unavailableReason?.message, + endsWith('log level ${expected.name}'), + reason: reason, + ); + expect( + (await driver.memoryBudget( + ImageGenerationComputeDevice.otherGpu, + ))?.source, + contains('log level ${expected.name}'), + reason: reason, + ); + } + }); + test('reports a CPU and Metal memory budget on macOS and Linux hosts, and ' - 'none for other GPUs', () { + 'none for other GPUs on a host without the runtime', () async { final driver = createImageGenerationDriver(); for (final device in [ ImageGenerationComputeDevice.cpu, ImageGenerationComputeDevice.metal, ]) { - final budget = driver.memoryBudget(device); + final budget = await driver.memoryBudget(device); if (Platform.isMacOS || Platform.isLinux) { expect(budget, isNotNull); expect(budget!.bytes, greaterThan(0)); @@ -56,6 +143,46 @@ void main() { expect(budget, isNull); } } - expect(driver.memoryBudget(ImageGenerationComputeDevice.otherGpu), isNull); + expect( + await driver.memoryBudget(ImageGenerationComputeDevice.otherGpu), + isNull, + ); + }); + + test('asks another GPU for its memory in another isolate, and budgets its ' + 'free memory', () async { + final driver = createImageGenerationDriver( + readGpuMemory: _gpuMemoryNamingItsIsolate, + ); + + final budget = await driver.memoryBudget( + ImageGenerationComputeDevice.otherGpu, + ); + + expect(budget?.bytes, 6 << 30); + expect(budget?.source, contains('free GPU memory of spawned isolate')); + }); + + test('a GPU whose memory is not known has no budget, and the CPU and ' + 'Metal budgets do not ask it', () async { + final driver = createImageGenerationDriver(readGpuMemory: _noGpuMemory); + + expect( + await driver.memoryBudget(ImageGenerationComputeDevice.otherGpu), + isNull, + ); + + final unasked = createImageGenerationDriver( + readGpuMemory: _gpuMemoryNamingItsIsolate, + ); + for (final device in [ + ImageGenerationComputeDevice.cpu, + ImageGenerationComputeDevice.metal, + ]) { + expect( + (await unasked.memoryBudget(device))?.source, + isNot(contains('isolate')), + ); + } }); } diff --git a/test/unit/core/image/image_generation_driver_stub_test.dart b/test/unit/core/image/image_generation_driver_stub_test.dart index cd74f07a9..963d3dafd 100644 --- a/test/unit/core/image/image_generation_driver_stub_test.dart +++ b/test/unit/core/image/image_generation_driver_stub_test.dart @@ -19,7 +19,7 @@ void main() { throwsA(isA()), ); for (final device in ImageGenerationComputeDevice.values) { - expect(driver.memoryBudget(device), isNull); + expect(await driver.memoryBudget(device), isNull); } await expectLater( driver.start( diff --git a/test/unit/core/image/image_generation_engine_test.dart b/test/unit/core/image/image_generation_engine_test.dart index 3e5407afa..60ed4e470 100644 --- a/test/unit/core/image/image_generation_engine_test.dart +++ b/test/unit/core/image/image_generation_engine_test.dart @@ -1030,6 +1030,36 @@ void main() { expect(driver.started, isEmpty); }); + test('refuses a model that does not fit a Vulkan GPU, naming the ' + 'estimate and the memory of the GPU', () async { + driver + ..status = _available('Vulkan0\tNVIDIA L4\nCPU\tHost\n') + ..sizes[_model] = 8 * _gib + ..budget = ( + bytes: 6 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB', + ); + + await expectLater( + load(_sdxs()), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('about 10.5 GiB'), + contains('only 6.00 GiB is available'), + contains( + 'free GPU memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB', + ), + ), + ), + ), + ); + expect(driver.budgetDevices, [ImageGenerationComputeDevice.otherGpu]); + expect(driver.started, isEmpty); + }); + test('counts every file toward the estimate', () async { driver.sizes[_model] = _gib; driver.sizes[_taesd] = _gib; @@ -1663,9 +1693,9 @@ final class _FakeDriver implements ImageGenerationDriver { final List budgetDevices = []; @override - ImageGenerationMemoryBudget? memoryBudget( + Future memoryBudget( ImageGenerationComputeDevice device, - ) { + ) async { budgetDevices.add(device); return budget; } diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 1a7eefe65..6b9582225 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -457,9 +457,16 @@ const List testMatrixRows = [ mode: 'local-only', covers: 'real opt-in stable_diffusion runtime bundled by the example hook, ' + 'a runtime probe that leaves the calling isolate responsive, a first ' + 'image after warmUp about as fast as a warm one, ' 'SDXS load and 256x256 one-step generation with labelled progress, ' 'same-seed determinism, pre-start and mid-run cancellation, the ' 'one-generation guard, dispose during generation, and PNG output; ' + 'the runtime\'s reason in the error of a truncated file, a missing ' + 'file and a file in the wrong role, without paths; runtime messages ' + 'through the log handler by level and none at the default levels; on ' + 'macOS the runtime\'s GPU memory total against the Metal working set ' + 'the memory check reads; ' 'SD-Turbo with TAESD when LLAMADART_SD_TURBO_MODEL is set, ' 'SDXL-Lightning warm-up and 1024x1024 generation (with TAESDXL when ' 'LLAMADART_TAESDXL is set) when LLAMADART_SDXL_LIGHTNING_MODEL is ' @@ -483,8 +490,11 @@ const List testMatrixRows = [ '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', + 'the idle, generating and loading exits again with the runtime log ' + 'forwarded at debug level; nothing on stderr at the default log ' + 'levels; the exports the required and the optional 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 ', @@ -626,7 +636,8 @@ const List testMatrixRows = [ mode: 'local-only', covers: 'chat-app image screen on a device with the bundled stable_diffusion ' - 'runtime: runtime probe, SDXS download through the screen when not ' + 'runtime: a runtime probe that leaves the UI isolate responsive, SDXS ' + 'download through the screen when not ' 'installed, seeded 512x512 generation with the used seed shown, and ' 'PNG plus screen-capture output in the app temporary directory', command: diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 9308a4391..6ae8dc9e5 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -7,6 +7,25 @@ For canonical full release notes, use: - [`CHANGELOG.md`](https://github.com/leehack/llamadart/blob/main/CHANGELOG.md) +## Unreleased + +- Adopt `leehack/stable-diffusion-native@v0.2.0-2` for the opt-in + `stable_diffusion` image runtime. +- Check the memory of a Vulkan GPU before loading an image model on Linux and + Windows: `ImageGenerationEngine.load` refuses a model whose estimate + exceeds the GPU's free memory, or its total memory when the driver reports + no free figure, with `LlamaModelException` + ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)). + The check has not run on a physical Vulkan GPU yet, and + `ImageModelParams(checkMemory: false)` loads anyway. +- Quote the errors stable-diffusion.cpp logged in the `LlamaModelException` + of an image model it cannot load, with files named by role + ([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)). +- Send the image runtime's messages to the `LlamaLogging.configure` handler + at the configured levels, after each load and generation. The runtime no + longer prints ggml's device messages to stderr: at the default level + `none` it logs nothing. + ## 0.11.1 - Give a chat template that reads content part lists but rejects image and diff --git a/website/docs/configuration/logging.md b/website/docs/configuration/logging.md index 24b87d168..e405633a3 100644 --- a/website/docs/configuration/logging.md +++ b/website/docs/configuration/logging.md @@ -51,6 +51,15 @@ above `debug` are never capped. An error thrown by the handler on a forwarded record is printed, not thrown. Web backends run on the main isolate and are unaffected. +## Image generation runtime + +The opt-in `stable_diffusion` runtime logs through the same handler. +`ImageGenerationEngine.load` takes the levels it finds and the runtime +records from the stricter of `level` and `nativeLevel`, so a later +`configure` call applies to the next load. Its messages arrive after each +load and generation, not while one runs, and are not printed to stderr at +any level; see [Runtime logs](../guides/image-generation#runtime-logs). + ## Recommended profiles - Local debugging: `level: info`, `nativeLevel: warn`. diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index 9538665b2..258cc3cce 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -18,9 +18,9 @@ Image generation is a Preview. [desktop models](#desktop-models) are validated on macOS Metal only ([#802](https://github.com/leehack/llamadart/issues/802)). - Open limits: no web runtime yet - ([#780](https://github.com/leehack/llamadart/issues/780)); Vulkan GPU - memory is not checked before loading - ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)); + ([#780](https://github.com/leehack/llamadart/issues/780)); the + [memory check](#memory-check) of a Vulkan GPU has not run on a physical GPU + yet ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)); the automatic attention and VAE settings were measured on an M4 Max and still need re-measuring on Android phones and iPhone ([#805](https://github.com/leehack/llamadart/issues/805)); the chat app's @@ -682,13 +682,45 @@ device the model loads on: | iOS: Metal or CPU | The app's remaining memory limit (`os_proc_available_memory`) | | macOS: CPU | Physical memory | | macOS: Metal | Physical memory, capped at the GPU's `recommendedMaxWorkingSetSize` (about two thirds to three quarters of it) | -| Linux, Windows: Vulkan | Not checked: the weights live in GPU memory, which the runtime does not report yet ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)) | +| Linux, Windows: Vulkan, discrete GPU | The GPU's free memory when its driver reports one (`VK_EXT_memory_budget`), otherwise its total memory | +| Linux: Vulkan, integrated GPU | `MemAvailable`, as for the CPU | +| Windows: Vulkan, integrated GPU | Not checked | | Windows: CPU | Not checked | A model that does not fit throws `LlamaModelException` naming both figures, instead of the system killing the app. Set `ImageModelParams(checkMemory: false)` to load anyway. +The Vulkan figures are the runtime's, which are ggml's: the memory of the +GPU a model loads on by default, the first discrete GPU or else the first +integrated one. The engine asks for them in a short-lived isolate, because +the first such call in a process can initialize the GPU. + +- With a memory budget from the driver, the free figure is what this process + can still allocate on the GPU, so it accounts for other processes and for + image models already loaded. +- Without one the runtime reports the total as free. The engine then + compares with the total, and does the same for a free figure of 0: only a + model that cannot fit the GPU at all is refused. +- An integrated GPU uses host memory, and a driver that exposes it as several + heaps makes the GPU's own figures count it more than once. The engine + ignores them and compares with host memory, which it does not read on + Windows. +- Nothing is checked when the GPU does not report its memory, when the + `SD_VK_DEVICE` environment variable picks the Vulkan device, or with a + `stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2`. + +With the check off, stable-diffusion.cpp keeps the weights that do not fit a +Vulkan GPU in host memory, which is slower but does not fail the load. So +the check refuses there what would have loaded slowly before. + +The Vulkan rules are tested on reported figures, and the call that reads them +is checked on macOS Metal, where its total equals the working set above. The +figures of a physical Vulkan GPU on Linux and Windows have not been checked +yet ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)). +The Apple checks do not use these figures: Metal's total is the same working +set, and its free figure counts only this process's allocations. + On Android, `MemAvailable` alone is too strict: it leaves out the memory the low-memory killer frees by stopping cached apps and what it swaps to zram, and it varied by up to a gigabyte between idle readings. On Firebase Test @@ -722,35 +754,62 @@ and 1024x1024 SDXL, SD 3.5 Large Turbo, FLUX and Z-Image stayed 0.5 to 1.6 GiB under it on Metal. SD 3.5 Medium, whose single file decodes with the full VAE, peaked 0.3 GiB above it (11.6 against 11.3 GiB). Larger sizes need more, especially on the CPU: SD-Turbo at 1024x1024 -peaked at 4.7 GiB there. On a Vulkan GPU too small for the model, -stable-diffusion.cpp keeps some weights in host memory, which is slower but -does not fail the load. +peaked at 4.7 GiB there. + +## Runtime logs + +stable-diffusion.cpp's and ggml's messages go to the handler of +[`LlamaLogging.configure`](../configuration/logging), each at its own level: + +```dart +await LlamaLogging.configure( + level: LlamaLogLevel.info, + handler: (record) => print('[${record.level.name}] ${record.message}'), +); +final engine = await ImageGenerationEngine.load(model); +``` + +- A message has to pass both `level` and `nativeLevel`, so the runtime + records from the stricter of the two, and nothing when either is `none`, + the default. A load takes the levels it finds: configure logging before + `load`. +- Messages arrive after each load and generation and at `dispose()`, not + while one runs: a worker isolate reads them from the runtime between its + calls. Each starts with `stable_diffusion: `, and model file paths are + replaced by roles, such as ``. +- The runtime keeps the most recent 256 KiB of messages. When one load or + generation records more, the oldest are lost and one warning says how + many. On an M4 Max an SDXS load recorded 28 messages at `info` and 40 at + `debug`, and reading them took about 0.1 ms. +- The runtime no longer writes ggml's device messages to stderr, at any + level. What a ggml backend writes to stderr itself still goes there. +- A `stable_diffusion` runtime older than `stable-diffusion-native` + `v0.2.0-2` has no log to read: it logs as before, to stderr only. ## Errors | Exception | When | | --- | --- | | `LlamaUnsupportedException` | The runtime is not bundled, the platform or CPU is unsupported, on the web, `ComputeDevice.gpu` without a GPU, `ComputeDevice.npu`, or `ModelLoadOptions.sha256` set for a `load` of several files | -| `LlamaModelException` | A file is missing, fails to download or is not an image-model component, two files share a role, a decoder does not match the diffusion model, the model does not fit, or the runtime cannot load it. A rejected split model names the roles it lacks, such as a VAE or text encoder, and `details` lists the roles passed | +| `LlamaModelException` | A file is missing, fails to download or is not an image-model component, two files share a role, a decoder does not match the diffusion model, the model does not fit, or the runtime cannot load it. A load the runtime rejects quotes the errors it logged, with files named by role, such as `tensor '...' extends beyond its model file`; a rejected split model also names the roles it lacks, such as a VAE or text encoder, and `details` lists the roles passed | | `LlamaImageGenerationException` | An invalid request or `params:` | | `LlamaStateException` | The load's cancel token cancelled it, another generation or load is running, or the engine is disposed | | `LlamaInferenceException` | The runtime failed a generation, for example an aborted Metal command buffer or running out of memory; the engine runs the next request | ## Known limits -- Runtime logs are not forwarded to `LlamaLogger`: stable-diffusion.cpp's log - text is only valid during a call made from its own threads - ([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)). - ggml's own backend messages still reach stderr. The same gap keeps the - runtime's own reason out of a load failure; the error names missing file - roles instead. +- [Runtime logs](#runtime-logs) arrive after a load or generation, not + during it. A failed load quotes what the runtime logged as errors, which + for a file in the wrong role is only `get sd version from file failed`, + and a failed generation does not quote its reason yet. - Android runs on the CPU only: ggml Vulkan and OpenCL crashed or ran slower on the phones tried ([stable-diffusion-native#2](https://github.com/leehack/stable-diffusion-native/issues/2)). - iOS can abort a Metal command buffer under GPU pressure (seen once with SD-Turbo at four steps); the task fails and the next request runs. -- Windows and Vulkan GPUs are not memory-checked. Per-platform validation - results, including timings, are in +- The Windows CPU and integrated GPUs on Windows are not memory-checked, and + the [memory check](#memory-check) of a Vulkan GPU has not run on a physical + GPU yet. Per-platform validation results, including timings, are in [#779](https://github.com/leehack/llamadart/issues/779). - The web has no image runtime yet ([#780](https://github.com/leehack/llamadart/issues/780)). diff --git a/website/docs/maintainers/native-and-web-sync.md b/website/docs/maintainers/native-and-web-sync.md index 24906af1b..f30301abe 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-1 \ + --stable-diffusion-tag v0.2.0-2 \ --dry-run python3 tool/native/sync_native_release_pins.py \ - --stable-diffusion-tag v0.2.0-1 + --stable-diffusion-tag v0.2.0-2 python3 tool/native/sync_stable_diffusion_bindings.py ``` @@ -177,7 +177,8 @@ GitHub digest, and rewrites `stableDiffusionReleaseTag`, also rewrites the `llamadart_stable_diffusion_flutter` `Package.swift` tag and checksum from the manifest's `xcframework` artifact, after checking that artifact against its GitHub digest, and records the pin in the companion -README and CHANGELOG. It +README and CHANGELOG. It does not touch other docs: update the pin in +`website/docs/platforms/support-matrix.md` by hand. It fails if a pinned bundle is no longer published or the tag moves backwards, and only notes new targets: a new target needs a `StableDiffusionBundleSpec` and a `stableDiffusionBundleForNativeBundle` mapping by hand. @@ -192,7 +193,8 @@ and a `stableDiffusionBundleForNativeBundle` mapping by hand. 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 +whether the runtime is supported, or, when llamadart also has to run on a +runtime without it, into one of its optional groups, which is `null` there ([exit teardown](https://github.com/leehack/llamadart/blob/main/doc/llama_cpp_exit_teardown.md#image-models)). After a sync, run diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index afe484763..387b57ee0 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -185,7 +185,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-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` | +| stable-diffusion.cpp native (opt-in, Preview) | `leehack/stable-diffusion-native@v0.2.0-2`, 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 From d4cc11c9f017eec13b4ba61a4187cfe23fe364e9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 20:09:25 -0400 Subject: [PATCH 2/4] fix: refuse an image model on a Vulkan GPU only when the GPU plus system memory cannot hold it stable-diffusion.cpp's automatic fit, which llamadart leaves on, keeps the weights that do not fit a GPU in host memory, so a model larger than the GPU loads and runs slower. The memory check no longer refuses such a load. - A discrete Vulkan GPU has two figures: the GPU's memory, above which the engine logs one warning that part of the model stays in system memory and generation will be slower, and the GPU's memory plus the host figure of the CPU check, above which the load is refused. The refusal names the estimate, the GPU figure and the host figure. - Where host memory is not read, as on Windows, nothing is refused and only the warning applies. - Integrated GPUs, SD_VK_DEVICE, a GPU that does not report its memory, an older runtime and Apple are unchanged. - A test pins that a load leaves auto_fit, params_backend and max_vram as the runtime initialized them, which the rule depends on. Refs #966, leehack/stable-diffusion-native#9. --- CHANGELOG.md | 13 +- .../stable_diffusion_memory.dart | 91 ++++++---- .../core/image/image_generation_driver.dart | 20 ++- .../image/image_generation_driver_io.dart | 9 +- .../image/image_generation_driver_stub.dart | 4 +- .../core/image/image_generation_engine.dart | 57 +++--- skills/llamadart-image-generation/SKILL.md | 10 +- .../stable_diffusion_memory_test.dart | 114 ++++++++---- .../stable_diffusion_params_test.dart | 26 +++ .../image_generation_driver_io_test.dart | 67 ++++--- .../image_generation_driver_stub_test.dart | 2 +- .../image/image_generation_engine_test.dart | 165 +++++++++++++++--- website/docs/changelog/recent-releases.md | 13 +- website/docs/guides/image-generation.md | 85 +++++---- 14 files changed, 474 insertions(+), 202 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e15ba67af..9580ba64a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,14 @@ - Adopt `leehack/stable-diffusion-native@v0.2.0-2` for the opt-in `stable_diffusion` image runtime. -- Check the memory of a Vulkan GPU before loading an image model on Linux and - Windows: `ImageGenerationEngine.load` refuses a model whose estimate - exceeds the GPU's free memory, or its total memory when the driver reports - no free figure, with `LlamaModelException` +- Check the memory of a Vulkan GPU before loading an image model ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)). - The check has not run on a physical Vulkan GPU yet, and - `ImageModelParams(checkMemory: false)` loads anyway. + On Linux `ImageGenerationEngine.load` refuses, with `LlamaModelException`, + a model that fits neither the GPU nor the GPU plus system memory. A model + larger than the GPU's memory still loads, with one warning, and runs + slower; on Windows it is warned about and never refused. Not validated on + a physical Vulkan GPU yet; `ImageModelParams(checkMemory: false)` skips + the check and the warning. - Quote the errors stable-diffusion.cpp logged in the `LlamaModelException` of an image model it cannot load, with files named by role ([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)). diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart index 4ed219e9b..12a066c72 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart @@ -63,7 +63,7 @@ int? stableDiffusionFileSize(String path) { /// /// On other GPUs, such as Vulkan, `null`: the weights live in device memory, /// so host memory would be the wrong figure. [readStableDiffusionGpuMemory] -/// and [stableDiffusionGpuMemoryBudget] give theirs. +/// and [stableDiffusionGpuMemoryLimits] give theirs. /// /// [abi], [readMemInfo], [readProcessStatus], [iosAvailableMemory], /// [macosPhysicalMemory] and [metalRecommendedWorkingSet] default to the @@ -176,50 +176,73 @@ StableDiffusionGpuMemory? readStableDiffusionGpuMemory({ }); } -/// The memory a new image model can use on the GPU [memory] describes, or -/// `null` when it is not known. +/// The memory limits of a new image model on the GPU [memory] describes; +/// neither is known when [memory] is `null`. /// -/// - A discrete GPU whose driver reports a budget (`VK_EXT_memory_budget`): -/// its free memory, which is what this process can still allocate there -/// and so accounts for other processes and for models already loaded. -/// - A discrete GPU without one: its total memory. The runtime then reports -/// the total as free, so equal figures mean "not reported", and so does a -/// free figure of 0, which a driver whose budget is below the process's use -/// gives. Only a model that cannot fit the device at all is refused. -/// - An integrated GPU: [hostBudget], the figure the CPU gets. Its memory is -/// host memory, and a driver that exposes that as several heaps has it -/// counted more than once in the device's figures, so they are not used. -/// `null` where host memory is not read, as on Windows. -ImageGenerationMemoryBudget? stableDiffusionGpuMemoryBudget( +/// The GPU's figure: +/// - with a budget from the driver (`VK_EXT_memory_budget`), its free memory, +/// which is what this process can still allocate there and so accounts for +/// other processes and for models already loaded; +/// - without one, its total memory. The runtime then reports the total as +/// free, so equal figures mean "not reported", and so does a free figure of +/// 0, which a driver whose budget is below the process's use gives. +/// +/// A discrete GPU does not bound a load by itself: stable-diffusion.cpp's +/// automatic fit, which llamadart leaves on, keeps the weights that do not +/// fit the GPU in host memory. So a model above the GPU's figure is only +/// `slower`, and it is refused above that figure plus [hostBudget], the +/// figure the CPU gets. Where host memory is not read, as on Windows, +/// nothing is refused. +/// +/// An integrated GPU uses host memory, and a driver that exposes that as +/// several heaps has it counted more than once in the device's figures. They +/// are not used: a model is refused above [hostBudget] alone. +ImageGenerationMemoryLimits stableDiffusionGpuMemoryLimits( StableDiffusionGpuMemory? memory, { required ImageGenerationMemoryBudget? Function() hostBudget, }) { if (memory == null || memory.totalBytes <= 0) { - return null; + return (refuse: null, slower: null); } + final host = hostBudget(); if (memory.integrated) { - final host = hostBudget(); - return host == null - ? null - : ( - bytes: host.bytes, - source: - '${host.source}; ${memory.name} is an integrated GPU, which ' - 'uses host memory', - ); - } - final total = '${_gib(memory.totalBytes)} GiB'; - if (memory.freeBytes > 0 && memory.freeBytes < memory.totalBytes) { return ( - bytes: memory.freeBytes, - source: 'free GPU memory of ${memory.name}, out of $total', + refuse: host == null + ? null + : ( + bytes: host.bytes, + source: + '${host.source}; ${memory.name} is an integrated GPU, which ' + 'uses host memory', + ), + slower: null, ); } + final budgeted = memory.freeBytes > 0 && memory.freeBytes < memory.totalBytes; + final ImageGenerationMemoryBudget gpu = budgeted + ? ( + bytes: memory.freeBytes, + source: + 'free GPU memory of ${memory.name}, out of ' + '${_gib(memory.totalBytes)} GiB', + ) + : ( + bytes: memory.totalBytes, + source: + 'the GPU memory of ${memory.name}, whose driver does not ' + 'report how much of it is free', + ); return ( - bytes: memory.totalBytes, - source: - 'the GPU memory of ${memory.name}, whose driver does not report how ' - 'much of it is free', + refuse: host == null + ? null + : ( + bytes: gpu.bytes + host.bytes, + source: + '${_gib(gpu.bytes)} GiB of GPU memory and ' + '${_gib(host.bytes)} GiB of system memory: ${gpu.source}; ' + '${host.source}', + ), + slower: gpu, ); } diff --git a/lib/src/core/image/image_generation_driver.dart b/lib/src/core/image/image_generation_driver.dart index 819748f95..55b459fe6 100644 --- a/lib/src/core/image/image_generation_driver.dart +++ b/lib/src/core/image/image_generation_driver.dart @@ -87,6 +87,15 @@ final class ImageGenerationSessionRequest { /// Memory the device can give an image model, and where the figure came from. typedef ImageGenerationMemoryBudget = ({int bytes, String source}); +/// What the memory of a device means for a load: a model that needs more than +/// [refuse] cannot load, and one that needs more than [slower] loads with +/// part of it outside the device's own memory, which makes generation slower. +/// Either is `null` when it is not known or does not apply. +typedef ImageGenerationMemoryLimits = ({ + ImageGenerationMemoryBudget? refuse, + ImageGenerationMemoryBudget? slower, +}); + /// Kind of device a model loads on, which decides whose memory bounds it. enum ImageGenerationComputeDevice { /// The CPU: host memory. @@ -97,7 +106,8 @@ enum ImageGenerationComputeDevice { metal, /// Any other GPU, such as Vulkan: its own device memory as the runtime - /// reports it, or host memory when the GPU is an integrated one. + /// reports it, with host memory behind it for what does not fit, or host + /// memory alone when the GPU is an integrated one. otherGpu, } @@ -141,10 +151,10 @@ abstract interface class ImageGenerationDriver { /// model file headers; fewer at the end of the file. Future readFileRange(String path, int offset, int length); - /// Memory available to a new model on [device], or `null` when it is not - /// known. Asking a GPU other than Metal is a native call that can block, so - /// on native platforms it runs in a short-lived isolate. - Future memoryBudget( + /// The memory limits of a new model on [device]. Asking a GPU other than + /// Metal is a native call that can block, so on native platforms it runs + /// in a short-lived isolate. + Future memoryLimits( ImageGenerationComputeDevice device, ); diff --git a/lib/src/core/image/image_generation_driver_io.dart b/lib/src/core/image/image_generation_driver_io.dart index b5a8a13ec..552df69de 100644 --- a/lib/src/core/image/image_generation_driver_io.dart +++ b/lib/src/core/image/image_generation_driver_io.dart @@ -65,15 +65,18 @@ class _NativeImageGenerationDriver implements ImageGenerationDriver { readStableDiffusionFileRange(path, offset, length); @override - Future memoryBudget( + Future memoryLimits( ImageGenerationComputeDevice device, ) async { if (device != ImageGenerationComputeDevice.otherGpu) { - return readStableDiffusionMemoryBudget(device: device); + return ( + refuse: readStableDiffusionMemoryBudget(device: device), + slower: null, + ); } final readGpuMemory = _readGpuMemory; final logLevel = imageRuntimeLogLevel(); - return stableDiffusionGpuMemoryBudget( + return stableDiffusionGpuMemoryLimits( // The query is a native call that can block: the first one in a // process initializes the GPU backend. await Isolate.run(() => readGpuMemory(logLevel: logLevel)), diff --git a/lib/src/core/image/image_generation_driver_stub.dart b/lib/src/core/image/image_generation_driver_stub.dart index f3e0fa1fa..ec0e4317b 100644 --- a/lib/src/core/image/image_generation_driver_stub.dart +++ b/lib/src/core/image/image_generation_driver_stub.dart @@ -26,9 +26,9 @@ class _UnsupportedImageGenerationDriver implements ImageGenerationDriver { Future.error(probe().unavailableReason!); @override - Future memoryBudget( + Future memoryLimits( ImageGenerationComputeDevice device, - ) async => null; + ) async => (refuse: null, slower: null); @override Future start(ImageGenerationSessionConfig config) => diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index 6430864d8..bb674a65a 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -4,6 +4,7 @@ import 'dart:math'; import '../../backends/stable_diffusion/stable_diffusion_runtime_status.dart'; import '../engine/engine_capabilities.dart'; import '../exceptions.dart'; +import '../llama_logger.dart'; import '../models/config/compute_device.dart'; import '../models/download/model_download_manager.dart'; import '../models/model_format.dart'; @@ -310,15 +311,19 @@ class ImageGenerationEngine { /// available: on Android the larger of `MemAvailable` and half of physical /// memory less what the app already holds, `MemAvailable` on Linux, the /// app's remaining memory limit on iOS, and physical memory on macOS, - /// capped on Metal by the GPU's recommended working set. On a Vulkan GPU - /// it is the GPU's free memory when its driver reports that, its total - /// memory otherwise, and for an integrated GPU the host figure of its - /// platform; the GPU is asked off the calling isolate. The Windows CPU, an - /// integrated GPU on Windows, a GPU that does not report its memory and a - /// load with the `SD_VK_DEVICE` environment variable set are not checked. A - /// model that does not fit throws [LlamaModelException] naming both - /// figures, instead of letting the system kill the app or, on a Vulkan - /// GPU, the runtime keep the weights that do not fit in host memory. + /// capped on Metal by the GPU's recommended working set. A model that + /// does not fit throws [LlamaModelException] naming both figures, instead + /// of letting the system kill the app. + /// + /// A Vulkan GPU does not bound a model by itself: the runtime keeps the + /// weights that do not fit it in host memory. The GPU's figure, asked off + /// the calling isolate, is its free memory when its driver reports that + /// and its total memory otherwise. A model above it loads, generates more + /// slowly, and one `LlamaLogger` warning says so; on Linux it is refused + /// only above that figure plus `MemAvailable`. An integrated GPU on Linux + /// gets `MemAvailable` alone. Windows, a GPU that does not report its + /// memory and a load with the `SD_VK_DEVICE` environment variable set are + /// never refused. /// /// [download]'s cancel token stops a download at once and is checked again /// after classification and after the native load; the native load itself @@ -416,7 +421,7 @@ class ImageGenerationEngine { if (params.checkMemory) { _checkMemory( weightBytes, - await driver.memoryBudget(switch (backendName) { + await driver.memoryLimits(switch (backendName) { _ when _isMetal(backendName) => ImageGenerationComputeDevice.metal, _ when _isGpu(backendName) => ImageGenerationComputeDevice.otherGpu, _ => ImageGenerationComputeDevice.cpu, @@ -743,22 +748,28 @@ class ImageGenerationEngine { static void _checkMemory( int weightBytes, - ImageGenerationMemoryBudget? budget, + ImageGenerationMemoryLimits limits, ) { - if (budget == null) { - return; - } final required = estimateImageGenerationMemoryBytes(weightBytes); - if (required <= budget.bytes) { - return; + final needs = + 'The image model needs about ${_gib(required)} GiB ' + '(${_gib(weightBytes)} GiB of weights plus working memory)'; + final refuse = limits.refuse; + if (refuse != null && required > refuse.bytes) { + throw LlamaModelException( + '$needs, but only ${_gib(refuse.bytes)} GiB is available ' + '(${refuse.source}). Use a smaller or more quantized model, free ' + 'memory, or set ImageModelParams.checkMemory to false to try anyway.', + ); + } + final slower = limits.slower; + if (slower != null && required > slower.bytes) { + LlamaLogger.instance.warning( + '$needs, more than the ${_gib(slower.bytes)} GiB available ' + '(${slower.source}). stable-diffusion.cpp keeps the part that does ' + 'not fit in system memory, so generation will be slower.', + ); } - throw LlamaModelException( - 'The image model needs about ${_gib(required)} GiB ' - '(${_gib(weightBytes)} GiB of weights plus working memory), but only ' - '${_gib(budget.bytes)} GiB is available (${budget.source}). Use a ' - 'smaller or more quantized model, free memory, or set ' - 'ImageModelParams.checkMemory to false to try anyway.', - ); } static String _gib(int bytes) { diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index a558266e3..a8ae86965 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -136,10 +136,12 @@ description: >- of `MemAvailable` and half of `MemTotal` less the app's own memory, `MemAvailable` on Linux CPU, the app's limit on iOS, physical memory on macOS, capped on Metal by the GPU's recommended working set. On a Vulkan - GPU (Linux, Windows) it is the GPU's free memory when the driver reports - one, otherwise its total; an integrated GPU gets the host figure. The - Windows CPU and integrated GPUs on Windows are not checked, and the Vulkan - check has not run on a physical GPU yet. SD-Turbo usually + GPU a model larger than the GPU's memory still loads, slower, with one + `LlamaLogger` warning (the runtime keeps the rest in system memory); on + Linux it is refused only above the GPU's memory plus `MemAvailable`, and + on Windows never. An integrated GPU on Linux gets `MemAvailable`. The + Windows CPU is not checked, and the Vulkan figures are not validated on a + physical GPU yet. SD-Turbo usually loads on 8 GB Android phones when no chat model is loaded, and is usually refused on 6 GB ones; offer SDXS there. - `ImageModelParams(device: ComputeDevice.auto | cpu | gpu, threads: 0)`. diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart index f720776b3..2e7a231cf 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart @@ -363,13 +363,14 @@ void main() { }); }); - group('stableDiffusionGpuMemoryBudget', () { + group('stableDiffusionGpuMemoryLimits', () { const host = (bytes: 5 * _gib, source: 'MemAvailable in /proc/meminfo'); + const noLimits = (refuse: null, slower: null); - ImageGenerationMemoryBudget? budget( + ImageGenerationMemoryLimits limits( StableDiffusionGpuMemory? memory, { ImageGenerationMemoryBudget? hostBudget = host, - }) => stableDiffusionGpuMemoryBudget(memory, hostBudget: () => hostBudget); + }) => stableDiffusionGpuMemoryLimits(memory, hostBudget: () => hostBudget); StableDiffusionGpuMemory gpu({ required int total, @@ -382,64 +383,103 @@ void main() { integrated: integrated, ); - test('a discrete GPU whose driver reports a budget gives its free ' - 'memory', () { - expect(budget(gpu(total: 24 * _gib, free: 9 * _gib)), ( - bytes: 9 * _gib, - source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + test('a discrete GPU whose driver reports a budget is slower above its ' + 'free memory, and refuses above that plus host memory', () { + expect(limits(gpu(total: 24 * _gib, free: 9 * _gib)), ( + refuse: ( + bytes: 14 * _gib, + source: + '9.00 GiB of GPU memory and 5.00 GiB of system memory: free ' + 'GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB; ' + 'MemAvailable in /proc/meminfo', + ), + slower: ( + bytes: 9 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + ), )); - expect( - budget(gpu(total: 8 * _gib, free: 8 * _gib - 1))?.bytes, - 8 * _gib - 1, - ); - expect(budget(gpu(total: 8 * _gib, free: 1))?.bytes, 1); + for (final free in [8 * _gib - 1, 1]) { + final result = limits(gpu(total: 8 * _gib, free: free)); + expect(result.slower?.bytes, free); + expect(result.refuse?.bytes, free + 5 * _gib); + } }); test('a discrete GPU that reports its total as free, or nothing as free, ' - 'gives its total memory and says that free memory is unknown', () { + 'uses its total memory and says that free memory is unknown', () { for (final free in [8 * _gib, 0]) { - expect(budget(gpu(total: 8 * _gib, free: free)), ( - bytes: 8 * _gib, - source: - 'the GPU memory of Vulkan0 (NVIDIA L4), whose driver does not ' - 'report how much of it is free', + expect(limits(gpu(total: 8 * _gib, free: free)), ( + refuse: ( + bytes: 13 * _gib, + source: + '8.00 GiB of GPU memory and 5.00 GiB of system memory: the ' + 'GPU memory of Vulkan0 (NVIDIA L4), whose driver does not ' + 'report how much of it is free; MemAvailable in ' + '/proc/meminfo', + ), + slower: ( + bytes: 8 * _gib, + source: + 'the GPU memory of Vulkan0 (NVIDIA L4), whose driver does ' + 'not report how much of it is free', + ), ), reason: '$free'); } }); - test('an integrated GPU gives the host figure, never its own', () { - for (final (total, free) in [(64 * _gib, 60 * _gib), (2 * _gib, _gib)]) { - expect(budget(gpu(total: total, free: free, integrated: true)), ( - bytes: 5 * _gib, + test('a discrete GPU where host memory is not read, as on Windows, is ' + 'slower above its figure and refuses nothing', () { + expect(limits(gpu(total: 24 * _gib, free: 9 * _gib), hostBudget: null), ( + refuse: null, + slower: ( + bytes: 9 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + ), + )); + expect(limits(gpu(total: 8 * _gib, free: 8 * _gib), hostBudget: null), ( + refuse: null, + slower: ( + bytes: 8 * _gib, source: - 'MemAvailable in /proc/meminfo; Vulkan0 (NVIDIA L4) is an ' - 'integrated GPU, which uses host memory', + 'the GPU memory of Vulkan0 (NVIDIA L4), whose driver does ' + 'not report how much of it is free', + ), + )); + }); + + test('an integrated GPU refuses above the host figure, never its own, ' + 'and has nothing slower', () { + for (final (total, free) in [(64 * _gib, 60 * _gib), (2 * _gib, _gib)]) { + expect(limits(gpu(total: total, free: free, integrated: true)), ( + refuse: ( + bytes: 5 * _gib, + source: + 'MemAvailable in /proc/meminfo; Vulkan0 (NVIDIA L4) is an ' + 'integrated GPU, which uses host memory', + ), + slower: null, )); } }); - test('an integrated GPU has no budget where host memory is not read', () { + test('an integrated GPU has no limit where host memory is not read', () { expect( - budget( + limits( gpu(total: 16 * _gib, free: 8 * _gib, integrated: true), hostBudget: null, ), - isNull, + noLimits, ); }); - test('unknown memory has no budget, and the host is not asked for a ' - 'discrete GPU', () { + test('unknown memory has no limit, and the host is not asked', () { ImageGenerationMemoryBudget? unasked() => fail('asked the host'); - expect(budget(null), isNull); - expect(budget(gpu(total: 0, free: 0)), isNull); + expect(limits(null), noLimits); + expect(limits(gpu(total: 0, free: 0)), noLimits); expect( - stableDiffusionGpuMemoryBudget( - gpu(total: 8 * _gib, free: _gib), - hostBudget: unasked, - )?.bytes, - _gib, + stableDiffusionGpuMemoryLimits(null, hostBudget: unasked), + noLimits, ); }); }); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_params_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_params_test.dart index b9f253bc9..ac7ded888 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_params_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_params_test.dart @@ -60,6 +60,32 @@ void main() { }); }); + // The memory check of a Vulkan GPU admits a model larger than the GPU + // because the runtime's automatic fit keeps the rest in host memory. + // The fit is off when auto_fit is false or a params backend is named. + test('leaves the automatic fit as the runtime initialized it, for a ' + 'named and an unnamed backend', () { + for (final backend in [null, 'gpu', 'cpu']) { + using((arena) { + final params = arena(); + params.ref.auto_fit = true; + applyStableDiffusionContextParams( + params, + ImageGenerationSessionConfig( + files: const {'model': '/m/sdxs.gguf'}, + backend: backend, + threads: 0, + ), + arena, + ); + + expect(params.ref.auto_fit, isTrue, reason: '$backend'); + expect(params.ref.params_backend, nullptr, reason: '$backend'); + expect(params.ref.max_vram, nullptr, reason: '$backend'); + }); + } + }); + test('leaves unset roles, backend and threads at their defaults', () { using((arena) { final params = arena(); diff --git a/test/unit/core/image/image_generation_driver_io_test.dart b/test/unit/core/image/image_generation_driver_io_test.dart index 0ec3942c5..d0d6f4cff 100644 --- a/test/unit/core/image/image_generation_driver_io_test.dart +++ b/test/unit/core/image/image_generation_driver_io_test.dart @@ -118,59 +118,78 @@ void main() { reason: reason, ); expect( - (await driver.memoryBudget( + (await driver.memoryLimits( ImageGenerationComputeDevice.otherGpu, - ))?.source, + )).slower?.source, contains('log level ${expected.name}'), reason: reason, ); } }); - test('reports a CPU and Metal memory budget on macOS and Linux hosts, and ' - 'none for other GPUs on a host without the runtime', () async { + test('the CPU and Metal refuse above their budget on macOS and Linux ' + 'hosts and have nothing slower, and other GPUs have no limit on a host ' + 'without the runtime', () async { final driver = createImageGenerationDriver(); for (final device in [ ImageGenerationComputeDevice.cpu, ImageGenerationComputeDevice.metal, ]) { - final budget = await driver.memoryBudget(device); + final limits = await driver.memoryLimits(device); if (Platform.isMacOS || Platform.isLinux) { - expect(budget, isNotNull); - expect(budget!.bytes, greaterThan(0)); + expect(limits.refuse, isNotNull); + expect(limits.refuse!.bytes, greaterThan(0)); } else if (Platform.isWindows) { - expect(budget, isNull); + expect(limits.refuse, isNull); } + expect(limits.slower, isNull); } - expect( - await driver.memoryBudget(ImageGenerationComputeDevice.otherGpu), - isNull, - ); + expect(await driver.memoryLimits(ImageGenerationComputeDevice.otherGpu), ( + refuse: null, + slower: null, + )); }); - test('asks another GPU for its memory in another isolate, and budgets its ' - 'free memory', () async { + test('asks another GPU for its memory in another isolate: slower above ' + 'its free memory, refused above that plus host memory where the host ' + 'reads it', () async { final driver = createImageGenerationDriver( readGpuMemory: _gpuMemoryNamingItsIsolate, ); - final budget = await driver.memoryBudget( + final limits = await driver.memoryLimits( ImageGenerationComputeDevice.otherGpu, ); + final host = (await driver.memoryLimits( + ImageGenerationComputeDevice.cpu, + )).refuse; - expect(budget?.bytes, 6 << 30); - expect(budget?.source, contains('free GPU memory of spawned isolate')); + expect(limits.slower?.bytes, 6 << 30); + expect( + limits.slower?.source, + contains('free GPU memory of spawned isolate'), + ); + if (Platform.isMacOS || Platform.isLinux) { + // MemAvailable on Linux moves between the two reads. + expect( + limits.refuse!.bytes, + closeTo((6 << 30) + host!.bytes, Platform.isLinux ? 1 << 30 : 0), + ); + expect(limits.refuse!.source, endsWith(host.source)); + } else if (Platform.isWindows) { + expect(limits.refuse, isNull); + } }); - test('a GPU whose memory is not known has no budget, and the CPU and ' - 'Metal budgets do not ask it', () async { + test('a GPU whose memory is not known has no limit, and the CPU and ' + 'Metal limits do not ask it', () async { final driver = createImageGenerationDriver(readGpuMemory: _noGpuMemory); - expect( - await driver.memoryBudget(ImageGenerationComputeDevice.otherGpu), - isNull, - ); + expect(await driver.memoryLimits(ImageGenerationComputeDevice.otherGpu), ( + refuse: null, + slower: null, + )); final unasked = createImageGenerationDriver( readGpuMemory: _gpuMemoryNamingItsIsolate, @@ -180,7 +199,7 @@ void main() { ImageGenerationComputeDevice.metal, ]) { expect( - (await unasked.memoryBudget(device))?.source, + (await unasked.memoryLimits(device)).refuse?.source, isNot(contains('isolate')), ); } diff --git a/test/unit/core/image/image_generation_driver_stub_test.dart b/test/unit/core/image/image_generation_driver_stub_test.dart index 963d3dafd..12bab05ed 100644 --- a/test/unit/core/image/image_generation_driver_stub_test.dart +++ b/test/unit/core/image/image_generation_driver_stub_test.dart @@ -19,7 +19,7 @@ void main() { throwsA(isA()), ); for (final device in ImageGenerationComputeDevice.values) { - expect(await driver.memoryBudget(device), isNull); + expect(await driver.memoryLimits(device), (refuse: null, slower: null)); } await expectLater( driver.start( diff --git a/test/unit/core/image/image_generation_engine_test.dart b/test/unit/core/image/image_generation_engine_test.dart index 60ed4e470..f57fe5e8d 100644 --- a/test/unit/core/image/image_generation_engine_test.dart +++ b/test/unit/core/image/image_generation_engine_test.dart @@ -1030,34 +1030,146 @@ void main() { expect(driver.started, isEmpty); }); - test('refuses a model that does not fit a Vulkan GPU, naming the ' - 'estimate and the memory of the GPU', () async { - driver - ..status = _available('Vulkan0\tNVIDIA L4\nCPU\tHost\n') - ..sizes[_model] = 8 * _gib - ..budget = ( - bytes: 6 * _gib, - source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB', - ); + group('on a Vulkan GPU', () { + const gpuFigure = ( + bytes: 6 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB', + ); + const gpuAndHost = ( + bytes: 10 * _gib, + source: + '6.00 GiB of GPU memory and 4.00 GiB of system memory: free GPU ' + 'memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB; MemAvailable in ' + '/proc/meminfo', + ); + late List records; + + setUp(() { + driver.status = _available('Vulkan0\tNVIDIA L4\nCPU\tHost\n'); + records = []; + final logger = LlamaLogger.instance; + final level = logger.level; + logger + ..setLevel(LlamaLogLevel.debug) + ..setHandler(records.add); + addTearDown(() { + logger + ..setLevel(level) + ..setHandler(null); + }); + }); - await expectLater( - load(_sdxs()), - throwsA( - isA().having( - (error) => error.message, - 'message', - allOf( - contains('about 10.5 GiB'), - contains('only 6.00 GiB is available'), - contains( - 'free GPU memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB', + test('refuses a model that fits neither the GPU nor the GPU plus ' + 'system memory, naming the estimate and both figures', () async { + driver + ..sizes[_model] = 8 * _gib + ..budget = gpuAndHost + ..slowerBudget = gpuFigure; + + await expectLater( + load(_sdxs()), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('about 10.5 GiB'), + contains('only 10.0 GiB is available'), + contains('6.00 GiB of GPU memory'), + contains('4.00 GiB of system memory'), + contains('Vulkan0 (NVIDIA L4)'), + contains('MemAvailable in /proc/meminfo'), ), ), ), - ), - ); - expect(driver.budgetDevices, [ImageGenerationComputeDevice.otherGpu]); - expect(driver.started, isEmpty); + ); + expect(driver.budgetDevices, [ImageGenerationComputeDevice.otherGpu]); + expect(driver.started, isEmpty); + expect(records, isEmpty); + }); + + test('loads a model larger than the GPU that fits the GPU plus system ' + 'memory, with one warning that names the figures', () async { + driver + ..sizes[_model] = 6 * _gib + ..budget = gpuAndHost + ..slowerBudget = gpuFigure; + + await load(_sdxs()); + + expect(driver.started, hasLength(1)); + expect(records, hasLength(1)); + expect(records.single.level, LlamaLogLevel.warn); + expect( + records.single.message, + 'The image model needs about 8.00 GiB (6.00 GiB of weights plus ' + 'working memory), more than the 6.00 GiB available (free GPU ' + 'memory of Vulkan0 (NVIDIA L4), out of 22.5 GiB). ' + 'stable-diffusion.cpp keeps the part that does not fit in system ' + 'memory, so generation will be slower.', + ); + }); + + test('the estimate has to exceed a figure, not reach it', () async { + // 4 GiB of weights are estimated at 5.5 GiB, and 8 GiB at 10.5 GiB. + driver + ..slowerBudget = (bytes: 11 * _gib ~/ 2, source: 'the GPU') + ..budget = (bytes: 21 * _gib ~/ 2, source: 'the GPU and the host'); + + driver.sizes[_model] = 4 * _gib; + await load(_sdxs()); + expect(records, isEmpty); + + driver.sizes[_model] = 8 * _gib; + await load(_sdxs()); + expect(records, hasLength(1)); + expect(driver.started, hasLength(2)); + + driver.sizes[_model] = 8 * _gib + 4; + await expectLater(load(_sdxs()), throwsA(isA())); + driver.sizes[_model] = 4 * _gib + 4; + await load(_sdxs()); + expect(records, hasLength(2)); + }); + + test('where host memory is not read, as on Windows, a model of any ' + 'size loads with the warning', () async { + driver + ..sizes[_model] = 64 * _gib + ..budget = null + ..slowerBudget = gpuFigure; + + await load(_sdxs()); + + expect(driver.started, hasLength(1)); + expect(records.single.level, LlamaLogLevel.warn); + expect(records.single.message, contains('more than the 6.00 GiB')); + }); + + test('a model that fits the GPU loads without a warning', () async { + driver + ..sizes[_model] = 2 * _gib + ..budget = gpuAndHost + ..slowerBudget = gpuFigure; + + await load(_sdxs()); + + expect(driver.started, hasLength(1)); + expect(records, isEmpty); + }); + + test('checkMemory false neither asks, refuses nor warns', () async { + driver + ..sizes[_model] = 64 * _gib + ..budget = gpuAndHost + ..slowerBudget = gpuFigure; + + await load(_sdxs(), params: const ImageModelParams(checkMemory: false)); + + expect(driver.budgetDevices, isEmpty); + expect(driver.started, hasLength(1)); + expect(records, isEmpty); + }); }); test('counts every file toward the estimate', () async { @@ -1650,6 +1762,7 @@ final class _FakeDriver implements ImageGenerationDriver { _t5xxl: ImageModelHeaders.t5xxl, }; ImageGenerationMemoryBudget? budget; + ImageGenerationMemoryBudget? slowerBudget; Object? startError; final List started = []; _FakeSession session = _FakeSession(); @@ -1693,11 +1806,11 @@ final class _FakeDriver implements ImageGenerationDriver { final List budgetDevices = []; @override - Future memoryBudget( + Future memoryLimits( ImageGenerationComputeDevice device, ) async { budgetDevices.add(device); - return budget; + return (refuse: budget, slower: slowerBudget); } @override diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 6ae8dc9e5..3de4432d5 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -11,13 +11,14 @@ For canonical full release notes, use: - Adopt `leehack/stable-diffusion-native@v0.2.0-2` for the opt-in `stable_diffusion` image runtime. -- Check the memory of a Vulkan GPU before loading an image model on Linux and - Windows: `ImageGenerationEngine.load` refuses a model whose estimate - exceeds the GPU's free memory, or its total memory when the driver reports - no free figure, with `LlamaModelException` +- Check the memory of a Vulkan GPU before loading an image model ([stable-diffusion-native#9](https://github.com/leehack/stable-diffusion-native/issues/9)). - The check has not run on a physical Vulkan GPU yet, and - `ImageModelParams(checkMemory: false)` loads anyway. + On Linux `ImageGenerationEngine.load` refuses, with `LlamaModelException`, + a model that fits neither the GPU nor the GPU plus system memory. A model + larger than the GPU's memory still loads, with one warning, and runs + slower; on Windows it is warned about and never refused. Not validated on + a physical Vulkan GPU yet; `ImageModelParams(checkMemory: false)` skips + the check and the warning. - Quote the errors stable-diffusion.cpp logged in the `LlamaModelException` of an image model it cannot load, with files named by role ([stable-diffusion-native#3](https://github.com/leehack/stable-diffusion-native/issues/3)). diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index 258cc3cce..b68e3e3f0 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -682,37 +682,54 @@ device the model loads on: | iOS: Metal or CPU | The app's remaining memory limit (`os_proc_available_memory`) | | macOS: CPU | Physical memory | | macOS: Metal | Physical memory, capped at the GPU's `recommendedMaxWorkingSetSize` (about two thirds to three quarters of it) | -| Linux, Windows: Vulkan, discrete GPU | The GPU's free memory when its driver reports one (`VK_EXT_memory_budget`), otherwise its total memory | +| Linux: Vulkan, discrete GPU | The GPU's memory plus `MemAvailable`; a model larger than the GPU's memory alone loads with a warning | | Linux: Vulkan, integrated GPU | `MemAvailable`, as for the CPU | +| Windows: Vulkan, discrete GPU | Never refused; a model larger than the GPU's memory loads with a warning | | Windows: Vulkan, integrated GPU | Not checked | | Windows: CPU | Not checked | -A model that does not fit throws `LlamaModelException` naming both figures, -instead of the system killing the app. Set -`ImageModelParams(checkMemory: false)` to load anyway. - -The Vulkan figures are the runtime's, which are ggml's: the memory of the -GPU a model loads on by default, the first discrete GPU or else the first -integrated one. The engine asks for them in a short-lived isolate, because -the first such call in a process can initialize the GPU. - -- With a memory budget from the driver, the free figure is what this process - can still allocate on the GPU, so it accounts for other processes and for - image models already loaded. -- Without one the runtime reports the total as free. The engine then - compares with the total, and does the same for a free figure of 0: only a - model that cannot fit the GPU at all is refused. -- An integrated GPU uses host memory, and a driver that exposes it as several - heaps makes the GPU's own figures count it more than once. The engine - ignores them and compares with host memory, which it does not read on - Windows. -- Nothing is checked when the GPU does not report its memory, when the - `SD_VK_DEVICE` environment variable picks the Vulkan device, or with a - `stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2`. - -With the check off, stable-diffusion.cpp keeps the weights that do not fit a -Vulkan GPU in host memory, which is slower but does not fail the load. So -the check refuses there what would have loaded slowly before. +A model that does not fit throws `LlamaModelException` naming the estimate +and the figures, instead of the system killing the app. Set +`ImageModelParams(checkMemory: false)` to load anyway, without a check or a +warning. + +### Vulkan GPUs + +A discrete Vulkan GPU does not bound a model by itself. stable-diffusion.cpp +plans where each part of a model goes when it loads (its automatic fit, which +the engine leaves on): the diffusion model, the text encoders and the VAE +each go to the GPU when they fit its free memory with room to compute, +otherwise to system memory, otherwise to another GPU, otherwise they stay on +disk. A model larger than the GPU therefore loads and generates more slowly. + +So the engine works with two figures: + +- **The GPU's memory.** Its free memory when the driver reports a budget + (`VK_EXT_memory_budget`): what this process can still allocate, which + accounts for other processes and for image models already loaded. Without + a budget the runtime reports the total as free, so the engine uses the + total, and does the same for a free figure of 0. A model whose estimate + exceeds this figure loads, and the engine logs one warning through + [`LlamaLogging`](#runtime-logs) with both numbers and the device, saying + that part of the model stays in system memory and generation will be + slower. It is a `warn` record, so the default level `none` hides it. +- **The GPU's memory plus system memory** (`MemAvailable`, as for the CPU). + On Linux a model whose estimate exceeds this sum is refused. Windows does + not read system memory, so nothing is refused there and only the warning + applies. + +An integrated GPU uses host memory, and a driver that exposes it as several +heaps makes the GPU's own figures count it more than once. The engine ignores +them and compares with `MemAvailable` on Linux, as for the CPU. + +Nothing is checked or warned about when the GPU does not report its memory, +when the `SD_VK_DEVICE` environment variable picks the Vulkan device, or with +a `stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2`. + +The figures are the runtime's, which are ggml's, for the GPU a model loads on +by default: the first discrete GPU, or else the first integrated one. The +engine asks for them in a short-lived isolate, because the first such call in +a process can initialize the GPU. The Vulkan rules are tested on reported figures, and the call that reads them is checked on macOS Metal, where its total equals the working set above. The @@ -782,7 +799,9 @@ final engine = await ImageGenerationEngine.load(model); many. On an M4 Max an SDXS load recorded 28 messages at `info` and 40 at `debug`, and reading them took about 0.1 ms. - The runtime no longer writes ggml's device messages to stderr, at any - level. What a ggml backend writes to stderr itself still goes there. + level, the default `none` included: its recorder is always registered, + because the reason of a failed load comes from it. What a ggml backend + writes to stderr itself still goes there. - A `stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2` has no log to read: it logs as before, to stderr only. @@ -807,9 +826,13 @@ final engine = await ImageGenerationEngine.load(model); ([stable-diffusion-native#2](https://github.com/leehack/stable-diffusion-native/issues/2)). - iOS can abort a Metal command buffer under GPU pressure (seen once with SD-Turbo at four steps); the task fails and the next request runs. -- The Windows CPU and integrated GPUs on Windows are not memory-checked, and - the [memory check](#memory-check) of a Vulkan GPU has not run on a physical - GPU yet. Per-platform validation results, including timings, are in +- On Linux a model on a Vulkan GPU is refused only when it fits neither the + GPU nor the GPU plus system memory; one larger than the GPU's memory loads + with a warning and runs slower. On Windows such a model is warned about + and never refused, and the Windows CPU and integrated GPUs on Windows are + not memory-checked. The [Vulkan figures](#vulkan-gpus) have not been + validated on a physical Vulkan GPU yet. Per-platform validation results, + including timings, are in [#779](https://github.com/leehack/llamadart/issues/779). - The web has no image runtime yet ([#780](https://github.com/leehack/llamadart/issues/780)). From 277e2c5dc8c2c4f90d19b22d13c44e73d7f96fe4 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 20:54:58 -0400 Subject: [PATCH 3/4] fix: follow the runtime's GPU choice in the Vulkan memory check on hosts with several GPUs With no backend named, stable-diffusion.cpp's automatic fit computes on the discrete GPU with the most free memory and can keep weights on the other GPUs. The check read the first discrete GPU only, so on a host with a small GPU listed before a large one it could refuse a model the runtime loads. - The check now asks every GPU (sd_dart_gpu_device_count, then sd_dart_gpu_device_memory by index, in the same short-lived isolate). - A model is refused only above the figures of all discrete GPUs plus the host figure. - The warning uses the GPU that computes: the discrete GPU with the most memory for ComputeDevice.auto, the first one for ComputeDevice.gpu. - Integrated GPUs add nothing beside a discrete one. A GPU that does not report its memory, or a runtime without the count function, means no check. - A count of dropped log messages that rises with nothing new to read is reported once, not again by the next read. - The guide says that the runtime logs each prompt at the debug level. Refs #966, leehack/stable-diffusion-native#9. --- doc/llama_cpp_exit_teardown.md | 18 +- .../test/fixtures/image_exit_probe.dart | 4 +- .../test/image_generation_e2e_test.dart | 4 +- .../stable_diffusion_calls.dart | 70 ++-- .../stable_diffusion_image_worker.dart | 11 +- .../stable_diffusion_memory.dart | 154 +++++---- .../core/image/image_generation_driver.dart | 13 +- .../image/image_generation_driver_io.dart | 13 +- .../image/image_generation_driver_stub.dart | 5 +- .../core/image/image_generation_engine.dart | 17 +- skills/llamadart-image-generation/SKILL.md | 13 +- .../fake_stable_diffusion_runtime.dart | 83 +++-- .../stable_diffusion_calls_test.dart | 30 +- .../stable_diffusion_image_worker_test.dart | 24 ++ .../stable_diffusion_memory_test.dart | 324 ++++++++++++++---- .../image_generation_driver_io_test.dart | 79 ++++- .../image_generation_driver_stub_test.dart | 5 +- .../image/image_generation_engine_test.dart | 43 ++- website/docs/guides/image-generation.md | 61 ++-- 19 files changed, 704 insertions(+), 267 deletions(-) diff --git a/doc/llama_cpp_exit_teardown.md b/doc/llama_cpp_exit_teardown.md index 6c19cc43f..6b98e7c7f 100644 --- a/doc/llama_cpp_exit_teardown.md +++ b/doc/llama_cpp_exit_teardown.md @@ -169,9 +169,10 @@ stand-in: - `sd_dart_log_enable`, `sd_dart_log_set_level`, `sd_dart_log_read`, `sd_dart_log_dropped` and `sd_dart_last_error` (`v0.2.0-2`): see "Image log". -- `sd_dart_gpu_device_memory` (`v0.2.0-2`) reads the memory of the default - GPU for the memory check of a Vulkan GPU. It runs in a short-lived isolate - of its own (`readStableDiffusionGpuMemory`), not in a worker. +- `sd_dart_gpu_device_count` and `sd_dart_gpu_device_memory` (`v0.2.0-2`) + read the memory of every GPU for the memory check of Vulkan GPUs. They run + in a short-lived isolate of their own (`readStableDiffusionGpuMemory`), not + in a worker. - Upstream calls that return at once: `sd_ctx_params_init`, `sd_ctx_supports_image_generation` and `sd_get_model_version_name` right after the load, `sd_img_gen_params_init` and `free_sd_images`. @@ -193,7 +194,7 @@ differs from the core pin. The functions `v0.2.0-2` added are optional: `StableDiffusionCalls.log` binds the five log functions when the runtime exports all of them, and -`gpuDeviceMemory` its one, and each is `null` otherwise +`gpu` its two device queries, and each is `null` otherwise (`StableDiffusionCalls.optionalNativeRelease`). On such a runtime image generation works as it did on `v0.2.0-1`: no log call is made, a failed load names the missing file roles and the release that reports reasons, and a @@ -219,10 +220,11 @@ runtime's default waits apply. - It waits up to two seconds for an `sd_dart_exit_free` in flight, and gives a thread 250 ms after its last such call, which covers the short upstream calls after a load. -- A device query (`sd_dart_gpu_device_memory`) in flight is waited for like a - load, up to 15 seconds, also when nothing is tracked: it reads ggml's - device registry, which C `exit` destroys. llamadart makes the query only - for a Vulkan GPU, on Linux and Windows, where teardown runs only when a +- A device query (`sd_dart_gpu_device_count`, `sd_dart_gpu_device_memory`) + in flight is waited for like a load, up to 15 seconds, also when nothing + is tracked: it reads ggml's device registry, which C `exit` destroys. + llamadart makes the queries only for Vulkan GPUs, on Linux and Windows, + where teardown runs only when a native host calls it. The probe's `sd_list_devices`, which initializes the devices first, is upstream's function and is not waited for. - The log reads (`sd_dart_log_read`, `sd_dart_log_dropped`, diff --git a/example/basic_app/test/fixtures/image_exit_probe.dart b/example/basic_app/test/fixtures/image_exit_probe.dart index 6e3afa5a2..59c9b20c7 100644 --- a/example/basic_app/test/fixtures/image_exit_probe.dart +++ b/example/basic_app/test/fixtures/image_exit_probe.dart @@ -52,8 +52,8 @@ Future main(List args) async { } } final calls = StableDiffusionCalls.tryResolve()!; - if (calls.log == null || calls.gpuDeviceMemory == null) { - throw StateError('The pinned runtime lacks the log or device memory'); + if (calls.log == null || calls.gpu == null) { + throw StateError('The pinned runtime lacks the log or the GPU queries'); } _reached(scenario); case 'quiet': diff --git a/example/basic_app/test/image_generation_e2e_test.dart b/example/basic_app/test/image_generation_e2e_test.dart index 4fc241231..b46f291d3 100644 --- a/example/basic_app/test/image_generation_e2e_test.dart +++ b/example/basic_app/test/image_generation_e2e_test.dart @@ -246,13 +246,13 @@ void main() { test('the GPU memory the runtime reports for Metal is the working set ' 'the memory check reads itself', () async { - final memory = await Isolate.run(readStableDiffusionGpuMemory); + final memory = (await Isolate.run(readStableDiffusionGpuMemory))!.single; final workingSet = readStableDiffusionMemoryBudget( device: ImageGenerationComputeDevice.metal, )!; print( - 'IMAGE_GPU_MEMORY ${memory!.name}: total ${memory.totalBytes}, free ' + 'IMAGE_GPU_MEMORY ${memory.name}: total ${memory.totalBytes}, free ' '${memory.freeBytes}, integrated ${memory.integrated}; ' '${workingSet.source}: ${workingSet.bytes}', ); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart index ad7ce0619..03f8df096 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_calls.dart @@ -26,6 +26,7 @@ typedef _GenerateImageNative = typedef _CancelGenerationNative = Void Function(Pointer, UnsignedInt); typedef _ExitFreeNative = Void Function(Pointer); +typedef _GpuDeviceCountNative = Int32 Function(); typedef _GpuDeviceMemoryNative = Int32 Function(Int32, Pointer); typedef _LogEnableNative = Void Function(); @@ -58,7 +59,7 @@ typedef _LastErrorNative = Size Function(Pointer, Size); /// has no way to report progress without a Dart callback, so image /// generation is unsupported on it rather than falling back. /// -/// [log] and [gpuDeviceMemory] are the functions [optionalNativeRelease] +/// [log] and [gpu] are the functions [optionalNativeRelease] /// added. Each group is bound only when the runtime exports all of it, and is /// `null` otherwise: a runtime between the two releases still generates /// images, without the runtime's log and its reason for a failed load, and @@ -89,7 +90,7 @@ final class StableDiffusionCalls { required this.imageGenerationParamsInit, required this.freeImages, this.log, - this.gpuDeviceMemory, + this.gpu, }); /// The oldest `stable-diffusion-native` release that exports the `sd_dart_` @@ -119,12 +120,15 @@ final class StableDiffusionCalls { 'sd_dart_last_error', ]; - /// The `sd_dart_` function of [gpuDeviceMemory]. - static const List deviceMemorySymbols = ['sd_dart_gpu_device_memory']; + /// The `sd_dart_` functions of [gpu]. + static const List deviceMemorySymbols = [ + 'sd_dart_gpu_device_count', + 'sd_dart_gpu_device_memory', + ]; /// Resolves the calls from the bundled runtime, or returns `null` when it - /// does not export every one of [wrapperSymbols]. [log] and - /// [gpuDeviceMemory] are `null` when it does not export theirs. + /// does not export every one of [wrapperSymbols]. [log] and [gpu] are + /// `null` when it does not export theirs. /// /// [symbol] replaces the lookup: it returns the address of the function /// exported under a name, and throws [ArgumentError] when there is none. @@ -181,6 +185,10 @@ final class StableDiffusionCalls { 'sd_dart_last_error' => Native.addressOf>( sd.sd_dart_last_error, ), + 'sd_dart_gpu_device_count' => + Native.addressOf>( + sd.sd_dart_gpu_device_count, + ), 'sd_dart_gpu_device_memory' => Native.addressOf>( sd.sd_dart_gpu_device_memory, @@ -246,10 +254,15 @@ final class StableDiffusionCalls { ).asFunction(), ), ), - gpuDeviceMemory: optional( - () => function<_GpuDeviceMemoryNative>( - 'sd_dart_gpu_device_memory', - ).asFunction(), + gpu: optional( + () => StableDiffusionGpuCalls( + deviceCount: function<_GpuDeviceCountNative>( + 'sd_dart_gpu_device_count', + ).asFunction(), + deviceMemory: function<_GpuDeviceMemoryNative>( + 'sd_dart_gpu_device_memory', + ).asFunction(), + ), ), ); } @@ -324,20 +337,35 @@ final class StableDiffusionCalls { /// [optionalNativeRelease]. final StableDiffusionLogCalls? log; - /// `sd_dart_gpu_device_memory`, or `null` on a runtime older than - /// [optionalNativeRelease]: writes the memory of GPU `deviceIndex`, or of - /// the device a context with no backend uses for - /// `SD_DART_GPU_DEFAULT_DEVICE`, to `out` and returns an - /// `sd_dart_gpu_status`. - /// - /// The first query in a process initializes the GPU backend, which on Metal - /// with an empty shader cache takes many seconds, so it never runs on a UI - /// isolate. It is a call exit teardown waits for, with the bound of a load. + /// The runtime's GPU device queries, or `null` on a runtime older than + /// [optionalNativeRelease]. + final StableDiffusionGpuCalls? gpu; +} + +/// The GPU device queries of the stable_diffusion runtime. +/// +/// The first query in a process initializes the GPU backend, which on Metal +/// with an empty shader cache takes many seconds, so none runs on a UI +/// isolate. Each is a call exit teardown waits for, with the bound of a load. +final class StableDiffusionGpuCalls { + /// Creates the calls from functions. + const StableDiffusionGpuCalls({ + required this.deviceCount, + required this.deviceMemory, + }); + + /// `sd_dart_gpu_device_count`: the number of GPU devices, discrete and + /// integrated, numbered from 0 in the order `sd_list_devices` lists them, + /// or a negative `sd_dart_gpu_status` without a GPU backend. + final int Function() deviceCount; + + /// `sd_dart_gpu_device_memory`: writes the memory, type and name of GPU + /// `deviceIndex` to `out` and returns an `sd_dart_gpu_status`. final int Function( int deviceIndex, Pointer out, - )? - gpuDeviceMemory; + ) + deviceMemory; } /// The log recorder of the stable_diffusion runtime: the library copies each 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 8b9025700..130a6f656 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:ffi'; import 'dart:isolate'; +import 'dart:math'; import 'package:ffi/ffi.dart'; @@ -417,10 +418,12 @@ final class _LogBatch { void deliver() { final known = StableDiffusionImageWorker._logPosition; - // Two workers that read at once can finish out of order. - if (position.after > known.after) { - StableDiffusionImageWorker._logPosition = position; - } + // Two workers that read at once can finish out of order, and the + // dropped count can rise with no new message to read. + StableDiffusionImageWorker._logPosition = ( + after: max(position.after, known.after), + dropped: max(position.dropped, known.dropped), + ); // No caller awaits these records, so `emit` prints an error of the log // handler instead of throwing it into the port. for (final record in records) { diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart index 12a066c72..42ca7f0cb 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart @@ -118,16 +118,16 @@ typedef StableDiffusionGpuMemory = ({ bool integrated, }); -/// The memory of the GPU a context with no named device loads on (the first -/// discrete GPU, or else the first integrated one), from +/// The memory of every GPU the runtime lists, discrete and integrated, in +/// the runtime's device order, from `sd_dart_gpu_device_count` and /// `sd_dart_gpu_device_memory`, or `null` when it is not known: /// /// - the runtime is older than `StableDiffusionCalls.optionalNativeRelease` -/// and does not export the query; -/// - the runtime has no GPU backend or found no GPU, or the device does not -/// report its memory; -/// - `SD_VK_DEVICE` is set: such a context then loads on the Vulkan device of -/// that number if it initializes, which the query does not follow. +/// and does not export the queries; +/// - the runtime has no GPU backend or found no GPU, or one of the devices +/// does not report its memory; +/// - `SD_VK_DEVICE` is set, which can make the runtime pick a Vulkan device +/// by number. /// /// The first query in a process initializes the GPU backend, as a load /// otherwise does, which can take many seconds, and exit teardown waits for @@ -138,7 +138,7 @@ typedef StableDiffusionGpuMemory = ({ /// /// [resolveCalls] and [environment] default to the bundled runtime and the /// process environment; tests replace them. -StableDiffusionGpuMemory? readStableDiffusionGpuMemory({ +List? readStableDiffusionGpuMemory({ StableDiffusionCalls? Function() resolveCalls = StableDiffusionCalls.tryResolve, LlamaLogLevel logLevel = LlamaLogLevel.none, @@ -148,38 +148,47 @@ StableDiffusionGpuMemory? readStableDiffusionGpuMemory({ return null; } final calls = resolveCalls(); - final query = calls?.gpuDeviceMemory; - if (calls == null || query == null) { + final gpu = calls?.gpu; + if (calls == null || gpu == null) { return null; } final log = calls.log; if (log != null) { recordStableDiffusionLog(log, logLevel); } + final count = gpu.deviceCount(); + if (count <= 0) { + return null; + } return using((arena) { final out = arena(); - final status = query(sd.SD_DART_GPU_DEFAULT_DEVICE, out); - if (status != sd.sd_dart_gpu_status.SD_DART_GPU_OK.value) { - return null; + final devices = []; + for (var index = 0; index < count; index++) { + final status = gpu.deviceMemory(index, out); + if (status != sd.sd_dart_gpu_status.SD_DART_GPU_OK.value) { + return null; + } + final memory = out.ref; + final name = _text(memory.name, 64); + final description = _text(memory.description, 256); + devices.add(( + name: description.isEmpty ? name : '$name ($description)', + totalBytes: memory.total_bytes, + freeBytes: memory.free_bytes, + integrated: + memory.type == + sd.sd_dart_gpu_device_type.SD_DART_GPU_DEVICE_INTEGRATED.value, + )); } - final memory = out.ref; - final name = _text(memory.name, 64); - final description = _text(memory.description, 256); - return ( - name: description.isEmpty ? name : '$name ($description)', - totalBytes: memory.total_bytes, - freeBytes: memory.free_bytes, - integrated: - memory.type == - sd.sd_dart_gpu_device_type.SD_DART_GPU_DEVICE_INTEGRATED.value, - ); + return devices; }); } -/// The memory limits of a new image model on the GPU [memory] describes; -/// neither is known when [memory] is `null`. +/// The memory limits of a new image model on the GPUs [gpus] describes, in +/// the runtime's device order; neither is known when [gpus] is `null` or +/// empty, or one of them reports no memory. /// -/// The GPU's figure: +/// A GPU's figure: /// - with a budget from the driver (`VK_EXT_memory_budget`), its free memory, /// which is what this process can still allocate there and so accounts for /// other processes and for models already loaded; @@ -187,65 +196,94 @@ StableDiffusionGpuMemory? readStableDiffusionGpuMemory({ /// free, so equal figures mean "not reported", and so does a free figure of /// 0, which a driver whose budget is below the process's use gives. /// -/// A discrete GPU does not bound a load by itself: stable-diffusion.cpp's +/// Discrete GPUs do not bound a load by themselves: stable-diffusion.cpp's /// automatic fit, which llamadart leaves on, keeps the weights that do not -/// fit the GPU in host memory. So a model above the GPU's figure is only -/// `slower`, and it is refused above that figure plus [hostBudget], the -/// figure the CPU gets. Where host memory is not read, as on Windows, -/// nothing is refused. +/// fit the GPU it computes on in host memory, or on another GPU. That GPU is +/// the discrete one with the most free memory when [runtimePicksGpu] (no +/// backend is named), and the first discrete one for the backend `gpu`. So a +/// model above that GPU's figure is only `slower`, and it is refused above +/// the figures of all discrete GPUs plus [hostBudget], the figure the CPU +/// gets. Where host memory is not read, as on Windows, nothing is refused. /// /// An integrated GPU uses host memory, and a driver that exposes that as /// several heaps has it counted more than once in the device's figures. They -/// are not used: a model is refused above [hostBudget] alone. +/// are never used: beside a discrete GPU an integrated one adds nothing, and +/// with integrated GPUs only a model is refused above [hostBudget] alone. ImageGenerationMemoryLimits stableDiffusionGpuMemoryLimits( - StableDiffusionGpuMemory? memory, { + List? gpus, { + required bool runtimePicksGpu, required ImageGenerationMemoryBudget? Function() hostBudget, }) { - if (memory == null || memory.totalBytes <= 0) { + if (gpus == null || gpus.isEmpty || gpus.any((gpu) => gpu.totalBytes <= 0)) { return (refuse: null, slower: null); } final host = hostBudget(); - if (memory.integrated) { + final discrete = [ + for (final gpu in gpus) + if (!gpu.integrated) _gpuFigure(gpu), + ]; + if (discrete.isEmpty) { return ( refuse: host == null ? null : ( bytes: host.bytes, source: - '${host.source}; ${memory.name} is an integrated GPU, which ' - 'uses host memory', + '${host.source}; ${gpus.first.name} is an integrated GPU, ' + 'which uses host memory', ), slower: null, ); } - final budgeted = memory.freeBytes > 0 && memory.freeBytes < memory.totalBytes; - final ImageGenerationMemoryBudget gpu = budgeted - ? ( - bytes: memory.freeBytes, - source: - 'free GPU memory of ${memory.name}, out of ' - '${_gib(memory.totalBytes)} GiB', - ) - : ( - bytes: memory.totalBytes, - source: - 'the GPU memory of ${memory.name}, whose driver does not ' - 'report how much of it is free', - ); + var computing = discrete.first; + if (runtimePicksGpu) { + for (final figure in discrete.skip(1)) { + if (figure.bytes > computing.bytes) { + computing = figure; + } + } + } + final gpuBytes = discrete.fold(0, (sum, figure) => sum + figure.bytes); return ( refuse: host == null ? null : ( - bytes: gpu.bytes + host.bytes, - source: - '${_gib(gpu.bytes)} GiB of GPU memory and ' - '${_gib(host.bytes)} GiB of system memory: ${gpu.source}; ' - '${host.source}', + bytes: gpuBytes + host.bytes, + source: [ + if (discrete.length == 1) + '${_gib(gpuBytes)} GiB of GPU memory and ' + '${_gib(host.bytes)} GiB of system memory: ' + '${discrete.single.source}' + else ...[ + '${_gib(gpuBytes)} GiB of GPU memory on ${discrete.length} ' + 'GPUs and ${_gib(host.bytes)} GiB of system memory: ' + '${_gib(discrete.first.bytes)} GiB, ' + '${discrete.first.source}', + for (final figure in discrete.skip(1)) + '${_gib(figure.bytes)} GiB, ${figure.source}', + ], + host.source, + ].join('; '), ), - slower: gpu, + slower: computing, ); } +ImageGenerationMemoryBudget _gpuFigure(StableDiffusionGpuMemory gpu) => + gpu.freeBytes > 0 && gpu.freeBytes < gpu.totalBytes + ? ( + bytes: gpu.freeBytes, + source: + 'free GPU memory of ${gpu.name}, out of ' + '${_gib(gpu.totalBytes)} GiB', + ) + : ( + bytes: gpu.totalBytes, + source: + 'the GPU memory of ${gpu.name}, whose driver does not report how ' + 'much of it is free', + ); + String _gib(int bytes) { final gib = bytes / (1 << 30); return gib.toStringAsFixed(gib < 10 ? 2 : 1); diff --git a/lib/src/core/image/image_generation_driver.dart b/lib/src/core/image/image_generation_driver.dart index 55b459fe6..28d40503a 100644 --- a/lib/src/core/image/image_generation_driver.dart +++ b/lib/src/core/image/image_generation_driver.dart @@ -151,12 +151,15 @@ abstract interface class ImageGenerationDriver { /// model file headers; fewer at the end of the file. Future readFileRange(String path, int offset, int length); - /// The memory limits of a new model on [device]. Asking a GPU other than - /// Metal is a native call that can block, so on native platforms it runs - /// in a short-lived isolate. + /// The memory limits of a new model on [device]. [runtimePicksGpu] says + /// that the load names no backend, so with several GPUs the runtime + /// computes on the one with the most free memory, not on the first. + /// Asking GPUs other than Metal is a native call that can block, so on + /// native platforms it runs in a short-lived isolate. Future memoryLimits( - ImageGenerationComputeDevice device, - ); + ImageGenerationComputeDevice device, { + required bool runtimePicksGpu, + }); /// Loads a native context. On native platforms the runtime's messages /// reach `LlamaLogger` from then on, at the levels `LlamaLogging` has when diff --git a/lib/src/core/image/image_generation_driver_io.dart b/lib/src/core/image/image_generation_driver_io.dart index 552df69de..4b06e56af 100644 --- a/lib/src/core/image/image_generation_driver_io.dart +++ b/lib/src/core/image/image_generation_driver_io.dart @@ -13,10 +13,9 @@ import 'image_generation_driver.dart'; typedef ImageRuntimeProbe = StableDiffusionRuntimeStatus Function({LlamaLogLevel logLevel}); -/// Reads the memory of the default GPU, recording the runtime's log at a -/// level. +/// Reads the memory of every GPU, recording the runtime's log at a level. typedef ImageGpuMemoryReader = - StableDiffusionGpuMemory? Function({LlamaLogLevel logLevel}); + List? Function({LlamaLogLevel logLevel}); /// Creates the driver for the bundled stable_diffusion runtime. /// @@ -66,8 +65,9 @@ class _NativeImageGenerationDriver implements ImageGenerationDriver { @override Future memoryLimits( - ImageGenerationComputeDevice device, - ) async { + ImageGenerationComputeDevice device, { + required bool runtimePicksGpu, + }) async { if (device != ImageGenerationComputeDevice.otherGpu) { return ( refuse: readStableDiffusionMemoryBudget(device: device), @@ -77,9 +77,10 @@ class _NativeImageGenerationDriver implements ImageGenerationDriver { final readGpuMemory = _readGpuMemory; final logLevel = imageRuntimeLogLevel(); return stableDiffusionGpuMemoryLimits( - // The query is a native call that can block: the first one in a + // The queries are native calls that can block: the first one in a // process initializes the GPU backend. await Isolate.run(() => readGpuMemory(logLevel: logLevel)), + runtimePicksGpu: runtimePicksGpu, hostBudget: readStableDiffusionMemoryBudget, ); } diff --git a/lib/src/core/image/image_generation_driver_stub.dart b/lib/src/core/image/image_generation_driver_stub.dart index ec0e4317b..c44f18ddc 100644 --- a/lib/src/core/image/image_generation_driver_stub.dart +++ b/lib/src/core/image/image_generation_driver_stub.dart @@ -27,8 +27,9 @@ class _UnsupportedImageGenerationDriver implements ImageGenerationDriver { @override Future memoryLimits( - ImageGenerationComputeDevice device, - ) async => (refuse: null, slower: null); + ImageGenerationComputeDevice device, { + required bool runtimePicksGpu, + }) async => (refuse: null, slower: null); @override Future start(ImageGenerationSessionConfig config) => diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index bb674a65a..310ce7323 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -316,12 +316,15 @@ class ImageGenerationEngine { /// of letting the system kill the app. /// /// A Vulkan GPU does not bound a model by itself: the runtime keeps the - /// weights that do not fit it in host memory. The GPU's figure, asked off - /// the calling isolate, is its free memory when its driver reports that - /// and its total memory otherwise. A model above it loads, generates more - /// slowly, and one `LlamaLogger` warning says so; on Linux it is refused - /// only above that figure plus `MemAvailable`. An integrated GPU on Linux - /// gets `MemAvailable` alone. Windows, a GPU that does not report its + /// weights that do not fit it in host memory, or on another GPU. A GPU's + /// figure, asked off the calling isolate, is its free memory when its + /// driver reports that and its total memory otherwise. A model above the + /// figure of the GPU it computes on (with [ComputeDevice.auto] the + /// discrete GPU with the most free memory, with [ComputeDevice.gpu] the + /// first) loads, generates more slowly, and one `LlamaLogger` warning says + /// so; on Linux it is refused only above the figures of all discrete GPUs + /// plus `MemAvailable`. An integrated GPU on Linux gets `MemAvailable` + /// alone. Windows, a GPU that does not report its /// memory and a load with the `SD_VK_DEVICE` environment variable set are /// never refused. /// @@ -425,7 +428,7 @@ class ImageGenerationEngine { _ when _isMetal(backendName) => ImageGenerationComputeDevice.metal, _ when _isGpu(backendName) => ImageGenerationComputeDevice.otherGpu, _ => ImageGenerationComputeDevice.cpu, - }), + }, runtimePicksGpu: params.device == ComputeDevice.auto), ); } final files = { diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index a8ae86965..375759d99 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -136,10 +136,12 @@ description: >- of `MemAvailable` and half of `MemTotal` less the app's own memory, `MemAvailable` on Linux CPU, the app's limit on iOS, physical memory on macOS, capped on Metal by the GPU's recommended working set. On a Vulkan - GPU a model larger than the GPU's memory still loads, slower, with one - `LlamaLogger` warning (the runtime keeps the rest in system memory); on - Linux it is refused only above the GPU's memory plus `MemAvailable`, and - on Windows never. An integrated GPU on Linux gets `MemAvailable`. The + GPU a model larger than the memory of the GPU that computes (with several + discrete GPUs, the one with the most free memory for `ComputeDevice.auto`) + still loads, slower, with one `LlamaLogger` warning (the runtime keeps the + rest in system memory); on Linux it is refused only above the memory of + every discrete GPU plus `MemAvailable`, and on Windows never. An + integrated GPU on Linux gets `MemAvailable`. The Windows CPU is not checked, and the Vulkan figures are not validated on a physical GPU yet. SD-Turbo usually loads on 8 GB Android phones when no chat model is loaded, and is usually @@ -224,7 +226,8 @@ description: >- - Runtime messages reach the `LlamaLogging.configure` handler when both `level` and `nativeLevel` admit them (default `none`: nothing is logged, to stderr either). Configure before `load`; messages arrive after each - load and generation, not during one. + load and generation, not during one. At `debug` they include each prompt + verbatim. ## Examples diff --git a/test/support/fake_stable_diffusion_runtime.dart b/test/support/fake_stable_diffusion_runtime.dart index 449d121d9..b1d54843c 100644 --- a/test/support/fake_stable_diffusion_runtime.dart +++ b/test/support/fake_stable_diffusion_runtime.dart @@ -39,10 +39,7 @@ const _logHistory = _logState + 4; const _logLatest = _logState + 8; const _logReadTo = _logState + 16; const _logDropped = _logState + 24; -const _gpuStatus = _logState + 32; -const _gpuType = _logState + 36; -const _gpuTotal = _logState + 40; -const _gpuFree = _logState + 48; +const _gpuCount = _logState + 32; const _lastErrorLength = _logState + 56; const _lastError = _logState + 64; const _lastErrorBytes = 1024; @@ -51,7 +48,11 @@ const _modelPathBytes = 512; const _logSlots = _modelPath + _modelPathBytes; const _logSlotCount = 256; const _logSlotBytes = 512; -const _stateBytes = _logSlots + _logSlotCount * _logSlotBytes; +// One GPU: status and type as Int32, then total and free as Int64. +const _gpus = _logSlots + _logSlotCount * _logSlotBytes; +const _gpuBytes = 24; +const _maxGpus = 4; +const _stateBytes = _gpus + _maxGpus * _gpuBytes; // sd_log_level_t. const _sdLogDebug = 0; @@ -85,7 +86,7 @@ final class FakeStableDiffusionRuntime { _state.cast()[_pauseAfter ~/ 4] = -1; _state.cast()[_logThreshold ~/ 4] = _sdLogInfo; _state.cast()[_logHistory ~/ 4] = logHistory; - _state.cast()[_gpuStatus ~/ 4] = -2; + _state.cast()[_gpuCount ~/ 4] = -2; final version = 'SD 2.x'.codeUnits; for (var i = 0; i < version.length; i++) { _state[_modelVersion + i] = version[i]; @@ -121,20 +122,40 @@ final class FakeStableDiffusionRuntime { /// memory. set olderRelease(bool value) => _state[_olderRelease] = value ? 1 : 0; - /// What `sd_dart_gpu_device_memory` answers for the default device: a - /// [status] other than 0 (`SD_DART_GPU_NO_BACKEND` at first) and nothing - /// else, or `Vulkan0`, a `Fake GPU`, with [total] and [free] bytes. + /// The GPUs the runtime lists: device `i` is `Vulkan`, a `Fake GPU `, + /// with its total and free bytes, and `sd_dart_gpu_device_memory` answers + /// its status when that is not 0. Past the last one it answers + /// `SD_DART_GPU_NO_DEVICE`. + set gpus(List<({int total, int free, bool integrated, int status})> devices) { + _state.cast()[_gpuCount ~/ 4] = devices.length; + for (final (index, device) in devices.indexed) { + final entry = _state + _gpus + index * _gpuBytes; + entry.cast()[0] = device.status; + entry.cast()[1] = device.integrated ? 2 : 1; + entry.cast()[1] = device.total; + entry.cast()[2] = device.free; + } + } + + /// What `sd_dart_gpu_device_count` answers instead of a count: + /// `SD_DART_GPU_NO_BACKEND` at first. + set gpuCountStatus(int status) => + _state.cast()[_gpuCount ~/ 4] = status; + + /// One GPU, as [gpus]. void setGpuMemory({ int status = 0, int total = 0, int free = 0, bool integrated = false, - }) { - _state.cast()[_gpuStatus ~/ 4] = status; - _state.cast()[_gpuType ~/ 4] = integrated ? 2 : 1; - _state.cast()[_gpuTotal ~/ 8] = total; - _state.cast()[_gpuFree ~/ 8] = free; - } + }) => gpus = [ + (total: total, free: free, integrated: integrated, status: status), + ]; + + /// Adds [count] to the messages the runtime dropped without recording + /// one, as a recorder that could not take its buffer in time does. + void dropUnrecorded(int count) => + _state.cast()[_logDropped ~/ 8] += count; /// The model path the last load read from its context parameters, or an /// empty string when they had none. @@ -347,23 +368,36 @@ final class _FakeCalls { ? 'sd_dart_gpu_device_memory:$deviceIndex' : 'sd_dart_gpu_device_memory:$deviceIndex:before-log-enable', ); - final status = _ints[_gpuStatus ~/ 4]; + if (deviceIndex < 0 || deviceIndex >= _ints[_gpuCount ~/ 4]) { + return -3; + } + final entry = _state + _gpus + deviceIndex * _gpuBytes; + final status = entry.cast()[0]; if (status != 0) { return status; } out.ref - ..total_bytes = _longs[_gpuTotal ~/ 8] - ..free_bytes = _longs[_gpuFree ~/ 8] - ..type = _ints[_gpuType ~/ 4]; - for (final (index, unit) in 'Vulkan0'.codeUnits.indexed) { + ..total_bytes = entry.cast()[1] + ..free_bytes = entry.cast()[2] + ..type = entry.cast()[1]; + for (final (index, unit) in 'Vulkan$deviceIndex\x00'.codeUnits.indexed) { out.ref.name[index] = unit; } - for (final (index, unit) in 'Fake GPU'.codeUnits.indexed) { + for (final (index, unit) in 'Fake GPU $deviceIndex\x00'.codeUnits.indexed) { out.ref.description[index] = unit; } return 0; } + int _gpuDeviceCount() { + _record( + _state[_logEnabled] != 0 + ? 'sd_dart_gpu_device_count' + : 'sd_dart_gpu_device_count:before-log-enable', + ); + return _ints[_gpuCount ~/ 4]; + } + Pointer _newContext(Pointer params) { _record( _state[_enabled] != 0 @@ -471,7 +505,12 @@ final class _FakeCalls { }, lastError: _readLastError, ), - gpuDeviceMemory: _state[_olderRelease] != 0 ? null : _gpuDeviceMemory, + gpu: _state[_olderRelease] != 0 + ? null + : StableDiffusionGpuCalls( + deviceCount: _gpuDeviceCount, + deviceMemory: _gpuDeviceMemory, + ), ); } diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart index 1daaf2476..a939689ce 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_calls_test.dart @@ -31,7 +31,10 @@ const _logSymbols = [ 'sd_dart_log_dropped', 'sd_dart_last_error', ]; -const _deviceMemorySymbols = ['sd_dart_gpu_device_memory']; +const _deviceMemorySymbols = [ + 'sd_dart_gpu_device_count', + 'sd_dart_gpu_device_memory', +]; // 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 @@ -76,11 +79,11 @@ void main() { expect(calls, isNotNull); expect(calls!.log, isNull); - expect(calls.gpuDeviceMemory, isNull); + expect(calls.gpu, isNull); }); - test('the log is bound only when the runtime exports all of its ' - 'functions, and the device memory query on its own', () { + test('the log and the GPU queries are each bound only when the runtime ' + 'exports all of their functions, one without the other', () { expect(StableDiffusionCalls.logSymbols, unorderedEquals(_logSymbols)); expect( StableDiffusionCalls.deviceMemorySymbols, @@ -98,11 +101,13 @@ void main() { for (final missing in _logSymbols) { final calls = without(missing); expect(calls.log, isNull, reason: missing); - expect(calls.gpuDeviceMemory, isNotNull, reason: missing); + expect(calls.gpu, isNotNull, reason: missing); + } + for (final missing in _deviceMemorySymbols) { + final calls = without(missing); + expect(calls.gpu, isNull, reason: missing); + expect(calls.log, isNotNull, reason: missing); } - final calls = without(_deviceMemorySymbols.single); - expect(calls.gpuDeviceMemory, isNull); - expect(calls.log, isNotNull); }); test('calls the function exported under the name of each of its ' @@ -124,8 +129,9 @@ void main() { expect(calls.log!.read(41, nullptr, 0, nullptr, nullptr), 42), 'sd_dart_log_dropped': () => expect(calls.log!.dropped(), 7), 'sd_dart_last_error': () => expect(calls.log!.lastError(nullptr, 9), 9), + 'sd_dart_gpu_device_count': () => expect(calls.gpu!.deviceCount(), 2), 'sd_dart_gpu_device_memory': () => - expect(calls.gpuDeviceMemory!(-1, nullptr), -3), + expect(calls.gpu!.deviceMemory(1, nullptr), -3), }; for (final MapEntry(key: name, value: call) in members.entries) { exports.called.clear(); @@ -134,7 +140,7 @@ void main() { } expect(exports.cancelMode, sd.sd_cancel_mode_t.SD_CANCEL_ALL.value); expect(exports.logLevel, 3); - expect(exports.deviceIndex, -1); + expect(exports.deviceIndex, 1); expect(calls.exitFreeAddress, exports.symbol('sd_dart_exit_free')); // sd_dart_progress_read is a leaf call, which cannot call back into @@ -291,6 +297,10 @@ final class _RecordingExports { _record('sd_dart_last_error', capacity), exceptionalReturn: 0, ), + 'sd_dart_gpu_device_count': NativeCallable.isolateLocal( + () => _record('sd_dart_gpu_device_count', 2), + exceptionalReturn: 0, + ), 'sd_dart_gpu_device_memory': NativeCallable< Int32 Function(Int32, Pointer) 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 b5b0f949d..75eceacad 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 @@ -795,6 +795,30 @@ void main() { expect(logged, hasLength(1)); }); + test('messages dropped with nothing new to read are reported once, ' + 'not again by the next read', () async { + final worker = await loaded(logLevel: LlamaLogLevel.error); + final logged = records(); + runtime.dropUnrecorded(3); + + await worker.generate(_request(), (_, _) {}); + await worker.generate(_request(), (_, _) {}); + await runtime.flush(); + + // Nothing is recorded at the error level, so the position stays. + expect(runtime.calls('worker'), [ + ..._generateCalls, + ..._logReads(0), + ..._generateCalls, + ..._logReads(0), + ]); + expect(logged, hasLength(1)); + expect( + logged.single.$2, + startsWith('The stable_diffusion runtime dropped 3 log messages'), + ); + }); + test('text that is not valid UTF-8 is delivered, not thrown', () async { final worker = await loaded(logLevel: LlamaLogLevel.info); final logged = records(); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart index 2e7a231cf..7141f4b35 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart @@ -294,7 +294,7 @@ void main() { tearDown(() => runtime.close()); - StableDiffusionGpuMemory? read({ + List? read({ LlamaLogLevel logLevel = LlamaLogLevel.none, String? vulkanDevice, }) => readStableDiffusionGpuMemory( @@ -303,42 +303,91 @@ void main() { environment: (name) => name == 'SD_VK_DEVICE' ? vulkanDevice : null, ); - test('asks the default device, after the recorder is registered at the ' - 'log level', () async { - runtime.setGpuMemory(total: 24 * _gib, free: 21 * _gib); + test('counts the GPUs and asks each one by its index, after the recorder ' + 'is registered at the log level', () async { + runtime.gpus = [ + (total: 4 * _gib, free: 3 * _gib, integrated: false, status: 0), + (total: 24 * _gib, free: 21 * _gib, integrated: false, status: 0), + (total: 16 * _gib, free: 12 * _gib, integrated: true, status: 0), + ]; final memory = read(logLevel: LlamaLogLevel.warn); await runtime.flush(); - expect(memory, ( - name: 'Vulkan0 (Fake GPU)', - totalBytes: 24 * _gib, - freeBytes: 21 * _gib, - integrated: false, - )); + expect(memory, [ + ( + name: 'Vulkan0 (Fake GPU 0)', + totalBytes: 4 * _gib, + freeBytes: 3 * _gib, + integrated: false, + ), + ( + name: 'Vulkan1 (Fake GPU 1)', + totalBytes: 24 * _gib, + freeBytes: 21 * _gib, + integrated: false, + ), + ( + name: 'Vulkan2 (Fake GPU 2)', + totalBytes: 16 * _gib, + freeBytes: 12 * _gib, + integrated: true, + ), + ]); expect(runtime.calls('caller'), [ 'sd_dart_log_enable', 'sd_dart_log_set_level:3', - 'sd_dart_gpu_device_memory:-1', + 'sd_dart_gpu_device_count', + 'sd_dart_gpu_device_memory:0', + 'sd_dart_gpu_device_memory:1', + 'sd_dart_gpu_device_memory:2', ]); }); - test('reports an integrated GPU as one', () { - runtime.setGpuMemory(total: 16 * _gib, free: 12 * _gib, integrated: true); - - expect(read()?.integrated, isTrue); - }); + test( + 'is null without a GPU backend or a GPU, and asks no device', + () async { + for (final status in [-2, 0]) { + runtime.gpuCountStatus = status; - test('is null for every status but OK: no backend, no device, memory ' - 'unavailable, an invalid argument', () { - for (final status in [-1, -2, -3, -4]) { - runtime.setGpuMemory(status: status, total: 8 * _gib, free: _gib); + expect(read(), isNull, reason: '$status'); + } + await runtime.flush(); + expect( + runtime.calls('caller').where((call) => call.contains('memory')), + isEmpty, + ); + }, + ); - expect(read(), isNull, reason: '$status'); + test('is null when one of the GPUs does not answer with its memory: ' + 'memory unavailable, no device, an invalid argument', () { + const known = ( + total: 8 * _gib, + free: 6 * _gib, + integrated: false, + status: 0, + ); + for (final status in [-1, -3, -4]) { + final failing = ( + total: 8 * _gib, + free: _gib, + integrated: false, + status: status, + ); + for (final devices in [ + [failing], + [known, failing], + [failing, known], + ]) { + runtime.gpus = devices; + + expect(read(), isNull, reason: '$status of ${devices.length}'); + } } }); - test('a runtime older than the query is not asked', () async { + test('a runtime older than the queries is not asked', () async { runtime ..olderRelease = true ..setGpuMemory(total: 8 * _gib, free: _gib); @@ -352,14 +401,14 @@ void main() { expect(readStableDiffusionGpuMemory(resolveCalls: () => null), isNull); }); - test('SD_VK_DEVICE, which makes the runtime pick the device, skips the ' - 'query', () async { + test('SD_VK_DEVICE, which can make the runtime pick the device, skips ' + 'the queries', () async { runtime.setGpuMemory(total: 8 * _gib, free: _gib); expect(read(vulkanDevice: '1'), isNull); await runtime.flush(); expect(runtime.calls('caller'), isEmpty); - expect(read(), isNotNull); + expect(read(), hasLength(1)); }); }); @@ -368,16 +417,22 @@ void main() { const noLimits = (refuse: null, slower: null); ImageGenerationMemoryLimits limits( - StableDiffusionGpuMemory? memory, { + List? gpus, { ImageGenerationMemoryBudget? hostBudget = host, - }) => stableDiffusionGpuMemoryLimits(memory, hostBudget: () => hostBudget); + bool runtimePicksGpu = true, + }) => stableDiffusionGpuMemoryLimits( + gpus, + runtimePicksGpu: runtimePicksGpu, + hostBudget: () => hostBudget, + ); StableDiffusionGpuMemory gpu({ required int total, required int free, bool integrated = false, + String name = 'Vulkan0 (NVIDIA L4)', }) => ( - name: 'Vulkan0 (NVIDIA L4)', + name: name, totalBytes: total, freeBytes: free, integrated: integrated, @@ -385,21 +440,28 @@ void main() { test('a discrete GPU whose driver reports a budget is slower above its ' 'free memory, and refuses above that plus host memory', () { - expect(limits(gpu(total: 24 * _gib, free: 9 * _gib)), ( - refuse: ( - bytes: 14 * _gib, - source: - '9.00 GiB of GPU memory and 5.00 GiB of system memory: free ' - 'GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB; ' - 'MemAvailable in /proc/meminfo', - ), - slower: ( - bytes: 9 * _gib, - source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', - ), - )); + for (final runtimePicksGpu in [true, false]) { + expect( + limits([ + gpu(total: 24 * _gib, free: 9 * _gib), + ], runtimePicksGpu: runtimePicksGpu), + ( + refuse: ( + bytes: 14 * _gib, + source: + '9.00 GiB of GPU memory and 5.00 GiB of system memory: free ' + 'GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB; ' + 'MemAvailable in /proc/meminfo', + ), + slower: ( + bytes: 9 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + ), + ), + ); + } for (final free in [8 * _gib - 1, 1]) { - final result = limits(gpu(total: 8 * _gib, free: free)); + final result = limits([gpu(total: 8 * _gib, free: free)]); expect(result.slower?.bytes, free); expect(result.refuse?.bytes, free + 5 * _gib); } @@ -408,7 +470,7 @@ void main() { test('a discrete GPU that reports its total as free, or nothing as free, ' 'uses its total memory and says that free memory is unknown', () { for (final free in [8 * _gib, 0]) { - expect(limits(gpu(total: 8 * _gib, free: free)), ( + expect(limits([gpu(total: 8 * _gib, free: free)]), ( refuse: ( bytes: 13 * _gib, source: @@ -429,14 +491,17 @@ void main() { test('a discrete GPU where host memory is not read, as on Windows, is ' 'slower above its figure and refuses nothing', () { - expect(limits(gpu(total: 24 * _gib, free: 9 * _gib), hostBudget: null), ( - refuse: null, - slower: ( - bytes: 9 * _gib, - source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + expect( + limits([gpu(total: 24 * _gib, free: 9 * _gib)], hostBudget: null), + ( + refuse: null, + slower: ( + bytes: 9 * _gib, + source: 'free GPU memory of Vulkan0 (NVIDIA L4), out of 24.0 GiB', + ), ), - )); - expect(limits(gpu(total: 8 * _gib, free: 8 * _gib), hostBudget: null), ( + ); + expect(limits([gpu(total: 8 * _gib, free: 8 * _gib)], hostBudget: null), ( refuse: null, slower: ( bytes: 8 * _gib, @@ -447,27 +512,141 @@ void main() { )); }); + group('with several discrete GPUs', () { + // A 4 GiB GPU listed before a 24 GiB one. + final small = gpu( + total: 4 * _gib, + free: 4 * _gib, + name: 'Vulkan0 (GTX 1650)', + ); + final large = gpu( + total: 24 * _gib, + free: 22 * _gib, + name: 'Vulkan1 (RTX 4090)', + ); + const smallSource = + 'the GPU memory of Vulkan0 (GTX 1650), whose driver does not ' + 'report how much of it is free'; + const largeSource = + 'free GPU memory of Vulkan1 (RTX 4090), out of 24.0 GiB'; + const sum = + '26.0 GiB of GPU memory on 2 GPUs and 5.00 GiB of system memory: ' + '4.00 GiB, $smallSource; 22.0 GiB, $largeSource; MemAvailable in ' + '/proc/meminfo'; + + test('with no backend named, a model is slower above the GPU with the ' + 'most memory, wherever it is listed, and refused above all of ' + 'them plus host memory', () { + for (final gpus in [ + [small, large], + [large, small], + ]) { + final result = limits(gpus); + + expect(result.slower, (bytes: 22 * _gib, source: largeSource)); + expect(result.refuse?.bytes, 31 * _gib); + } + expect(limits([small, large]).refuse?.source, sum); + }); + + test('a 16.8 GiB model on a 4 GiB GPU listed before a 24 GiB one, ' + 'with 9 GiB of host memory, neither is refused nor slower', () { + const estimate = 168 * _gib ~/ 10; + final result = limits( + [ + gpu(total: 4 * _gib, free: 4 * _gib, name: 'Vulkan0'), + gpu(total: 24 * _gib, free: 24 * _gib, name: 'Vulkan1'), + ], + hostBudget: (bytes: 9 * _gib, source: 'MemAvailable'), + ); + + expect(result.refuse!.bytes, 37 * _gib); + expect(result.refuse!.bytes, greaterThan(estimate)); + expect(result.slower!.bytes, 24 * _gib); + expect(result.slower!.source, contains('Vulkan1')); + // The first GPU and the host alone would not hold it. + expect(4 * _gib + 9 * _gib, lessThan(estimate)); + }); + + test('the backend gpu is the first discrete GPU: a model is slower ' + 'above that one, and still refused above all of them plus host ' + 'memory', () { + final result = limits([small, large], runtimePicksGpu: false); + + expect(result.slower, (bytes: 4 * _gib, source: smallSource)); + expect(result.refuse, (bytes: 31 * _gib, source: sum)); + expect( + limits([large, small], runtimePicksGpu: false).slower?.bytes, + 22 * _gib, + ); + }); + + test('of two GPUs with the same figure the first one computes', () { + final first = gpu(total: 8 * _gib, free: 6 * _gib, name: 'Vulkan0'); + final second = gpu(total: 12 * _gib, free: 6 * _gib, name: 'Vulkan1'); + + expect( + limits([first, second]).slower?.source, + 'free GPU memory of Vulkan0, out of 8.00 GiB', + ); + }); + + test('where host memory is not read nothing is refused', () { + final result = limits([small, large], hostBudget: null); + + expect(result.refuse, isNull); + expect(result.slower?.bytes, 22 * _gib); + }); + + test('an integrated GPU beside discrete ones adds nothing: its memory ' + 'is host memory', () { + final integrated = gpu( + total: 64 * _gib, + free: 60 * _gib, + integrated: true, + name: 'Vulkan2 (Intel UHD)', + ); + for (final gpus in [ + [integrated, small, large], + [small, large, integrated], + ]) { + for (final runtimePicksGpu in [true, false]) { + final result = limits(gpus, runtimePicksGpu: runtimePicksGpu); + + expect(result.refuse, (bytes: 31 * _gib, source: sum)); + expect(result.slower?.bytes, (runtimePicksGpu ? 22 : 4) * _gib); + } + } + }); + }); + test('an integrated GPU refuses above the host figure, never its own, ' 'and has nothing slower', () { for (final (total, free) in [(64 * _gib, 60 * _gib), (2 * _gib, _gib)]) { - expect(limits(gpu(total: total, free: free, integrated: true)), ( - refuse: ( - bytes: 5 * _gib, - source: - 'MemAvailable in /proc/meminfo; Vulkan0 (NVIDIA L4) is an ' - 'integrated GPU, which uses host memory', - ), - slower: null, - )); + for (final runtimePicksGpu in [true, false]) { + expect( + limits([ + gpu(total: total, free: free, integrated: true), + ], runtimePicksGpu: runtimePicksGpu), + ( + refuse: ( + bytes: 5 * _gib, + source: + 'MemAvailable in /proc/meminfo; Vulkan0 (NVIDIA L4) is an ' + 'integrated GPU, which uses host memory', + ), + slower: null, + ), + ); + } } }); test('an integrated GPU has no limit where host memory is not read', () { expect( - limits( + limits([ gpu(total: 16 * _gib, free: 8 * _gib, integrated: true), - hostBudget: null, - ), + ], hostBudget: null), noLimits, ); }); @@ -475,12 +654,21 @@ void main() { test('unknown memory has no limit, and the host is not asked', () { ImageGenerationMemoryBudget? unasked() => fail('asked the host'); - expect(limits(null), noLimits); - expect(limits(gpu(total: 0, free: 0)), noLimits); - expect( - stableDiffusionGpuMemoryLimits(null, hostBudget: unasked), - noLimits, - ); + for (final gpus in [ + null, + [], + [gpu(total: 0, free: 0)], + [gpu(total: 8 * _gib, free: _gib), gpu(total: 0, free: 0)], + ]) { + expect( + stableDiffusionGpuMemoryLimits( + gpus, + runtimePicksGpu: true, + hostBudget: unasked, + ), + noLimits, + ); + } }); }); diff --git a/test/unit/core/image/image_generation_driver_io_test.dart b/test/unit/core/image/image_generation_driver_io_test.dart index d0d6f4cff..4f8968feb 100644 --- a/test/unit/core/image/image_generation_driver_io_test.dart +++ b/test/unit/core/image/image_generation_driver_io_test.dart @@ -23,16 +23,30 @@ StableDiffusionRuntimeStatus _probeNamingItsIsolate({ LlamaUnsupportedException('$_isolate isolate, log level ${logLevel.name}'), ); -StableDiffusionGpuMemory? _gpuMemoryNamingItsIsolate({ +List? _gpuMemoryNamingItsIsolate({ LlamaLogLevel logLevel = LlamaLogLevel.none, -}) => ( - name: '$_isolate isolate, log level ${logLevel.name}', - totalBytes: 8 << 30, - freeBytes: 6 << 30, - integrated: false, -); - -StableDiffusionGpuMemory? _noGpuMemory({ +}) => [ + ( + name: '$_isolate isolate, log level ${logLevel.name}', + totalBytes: 8 << 30, + freeBytes: 6 << 30, + integrated: false, + ), +]; + +List? _twoGpus({ + LlamaLogLevel logLevel = LlamaLogLevel.none, +}) => [ + (name: 'Vulkan0', totalBytes: 4 << 30, freeBytes: 3 << 30, integrated: false), + ( + name: 'Vulkan1', + totalBytes: 24 << 30, + freeBytes: 20 << 30, + integrated: false, + ), +]; + +List? _noGpuMemory({ LlamaLogLevel logLevel = LlamaLogLevel.none, }) => null; @@ -120,6 +134,7 @@ void main() { expect( (await driver.memoryLimits( ImageGenerationComputeDevice.otherGpu, + runtimePicksGpu: true, )).slower?.source, contains('log level ${expected.name}'), reason: reason, @@ -136,7 +151,7 @@ void main() { ImageGenerationComputeDevice.cpu, ImageGenerationComputeDevice.metal, ]) { - final limits = await driver.memoryLimits(device); + final limits = await driver.memoryLimits(device, runtimePicksGpu: true); if (Platform.isMacOS || Platform.isLinux) { expect(limits.refuse, isNotNull); expect(limits.refuse!.bytes, greaterThan(0)); @@ -145,10 +160,13 @@ void main() { } expect(limits.slower, isNull); } - expect(await driver.memoryLimits(ImageGenerationComputeDevice.otherGpu), ( - refuse: null, - slower: null, - )); + expect( + await driver.memoryLimits( + ImageGenerationComputeDevice.otherGpu, + runtimePicksGpu: true, + ), + (refuse: null, slower: null), + ); }); test('asks another GPU for its memory in another isolate: slower above ' @@ -160,9 +178,11 @@ void main() { final limits = await driver.memoryLimits( ImageGenerationComputeDevice.otherGpu, + runtimePicksGpu: true, ); final host = (await driver.memoryLimits( ImageGenerationComputeDevice.cpu, + runtimePicksGpu: true, )).refuse; expect(limits.slower?.bytes, 6 << 30); @@ -182,14 +202,32 @@ void main() { } }); + test('with two GPUs the driver passes on whether the runtime picks the ' + 'one it computes on', () async { + final driver = createImageGenerationDriver(readGpuMemory: _twoGpus); + + Future slower({ + required bool runtimePicksGpu, + }) async => (await driver.memoryLimits( + ImageGenerationComputeDevice.otherGpu, + runtimePicksGpu: runtimePicksGpu, + )).slower; + + expect((await slower(runtimePicksGpu: true))?.bytes, 20 << 30); + expect((await slower(runtimePicksGpu: false))?.bytes, 3 << 30); + }); + test('a GPU whose memory is not known has no limit, and the CPU and ' 'Metal limits do not ask it', () async { final driver = createImageGenerationDriver(readGpuMemory: _noGpuMemory); - expect(await driver.memoryLimits(ImageGenerationComputeDevice.otherGpu), ( - refuse: null, - slower: null, - )); + expect( + await driver.memoryLimits( + ImageGenerationComputeDevice.otherGpu, + runtimePicksGpu: true, + ), + (refuse: null, slower: null), + ); final unasked = createImageGenerationDriver( readGpuMemory: _gpuMemoryNamingItsIsolate, @@ -199,7 +237,10 @@ void main() { ImageGenerationComputeDevice.metal, ]) { expect( - (await unasked.memoryLimits(device)).refuse?.source, + (await unasked.memoryLimits( + device, + runtimePicksGpu: true, + )).refuse?.source, isNot(contains('isolate')), ); } diff --git a/test/unit/core/image/image_generation_driver_stub_test.dart b/test/unit/core/image/image_generation_driver_stub_test.dart index 12bab05ed..8a79db633 100644 --- a/test/unit/core/image/image_generation_driver_stub_test.dart +++ b/test/unit/core/image/image_generation_driver_stub_test.dart @@ -19,7 +19,10 @@ void main() { throwsA(isA()), ); for (final device in ImageGenerationComputeDevice.values) { - expect(await driver.memoryLimits(device), (refuse: null, slower: null)); + expect(await driver.memoryLimits(device, runtimePicksGpu: true), ( + refuse: null, + slower: null, + )); } await expectLater( driver.start( diff --git a/test/unit/core/image/image_generation_engine_test.dart b/test/unit/core/image/image_generation_engine_test.dart index f57fe5e8d..d4eed88e3 100644 --- a/test/unit/core/image/image_generation_engine_test.dart +++ b/test/unit/core/image/image_generation_engine_test.dart @@ -1146,6 +1146,42 @@ void main() { expect(records.single.message, contains('more than the 6.00 GiB')); }); + test('says that the runtime picks the GPU for ComputeDevice.auto, ' + 'and that it does not for ComputeDevice.gpu', () async { + driver.status = _available( + 'Vulkan0\tGTX 1650\nVulkan1\tRTX 4090\nCPU\tHost\n', + ); + + await load(_sdxs()); + await load( + _sdxs(), + params: const ImageModelParams(device: ComputeDevice.gpu), + ); + + expect(driver.runtimePicks, [true, false]); + expect( + driver.budgetDevices, + everyElement(ImageGenerationComputeDevice.otherGpu), + ); + }); + + test('with a small GPU listed before a large one, a model that fits ' + 'the large one loads: 16.8 GiB against 4, 24 and 9 GiB', () async { + driver + ..status = _available( + 'Vulkan0\tGTX 1650\nVulkan1\tRTX 4090\nCPU\tHost\n', + ) + // 13.04 GiB of weights are estimated at 16.8 GiB. + ..sizes[_model] = 1304 * _gib ~/ 100 + ..slowerBudget = (bytes: 24 * _gib, source: 'Vulkan1') + ..budget = (bytes: 37 * _gib, source: 'two GPUs and the host'); + + await load(_sdxs()); + + expect(driver.started, hasLength(1)); + expect(records, isEmpty); + }); + test('a model that fits the GPU loads without a warning', () async { driver ..sizes[_model] = 2 * _gib @@ -1804,12 +1840,15 @@ final class _FakeDriver implements ImageGenerationDriver { } final List budgetDevices = []; + final List runtimePicks = []; @override Future memoryLimits( - ImageGenerationComputeDevice device, - ) async { + ImageGenerationComputeDevice device, { + required bool runtimePicksGpu, + }) async { budgetDevices.add(device); + runtimePicks.add(runtimePicksGpu); return (refuse: budget, slower: slowerBudget); } diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index b68e3e3f0..29763f8ac 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -682,9 +682,9 @@ device the model loads on: | iOS: Metal or CPU | The app's remaining memory limit (`os_proc_available_memory`) | | macOS: CPU | Physical memory | | macOS: Metal | Physical memory, capped at the GPU's `recommendedMaxWorkingSetSize` (about two thirds to three quarters of it) | -| Linux: Vulkan, discrete GPU | The GPU's memory plus `MemAvailable`; a model larger than the GPU's memory alone loads with a warning | +| Linux: Vulkan, discrete GPUs | The memory of every discrete GPU plus `MemAvailable`; a model larger than the memory of the GPU that computes loads with a warning | | Linux: Vulkan, integrated GPU | `MemAvailable`, as for the CPU | -| Windows: Vulkan, discrete GPU | Never refused; a model larger than the GPU's memory loads with a warning | +| Windows: Vulkan, discrete GPUs | Never refused; a model larger than the memory of the GPU that computes loads with a warning | | Windows: Vulkan, integrated GPU | Not checked | | Windows: CPU | Not checked | @@ -698,36 +698,45 @@ warning. A discrete Vulkan GPU does not bound a model by itself. stable-diffusion.cpp plans where each part of a model goes when it loads (its automatic fit, which the engine leaves on): the diffusion model, the text encoders and the VAE -each go to the GPU when they fit its free memory with room to compute, -otherwise to system memory, otherwise to another GPU, otherwise they stay on -disk. A model larger than the GPU therefore loads and generates more slowly. +each go to the GPU that computes when they fit its free memory with room to +compute, otherwise to system memory, otherwise to another GPU, otherwise they +stay on disk. A model larger than the GPU therefore loads and generates more +slowly. So the engine works with two figures: -- **The GPU's memory.** Its free memory when the driver reports a budget - (`VK_EXT_memory_budget`): what this process can still allocate, which - accounts for other processes and for image models already loaded. Without - a budget the runtime reports the total as free, so the engine uses the - total, and does the same for a free figure of 0. A model whose estimate - exceeds this figure loads, and the engine logs one warning through - [`LlamaLogging`](#runtime-logs) with both numbers and the device, saying - that part of the model stays in system memory and generation will be - slower. It is a `warn` record, so the default level `none` hides it. -- **The GPU's memory plus system memory** (`MemAvailable`, as for the CPU). - On Linux a model whose estimate exceeds this sum is refused. Windows does - not read system memory, so nothing is refused there and only the warning - applies. +- **The memory of the GPU that computes.** A GPU's figure is its free memory + when the driver reports a budget (`VK_EXT_memory_budget`): what this + process can still allocate, which accounts for other processes and for + image models already loaded. Without a budget the runtime reports the + total as free, so the engine uses the total, and does the same for a free + figure of 0. A model whose estimate exceeds this figure loads, and the + engine logs one warning through [`LlamaLogging`](#runtime-logs) with both + numbers and the device, saying that part of the model stays in system + memory and generation will be slower. It is a `warn` record, so the + default level `none` hides it. +- **The memory of every discrete GPU plus system memory** (`MemAvailable`, + as for the CPU). On Linux a model whose estimate exceeds this sum is + refused. Windows does not read system memory, so nothing is refused there + and only the warning applies. + +With several discrete GPUs, the one that computes is the runtime's choice: +for `ComputeDevice.auto` the discrete GPU with the most free memory, wherever +it is listed, and for `ComputeDevice.gpu` the first one. The engine follows +that for the warning. `capabilities.backendName` still names the first GPU +listed. An integrated GPU uses host memory, and a driver that exposes it as several -heaps makes the GPU's own figures count it more than once. The engine ignores -them and compares with `MemAvailable` on Linux, as for the CPU. +heaps makes the GPU's own figures count it more than once. The engine never +uses them: beside a discrete GPU an integrated one adds nothing to the sum, +and with integrated GPUs only it compares with `MemAvailable` on Linux, as +for the CPU. -Nothing is checked or warned about when the GPU does not report its memory, -when the `SD_VK_DEVICE` environment variable picks the Vulkan device, or with -a `stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2`. +Nothing is checked or warned about when a GPU does not report its memory, +when the `SD_VK_DEVICE` environment variable is set, or with a +`stable_diffusion` runtime older than `stable-diffusion-native` `v0.2.0-2`. -The figures are the runtime's, which are ggml's, for the GPU a model loads on -by default: the first discrete GPU, or else the first integrated one. The +The figures are the runtime's, which are ggml's, for every GPU it lists. The engine asks for them in a short-lived isolate, because the first such call in a process can initialize the GPU. @@ -790,6 +799,8 @@ final engine = await ImageGenerationEngine.load(model); records from the stricter of the two, and nothing when either is `none`, the default. A load takes the levels it finds: configure logging before `load`. +- At `debug` the runtime logs each prompt verbatim, with its tokens. Keep + that level out of logs that leave the device. - Messages arrive after each load and generation and at `dispose()`, not while one runs: a worker isolate reads them from the runtime between its calls. Each starts with `stable_diffusion: `, and model file paths are From 43e4908bdb0b1892b3013c12edeb498906b60fd2 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Thu, 8 Oct 2026 21:30:55 -0400 Subject: [PATCH 4/4] test: drop an assertion on constants from the two-GPU memory check case --- .../backends/stable_diffusion/stable_diffusion_memory_test.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart index 7141f4b35..89068e26f 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart @@ -564,8 +564,6 @@ void main() { expect(result.refuse!.bytes, greaterThan(estimate)); expect(result.slower!.bytes, 24 * _gib); expect(result.slower!.source, contains('Vulkan1')); - // The first GPU and the host alone would not hold it. - expect(4 * _gib + 9 * _gib, lessThan(estimate)); }); test('the backend gpu is the first discrete GPU: a model is slower '