From 615ed3dc40e5bf5d1b6d0a25605723aaaff9ef7c Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 07:05:40 -0400 Subject: [PATCH] fix: opt into image generation without dropping the default runtimes `llamadart_native_runtimes` replaces the default runtime families, and `stable_diffusion` is in no default, so the documented opt-in `[llama_cpp, stable_diffusion]` shipped no `litert_lm`. Add `llamadart_extra_runtimes`, which appends opt-in families to whatever `llamadart_native_runtimes` selects for the target. It takes the same list, `runtimes` and `platforms` shapes, accepts only opt-in runtimes, and fails the build on any other name. Every existing `llamadart_native_runtimes` value resolves as before. Docs, skills, the runtime's "not bundled" errors and the chat app now opt in through the new key. Closes #856 --- CHANGELOG.md | 5 + README.md | 7 +- example/basic_app/README.md | 4 + example/basic_app/pubspec.yaml | 5 +- example/chat_app/README.md | 7 +- example/chat_app/pubspec.yaml | 20 +- hook/build.dart | 12 +- .../stable_diffusion_runtime_io.dart | 2 +- .../stable_diffusion_runtime_stub.dart | 2 +- .../core/image/image_generation_engine.dart | 2 +- lib/src/hook/native_bundle_config.dart | 85 ++++-- skills/llamadart-flutter-app/SKILL.md | 5 +- skills/llamadart-image-generation/SKILL.md | 6 +- .../stable_diffusion_runtime_hook_test.dart | 42 ++- .../stable_diffusion_runtime_io_test.dart | 4 +- ...ook_stable_diffusion_integration_test.dart | 183 +++++++++++++ test/unit/hook/native_bundle_config_test.dart | 253 ++++++++++++++++++ website/docs/changelog/recent-releases.md | 5 + website/docs/guides/backend-selection.md | 2 +- website/docs/guides/image-generation.md | 7 +- website/docs/platforms/native-build-hooks.md | 23 +- 21 files changed, 614 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a91f9b8fb..65b777717 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ ## Unreleased +- Add the `llamadart_extra_runtimes` build-hook key. + `llamadart_extra_runtimes: [stable_diffusion]` opts into image generation + and keeps the default `llama_cpp` and `litert_lm` runtimes, which naming + `stable_diffusion` in `llamadart_native_runtimes` drops + ([#856](https://github.com/leehack/llamadart/issues/856)). - Update the default LiteRT-LM runtime to `leehack/litert-lm-native@v0.18.0` (upstream LiteRT-LM `v0.18.0`). On the macOS GPU backend the program cache of Qwen3 0.6B and Gemma 4 E2B no longer diff --git a/README.md b/README.md index 911f20c77..f24a6ee64 100644 --- a/README.md +++ b/README.md @@ -99,10 +99,13 @@ experimental and may change, and the runtime is opt-in. hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_extra_runtimes: [stable_diffusion] ``` - Keep `litert_lm` in the list if the app also loads `.litertlm` models. + The key adds to what `llamadart_native_runtimes` selects, so the default + `llama_cpp` and `litert_lm` runtimes stay. Naming `stable_diffusion` in + `llamadart_native_runtimes` bundles it too, but that list replaces the + defaults. - **Flutter iOS/macOS apps** should add the `llamadart_stable_diffusion_flutter` companion (see [Install](#install)), diff --git a/example/basic_app/README.md b/example/basic_app/README.md index 61eb6b756..6f69bba06 100644 --- a/example/basic_app/README.md +++ b/example/basic_app/README.md @@ -232,6 +232,10 @@ hooks: llamadart_native_runtimes: [llama_cpp, stable_diffusion] ``` +That list also leaves out `litert_lm`, which no example here loads. An app that +keeps the default runtimes sets `llamadart_extra_runtimes: [stable_diffusion]` +instead. + The first run downloads the runtime (40 to 70 MB) through the build hook. `ImageGenerationEngine.load` then downloads the files this example pins for the preset in `lib/services/image_cli_options.dart`, unless a flag names a diff --git a/example/basic_app/pubspec.yaml b/example/basic_app/pubspec.yaml index 89d3457ff..3b63b3326 100644 --- a/example/basic_app/pubspec.yaml +++ b/example/basic_app/pubspec.yaml @@ -21,5 +21,8 @@ dev_dependencies: hooks: user_defines: llamadart: - # The image example needs the opt-in stable_diffusion runtime. + # The image example needs the opt-in stable_diffusion runtime. Every + # example here loads GGUF, so this list also leaves out litert_lm; an + # app that keeps the default runtimes sets + # `llamadart_extra_runtimes: [stable_diffusion]` instead. llamadart_native_runtimes: [llama_cpp, stable_diffusion] diff --git a/example/chat_app/README.md b/example/chat_app/README.md index f16086963..f82736cd1 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -65,11 +65,12 @@ macOS `14.0` or newer first. This app bundles the `llama_cpp` and `litert_lm` native runtimes and declares both Apple companion packages so GGUF and `.litertlm` presets work on supported targets. It also opts into the experimental `stable_diffusion` runtime for the -image screen, which adds about 37 MB per iOS, macOS and Android arm64 target +image screen with `llamadart_extra_runtimes`, which keeps those defaults. The +runtime adds about 37 MB per iOS, macOS and Android arm64 target and 38 to 72 MB on Linux and Windows (CPU or Vulkan build; Vulkan by default), and declares `llamadart_stable_diffusion_flutter` so iOS and macOS link it -through SwiftPM. Android x64 has no `stable_diffusion` build and skips it with -a build warning; the Windows arm64 entry leaves it out. If you copy +through SwiftPM. Android x64 and Windows arm64 have no `stable_diffusion` build +and skip it with a build warning. If you copy this app and only ship GGUF models, set `llamadart_native_runtimes` to `[llama_cpp]` and keep only `llamadart_llama_cpp_flutter` to reduce bundle size. Flutter iOS/macOS apps should declare the companion package for every diff --git a/example/chat_app/pubspec.yaml b/example/chat_app/pubspec.yaml index 1b19ad331..c73d18300 100644 --- a/example/chat_app/pubspec.yaml +++ b/example/chat_app/pubspec.yaml @@ -57,16 +57,10 @@ hooks: user_defines: llamadart: # The chat example intentionally demonstrates both GGUF and .litertlm - # model flows, plus the opt-in stable_diffusion runtime for its image - # screen. On iOS and macOS the companion packages above link these - # runtimes through Swift Package Manager instead. android-x64 has no - # stable_diffusion build and skips it with a build warning; the entries - # below leave out what is not published. Smaller examples rely on the - # package defaults. - llamadart_native_runtimes: - runtimes: [llama_cpp, litert_lm, stable_diffusion] - platforms: - # No LiteRT-LM bundle for these targets, nor stable_diffusion for - # windows-arm64. - ios-x86_64-sim: [llama_cpp, stable_diffusion] - windows-arm64: [llama_cpp] + # model flows, which the package defaults bundle, plus the opt-in + # stable_diffusion runtime for its image screen. On iOS and macOS the + # companion packages above link these runtimes through Swift Package + # Manager instead. A target without a stable_diffusion or LiteRT-LM + # build (android-x64, windows-arm64) skips that runtime with a build + # warning. + llamadart_extra_runtimes: [stable_diffusion] diff --git a/hook/build.dart b/hook/build.dart index 3a4de49fa..7ac48894a 100644 --- a/hook/build.dart +++ b/hook/build.dart @@ -160,6 +160,7 @@ void main(List args) async { final pkgRoot = input.packageRoot.toFilePath(); final rawNativeRuntimeConfig = input.userDefines[nativeRuntimesUserDefineKey]; + final rawExtraRuntimeConfig = input.userDefines[extraRuntimesUserDefineKey]; final appleCompanions = _flutterAppleCompanions( input: input, code: code, @@ -171,6 +172,7 @@ void main(List args) async { final configuredRuntimes = selectNativeRuntimesForBundle( bundle: spec.bundle, rawUserConfig: rawNativeRuntimeConfig, + rawExtraConfig: rawExtraRuntimeConfig, warn: log.warning, ); var selectedRuntimes = appleSpmRuntimes == null @@ -217,10 +219,12 @@ void main(List args) async { )]; if (selectedRuntimes.contains(nativeRuntimeStableDiffusion) && stableDiffusionBundleSpec == null) { - if (nativeRuntimeNamedForExactBundle( - bundle: spec.bundle, - rawUserConfig: rawNativeRuntimeConfig, - runtime: nativeRuntimeStableDiffusion, + if ([rawNativeRuntimeConfig, rawExtraRuntimeConfig].any( + (rawConfig) => nativeRuntimeNamedForExactBundle( + bundle: spec.bundle, + rawUserConfig: rawConfig, + runtime: nativeRuntimeStableDiffusion, + ), )) { throw Exception( 'stable_diffusion runtime is not available for ${spec.bundle}.', 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 8cd51da68..bafc1c941 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_io.dart @@ -203,7 +203,7 @@ LlamaUnsupportedException stableDiffusionLoadFailure({ return LlamaUnsupportedException( 'stable_diffusion runtime is not bundled for $platform; add ' 'stable_diffusion to hooks.user_defines.llamadart.' - 'llamadart_native_runtimes$companionAdvice and rebuild.', + 'llamadart_extra_runtimes$companionAdvice and rebuild.', ); } if (_vulkanLoaderNames.any(detail.toLowerCase().contains)) { diff --git a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_stub.dart b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_stub.dart index 5727f5153..57b1f9c55 100644 --- a/lib/src/backends/stable_diffusion/stable_diffusion_runtime_stub.dart +++ b/lib/src/backends/stable_diffusion/stable_diffusion_runtime_stub.dart @@ -7,7 +7,7 @@ StableDiffusionRuntimeStatus probeStableDiffusionRuntime() { LlamaUnsupportedException( 'stable_diffusion runtime is not available on the web: it needs a ' 'native platform (Android arm64, iOS, macOS, Linux or Windows x64) with ' - 'stable_diffusion in llamadart_native_runtimes.', + 'stable_diffusion in llamadart_extra_runtimes.', ), ); } diff --git a/lib/src/core/image/image_generation_engine.dart b/lib/src/core/image/image_generation_engine.dart index 310ce7323..615ff0780 100644 --- a/lib/src/core/image/image_generation_engine.dart +++ b/lib/src/core/image/image_generation_engine.dart @@ -146,7 +146,7 @@ class ImageGenerationTask { /// 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 +/// `hooks.user_defines.llamadart.llamadart_extra_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]. diff --git a/lib/src/hook/native_bundle_config.dart b/lib/src/hook/native_bundle_config.dart index 7405a1a46..fb8aa609d 100644 --- a/lib/src/hook/native_bundle_config.dart +++ b/lib/src/hook/native_bundle_config.dart @@ -2,9 +2,10 @@ /// `hook/build.dart`. Pure decisions over already-discovered paths and /// already-decoded config: nothing here downloads, extracts, or emits assets. /// -/// [nativeRuntimesUserDefineKey] picks the runtime families to build; +/// [nativeRuntimesUserDefineKey] picks the runtime families to build and +/// [extraRuntimesUserDefineKey] adds opt-in families to that pick; /// [nativeBackendUserDefineKey] filters the split llama.cpp backend modules -/// within `llama_cpp`. Both scope by platform through a `platforms` map, or — +/// within `llama_cpp`. All scope by platform through a `platforms` map, or — /// kept for backward compatibility — a bare map already keyed by platform. /// /// Entry-point roles, deliberately not a call order `hook/build.dart` may @@ -57,6 +58,11 @@ const String nativePathUserDefineKey = 'llamadart_native_path'; /// [selectNativeRuntimesForBundle]. const String nativeRuntimesUserDefineKey = 'llamadart_native_runtimes'; +/// User-define key adding opt-in runtime families to whatever +/// [nativeRuntimesUserDefineKey] selects, so the defaults stay without being +/// restated. Decoded by [selectNativeRuntimesForBundle]. +const String extraRuntimesUserDefineKey = 'llamadart_extra_runtimes'; + /// The llama.cpp/GGUF runtime family; the only one with configurable backends. const String nativeRuntimeLlamaCpp = 'llama_cpp'; @@ -76,10 +82,14 @@ const List allNativeRuntimes = [ nativeRuntimeLiteRtLm, ]; +/// The opt-in runtime families, the only ones [extraRuntimesUserDefineKey] +/// accepts. +const List optInNativeRuntimes = [nativeRuntimeStableDiffusion]; + /// Every runtime family a config may name. const List supportedNativeRuntimes = [ ...allNativeRuntimes, - nativeRuntimeStableDiffusion, + ...optInNativeRuntimes, ]; /// Fallback families for config that names no runtimes. An explicit `none` @@ -562,20 +572,29 @@ List? parseRequestedBackends({ /// at all — an unsupported scalar at the *root* included — the fallback to /// [defaultNativeRuntimes] is silent when the key is unset or the config is /// platform-scoped, and a [warn] otherwise. +/// +/// [rawExtraConfig] (`llamadart_extra_runtimes`) then appends the +/// [optInNativeRuntimes] it names for [bundle] that the selection lacks. It +/// takes the same shapes, platform precedence and aliases, and `none` clears +/// it; unset, empty, or without an entry for [bundle] it adds nothing. Unlike +/// [rawUserConfig] it is strict: any other value, `all` and the default +/// families included, throws a [FormatException], because a dropped name there +/// would leave the app without a runtime it asked for. List selectNativeRuntimesForBundle({ required String bundle, required Object? rawUserConfig, + Object? rawExtraConfig, required void Function(String message) warn, }) { + final extras = _extraNativeRuntimesForBundle( + bundle: bundle, + rawExtraConfig: rawExtraConfig, + ); final parsed = _parseNativeRuntimeConfigForBundle( bundle: bundle, rawUserConfig: rawUserConfig, ); - if (parsed == null) { - return defaultNativeRuntimes; - } - - final invalid = parsed.invalid; + final invalid = parsed?.invalid ?? const []; if (invalid.isNotEmpty) { warn( 'Ignoring unknown native runtime(s) for $bundle: ${invalid.join(', ')}. ' @@ -583,7 +602,32 @@ List selectNativeRuntimesForBundle({ ); } - return parsed.runtimes; + final selected = parsed?.runtimes ?? defaultNativeRuntimes; + final added = extras.where((runtime) => !selected.contains(runtime)); + return added.isEmpty ? selected : [...selected, ...added]; +} + +List _extraNativeRuntimesForBundle({ + required String bundle, + required Object? rawExtraConfig, +}) { + final parsed = _parseNativeRuntimeConfigForBundle( + bundle: bundle, + rawUserConfig: rawExtraConfig, + optInOnly: true, + ); + if (parsed == null) { + return const []; + } + if (parsed.invalid.isNotEmpty) { + throw FormatException( + 'hooks.user_defines.llamadart.$extraRuntimesUserDefineKey names ' + '${parsed.invalid.join(', ')} for $bundle; it accepts only the opt-in ' + 'runtimes: ${optInNativeRuntimes.join(', ')}. Select ' + '${allNativeRuntimes.join(' and ')} with $nativeRuntimesUserDefineKey.', + ); + } + return parsed.explicit.toList(growable: false); } /// Whether [runtime] was named for [bundle], not implied by a default or by @@ -795,6 +839,7 @@ List selectBackendsForBundle({ _parseNativeRuntimeConfigForBundle({ required String bundle, required Object? rawUserConfig, + bool optInOnly = false, }) { if (rawUserConfig == null) { return null; @@ -803,7 +848,7 @@ _parseNativeRuntimeConfigForBundle({ if (rawUserConfig is String || rawUserConfig is List || rawUserConfig == false) { - return _parseRuntimeList(rawUserConfig); + return _parseRuntimeList(rawUserConfig, optInOnly: optInOnly); } final root = _toStringMap(rawUserConfig); @@ -829,15 +874,15 @@ _parseNativeRuntimeConfigForBundle({ if (platformValue is Map) { final platformMap = _toStringMap(platformValue); if (platformMap != null && platformMap.containsKey('runtimes')) { - return _parseRuntimeList(platformMap['runtimes']); + return _parseRuntimeList(platformMap['runtimes'], optInOnly: optInOnly); } - return _parseRuntimeList(platformValue); + return _parseRuntimeList(platformValue, optInOnly: optInOnly); } - return _parseRuntimeList(platformValue); + return _parseRuntimeList(platformValue, optInOnly: optInOnly); } if (globalValue != null) { - return _parseRuntimeList(globalValue); + return _parseRuntimeList(globalValue, optInOnly: optInOnly); } final hasRuntimeShape = @@ -1226,8 +1271,10 @@ List _parseBackendList(Object? value) { return result; } +/// With [optInOnly], a token naming anything but `none` or one of +/// [optInNativeRuntimes] is reported as invalid. ({List runtimes, List invalid, Set explicit}) -_parseRuntimeList(Object? value) { +_parseRuntimeList(Object? value, {bool optInOnly = false}) { final result = []; final invalid = []; final explicit = {}; @@ -1243,6 +1290,12 @@ _parseRuntimeList(Object? value) { } return; } + if (optInOnly && + normalized != 'none' && + !optInNativeRuntimes.contains(normalized)) { + invalid.add(token.trim()); + return; + } if (normalized == 'all') { for (final runtime in allNativeRuntimes) { if (!result.contains(runtime)) { @@ -1299,7 +1352,7 @@ _parseRuntimeList(Object? value) { if (value is Map) { final mapped = _toStringMap(value); if (mapped != null && mapped.containsKey('runtimes')) { - return _parseRuntimeList(mapped['runtimes']); + return _parseRuntimeList(mapped['runtimes'], optInOnly: optInOnly); } } diff --git a/skills/llamadart-flutter-app/SKILL.md b/skills/llamadart-flutter-app/SKILL.md index 4a515121e..ac1e942fc 100644 --- a/skills/llamadart-flutter-app/SKILL.md +++ b/skills/llamadart-flutter-app/SKILL.md @@ -142,8 +142,9 @@ or shipping runtimes the app does not use. user-defines do not change SwiftPM binaries either. The stable_diffusion companion is independent: it selects image generation on iOS and macOS and leaves llama.cpp and LiteRT-LM where they were. -- Image generation (`ImageGenerationEngine`) needs `stable_diffusion` added - to `llamadart_native_runtimes`; it is never bundled by default. On iOS and +- Image generation (`ImageGenerationEngine`) needs + `llamadart_extra_runtimes: [stable_diffusion]`, which keeps the default + runtimes; it is never bundled by default. On iOS and macOS add `llamadart_stable_diffusion_flutter` instead, since App Store Connect rejects the iOS framework the hook bundles. Details are in the llamadart-image-generation skill. diff --git a/skills/llamadart-image-generation/SKILL.md b/skills/llamadart-image-generation/SKILL.md index 375759d99..b31d7f01b 100644 --- a/skills/llamadart-image-generation/SKILL.md +++ b/skills/llamadart-image-generation/SKILL.md @@ -26,10 +26,12 @@ description: >- hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_extra_runtimes: [stable_diffusion] ``` - Keep `litert_lm` in the list if the app also loads `.litertlm` models. Run + The key adds to what `llamadart_native_runtimes` selects, so the default + `llama_cpp` and `litert_lm` stay; naming `stable_diffusion` in + `llamadart_native_runtimes` instead replaces the defaults. 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. diff --git a/test/integration/stable_diffusion_runtime_hook_test.dart b/test/integration/stable_diffusion_runtime_hook_test.dart index e56010801..0ae7be428 100644 --- a/test/integration/stable_diffusion_runtime_hook_test.dart +++ b/test/integration/stable_diffusion_runtime_hook_test.dart @@ -15,7 +15,7 @@ import 'package:test/test.dart'; void main() { test('opting in bundles a runtime that loads and lists devices', () async { final status = await _probeConsumer( - runtimesDefine: const ['llama_cpp', 'stable_diffusion'], + define: 'llamadart_native_runtimes: [llama_cpp, stable_diffusion]', ); expect(status['available'], isTrue, reason: '$status'); @@ -32,8 +32,23 @@ void main() { expect(devices, contains(startsWith('MTL'))); }); + test('llamadart_extra_runtimes bundles it beside the default ' + 'runtimes', () async { + final status = await _probeConsumer( + define: 'llamadart_extra_runtimes: [stable_diffusion]', + ); + + expect(status['available'], isTrue, reason: '$status'); + expect( + status['hookLog'], + contains( + 'Selected native runtimes: llama_cpp, litert_lm, stable_diffusion.', + ), + ); + }); + test('without opting in the runtime is reported as not bundled', () async { - final status = await _probeConsumer(runtimesDefine: null); + final status = await _probeConsumer(define: null); expect(status['available'], isFalse); expect( @@ -43,19 +58,18 @@ void main() { }); } -Future> _probeConsumer({ - required List? runtimesDefine, -}) async { +/// The probe's status for a consumer whose `hooks.user_defines.llamadart` +/// holds [define], plus the llamadart hook's output under `hookLog`. +Future> _probeConsumer({required String? define}) async { final consumer = await Directory.systemTemp.createTemp('llamadart-sd-hook-'); addTearDown(() => consumer.delete(recursive: true)); - final hooks = runtimesDefine == null + final hooks = define == null ? '' : ''' hooks: user_defines: llamadart: - llamadart_native_runtimes: - runtimes: [${runtimesDefine.join(', ')}] + $define '''; await File(path.join(consumer.path, 'pubspec.yaml')).writeAsString(''' name: llamadart_sd_hook_consumer @@ -95,7 +109,17 @@ void main() { final line = LineSplitter.split( output, ).singleWhere((line) => line.startsWith('SD_PROBE ')); - return jsonDecode(line.substring('SD_PROBE '.length)) as Map; + final hookLog = + Directory( + path.join(consumer.path, '.dart_tool', 'hooks_runner', 'llamadart'), + ) + .listSync(recursive: true) + .whereType() + .where((file) => path.basename(file.path) == 'stdout.txt'); + return { + ...jsonDecode(line.substring('SD_PROBE '.length)) as Map, + 'hookLog': hookLog.map((file) => file.readAsStringSync()).join(), + }; } Future _expectSuccess( 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 312fa41c4..67febda9a 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 @@ -228,7 +228,7 @@ void main() { 'message', allOf( contains('stable_diffusion runtime is not bundled for linux-x64'), - contains('llamadart_native_runtimes'), + contains('llamadart_extra_runtimes'), ), ), ); @@ -308,7 +308,7 @@ void main() { message, allOf( contains('not bundled for $platform'), - contains('llamadart_native_runtimes'), + contains('llamadart_extra_runtimes'), contains('llamadart_stable_diffusion_flutter'), ), reason: platform, diff --git a/test/unit/hook/build_hook_stable_diffusion_integration_test.dart b/test/unit/hook/build_hook_stable_diffusion_integration_test.dart index 09ce70d0a..61ab32f84 100644 --- a/test/unit/hook/build_hook_stable_diffusion_integration_test.dart +++ b/test/unit/hook/build_hook_stable_diffusion_integration_test.dart @@ -15,6 +15,7 @@ import '../../../hook/build.dart' as build_hook; const _stableDiffusionAssetId = 'package:llamadart/stable_diffusion'; const _primaryAssetId = 'package:llamadart/llamadart'; +const _liteRtLmAssetIdPrefix = 'package:llamadart/litert_lm_'; void main() { final nativeBundlesRoot = '.dart_tool/llamadart/native_bundles/$llamaCppTag'; @@ -43,6 +44,13 @@ void main() { 'libggml-cpu.so', ], 'macos-arm64': const ['libllamadart.dylib'], + 'windows-arm64': const [ + 'llamadart-windows-arm64.dll', + 'llama-windows-arm64.dll', + 'ggml-windows-arm64.dll', + 'ggml-base-windows-arm64.dll', + 'ggml-cpu-windows-arm64.dll', + ], }; final stableDiffusionBundles = { for (final spec in stableDiffusionBundleSpecs) @@ -130,6 +138,181 @@ void main() { } }); + test('llamadart_extra_runtimes adds stable_diffusion to whatever ' + 'llamadart_native_runtimes selects', () async { + for (final (defines, bundlesLiteRtLm) in <(Map, bool)>[ + ( + { + 'llamadart_extra_runtimes': ['stable_diffusion'], + }, + true, + ), + ( + { + 'llamadart_native_runtimes': ['all'], + 'llamadart_extra_runtimes': 'stable-diffusion', + }, + true, + ), + ( + { + 'llamadart_native_runtimes': ['llama_cpp'], + 'llamadart_extra_runtimes': ['stable_diffusion'], + }, + false, + ), + ( + { + 'llamadart_native_runtimes': ['llama_cpp', 'stable_diffusion'], + }, + false, + ), + ]) { + await testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.linux, + targetArchitecture: Architecture.x64, + userDefines: _userDefines(defines), + check: (_, output) { + final ids = _codeAssetIds(output); + expect( + ids, + containsAll([_primaryAssetId, _stableDiffusionAssetId]), + reason: '$defines', + ); + expect( + ids.any((id) => id.startsWith(_liteRtLmAssetIdPrefix)), + bundlesLiteRtLm, + reason: '$defines', + ); + }, + ); + } + }); + + test('llamadart_extra_runtimes leaves out what a target does not ' + 'publish', () async { + await testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.windows, + targetArchitecture: Architecture.arm64, + userDefines: _userDefines({ + 'llamadart_extra_runtimes': ['stable_diffusion'], + }), + check: (_, output) { + final ids = _codeAssetIds(output); + expect(ids, contains(_primaryAssetId)); + expect(ids, isNot(contains(_stableDiffusionAssetId))); + expect(ids.any((id) => id.startsWith(_liteRtLmAssetIdPrefix)), isFalse); + }, + ); + + await testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.android, + targetArchitecture: Architecture.x64, + targetAndroidNdkApi: 30, + userDefines: _userDefines({ + 'llamadart_native_runtimes': ['llama_cpp'], + 'llamadart_extra_runtimes': { + 'platforms': { + 'android': ['stable_diffusion'], + }, + }, + }), + check: (_, output) { + expect(_codeAssetIds(output), isNot(contains(_stableDiffusionAssetId))); + expect(_codeAssetIds(output), contains(_primaryAssetId)); + }, + ); + + var emitted = false; + await expectLater( + testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.android, + targetArchitecture: Architecture.x64, + targetAndroidNdkApi: 30, + userDefines: _userDefines({ + 'llamadart_native_runtimes': ['llama_cpp'], + 'llamadart_extra_runtimes': { + 'platforms': { + 'android-x64': ['stable_diffusion'], + }, + }, + }), + check: (_, _) => emitted = true, + ), + throwsA( + predicate( + (error) => error.toString().contains( + 'stable_diffusion runtime is not available for android-x64', + ), + ), + ), + ); + expect(emitted, isFalse); + }); + + test('llamadart_extra_runtimes fails the build on a name that is not an ' + 'opt-in runtime', () async { + for (final extra in const [ + ['stable_diffusion', 'onnx'], + 'all', + ['litert_lm'], + ]) { + var emitted = false; + await expectLater( + testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.linux, + targetArchitecture: Architecture.x64, + userDefines: _userDefines({'llamadart_extra_runtimes': extra}), + check: (_, _) => emitted = true, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + contains('llamadart_extra_runtimes'), + contains('stable_diffusion'), + ), + ), + ), + reason: '$extra', + ); + expect(emitted, isFalse, reason: '$extra'); + } + }); + + test('llamadart_extra_runtimes still selects stable_diffusion when Apple ' + 'companions choose the other runtimes', () async { + final defines = await _flutterAppleApp( + companions: const [_llamaCppCompanionName], + defines: { + 'llamadart_extra_runtimes': ['stable_diffusion'], + }, + ); + await testCodeBuildHook( + mainMethod: build_hook.main, + targetOS: OS.iOS, + targetArchitecture: Architecture.arm64, + targetIOSSdk: IOSSdk.iPhoneOS, + userDefines: defines, + check: (_, output) { + expect(_codeAssetIds(output), { + _primaryAssetId, + _stableDiffusionAssetId, + }); + expect( + _stableDiffusionAsset(output).linkMode, + isA(), + ); + }, + ); + }); + test('Linux bundles the Vulkan archive with default backends', () async { await testCodeBuildHook( mainMethod: build_hook.main, diff --git a/test/unit/hook/native_bundle_config_test.dart b/test/unit/hook/native_bundle_config_test.dart index 278ea0c4d..2aa17bd70 100644 --- a/test/unit/hook/native_bundle_config_test.dart +++ b/test/unit/hook/native_bundle_config_test.dart @@ -1022,6 +1022,259 @@ void main() { }); }); + group('llamadart_extra_runtimes', () { + const bundles = [ + 'android-arm64', + 'android-x64', + 'ios-arm64', + 'ios-arm64-sim', + 'ios-x86_64-sim', + 'linux-arm64', + 'linux-x64', + 'macos-arm64', + 'macos-x86_64', + 'windows-arm64', + 'windows-x64', + ]; + + List select( + Object? rawUserConfig, + Object? rawExtraConfig, { + String bundle = 'linux-x64', + List? warnings, + }) => selectNativeRuntimesForBundle( + bundle: bundle, + rawUserConfig: rawUserConfig, + rawExtraConfig: rawExtraConfig, + warn: (warnings ?? []).add, + ); + + test('opting in keeps the default runtimes on every bundle', () { + for (final bundle in bundles) { + final warnings = []; + expect( + select( + null, + const ['stable_diffusion'], + bundle: bundle, + warnings: warnings, + ), + [...defaultNativeRuntimes, nativeRuntimeStableDiffusion], + reason: bundle, + ); + expect(warnings, isEmpty, reason: bundle); + } + }); + + test('adds to an explicit list, an exclusion and none', () { + const extra = ['stable_diffusion']; + for (final (rawUserConfig, expected) in const <(Object?, List)>[ + ('all', ['llama_cpp', 'litert_lm', 'stable_diffusion']), + ([], ['llama_cpp', 'litert_lm', 'stable_diffusion']), + (['llama_cpp'], ['llama_cpp', 'stable_diffusion']), + (['litert_lm'], ['litert_lm', 'stable_diffusion']), + (['stable_diffusion', 'llama_cpp'], ['stable_diffusion', 'llama_cpp']), + ('none', ['stable_diffusion']), + ( + { + 'runtimes': ['llama_cpp', 'litert_lm'], + 'platforms': { + 'linux': ['litert_lm'], + }, + }, + ['litert_lm', 'stable_diffusion'], + ), + ]) { + expect( + select(rawUserConfig, extra), + expected, + reason: '$rawUserConfig', + ); + } + }); + + test('adds nothing when unset, empty or cleared', () { + for (final rawUserConfig in const [ + null, + ['llama_cpp'], + ['llama_cpp', 'stable_diffusion'], + 'none', + ]) { + final expected = selectNativeRuntimesForBundle( + bundle: 'linux-x64', + rawUserConfig: rawUserConfig, + warn: (_) {}, + ); + for (final rawExtraConfig in const [ + null, + '', + [], + 'none', + false, + ['stable_diffusion', 'none'], + {'runtimes': []}, + { + 'platforms': { + 'android': ['stable_diffusion'], + }, + }, + { + 'runtimes': ['stable_diffusion'], + 'platforms': {'linux-x64': 'none'}, + }, + ]) { + expect( + select(rawUserConfig, rawExtraConfig), + expected, + reason: '$rawUserConfig + $rawExtraConfig', + ); + } + } + }); + + test('accepts the shapes and aliases of llamadart_native_runtimes', () { + for (final rawExtraConfig in const [ + 'stable_diffusion', + ' Stable-Diffusion ', + ['none', 'stable_diffusion'], + {'runtimes': 'stable_diffusion'}, + { + 'platforms': { + 'linux': ['stable_diffusion'], + }, + }, + { + 'runtimes': 'none', + 'platforms': { + 'linux-x64': { + 'runtimes': ['stable_diffusion'], + }, + }, + }, + ]) { + expect(select(null, rawExtraConfig), [ + ...defaultNativeRuntimes, + nativeRuntimeStableDiffusion, + ], reason: '$rawExtraConfig'); + } + }); + + test('scopes by platform with the exact bundle before its OS', () { + const rawExtraConfig = { + 'platforms': { + 'android': ['stable_diffusion'], + 'android-x64': 'none', + 'macos': ['stable_diffusion'], + }, + }; + final optedIn = { + for (final bundle in bundles) + bundle: select( + null, + rawExtraConfig, + bundle: bundle, + ).contains(nativeRuntimeStableDiffusion), + }; + expect(optedIn, { + for (final bundle in bundles) + bundle: const { + 'android-arm64', + 'macos-arm64', + 'macos-x86_64', + }.contains(bundle), + }); + expect( + nativeRuntimeNamedForExactBundle( + bundle: 'android-x64', + rawUserConfig: const { + 'platforms': { + 'android-x64': ['stable_diffusion'], + }, + }, + runtime: nativeRuntimeStableDiffusion, + ), + isTrue, + ); + }); + + test('rejects every name that is not an opt-in runtime', () { + for (final (rawExtraConfig, rejected) in const <(Object, String)>[ + ('onnx', 'onnx'), + (['stable_diffusion', 'tflite', 'onnx'], 'tflite, onnx'), + ('all', 'all'), + (['both'], 'both'), + (['llama_cpp', 'stable_diffusion'], 'llama_cpp'), + ('litert', 'litert'), + (true, 'true'), + ([42], '42'), + ({'runtimes': 7}, '7'), + ( + { + 'platforms': { + 'linux-x64': ['sd'], + }, + }, + 'sd', + ), + ({'stable_diffusion': true}, '{stable_diffusion: true}'), + ]) { + expect( + () => select(null, rawExtraConfig), + throwsA( + isA().having( + (error) => error.message, + 'message', + allOf( + startsWith( + 'hooks.user_defines.llamadart.llamadart_extra_runtimes ' + 'names $rejected for linux-x64;', + ), + contains('opt-in runtimes: stable_diffusion.'), + contains( + 'Select llama_cpp and litert_lm with ' + 'llamadart_native_runtimes.', + ), + ), + ), + ), + reason: '$rawExtraConfig', + ); + } + }); + + test('an unknown llamadart_native_runtimes name is still a warning', () { + final warnings = []; + expect( + select( + const ['llama_cpp', 'onnx'], + const ['stable_diffusion'], + warnings: warnings, + ), + [nativeRuntimeLlamaCpp, nativeRuntimeStableDiffusion], + ); + expect( + warnings.single, + allOf( + contains('onnx'), + contains( + 'Supported runtimes: llama_cpp, litert_lm, stable_diffusion.', + ), + ), + ); + }); + + test('a name scoped to another platform is not validated here', () { + expect( + select(null, const { + 'platforms': { + 'android': ['onnx'], + }, + }), + defaultNativeRuntimes, + ); + }); + }); + group('stableDiffusionBundleForNativeBundle', () { NativeBundleSpec spec(OS os, Architecture arch, {bool sim = false}) => resolveNativeBundleSpec(os: os, arch: arch, isIosSimulator: sim)!; diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 1c52df376..2de1df275 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -9,6 +9,11 @@ For canonical full release notes, use: ## Unreleased +- Add the `llamadart_extra_runtimes` build-hook key. + `llamadart_extra_runtimes: [stable_diffusion]` opts into image generation + and keeps the default `llama_cpp` and `litert_lm` runtimes, which naming + `stable_diffusion` in `llamadart_native_runtimes` drops + ([#856](https://github.com/leehack/llamadart/issues/856)). - Update the default LiteRT-LM runtime to `leehack/litert-lm-native@v0.18.0` (upstream LiteRT-LM `v0.18.0`). On the macOS GPU backend the program cache of Qwen3 0.6B and Gemma 4 E2B no longer diff --git a/website/docs/guides/backend-selection.md b/website/docs/guides/backend-selection.md index 8a4fcdde5..d71b73e2c 100644 --- a/website/docs/guides/backend-selection.md +++ b/website/docs/guides/backend-selection.md @@ -236,4 +236,4 @@ 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, which [image generation](./image-generation) -needs, is never included unless named there. +needs, is included only when the app opts in with `llamadart_extra_runtimes`. diff --git a/website/docs/guides/image-generation.md b/website/docs/guides/image-generation.md index 29763f8ac..eb97a5635 100644 --- a/website/docs/guides/image-generation.md +++ b/website/docs/guides/image-generation.md @@ -72,15 +72,18 @@ engine's capabilities. ## 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: +default. Add it in the app's `pubspec.yaml`, then run `flutter clean` once: ```yaml hooks: user_defines: llamadart: - llamadart_native_runtimes: [llama_cpp, stable_diffusion] + llamadart_extra_runtimes: [stable_diffusion] ``` +The key adds to what `llamadart_native_runtimes` selects, so the default +`llama_cpp` and `litert_lm` runtimes stay. + 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 diff --git a/website/docs/platforms/native-build-hooks.md b/website/docs/platforms/native-build-hooks.md index c172d94fe..0958d9cf6 100644 --- a/website/docs/platforms/native-build-hooks.md +++ b/website/docs/platforms/native-build-hooks.md @@ -17,6 +17,7 @@ Configure the hook under `hooks.user_defines.llamadart` in the app's | Key | Selects | Default | | --- | --- | --- | | `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_extra_runtimes` | Opt-in runtime families added to that selection: `stable_diffusion` | None | | `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) | @@ -79,17 +80,24 @@ hooks: [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) runtime 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: +70 MB per target, so it is never bundled by default or by `all`/`both`. Add it +with `llamadart_extra_runtimes`, which keeps whatever +`llamadart_native_runtimes` selects, the defaults included: ```yaml hooks: user_defines: llamadart: - llamadart_native_runtimes: - runtimes: [llama_cpp, stable_diffusion] + llamadart_extra_runtimes: [stable_diffusion] ``` +- `llamadart_extra_runtimes` takes the same list, `runtimes` and `platforms` + shapes as `llamadart_native_runtimes`, and `none` adds nothing for a + platform. It accepts only opt-in runtimes: any other name, `all` and + `llama_cpp` included, fails the build. +- Naming `stable_diffusion` in `llamadart_native_runtimes` bundles it too, but + that list replaces the defaults: `[llama_cpp, stable_diffusion]` ships no + `litert_lm`. - Published for `android-arm64`, `ios-arm64`, `ios-arm64-sim`, `ios-x86_64-sim`, `macos-arm64`, `macos-x86_64`, `linux-arm64`, `linux-x64` and `windows-x64`, built for iOS @@ -127,8 +135,8 @@ hooks: 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. + warning. Naming it under that exact bundle key in either setting, for + example `android-x64: [stable_diffusion]`, fails the build instead. - Flutter iOS and macOS apps should add the `llamadart_stable_diffusion_flutter` companion instead; see [Flutter Apple apps](#flutter-apple-apps). Without it the hook bundles the runtime, and App Store Connect rejects that iOS @@ -298,7 +306,8 @@ When the llama.cpp or LiteRT-LM companion is present, the installed companions choose the Apple `llama_cpp` and `litert_lm` families and the rest of `llamadart_native_runtimes` is ignored with a warning. `stable_diffusion` is decided on its own: its companion selects it, and otherwise the hook bundles it -when `llamadart_native_runtimes` names it. Adding only the stable_diffusion +when `llamadart_extra_runtimes` or `llamadart_native_runtimes` names it. Adding +only the stable_diffusion companion leaves llama.cpp and LiteRT-LM on the hook. The build checks the resolved llama.cpp and stable_diffusion companions' pins against the core package and rejects local `Artifacts` overrides. The tag,