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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,26 @@
`LlamaStructuredOutput.parse` still decode it); trim replies you compare
exactly. `ChatSession` and its tool loop store assistant turns in `history`
without that whitespace, so the next prompt is unchanged.
- **Behavior change:** an image or audio part of a chat request to a GGUF
model takes the place it has in its message, as llama.cpp's `llama-server`
renders it ([#964](https://github.com/leehack/llamadart/issues/964)). For
Qwen3.5 and Qwen2.5-Omni it was attached before the whole prompt, and for
GLM-OCR it was wrapped in the image start and end tokens twice, so prompts
for media turns of these models change. A chat template no longer writes
its own text for a media part: Qwen's `Picture N: ` under `add_vision_id`,
the Kimi-K2 wrapper, Reka's run of image tokens and Cohere's
`<|IMG_PATCH|>` are gone, as on `llama-server`. A placeholder string that
a chat message quotes (`<img>`, `<image>`, `[IMG]`, `<__media__>`) is text
instead of a part. Where the runtime would still read such a string as a
part, it reaches the model with a zero-width space (U+200B) after its
first character, which the model may repeat in its answer: a quoted
`<__media__>` in `create` on native; every placeholder the bridge
rewrites in `create` on Web; and every placeholder `generate` reads in the
prompt `chatTemplate` returns for messages with media and in `create` on
a custom backend without `BackendChatPromptGeneration`, which
`package:llamadart/backend.dart` now exports. A prompt written for
`generate` keeps its placeholders, and `chatTemplate` output for messages
without media is unchanged.

## 0.11.1

Expand Down
6 changes: 3 additions & 3 deletions doc/litert_lm_templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,9 @@ Templates are committed as jinja under `tool/litert_lm_templates/` and embedded
into `lib/src/backends/litert_lm/litert_lm_chat_templates.dart` by a generator.
Start from the canonical template llama.cpp uses. Keep any runtime
content-shape adapter in this source and cover it with prompt-parity tests.
An adapter that reads content part lists either renders image and audio parts
or rejects both: the Dart renderer gives a template that reads part lists
media as typed parts unless it rejects both kinds. Pin the result in
The Dart renderer gives an adapter the media marker in the message text and
never an image or audio part. It still reports an adapter that reads content
part lists but rejects both kinds as reading strings only. Pin the result in
`test/unit/core/template/template_caps_cache_fixtures_test.dart`.

1. Copy the canonical jinja into `tool/litert_lm_templates/<id>.jinja`
Expand Down
11 changes: 11 additions & 0 deletions doc/webgpu_bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,17 @@ gates against real assets and models; its header lists the setup.
exported from `package:llamadart`.
- Large model URL loads can use a worker-thread fetch-backed path to reduce
contiguous `ArrayBuffer` pressure, but only after an explicit opt-in.
- With media parts the bridge reads its marker `<__media__>` and the
placeholders it rewrites to it (`<image>`, `[IMG]`, `<|image|>`, `<img>`,
`<|img|>`, `<|vision_start|><|image_pad|><|vision_end|>` and its
`video_pad` form, `<audio>`, `<|audio|>`, `<|image_N|>`, `<|audio_N|>`) as
a part wherever they are in the prompt, and the pinned assets have no
option that turns this off. For a prompt that `LlamaEngine.create` rendered,
`WebGpuLlamaBackend` writes `<__media__>` where each part was and puts a
zero-width space after the first character of any such string in the rest,
so a message that quotes one is not read as media. A prompt passed to
`generate` goes to the bridge as written. A bridge option that takes the
marker with the request would make the zero-width space unnecessary.
- Bridge runtimes can provide `llama_webgpu_core_mem64.js/.wasm`. When the
page sets `__llamadartBridgeCoreModuleUrlMem64` and memory64 is preferred,
the bridge tries the wasm64 core first and falls back to wasm32.
Expand Down
1 change: 1 addition & 0 deletions lib/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export 'src/backends/backend.dart'
LlamaBackend,
BackendAvailability,
BackendBatchEmbeddings,
BackendChatPromptGeneration,
BackendDartLogLevel,
BackendDecision,
BackendDecisionCapabilities,
Expand Down
28 changes: 28 additions & 0 deletions lib/src/backends/backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,34 @@ abstract class BackendRuntimeIdentity {
LlamaRuntime? get runtime;
}

/// Optional backend capability for a prompt that `LlamaEngine.create`
/// rendered from chat messages with media parts, as opposed to a prompt the
/// caller of `LlamaEngine.generate` wrote.
///
/// A backend that reads media placeholders in the prompt of
/// [LlamaBackend.generate] (`<__media__>`, `<image>`, `<img>` and the like)
/// would also read one that a chat message only quotes. With this interface
/// the engine hands such a backend the rendered prompt apart from a caller's.
/// Without it the engine passes the prompt to [LlamaBackend.generate] with
/// `<__media__>` where each part was and a zero-width space (U+200B) after
/// the first character of every other placeholder string.
abstract class BackendChatPromptGeneration {
/// Generates like [LlamaBackend.generate] from the chat-rendered [prompt].
///
/// [mediaMarker] stands in [prompt] once for each image or audio part of
/// [parts], in order, where that part was in its message. It is a random
/// string, drawn once for the isolate, that message text does not hold.
/// Everything else in [prompt] is template or message text: the backend
/// must not rewrite a placeholder in it or read it as media.
Stream<List<int>> generateChatPrompt(
int contextHandle,
String prompt,
GenerationParams params, {
required String mediaMarker,
List<LlamaContentPart>? parts,
});
}

/// Internal backend probe for media the loaded model takes directly, without
/// a multimodal projector.
abstract class BackendDirectMediaInput {
Expand Down
27 changes: 27 additions & 0 deletions lib/src/backends/llama_cpp/llama_cpp_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class NativeLlamaBackend
BackendVideoRuntimeSupport,
BackendGenerationLimitReporting,
BackendGenerationUsageReporting,
BackendChatPromptGeneration,
BackendDartLogLevel {
Isolate? _isolate;
SendPort? _sendPort;
Expand Down Expand Up @@ -506,6 +507,29 @@ class NativeLlamaBackend
String prompt,
GenerationParams params, {
List<LlamaContentPart>? parts,
}) => _generate(contextHandle, prompt, params, parts: parts);

@override
Stream<List<int>> generateChatPrompt(
int contextHandle,
String prompt,
GenerationParams params, {
required String mediaMarker,
List<LlamaContentPart>? parts,
}) => _generate(
contextHandle,
prompt,
params,
parts: parts,
chatMediaMarker: mediaMarker,
);

Stream<List<int>> _generate(
int contextHandle,
String prompt,
GenerationParams params, {
List<LlamaContentPart>? parts,
String? chatMediaMarker,
}) {
final failure = _workerFailure;
if (failure != null) return Stream<List<int>>.error(failure);
Expand Down Expand Up @@ -533,6 +557,7 @@ class NativeLlamaBackend
prompt,
params,
parts,
chatMediaMarker,
);
}

Expand Down Expand Up @@ -585,6 +610,7 @@ class NativeLlamaBackend
String prompt,
GenerationParams params,
List<LlamaContentPart>? parts,
String? chatMediaMarker,
) {
final rp = _openResponsePort();

Expand Down Expand Up @@ -654,6 +680,7 @@ class NativeLlamaBackend
cancelToken.address,
rp.sendPort,
parts: parts,
chatMediaMarker: chatMediaMarker,
),
);
} catch (error, stackTrace) {
Expand Down
68 changes: 64 additions & 4 deletions lib/src/backends/llama_cpp/llama_cpp_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4707,13 +4707,54 @@ class LlamaCppService {
/// Supports multimodal input via [parts].
/// Calls [onLimit] before the stream closes when a token limit ended the
/// generation.
///
/// The caller wrote [prompt]: a media placeholder in it stands for a part,
/// and parts without one go before the prompt.
Stream<List<int>> generate(
int contextHandle,
String prompt,
GenerationParams params,
int cancelTokenAddress, {
List<LlamaContentPart>? parts,
void Function(BackendGenerationLimit limit)? onLimit,
}) => _generate(
contextHandle,
prompt,
params,
cancelTokenAddress,
parts: parts,
onLimit: onLimit,
);

/// Generates like [generate] from a [prompt] that a chat template rendered
/// with [mediaMarker] where each part was. A placeholder string elsewhere
/// in it is message text.
Stream<List<int>> generateChatPrompt(
int contextHandle,
String prompt,
GenerationParams params,
int cancelTokenAddress, {
required String mediaMarker,
List<LlamaContentPart>? parts,
void Function(BackendGenerationLimit limit)? onLimit,
}) => _generate(
contextHandle,
prompt,
params,
cancelTokenAddress,
parts: parts,
chatMediaMarker: mediaMarker,
onLimit: onLimit,
);

Stream<List<int>> _generate(
int contextHandle,
String prompt,
GenerationParams params,
int cancelTokenAddress, {
List<LlamaContentPart>? parts,
String? chatMediaMarker,
void Function(BackendGenerationLimit limit)? onLimit,
}) async* {
var ctx = _contexts[contextHandle];
if (ctx == null) throw Exception("Invalid context handle");
Expand Down Expand Up @@ -4876,6 +4917,7 @@ class LlamaCppService {
tokensPtr,
nCtx,
modelParams,
chatMediaMarker: chatMediaMarker,
allowTextPromptReuse:
speculativeConfig == null &&
!hasMediaParts &&
Expand Down Expand Up @@ -5673,6 +5715,7 @@ class LlamaCppService {
Pointer<Int32> tokensPtr,
int nCtx,
llama_context_params modelParams, {
required String? chatMediaMarker,
required bool allowTextPromptReuse,
required Pointer<llama_dart_speculative> speculativeSession,
required _SpeculativeApi? speculativeApi,
Expand All @@ -5696,6 +5739,7 @@ class LlamaCppService {
mediaParts,
modelParams,
cancelToken,
chatMediaMarker: chatMediaMarker,
);
return (nPast: nPast, promptTokenCount: 0);
} else {
Expand Down Expand Up @@ -5724,8 +5768,9 @@ class LlamaCppService {
String prompt,
List<LlamaContentPart> mediaParts,
llama_context_params modelParams,
Pointer<Int8> cancelToken,
) {
Pointer<Int8> cancelToken, {
required String? chatMediaMarker,
}) {
_calls.failures.ensureUsable(mmCtx, 'This multimodal projector');
int initialTokens = 0;
// Zeroed, so the cleanup of a part that failed skips the slots after it.
Expand Down Expand Up @@ -5791,6 +5836,7 @@ class LlamaCppService {
final normalizedPrompt = _normalizeMtmdPromptMarkers(
prompt,
mediaParts.length,
chatMediaMarker: chatMediaMarker,
);
promptPtr = normalizedPrompt.toNativeUtf8();
inputText.ref.text = promptPtr.cast();
Expand Down Expand Up @@ -5895,13 +5941,27 @@ class LlamaCppService {
);
}

String _normalizeMtmdPromptMarkers(String prompt, int mediaPartCount) {
String _normalizeMtmdPromptMarkers(
String prompt,
int mediaPartCount, {
required String? chatMediaMarker,
}) {
final markerPtr = _mtmdDefaultMarker();
final marker = markerPtr == nullptr
? '<__media__>'
: markerPtr.cast<Utf8>().toDartString();

var normalized = normalizeMediaPlaceholders(prompt, marker: marker);
// The projector splits a prompt on its marker wherever it is. Its helper
// for speech output writes the default marker itself, so the projector
// cannot be given another one.
var normalized = chatMediaMarker == null
? normalizeMediaPlaceholders(prompt, marker: marker)
: chatPromptForMarkerRuntime(
prompt,
chatMarker: chatMediaMarker,
marker: marker,
runtimePlaceholders: marker,
);

if (mediaPartCount <= 0) {
return normalized;
Expand Down
27 changes: 19 additions & 8 deletions lib/src/backends/llama_cpp/worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -248,14 +248,25 @@ void runLlamaWorkerForTesting(
final stopwatch = Stopwatch()..start();
Duration? timeToFirstToken;
BackendGenerationLimit? limit;
final stream = service.generate(
message.contextHandle,
message.prompt,
message.params,
message.cancelTokenAddress,
parts: message.parts,
onLimit: (reached) => limit = reached,
);
final chatMediaMarker = message.chatMediaMarker;
final stream = chatMediaMarker == null
? service.generate(
message.contextHandle,
message.prompt,
message.params,
message.cancelTokenAddress,
parts: message.parts,
onLimit: (reached) => limit = reached,
)
: service.generateChatPrompt(
message.contextHandle,
message.prompt,
message.params,
message.cancelTokenAddress,
mediaMarker: chatMediaMarker,
parts: message.parts,
onLimit: (reached) => limit = reached,
);

final batcher = NativeTokenStreamBatcher(
tokenThreshold: message.params.streamBatchTokenThreshold,
Expand Down
5 changes: 5 additions & 0 deletions lib/src/backends/llama_cpp/worker_messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ class GenerateRequest extends WorkerRequest {
/// Multimodal content parts.
final List<LlamaContentPart>? parts;

/// The marker a chat template rendered [prompt] with, or null for a prompt
/// the caller wrote.
final String? chatMediaMarker;

/// Creates a new [GenerateRequest].
GenerateRequest(
this.contextHandle,
Expand All @@ -91,6 +95,7 @@ class GenerateRequest extends WorkerRequest {
this.cancelTokenAddress,
super.sendPort, {
this.parts,
this.chatMediaMarker,
});
}

Expand Down
28 changes: 28 additions & 0 deletions lib/src/backends/native/native_backend.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import '../../core/models/inference/tool_choice.dart';
import '../../core/models/model_format.dart';
import '../../core/models/tools/tool_definition.dart';
import '../../core/template/handlers/translate_gemma_handler.dart';
import '../../core/template/media_placeholders.dart';
import '../backend.dart';
import '../litert_lm/litert_lm_backend.dart';
import '../llama_cpp/llama_cpp_backend.dart';
Expand Down Expand Up @@ -48,6 +49,7 @@ class NativeAutoBackend
BackendStatePersistenceSupport,
BackendGrammarConstraintsSupport,
BackendNativeChatGeneration,
BackendChatPromptGeneration,
BackendDeferredEngineCreation,
BackendTextToSpeech,
BackendDecision,
Expand Down Expand Up @@ -194,6 +196,32 @@ class NativeAutoBackend
);
}

@override
Stream<List<int>> generateChatPrompt(
int contextHandle,
String prompt,
GenerationParams params, {
required String mediaMarker,
List<LlamaContentPart>? parts,
}) {
final delegate = _requireDelegate();
if (delegate is BackendChatPromptGeneration) {
return (delegate as BackendChatPromptGeneration).generateChatPrompt(
contextHandle,
prompt,
params,
mediaMarker: mediaMarker,
parts: parts,
);
}
return delegate.generate(
contextHandle,
prompt.replaceAll(mediaMarker, mtmdMediaMarker),
params,
parts: parts,
);
}

@override
BackendGenerationLimit? generationLimitOf(Stream<List<int>> generation) {
final delegate = _delegate;
Expand Down
Loading
Loading