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: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) |
Expand Down
7 changes: 7 additions & 0 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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
Expand Down
64 changes: 64 additions & 0 deletions example/basic_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
131 changes: 131 additions & 0 deletions example/basic_app/bin/llamadart_image_example.dart
Original file line number Diff line number Diff line change
@@ -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<void> main(List<String> 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<ProcessSignal>? 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<String> _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;
}
3 changes: 3 additions & 0 deletions example/basic_app/dart_test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
tags:
local-only:
skip: "Needs local model files. Use: dart test --run-skipped -t local-only"
Loading
Loading