Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## Unreleased

- With `llamadart_litert_lm_flutter` `0.0.15`, the Flutter macOS build now
only warns to upgrade the companion to `0.0.16`, the release pinning
`v0.18.0-1`, instead of claiming that the app cannot load LiteRT-LM and needs
the build phase; the app already loads the companion's runtime from its
bundle ([#1064](https://github.com/leehack/llamadart/issues/1064)).

## 0.12.2

- Pair this release with Apple companions `llamadart_llama_cpp_flutter`
Expand Down
105 changes: 72 additions & 33 deletions hook/build.dart
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ void main(List<String> args) async {
);
final appleSpmRuntimes = appleCompanions?.runtimes;
final stableDiffusionCompanion = appleCompanions?.stableDiffusion ?? false;
final liteRtLmMacOsCompanionGap = appleCompanions?.liteRtLmMacOsGap;
final liteRtLmMacOsCompanionWarning = appleCompanions?.liteRtLmMacOsWarning;
final configuredRuntimes = selectNativeRuntimesForBundle(
bundle: spec.bundle,
rawUserConfig: rawNativeRuntimeConfig,
Expand Down Expand Up @@ -346,7 +346,7 @@ void main(List<String> args) async {
includeLlamaCpp: selectedRuntimes.contains(nativeRuntimeLlamaCpp),
includeLiteRtLm: selectedRuntimes.contains(nativeRuntimeLiteRtLm),
appleSpmRuntimes: appleSpmRuntimes,
liteRtLmMacOsCompanionGap: liteRtLmMacOsCompanionGap,
liteRtLmMacOsCompanionWarning: liteRtLmMacOsCompanionWarning,
rawNativeRuntimeConfig: rawNativeRuntimeConfig,
hasNativeSourceOverride: _hasNativeSourceOverride(input.userDefines),
hasNativeBackendOverride:
Expand Down Expand Up @@ -547,7 +547,7 @@ Future<List<String>?> _emitAppleSpmAssetsIfEnabled({
required bool includeLlamaCpp,
required bool includeLiteRtLm,
required List<String>? appleSpmRuntimes,
required String? liteRtLmMacOsCompanionGap,
required String? liteRtLmMacOsCompanionWarning,
required Object? rawNativeRuntimeConfig,
required bool hasNativeSourceOverride,
required bool hasNativeBackendOverride,
Expand Down Expand Up @@ -600,15 +600,9 @@ Future<List<String>?> _emitAppleSpmAssetsIfEnabled({
handledRuntimes.add(nativeRuntimeLlamaCpp);
}
if (includeLiteRtLm) {
if (code.targetOS == OS.macOS && liteRtLmMacOsCompanionGap != null) {
final fallback =
'The resolved $_liteRtLmFlutterPackageName does not link the '
'complete macOS LiteRT-LM runtime ($liteRtLmMacOsCompanionGap), so '
'LiteRT-LM stays in the hook cache, which a sandboxed or relocated '
'app cannot load. Upgrade $_liteRtLmFlutterPackageName together '
'with $_packageName.';
log.warning(fallback);
stderr.writeln('warning: llamadart: $fallback');
if (code.targetOS == OS.macOS && liteRtLmMacOsCompanionWarning != null) {
log.warning(liteRtLmMacOsCompanionWarning);
stderr.writeln('warning: llamadart: $liteRtLmMacOsCompanionWarning');
} else {
log.info(
'LiteRT-LM will resolve symbols from the SPM-linked process image.',
Expand All @@ -632,12 +626,12 @@ bool _isAppleTarget(OS os) => os == OS.iOS || os == OS.macOS;
/// companion is a dependency and those families come from the hook.
/// [stableDiffusion] is decided on its own, so adding only the
/// stable_diffusion companion never moves llama_cpp or litert_lm off the hook.
/// [liteRtLmMacOsGap] says why a macOS LiteRT-LM companion cannot supply the
/// runtime, or is `null` when it can or the build is not macOS LiteRT-LM.
/// [liteRtLmMacOsWarning] says how a macOS LiteRT-LM companion does not match
/// this core, or is `null` when it does or the build is not macOS LiteRT-LM.
typedef _AppleCompanions = ({
List<String>? runtimes,
bool stableDiffusion,
String? liteRtLmMacOsGap,
String? liteRtLmMacOsWarning,
});

/// The companions of a Flutter iOS/macOS app build, or `null` for every other
Expand Down Expand Up @@ -689,15 +683,18 @@ _AppleCompanions? _flutterAppleCompanions({

final dependencies = _pubspecDependencyNames(pubspecSource);
final runtimes = <String>[];
String? liteRtLmMacOsGap;
String? liteRtLmMacOsWarning;
if (dependencies.contains(_llamaCppFlutterPackageName)) {
_validateAppleCompanion(_llamaCppCompanion, consumerRoot, output, log);
runtimes.add(nativeRuntimeLlamaCpp);
}
if (dependencies.contains(_liteRtLmFlutterPackageName)) {
runtimes.add(nativeRuntimeLiteRtLm);
if (code.targetOS == OS.macOS) {
liteRtLmMacOsGap = _liteRtLmMacOsCompanionGap(consumerRoot, output);
liteRtLmMacOsWarning = _liteRtLmMacOsCompanionWarning(
consumerRoot,
output,
);
}
}
final stableDiffusion = dependencies.contains(
Expand All @@ -722,7 +719,7 @@ _AppleCompanions? _flutterAppleCompanions({
return (
runtimes: runtimes.isEmpty ? null : runtimes,
stableDiffusion: stableDiffusion,
liteRtLmMacOsGap: liteRtLmMacOsGap,
liteRtLmMacOsWarning: liteRtLmMacOsWarning,
);
}

Expand Down Expand Up @@ -932,10 +929,10 @@ Directory _resolvedCompanionRoot(
return Directory.fromUri(uri);
}

/// Why the resolved LiteRT-LM companion cannot supply the macOS runtime
/// through SwiftPM, or `null` when its manifest is the maintained one pinning
/// [liteRtLmReleaseTag].
String? _liteRtLmMacOsCompanionGap(
/// The build warning for a resolved LiteRT-LM companion that does not match
/// this core on macOS, or `null` when its manifest is the maintained one
/// pinning [liteRtLmReleaseTag].
String? _liteRtLmMacOsCompanionWarning(
Directory consumerRoot,
BuildOutputBuilder output,
) {
Expand All @@ -959,18 +956,16 @@ String? _liteRtLmMacOsCompanionGap(
output.dependencies.add(manifest.uri);
if (!manifest.existsSync()) gap('Package.swift is missing');
final source = manifest.readAsStringSync().replaceAll('\r\n', '\n');
final pins = RegExp(
final pinPattern = RegExp(
r'^let liteRtLmTag = "([^"\n]+)"$',
multiLine: true,
).allMatches(source).toList();
if (pins.length != 1 || pins.single.group(1) != liteRtLmReleaseTag) {
);
final pins = pinPattern.allMatches(source).toList();
if (pins.length != 1) {
gap('it does not pin leehack/litert-lm-native@$liteRtLmReleaseTag');
}
final template = source
.replaceFirst(
RegExp(r'^let liteRtLmTag = "[^"\n]+"$', multiLine: true),
'let liteRtLmTag = "PIN"',
)
.replaceFirst(pinPattern, 'let liteRtLmTag = "PIN"')
.replaceAll(
RegExp(r'checksum: "[0-9a-f]{64}"'),
'checksum: "CHECKSUM"',
Expand All @@ -979,14 +974,58 @@ String? _liteRtLmMacOsCompanionGap(
_liteRtLmCompanionManifestTemplateSha256) {
gap('its Package.swift is not the macOS-complete manifest');
}
return null;
final pin = pins.single.group(1)!;
if (pin == liteRtLmReleaseTag) return null;
if (_isEarlierLiteRtLmRebuild(pin)) {
return 'The resolved $_liteRtLmFlutterPackageName pins '
'leehack/litert-lm-native@$pin, an earlier build of this core\'s '
'LiteRT-LM release $liteRtLmReleaseTag. It still embeds its '
'complete macOS LiteRT-LM runtime, which the app loads from its '
'bundle. Upgrade $_liteRtLmFlutterPackageName to the release '
'pinning $liteRtLmReleaseTag.';
}
return 'The resolved $_liteRtLmFlutterPackageName pins '
'leehack/litert-lm-native@$pin rather than this core\'s '
'$liteRtLmReleaseTag, so LiteRT-LM stays in the hook cache. Upgrade '
'$_liteRtLmFlutterPackageName and $_packageName together to a '
'matching released pair.';
} on _CompanionGap catch (error) {
return error.reason;
return _liteRtLmIncompleteCompanionWarning(error.reason);
} on FileSystemException {
return 'its metadata could not be read';
return _liteRtLmIncompleteCompanionWarning(
'its metadata could not be read',
);
} on FormatException {
return 'the resolved package configuration is malformed';
return _liteRtLmIncompleteCompanionWarning(
'the resolved package configuration is malformed',
);
}
}

String _liteRtLmIncompleteCompanionWarning(String reason) =>
'The resolved $_liteRtLmFlutterPackageName does not link the complete '
'macOS LiteRT-LM runtime ($reason), so LiteRT-LM stays in the hook cache, '
'which a sandboxed or relocated app cannot load. Upgrade '
'$_liteRtLmFlutterPackageName together with $_packageName.';

/// Whether [pin] is an earlier build of this core's upstream LiteRT-LM
/// release: the same `vMAJOR.MINOR.PATCH` prefix as [liteRtLmReleaseTag]
/// with a lower wrapper rebuild counter, which a bare `vMAJOR.MINOR.PATCH`
/// has as 0. The native release manifest binds that prefix to one upstream
/// commit, so such a companion embeds the same LiteRT-LM release.
bool _isEarlierLiteRtLmRebuild(String pin) {
final tagPattern = RegExp(r'^(v\d+\.\d+\.\d+)(?:-([1-9]\d*))?$');
final core = tagPattern.firstMatch(liteRtLmReleaseTag);
final candidate = tagPattern.firstMatch(pin);
if (core == null || candidate == null || candidate[1] != core[1]) {
return false;
}
int? rebuild(RegExpMatch tag) => int.tryParse(tag[2] ?? '0');
final candidateRebuild = rebuild(candidate);
final coreRebuild = rebuild(core);
return candidateRebuild != null &&
coreRebuild != null &&
candidateRebuild < coreRebuild;
}

class _CompanionGap implements Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// swift-tools-version: 5.9
import Foundation
import PackageDescription

let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
let artifactsRoot = packageRoot.appendingPathComponent("Artifacts")
let liteRtLmTag = "v0.18.0"

func localArtifactPath(_ name: String) -> String? {
let path = artifactsRoot.appendingPathComponent(name).path
return FileManager.default.fileExists(atPath: path) ? "Artifacts/\(name)" : nil
}

func nativeRepoBinaryTarget(
name: String,
repository: String,
artifactName: String,
tag: String,
checksum: String
) -> Target {
if let path = localArtifactPath("\(name).xcframework") {
return .binaryTarget(name: name, path: path)
}
return .binaryTarget(
name: name,
url: "https://github.com/\(repository)/releases/download/\(tag)/\(artifactName)",
checksum: checksum
)
}

let package = Package(
name: "llamadart_litert_lm_flutter",
platforms: [
.iOS("16.4"),
.macOS("14.0")
],
products: [
.library(
name: "llamadart-litert-lm-flutter",
type: .dynamic,
targets: ["llamadart_litert_lm_flutter"]
)
],
targets: [
nativeRepoBinaryTarget(
name: "LiteRtLm",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRtLm-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "232c864fa72391b99de3251296771b0bd0f9456a4563088e1803323a2a67a328"
),
nativeRepoBinaryTarget(
name: "CLiteRTLM",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-CLiteRTLM-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "e73a08a5208fe6e26b1e4b38a3a67d07b2a9839a6c3df57b10b2f6d7ed513747"
),
nativeRepoBinaryTarget(
name: "CLiteRTLMMac",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-CLiteRTLMMac-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "9d122c2ddc776bd3b262849afa75c656daa200e3431efb829f3778b0cd185eac"
),
nativeRepoBinaryTarget(
name: "LiteRtMetalAccelerator",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRtMetalAccelerator-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "279a1dd0cb88c777093fc99dc03227d44390ea89aeb98dbf22876ae694941580"
),
nativeRepoBinaryTarget(
name: "LiteRtTopKMetalSampler",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRtTopKMetalSampler-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "ca9a079c3d91c41923e529c68aebfebb540cb65b2100787b035d433bcead7ce2"
),
nativeRepoBinaryTarget(
name: "LiteRt",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRt-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "87d90748f50ae6048fc7fc5b0de6f14470baef036258180cf52d68f1e031dbaf"
),
nativeRepoBinaryTarget(
name: "LiteRtTopKWebGpuSampler",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRtTopKWebGpuSampler-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "4370a377fc5d5b5e7f5d8b106add4df876e99a6c5c052578e2e48c9bd69e1b52"
),
nativeRepoBinaryTarget(
name: "LiteRtWebGpuAccelerator",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-LiteRtWebGpuAccelerator-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "8c5fbd141736f9ab6f6937a4481ddca6cc1259dbd3441cc12e0cf4de91ccf2a8"
),
nativeRepoBinaryTarget(
name: "WebgpuDawn",
repository: "leehack/litert-lm-native",
artifactName: "litert-lm-native-apple-WebgpuDawn-xcframework-\(liteRtLmTag).zip",
tag: liteRtLmTag,
checksum: "067cdfdcda01005ffff596f45f28c4093e59920a8f254219563f0462c18e2e3f"
),
.target(
name: "llamadart_litert_lm_flutter",
dependencies: [
.target(name: "LiteRtLm", condition: .when(platforms: [.iOS, .macOS])),
.target(name: "CLiteRTLM", condition: .when(platforms: [.iOS])),
.target(name: "CLiteRTLMMac", condition: .when(platforms: [.macOS])),
.target(name: "LiteRtMetalAccelerator", condition: .when(platforms: [.iOS])),
.target(name: "LiteRtTopKMetalSampler", condition: .when(platforms: [.iOS])),
.target(name: "LiteRt", condition: .when(platforms: [.macOS])),
.target(name: "LiteRtTopKWebGpuSampler", condition: .when(platforms: [.macOS])),
.target(name: "LiteRtWebGpuAccelerator", condition: .when(platforms: [.macOS])),
.target(name: "WebgpuDawn", condition: .when(platforms: [.macOS]))
],
linkerSettings: [
.unsafeFlags(["-Xlinker", "-reexport_framework", "-Xlinker", "LiteRtLm"], .when(platforms: [.iOS])),
.unsafeFlags(["-Xlinker", "-reexport_framework", "-Xlinker", "CLiteRTLM"], .when(platforms: [.iOS]))
]
)
]
)
Loading
Loading