diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d4e6eeff..c7f985498 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,8 @@ - Ship agent skills for coding agents covering setup, chat and streaming, tool calling, web, Flutter apps, multimodal input, embeddings, speech, LoRA - adapters and decision models; install them with `dart run skills@ get`. + adapters, decision models and image generation; install them with + `dart run skills@ get`. - Add an observability guide and tested optional OpenTelemetry example with Langfuse and Grafana recipes. - Apply `ModelParams.loras` at model load on native llama.cpp and WebGPU, where they were silently ignored; an adapter that cannot be applied, or @@ -16,6 +17,11 @@ generation; it is never bundled by default or by `all`, and `llamadart_stable_diffusion_backends` picks its CPU or Vulkan build on Linux and Windows ([#777](https://github.com/leehack/llamadart/issues/777)). +- Add experimental on-device image generation, `ImageGenerationEngine`, on + the opt-in `stable_diffusion` runtime: SDXS and SD-Turbo presets, + phase-labelled progress, cancellation, PNG output and a memory check before + loading; not available on the web + ([#778](https://github.com/leehack/llamadart/issues/778)). - Throw `LlamaUnsupportedException` for image or audio parts sent to a GGUF model with no projector loaded: native llama.cpp answered from the text alone, and WebGPU threw an untyped error surfaced as diff --git a/README.md b/README.md index af80f49d2..f29877579 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,13 @@ for each target. transcripts. - Experimental typed Qwen3-TTS synthesis on native llama.cpp through `TextToSpeechEngine`, returning complete PCM with WAV encoding. +- Experimental text-to-image generation through `ImageGenerationEngine` and + the opt-in `stable_diffusion` (stable-diffusion.cpp) runtime: SDXS and + SD-Turbo on Android arm64 (CPU), iOS and macOS (Metal), and Linux and + Windows (CPU or Vulkan), with progress, cancellation and PNG output; + validated with real models on macOS, iOS, Android, Linux x64 and Windows x64 + ([#779](https://github.com/leehack/llamadart/issues/779)). Not available on + the web. - Experimental Laya-style decision models on native llama.cpp through `DecisionEngine`: typed choice, score, and yes/no answers from a ModernBERT encoder GGUF and a safetensors head, one encoder pass per question; validated @@ -217,6 +224,7 @@ bindings, runtime behavior, and docs have been validated together. | Use images, audio, or projectors | [Multimodal](https://llamadart.leehack.com/docs/guides/multimodal) | | Transcribe speech on device | [Speech to text](https://llamadart.leehack.com/docs/guides/speech-to-text) | | Synthesize speech on device | [Text to speech](https://llamadart.leehack.com/docs/guides/text-to-speech) | +| Generate images on device | [Image generation](https://llamadart.leehack.com/docs/guides/image-generation) | | Answer typed questions with a decision model | [Decision models](https://llamadart.leehack.com/docs/guides/decision-models) | | Generate embeddings | [Embeddings](https://llamadart.leehack.com/docs/guides/embeddings) | | Score next-token log-probabilities | [Next-token scores](https://llamadart.leehack.com/docs/guides/generation-and-streaming#next-token-scores) | diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 502a6d09b..9e7945e8e 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -151,6 +151,7 @@ Pick targeted rows based on the touched surface: | Speech-to-text API or adapter | `speech-to-text-smoke`, `web-speech-to-text-smoke`, plus `litert-lm-asr-smoke` for the dedicated LiteRT-LM streaming engine | | Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | | Decision engine, decision head, or safetensors reader | `decision-model-smoke` | +| Image generation API or `stable_diffusion` runtime | `image-generation-smoke`, `native-hook-bundles` | | Chat-app microphone transcription flow | `chat-app-microphone-transcription-smoke` | | Chat-app live LiteRT-LM dictation | `litert-lm-asr-smoke`, `chat-app-live-speech-smoke` | | Chat-app Ask with voice | `gguf-audio-chat-smoke`, `litert-lm-chat-features-smoke`, `chat-app-voice-question-smoke` | @@ -285,6 +286,12 @@ dart run tool/testing/run_local_e2e.dart \ --scenario chat-app-web-text-to-speech-smoke \ [--audio-path /path/to/speaker-reference.wav] +# Runs in example/basic_app, which opts into the stable_diffusion runtime, and +# writes PNGs to build/image-generation-smoke. Export LLAMADART_SD_TURBO_MODEL +# (and optionally LLAMADART_TAESD) first to add the SD-Turbo case. +dart run tool/testing/run_local_e2e.dart --scenario image-generation-smoke \ + --model-path /path/to/sdxs-512-tinySDdistilled_Q8_0.gguf + # Runs the 24 Laya 0.3.5 fixture rows: exact token ids and markers, raw # marker logits within LLAMADART_DECISION_LOGIT_TOLERANCE (default 0.25), and # probabilities, confidence, act probability and noul within diff --git a/example/basic_app/README.md b/example/basic_app/README.md index 86ae1a64a..42dc3300f 100644 --- a/example/basic_app/README.md +++ b/example/basic_app/README.md @@ -16,6 +16,7 @@ A clean, organized CLI application demonstrating the capabilities of the `llamad - **Embedding Demo**: Includes a dedicated embedding CLI example. - **SQLite Vector Demo**: Stores embeddings in SQLite and runs nearest-neighbor search with `sqlite_vector`. - **Decision Model Demo**: Triages a support ticket with a Laya decision model through `DecisionEngine`. +- **Image Generation Demo (experimental)**: Writes a PNG with SDXS or SD-Turbo through `ImageGenerationEngine`, with progress and Ctrl-C cancellation. ## Usage @@ -219,6 +220,67 @@ Decision CLI flags (`bin/llamadart_decision_example.dart`): (`ModelParams.numberOfThreadsBatch`; `0` keeps the default). - `--json`: Also print the Laya response JSON. +### 8. Image Generation Example (experimental) + +Generate a PNG with `ImageGenerationEngine` and the opt-in `stable_diffusion` +runtime. This example's `pubspec.yaml` opts in: + +```yaml +hooks: + user_defines: + llamadart: + llamadart_native_runtimes: [llama_cpp, stable_diffusion] +``` + +The first run downloads the runtime (40 to 70 MB) through the build hook and, +unless `--model` names a local file, the pinned SDXS checkpoint (651 MB) from +`concedo/sdxs-512-tinySDdistilled-GGUF` into the package-managed cache. + +```bash +dart run bin/llamadart_image_example.dart \ + -p "a red fox in autumn leaves" --seed 42 -o fox.png +``` + +SD-Turbo (1.9 GB) with the TAESD decoder, four steps: + +```bash +dart run bin/llamadart_image_example.dart --preset sd-turbo --taesd default \ + --steps 4 -p "a lighthouse at dusk" -o lighthouse.png +``` + +Progress prints per phase (`encodingPrompt`, `sampling 1/4`, `decoding`). +Ctrl-C cancels the generation before its next sampling step and exits with +code 130. It runs on macOS, Linux and Windows x64 hosts (x64 CPUs need AVX2, +FMA, F16C and BMI2); elsewhere, or when the runtime is not bundled, it exits +with code 2 and the reason. + +Image CLI flags (`bin/llamadart_image_example.dart`): + +- `--preset`: `sdxs` (default) or `sd-turbo`. +- `-m, --model`: Checkpoint as a local path, HTTP(S) URL, or `hf://` source; + defaults to the pinned checkpoint for the preset. +- `--taesd`: TAESD decoder for `sd-turbo`, in the same forms, or `default` + for the pinned `madebyollin/taesd`. +- `-p, --prompt`: Prompt (required). `--negative`: negative prompt. +- `--width`, `--height`: Multiples of 8 from 64 to 2048 (default `512`). +- `--steps`, `--guidance`: Override the preset (SDXS and SD-Turbo default to + 1 step at guidance 1). +- `--seed`: Seed; random when omitted, and printed either way. +- `--count`: Images to generate; later files get `-1`, `-2` suffixes. +- `-o, --out`: PNG path (default `image.png`). +- `--device`: `auto`, `cpu` or `gpu`. `--threads`: CPU threads (`0`: all + physical cores). + +With model files on disk, the local-only test runs real generation, including +determinism, cancellation and the one-generation-at-a-time guard: + +```bash +LLAMADART_SDXS_MODEL=/models/sdxs-512-tinySDdistilled_Q8_0.gguf \ +LLAMADART_SD_TURBO_MODEL=/models/sd_turbo-f16-q8_0.gguf \ +LLAMADART_TAESD=/models/taesd.safetensors \ + dart test --run-skipped -t local-only test/image_generation_e2e_test.dart +``` + ## Options - `-m, --model`: Local path, HTTP(S) URL, or `hf://` Hugging Face source for a GGUF model. @@ -249,6 +311,8 @@ dart test - **`bin/llamadart_sqlite_vector_example.dart`**: SQLite vector retrieval CLI example. - **`bin/llamadart_decision_example.dart`**: Decision model CLI example. - **`lib/services/decision_cli_options.dart`**: Decision CLI flags and pinned model sources. +- **`bin/llamadart_image_example.dart`**: Image generation CLI example. +- **`lib/services/image_cli_options.dart`**: Image CLI flags and pinned model sources. - **`lib/services/decision_ticket_triage.dart`**: Typed ticket question keys and answer formatting. - **`lib/services/llama_service.dart`**: High-level wrapper for the `llamadart` engine. - **`lib/services/model_service.dart`**: Handles model downloading and path verification. diff --git a/example/basic_app/bin/llamadart_image_example.dart b/example/basic_app/bin/llamadart_image_example.dart new file mode 100644 index 000000000..301c54c10 --- /dev/null +++ b/example/basic_app/bin/llamadart_image_example.dart @@ -0,0 +1,131 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_basic_example/services/image_cli_options.dart'; + +Future main(List arguments) async { + final parser = createImageArgParser(); + final ImageCliOptions options; + try { + final results = parser.parse(arguments); + if (results['help'] as bool) { + stdout.write(buildImageHelpText(parser)); + return; + } + options = parseImageCliOptions(results); + } on FormatException catch (error) { + stderr + ..writeln(error.message) + ..writeln() + ..writeln(parser.usage); + exitCode = 64; + return; + } + + final runtime = ImageGenerationEngine.runtimeCapabilities(); + if (!runtime.isSupported) { + stderr.writeln( + 'Image generation is unavailable: ${runtime.unsupportedReason}', + ); + exitCode = 2; + return; + } + + final downloads = DefaultModelDownloadManager(); + ImageGenerationEngine? engine; + StreamSubscription? interrupt; + try { + final modelPath = await _resolve(downloads, options.modelSource, 'model'); + final taesdSource = options.taesdSource; + final taesdPath = taesdSource == null + ? null + : await _resolve(downloads, taesdSource, 'TAESD'); + + print('Loading ${options.preset.flag}...'); + final loadTimer = Stopwatch()..start(); + engine = await ImageGenerationEngine.load( + options.model(modelPath, taesdPath), + options: ImageGenerationOptions( + device: options.device, + threads: options.threads, + ), + ); + final capabilities = engine.capabilities; + print( + 'Loaded ${capabilities.modelVersion} on ${capabilities.backendName} ' + 'in ${loadTimer.elapsedMilliseconds} ms.', + ); + + final task = engine.generate(options.request); + interrupt = ProcessSignal.sigint.watch().listen((_) { + stdout.writeln('\nCancelling...'); + task.cancel(); + }); + + await for (final event in task.events) { + switch (event) { + case ImageGenerationProgressEvent( + :final phase, + :final step, + :final steps, + :final imageIndex, + :final imageCount, + ): + final image = imageCount > 1 ? ' image ${imageIndex + 1}' : ''; + stdout.write('\r${phase.name}$image $step/$steps\x1B[K'); + case ImageGenerationFinalEvent(:final result): + stdout.writeln(); + for (final (index, image) in result.images.indexed) { + final path = options.outputPathFor(index); + File(path).writeAsBytesSync(image.toPng()); + print( + 'Wrote $path (${image.width}x${image.height}, seed ' + '${result.seed + index}).', + ); + } + print('Generated in ${result.elapsed.inMilliseconds} ms.'); + } + } + if ((await task.done).state == ImageGenerationCompletionState.cancelled) { + print('Cancelled.'); + exitCode = 130; + } + } on LlamaUnsupportedException catch (error) { + stderr.writeln('\nCannot generate images here: ${error.message}'); + exitCode = 2; + } on LlamaException catch (error) { + stderr.writeln('\nError: ${error.message}'); + exitCode = 1; + } catch (error) { + stderr.writeln('\nError: $error'); + exitCode = 1; + } finally { + await interrupt?.cancel(); + await engine?.dispose(); + } +} + +Future _resolve( + DefaultModelDownloadManager downloads, + ModelSource source, + String label, +) async { + if (source.isLocal) { + return source.path!; + } + print('Fetching $label ${source.displayName}...'); + final entry = await downloads.ensureModel( + source, + onProgress: (progress) { + final fraction = progress.fraction; + stdout.write( + fraction == null + ? '\r${progress.receivedBytes ~/ 1048576} MB' + : '\r${(fraction * 100).toStringAsFixed(0)}%', + ); + }, + ); + stdout.writeln(); + return entry.filePath; +} diff --git a/example/basic_app/dart_test.yaml b/example/basic_app/dart_test.yaml new file mode 100644 index 000000000..18d1b6713 --- /dev/null +++ b/example/basic_app/dart_test.yaml @@ -0,0 +1,3 @@ +tags: + local-only: + skip: "Needs local model files. Use: dart test --run-skipped -t local-only" diff --git a/example/basic_app/lib/services/image_cli_options.dart b/example/basic_app/lib/services/image_cli_options.dart new file mode 100644 index 000000000..5e1a728cf --- /dev/null +++ b/example/basic_app/lib/services/image_cli_options.dart @@ -0,0 +1,227 @@ +import 'package:args/args.dart'; +import 'package:llamadart/llamadart.dart'; + +/// Default SDXS checkpoint: `concedo/sdxs-512-tinySDdistilled-GGUF`, pinned. +const String defaultSdxsModelSource = + 'hf://concedo/sdxs-512-tinySDdistilled-GGUF' + '@3144d898d61492f8382ffcabec055733fc5b2a0e/' + 'sdxs-512-tinySDdistilled_Q8_0.gguf'; + +/// Default SD-Turbo checkpoint: `Green-Sky/SD-Turbo-GGUF`, pinned. +const String defaultSdTurboModelSource = + 'hf://Green-Sky/SD-Turbo-GGUF@19a31586d02d64a73b4419bc193b3ecfaf38e1f0/' + 'sd_turbo-f16-q8_0.gguf'; + +/// TAESD decoder for SD-Turbo: `madebyollin/taesd`, pinned. +const String defaultTaesdSource = + 'hf://madebyollin/taesd@614f76814bbe30edbe2e627ace1c2234c81a2c0e/' + 'diffusion_pytorch_model.safetensors'; + +/// Model presets the image example accepts. +enum ImagePreset { + /// SDXS-512: one step, guidance 1. + sdxs('sdxs'), + + /// SD-Turbo: one step by default, optional TAESD. + sdTurbo('sd-turbo'); + + const ImagePreset(this.flag); + + /// Value of `--preset`. + final String flag; +} + +/// Parsed command-line options for the image example. +final class ImageCliOptions { + /// Creates parsed options. + const ImageCliOptions({ + required this.preset, + required this.modelSource, + required this.taesdSource, + required this.request, + required this.outputPath, + required this.device, + required this.threads, + }); + + /// Model preset. + final ImagePreset preset; + + /// Checkpoint source. + final ModelSource modelSource; + + /// TAESD source for SD-Turbo, or `null` to decode with the full VAE. + final ModelSource? taesdSource; + + /// Generation request. + final ImageGenerationRequest request; + + /// PNG output path. With `--count` above 1, later images get `-1`, `-2` + /// suffixes. + final String outputPath; + + /// Device to run on. + final ImageGenerationDevice device; + + /// CPU threads; 0 uses the physical cores. + final int threads; + + /// The engine model for [preset] with the resolved local files. + ImageGenerationModel model(String modelPath, String? taesdPath) => + switch (preset) { + ImagePreset.sdxs => ImageGenerationModel.sdxs(modelPath), + ImagePreset.sdTurbo => ImageGenerationModel.sdTurbo( + modelPath, + taesdPath: taesdPath, + ), + }; + + /// Output path of image [index]. + String outputPathFor(int index) { + if (index == 0) { + return outputPath; + } + final dot = outputPath.lastIndexOf('.'); + return dot <= 0 + ? '$outputPath-$index' + : '${outputPath.substring(0, dot)}-$index${outputPath.substring(dot)}'; + } +} + +/// Creates the argument parser for the image example. +ArgParser createImageArgParser() { + return ArgParser() + ..addOption( + 'preset', + help: 'Model preset.', + allowed: [for (final preset in ImagePreset.values) preset.flag], + defaultsTo: ImagePreset.sdxs.flag, + ) + ..addOption( + 'model', + abbr: 'm', + help: + 'Checkpoint: local path, HTTP(S) URL, or hf:// source. Defaults to ' + 'the pinned SDXS or SD-Turbo GGUF for --preset.', + ) + ..addOption( + 'taesd', + help: + 'TAESD decoder for sd-turbo (local path, URL, or hf:// source), or ' + '"default" for the pinned madebyollin/taesd.', + ) + ..addOption('prompt', abbr: 'p', help: 'Prompt (required).') + ..addOption('negative', help: 'Negative prompt.', defaultsTo: '') + ..addOption('width', help: 'Width in pixels.', defaultsTo: '512') + ..addOption('height', help: 'Height in pixels.', defaultsTo: '512') + ..addOption('steps', help: 'Sampling steps (default: the preset).') + ..addOption('guidance', help: 'Guidance scale (default: the preset).') + ..addOption('seed', help: 'Seed (default: random).') + ..addOption('count', help: 'Number of images.', defaultsTo: '1') + ..addOption('out', abbr: 'o', help: 'PNG path.', defaultsTo: 'image.png') + ..addOption( + 'device', + help: 'Device.', + allowed: [for (final device in ImageGenerationDevice.values) device.name], + defaultsTo: ImageGenerationDevice.auto.name, + ) + ..addOption('threads', help: 'CPU threads (0: all cores).', defaultsTo: '0') + ..addFlag('help', abbr: 'h', help: 'Show this help.', negatable: false); +} + +/// Parses [results] from [createImageArgParser]. +/// +/// Throws [FormatException] without `--prompt`, for a malformed number or +/// model source, or for `--taesd` with the sdxs preset. Range checks are left +/// to the engine. +ImageCliOptions parseImageCliOptions(ArgResults results) { + final preset = ImagePreset.values.firstWhere( + (preset) => preset.flag == results['preset'], + ); + final prompt = results['prompt'] as String?; + if (prompt == null) { + throw const FormatException('--prompt is required.'); + } + final taesdText = results['taesd'] as String?; + if (taesdText != null && preset != ImagePreset.sdTurbo) { + throw const FormatException('--taesd applies only to --preset sd-turbo.'); + } + final modelText = + results['model'] as String? ?? + switch (preset) { + ImagePreset.sdxs => defaultSdxsModelSource, + ImagePreset.sdTurbo => defaultSdTurboModelSource, + }; + return ImageCliOptions( + preset: preset, + modelSource: _source('model', modelText), + taesdSource: switch (taesdText) { + null => null, + 'default' => ModelSource.parse(defaultTaesdSource), + final text => _source('taesd', text), + }, + request: ImageGenerationRequest( + prompt: prompt, + negativePrompt: results['negative'] as String, + width: _int(results, 'width')!, + height: _int(results, 'height')!, + steps: _int(results, 'steps'), + guidanceScale: _double(results, 'guidance'), + seed: _int(results, 'seed'), + count: _int(results, 'count')!, + ), + outputPath: results['out'] as String, + device: ImageGenerationDevice.values.byName(results['device'] as String), + threads: _int(results, 'threads')!, + ); +} + +/// Builds the help text for the image example. +String buildImageHelpText(ArgParser parser) { + return (StringBuffer() + ..writeln('llamadart Image Generation Example (experimental)') + ..writeln() + ..writeln( + 'Generates a PNG with SDXS or SD-Turbo through the opt-in ' + 'stable_diffusion runtime. Ctrl-C cancels.', + ) + ..writeln() + ..writeln(parser.usage) + ..writeln() + ..writeln('Examples:') + ..writeln( + ' dart run bin/llamadart_image_example.dart ' + "-p 'a red fox in autumn leaves' --seed 42", + ) + ..writeln( + ' dart run bin/llamadart_image_example.dart --preset sd-turbo ' + "--taesd default --steps 4 -p 'a lighthouse at dusk'", + )) + .toString(); +} + +ModelSource _source(String option, String text) { + try { + return ModelSource.parse(text); + } on ArgumentError catch (error) { + throw FormatException('--$option: ${error.message}'); + } +} + +int? _int(ArgResults results, String option) { + final text = results[option] as String?; + if (text == null) { + return null; + } + return int.tryParse(text) ?? + (throw FormatException('--$option must be an integer: $text')); +} + +double? _double(ArgResults results, String option) { + final text = results[option] as String?; + if (text == null) { + return null; + } + return double.tryParse(text) ?? + (throw FormatException('--$option must be a number: $text')); +} diff --git a/example/basic_app/pubspec.yaml b/example/basic_app/pubspec.yaml index ec13e576a..c69f40b0d 100644 --- a/example/basic_app/pubspec.yaml +++ b/example/basic_app/pubspec.yaml @@ -16,3 +16,9 @@ dependencies: dev_dependencies: lints: ^6.1.0 test: ^1.26.3 + +hooks: + user_defines: + llamadart: + # The image example needs the opt-in stable_diffusion runtime. + llamadart_native_runtimes: [llama_cpp, stable_diffusion] diff --git a/example/basic_app/test/image_cli_options_test.dart b/example/basic_app/test/image_cli_options_test.dart new file mode 100644 index 000000000..b54f58868 --- /dev/null +++ b/example/basic_app/test/image_cli_options_test.dart @@ -0,0 +1,130 @@ +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_basic_example/services/image_cli_options.dart'; +import 'package:test/test.dart'; + +ImageCliOptions _parse(List arguments) => + parseImageCliOptions(createImageArgParser().parse(arguments)); + +void main() { + test('defaults to the pinned SDXS checkpoint and a random seed', () { + final options = _parse(const ['-p', 'a fox']); + + expect(options.preset, ImagePreset.sdxs); + expect( + options.modelSource.canonicalKey, + ModelSource.parse(defaultSdxsModelSource).canonicalKey, + ); + expect(options.taesdSource, isNull); + expect(options.request.prompt, 'a fox'); + expect(options.request.width, 512); + expect(options.request.height, 512); + expect(options.request.steps, isNull); + expect(options.request.guidanceScale, isNull); + expect(options.request.seed, isNull); + expect(options.request.count, 1); + expect(options.outputPath, 'image.png'); + expect(options.device, ImageGenerationDevice.auto); + expect(options.threads, 0); + expect( + options.model('/m/sdxs.gguf', null).family, + ImageGenerationModelFamily.sdxs, + ); + }); + + test('reads every option for sd-turbo', () { + final options = _parse(const [ + '--preset', + 'sd-turbo', + '-m', + '/models/turbo.gguf', + '--taesd', + '/models/taesd.safetensors', + '-p', + 'a lighthouse', + '--negative', + 'blurry', + '--width', + '256', + '--height', + '320', + '--steps', + '4', + '--guidance', + '1.5', + '--seed', + '42', + '--count', + '2', + '-o', + 'out/light.png', + '--device', + 'cpu', + '--threads', + '6', + ]); + + expect(options.preset, ImagePreset.sdTurbo); + expect(options.modelSource.path, '/models/turbo.gguf'); + expect(options.taesdSource?.path, '/models/taesd.safetensors'); + expect(options.request.negativePrompt, 'blurry'); + expect((options.request.width, options.request.height), (256, 320)); + expect(options.request.steps, 4); + expect(options.request.guidanceScale, 1.5); + expect(options.request.seed, 42); + expect(options.request.count, 2); + expect(options.device, ImageGenerationDevice.cpu); + expect(options.threads, 6); + expect(options.outputPathFor(0), 'out/light.png'); + expect(options.outputPathFor(1), 'out/light-1.png'); + final model = options.model('/m/turbo.gguf', '/m/taesd.safetensors'); + expect(model.files.taesd, '/m/taesd.safetensors'); + }); + + test('sd-turbo defaults to the pinned checkpoint and --taesd default', () { + final options = _parse(const [ + '--preset', + 'sd-turbo', + '--taesd', + 'default', + '-p', + 'a', + ]); + + expect( + options.modelSource.canonicalKey, + ModelSource.parse(defaultSdTurboModelSource).canonicalKey, + ); + expect( + options.taesdSource?.canonicalKey, + ModelSource.parse(defaultTaesdSource).canonicalKey, + ); + }); + + test('rejects a missing prompt, malformed numbers and sdxs TAESD', () { + for (final (arguments, message) in const [ + ([], '--prompt'), + (['-p', 'a', '--width', 'wide'], '--width'), + (['-p', 'a', '--guidance', 'high'], '--guidance'), + (['-p', 'a', '--taesd', 'default'], '--taesd'), + (['-p', 'a', '--model', 'ftp://host/m.gguf'], '--model'), + ]) { + expect( + () => _parse(arguments), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains(message), + ), + ), + reason: '$arguments', + ); + } + }); + + test('names output files without an extension', () { + final options = _parse(const ['-p', 'a', '-o', 'out']); + + expect(options.outputPathFor(2), 'out-2'); + }); +} diff --git a/example/basic_app/test/image_generation_e2e_test.dart b/example/basic_app/test/image_generation_e2e_test.dart new file mode 100644 index 000000000..88961a3fb --- /dev/null +++ b/example/basic_app/test/image_generation_e2e_test.dart @@ -0,0 +1,190 @@ +@Tags(['local-only']) +@Timeout(Duration(minutes: 10)) +library; + +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; +import 'package:test/test.dart'; + +// Real image generation through the stable_diffusion runtime this example +// opts into. Downloads nothing: set LLAMADART_SDXS_MODEL, and optionally +// LLAMADART_SD_TURBO_MODEL, LLAMADART_TAESD and LLAMADART_IMAGE_OUTPUT_DIR. +void main() { + final sdxsPath = Platform.environment['LLAMADART_SDXS_MODEL']; + final sdTurboPath = Platform.environment['LLAMADART_SD_TURBO_MODEL']; + final taesdPath = Platform.environment['LLAMADART_TAESD']; + final outputDir = Platform.environment['LLAMADART_IMAGE_OUTPUT_DIR']; + if (outputDir != null) { + Directory(outputDir).createSync(recursive: true); + } + + group('SDXS', () { + late ImageGenerationEngine engine; + + setUpAll(() async { + engine = await ImageGenerationEngine.load( + ImageGenerationModel.sdxs(sdxsPath!), + ); + }); + + tearDownAll(() => engine.dispose()); + + test( + 'generates a 256x256 image in one step with labelled progress', + () async { + final task = engine.generate( + const ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + width: 256, + height: 256, + seed: 42, + ), + ); + final events = await task.events.toList(); + + final phases = events + .whereType() + .map((e) => '${e.phase.name} ${e.step}/${e.steps}') + .toList(); + expect(phases, [ + 'encodingPrompt 0/1', + 'sampling 0/1', + 'sampling 1/1', + 'decoding 0/1', + ]); + final result = (events.last as ImageGenerationFinalEvent).result; + final image = result.images.single; + expect((image.width, image.height, image.channels), (256, 256, 3)); + expect(image.pixels, hasLength(256 * 256 * 3)); + expect(image.pixels.toSet().length, greaterThan(64)); + expect(result.seed, 42); + final png = image.toPng(); + expect(png.sublist(1, 4), 'PNG'.codeUnits); + if (outputDir != null) { + File('$outputDir/sdxs-256-seed42.png').writeAsBytesSync(png); + } + expect( + engine.capabilities.backendName, + Platform.isMacOS ? startsWith('MTL') : isNotEmpty, + ); + }, + ); + + test('the same seed reproduces the same pixels', () async { + Future> run(int seed) async => (await engine.generateImage( + ImageGenerationRequest( + prompt: 'a lighthouse on a cliff', + width: 256, + height: 256, + seed: seed, + ), + )).images.single.pixels; + + final first = await run(7); + expect(await run(7), first); + expect(await run(8), isNot(first)); + }); + + test('a cancel before sampling and a cancel mid-run both stop, and the ' + 'engine keeps working', () async { + final early = engine.generate( + const ImageGenerationRequest(prompt: 'a forest', steps: 20), + )..cancel(); + expect( + (await early.done).state, + ImageGenerationCompletionState.cancelled, + ); + + final running = engine.generate( + const ImageGenerationRequest(prompt: 'a forest', steps: 20), + ); + var lastSamplingStep = 0; + await for (final event in running.events) { + if (event case ImageGenerationProgressEvent( + phase: ImageGenerationPhase.sampling, + :final step, + )) { + lastSamplingStep = step; + if (step == 1) { + running.cancel(); + } + } + } + expect( + (await running.done).state, + ImageGenerationCompletionState.cancelled, + ); + expect(lastSamplingStep, lessThan(20)); + + final after = await engine.generateImage( + const ImageGenerationRequest( + prompt: 'a forest', + width: 256, + height: 256, + seed: 1, + ), + ); + expect(after.images.single.width, 256); + }); + + test('rejects a second generation or load while one runs', () async { + final running = engine.generate( + const ImageGenerationRequest(prompt: 'a', width: 256, height: 256), + ); + + expect( + () => engine.generate(const ImageGenerationRequest(prompt: 'b')), + throwsA(isA()), + ); + await expectLater( + ImageGenerationEngine.load(ImageGenerationModel.sdxs(sdxsPath!)), + throwsA(isA()), + ); + expect( + (await running.done).state, + ImageGenerationCompletionState.completed, + ); + }); + }, skip: sdxsPath == null ? 'Set LLAMADART_SDXS_MODEL' : false); + + test('SD-Turbo with TAESD generates in one step', () async { + final engine = await ImageGenerationEngine.load( + ImageGenerationModel.sdTurbo(sdTurboPath!, taesdPath: taesdPath), + ); + addTearDown(engine.dispose); + + final result = await engine.generateImage( + const ImageGenerationRequest( + prompt: 'a bowl of ramen, studio photo', + width: 256, + height: 256, + seed: 42, + ), + ); + + expect(engine.capabilities.modelVersion, contains('2.')); + expect(result.images.single.pixels.toSet().length, greaterThan(64)); + if (outputDir != null) { + File( + '$outputDir/sd-turbo-256-seed42.png', + ).writeAsBytesSync(result.images.single.toPng()); + } + }, skip: sdTurboPath == null ? 'Set LLAMADART_SD_TURBO_MODEL' : false); + + test('dispose during a generation cancels it', () async { + final engine = await ImageGenerationEngine.load( + ImageGenerationModel.sdxs(sdxsPath!), + ); + final result = engine.generateImage( + const ImageGenerationRequest(prompt: 'a castle', steps: 20), + ); + + final cancelled = expectLater(result, throwsA(isA())); + + await engine.dispose(); + + await cancelled; + expect(engine.capabilities.isSupported, isFalse); + }, skip: sdxsPath == null ? 'Set LLAMADART_SDXS_MODEL' : false); +} diff --git a/lib/llamadart.dart b/lib/llamadart.dart index f191eaf55..deaea78d3 100644 --- a/lib/llamadart.dart +++ b/lib/llamadart.dart @@ -41,6 +41,18 @@ export 'src/core/engine/chat_session.dart' show ChatSession; export 'src/core/speech/speech_to_text.dart'; export 'src/core/speech/text_to_speech.dart'; +// Image generation (experimental) +export 'src/core/image/generated_image.dart'; +export 'src/core/image/image_generation_engine.dart' + show + ImageGenerationCapabilities, + ImageGenerationEngine, + ImageGenerationTask; +export 'src/core/image/image_generation_events.dart'; +export 'src/core/image/image_generation_model.dart'; +export 'src/core/image/image_generation_request.dart' + show ImageGenerationRequest; + // Decision models export 'src/core/decision/decision_engine.dart'; export 'src/core/decision/decision_key.dart'; diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart new file mode 100644 index 000000000..b32aa2ebe --- /dev/null +++ b/lib/src/backends/stable_diffusion/stable_diffusion_image_worker.dart @@ -0,0 +1,352 @@ +import 'dart:async'; +import 'dart:ffi'; +import 'dart:isolate'; + +import 'package:ffi/ffi.dart'; + +import '../../core/exceptions.dart'; +import '../../core/image/generated_image.dart'; +import '../../core/image/image_generation_driver.dart'; +import 'stable_diffusion_bindings.dart' as sd; + +typedef _ProgressCallback = NativeCallable; + +/// One stable-diffusion.cpp context running in a dedicated worker isolate. +/// +/// Loading and `generate_image` block, so both run in the worker. Progress +/// comes back through a [NativeCallable.listener] owned by the calling +/// isolate, which is safe to invoke from any runtime thread. Cancellation +/// calls `sd_cancel_generation` from the calling isolate, since the worker is +/// blocked inside `generate_image`; the runtime flag is atomic. +final class StableDiffusionImageWorker implements ImageGenerationSession { + final Isolate _isolate; + final ReceivePort _replies; + final StreamIterator _replyIterator; + final SendPort _commands; + final _ProgressCallback _progress; + final Pointer _context; + void Function(int step, int steps)? _onProgress; + bool _disposed = false; + bool _stopped = false; + + @override + final String modelVersion; + + StableDiffusionImageWorker._( + this._isolate, + this._replies, + this._replyIterator, + this._commands, + this._progress, + this._context, + this.modelVersion, + ); + + /// Spawns a worker and loads [config] in it. + /// + /// Throws [LlamaModelException] when the runtime cannot load the files as + /// an image model. + static Future start( + ImageGenerationSessionConfig config, + ) async { + void Function(int step, int steps)? route; + final progress = _ProgressCallback.listener( + (int step, int steps, double _, Pointer _) => + route?.call(step, steps), + ); + final replies = ReceivePort('llamadart-image-generation-replies'); + final iterator = StreamIterator(replies); + Isolate? isolate; + try { + isolate = await Isolate.spawn( + _workerMain, + (replies.sendPort, config, progress.nativeFunction.address), + debugName: 'llamadart-image-generation', + onExit: replies.sendPort, + onError: replies.sendPort, + ); + final loaded = _unwrap(await _next(iterator)) as _Loaded; + final worker = StableDiffusionImageWorker._( + isolate, + replies, + iterator, + loaded.commands, + progress, + Pointer.fromAddress(loaded.context), + loaded.modelVersion, + ); + route = (step, steps) => worker._onProgress?.call(step, steps); + return worker; + } catch (_) { + isolate?.kill(priority: Isolate.immediate); + await iterator.cancel(); + progress.close(); + rethrow; + } + } + + @override + Future?> generate( + ImageGenerationSessionRequest request, + void Function(int step, int steps) onProgress, + ) async { + if (_stopped) { + throw LlamaStateException( + 'The image-generation worker stopped; load the model again.', + ); + } + _onProgress = onProgress; + try { + _commands.send(request); + final reply = await _reply() as _Generated; + return reply.images == null + ? null + : [ + for (final image in reply.images!) + GeneratedImage( + width: image.width, + height: image.height, + channels: image.channels, + pixels: image.pixels.materialize().asUint8List(), + ), + ]; + } finally { + _onProgress = null; + } + } + + @override + void cancel() { + if (!_disposed) { + sd.sd_cancel_generation(_context, sd.sd_cancel_mode_t.SD_CANCEL_ALL); + } + } + + @override + Future dispose() async { + if (_disposed) { + return; + } + _disposed = true; + try { + if (!_stopped) { + _commands.send(const _Dispose()); + await _reply(); + } + } finally { + _isolate.kill(priority: Isolate.immediate); + await _replyIterator.cancel(); + _replies.close(); + // The worker cleared the callback before replying, so nothing calls it. + _progress.close(); + } + } + + /// The next worker reply, unwrapped. Marks the worker stopped when it has + /// exited, so later calls fail at once instead of waiting for a reply. + Future _reply() async { + try { + return _unwrap(await _next(_replyIterator)); + } on LlamaStateException { + _stopped = true; + rethrow; + } + } + + static Future _next(StreamIterator replies) async { + if (!await replies.moveNext()) { + throw LlamaStateException('The image-generation worker stopped.'); + } + return replies.current; + } + + static Object? _unwrap(Object? reply) => switch (reply) { + _LoadFailure(:final message) => throw LlamaModelException(message), + null => throw LlamaStateException( + 'The image-generation worker exited unexpectedly.', + ), + [final error, _] => throw LlamaStateException( + 'The image-generation worker failed.', + error, + ), + _ => reply, + }; +} + +final class _Loaded { + final SendPort commands; + final int context; + final String modelVersion; + + const _Loaded(this.commands, this.context, this.modelVersion); +} + +final class _LoadFailure { + final String message; + + const _LoadFailure(this.message); +} + +final class _Dispose { + const _Dispose(); +} + +final class _Disposed { + const _Disposed(); +} + +final class _ImagePayload { + final int width; + final int height; + final int channels; + final TransferableTypedData pixels; + + const _ImagePayload(this.width, this.height, this.channels, this.pixels); +} + +final class _Generated { + final List<_ImagePayload>? images; + + const _Generated(this.images); +} + +void _workerMain((SendPort, ImageGenerationSessionConfig, int) arguments) { + final (replies, config, progressAddress) = arguments; + final progress = + Pointer>.fromAddress( + progressAddress, + ); + + final context = _withProgress(progress, () => _newContext(config)); + if (context == nullptr) { + replies.send( + const _LoadFailure( + 'stable-diffusion.cpp could not load the image model files; check ' + 'that they form a supported checkpoint and that the device has ' + 'enough memory.', + ), + ); + return; + } + if (!sd.sd_ctx_supports_image_generation(context)) { + sd.free_sd_ctx(context); + replies.send( + const _LoadFailure('The loaded model does not support image generation.'), + ); + return; + } + + final commands = ReceivePort('llamadart-image-generation-commands'); + final version = sd.sd_get_model_version_name(context); + replies.send( + _Loaded( + commands.sendPort, + context.address, + version == nullptr ? '' : version.cast().toDartString(), + ), + ); + commands.listen((command) { + switch (command) { + case ImageGenerationSessionRequest(): + replies.send( + _withProgress(progress, () => _generate(context, command)), + ); + case _Dispose(): + sd.free_sd_ctx(context); + commands.close(); + replies.send(const _Disposed()); + } + }); +} + +/// Runs [body] with the process-wide progress callback set, so the runtime +/// never prints progress bars to stdout, and clears it before returning. +T _withProgress( + Pointer> progress, + T Function() body, +) { + sd.sd_set_progress_callback(progress, nullptr); + try { + return body(); + } finally { + sd.sd_set_progress_callback(nullptr, nullptr); + } +} + +Pointer _newContext(ImageGenerationSessionConfig config) { + return using((arena) { + Pointer text(String? value) => + value == null ? nullptr : value.toNativeUtf8(allocator: arena).cast(); + + final params = arena(); + sd.sd_ctx_params_init(params); + final files = config.files; + params.ref + ..model_path = text(files['model']) + ..diffusion_model_path = text(files['diffusionModel']) + ..vae_path = text(files['vae']) + ..taesd_path = text(files['taesd']) + ..clip_l_path = text(files['clipL']) + ..clip_g_path = text(files['clipG']) + ..t5xxl_path = text(files['t5xxl']) + ..backend = text(config.backend) + // Load every weight now, so a model that does not fit fails the load + // and progress during generation is only sampling. + ..eager_load = true; + if (config.threads > 0) { + params.ref.n_threads = config.threads; + } + return sd.new_sd_ctx(params); + }); +} + +_Generated _generate( + Pointer context, + ImageGenerationSessionRequest request, +) { + return using((arena) { + final params = arena(); + sd.sd_img_gen_params_init(params); + params.ref + ..prompt = request.prompt.toNativeUtf8(allocator: arena).cast() + ..negative_prompt = request.negativePrompt + .toNativeUtf8(allocator: arena) + .cast() + ..width = request.width + ..height = request.height + ..seed = request.seed + ..batch_count = request.count; + params.ref.sample_params + ..sample_steps = request.steps + ..guidance.txt_cfg = request.guidanceScale; + + final imagesOut = arena>(); + final countOut = arena(); + final ok = sd.generate_image(context, params, imagesOut, countOut); + final images = imagesOut.value; + final count = countOut.value; + try { + if (!ok || images == nullptr) { + return const _Generated(null); + } + return _Generated([ + for (var i = 0; i < count; i++) + if (images[i].data != nullptr) _copy(images[i]), + ]); + } finally { + if (images != nullptr) { + sd.free_sd_images(images, count); + } + } + }); +} + +_ImagePayload _copy(sd.sd_image_t image) { + final length = image.width * image.height * image.channel; + return _ImagePayload( + image.width, + image.height, + image.channel, + TransferableTypedData.fromList([image.data.asTypedList(length)]), + ); +} diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart new file mode 100644 index 000000000..2e03e8cf7 --- /dev/null +++ b/lib/src/backends/stable_diffusion/stable_diffusion_memory.dart @@ -0,0 +1,123 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; + +/// Size of the regular file at [path] in bytes, or `null` when there is none. +int? stableDiffusionFileSize(String path) { + final file = File(path); + try { + return file.statSync().type == FileSystemEntityType.file + ? file.lengthSync() + : null; + } on FileSystemException { + return null; + } +} + +/// Memory the host can give a new image model, and where the figure came +/// from, or `null` when the platform does not report one. +/// +/// - Android and Linux: `MemAvailable` from `/proc/meminfo`, the memory the +/// kernel can hand out without swapping. Android's low-memory killer acts +/// on the same figure. +/// - iOS: `os_proc_available_memory()`, what the app can still allocate +/// before it reaches its memory limit. +/// - macOS: physical memory (`hw.memsize`). macOS compresses and swaps, so +/// only a model that cannot fit at all is refused. +/// - Windows and others: `null`; the check is skipped. +/// +/// [abi], [readMemInfo], [iosAvailableMemory] and [macosPhysicalMemory] +/// default to the host; tests replace them. +({int bytes, String source})? readStableDiffusionMemoryBudget({ + Abi? abi, + String? Function() readMemInfo = _readProcMemInfo, + int? Function() iosAvailableMemory = _iosAvailableMemory, + int? Function() macosPhysicalMemory = _macosPhysicalMemory, +}) { + final target = abi ?? Abi.current(); + final os = target.toString().split('_').first; + final (int?, String) reading = switch (os) { + 'android' || 'linux' => ( + switch (readMemInfo()) { + final String memInfo => parseMemAvailableBytes(memInfo), + null => null, + }, + 'MemAvailable in /proc/meminfo', + ), + 'ios' => (iosAvailableMemory(), "the app's remaining iOS memory limit"), + 'macos' => (macosPhysicalMemory(), 'physical memory'), + _ => (null, ''), + }; + final bytes = reading.$1; + return bytes == null || bytes <= 0 + ? null + : (bytes: bytes, source: reading.$2); +} + +/// `MemAvailable` from `/proc/meminfo` text, in bytes, or `null` when the +/// line is missing or malformed (kernels before 3.14 do not report it). +int? parseMemAvailableBytes(String memInfo) { + final match = RegExp( + r'^MemAvailable:\s+(\d+)\s*kB\s*$', + multiLine: true, + ).firstMatch(memInfo); + final kib = match == null ? null : int.tryParse(match.group(1)!); + return kib == null ? null : kib * 1024; +} + +String? _readProcMemInfo() { + try { + return File('/proc/meminfo').readAsStringSync(); + } on FileSystemException { + return null; + } +} + +int? _iosAvailableMemory() { + try { + final available = DynamicLibrary.process() + .lookupFunction( + 'os_proc_available_memory', + ); + return available(); + } on ArgumentError { + return null; + } +} + +int? _macosPhysicalMemory() { + try { + final sysctlbyname = DynamicLibrary.process() + .lookupFunction< + Int Function( + Pointer, + Pointer, + Pointer, + Pointer, + Size, + ), + int Function( + Pointer, + Pointer, + Pointer, + Pointer, + int, + ) + >('sysctlbyname'); + return using((arena) { + final value = arena(); + final length = arena()..value = sizeOf(); + final status = sysctlbyname( + 'hw.memsize'.toNativeUtf8(allocator: arena), + value.cast(), + length, + nullptr, + 0, + ); + return status == 0 ? value.value : null; + }); + } on ArgumentError { + return null; + } +} 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 67bb3fa10..f4c7324c5 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -36,17 +36,30 @@ const Set stableDiffusionPublishedAbis = { /// The library is resolved through its native-asset id /// (`package:llamadart/stable_diffusion`) on the first native call, so /// nothing is loaded before the platform checks pass: an unpublished ABI is -/// rejected up front, and on Android arm64 `/proc/cpuinfo` must report -/// [stableDiffusionRequiredArmFeatures] because the runtime is built for -/// Armv8.2 dot-product and fp16 and would crash with an illegal instruction -/// otherwise. Then `sd_version`, -/// `sd_commit` and `sd_list_devices` must answer. +/// rejected up front, and the CPU must support what the runtime was compiled +/// for, or it would crash with an illegal instruction: /// -/// [abi], [readCpuInfo] and [api] default to the host and the bundled -/// library; tests replace them. +/// - Android arm64: `/proc/cpuinfo` must report +/// [stableDiffusionRequiredArmFeatures] (Armv8.2 dot-product and fp16). +/// - Linux x64: `/proc/cpuinfo` must report +/// [stableDiffusionRequiredX86Features]. +/// - Windows x64: `IsProcessorFeaturePresent` must report AVX2. Windows has no +/// feature constant for FMA, F16C or BMI2; every x86 CPU with AVX2 also has +/// them. +/// +/// macOS x64 needs no check: the runtime is cross-compiled without AVX, and +/// macOS 13.3 runs only on Intel CPUs that have AVX2 anyway. +/// +/// Then `sd_version`, `sd_commit` and `sd_list_devices` must answer. +/// +/// [abi], [readCpuInfo], [windowsHasAvx2], [missingWindowsLibraries] and +/// [api] default to the host and the bundled library; tests replace them. StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ Abi? abi, String? Function() readCpuInfo = _readProcCpuInfo, + bool Function() windowsHasAvx2 = _windowsHasAvx2, + List Function(List names) missingWindowsLibraries = + _missingWindowsLibraries, StableDiffusionNativeApi api = const _BundledStableDiffusionApi(), }) { final targetAbi = abi ?? Abi.current(); @@ -83,6 +96,30 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ } } + if (targetAbi == Abi.linuxX64) { + final cpuInfo = readCpuInfo(); + if (cpuInfo == null || !cpuInfoReportsRequiredX86Features(cpuInfo)) { + final evidence = cpuInfo == null + ? '/proc/cpuinfo could not be read to confirm it' + : 'this CPU does not report them in /proc/cpuinfo'; + return StableDiffusionRuntimeStatus.unavailable( + LlamaUnsupportedException( + 'stable_diffusion runtime on $platform requires an x86-64 CPU with ' + '$_x86FeatureList, and $evidence.', + ), + ); + } + } + + if (targetAbi == Abi.windowsX64 && !windowsHasAvx2()) { + return StableDiffusionRuntimeStatus.unavailable( + LlamaUnsupportedException( + 'stable_diffusion runtime on $platform requires an x86-64 CPU with ' + '$_x86FeatureList; this CPU does not report AVX2.', + ), + ); + } + try { final version = api.version(); final commit = api.commit(); @@ -94,7 +131,11 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ ); } on ArgumentError catch (error) { return StableDiffusionRuntimeStatus.unavailable( - stableDiffusionLoadFailure(platform: platform, error: error), + stableDiffusionLoadFailure( + platform: platform, + error: error, + missingWindowsLibraries: missingWindowsLibraries, + ), ); } } @@ -105,11 +146,16 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime({ /// symbol through the same [ArgumentError]; only its message tells them /// apart. A missing asset is checked first because that message lists every /// bundled asset, which on Linux and Windows includes llama.cpp's -/// `ggml-vulkan`. A dynamic-loader failure names the loader library it could -/// not find. +/// `ggml-vulkan`. A Linux dynamic-loader failure names the loader library it +/// could not find. Windows reports only error 126 without naming the +/// dependency, so [missingWindowsLibraries] checks which of the runtime's +/// imports fail to load: the Visual C++ runtime, which stock Windows Server +/// lacks, and the Vulkan loader. LlamaUnsupportedException stableDiffusionLoadFailure({ required String platform, required ArgumentError error, + List Function(List names) missingWindowsLibraries = + _missingWindowsLibraries, }) { final detail = '${error.message ?? error}'; if (detail.contains('No asset with id')) { @@ -123,8 +169,9 @@ LlamaUnsupportedException stableDiffusionLoadFailure({ return LlamaUnsupportedException( 'stable_diffusion runtime on $platform is the Vulkan variant, which ' 'requires the Vulkan loader (libvulkan.so.1 on Linux, vulkan-1.dll on ' - 'Windows); install it, or select the CPU backend for this platform in ' - 'llamadart_native_backends and rebuild.', + 'Windows); install it, or set ' + 'hooks.user_defines.llamadart.llamadart_stable_diffusion_backends to ' + '[cpu] for this platform and rebuild.', ); } if (detail.contains('Failed to lookup symbol')) { @@ -134,16 +181,73 @@ LlamaUnsupportedException stableDiffusionLoadFailure({ 'pinned stable-diffusion-native release.', ); } + final firstLine = detail.split('\n').first.trimRight(); + if (detail.contains('error code: 126')) { + final cause = firstLine.replaceFirst(RegExp(r'\.+$'), ''); + final missingRuntime = missingWindowsLibraries( + _windowsVisualCppRuntimeLibraries, + ); + if (missingRuntime.isNotEmpty) { + return LlamaUnsupportedException( + 'stable_diffusion runtime could not be loaded on $platform: $cause. ' + 'It requires the Microsoft Visual C++ 2015-2022 Redistributable (x64), ' + 'and ${missingRuntime.join(', ')} could not be loaded; install ' + 'vc_redist.x64.exe or ship those DLLs next to stable-diffusion.dll.', + ); + } + if (missingWindowsLibraries(const ['vulkan-1.dll']).isNotEmpty) { + return LlamaUnsupportedException( + 'stable_diffusion runtime could not be loaded on $platform: $cause. ' + 'vulkan-1.dll could not be loaded; if the app bundles the Vulkan ' + 'build, install a GPU driver that provides the Vulkan loader, or set ' + 'hooks.user_defines.llamadart.llamadart_stable_diffusion_backends to ' + '[cpu] and rebuild.', + ); + } + return LlamaUnsupportedException( + 'stable_diffusion runtime could not be loaded on $platform: $cause. ' + 'Windows does not name the missing dependency, and the Visual C++ ' + 'runtime and Vulkan loader both load.', + ); + } return LlamaUnsupportedException( - 'stable_diffusion runtime could not be loaded on $platform: ' - '${detail.split('\n').first}', + 'stable_diffusion runtime could not be loaded on $platform: $firstLine', ); } final String _armFeatureList = stableDiffusionRequiredArmFeatures.join(', '); +final String _x86FeatureList = stableDiffusionRequiredX86Features + .map((feature) => feature.toUpperCase()) + .join(', '); + +/// `PF_AVX2_INSTRUCTIONS_AVAILABLE` for `IsProcessorFeaturePresent`. +const int _pfAvx2InstructionsAvailable = 40; + const List _vulkanLoaderNames = ['libvulkan.so', 'vulkan-1.dll']; +/// The Visual C++ runtime DLLs `stable-diffusion.dll` imports. +const List _windowsVisualCppRuntimeLibraries = [ + 'msvcp140.dll', + 'msvcp140_codecvt_ids.dll', + 'vcruntime140.dll', + 'vcruntime140_1.dll', +]; + +List _missingWindowsLibraries(List names) => [ + for (final name in names) + if (!_canLoadLibrary(name)) name, +]; + +bool _canLoadLibrary(String name) { + try { + DynamicLibrary.open(name); + return true; + } on ArgumentError { + return false; + } +} + String _abiLabel(Abi abi) => abi.toString().replaceAll('_', '-'); String? _readProcCpuInfo() { @@ -154,6 +258,14 @@ String? _readProcCpuInfo() { } } +bool _windowsHasAvx2() { + final isProcessorFeaturePresent = DynamicLibrary.open('kernel32.dll') + .lookupFunction( + 'IsProcessorFeaturePresent', + ); + return isProcessorFeaturePresent(_pfAvx2InstructionsAvailable) != 0; +} + final class _BundledStableDiffusionApi implements StableDiffusionNativeApi { const _BundledStableDiffusionApi(); diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart index 1b0c0b53d..2c5598b0c 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart @@ -88,19 +88,38 @@ const List stableDiffusionRequiredArmFeatures = [ /// [stableDiffusionRequiredArmFeatures]. `false` when there is no `Features` /// line, so an unreadable or foreign format never passes. Every core must /// report them because the process may be scheduled on any of them. -bool cpuInfoReportsRequiredArmFeatures(String cpuInfo) { - var sawFeatures = false; +bool cpuInfoReportsRequiredArmFeatures(String cpuInfo) => + _everyLineReports(cpuInfo, 'features', stableDiffusionRequiredArmFeatures); + +/// CPU features the Linux and Windows x64 runtimes are compiled for: ggml's +/// portable x86 build enables AVX2, FMA, F16C and BMI2, so a CPU without them +/// crashes with an illegal instruction. +const List stableDiffusionRequiredX86Features = [ + 'avx2', + 'fma', + 'f16c', + 'bmi2', +]; + +/// Whether every `flags` line of an x86 Linux `/proc/cpuinfo` lists all of +/// [stableDiffusionRequiredX86Features]. `false` when there is no `flags` +/// line, so an unreadable or foreign format never passes. +bool cpuInfoReportsRequiredX86Features(String cpuInfo) => + _everyLineReports(cpuInfo, 'flags', stableDiffusionRequiredX86Features); + +bool _everyLineReports(String cpuInfo, String key, List required) { + var sawKey = false; for (final line in cpuInfo.split('\n')) { final separator = line.indexOf(':'); if (separator < 0 || - line.substring(0, separator).trim().toLowerCase() != 'features') { + line.substring(0, separator).trim().toLowerCase() != key) { continue; } - sawFeatures = true; + sawKey = true; final features = line.substring(separator + 1).trim().split(RegExp(r'\s+')); - if (!stableDiffusionRequiredArmFeatures.every(features.contains)) { + if (!required.every(features.contains)) { return false; } } - return sawFeatures; + return sawKey; } diff --git a/lib/src/core/exceptions.dart b/lib/src/core/exceptions.dart index cbd8ef205..8b0ff6e88 100644 --- a/lib/src/core/exceptions.dart +++ b/lib/src/core/exceptions.dart @@ -94,6 +94,13 @@ class LlamaStateException extends LlamaException { LlamaStateException(super.message, [super.details]); } +/// Exception thrown when an image-generation request or image buffer is +/// invalid. +class LlamaImageGenerationException extends LlamaException { + /// Creates a new [LlamaImageGenerationException]. + LlamaImageGenerationException(super.message, [super.details]); +} + /// Exception thrown when a decision-model request is invalid or cannot be answered. class LlamaDecisionException extends LlamaException { /// Creates a new [LlamaDecisionException]. diff --git a/lib/src/core/image/generated_image.dart b/lib/src/core/image/generated_image.dart new file mode 100644 index 000000000..31b2bdc7c --- /dev/null +++ b/lib/src/core/image/generated_image.dart @@ -0,0 +1,56 @@ +import 'dart:typed_data'; + +import 'png_encoder.dart'; + +/// A generated image with 8-bit interleaved channels. +class GeneratedImage { + /// Width in pixels. + final int width; + + /// Height in pixels. + final int height; + + /// Channels per pixel: 3 (RGB) for the stable_diffusion runtime. + final int channels; + + /// Row-major pixel bytes, `width * height * channels` long. + final Uint8List pixels; + + /// Creates a generated image. + const GeneratedImage({ + required this.width, + required this.height, + required this.channels, + required this.pixels, + }); + + /// Encodes this image as PNG bytes. + /// + /// Throws `LlamaImageGenerationException` when [pixels] does not match the + /// dimensions or [channels] is not 1, 3 or 4. + Uint8List toPng() => encodePng( + width: width, + height: height, + channels: channels, + pixels: pixels, + ); +} + +/// The images of one completed generation. +class ImageGenerationResult { + /// Generated images, one per requested image, in seed order. + final List images; + + /// Seed of the first image; image `i` used `seed + i`. + final int seed; + + /// Wall-clock generation time, excluding model load. + final Duration elapsed; + + /// Creates a generation result. + const ImageGenerationResult({ + required this.images, + required this.seed, + required this.elapsed, + }); +} diff --git a/lib/src/core/image/image_generation_driver.dart b/lib/src/core/image/image_generation_driver.dart new file mode 100644 index 000000000..8f6c525d6 --- /dev/null +++ b/lib/src/core/image/image_generation_driver.dart @@ -0,0 +1,108 @@ +import '../../backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import 'generated_image.dart'; + +/// Model files and runtime settings for one native image-generation context. +final class ImageGenerationSessionConfig { + /// Weight files keyed by role, as in `ImageGenerationModelFiles.paths`. + final Map files; + + /// stable-diffusion.cpp backend name (`cpu`, `gpu`), or `null` for the + /// runtime default. + final String? backend; + + /// CPU threads; `0` uses the physical core count. + final int threads; + + /// Creates a session configuration. + const ImageGenerationSessionConfig({ + required this.files, + required this.backend, + required this.threads, + }); +} + +/// Fully resolved parameters for one native generation. +final class ImageGenerationSessionRequest { + /// Prompt. + final String prompt; + + /// Negative prompt. + final String negativePrompt; + + /// Width in pixels. + final int width; + + /// Height in pixels. + final int height; + + /// Sampling steps. + final int steps; + + /// Classifier-free guidance scale. + final double guidanceScale; + + /// Seed of the first image. + final int seed; + + /// Number of images. + final int count; + + /// Creates resolved generation parameters. + const ImageGenerationSessionRequest({ + required this.prompt, + required this.negativePrompt, + required this.width, + required this.height, + required this.steps, + required this.guidanceScale, + required this.seed, + required this.count, + }); +} + +/// Memory the device can give an image model, and where the figure came from. +typedef ImageGenerationMemoryBudget = ({int bytes, String source}); + +/// A loaded native image-generation context. +abstract interface class ImageGenerationSession { + /// Model family the runtime detected, such as `SD 2.x`. + String get modelVersion; + + /// Runs one generation, reporting native `(step, steps)` progress. + /// + /// Returns `null` when the runtime reports failure, which includes a + /// cancelled generation and a GPU command-buffer abort. The session stays + /// usable afterwards. + Future?> generate( + ImageGenerationSessionRequest request, + void Function(int step, int steps) onProgress, + ); + + /// Asks a running [generate] to stop. Safe to call at any time; the + /// runtime clears the request when the next generation starts. + void cancel(); + + /// Frees the native context. Must not overlap [generate]. + Future dispose(); +} + +/// Platform services behind `ImageGenerationEngine`. +abstract interface class ImageGenerationDriver { + /// Probes the stable_diffusion runtime without loading a model. + StableDiffusionRuntimeStatus probe(); + + /// Size of the file at [path] in bytes, or `null` when it does not exist. + int? fileSize(String path); + + /// Memory available to a new model, or `null` when the platform does not + /// report it. + ImageGenerationMemoryBudget? memoryBudget(); + + /// Loads a native context. + /// + /// Throws `LlamaModelException` when the runtime rejects the files. + Future start(ImageGenerationSessionConfig config); +} + +/// Test-only driver override used by focused public API tests. +ImageGenerationDriver? debugImageGenerationDriverOverride; diff --git a/lib/src/core/image/image_generation_driver_io.dart b/lib/src/core/image/image_generation_driver_io.dart new file mode 100644 index 000000000..77e0147a7 --- /dev/null +++ b/lib/src/core/image/image_generation_driver_io.dart @@ -0,0 +1,27 @@ +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 'image_generation_driver.dart'; + +/// Creates the driver for the bundled stable_diffusion runtime. +ImageGenerationDriver createImageGenerationDriver() => + const _NativeImageGenerationDriver(); + +class _NativeImageGenerationDriver implements ImageGenerationDriver { + const _NativeImageGenerationDriver(); + + @override + StableDiffusionRuntimeStatus probe() => probeStableDiffusionRuntime(); + + @override + int? fileSize(String path) => stableDiffusionFileSize(path); + + @override + ImageGenerationMemoryBudget? memoryBudget() => + readStableDiffusionMemoryBudget(); + + @override + Future start(ImageGenerationSessionConfig config) => + StableDiffusionImageWorker.start(config); +} diff --git a/lib/src/core/image/image_generation_driver_stub.dart b/lib/src/core/image/image_generation_driver_stub.dart new file mode 100644 index 000000000..4f165826e --- /dev/null +++ b/lib/src/core/image/image_generation_driver_stub.dart @@ -0,0 +1,25 @@ +import '../../backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import '../../backends/stable_diffusion/stable_diffusion_runtime_stub.dart'; +import 'image_generation_driver.dart'; + +/// Creates the driver for platforms without native image generation, such as +/// the web. Its probe always reports the runtime unavailable. +ImageGenerationDriver createImageGenerationDriver() => + const _UnsupportedImageGenerationDriver(); + +class _UnsupportedImageGenerationDriver implements ImageGenerationDriver { + const _UnsupportedImageGenerationDriver(); + + @override + StableDiffusionRuntimeStatus probe() => probeStableDiffusionRuntime(); + + @override + int? fileSize(String path) => null; + + @override + ImageGenerationMemoryBudget? memoryBudget() => null; + + @override + Future start(ImageGenerationSessionConfig config) => + Future.error(probe().unavailableReason!); +} diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart new file mode 100644 index 000000000..d5427a83d --- /dev/null +++ b/lib/src/core/image/image_generation_engine.dart @@ -0,0 +1,524 @@ +import 'dart:async'; +import 'dart:math'; + +import '../../backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import '../exceptions.dart'; +import 'generated_image.dart'; +import 'image_generation_driver.dart'; +import 'image_generation_driver_stub.dart' + if (dart.library.io) 'image_generation_driver_io.dart'; +import 'image_generation_events.dart'; +import 'image_generation_model.dart'; +import 'image_generation_progress.dart'; +import 'image_generation_request.dart'; + +/// Image-generation support of the runtime, and of a loaded engine. +class ImageGenerationCapabilities { + /// Whether images can be generated. + final bool isSupported; + + /// Actionable reason when [isSupported] is false. + final String? unsupportedReason; + + /// Device the engine runs on, such as `MTL0`, `Vulkan0` or `CPU`. For + /// `ImageGenerationEngine.runtimeCapabilities`, the device + /// `ImageGenerationDevice.auto` would pick. + final String? backendName; + + /// Every device the runtime reports, such as `MTL0`, `BLAS` and `CPU`. + final List deviceNames; + + /// stable-diffusion.cpp version of the bundled runtime. + final String? runtimeVersion; + + /// Model family the runtime detected, such as `SD 2.x`; `null` before a + /// model is loaded. + final String? modelVersion; + + /// Whether a running generation can be cancelled. + final bool supportsCancellation; + + /// Maximum concurrent generations: one per process. + final int maxConcurrentTasks; + + /// Creates a capability snapshot. + const ImageGenerationCapabilities({ + required this.isSupported, + this.unsupportedReason, + this.backendName, + this.deviceNames = const [], + this.runtimeVersion, + this.modelVersion, + this.supportsCancellation = false, + this.maxConcurrentTasks = 0, + }); +} + +/// A cancellable image generation. +class ImageGenerationTask { + final StreamController _events = + StreamController(); + final Completer _done = + Completer(); + final void Function() _onCancel; + bool _cancelled = false; + + ImageGenerationTask._(this._onCancel); + + /// Progress events followed by one [ImageGenerationFinalEvent]. + /// + /// Single-subscription. A failure is emitted as a stream error and also + /// reported by [done]; a cancelled task closes the stream without a final + /// event. + Stream get events => _events.stream; + + /// Completes once the task succeeds, is cancelled, or fails. + Future get done => _done.future; + + /// Whether cancellation has been requested. + bool get isCancellationRequested => _cancelled; + + /// Requests cancellation. Calling this more than once, or after the task + /// finished, is safe. + /// + /// The runtime stops before its next sampling step or before decoding, so + /// the task can take up to one step to report + /// [ImageGenerationCompletionState.cancelled]. + void cancel() { + if (_cancelled || _done.isCompleted) { + return; + } + _cancelled = true; + _onCancel(); + } + + void _add(ImageGenerationEvent event) { + if (!_events.isClosed) { + _events.add(event); + } + } + + void _finish(ImageGenerationCompletion completion) { + if (!_events.isClosed) { + unawaited(_events.close()); + } + if (!_done.isCompleted) { + _done.complete(completion); + } + } +} + +/// Experimental on-device text-to-image generation through the opt-in +/// stable_diffusion runtime (stable-diffusion.cpp). +/// +/// The app must bundle the runtime by adding `stable_diffusion` to +/// `hooks.user_defines.llamadart.llamadart_native_runtimes`. It runs on +/// Android arm64 (CPU), iOS and macOS (Metal), and Linux and Windows (CPU or +/// Vulkan). On the web and other platforms [load] throws +/// [LlamaUnsupportedException]. +/// +/// The model runs in a worker isolate, so the calling isolate stays +/// responsive. stable-diffusion.cpp reports progress through one +/// process-wide callback, so only one generation or model load can run at a +/// time; a second one throws [LlamaStateException]. The guard covers engines +/// 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. +/// +/// ```dart +/// final engine = await ImageGenerationEngine.load( +/// ImageGenerationModel.sdxs('sdxs-512-tinySDdistilled_Q8_0.gguf'), +/// ); +/// final result = await engine.generateImage( +/// const ImageGenerationRequest(prompt: 'a red fox in autumn leaves'), +/// ); +/// final png = result.images.first.toPng(); +/// await engine.dispose(); +/// ``` +class ImageGenerationEngine { + static Object? _activeOperation; + static final Random _seedRandom = Random(); + + /// The loaded model. + final ImageGenerationModel model; + + /// The runtime settings the model was loaded with. + final ImageGenerationOptions options; + + final ImageGenerationSession _session; + final StableDiffusionRuntimeStatus _runtime; + final String _backendName; + ImageGenerationTask? _activeTask; + Future? _disposal; + + ImageGenerationEngine._( + this.model, + this.options, + this._session, + this._runtime, + this._backendName, + ); + + /// Probes the bundled runtime without loading a model. + /// + /// Reports unsupported when the runtime is not bundled, the platform or CPU + /// is not supported, or on the web. + static ImageGenerationCapabilities runtimeCapabilities() { + final status = _driver.probe(); + final reason = status.unavailableReason; + if (reason != null) { + return ImageGenerationCapabilities( + isSupported: false, + unsupportedReason: reason.message, + ); + } + return ImageGenerationCapabilities( + isSupported: true, + backendName: _backendNameFor(ImageGenerationDevice.auto, status.devices), + deviceNames: [for (final device in status.devices) device.name], + runtimeVersion: status.version, + supportsCancellation: true, + maxConcurrentTasks: 1, + ); + } + + /// Loads [model] and returns a ready engine. + /// + /// Weights load eagerly, so the first [generate] does not pay for them. On + /// Apple GPUs the first generation after a load is still slower while + /// Metal compiles its shaders (about 19 s on an iPhone 16 Pro). + /// + /// Before loading, when [ImageGenerationOptions.checkMemory] is set and the + /// platform reports it, the model's estimated memory + /// (a quarter more than its file sizes, plus 256 MiB) is compared + /// with the memory available: `MemAvailable` on Android and Linux, the + /// app's remaining memory limit on iOS, and physical memory on macOS. + /// Windows reports nothing and is not checked. A model that does not fit + /// throws [LlamaModelException] naming both figures, instead of letting the + /// system kill the app. + /// + /// Throws: + /// - [LlamaUnsupportedException] when the runtime is unavailable (see + /// [runtimeCapabilities]), or when [ImageGenerationDevice.gpu] is + /// requested and the runtime reports no GPU. + /// - [LlamaModelException] when a file is missing, the model does not fit, + /// or the runtime cannot load it as an image model. + /// - [LlamaStateException] while another generation or load is running. + static Future load( + ImageGenerationModel model, { + ImageGenerationOptions options = const ImageGenerationOptions(), + }) async { + final driver = _driver; + final runtime = driver.probe()..throwIfUnavailable(); + final backendName = _backendNameFor(options.device, runtime.devices); + if (options.threads < 0) { + throw LlamaImageGenerationException( + 'ImageGenerationOptions.threads must be 0 or greater.', + options.threads, + ); + } + final files = model.files.paths; + if (files['model'] == null && files['diffusionModel'] == null) { + throw LlamaModelException( + 'An image-generation model needs a model or diffusionModel file.', + ); + } + var weightBytes = 0; + for (final MapEntry(key: role, value: path) in files.entries) { + final size = path.trim().isEmpty ? null : driver.fileSize(path); + if (size == null) { + throw LlamaModelException( + 'Image-generation $role file not found: "$path".', + ); + } + weightBytes += size; + } + if (options.checkMemory) { + _checkMemory(weightBytes, driver.memoryBudget()); + } + + final operation = _acquireOperation(); + try { + final session = await driver.start( + ImageGenerationSessionConfig( + files: files, + backend: switch (options.device) { + ImageGenerationDevice.auto => null, + ImageGenerationDevice.cpu => 'cpu', + ImageGenerationDevice.gpu => 'gpu', + }, + threads: options.threads, + ), + ); + return ImageGenerationEngine._( + model, + options, + session, + runtime, + backendName, + ); + } finally { + _releaseOperation(operation); + } + } + + /// Support of this engine; unsupported once disposed. + ImageGenerationCapabilities get capabilities { + if (_disposal != null) { + return const ImageGenerationCapabilities( + isSupported: false, + unsupportedReason: 'The ImageGenerationEngine is disposed.', + ); + } + return ImageGenerationCapabilities( + isSupported: true, + backendName: _backendName, + deviceNames: [for (final device in _runtime.devices) device.name], + runtimeVersion: _runtime.version, + modelVersion: _session.modelVersion, + supportsCancellation: true, + maxConcurrentTasks: 1, + ); + } + + /// Whether [dispose] has been called. + bool get isDisposed => _disposal != null; + + /// Starts generating the images [request] describes. + /// + /// Unset steps and guidance come from [ImageGenerationModel.defaults], and + /// an unset seed is picked at random and reported in the result. + /// + /// Throws [LlamaImageGenerationException] for an invalid request, including + /// invalid steps or guidance from [ImageGenerationModel.defaults], and + /// [LlamaStateException] after [dispose] or while another generation or + /// load is running. A runtime failure after the task starts, such as an + /// aborted GPU command buffer, fails the task with + /// [LlamaInferenceException]; the engine stays usable. + ImageGenerationTask generate(ImageGenerationRequest request) { + if (_disposal != null) { + throw LlamaStateException('The ImageGenerationEngine is disposed.'); + } + // Validate after applying the model defaults: custom defaults are not + // checked when the model is built, and the runtime crashes on 0 steps. + final effective = ImageGenerationRequest( + prompt: request.prompt, + negativePrompt: request.negativePrompt, + width: request.width, + height: request.height, + steps: request.steps ?? model.defaults.steps, + guidanceScale: request.guidanceScale ?? model.defaults.guidanceScale, + seed: request.seed, + count: request.count, + ); + validateImageGenerationRequest(effective); + final operation = _acquireOperation(); + final resolved = ImageGenerationSessionRequest( + prompt: effective.prompt, + negativePrompt: effective.negativePrompt, + width: effective.width, + height: effective.height, + steps: effective.steps!, + guidanceScale: effective.guidanceScale!, + seed: effective.seed ?? _seedRandom.nextInt(0x7FFFFFFF), + count: effective.count, + ); + final task = ImageGenerationTask._(_session.cancel); + _activeTask = task; + unawaited(_run(task, resolved, operation)); + return task; + } + + /// Generates the images [request] describes and returns them. + /// + /// Throws what [generate] throws, the failure of the task, or + /// [LlamaStateException] when [dispose] cancels it. + Future generateImage( + ImageGenerationRequest request, + ) async { + final completion = await generate(request).done; + return switch (completion.state) { + ImageGenerationCompletionState.completed => completion.result!, + ImageGenerationCompletionState.failed => throw completion.error!, + ImageGenerationCompletionState.cancelled => throw LlamaStateException( + 'Image generation was cancelled because the engine was disposed.', + ), + }; + } + + /// Cancels a running generation, waits for it to stop, and frees the + /// model. Calling this more than once is safe. + Future dispose() => _disposal ??= _dispose(); + + Future _dispose() async { + final task = _activeTask; + if (task != null) { + task.cancel(); + await task.done; + } + await _session.dispose(); + } + + Future _run( + ImageGenerationTask task, + ImageGenerationSessionRequest request, + Object operation, + ) async { + late final ImageGenerationCompletion completion; + try { + final tracker = ImageGenerationProgressTracker( + steps: request.steps, + imageCount: request.count, + ); + task._add(tracker.start()); + final stopwatch = Stopwatch()..start(); + final images = await _session.generate(request, (step, steps) { + if (task.isCancellationRequested) { + // stable-diffusion.cpp clears the cancel flag when a generation + // starts, so a cancel that arrived before then is re-applied here. + _session.cancel(); + return; + } + tracker.onNativeProgress(step, steps).forEach(task._add); + }); + stopwatch.stop(); + if (task.isCancellationRequested) { + completion = const ImageGenerationCompletion.cancelled(); + return; + } + if (images == null || images.isEmpty) { + throw LlamaInferenceException( + 'stable-diffusion.cpp could not generate the image. It reports no ' + 'reason; causes include running out of memory and an aborted GPU ' + 'command buffer. The engine can run the next request.', + ); + } + final result = ImageGenerationResult( + images: images, + seed: request.seed, + elapsed: stopwatch.elapsed, + ); + task._add(ImageGenerationFinalEvent(result)); + completion = ImageGenerationCompletion.completed(result); + } catch (error, stackTrace) { + if (task.isCancellationRequested) { + completion = const ImageGenerationCompletion.cancelled(); + return; + } + final failure = error is LlamaException + ? error + : LlamaInferenceException('Image generation failed.', error); + task._events.addError(failure, stackTrace); + completion = ImageGenerationCompletion.failed(failure); + } finally { + // Release before `done` completes so a caller awaiting it can start + // the next generation. + _releaseOperation(operation); + if (identical(_activeTask, task)) { + _activeTask = null; + } + task._finish(completion); + } + } + + static ImageGenerationDriver get _driver => + debugImageGenerationDriverOverride ?? createImageGenerationDriver(); + + static Object _acquireOperation() { + if (_activeOperation != null) { + throw LlamaStateException( + 'Another image generation or image model load is running. ' + 'stable-diffusion.cpp reports progress through one process-wide ' + 'callback, so only one can run at a time.', + ); + } + return _activeOperation = Object(); + } + + static void _releaseOperation(Object operation) { + if (identical(_activeOperation, operation)) { + _activeOperation = null; + } + } + + static void _checkMemory( + int weightBytes, + ImageGenerationMemoryBudget? budget, + ) { + if (budget == null) { + return; + } + final required = estimateImageGenerationMemoryBytes(weightBytes); + if (required <= budget.bytes) { + return; + } + 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 ' + 'ImageGenerationOptions.checkMemory to false to try anyway.', + ); + } + + static String _gib(int bytes) { + final gib = bytes / (1 << 30); + return gib.toStringAsFixed(gib < 10 ? 2 : 1); + } + + static String _backendNameFor( + ImageGenerationDevice device, + List devices, + ) { + final gpu = devices.where(_isGpu).firstOrNull?.name; + final cpu = devices + .where((d) => d.name.toUpperCase() == 'CPU') + .firstOrNull + ?.name; + return switch (device) { + ImageGenerationDevice.auto => gpu ?? cpu ?? 'CPU', + ImageGenerationDevice.cpu => cpu ?? 'CPU', + ImageGenerationDevice.gpu => + gpu ?? + (throw LlamaUnsupportedException( + 'ImageGenerationDevice.gpu needs a GPU, and the stable_diffusion ' + 'runtime reports only ${devices.map((d) => d.name).join(', ')}. ' + 'Android runs on the CPU; on Linux and Windows set ' + 'hooks.user_defines.llamadart.' + 'llamadart_stable_diffusion_backends to [vulkan]. Use ' + 'ImageGenerationDevice.auto or cpu otherwise.', + )), + }; + } + + static bool _isGpu(StableDiffusionDevice device) { + final name = device.name.toLowerCase(); + return _gpuDevicePrefixes.any(name.startsWith); + } + + /// ggml registry names of GPU devices. The published runtimes use Metal + /// (`MTL0`) and Vulkan (`Vulkan0`). + static const List _gpuDevicePrefixes = [ + 'mtl', + 'metal', + 'vulkan', + 'cuda', + 'rocm', + 'gpuopencl', + 'opencl', + 'sycl', + ]; +} + +/// Estimated peak memory, in bytes, of an image model whose files total +/// [weightBytes]: the weights plus a quarter for compute buffers, plus +/// 256 MiB for the text encoder, VAE decode and runtime. +/// +/// Measured peaks at 512x512 fit it: SDXS Q8 (651 MB of weights) used 1.06 +/// to 1.55 GB of process memory, including the app, on iPhone, Mac and +/// Android. +int estimateImageGenerationMemoryBytes(int weightBytes) => + weightBytes + weightBytes ~/ 4 + (256 << 20); diff --git a/lib/src/core/image/image_generation_events.dart b/lib/src/core/image/image_generation_events.dart new file mode 100644 index 000000000..9fd1d7c51 --- /dev/null +++ b/lib/src/core/image/image_generation_events.dart @@ -0,0 +1,117 @@ +import '../exceptions.dart'; +import 'generated_image.dart'; + +/// Stage of an image generation. +enum ImageGenerationPhase { + /// The runtime is loading weights it did not load with the model. + loading, + + /// The text encoder is encoding the prompt. + encodingPrompt, + + /// The diffusion model is denoising the latent image. + sampling, + + /// The VAE is decoding latents into pixels. + decoding, +} + +/// Base class for image-generation events. +sealed class ImageGenerationEvent { + /// Creates an image-generation event. + const ImageGenerationEvent(); +} + +/// Progress emitted before the final images are available. +class ImageGenerationProgressEvent extends ImageGenerationEvent { + /// Current phase. + final ImageGenerationPhase phase; + + /// Completed units of the current phase. During + /// [ImageGenerationPhase.sampling] these are sampling steps, and `0` means + /// sampling of [imageIndex] has started. During + /// [ImageGenerationPhase.loading] they are the tensors the runtime reports + /// loading. [ImageGenerationPhase.decoding] starts at `0` of [imageCount] + /// images and counts tiles if the runtime decodes in tiles. + final int step; + + /// Total units of the current phase. + final int steps; + + /// Zero-based index of the image being generated. + final int imageIndex; + + /// Number of images requested. + final int imageCount; + + /// Creates a progress event. + const ImageGenerationProgressEvent({ + required this.phase, + required this.step, + required this.steps, + required this.imageIndex, + required this.imageCount, + }); +} + +/// Final event carrying the generated images. +class ImageGenerationFinalEvent extends ImageGenerationEvent { + /// The generation result. + final ImageGenerationResult result; + + /// Creates a final event. + const ImageGenerationFinalEvent(this.result); +} + +/// Terminal state of an image-generation task. +enum ImageGenerationCompletionState { + /// Generation produced images. + completed, + + /// Generation was cancelled. + cancelled, + + /// Generation failed. + failed, +} + +/// Terminal details of an image-generation task. +class ImageGenerationCompletion { + /// Terminal state. + final ImageGenerationCompletionState state; + + /// Result when [state] is [ImageGenerationCompletionState.completed]. + final ImageGenerationResult? result; + + /// Failure when [state] is [ImageGenerationCompletionState.failed]. + final LlamaException? error; + + const ImageGenerationCompletion._({ + required this.state, + this.result, + this.error, + }); + + /// Creates a successful completion. + factory ImageGenerationCompletion.completed(ImageGenerationResult result) => + ImageGenerationCompletion._( + state: ImageGenerationCompletionState.completed, + result: result, + ); + + /// Creates a cancelled completion. + const factory ImageGenerationCompletion.cancelled() = + _CancelledImageGenerationCompletion; + + /// Creates a failed completion. + factory ImageGenerationCompletion.failed(LlamaException error) => + ImageGenerationCompletion._( + state: ImageGenerationCompletionState.failed, + error: error, + ); +} + +class _CancelledImageGenerationCompletion extends ImageGenerationCompletion { + const _CancelledImageGenerationCompletion() + : super._(state: ImageGenerationCompletionState.cancelled); +} diff --git a/lib/src/core/image/image_generation_model.dart b/lib/src/core/image/image_generation_model.dart new file mode 100644 index 000000000..868412af5 --- /dev/null +++ b/lib/src/core/image/image_generation_model.dart @@ -0,0 +1,170 @@ +/// Local weight files for one image-generation model. +/// +/// Single-file checkpoints set [model]. Split checkpoints set +/// [diffusionModel] and the matching [vae] and text encoders. [taesd] adds +/// the tiny autoencoder, which replaces the VAE decoder for faster, +/// lower-memory decoding at a small quality cost. +class ImageGenerationModelFiles { + /// Single-file checkpoint (`.gguf`, `.safetensors` or `.ckpt`). + final String? model; + + /// Standalone diffusion (UNet) weights of a split checkpoint. + final String? diffusionModel; + + /// Standalone VAE weights. + final String? vae; + + /// Tiny autoencoder (TAESD) weights, such as `madebyollin/taesd`'s + /// `diffusion_pytorch_model.safetensors`. + final String? taesd; + + /// Standalone CLIP-L text encoder. + final String? clipL; + + /// Standalone CLIP-G text encoder. + final String? clipG; + + /// Standalone T5-XXL text encoder. + final String? t5xxl; + + /// Creates a file set. Every path is a local file. + const ImageGenerationModelFiles({ + this.model, + this.diffusionModel, + this.vae, + this.taesd, + this.clipL, + this.clipG, + this.t5xxl, + }); + + /// Every non-null path, keyed by its role, in declaration order. + Map get paths => { + 'model': ?model, + 'diffusionModel': ?diffusionModel, + 'vae': ?vae, + 'taesd': ?taesd, + 'clipL': ?clipL, + 'clipG': ?clipG, + 't5xxl': ?t5xxl, + }; +} + +/// Sampling defaults a model needs when a request leaves them unset. +class ImageGenerationDefaults { + /// Sampling steps. + final int steps; + + /// Classifier-free guidance scale. `1` disables the negative prompt and + /// halves the work per step. + final double guidanceScale; + + /// Creates sampling defaults. The defaults suit undistilled SD 1.x and 2.x + /// checkpoints. + const ImageGenerationDefaults({this.steps = 20, this.guidanceScale = 7.0}); +} + +/// Model family a preset was built for. +enum ImageGenerationModelFamily { + /// SDXS-512, a one-step distilled SD 1.x-size model. + sdxs, + + /// SD-Turbo, an adversarially distilled SD 2.1 model for 1 to 4 steps. + sdTurbo, + + /// Any other checkpoint the runtime accepts. + custom, +} + +/// An image-generation model: its files and the sampling defaults it needs. +/// +/// Use a preset for the validated models, or [ImageGenerationModel.custom] +/// for other SD 1.x and 2.x checkpoints stable-diffusion.cpp can load. +class ImageGenerationModel { + /// Family the preset was built for. + final ImageGenerationModelFamily family; + + /// Local weight files. + final ImageGenerationModelFiles files; + + /// Defaults applied when a request leaves steps or guidance unset. + final ImageGenerationDefaults defaults; + + const ImageGenerationModel._(this.family, this.files, this.defaults); + + /// SDXS-512 from a single-file checkpoint, such as + /// `concedo/sdxs-512-tinySDdistilled-GGUF`'s + /// `sdxs-512-tinySDdistilled_Q8_0.gguf` (651 MB). + /// + /// SDXS is distilled for exactly one step with guidance 1; more steps or a + /// higher guidance scale degrade the image. + factory ImageGenerationModel.sdxs(String modelPath) => ImageGenerationModel._( + ImageGenerationModelFamily.sdxs, + ImageGenerationModelFiles(model: modelPath), + const ImageGenerationDefaults(steps: 1, guidanceScale: 1), + ); + + /// SD-Turbo from a single-file checkpoint, such as + /// `Green-Sky/SD-Turbo-GGUF`'s `sd_turbo-f16-q8_0.gguf` (1.9 GB). + /// + /// Defaults to one step with guidance 1. SD-Turbo also accepts up to four + /// steps (`steps: 4`) for more detail at about four times the sampling + /// time. [taesdPath] decodes with TAESD instead of the full VAE, which is + /// several times faster and needs far less memory on phones. + factory ImageGenerationModel.sdTurbo(String modelPath, {String? taesdPath}) => + ImageGenerationModel._( + ImageGenerationModelFamily.sdTurbo, + ImageGenerationModelFiles(model: modelPath, taesd: taesdPath), + const ImageGenerationDefaults(steps: 1, guidanceScale: 1), + ); + + /// Any other checkpoint, with the sampling [defaults] it needs. + /// + /// Experimental: only SD 1.x and 2.x-family checkpoints are in scope, and + /// only SDXS and SD-Turbo are validated. Larger families that + /// stable-diffusion.cpp supports, such as SDXL or FLUX, may load but are + /// untested and can exceed phone memory. + factory ImageGenerationModel.custom( + ImageGenerationModelFiles files, { + ImageGenerationDefaults defaults = const ImageGenerationDefaults(), + }) => ImageGenerationModel._( + ImageGenerationModelFamily.custom, + files, + defaults, + ); +} + +/// Device an image-generation engine runs on. +enum ImageGenerationDevice { + /// The first GPU the runtime reports (Metal on Apple, Vulkan on the Linux + /// and Windows Vulkan build), otherwise the CPU. + auto, + + /// The CPU. + cpu, + + /// The first GPU the runtime reports. Loading fails with + /// `LlamaUnsupportedException` when there is none, as on Android and the + /// Linux and Windows CPU builds. + gpu, +} + +/// Runtime settings for an image-generation engine. +class ImageGenerationOptions { + /// Device to run on. + final ImageGenerationDevice device; + + /// CPU threads. `0` uses the number of physical cores. + final int threads; + + /// Whether `ImageGenerationEngine.load` refuses a model that its memory + /// estimate says cannot fit the device. See `ImageGenerationEngine.load`. + final bool checkMemory; + + /// Creates runtime settings. + const ImageGenerationOptions({ + this.device = ImageGenerationDevice.auto, + this.threads = 0, + this.checkMemory = true, + }); +} diff --git a/lib/src/core/image/image_generation_progress.dart b/lib/src/core/image/image_generation_progress.dart new file mode 100644 index 000000000..48f56b01f --- /dev/null +++ b/lib/src/core/image/image_generation_progress.dart @@ -0,0 +1,80 @@ +import 'image_generation_events.dart'; + +/// Labels stable-diffusion.cpp progress callbacks with a phase. +/// +/// The runtime reports every kind of progress through one +/// `(step, steps)` callback with no phase: sampling steps, tensors loaded +/// lazily, and VAE tiles. The labels are derived from the call sequence: +/// +/// - Generation starts in [ImageGenerationPhase.encodingPrompt]; the runtime +/// reports nothing while it encodes the prompt. +/// - A callback whose total equals the resolved sampling step count is a +/// sampling step. Each image's pass reports `0/steps` when its first step +/// starts and `k/steps` after step `k`. +/// - When the last image's pass reports `steps/steps`, a +/// [ImageGenerationPhase.decoding] event follows with `0/imageCount`; the +/// runtime reports no decoding progress unless it decodes in tiles. +/// - Any other callback is [ImageGenerationPhase.decoding] once every image +/// is sampled (tiled VAE decode) and [ImageGenerationPhase.loading] before +/// that (lazy tensor loading, which reports tensor counts). +/// +/// The engine loads weights eagerly, so loading callbacks do not occur in +/// practice. A lazily loaded tensor group whose size equals the step count +/// would be mislabelled as sampling. +final class ImageGenerationProgressTracker { + /// Resolved sampling steps per image. + final int steps; + + /// Number of images requested. + final int imageCount; + + int _completedImages = 0; + + /// Creates a tracker for one generation. + ImageGenerationProgressTracker({ + required this.steps, + required this.imageCount, + }); + + /// The event emitted when generation starts. + ImageGenerationProgressEvent start() => + _event(ImageGenerationPhase.encodingPrompt, 0, steps); + + /// The events one native `(step, total)` callback maps to. + List onNativeProgress(int step, int total) { + final allSampled = _completedImages >= imageCount; + if (total != steps || step < 0 || step > steps || allSampled) { + return [ + _event( + allSampled + ? ImageGenerationPhase.decoding + : ImageGenerationPhase.loading, + step, + total, + ), + ]; + } + final events = [_event(ImageGenerationPhase.sampling, step, steps)]; + if (step == steps) { + _completedImages++; + if (_completedImages == imageCount) { + events.add(_event(ImageGenerationPhase.decoding, 0, imageCount)); + } + } + return events; + } + + ImageGenerationProgressEvent _event( + ImageGenerationPhase phase, + int step, + int total, + ) => ImageGenerationProgressEvent( + phase: phase, + step: step, + steps: total, + imageIndex: _completedImages < imageCount + ? _completedImages + : imageCount - 1, + imageCount: imageCount, + ); +} diff --git a/lib/src/core/image/image_generation_request.dart b/lib/src/core/image/image_generation_request.dart new file mode 100644 index 000000000..efdfe2bf7 --- /dev/null +++ b/lib/src/core/image/image_generation_request.dart @@ -0,0 +1,115 @@ +import '../exceptions.dart'; + +/// A request to generate one or more images from a text prompt. +class ImageGenerationRequest { + /// Smallest accepted [width] and [height]. + static const int minDimension = 64; + + /// Largest accepted [width] and [height]. + static const int maxDimension = 2048; + + /// Largest accepted [steps]. + static const int maxSteps = 150; + + /// Largest accepted [guidanceScale]. + static const double maxGuidanceScale = 30; + + /// Largest accepted [count]. + static const int maxCount = 16; + + /// Text prompt. + final String prompt; + + /// Negative prompt. Ignored when the guidance scale is 1, as with the SDXS + /// and SD-Turbo presets. + final String negativePrompt; + + /// Output width in pixels: a multiple of 8 from [minDimension] to + /// [maxDimension]. SD 1.x and 2.x models are trained at 512. The runtime + /// rounds up to a multiple of 64 for these models; `GeneratedImage.width` + /// reports the size produced. + final int width; + + /// Output height in pixels, with the same range and rounding as [width]. + final int height; + + /// Sampling steps from 1 to [maxSteps]. `null` uses the model's default. + final int? steps; + + /// Classifier-free guidance scale from 0 to [maxGuidanceScale]. `null` uses + /// the model's default. + final double? guidanceScale; + + /// Random seed, 0 or greater. `null` picks a random seed; the result + /// reports the seed used either way. + final int? seed; + + /// Number of images, from 1 to [maxCount]. Image `i` uses seed `seed + i`. + final int count; + + /// Creates an image-generation request. + const ImageGenerationRequest({ + required this.prompt, + this.negativePrompt = '', + this.width = 512, + this.height = 512, + this.steps, + this.guidanceScale, + this.seed, + this.count = 1, + }); +} + +/// Throws [LlamaImageGenerationException] naming the first invalid field of +/// [request]. +void validateImageGenerationRequest(ImageGenerationRequest request) { + Never reject(String message, Object? value) => + throw LlamaImageGenerationException(message, value); + + if (request.prompt.trim().isEmpty) { + reject('The image-generation prompt must not be empty.', null); + } + for (final (name, value) in [ + ('width', request.width), + ('height', request.height), + ]) { + if (value < ImageGenerationRequest.minDimension || + value > ImageGenerationRequest.maxDimension || + value % 8 != 0) { + reject( + '$name must be a multiple of 8 from ' + '${ImageGenerationRequest.minDimension} to ' + '${ImageGenerationRequest.maxDimension}.', + value, + ); + } + } + final steps = request.steps; + if (steps != null && (steps < 1 || steps > ImageGenerationRequest.maxSteps)) { + reject( + 'steps must be from 1 to ${ImageGenerationRequest.maxSteps}.', + steps, + ); + } + final guidanceScale = request.guidanceScale; + if (guidanceScale != null && + (!guidanceScale.isFinite || + guidanceScale < 0 || + guidanceScale > ImageGenerationRequest.maxGuidanceScale)) { + reject( + 'guidanceScale must be from 0 to ' + '${ImageGenerationRequest.maxGuidanceScale}.', + guidanceScale, + ); + } + final seed = request.seed; + if (seed != null && seed < 0) { + reject('seed must be 0 or greater.', seed); + } + if (request.count < 1 || request.count > ImageGenerationRequest.maxCount) { + reject( + 'count must be from 1 to ${ImageGenerationRequest.maxCount}.', + request.count, + ); + } +} diff --git a/lib/src/core/image/png_encoder.dart b/lib/src/core/image/png_encoder.dart new file mode 100644 index 000000000..9b2a3c012 --- /dev/null +++ b/lib/src/core/image/png_encoder.dart @@ -0,0 +1,103 @@ +import 'dart:typed_data'; + +import 'package:archive/archive.dart'; + +import '../exceptions.dart'; + +const List _pngSignature = [ + 0x89, + 0x50, + 0x4E, + 0x47, + 0x0D, + 0x0A, + 0x1A, + 0x0A, +]; + +/// Encodes row-major 8-bit grayscale (1), RGB (3) or RGBA (4) [pixels] as a +/// PNG. Throws [LlamaImageGenerationException] when the buffer does not match +/// the dimensions. +Uint8List encodePng({ + required int width, + required int height, + required int channels, + required Uint8List pixels, +}) { + final colorType = switch (channels) { + 1 => 0, + 3 => 2, + 4 => 6, + _ => throw LlamaImageGenerationException( + 'PNG encoding supports 1, 3 or 4 channels.', + channels, + ), + }; + if (width <= 0 || height <= 0) { + throw LlamaImageGenerationException( + 'PNG encoding needs a positive width and height.', + '${width}x$height', + ); + } + final rowBytes = width * channels; + if (pixels.length != rowBytes * height) { + throw LlamaImageGenerationException( + 'Pixel buffer length does not match ${width}x$height with $channels ' + 'channels.', + pixels.length, + ); + } + + // Each scanline starts with filter type 0 (None). + final scanlines = Uint8List((rowBytes + 1) * height); + for (var y = 0; y < height; y++) { + scanlines.setRange( + y * (rowBytes + 1) + 1, + (y + 1) * (rowBytes + 1), + pixels, + y * rowBytes, + ); + } + + final header = ByteData(13) + ..setUint32(0, width) + ..setUint32(4, height) + ..setUint8(8, 8) + ..setUint8(9, colorType); + + final out = BytesBuilder(copy: false)..add(_pngSignature); + _writeChunk(out, 'IHDR', header.buffer.asUint8List()); + _writeChunk(out, 'IDAT', const ZLibEncoder().encodeBytes(scanlines)); + _writeChunk(out, 'IEND', Uint8List(0)); + return out.takeBytes(); +} + +void _writeChunk(BytesBuilder out, String type, Uint8List data) { + final typeBytes = Uint8List.fromList(type.codeUnits); + final crc = _crc32(_crc32(0xFFFFFFFF, typeBytes), data) ^ 0xFFFFFFFF; + out + ..add((ByteData(4)..setUint32(0, data.length)).buffer.asUint8List()) + ..add(typeBytes) + ..add(data) + ..add((ByteData(4)..setUint32(0, crc)).buffer.asUint8List()); +} + +final Uint32List _crcTable = () { + final table = Uint32List(256); + for (var n = 0; n < 256; n++) { + var c = n; + for (var k = 0; k < 8; k++) { + c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; + } + table[n] = c; + } + return table; +}(); + +int _crc32(int crc, Uint8List bytes) { + var c = crc; + for (final byte in bytes) { + c = _crcTable[(c ^ byte) & 0xFF] ^ (c >> 8); + } + return c; +} diff --git a/skills/llamadart-flutter-app/SKILL.md b/skills/llamadart-flutter-app/SKILL.md index 1c84ceb77..824e25afe 100644 --- a/skills/llamadart-flutter-app/SKILL.md +++ b/skills/llamadart-flutter-app/SKILL.md @@ -87,6 +87,9 @@ or shipping runtimes the app does not use. otherwise ignored with a warning (only the experimental opt-in `stable_diffusion` there still applies); the tag, repository, path and backend user-defines do not change SwiftPM binaries either. +- Image generation (`ImageGenerationEngine`) needs `stable_diffusion` added + to `llamadart_native_runtimes`; it is never bundled by default. Details are + in the llamadart-image-generation skill. - Native runtimes are downloaded by the build hook on the first `flutter run` or `flutter build` for each target; no C++ toolchain is needed. Expect a slower first build. After changing any diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md new file mode 100644 index 000000000..78e3ae73d --- /dev/null +++ b/skills/llamadart-image-generation/SKILL.md @@ -0,0 +1,186 @@ +--- +name: llamadart-image-generation +description: >- + Use when generating images from text prompts in a llamadart app with the + experimental ImageGenerationEngine: opting into the stable_diffusion + runtime, loading SDXS or SD-Turbo (with TAESD), showing progress, cancelling, + saving PNGs, or handling unsupported platforms, memory refusals and + concurrent-generation errors. +--- + +# Image generation with llamadart + +## Guidelines + +- Image generation is the experimental `ImageGenerationEngine`, separate from + `LlamaEngine`. It runs stable-diffusion.cpp through the opt-in + `stable_diffusion` native runtime. Text-to-image only: no image-to-image, + inpainting, LoRA or ControlNet. +- The app must bundle the runtime (about 40 to 70 MB per target); it is never + included by default or by `all`. In the app's `pubspec.yaml`: + + ```yaml + hooks: + user_defines: + llamadart: + llamadart_native_runtimes: [llama_cpp, stable_diffusion] + ``` + + Keep `litert_lm` in the list if the app also loads `.litertlm` models. Run + `flutter clean` once after changing it. Linux and Windows bundle the Vulkan + build when `llamadart_native_backends` selects Vulkan (the default); + `llamadart_stable_diffusion_backends: [cpu]` picks the CPU build. +- Platforms: Android arm64 (CPU only; Armv8.2 dot-product and fp16), iOS 16.4+ + and macOS 13.3+ (Metal), Linux arm64/x64 and Windows x64 (CPU or Vulkan; x64 + CPUs need AVX2, FMA, F16C and BMI2). Web, Android x64, the iOS x86_64 + simulator and Windows arm64 are unsupported. Windows needs the Visual C++ + 2015-2022 x64 runtime. +- Gate UI on `ImageGenerationEngine.runtimeCapabilities()` (synchronous; no + model needed): show `unsupportedReason` when `isSupported` is false. + `ImageGenerationEngine.load` throws `LlamaUnsupportedException` in the same + cases. +- Models (local files; download with `DefaultModelDownloadManager` or + `ModelSource` first): + - `ImageGenerationModel.sdxs(path)`: `concedo/sdxs-512-tinySDdistilled-GGUF` + `sdxs-512-tinySDdistilled_Q8_0.gguf` (651 MB). Exactly 1 step at guidance + 1, which are its defaults; do not raise them. + - `ImageGenerationModel.sdTurbo(path, taesdPath: ...)`: + `Green-Sky/SD-Turbo-GGUF` `sd_turbo-f16-q8_0.gguf` (1.9 GB). Defaults to 1 + step at guidance 1; up to 4 steps add detail. For TAESD use + `madebyollin/taesd` `diffusion_pytorch_model.safetensors`, not + `taesd_decoder.safetensors`; prefer it on phones. + - `ImageGenerationModel.custom(ImageGenerationModelFiles(...), defaults: + ImageGenerationDefaults(steps:, guidanceScale:))` for other SD 1.x/2.x + checkpoints; experimental and unvalidated. +- `load` checks every file exists and, unless + `ImageGenerationOptions(checkMemory: false)`, refuses a model whose estimate + (file sizes plus a quarter plus 256 MiB) exceeds the device figure + (`MemAvailable` on Android/Linux, the app's limit on iOS, physical memory on + macOS; Windows is not checked) with `LlamaModelException`. SD-Turbo does not + fit 6 GB Android phones; offer SDXS there. +- `ImageGenerationOptions(device: auto | cpu | gpu, threads: 0)`. `gpu` + without a GPU (Android, CPU builds) throws `LlamaUnsupportedException`. +- `load` loads weights eagerly; on Apple the first generation is still slow + (about 19 s on iPhone) while Metal compiles shaders. Show progress. +- `engine.generate(request)` returns an `ImageGenerationTask` synchronously; + invalid requests throw `LlamaImageGenerationException` first. Width and + height are multiples of 8 from 64 to 2048 (512 is native; 256 is fine for + SDXS and SD-Turbo; the runtime rounds up to 64, so read the size from + `GeneratedImage`), steps 1 to 150, guidance 0 to 30, count 1 to 16. + `seed: null` is random; `result.seed` reports it, image `i` used + `seed + i`, and the same seed reproduces the same pixels. +- `task.events` (single subscription): `ImageGenerationProgressEvent` + (`phase`: `encodingPrompt`, `sampling`, `decoding`, rarely `loading`; + `step`, `steps`, `imageIndex`, `imageCount`), then one + `ImageGenerationFinalEvent(result)`. Failures arrive as a stream error and + as `ImageGenerationCompletionState.failed` on `task.done`. +- `engine.generateImage(request)` is the one-call form returning + `ImageGenerationResult` (`images`, `seed`, `elapsed`). +- `GeneratedImage` has `width`, `height`, `channels` (3) and row-major RGB + `pixels`; `toPng()` returns PNG bytes (for `Image.memory` or a file). +- One generation or model load at a time per process (stable-diffusion.cpp's + progress callback is global): a second one throws `LlamaStateException`, + even on another engine. Await `task.done` before the next request; disable + the Generate button while one runs. Do not generate from several isolates. +- `task.cancel()` stops before the next sampling step; `done` reports + `cancelled` and the stream closes without a final event. `dispose()` cancels + a running task, waits, then frees the model. +- 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`. + +## Examples + +Load SDXS, stream progress and save a PNG: + +```dart +import 'dart:io'; + +import 'package:llamadart/llamadart.dart'; + +Future generateFox(String sdxsPath, String outputPath) async { + final ImageGenerationCapabilities runtime = + ImageGenerationEngine.runtimeCapabilities(); + if (!runtime.isSupported) { + throw LlamaUnsupportedException(runtime.unsupportedReason!); + } + + final ImageGenerationEngine engine = await ImageGenerationEngine.load( + ImageGenerationModel.sdxs(sdxsPath), + ); + try { + final ImageGenerationTask task = engine.generate( + const ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + width: 512, + height: 512, + seed: 42, + ), + ); + await for (final ImageGenerationEvent event in task.events) { + switch (event) { + case ImageGenerationProgressEvent( + :final ImageGenerationPhase phase, + :final int step, + :final int steps, + ): + print('${phase.name} $step/$steps'); + case ImageGenerationFinalEvent(:final ImageGenerationResult result): + await File(outputPath).writeAsBytes(result.images.first.toPng()); + print('Seed ${result.seed} in ${result.elapsed.inMilliseconds} ms'); + } + } + } on LlamaInferenceException catch (error) { + print('Generation failed, engine still usable: ${error.message}'); + } finally { + await engine.dispose(); + } +} +``` + +SD-Turbo with TAESD, downloaded through the model cache, with cancellation: + +```dart +import 'dart:typed_data'; + +import 'package:llamadart/llamadart.dart'; + +Future generateWithCancel(Future userCancelled) async { + final DefaultModelDownloadManager downloads = DefaultModelDownloadManager(); + final ModelCacheEntry model = await downloads.ensureModel( + ModelSource.parse('hf://Green-Sky/SD-Turbo-GGUF/sd_turbo-f16-q8_0.gguf'), + ); + final ModelCacheEntry taesd = await downloads.ensureModel( + ModelSource.parse( + 'hf://madebyollin/taesd/diffusion_pytorch_model.safetensors', + ), + ); + + final ImageGenerationEngine engine; + try { + engine = await ImageGenerationEngine.load( + ImageGenerationModel.sdTurbo(model.filePath, taesdPath: taesd.filePath), + ); + } on LlamaModelException catch (error) { + print('Model refused or failed to load: ${error.message}'); + return null; + } + + try { + final ImageGenerationTask task = engine.generate( + const ImageGenerationRequest(prompt: 'a lighthouse at dusk', steps: 4), + ); + userCancelled.then((_) => task.cancel()); + final ImageGenerationCompletion completion = await task.done; + return switch (completion.state) { + ImageGenerationCompletionState.completed => + completion.result!.images.first.toPng(), + ImageGenerationCompletionState.cancelled => null, + ImageGenerationCompletionState.failed => throw completion.error!, + }; + } finally { + await engine.dispose(); + } +} +``` 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 new file mode 100644 index 000000000..e40108436 --- /dev/null +++ b/test/unit/backends/stable_diffusion/stable_diffusion_image_worker_test.dart @@ -0,0 +1,38 @@ +@TestOn('vm') +library; + +import 'package:test/test.dart'; + +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_image_worker.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart'; +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/image_generation_driver.dart'; + +// Real generation needs the opt-in runtime, which the root package does not +// bundle; example/basic_app/test/image_generation_e2e_test.dart covers it. +void main() { + test( + 'a worker whose runtime is missing fails its start and exits', + () async { + await expectLater( + StableDiffusionImageWorker.start( + const ImageGenerationSessionConfig( + files: {'model': '/models/sdxs.gguf'}, + backend: null, + threads: 0, + ), + ), + throwsA( + isA().having( + (error) => '${error.details}', + 'details', + contains('stable_diffusion'), + ), + ), + ); + }, + skip: probeStableDiffusionRuntime().isAvailable + ? 'the stable_diffusion runtime is bundled here' + : false, + ); +} diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart new file mode 100644 index 000000000..b80acc3c3 --- /dev/null +++ b/test/unit/backends/stable_diffusion/stable_diffusion_memory_test.dart @@ -0,0 +1,92 @@ +@TestOn('vm') +library; + +import 'dart:ffi'; +import 'dart:io'; + +import 'package:test/test.dart'; + +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_memory.dart'; + +const _memInfo = ''' +MemTotal: 5750000 kB +MemFree: 300000 kB +MemAvailable: 2097152 kB +Buffers: 10000 kB +'''; + +void main() { + group('parseMemAvailableBytes', () { + test('reads MemAvailable in bytes', () { + expect(parseMemAvailableBytes(_memInfo), 2097152 * 1024); + }); + + test('is null without a MemAvailable line', () { + expect(parseMemAvailableBytes('MemTotal: 5750000 kB\n'), isNull); + expect(parseMemAvailableBytes(''), isNull); + }); + }); + + group('readStableDiffusionMemoryBudget', () { + ({int bytes, String source})? read( + Abi abi, { + String? memInfo, + int? ios, + int? macos, + }) => readStableDiffusionMemoryBudget( + abi: abi, + readMemInfo: () => memInfo, + iosAvailableMemory: () => ios, + macosPhysicalMemory: () => macos, + ); + + test('uses MemAvailable on Android and Linux', () { + for (final abi in [Abi.androidArm64, Abi.linuxX64, Abi.linuxArm64]) { + expect(read(abi, memInfo: _memInfo, ios: 1, macos: 1), ( + bytes: 2 << 30, + source: 'MemAvailable in /proc/meminfo', + )); + expect(read(abi), isNull, reason: 'unreadable /proc/meminfo'); + } + }); + + test("uses the app's remaining memory limit on iOS", () { + expect(read(Abi.iosArm64, memInfo: _memInfo, ios: 3 << 30, macos: 1), ( + bytes: 3 << 30, + source: "the app's remaining iOS memory limit", + )); + expect(read(Abi.iosArm64, ios: 0), isNull); + }); + + test('uses physical memory on macOS', () { + expect(read(Abi.macosArm64, ios: 1, macos: 64 << 30), ( + bytes: 64 << 30, + source: 'physical memory', + )); + }); + + test('reports nothing on Windows', () { + expect(read(Abi.windowsX64, memInfo: _memInfo, ios: 1, macos: 1), isNull); + }); + + test('reads the host', () { + final budget = readStableDiffusionMemoryBudget(); + if (Platform.isMacOS || Platform.isLinux) { + expect(budget!.bytes, greaterThan(1 << 30)); + } + }); + }); + + group('stableDiffusionFileSize', () { + test('sizes a file and ignores directories and missing paths', () async { + final directory = await Directory.systemTemp.createTemp('llamadart-sd-'); + addTearDown(() => directory.delete(recursive: true)); + final file = File('${directory.path}/taesd.safetensors') + ..writeAsBytesSync(List.filled(42, 1)); + + expect(stableDiffusionFileSize(file.path), 42); + expect(stableDiffusionFileSize(directory.path), isNull); + expect(stableDiffusionFileSize('${file.path}.missing'), isNull); + }); + }); +} 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 0319e3ef4..4d6c59287 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 @@ -2,6 +2,7 @@ library; import 'dart:ffi'; +import 'dart:io'; import 'package:test/test.dart'; @@ -10,6 +11,7 @@ import 'package:llamadart/src/core/exceptions.dart'; const _dotProductCpuInfo = 'Features\t: fp asimd atomics fphp asimdhp asimddp\n'; +const _haswellCpuInfo = 'flags\t\t: fpu sse4_2 avx f16c fma avx2 bmi2\n'; void main() { group('probeStableDiffusionRuntime', () { @@ -79,19 +81,88 @@ void main() { expect(api.calls, greaterThan(0)); }); - test('desktop probes ignore /proc/cpuinfo', () { + test('Arm desktop and Apple probes check no CPU features', () { + for (final abi in [Abi.linuxArm64, Abi.macosArm64, Abi.macosX64]) { + final status = probeStableDiffusionRuntime( + abi: abi, + readCpuInfo: () => fail('cpuinfo is not read on $abi'), + windowsHasAvx2: () => fail('Windows is not queried on $abi'), + api: _FakeApi(), + ); + + expect(status.isAvailable, isTrue, reason: '$abi'); + } + }); + + test('Linux x64 without AVX2, FMA, F16C or BMI2 never loads the ' + 'library', () { + for (final cpuInfo in [ + 'flags\t\t: fpu sse4_2 avx popcnt\n', + '$_haswellCpuInfo${'flags\t\t: fpu sse4_2 avx avx2\n'}', + null, + ]) { + final api = _FakeApi(); + final status = probeStableDiffusionRuntime( + abi: Abi.linuxX64, + readCpuInfo: () => cpuInfo, + api: api, + ); + + expect(api.calls, 0, reason: cpuInfo); + expect( + status.unavailableReason?.message, + allOf( + contains('linux-x64'), + contains('AVX2, FMA, F16C, BMI2'), + cpuInfo == null + ? contains('could not be read') + : contains('does not report them'), + ), + reason: cpuInfo, + ); + } + }); + + test('Linux x64 with the required features on every core loads the ' + 'library', () { + final api = _FakeApi(); final status = probeStableDiffusionRuntime( - abi: Abi.linuxArm64, - readCpuInfo: () => fail('cpuinfo is only read on Android'), - api: _FakeApi(), + abi: Abi.linuxX64, + readCpuInfo: () => _haswellCpuInfo * 8, + api: api, ); expect(status.isAvailable, isTrue); + expect(api.calls, greaterThan(0)); + }); + + test('Windows x64 requires AVX2 before loading the library', () { + final api = _FakeApi(); + final rejected = probeStableDiffusionRuntime( + abi: Abi.windowsX64, + readCpuInfo: () => fail('cpuinfo is not read on Windows'), + windowsHasAvx2: () => false, + api: api, + ); + + expect(api.calls, 0); + expect( + rejected.unavailableReason?.message, + allOf(contains('windows-x64'), contains('does not report AVX2')), + ); + + final accepted = probeStableDiffusionRuntime( + abi: Abi.windowsX64, + windowsHasAvx2: () => true, + api: api, + ); + expect(accepted.isAvailable, isTrue); }); test('a missing native asset reports how to opt in', () { final status = probeStableDiffusionRuntime( abi: Abi.linuxX64, + readCpuInfo: () => _haswellCpuInfo, api: _FakeApi( error: ArgumentError( "Couldn't resolve native function 'sd_version' in " @@ -134,7 +205,7 @@ void main() { expect(message, contains('Vulkan variant')); expect(message, contains('libvulkan.so.1')); - expect(message, contains('select the CPU backend')); + expect(message, contains('llamadart_stable_diffusion_backends to [cpu]')); expect(message, isNot(contains('/app/lib'))); }); @@ -177,6 +248,87 @@ void main() { expect(message, contains('does not export the stable-diffusion.h API')); }); + group('Windows error 126', () { + final error126 = ArgumentError( + "Couldn't resolve native function 'sd_version' in " + "'package:llamadart/stable_diffusion' : Failed to load dynamic " + "library 'stable-diffusion.dll': The specified module could not be " + 'found.\r\n (error code: 126).\n', + ); + + String messageWithMissing(Set missing) { + final checked = []; + final message = stableDiffusionLoadFailure( + platform: 'windows-x64', + error: error126, + missingWindowsLibraries: (names) { + checked.addAll(names); + return [ + for (final name in names) + if (missing.contains(name)) name, + ]; + }, + ).message; + expect(checked, isNotEmpty); + return message; + } + + test('names a missing Visual C++ runtime before the Vulkan loader', () { + final message = messageWithMissing({'msvcp140.dll', 'vulkan-1.dll'}); + + expect(message, contains('could not be loaded on windows-x64')); + expect(message, contains('Visual C++ 2015-2022 Redistributable')); + expect(message, contains('msvcp140.dll could not be loaded')); + expect(message, isNot(contains('vulkan-1.dll'))); + expect(message, isNot(contains('..'))); + }); + + test('names the Vulkan loader when the runtime is present', () { + final message = messageWithMissing({'vulkan-1.dll'}); + + expect(message, contains('vulkan-1.dll could not be loaded')); + expect( + message, + contains('llamadart_stable_diffusion_backends to [cpu]'), + ); + expect(message, isNot(contains('Visual C++'))); + expect(message, isNot(contains('..'))); + }); + + test( + 'the default check probes every Visual C++ DLL the runtime imports', + () { + // Off Windows none of these load, so the real check must report all + // of them: this pins the list against stable-diffusion.dll's PE + // imports (MSVCP140, MSVCP140_CODECVT_IDS, VCRUNTIME140, + // VCRUNTIME140_1). + final message = stableDiffusionLoadFailure( + platform: 'windows-x64', + error: error126, + ).message; + + expect( + message, + contains( + 'msvcp140.dll, msvcp140_codecvt_ids.dll, vcruntime140.dll, ' + 'vcruntime140_1.dll could not be loaded', + ), + ); + expect(message, contains('could not be found. It requires')); + }, + skip: Platform.isWindows + ? 'the Visual C++ runtime loads on Windows hosts' + : false, + ); + + test('says neither dependency is missing when both load', () { + final message = messageWithMissing(const {}); + + expect(message, contains('does not name the missing dependency')); + expect(message, isNot(contains('install'))); + }); + }); + test('keeps the first line of any other loader failure', () { final message = messageFor('dlopen failed: bad ELF magic\nsecond line'); diff --git a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_status_test.dart b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_status_test.dart index 58097df8e..4e7f7104f 100644 --- a/test/unit/backends/stable_diffusion/stable_diffusion_runtime_status_test.dart +++ b/test/unit/backends/stable_diffusion/stable_diffusion_runtime_status_test.dart @@ -103,4 +103,41 @@ void main() { ); }); }); + + group('cpuInfoReportsRequiredX86Features', () { + const haswellCore = + 'flags\t\t: fpu sse4_2 avx f16c fma bmi1 avx2 bmi2 popcnt\n'; + const sandyBridgeCore = 'flags\t\t: fpu sse4_2 avx popcnt\n'; + + test('accepts cores that all report AVX2, FMA, F16C and BMI2', () { + expect(cpuInfoReportsRequiredX86Features(haswellCore * 4), isTrue); + }); + + test('rejects a core without AVX2, even beside cores with it', () { + expect(cpuInfoReportsRequiredX86Features(sandyBridgeCore), isFalse); + expect( + cpuInfoReportsRequiredX86Features(haswellCore + sandyBridgeCore), + isFalse, + ); + }); + + test('rejects AVX2 without FMA or F16C', () { + expect( + cpuInfoReportsRequiredX86Features('flags\t: avx avx2 bmi2 f16c\n'), + isFalse, + ); + expect( + cpuInfoReportsRequiredX86Features('flags\t: avx avx2 bmi2 fma\n'), + isFalse, + ); + }); + + test('rejects input with no flags line', () { + expect(cpuInfoReportsRequiredX86Features(''), isFalse); + expect( + cpuInfoReportsRequiredX86Features('Features\t: avx2 fma f16c bmi2\n'), + isFalse, + ); + }); + }); } diff --git a/test/unit/core/exceptions_test.dart b/test/unit/core/exceptions_test.dart index f28447736..4aa5966ae 100644 --- a/test/unit/core/exceptions_test.dart +++ b/test/unit/core/exceptions_test.dart @@ -69,5 +69,12 @@ void main() { expect(ex.details, 'plan'); expect(ex.toString(), 'LlamaException: Too many options (plan)'); }); + + test('LlamaImageGenerationException properties', () { + final ex = LlamaImageGenerationException('width must be 64..2048', 7); + expect(ex.message, 'width must be 64..2048'); + expect(ex.details, 7); + expect(ex.toString(), 'LlamaException: width must be 64..2048 (7)'); + }); }); } diff --git a/test/unit/core/image/generated_image_test.dart b/test/unit/core/image/generated_image_test.dart new file mode 100644 index 000000000..51785df21 --- /dev/null +++ b/test/unit/core/image/generated_image_test.dart @@ -0,0 +1,34 @@ +import 'dart:typed_data'; + +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/generated_image.dart'; + +void main() { + test('toPng encodes the pixels at the image dimensions', () { + final image = GeneratedImage( + width: 3, + height: 2, + channels: 3, + pixels: Uint8List(18), + ); + + final png = image.toPng(); + + final header = ByteData.sublistView(png, 16, 24); + expect(header.getUint32(0), 3); + expect(header.getUint32(4), 2); + }); + + test('toPng rejects pixels that do not match the dimensions', () { + final image = GeneratedImage( + width: 3, + height: 2, + channels: 3, + pixels: Uint8List(17), + ); + + expect(image.toPng, throwsA(isA())); + }); +} diff --git a/test/unit/core/image/image_generation_driver_io_test.dart b/test/unit/core/image/image_generation_driver_io_test.dart new file mode 100644 index 000000000..dcf3508ed --- /dev/null +++ b/test/unit/core/image/image_generation_driver_io_test.dart @@ -0,0 +1,40 @@ +@TestOn('vm') +library; + +import 'dart:io'; + +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/image/image_generation_driver_io.dart'; + +void main() { + test('sizes regular files only', () async { + final directory = await Directory.systemTemp.createTemp('llamadart-img-'); + addTearDown(() => directory.delete(recursive: true)); + final file = File('${directory.path}/model.gguf') + ..writeAsBytesSync(List.filled(1234, 0)); + final driver = createImageGenerationDriver(); + + expect(driver.fileSize(file.path), 1234); + expect(driver.fileSize(directory.path), isNull); + expect(driver.fileSize('${directory.path}/missing.gguf'), isNull); + }); + + test('probes the host runtime, which the root package does not bundle', () { + final status = createImageGenerationDriver().probe(); + + expect(status.isAvailable, isFalse); + expect(status.unavailableReason?.message, contains('stable_diffusion')); + }); + + test('reports a memory budget on macOS and Linux hosts', () { + final budget = createImageGenerationDriver().memoryBudget(); + + if (Platform.isMacOS || Platform.isLinux) { + expect(budget, isNotNull); + expect(budget!.bytes, greaterThan(0)); + } else if (Platform.isWindows) { + expect(budget, isNull); + } + }); +} diff --git a/test/unit/core/image/image_generation_driver_stub_test.dart b/test/unit/core/image/image_generation_driver_stub_test.dart new file mode 100644 index 000000000..f28abc4df --- /dev/null +++ b/test/unit/core/image/image_generation_driver_stub_test.dart @@ -0,0 +1,31 @@ +import 'package:test/test.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_stub.dart'; + +void main() { + test('reports the runtime unavailable and never starts', () async { + final driver = createImageGenerationDriver(); + + expect(driver.probe().isAvailable, isFalse); + expect(driver.fileSize('/models/sdxs.gguf'), isNull); + expect(driver.memoryBudget(), isNull); + await expectLater( + driver.start( + const ImageGenerationSessionConfig( + files: {'model': '/models/sdxs.gguf'}, + backend: null, + threads: 0, + ), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('not available on the web'), + ), + ), + ); + }); +} diff --git a/test/unit/core/image/image_generation_engine_test.dart b/test/unit/core/image/image_generation_engine_test.dart new file mode 100644 index 000000000..9b3a0ae87 --- /dev/null +++ b/test/unit/core/image/image_generation_engine_test.dart @@ -0,0 +1,718 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:test/test.dart'; + +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart/src/backends/stable_diffusion/stable_diffusion_runtime_status.dart'; +import 'package:llamadart/src/core/image/image_generation_driver.dart'; +import 'package:llamadart/src/core/image/image_generation_engine.dart'; + +const _model = '/models/sdxs.gguf'; +const _taesd = '/models/taesd.safetensors'; +const _gib = 1 << 30; + +void main() { + late _FakeDriver driver; + final engines = []; + + Future load( + ImageGenerationModel model, { + ImageGenerationOptions options = const ImageGenerationOptions(), + }) async { + final engine = await ImageGenerationEngine.load(model, options: options); + engines.add(engine); + return engine; + } + + setUp(() { + driver = _FakeDriver(); + debugImageGenerationDriverOverride = driver; + }); + + tearDown(() async { + for (final engine in engines) { + await engine.dispose(); + } + engines.clear(); + debugImageGenerationDriverOverride = null; + }); + + group('runtimeCapabilities', () { + test('reports the devices and the device auto would pick', () { + final capabilities = ImageGenerationEngine.runtimeCapabilities(); + + expect(capabilities.isSupported, isTrue); + expect(capabilities.deviceNames, ['MTL0', 'BLAS', 'CPU']); + expect(capabilities.backendName, 'MTL0'); + expect(capabilities.runtimeVersion, 'master-929'); + expect(capabilities.modelVersion, isNull); + expect(capabilities.maxConcurrentTasks, 1); + }); + + test('reports why the runtime is unavailable', () { + driver.status = StableDiffusionRuntimeStatus.unavailable( + LlamaUnsupportedException('stable_diffusion runtime is not bundled'), + ); + + final capabilities = ImageGenerationEngine.runtimeCapabilities(); + + expect(capabilities.isSupported, isFalse); + expect(capabilities.unsupportedReason, contains('not bundled')); + expect(capabilities.deviceNames, isEmpty); + }); + }); + + group('load', () { + test('throws the probe reason and loads nothing when the runtime is ' + 'unavailable', () async { + driver.status = StableDiffusionRuntimeStatus.unavailable( + LlamaUnsupportedException('not published for android-x64'), + ); + + await expectLater( + load(ImageGenerationModel.sdxs(_model)), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'not published for android-x64', + ), + ), + ); + expect(driver.started, isEmpty); + }); + + test('passes every file and the device choice to the runtime', () async { + final engine = await load( + ImageGenerationModel.sdTurbo(_model, taesdPath: _taesd), + options: const ImageGenerationOptions( + device: ImageGenerationDevice.cpu, + threads: 4, + ), + ); + + final config = driver.started.single; + expect(config.files, {'model': _model, 'taesd': _taesd}); + expect(config.backend, 'cpu'); + expect(config.threads, 4); + expect(engine.capabilities.backendName, 'CPU'); + expect(engine.capabilities.modelVersion, 'SD 2.x'); + expect(engine.capabilities.deviceNames, ['MTL0', 'BLAS', 'CPU']); + expect(engine.capabilities.supportsCancellation, isTrue); + }); + + test('auto leaves the device to the runtime and reports its GPU', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + + expect(driver.started.single.backend, isNull); + expect(engine.capabilities.backendName, 'MTL0'); + }); + + test('gpu selects the first GPU the runtime reports', () async { + driver.status = _available('Vulkan0\tAMD Radeon\nCPU\tHost\n'); + + final engine = await load( + ImageGenerationModel.sdxs(_model), + options: const ImageGenerationOptions( + device: ImageGenerationDevice.gpu, + ), + ); + + expect(driver.started.single.backend, 'gpu'); + expect(engine.capabilities.backendName, 'Vulkan0'); + }); + + test('gpu without a GPU device throws LlamaUnsupportedException', () async { + driver.status = _available('CPU\tCortex-A78\n'); + + await expectLater( + load( + ImageGenerationModel.sdxs(_model), + options: const ImageGenerationOptions( + device: ImageGenerationDevice.gpu, + ), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('ImageGenerationDevice.gpu needs a GPU'), + contains('reports only CPU'), + contains('llamadart_stable_diffusion_backends'), + ), + ), + ), + ); + expect(driver.started, isEmpty); + + final engine = await load(ImageGenerationModel.sdxs(_model)); + expect(engine.capabilities.backendName, 'CPU'); + }); + + test('a missing file throws LlamaModelException naming its role', () async { + driver.sizes.remove(_taesd); + + await expectLater( + load(ImageGenerationModel.sdTurbo(_model, taesdPath: _taesd)), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf(contains('taesd'), contains(_taesd)), + ), + ), + ); + await expectLater( + load(ImageGenerationModel.sdxs(' ')), + throwsA(isA()), + ); + expect(driver.started, isEmpty); + }); + + test('a file set without model or diffusionModel is rejected', () async { + await expectLater( + load( + ImageGenerationModel.custom( + const ImageGenerationModelFiles(vae: '/models/vae.safetensors'), + ), + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('model or diffusionModel'), + ), + ), + ); + }); + + test('negative threads are rejected', () async { + await expectLater( + load( + ImageGenerationModel.sdxs(_model), + options: const ImageGenerationOptions(threads: -1), + ), + throwsA(isA()), + ); + }); + + test( + 'a load failure propagates and frees the one-operation slot', + () async { + driver.startError = LlamaModelException('not an image model'); + + await expectLater( + load(ImageGenerationModel.sdxs(_model)), + throwsA(isA()), + ); + + driver.startError = null; + await load(ImageGenerationModel.sdxs(_model)); + }, + ); + }); + + group('memory preflight', () { + test('refuses a model whose estimate exceeds the budget', () async { + driver.sizes[_model] = 2 * _gib; + driver.budget = ( + bytes: 2 * _gib, + source: 'MemAvailable in /proc/meminfo', + ); + + await expectLater( + load(ImageGenerationModel.sdxs(_model)), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('about 2.75 GiB'), + contains('2.00 GiB of weights'), + contains('only 2.00 GiB is available'), + contains('MemAvailable in /proc/meminfo'), + contains('checkMemory'), + ), + ), + ), + ); + expect(driver.started, isEmpty); + }); + + test('counts every file toward the estimate', () async { + driver.sizes[_model] = _gib; + driver.sizes[_taesd] = _gib; + final required = estimateImageGenerationMemoryBytes(2 * _gib); + driver.budget = (bytes: required - 1, source: 'physical memory'); + + await expectLater( + load(ImageGenerationModel.sdTurbo(_model, taesdPath: _taesd)), + throwsA(isA()), + ); + + driver.budget = (bytes: required, source: 'physical memory'); + await load(ImageGenerationModel.sdTurbo(_model, taesdPath: _taesd)); + }); + + test('is skipped without a budget or when checkMemory is false', () async { + driver.sizes[_model] = 64 * _gib; + + await load(ImageGenerationModel.sdxs(_model)); + + driver.budget = (bytes: _gib, source: 'physical memory'); + await load( + ImageGenerationModel.sdxs(_model), + options: const ImageGenerationOptions(checkMemory: false), + ); + expect(driver.started, hasLength(2)); + }); + + test('the estimate adds a quarter and 256 MiB to the weights', () { + expect(estimateImageGenerationMemoryBytes(0), 256 << 20); + expect( + estimateImageGenerationMemoryBytes(4 * _gib), + 5 * _gib + (256 << 20), + ); + }); + }); + + group('generate', () { + test('rejects invalid requests before starting', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + + for (final request in [ + const ImageGenerationRequest(prompt: ' '), + const ImageGenerationRequest(prompt: 'a', width: 500), + const ImageGenerationRequest(prompt: 'a', height: 56), + const ImageGenerationRequest(prompt: 'a', width: 2056), + const ImageGenerationRequest(prompt: 'a', steps: 0), + const ImageGenerationRequest(prompt: 'a', steps: 151), + const ImageGenerationRequest(prompt: 'a', guidanceScale: -1), + const ImageGenerationRequest(prompt: 'a', guidanceScale: double.nan), + const ImageGenerationRequest(prompt: 'a', seed: -1), + const ImageGenerationRequest(prompt: 'a', count: 0), + const ImageGenerationRequest(prompt: 'a', count: 17), + ]) { + expect( + () => engine.generate(request), + throwsA(isA()), + ); + } + expect(driver.session.requests, isEmpty); + + await engine.generate(const ImageGenerationRequest(prompt: 'a')).done; + }); + + test('rejects invalid custom model defaults before starting', () async { + for (final defaults in const [ + ImageGenerationDefaults(steps: 0), + ImageGenerationDefaults(steps: -3), + ImageGenerationDefaults(steps: 1000), + ImageGenerationDefaults(guidanceScale: double.nan), + ImageGenerationDefaults(guidanceScale: -1), + ]) { + final engine = await load( + ImageGenerationModel.custom( + const ImageGenerationModelFiles(model: _model), + defaults: defaults, + ), + ); + expect( + () => engine.generate(const ImageGenerationRequest(prompt: 'a')), + throwsA(isA()), + reason: 'steps ${defaults.steps}, guidance ${defaults.guidanceScale}', + ); + expect(driver.session.requests, isEmpty); + + // A valid request value still overrides an invalid default, and the + // rejection above released the operation lock. + await engine + .generate( + const ImageGenerationRequest( + prompt: 'a', + steps: 2, + guidanceScale: 1, + ), + ) + .done; + expect(driver.session.requests.single.steps, 2); + await engine.dispose(); + driver = _FakeDriver(); + debugImageGenerationDriverOverride = driver; + } + }); + + test('fills unset steps and guidance from the model defaults', () async { + final sdxs = await load(ImageGenerationModel.sdxs(_model)); + await sdxs.generate(const ImageGenerationRequest(prompt: 'a')).done; + expect(driver.session.requests.last.steps, 1); + expect(driver.session.requests.last.guidanceScale, 1); + + await sdxs + .generate( + const ImageGenerationRequest( + prompt: 'a', + steps: 3, + guidanceScale: 2.5, + ), + ) + .done; + expect(driver.session.requests.last.steps, 3); + expect(driver.session.requests.last.guidanceScale, 2.5); + + final custom = await load( + ImageGenerationModel.custom( + const ImageGenerationModelFiles(model: _model), + ), + ); + await custom.generate(const ImageGenerationRequest(prompt: 'a')).done; + expect(driver.session.requests.last.steps, 20); + expect(driver.session.requests.last.guidanceScale, 7); + }); + + test('reports the seed it used', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + + final fixed = await engine.generateImage( + const ImageGenerationRequest(prompt: 'a', seed: 42), + ); + expect(fixed.seed, 42); + expect(driver.session.requests.last.seed, 42); + + final random = await engine.generateImage( + const ImageGenerationRequest(prompt: 'a'), + ); + expect(random.seed, driver.session.requests.last.seed); + expect(random.seed, greaterThanOrEqualTo(0)); + }); + + test('emits phases in order and one final event', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + + final task = engine.generate( + const ImageGenerationRequest( + prompt: 'a lighthouse', + width: 256, + height: 256, + steps: 2, + count: 2, + ), + ); + final events = await task.events.toList(); + + final progress = events + .whereType() + .map((e) => '${e.phase.name} ${e.step}/${e.steps} #${e.imageIndex}') + .toList(); + expect(progress, [ + 'encodingPrompt 0/2 #0', + 'sampling 0/2 #0', + 'sampling 1/2 #0', + 'sampling 2/2 #0', + 'sampling 0/2 #1', + 'sampling 1/2 #1', + 'sampling 2/2 #1', + 'decoding 0/2 #1', + ]); + final result = (events.last as ImageGenerationFinalEvent).result; + expect(result.images, hasLength(2)); + expect(result.images.first.width, 256); + final completion = await task.done; + expect(completion.state, ImageGenerationCompletionState.completed); + expect(completion.result, same(result)); + expect(driver.session.requests.single.prompt, 'a lighthouse'); + }); + + test('allows one generation at a time across engines and loads', () async { + final first = await load(ImageGenerationModel.sdxs(_model)); + final second = await load(ImageGenerationModel.sdxs(_model)); + final gate = driver.session.gate = Completer(); + + final running = first.generate(const ImageGenerationRequest(prompt: 'a')); + + for (final start in [ + () => first.generate(const ImageGenerationRequest(prompt: 'b')), + () => second.generate(const ImageGenerationRequest(prompt: 'c')), + ]) { + expect( + start, + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('process-wide callback'), + ), + ), + ); + } + await expectLater( + load(ImageGenerationModel.sdxs(_model)), + throwsA(isA()), + ); + + gate.complete(); + expect( + (await running.done).state, + ImageGenerationCompletionState.completed, + ); + driver.session.gate = null; + + final next = await second.generateImage( + const ImageGenerationRequest(prompt: 'd'), + ); + expect(next.images, isNotEmpty); + }); + + test('a cancel before the runtime starts is re-applied on its first ' + 'progress callback', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + final gate = driver.session.gate = Completer(); + + final task = engine.generate( + const ImageGenerationRequest(prompt: 'a', steps: 4), + ); + final events = task.events.toList(); + task.cancel(); + expect(driver.session.cancelCalls, 1); + + // The runtime clears the flag when generation starts. + gate.complete(); + final completion = await task.done; + + expect(completion.state, ImageGenerationCompletionState.cancelled); + expect(driver.session.cancelCalls, 2); + expect(driver.session.stepsRun, 0); + expect(await events, everyElement(isA())); + }); + + test('cancel during sampling stops the runtime', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + final task = engine.generate( + const ImageGenerationRequest(prompt: 'a', steps: 8), + ); + + final events = []; + await for (final event in task.events) { + events.add(event); + if (event case ImageGenerationProgressEvent( + phase: ImageGenerationPhase.sampling, + step: 1, + )) { + task.cancel(); + task.cancel(); + } + } + + expect((await task.done).state, ImageGenerationCompletionState.cancelled); + expect(driver.session.stepsRun, lessThan(8)); + expect(events.whereType(), isEmpty); + expect(task.isCancellationRequested, isTrue); + }); + + test('a runtime failure fails the task with LlamaInferenceException and ' + 'the engine runs the next request', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + driver.session.failNext = true; + + final task = engine.generate(const ImageGenerationRequest(prompt: 'a')); + await expectLater( + task.events.drain(), + throwsA(isA()), + ); + final completion = await task.done; + expect(completion.state, ImageGenerationCompletionState.failed); + expect( + completion.error, + isA().having( + (error) => error.message, + 'message', + contains('The engine can run the next request'), + ), + ); + + final next = await engine.generateImage( + const ImageGenerationRequest(prompt: 'b'), + ); + expect(next.images, hasLength(1)); + }); + + test('maps unexpected errors to LlamaInferenceException and keeps typed ' + 'ones', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + + driver.session.error = StateError('worker bug'); + await expectLater( + engine.generateImage(const ImageGenerationRequest(prompt: 'a')), + throwsA( + isA().having( + (error) => error.details, + 'details', + isA(), + ), + ), + ); + + driver.session.error = LlamaStateException('worker stopped'); + await expectLater( + engine.generateImage(const ImageGenerationRequest(prompt: 'a')), + throwsA(isA()), + ); + }); + + test('dispose cancels a running generation before freeing the ' + 'model', () async { + final engine = await load(ImageGenerationModel.sdxs(_model)); + final gate = driver.session.gate = Completer(); + final result = engine.generateImage( + const ImageGenerationRequest(prompt: 'a', steps: 4), + ); + final resultExpectation = expectLater( + result, + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('disposed'), + ), + ), + ); + + final disposal = engine.dispose(); + expect(engine.isDisposed, isTrue); + expect(driver.session.disposed, isFalse); + gate.complete(); + await disposal; + await resultExpectation; + + expect(driver.session.disposedAfterGenerate, isTrue); + expect(driver.session.stepsRun, 0); + await engine.dispose(); + expect(driver.session.disposeCalls, 1); + expect(engine.capabilities.isSupported, isFalse); + expect( + () => engine.generate(const ImageGenerationRequest(prompt: 'a')), + throwsA(isA()), + ); + }); + }); +} + +StableDiffusionRuntimeStatus _available(String devices) => + StableDiffusionRuntimeStatus.available( + version: 'master-929', + commit: '3f8527a', + devices: parseStableDiffusionDeviceList(devices), + ); + +final class _FakeDriver implements ImageGenerationDriver { + StableDiffusionRuntimeStatus status = _available( + 'MTL0\tApple M4\nBLAS\tAccelerate\nCPU\tApple M4\n', + ); + final Map sizes = {_model: 651 << 20, _taesd: 9 << 20}; + ImageGenerationMemoryBudget? budget; + Object? startError; + final List started = []; + _FakeSession session = _FakeSession(); + + @override + StableDiffusionRuntimeStatus probe() => status; + + @override + int? fileSize(String path) => sizes[path]; + + @override + ImageGenerationMemoryBudget? memoryBudget() => budget; + + @override + Future start( + ImageGenerationSessionConfig config, + ) async { + final error = startError; + if (error != null) { + throw error; + } + started.add(config); + return session; + } +} + +/// Behaves like stable-diffusion.cpp: a generation clears the cancel flag +/// when it starts, reports `0/steps` then each step, and checks the flag +/// before every step and before decoding. +final class _FakeSession implements ImageGenerationSession { + final List requests = []; + Completer? gate; + bool failNext = false; + Object? error; + bool _cancelFlag = false; + bool _generating = false; + int cancelCalls = 0; + int stepsRun = 0; + int disposeCalls = 0; + bool disposed = false; + bool disposedAfterGenerate = false; + + @override + String get modelVersion => 'SD 2.x'; + + @override + Future?> generate( + ImageGenerationSessionRequest request, + void Function(int step, int steps) onProgress, + ) async { + requests.add(request); + _generating = true; + stepsRun = 0; + try { + await gate?.future; + _cancelFlag = false; + final failure = error; + if (failure != null) { + error = null; + throw failure; + } + for (var image = 0; image < request.count; image++) { + onProgress(0, request.steps); + for (var step = 1; step <= request.steps; step++) { + await Future.delayed(Duration.zero); + if (_cancelFlag) { + return null; + } + stepsRun++; + onProgress(step, request.steps); + } + } + await Future.delayed(Duration.zero); + if (_cancelFlag || failNext) { + failNext = false; + return null; + } + return [ + for (var i = 0; i < request.count; i++) + GeneratedImage( + width: request.width, + height: request.height, + channels: 3, + pixels: Uint8List(request.width * request.height * 3), + ), + ]; + } finally { + _generating = false; + } + } + + @override + void cancel() { + cancelCalls++; + _cancelFlag = true; + } + + @override + Future dispose() async { + disposeCalls++; + disposed = true; + disposedAfterGenerate = !_generating; + } +} diff --git a/test/unit/core/image/image_generation_engine_web_test.dart b/test/unit/core/image/image_generation_engine_web_test.dart new file mode 100644 index 000000000..7580eb0a0 --- /dev/null +++ b/test/unit/core/image/image_generation_engine_web_test.dart @@ -0,0 +1,28 @@ +@TestOn('browser') +library; + +import 'package:test/test.dart'; + +import 'package:llamadart/llamadart.dart'; + +void main() { + test('the web reports image generation unsupported', () { + final capabilities = ImageGenerationEngine.runtimeCapabilities(); + + expect(capabilities.isSupported, isFalse); + expect(capabilities.unsupportedReason, contains('web')); + }); + + test('load throws LlamaUnsupportedException on the web', () async { + await expectLater( + ImageGenerationEngine.load(ImageGenerationModel.sdxs('sdxs.gguf')), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('not available on the web'), + ), + ), + ); + }); +} diff --git a/test/unit/core/image/image_generation_events_test.dart b/test/unit/core/image/image_generation_events_test.dart new file mode 100644 index 000000000..985ca2f31 --- /dev/null +++ b/test/unit/core/image/image_generation_events_test.dart @@ -0,0 +1,46 @@ +import 'dart:typed_data'; + +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/generated_image.dart'; +import 'package:llamadart/src/core/image/image_generation_events.dart'; + +void main() { + final result = ImageGenerationResult( + images: [ + GeneratedImage(width: 8, height: 8, channels: 3, pixels: Uint8List(192)), + ], + seed: 7, + elapsed: const Duration(milliseconds: 5), + ); + + test('completed carries the result only', () { + final completion = ImageGenerationCompletion.completed(result); + + expect(completion.state, ImageGenerationCompletionState.completed); + expect(completion.result, same(result)); + expect(completion.error, isNull); + }); + + test('cancelled carries neither result nor error', () { + const completion = ImageGenerationCompletion.cancelled(); + + expect(completion.state, ImageGenerationCompletionState.cancelled); + expect(completion.result, isNull); + expect(completion.error, isNull); + }); + + test('failed carries the error only', () { + final error = LlamaInferenceException('GPU abort'); + final completion = ImageGenerationCompletion.failed(error); + + expect(completion.state, ImageGenerationCompletionState.failed); + expect(completion.error, same(error)); + expect(completion.result, isNull); + }); + + test('the final event carries the result', () { + expect(ImageGenerationFinalEvent(result).result, same(result)); + }); +} diff --git a/test/unit/core/image/image_generation_model_test.dart b/test/unit/core/image/image_generation_model_test.dart new file mode 100644 index 000000000..3f38383d9 --- /dev/null +++ b/test/unit/core/image/image_generation_model_test.dart @@ -0,0 +1,69 @@ +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/image/image_generation_model.dart'; + +void main() { + test('sdxs samples one step at guidance 1', () { + final model = ImageGenerationModel.sdxs('/m/sdxs.gguf'); + + expect(model.family, ImageGenerationModelFamily.sdxs); + expect(model.files.paths, {'model': '/m/sdxs.gguf'}); + expect(model.defaults.steps, 1); + expect(model.defaults.guidanceScale, 1); + }); + + test('sdTurbo samples one step at guidance 1 and adds TAESD', () { + final withTaesd = ImageGenerationModel.sdTurbo( + '/m/turbo.gguf', + taesdPath: '/m/taesd.safetensors', + ); + final withoutTaesd = ImageGenerationModel.sdTurbo('/m/turbo.gguf'); + + expect(withTaesd.family, ImageGenerationModelFamily.sdTurbo); + expect(withTaesd.files.paths, { + 'model': '/m/turbo.gguf', + 'taesd': '/m/taesd.safetensors', + }); + expect(withoutTaesd.files.paths, {'model': '/m/turbo.gguf'}); + expect(withTaesd.defaults.steps, 1); + expect(withTaesd.defaults.guidanceScale, 1); + }); + + test('custom keeps its files and defaults to 20 steps at guidance 7', () { + final model = ImageGenerationModel.custom( + const ImageGenerationModelFiles( + diffusionModel: '/m/unet.gguf', + vae: '/m/vae.safetensors', + clipL: '/m/clip_l.safetensors', + clipG: '/m/clip_g.safetensors', + t5xxl: '/m/t5.gguf', + ), + ); + + expect(model.family, ImageGenerationModelFamily.custom); + expect(model.files.paths.keys, [ + 'diffusionModel', + 'vae', + 'clipL', + 'clipG', + 't5xxl', + ]); + expect(model.defaults.steps, 20); + expect(model.defaults.guidanceScale, 7); + + final tuned = ImageGenerationModel.custom( + const ImageGenerationModelFiles(model: '/m/sd15.safetensors'), + defaults: const ImageGenerationDefaults(steps: 8, guidanceScale: 2), + ); + expect(tuned.defaults.steps, 8); + expect(tuned.defaults.guidanceScale, 2); + }); + + test('options default to auto, physical cores and a memory check', () { + const options = ImageGenerationOptions(); + + expect(options.device, ImageGenerationDevice.auto); + expect(options.threads, 0); + expect(options.checkMemory, isTrue); + }); +} diff --git a/test/unit/core/image/image_generation_progress_test.dart b/test/unit/core/image/image_generation_progress_test.dart new file mode 100644 index 000000000..a92b4d642 --- /dev/null +++ b/test/unit/core/image/image_generation_progress_test.dart @@ -0,0 +1,85 @@ +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/image/image_generation_events.dart'; +import 'package:llamadart/src/core/image/image_generation_progress.dart'; + +String _label(ImageGenerationProgressEvent event) => + '${event.phase.name} ${event.step}/${event.steps} ' + '#${event.imageIndex}/${event.imageCount}'; + +List _feed( + ImageGenerationProgressTracker tracker, + List<(int, int)> callbacks, +) => [ + for (final (step, total) in callbacks) + ...tracker.onNativeProgress(step, total).map(_label), +]; + +void main() { + test('starts in encodingPrompt', () { + final tracker = ImageGenerationProgressTracker(steps: 4, imageCount: 1); + + expect(_label(tracker.start()), 'encodingPrompt 0/4 #0/1'); + }); + + test('labels an eagerly loaded single image as sampling, then decoding', () { + final tracker = ImageGenerationProgressTracker(steps: 1, imageCount: 1); + + expect(_feed(tracker, [(0, 1), (1, 1)]), [ + 'sampling 0/1 #0/1', + 'sampling 1/1 #0/1', + 'decoding 0/1 #0/1', + ]); + }); + + test('advances the image index per sampling pass', () { + final tracker = ImageGenerationProgressTracker(steps: 2, imageCount: 2); + + expect(_feed(tracker, [(0, 2), (1, 2), (2, 2), (0, 2), (1, 2), (2, 2)]), [ + 'sampling 0/2 #0/2', + 'sampling 1/2 #0/2', + 'sampling 2/2 #0/2', + 'sampling 0/2 #1/2', + 'sampling 1/2 #1/2', + 'sampling 2/2 #1/2', + 'decoding 0/2 #1/2', + ]); + }); + + test('labels lazy tensor loads as loading and tiled decodes as decoding ' + '(first SDXS run with lazy loading)', () { + final tracker = ImageGenerationProgressTracker(steps: 1, imageCount: 1); + + expect( + _feed(tracker, [ + (4, 196), + (196, 196), + (0, 1), + (0, 280), + (280, 280), + (1, 1), + (0, 67), + (67, 67), + ]), + [ + 'loading 4/196 #0/1', + 'loading 196/196 #0/1', + 'sampling 0/1 #0/1', + 'loading 0/280 #0/1', + 'loading 280/280 #0/1', + 'sampling 1/1 #0/1', + 'decoding 0/1 #0/1', + 'decoding 0/67 #0/1', + 'decoding 67/67 #0/1', + ], + ); + }); + + test('a callback after every image is sampled is decoding, even with the ' + 'step total', () { + final tracker = ImageGenerationProgressTracker(steps: 4, imageCount: 1); + _feed(tracker, [(0, 4), (1, 4), (2, 4), (3, 4), (4, 4)]); + + expect(_feed(tracker, [(2, 4)]), ['decoding 2/4 #0/1']); + }); +} diff --git a/test/unit/core/image/image_generation_request_test.dart b/test/unit/core/image/image_generation_request_test.dart new file mode 100644 index 000000000..6c45b8d50 --- /dev/null +++ b/test/unit/core/image/image_generation_request_test.dart @@ -0,0 +1,77 @@ +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/image_generation_request.dart'; + +void main() { + test('defaults to one 512x512 image with the model defaults', () { + const request = ImageGenerationRequest(prompt: 'a fox'); + + expect(request.width, 512); + expect(request.height, 512); + expect(request.count, 1); + expect(request.negativePrompt, ''); + expect(request.steps, isNull); + expect(request.guidanceScale, isNull); + expect(request.seed, isNull); + validateImageGenerationRequest(request); + }); + + test('accepts the bounds', () { + for (final request in const [ + ImageGenerationRequest( + prompt: 'a', + width: 64, + height: 2048, + steps: 1, + guidanceScale: 0, + seed: 0, + count: 1, + ), + ImageGenerationRequest( + prompt: 'a', + width: 2048, + height: 64, + steps: 150, + guidanceScale: 30, + seed: 0x7FFFFFFF, + count: 16, + ), + ]) { + validateImageGenerationRequest(request); + } + }); + + test('names the first invalid field', () { + for (final (request, field, value) in const [ + (ImageGenerationRequest(prompt: ''), 'prompt', null), + (ImageGenerationRequest(prompt: 'a', width: 524), 'width', 524), + (ImageGenerationRequest(prompt: 'a', width: 56), 'width', 56), + (ImageGenerationRequest(prompt: 'a', height: 2056), 'height', 2056), + (ImageGenerationRequest(prompt: 'a', steps: 0), 'steps', 0), + (ImageGenerationRequest(prompt: 'a', steps: 151), 'steps', 151), + ( + ImageGenerationRequest(prompt: 'a', guidanceScale: 30.5), + 'guidanceScale', + 30.5, + ), + ( + ImageGenerationRequest(prompt: 'a', guidanceScale: double.infinity), + 'guidanceScale', + double.infinity, + ), + (ImageGenerationRequest(prompt: 'a', seed: -1), 'seed', -1), + (ImageGenerationRequest(prompt: 'a', count: 17), 'count', 17), + ]) { + expect( + () => validateImageGenerationRequest(request), + throwsA( + isA() + .having((error) => error.message, 'message', contains(field)) + .having((error) => error.details, 'details', value), + ), + reason: field, + ); + } + }); +} diff --git a/test/unit/core/image/png_encoder_test.dart b/test/unit/core/image/png_encoder_test.dart new file mode 100644 index 000000000..361133e51 --- /dev/null +++ b/test/unit/core/image/png_encoder_test.dart @@ -0,0 +1,91 @@ +import 'dart:typed_data'; + +import 'package:archive/archive.dart'; +import 'package:test/test.dart'; + +import 'package:llamadart/src/core/exceptions.dart'; +import 'package:llamadart/src/core/image/png_encoder.dart'; + +void main() { + test('writes a signature, IHDR, IDAT and IEND with valid CRCs', () { + final pixels = Uint8List.fromList([ + 255, 0, 0, 0, 255, 0, // + 0, 0, 255, 255, 255, 255, + ]); + + final png = encodePng(width: 2, height: 2, channels: 3, pixels: pixels); + final chunks = _chunks(png); + + expect(png.sublist(0, 8), [137, 80, 78, 71, 13, 10, 26, 10]); + expect(chunks.map((c) => c.type), ['IHDR', 'IDAT', 'IEND']); + final header = ByteData.sublistView(chunks.first.data); + expect(header.getUint32(0), 2); + expect(header.getUint32(4), 2); + expect(chunks.first.data.sublist(8), [8, 2, 0, 0, 0]); + // Each scanline is filter byte 0 followed by the row. + expect(const ZLibDecoder().decodeBytes(chunks[1].data), [ + 0, 255, 0, 0, 0, 255, 0, // + 0, 0, 0, 255, 255, 255, 255, + ]); + }); + + test('uses the PNG color type for 1, 3 and 4 channels', () { + for (final (channels, colorType) in [(1, 0), (3, 2), (4, 6)]) { + final png = encodePng( + width: 1, + height: 1, + channels: channels, + pixels: Uint8List(channels), + ); + expect(_chunks(png).first.data[9], colorType, reason: '$channels'); + } + }); + + test('matches the standard CRC-32 of the IEND chunk', () { + final png = encodePng( + width: 1, + height: 1, + channels: 3, + pixels: Uint8List(3), + ); + + expect(png.sublist(png.length - 4), [0xAE, 0x42, 0x60, 0x82]); + }); + + test('rejects a buffer that does not match the dimensions', () { + for (final (width, height, channels, length) in [ + (2, 2, 3, 11), + (2, 2, 2, 8), + (0, 2, 3, 0), + ]) { + expect( + () => encodePng( + width: width, + height: height, + channels: channels, + pixels: Uint8List(length), + ), + throwsA(isA()), + reason: '${width}x$height@$channels/$length', + ); + } + }); +} + +List<({String type, Uint8List data})> _chunks(Uint8List png) { + final view = ByteData.sublistView(png); + final chunks = <({String type, Uint8List data})>[]; + var offset = 8; + while (offset < png.length) { + final length = view.getUint32(offset); + final type = String.fromCharCodes(png.sublist(offset + 4, offset + 8)); + final data = png.sublist(offset + 8, offset + 8 + length); + final crc = view.getUint32(offset + 8 + length); + expect(crc, _crc(png.sublist(offset + 4, offset + 8 + length))); + chunks.add((type: type, data: data)); + offset += 12 + length; + } + return chunks; +} + +int _crc(List bytes) => getCrc32(bytes); diff --git a/test/unit/hook/native_bundle_config_test.dart b/test/unit/hook/native_bundle_config_test.dart index 579112e09..381beae57 100644 --- a/test/unit/hook/native_bundle_config_test.dart +++ b/test/unit/hook/native_bundle_config_test.dart @@ -1172,6 +1172,82 @@ void main() { } }); + test('llamadart_stable_diffusion_backends picks Vulkan over CPU in a ' + 'mixed list', () { + for (final (os, arch, base) in [ + (OS.linux, Architecture.x64, 'linux-x64'), + (OS.windows, Architecture.x64, 'windows-x64'), + ]) { + final nativeSpec = spec(os, arch); + final warnings = []; + for (final mixed in [ + ['cpu', 'vulkan'], + ['vulkan', 'cpu'], + 'cpu, vk', + { + 'platforms': { + os.name: ['cpu', 'vulkan'], + }, + }, + ]) { + expect( + stableDiffusionBundleForNativeBundle( + spec: nativeSpec, + rawBackendConfig: { + 'platforms': {os.name: 'cpu'}, + }, + rawStableDiffusionBackendConfig: mixed, + warn: warnings.add, + ), + '$base-vulkan', + reason: '$mixed', + ); + } + expect(warnings, isEmpty); + } + }); + + test('an empty llamadart_stable_diffusion_backends neither warns nor ' + 'overrides the llama.cpp choice', () { + for (final (os, arch, base) in [ + (OS.linux, Architecture.x64, 'linux-x64'), + (OS.windows, Architecture.x64, 'windows-x64'), + ]) { + final nativeSpec = spec(os, arch); + for (final empty in [ + [], + '', + { + 'platforms': {os.name: []}, + }, + { + 'platforms': { + os.name: {'backends': []}, + }, + }, + ]) { + final warnings = []; + String? select(Object? llamaCpp) => + stableDiffusionBundleForNativeBundle( + spec: nativeSpec, + rawBackendConfig: llamaCpp, + rawStableDiffusionBackendConfig: empty, + warn: warnings.add, + ); + + expect(select(null), '$base-vulkan', reason: '$empty'); + expect( + select({ + 'platforms': {os.name: 'cpu'}, + }), + base, + reason: '$empty', + ); + expect(warnings, isEmpty, reason: '$empty'); + } + } + }); + test('llamadart_stable_diffusion_backends does not change Apple or ' 'Android archives', () { for (final (nativeSpec, bundle) in [ diff --git a/test/unit/test_structure/mirrored_unit_structure_test.dart b/test/unit/test_structure/mirrored_unit_structure_test.dart index a6914bb71..eaf79f73f 100644 --- a/test/unit/test_structure/mirrored_unit_structure_test.dart +++ b/test/unit/test_structure/mirrored_unit_structure_test.dart @@ -10,6 +10,7 @@ import 'package:test/test.dart'; /// exist under `lib/src` and to have no mirrored file under `test/unit`. const Set behaviorlessSources = { 'backends/webgpu/interop.dart', + 'core/image/image_generation_driver.dart', 'core/models/config/flash_attention.dart', 'core/models/config/kv_cache_type.dart', }; diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 63c37cb71..804337865 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -771,6 +771,39 @@ void main() { expect(result.stderr, contains('--model-path and --mmproj-path')); }); + test('dry-runs image generation in the opted-in example', () async { + final result = await runLocalE2e(const [ + '--scenario', + 'image-generation-smoke', + '--model-path', + 'models/sdxs-512-tinySDdistilled_Q8_0.gguf', + '--dry-run', + ], projectRoot: '/repo'); + + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + "cd /repo/example/basic_app && LLAMADART_SDXS_MODEL=" + "models/sdxs-512-tinySDdistilled_Q8_0.gguf " + "LLAMADART_IMAGE_OUTPUT_DIR=/repo/build/image-generation-smoke " + "dart test --run-skipped -t local-only " + "test/image_generation_e2e_test.dart", + ), + ); + }); + + test('requires an SDXS model for image generation', () async { + final result = await runLocalE2e(const [ + '--scenario', + 'image-generation-smoke', + '--dry-run', + ], projectRoot: '/repo'); + + expect(result.exitCode, 64); + expect(result.stderr, contains('--model-path is required')); + }); + test('passes the GGUF stop-sequence backend only when given', () async { Future dryRun(List backend) async { final result = await runLocalE2e([ diff --git a/test/unit/tooling/test_matrix_test.dart b/test/unit/tooling/test_matrix_test.dart index dc7bff0a4..a56e23932 100644 --- a/test/unit/tooling/test_matrix_test.dart +++ b/test/unit/tooling/test_matrix_test.dart @@ -54,6 +54,7 @@ void main() { expect(ids, contains('gemma4-webgpu-mem64')); expect(ids, contains('physical-ios-speech-e2e')); expect(ids, contains('decision-model-smoke')); + expect(ids, contains('image-generation-smoke')); }); test('rows name local E2E scenarios that the runner defines', () { @@ -71,6 +72,7 @@ void main() { } } expect(referenced, contains('decision-model-smoke')); + expect(referenced, contains('image-generation-smoke')); }); test('speech-to-text rows take WAV, MP3 or FLAC fixtures', () { diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index 9ffd53ebf..9522aba7d 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -586,6 +586,34 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'image-generation-smoke', + group: LocalE2eScenarioGroup.dartLocalOnly, + description: + 'Run experimental ImageGenerationEngine on SDXS through the opt-in ' + 'stable_diffusion runtime; SD-Turbo too when ' + 'LLAMADART_SD_TURBO_MODEL is set.', + requiresDevice: false, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: '${context.projectRoot}/example/basic_app', + executable: 'dart', + arguments: const [ + 'test', + '--run-skipped', + '-t', + 'local-only', + 'test/image_generation_e2e_test.dart', + ], + environment: { + 'LLAMADART_SDXS_MODEL': context.modelPath!, + 'LLAMADART_IMAGE_OUTPUT_DIR': + '${context.projectRoot}/build/image-generation-smoke', + }, + description: 'Image generation real-model smoke', + ), + ], + ), LocalE2eScenario( name: 'decision-model-smoke', group: LocalE2eScenarioGroup.dartLocalOnly, @@ -1449,6 +1477,13 @@ Future runLocalE2e( '--expect are required for litert-lm-asr-smoke.\n', ); } + if (scenario.name == 'image-generation-smoke' && parsed.modelPath == null) { + return const LocalE2eResult( + 64, + stderr: + '--model-path is required for image-generation-smoke.\n', + ); + } if (scenario.name == 'text-to-speech-smoke' && (parsed.modelPath == null || parsed.mmprojPath == null)) { return const LocalE2eResult( diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index e24cdbc20..b3b9f5230 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -432,6 +432,23 @@ const List testMatrixRows = [ 'Text-to-speech API, native audio generation, Qwen3-TTS projector, or ' 'chat-app synthesis changes.', ), + TestMatrixRow( + id: 'image-generation-smoke', + tier: 'targeted', + mode: 'local-only', + covers: + 'real opt-in stable_diffusion runtime bundled by the example hook, ' + '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; ' + 'SD-Turbo with TAESD when LLAMADART_SD_TURBO_MODEL is set', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'image-generation-smoke --model-path ', + useWhen: + 'Image generation API, stable_diffusion runtime pins, bindings, ' + 'probe or hook changes.', + ), TestMatrixRow( id: 'decision-model-smoke', tier: 'targeted', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index e8ab8c27a..586e697f7 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -11,7 +11,8 @@ For canonical full release notes, use: - Ship agent skills for coding agents covering setup, chat and streaming, tool calling, web, Flutter apps, multimodal input, embeddings, speech, LoRA - adapters and decision models; install them with `dart run skills@ get`. + adapters, decision models and image generation; install them with + `dart run skills@ get`. - Add an observability guide and tested optional OpenTelemetry example with Langfuse and Grafana recipes. - Apply `ModelParams.loras` at model load on native llama.cpp and WebGPU, where they were silently ignored; an adapter that cannot be applied, or @@ -25,6 +26,11 @@ For canonical full release notes, use: generation; it is never bundled by default or by `all`, and `llamadart_stable_diffusion_backends` picks its CPU or Vulkan build on Linux and Windows ([#777](https://github.com/leehack/llamadart/issues/777)). +- Add experimental on-device image generation, `ImageGenerationEngine`, on + the opt-in `stable_diffusion` runtime: SDXS and SD-Turbo presets, + phase-labelled progress, cancellation, PNG output and a memory check before + loading; not available on the web + ([#778](https://github.com/leehack/llamadart/issues/778)). - Throw `LlamaUnsupportedException` for image or audio parts sent to a GGUF model with no projector loaded: native llama.cpp answered from the text alone, and WebGPU threw an untyped error surfaced as diff --git a/website/docs/examples/basic-app.md b/website/docs/examples/basic-app.md index 3d4b962c0..a80a4896b 100644 --- a/website/docs/examples/basic-app.md +++ b/website/docs/examples/basic-app.md @@ -1,14 +1,14 @@ --- title: Basic app example sidebar_label: Basic app -description: Minimal Dart console apps for chat, embeddings, SQLite vector retrieval and decision models, the quickest way to see the core llamadart API. +description: Minimal Dart console apps for chat, embeddings, SQLite vector retrieval, decision models and image generation, the quickest way to see the core llamadart API. --- Path: `example/basic_app` · Platforms: Dart console on macOS, Linux and Windows · First-run download: `Qwen3.5-0.8B-Q4_K_M.gguf` (533 MB) -Dart console apps that show the core API: chat, embeddings, vector retrieval -and decision models, without Flutter. +Dart console apps that show the core API: chat, embeddings, vector retrieval, +decision models and image generation, without Flutter. ## Run @@ -33,6 +33,10 @@ dart run bin/llamadart_sqlite_vector_example.dart \ # Decision model: triage a support ticket # (downloads laya-Q8_0.gguf, 421 MB, and laya-head.safetensors, 106 MB) dart run bin/llamadart_decision_example.dart + +# Image generation: write a PNG with SDXS (downloads the stable_diffusion +# runtime and sdxs-512-tinySDdistilled_Q8_0.gguf, 651 MB); Ctrl-C cancels +dart run bin/llamadart_image_example.dart -p "a red fox in autumn leaves" ``` ## What it demonstrates @@ -51,6 +55,10 @@ dart run bin/llamadart_decision_example.dart - Typed choice, score and yes/no answers from a decision model with `ChoiceKey.enumOf`, `ScoreKey.of`, `NoulKey.of` and `answerOf` ([Decision models](../guides/decision-models#typed-questions)). +- Experimental image generation with SDXS or SD-Turbo: phase progress, + Ctrl-C cancellation and PNG output, with the `stable_diffusion` runtime + opted in through the example's `pubspec.yaml` + ([Image generation](../guides/image-generation)). ## Test @@ -59,6 +67,6 @@ cd example/basic_app dart test ``` -Full options: every flag of the four CLIs, the retrieval result fields and +Full options: every flag of the five CLIs, the retrieval result fields and the decision-model head options are in the [example README](https://github.com/leehack/llamadart/tree/main/example/basic_app). diff --git a/website/docs/guides/backend-selection.md b/website/docs/guides/backend-selection.md index 7a490cdbc..eeb272f70 100644 --- a/website/docs/guides/backend-selection.md +++ b/website/docs/guides/backend-selection.md @@ -136,4 +136,5 @@ Native apps include the llama.cpp and LiteRT-LM runtime families by default, so one build can load both GGUF and `.litertlm` models. To ship only one, set `llamadart_native_runtimes` as described in [Native Build Hooks](../platforms/native-build-hooks). The experimental -`stable_diffusion` runtime is never included unless named there. +`stable_diffusion` runtime, which [image generation](./image-generation) +needs, is never included unless named there. diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md new file mode 100644 index 000000000..c37c69422 --- /dev/null +++ b/website/docs/guides/image-generation.md @@ -0,0 +1,208 @@ +--- +title: On-device image generation +sidebar_label: Image generation +description: Generate images from text prompts on device with the experimental ImageGenerationEngine and the opt-in stable-diffusion.cpp runtime. +--- + +`ImageGenerationEngine` turns a text prompt into images on the device. It runs +[stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) through +the opt-in `stable_diffusion` native runtime, separately from `LlamaEngine`. + +The API is experimental. Two small, distilled SD 1.x/2.x-family models are +validated: SDXS-512 and SD-Turbo. It is text-to-image only: no image-to-image, +inpainting, LoRA or ControlNet yet. + +## Support + +| Platform | Device | Minimum OS | Notes | +| --- | --- | --- | --- | +| macOS (arm64, x86_64) | Metal, CPU | macOS 13.3 | Validated on an M4 Max | +| iOS (arm64, arm64 simulator) | Metal, CPU | iOS 16.4 | Validated on iPhone 16 Pro and iPhone SE 3; no x86_64 simulator runtime | +| Android arm64 | CPU | Not set by llamadart | Needs Armv8.2 dot-product and fp16 (`asimddp`, `fphp`, `asimdhp`); validated on Pixel 9 Pro, Galaxy S24 and Galaxy A53; no x64 runtime | +| Linux (arm64, x64) | CPU, or Vulkan with the Vulkan build | Not set by llamadart | x64 CPUs need AVX2, FMA, F16C and BMI2; validated on x64 with CPU and an NVIDIA L4 | +| Windows x64 | CPU, or Vulkan with the Vulkan build | Not set by llamadart | Needs the Microsoft Visual C++ 2015-2022 Redistributable (x64) and AVX2; the Vulkan build needs a GPU driver that provides `vulkan-1.dll`; validated on Windows Server 2022 with CPU and an NVIDIA L4; no arm64 runtime | +| Web | None | | `load` throws `LlamaUnsupportedException` | + +Measured with the prototype on the same runtime, 512x512, one step, warm: + +| Device | SDXS Q8 (651 MB) | SD-Turbo Q8 + TAESD (1.9 GB) | +| --- | --- | --- | +| M4 Max, Metal | 1.5 s | 1.2 s | +| iPhone 16 Pro, Metal | 1.7 s | 4.1 s | +| Galaxy S24, CPU | 5.9 s | 11.8 s | +| Galaxy A53, CPU | 26 to 29 s | Does not fit in memory | + +`ImageGenerationEngine.runtimeCapabilities()` reports whether this build and +device can generate images, and why not, without loading a model. + +## Bundle the runtime + +The runtime adds about 40 to 70 MB per target, so it is never bundled by +default. Name it in the app's `pubspec.yaml`, then run `flutter clean` once: + +```yaml +hooks: + user_defines: + llamadart: + llamadart_native_runtimes: [llama_cpp, stable_diffusion] +``` + +Linux and Windows get the Vulkan build when `llamadart_native_backends` +selects Vulkan, which it does by default; set +`llamadart_stable_diffusion_backends: [cpu]` for the CPU build. See +[Native runtime configuration](../platforms/native-build-hooks#opt-in-stable_diffusion-runtime-experimental). + +## Get a model + +| Preset | Files | Defaults | +| --- | --- | --- | +| `ImageGenerationModel.sdxs(path)` | `sdxs-512-tinySDdistilled_Q8_0.gguf` from [`concedo/sdxs-512-tinySDdistilled-GGUF`](https://huggingface.co/concedo/sdxs-512-tinySDdistilled-GGUF) (651 MB) | 1 step, guidance 1 | +| `ImageGenerationModel.sdTurbo(path, taesdPath: ...)` | `sd_turbo-f16-q8_0.gguf` from [`Green-Sky/SD-Turbo-GGUF`](https://huggingface.co/Green-Sky/SD-Turbo-GGUF) (1.9 GB), optionally `diffusion_pytorch_model.safetensors` from [`madebyollin/taesd`](https://huggingface.co/madebyollin/taesd) (9 MB) | 1 step, guidance 1 | +| `ImageGenerationModel.custom(files, defaults: ...)` | Other SD 1.x/2.x checkpoints, single-file or split | 20 steps, guidance 7 | + +SDXS is distilled for exactly one step. SD-Turbo takes one to four steps; four +add detail at about four times the sampling time. TAESD replaces the full VAE +decoder: several times faster and far less memory, at a small quality cost. +Use it on phones. `taesd_decoder.safetensors` from the same repository is +rejected by the runtime; use `diffusion_pytorch_model.safetensors`. + +The engine takes local files. Download them with the package-managed cache, +which resumes interrupted downloads: + +```dart +final downloads = DefaultModelDownloadManager(); +final entry = await downloads.ensureModel( + ModelSource.parse( + 'hf://concedo/sdxs-512-tinySDdistilled-GGUF/' + 'sdxs-512-tinySDdistilled_Q8_0.gguf', + ), +); +final model = ImageGenerationModel.sdxs(entry.filePath); +``` + +`.custom` is experimental. Larger families stable-diffusion.cpp supports, such +as SDXL or FLUX, may load but are untested and can exceed phone memory. + +## Generate + +```dart +final engine = await ImageGenerationEngine.load( + model, + options: const ImageGenerationOptions(device: ImageGenerationDevice.auto), +); +print('${engine.capabilities.modelVersion} on ' + '${engine.capabilities.backendName}'); + +final task = engine.generate( + const ImageGenerationRequest( + prompt: 'a red fox in autumn leaves', + width: 512, + height: 512, + seed: 42, + ), +); +await for (final event in task.events) { + switch (event) { + case ImageGenerationProgressEvent(:final phase, :final step, :final steps): + print('$phase $step/$steps'); + case ImageGenerationFinalEvent(:final result): + final png = result.images.first.toPng(); + print('${png.length} PNG bytes, seed ${result.seed}'); + } +} +await engine.dispose(); +``` + +`engine.generateImage(request)` is the one-call form; it returns the +`ImageGenerationResult` or throws the failure. + +- Width and height are multiples of 8 from 64 to 2048. SD 1.x/2.x models are + trained at 512; SDXS and SD-Turbo also work at 256. The runtime rounds the + size up to a multiple of 64 for these models, so a 200x136 request produces + 256x192; `GeneratedImage.width` and `height` report the real size. +- `steps` and `guidanceScale` fall back to the model's defaults. A guidance of + 1 skips the negative prompt and halves the work per step. +- A `null` seed picks one at random. `result.seed` reports the seed used, and + image `i` of `count` used `seed + i`. The same seed, size, steps and model + reproduce the same pixels. +- `GeneratedImage.pixels` holds row-major RGB bytes; `toPng()` encodes them. +- Invalid requests throw `LlamaImageGenerationException` before a task + starts. + +`load` loads every weight up front. On Apple GPUs the first generation after a +load is still slower while Metal compiles its shaders: about 19 s on an +iPhone 16 Pro, then 1.7 s per SDXS image. + +## Progress phases + +The runtime reports all progress through one `(step, steps)` callback, so the +engine labels it from the call sequence: + +1. `encodingPrompt` when the generation starts. +2. `sampling` with `0/steps` when each image's first step starts, then one + event per step. `imageIndex` says which image. +3. `decoding` with `0/count` after the last image's last step, then the final + event. The runtime reports decoding progress only when it decodes in tiles. + +`loading` appears only if the runtime loads weights lazily, which the engine +avoids by loading them eagerly. + +## Cancellation, concurrency and disposal + +- `task.cancel()` stops before the next sampling step or before decoding, and + `task.done` then reports `cancelled`. A cancel issued before the runtime + starts is honored too. +- stable-diffusion.cpp reports progress through one process-wide callback, so + one generation or model load runs at a time. Another `generate` or `load` + meanwhile throws `LlamaStateException`, even on a different engine. The guard + covers engines in one isolate; do not generate from several isolates at + once. +- `dispose()` cancels a running generation, waits for it, and frees the model. + `generateImage` then throws `LlamaStateException`. +- Generation runs in a worker isolate; the calling isolate stays responsive. + +## Memory check + +Before loading, the engine estimates the model's peak memory as its file +sizes plus a quarter, plus 256 MiB, and compares that with what the device +reports: + +| Platform | Compared with | +| --- | --- | +| Android, Linux | `MemAvailable` from `/proc/meminfo` | +| iOS | The app's remaining memory limit (`os_proc_available_memory`) | +| macOS | Physical memory | +| Windows | Not checked | + +A model that does not fit throws `LlamaModelException` naming both figures, +instead of the system killing the app. The estimate is simple and matches the +measured SDXS peaks (1.06 to 1.55 GB of process memory); set +`ImageGenerationOptions(checkMemory: false)` to load anyway. + +## Errors + +| Exception | When | +| --- | --- | +| `LlamaUnsupportedException` | The runtime is not bundled, the platform or CPU is unsupported, on the web, or `ImageGenerationDevice.gpu` without a GPU | +| `LlamaModelException` | A file is missing, the model does not fit, or the runtime cannot load it as an image model | +| `LlamaImageGenerationException` | An invalid request or options | +| `LlamaStateException` | 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. +- 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 is not memory-checked. 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)). + +The [basic app](../examples/basic-app) has a command-line image example. diff --git a/website/docs/intro.md b/website/docs/intro.md index 8176e24bf..eeb46b1e4 100644 --- a/website/docs/intro.md +++ b/website/docs/intro.md @@ -30,6 +30,8 @@ macOS, Linux, Windows and the web, behind one Dart API. - [Image and audio input](./guides/multimodal) with multimodal models. - [Speech to text](./guides/speech-to-text) and [text to speech](./guides/text-to-speech). +- [Image generation](./guides/image-generation) from text prompts, with the + opt-in stable-diffusion.cpp runtime (experimental). - [Decision models](./guides/decision-models) that answer typed questions without generating text. - Runtime [LoRA adapters](./guides/lora-adapters). diff --git a/website/docs/platforms/native-build-hooks.md b/website/docs/platforms/native-build-hooks.md index e0b18d609..2de9602ec 100644 --- a/website/docs/platforms/native-build-hooks.md +++ b/website/docs/platforms/native-build-hooks.md @@ -18,6 +18,7 @@ Configure the hook under `hooks.user_defines.llamadart` in the app's | --- | --- | --- | | `llamadart_native_runtimes` | Runtime families to bundle: `llama_cpp`, `litert_lm`, and the opt-in `stable_diffusion` | `llama_cpp` and `litert_lm` where published | | `llamadart_native_backends` | llama.cpp backend modules, and Android arm64 CPU variants | `cpu` and `vulkan` where present | +| `llamadart_stable_diffusion_backends` | The `stable_diffusion` build on Linux and Windows: `cpu` or `vulkan` | Follows `llamadart_native_backends` | | `llamadart_native_tag` | `leehack/llamadart-native` release to download | The [pinned release](./support-matrix#pinned-runtimes) | | `llamadart_native_repository` | GitHub repository to download llama.cpp bundles from | `leehack/llamadart-native` | | `llamadart_native_path` | Local archive or bundle directory used instead of a download | Unset | @@ -76,9 +77,10 @@ hooks: `stable_diffusion` bundles the [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) runtime -from `leehack/stable-diffusion-native`. It is groundwork for experimental image -generation and has no public Dart API yet. It adds about 40 to 70 MB per target, so -it is never bundled by default or by `all`/`both`; name it explicitly: +from `leehack/stable-diffusion-native` for the experimental +[`ImageGenerationEngine`](../guides/image-generation). It adds about 40 to +70 MB per target, so it is never bundled by default or by `all`/`both`; name it +explicitly: ```yaml hooks: @@ -89,9 +91,15 @@ hooks: ``` - Published for `android-arm64`, `ios-arm64`, `ios-arm64-sim`, `macos-arm64`, - `macos-x86_64`, `linux-arm64`, `linux-x64` and `windows-x64`. On Android it - needs an Armv8.2 CPU with dot-product and fp16 (`asimddp`, `fphp`, - `asimdhp`). + `macos-x86_64`, `linux-arm64`, `linux-x64` and `windows-x64`, built for iOS + 16.4 and macOS 13.3 or newer. At run time the engine checks the CPU before + loading the library: Android needs an Armv8.2 CPU with dot-product and fp16 + (`asimddp`, `fphp`, `asimdhp`), and Linux and Windows x64 need AVX2, FMA, + F16C and BMI2. Otherwise `ImageGenerationEngine.load` throws + `LlamaUnsupportedException` instead of crashing on an illegal + instruction. On Windows the runtime also needs the Microsoft Visual C++ + 2015-2022 Redistributable (x64); stock Windows Server lacks it, and the + error names the DLL that failed to load. - Apple builds use the Metal build and Android the CPU build. Linux and Windows publish a CPU build (about 38 MB) and a Vulkan build (about 72 MB) that needs the system Vulkan loader (`libvulkan.so.1` or `vulkan-1.dll`) at run time. @@ -110,10 +118,13 @@ hooks: # windows: [cpu] ``` - It accepts `cpu` and `vulkan` and leaves the llama.cpp backends unchanged. - Without it, the build follows `llamadart_native_backends` for the same + It accepts `cpu` and `vulkan` (alias `vk`) and leaves the llama.cpp + backends unchanged. A list naming `vulkan` selects the Vulkan build even + when it also names `cpu`. Without an entry for the platform, or with an + empty one, the build follows `llamadart_native_backends` for the same platform: Vulkan when Vulkan is selected there, which is the default, and - CPU otherwise. + CPU otherwise. A value naming neither `cpu` nor `vulkan` is ignored with a + build warning and the same fallback applies. - Other targets, such as `android-x64` or Windows arm64, are skipped with a warning. Naming it for that exact bundle key, for example `android-x64: [stable_diffusion]`, fails the build instead. diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index ccd6705c7..15f86340b 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -12,16 +12,21 @@ runtime out of the app, see [Native runtime configuration](./native-build-hooks) ## At a glance -| Platform | GGUF backends | LiteRT-LM backends | Minimum OS | Speech to text | Text to speech | Decision models | Status | -| --- | --- | --- | --- | --- | --- | --- | --- | -| Android (arm64, x64) | CPU, Vulkan; OpenCL opt-in | CPU, GPU, NPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | Supported | -| iOS (arm64, arm64 simulator, x86_64 simulator) | CPU, Metal | CPU, GPU; none on the x86_64 simulator | iOS 16.4 | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | Supported | -| macOS (arm64, x86_64) | CPU, Metal | arm64: CPU, GPU; x86_64: CPU | macOS 14.0 (Flutter) | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Validated on Metal and CPU | Supported | -| Linux (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA, HIP opt-in | arm64: CPU; x64: CPU, explicit GPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | Supported | -| Windows (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA opt-in | x64: CPU, explicit GPU; arm64: none | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR on x64 | Qwen3-TTS | Untested | Supported | -| Web | WebGPU, WebAssembly CPU | CPU, GPU through `@litert-lm/core` | Chrome 128, Firefox 129, Safari 17.4 | Qwen3-ASR, WAV, MP3 or FLAC bytes, bridge `v0.1.30+` | Qwen3-TTS, bridge `v0.1.33+`, memory64 | Bridge `v0.1.47+`; checked in headless Chromium on macOS | Experimental | +| Platform | GGUF backends | LiteRT-LM backends | Minimum OS | Speech to text | Text to speech | Decision models | Image generation | Status | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| Android (arm64, x64) | CPU, Vulkan; OpenCL opt-in | CPU, GPU, NPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | arm64 CPU; validated on Pixel 9 Pro, Galaxy S24 and A53 | Supported | +| iOS (arm64, arm64 simulator, x86_64 simulator) | CPU, Metal | CPU, GPU; none on the x86_64 simulator | iOS 16.4 | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | Metal, iOS 16.4; arm64 only; validated on iPhone 16 Pro and SE 3 | Supported | +| macOS (arm64, x86_64) | CPU, Metal | arm64: CPU, GPU; x86_64: CPU | macOS 14.0 (Flutter) | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Validated on Metal and CPU | Metal, macOS 13.3; validated on arm64 | Supported | +| Linux (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA, HIP opt-in | arm64: CPU; x64: CPU, explicit GPU | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR | Qwen3-TTS | Untested | CPU or Vulkan; x64 needs AVX2; validated on x64 (CPU, NVIDIA L4) | Supported | +| Windows (arm64, x64) | CPU, Vulkan; BLAS opt-in; x64: CUDA opt-in | x64: CPU, explicit GPU; arm64: none | Not set by llamadart | Qwen3-ASR (GGUF); LiteRT-LM ASR on x64 | Qwen3-TTS | Untested | x64 CPU or Vulkan, needs AVX2 and the Visual C++ runtime; validated on Windows Server 2022 (CPU, NVIDIA L4) | Supported | +| Web | WebGPU, WebAssembly CPU | CPU, GPU through `@litert-lm/core` | Chrome 128, Firefox 129, Safari 17.4 | Qwen3-ASR, WAV, MP3 or FLAC bytes, bridge `v0.1.30+` | Qwen3-TTS, bridge `v0.1.33+`, memory64 | Bridge `v0.1.47+`; checked in headless Chromium on macOS | No | Experimental | -Speech to text, text to speech and decision models are experimental. GGUF +Speech to text, text to speech, decision models and image generation are +experimental. Image generation needs the opt-in `stable_diffusion` runtime, +built for iOS 16.4 and macOS 13.3; x64 Linux and Windows CPUs need AVX2, FMA, +F16C and BMI2, Windows needs the Microsoft Visual C++ 2015-2022 +Redistributable (x64), and Android arm64 needs dot-product and fp16. See +[Image generation](../guides/image-generation#support). GGUF Qwen3-ASR accepts WAV, MP3 and FLAC; real-model checks cover all three on native macOS and in headless Chromium. LiteRT-LM ASR is CPU-only streaming recognition. Decision models run on llama.cpp and WebGPU only; on LiteRT-LM @@ -104,7 +109,7 @@ thinking-budget and speculative decoding rows for the loaded model. Guides: | --- | --- | | llama.cpp native | `leehack/llamadart-native@v0.5.0` | | LiteRT-LM native | `leehack/litert-lm-native@v0.17.0-6` | -| stable-diffusion.cpp native (opt-in, experimental) | `leehack/stable-diffusion-native@v0.1.1`; see [Opt-in stable_diffusion runtime](./native-build-hooks#opt-in-stable_diffusion-runtime-experimental) | +| stable-diffusion.cpp native (opt-in, experimental) | `leehack/stable-diffusion-native@v0.1.1`, for [image generation](../guides/image-generation); see [Opt-in stable_diffusion runtime](./native-build-hooks#opt-in-stable_diffusion-runtime-experimental) | | 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 diff --git a/website/sidebars.json b/website/sidebars.json index 57fc5e802..36d113796 100644 --- a/website/sidebars.json +++ b/website/sidebars.json @@ -42,6 +42,7 @@ "guides/multimodal", "guides/speech-to-text", "guides/text-to-speech", + "guides/image-generation", "guides/decision-models", "guides/lora-adapters" ]