Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## Unreleased

- Add LFM3-Audio and Soprano speech output on native llama.cpp (`Lfm3AudioTtsAdapter`, `SopranoTtsAdapter`) and predefined voice selection (`TextToSpeechRequest.voice`, `TextToSpeechCapabilities.voices`); runtimes before llamadart-native v0.8.0 refuse them with `LlamaUnsupportedException` ([#1615](https://github.com/leehack/llamadart/issues/1615)).
- Update the default llama.cpp native runtime to `leehack/llamadart-native@v0.9.0` (llama.cpp `v0.9.0`). On ARM64 CPUs, F16 dot products of large values no longer overflow to inf or NaN ([llamadart-native#174](https://github.com/leehack/llamadart-native/issues/174)), and Qwen3-TTS sampling applies the GGUF's suppress tokens. Flutter Apple apps get it from `llamadart_llama_cpp_flutter` `0.19.0`, released with this core. Web keeps llama.cpp `v0.8.0` until a later bridge repin.
- Fix LiteRT-LM text-only or audio-only turns that failed with "Image history requires a vision encoder." after an image turn on the same engine ([#1781](https://github.com/leehack/llamadart/issues/1781)).
- Move Web LiteRT-LM to `@litert-lm/core@0.19.0`; WebGPU loads keep the runtime's default backend, so standard `.litertlm` bundles can load there. Web embeddings, tool loops, media and custom templates stay unsupported.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ experimental. Native targets need no network once the model is on the device.
- Streaming chat and text generation, with structured JSON output and cancellable task handles.
- Tool calling driven by the model's chat template.
- Embeddings, reranking, and image and audio input with multimodal models.
- Speech to text, text to speech, and decision models with cooperative task cancellation.
- Speech to text, text to speech (Qwen3-TTS; LFM3-Audio and Soprano on native), and decision models with cooperative task cancellation.
- Image generation from text prompts on native platforms (Preview).
- Runtime LoRA adapters for llama.cpp, observability hooks and typed capability checks.

Expand Down
18 changes: 17 additions & 1 deletion doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ Pick targeted rows based on the touched surface:
| Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` |
| Isolate shutdown releases, exit teardown, a Flutter pin bump, or app-exit guidance | `chat-app-macos-quit` |
| Speech-to-text API or adapter | `speech-to-text-smoke`, `web-speech-to-text-smoke`, plus `litert-lm-asr-smoke` and `litert-lm-asr-preservation` 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 |
| Text-to-speech API or adapter | `text-to-speech-smoke`, `text-to-speech-models-smoke` for LFM3-Audio and Soprano, plus `web-text-to-speech-smoke` for browser synthesis/playback/export |
| Decision engine, decision head, or safetensors reader | `decision-model-smoke`, plus `decision-model-web-smoke` for the Web decision head or bridge pin |
| Image generation API or `stable_diffusion` runtime | `image-generation-smoke`, `native-hook-bundles` |
| Complete image checkpoint formats or explicit role transport | `image-container-formats` (local hashed inputs and independent CPU references) |
Expand Down Expand Up @@ -447,6 +447,18 @@ dart run tool/testing/run_local_e2e.dart \
--scenario chat-app-web-text-to-speech-smoke \
[--audio-path /path/to/speaker-reference.wav]

# Each model whose two variables are set runs; the Qwen3-ASR pair checks that
# the speech transcribes back to its text. Soprano has no published GGUF:
# convert it as the text-to-speech guide describes. WAVs go to
# build/text-to-speech-models.
LLAMADART_TTS_LFM3_MODEL_PATH=/path/to/LFM3-Audio-2B-Q4_K_M.gguf \
LLAMADART_TTS_LFM3_MMPROJ_PATH=/path/to/mmproj-LFM3-Audio-2B-Q8_0.gguf \
LLAMADART_TTS_SOPRANO_MODEL_PATH=/path/to/soprano.gguf \
LLAMADART_TTS_SOPRANO_MMPROJ_PATH=/path/to/mmproj-soprano.gguf \
LLAMADART_STT_MODEL_PATH=/path/to/Qwen3-ASR-0.6B-Q8_0.gguf \
LLAMADART_STT_MMPROJ_PATH=/path/to/mmproj-Qwen3-ASR-0.6B-Q8_0.gguf \
dart run tool/testing/run_local_e2e.dart --scenario text-to-speech-models-smoke

# 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 cases, including
Expand Down Expand Up @@ -843,6 +855,10 @@ Raw C exit with live isolates remains a separately invocable diagnostic and
is excluded from Linux qualification. These subprocess checks do not prove
Flutter engine shutdown ordering.

On macOS, `EXIT_TEARDOWN_TTS_MODEL`, `EXIT_TEARDOWN_TTS_MMPROJ` and
`EXIT_TEARDOWN_TTS_ADAPTER` (`qwen3-tts`, `lfm3-audio` or `soprano`) add
`quit-speaking`, which calls C `exit` once synthesis has generated a frame.

On macOS, the row runs `test/fixtures/llama_cpp_exit_probe.dart` as a
child process and ends it while llama.cpp objects are alive on Metal: C `exit`
through FFI from the main isolate with a model idle, generating or loading;
Expand Down
5 changes: 5 additions & 0 deletions example/basic_app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ For model-free lifecycle ownership across text and attached speech engines, run
capabilities and closes dependants before their underlying engine. No weights
are loaded; normal Dart build hooks can still prepare native assets.

To synthesize a WAV file with Qwen3-TTS, LFM3-Audio or Soprano, run
`dart run bin/llamadart_text_to_speech_example.dart -m <model.gguf> -p
<mmproj.gguf> -a lfm3-audio --voice male`. It prints the listed voices; Ctrl-C
cancels the synthesis.

## Features

- **Interactive Mode**: Have a back-and-forth conversation with an LLM in your terminal.
Expand Down
89 changes: 89 additions & 0 deletions example/basic_app/bin/llamadart_text_to_speech_example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import 'dart:async';
import 'dart:io';

import 'package:args/args.dart';
import 'package:llamadart/llamadart.dart';

const Map<String, TextToSpeechAdapter> _adapters = {
'qwen3-tts': Qwen3TtsAdapter(),
'lfm3-audio': Lfm3AudioTtsAdapter(),
'soprano': SopranoTtsAdapter(),
};

Future<void> main(List<String> arguments) async {
final parser = ArgParser()
..addOption('model', abbr: 'm', help: 'Model GGUF path or URL.')
..addOption('projector', abbr: 'p', help: 'Projector GGUF path or URL.')
..addOption(
'adapter',
abbr: 'a',
allowed: _adapters.keys,
defaultsTo: 'qwen3-tts',
help: 'Model family.',
)
..addOption('text', abbr: 't', defaultsTo: 'Hello from llamadart.')
..addOption('voice', help: 'Predefined voice; see the listed voices.')
..addOption('language', help: 'Language, for models that take one.')
..addOption('temperature', help: 'Sampling temperature.')
..addOption('out', abbr: 'o', defaultsTo: 'speech.wav')
..addFlag('help', abbr: 'h', negatable: false);
final options = parser.parse(arguments);
final model = options['model'] as String?;
final projector = options['projector'] as String?;
if (options['help'] == true || model == null || projector == null) {
stdout.writeln(
'Usage: dart run bin/llamadart_text_to_speech_example.dart '
'-m <model.gguf> -p <mmproj.gguf> [options]\n${parser.usage}',
);
return;
}

final TextToSpeechEngine synthesizer;
try {
synthesizer = await TextToSpeechEngine.load(
TextToSpeechModel(
ModelSource.parse(model),
projector: ModelSource.parse(projector),
adapter: _adapters[options['adapter']]!,
),
);
} on LlamaUnsupportedException catch (error) {
stderr.writeln('Unsupported: ${error.message}');
exitCode = 1;
return;
}
StreamSubscription<ProcessSignal>? interrupt;
try {
final capabilities = await synthesizer.capabilities;
stdout.writeln(
'${synthesizer.adapter.name}: ${capabilities.sampleRateHz} Hz, '
'voices: ${capabilities.voices.isEmpty ? 'none listed' : capabilities.voices.join(', ')}',
);
final temperature = options['temperature'] as String?;
final task = await synthesizer.synthesize(
TextToSpeechRequest(
text: options['text'] as String,
voice: options['voice'] as String?,
language: options['language'] as String?,
temperature: temperature == null ? 0.8 : double.parse(temperature),
maxFrames: 1024,
),
);
interrupt = ProcessSignal.sigint.watch().listen((_) => task.cancel());
task.events.listen((event) {
if (event is TextToSpeechProgressEvent) {
stdout.write('\r${event.phase.name}: ${event.framesGenerated} frames');
}
});
final result = await task.result;
final output = options['out'] as String;
await File(output).writeAsBytes(result.toWavBytes());
stdout.writeln('\nWrote ${result.duration} to $output');
} on LlamaException catch (error) {
stderr.writeln('\nSynthesis failed or was cancelled: $error');
exitCode = 1;
} finally {
await interrupt?.cancel();
await synthesizer.dispose();
}
}
1 change: 1 addition & 0 deletions lib/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export 'src/backends/backend.dart'
BackendTextToSpeech,
BackendTextToSpeechCapabilities,
BackendTextToSpeechModel,
BackendTextToSpeechModelSupport,
BackendTextToSpeechPhase,
BackendTextToSpeechProgress,
BackendTextToSpeechRequest,
Expand Down
35 changes: 35 additions & 0 deletions lib/src/backends/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,12 @@ abstract class BackendGenerationUsageReporting {
enum BackendTextToSpeechModel {
/// Qwen3-TTS audio generation through llama.cpp mtmd.
qwen3Tts,

/// LFM3-Audio and LFM3-Omni speech output through llama.cpp mtmd.
lfm3Audio,

/// Soprano speech output through llama.cpp mtmd.
soprano,
}

/// Phase reported while a backend synthesizes speech.
Expand Down Expand Up @@ -625,6 +631,15 @@ class BackendTextToSpeechCapabilities {
/// Whether an active synthesis can be cancelled cooperatively.
final bool supportsCancellation;

/// Whether a predefined voice can be selected by name.
final bool supportsVoice;

/// The predefined voices, in the model's order; the first one speaks when
/// a request names none.
///
/// Empty when the model has no voices or the backend cannot list them.
final List<String> voices;

/// Creates a backend capability snapshot.
const BackendTextToSpeechCapabilities({
required this.isSupported,
Expand All @@ -635,6 +650,8 @@ class BackendTextToSpeechCapabilities {
this.supportsLanguage = false,
this.supportsSpeakerReference = false,
this.supportsCancellation = false,
this.supportsVoice = false,
this.voices = const <String>[],
});
}

Expand All @@ -652,6 +669,9 @@ class BackendTextToSpeechRequest {
/// Optional encoded reference-audio bytes.
final Uint8List? speakerAudioBytes;

/// Optional predefined voice name, or null for the model's default.
final String? voice;

/// Maximum number of audio-codec frames to generate.
final int maxFrames;

Expand Down Expand Up @@ -679,6 +699,7 @@ class BackendTextToSpeechRequest {
this.language,
this.speakerAudioPath,
this.speakerAudioBytes,
this.voice,
this.maxFrames = 512,
this.promptBatchSize = 512,
this.topK = 40,
Expand Down Expand Up @@ -739,6 +760,20 @@ class BackendTextToSpeechResult {
});
}

/// Optional backend probe for the text-to-speech models its runtime drives,
/// answered before a model loads.
///
/// `TextToSpeechEngine.load` asks it for the models its adapter accepts and
/// refuses the load when the runtime drives none of them, before downloading
/// or loading any file.
abstract class BackendTextToSpeechModelSupport {
/// Why the runtime cannot drive [model], or null when it can or cannot tell
/// without a loaded model. Must not load a model.
Future<String?> textToSpeechModelUnsupportedReason(
BackendTextToSpeechModel model,
);
}

/// Optional backend capability for dedicated text-to-speech synthesis.
abstract class BackendTextToSpeech {
/// Discovers support for the loaded context and multimodal projector.
Expand Down
68 changes: 68 additions & 0 deletions lib/src/backends/llama_cpp/library_loading.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ class _TtsApi {
final _TtsSetCancelFlagDart? setCancelFlag;
final ggml_backend_sched_eval_callback evalCallback;

// Model-type opt-in (llamadart-native v0.8.0). Older wrappers lack it and
// drive Qwen3-TTS only through the legacy calls.
final _TtsSupportedModelTypesDart? supportedModelTypes;
final _TtsGetInfoExtDart? getInfoExt;
final _TtsInitExtDart? initExt;
final _TtsStartWithVoiceDart? startWithVoice;

// Predefined-voice listing (llamadart-native v0.9.0).
final _TtsGetVoiceCountDart? getVoiceCount;
final _TtsGetVoiceNameDart? getVoiceName;

const _TtsApi({
required this.apiVersion,
required this.requestDefault,
Expand All @@ -33,12 +44,35 @@ class _TtsApi {
required this.lastError,
required this.setCancelFlag,
required this.evalCallback,
required this.supportedModelTypes,
required this.getInfoExt,
required this.initExt,
required this.startWithVoice,
required this.getVoiceCount,
required this.getVoiceName,
});

/// Whether the runtime has the whole model-type opt-in.
bool get hasModelTypeOptIn =>
supportedModelTypes != null &&
getInfoExt != null &&
initExt != null &&
startWithVoice != null;

/// Whether the runtime lists predefined voices.
bool get listsVoices => getVoiceCount != null && getVoiceName != null;

static _TtsApi? tryLoad(DynamicLibrary library) {
try {
const setCancelFlagSymbol = 'llama_dart_tts_set_cancel_flag';
const evalCallbackSymbol = 'llama_dart_tts_eval_callback';
bool has(String symbol) => library.providesSymbol(symbol);
const supportedModelTypesSymbol = 'llama_dart_tts_supported_model_types';
const getInfoExtSymbol = 'llama_dart_tts_get_info_ext';
const initExtSymbol = 'llama_dart_tts_init_ext';
const startWithVoiceSymbol = 'llama_dart_tts_start_with_voice';
const getVoiceCountSymbol = 'llama_dart_tts_get_voice_count';
const getVoiceNameSymbol = 'llama_dart_tts_get_voice_name';
return _TtsApi(
apiVersion: library
.lookupFunction<_TtsApiVersionNative, _TtsApiVersionDart>(
Expand Down Expand Up @@ -92,6 +126,40 @@ class _TtsApi {
NativeFunction<ggml_backend_sched_eval_callbackFunction>
>(evalCallbackSymbol)
: nullptr,
supportedModelTypes: has(supportedModelTypesSymbol)
? library.lookupFunction<
_TtsSupportedModelTypesNative,
_TtsSupportedModelTypesDart
>(supportedModelTypesSymbol)
: null,
getInfoExt: has(getInfoExtSymbol)
? library.lookupFunction<_TtsGetInfoExtNative, _TtsGetInfoExtDart>(
getInfoExtSymbol,
)
: null,
initExt: has(initExtSymbol)
? library.lookupFunction<_TtsInitExtNative, _TtsInitExtDart>(
initExtSymbol,
)
: null,
startWithVoice: has(startWithVoiceSymbol)
? library.lookupFunction<
_TtsStartWithVoiceNative,
_TtsStartWithVoiceDart
>(startWithVoiceSymbol)
: null,
getVoiceCount: has(getVoiceCountSymbol)
? library.lookupFunction<
_TtsGetVoiceCountNative,
_TtsGetVoiceCountDart
>(getVoiceCountSymbol)
: null,
getVoiceName: has(getVoiceNameSymbol)
? library
.lookupFunction<_TtsGetVoiceNameNative, _TtsGetVoiceNameDart>(
getVoiceNameSymbol,
)
: null,
);
} catch (_) {
return null;
Expand Down
20 changes: 20 additions & 0 deletions lib/src/backends/llama_cpp/llama_cpp_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ class NativeLlamaBackend
BackendStatePersistence,
BackendStateIdentity,
BackendTextToSpeech,
BackendTextToSpeechModelSupport,
BackendDecision,
BackendGenerationCapabilitiesSupport,
BackendVideoRuntimeSupport,
Expand Down Expand Up @@ -1485,6 +1486,25 @@ class NativeLlamaBackend
return res as bool;
}

@override
Future<String?> textToSpeechModelUnsupportedReason(
BackendTextToSpeechModel model,
) async {
await _ensureIsolate();
final rp = _openResponsePort();
_dispatchRequest(rp, TextToSpeechModelSupportRequest(model, rp.sendPort));
final response = await _receiveResponse(rp);
if (response is TextToSpeechModelSupportResponse) {
return response.unsupportedReason;
}
if (response is ErrorResponse) {
throw _workerError(response);
}
throw LlamaTextToSpeechException(
'Unexpected native text-to-speech model support response.',
);
}

@override
Future<BackendTextToSpeechCapabilities> textToSpeechCapabilities(
int contextHandle,
Expand Down
Loading
Loading