From 874f045074eb11551522675a71bf235c1ccea683 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 10 Nov 2026 12:47:15 -0500 Subject: [PATCH 1/4] Gate native LiteRT-LM JSON Schema per host ABI and accelerator Replace the macOS-only gate with a per-ABI table of qualified backends and add the chat-app-litert-json-schema device scenario for Android and iOS qualification. The table lists candidate hosts; entries without real-model evidence are removed before review. Part of #174. --- doc/testing_matrix.md | 6 + .../litert_lm_json_schema_e2e_test.dart | 219 ++++++++++++++++++ .../backends/litert_lm/litert_lm_service.dart | 40 ++-- .../litert_lm/litert_lm_service_test.dart | 11 +- test/unit/tooling/run_local_e2e_test.dart | 64 ++++- tool/testing/run_local_e2e.dart | 47 +++- tool/testing/test_matrix.dart | 18 ++ 7 files changed, 382 insertions(+), 23 deletions(-) create mode 100644 example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 79bd9d096..64a5773dd 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -166,6 +166,7 @@ Pick targeted rows based on the touched surface: | Large WebGPU GGUF / wasm64 selection | `gemma4-webgpu-mem64` | | LiteRT-LM web / Gemma 4 web bundle | `gemma4-litert-web` | | Chat app model cache/download/projector | `chat-app-device-cache` | +| LiteRT-LM native JSON Schema on a device | `chat-app-litert-json-schema` | | LiteRT-LM engine reload memory on a device | `chat-app-litert-reload-memory` | | LiteRT-LM bundle in a read-only directory on a device | `chat-app-litert-read-only-bundle` | | Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` | @@ -1245,6 +1246,11 @@ recovery, thinking (Gemma 4 reasons and still returns the constrained reply; Qwen3 is refused), system/history, before/after-content cancellation and a `length` finish cut off inside a constrained string. Run it per model and backend; `--list` and `--dry-run` first. Each host platform needs its own run. +`chat-app-litert-json-schema` runs the same checks in the chat app on an +Android or iOS device, simulator or emulator. `--model-path` is a path the app +can read (a host path works on the iOS simulator and macOS) or an `http(s)` +URL the app downloads into its support directory; for an Android emulator, +serve the bundle on the host and use `http://10.0.2.2:/`. ### Complete image checkpoint containers diff --git a/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart new file mode 100644 index 000000000..b1fd47c31 --- /dev/null +++ b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart @@ -0,0 +1,219 @@ +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 20)) +/// Device qualification of native LiteRT-LM JSON Schema output. +/// +/// Run through `run_local_e2e.dart --scenario chat-app-litert-json-schema`, +/// which serves the model to the device and passes these defines. +library; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:path_provider/path_provider.dart'; + +const _families = { + 'c5f39b4191926786c3e6668b62af4d6eb15248dfc7a5348252a9b406f33f2108': + 'qwen3-0.6b', + '181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c': + 'gemma-4-e2b', +}; +const _prompt = + 'Reply with exactly the word BANANA. Do not use JSON, quotes, punctuation, or explanation.'; +const _params = GenerationParams( + maxTokens: 64, + temp: 0, + topK: 1, + topP: 1, + penalty: 1, + seed: 42, +); +const _messages = [ + LlamaChatMessage.fromText(role: LlamaChatRole.user, text: _prompt), +]; +const _sentinel = { + 'type': 'object', + 'properties': { + 'verdict': {'type': 'string', 'const': 'CEDAR_174'}, + }, + 'required': ['verdict'], + 'additionalProperties': false, +}; +const _wide = { + 'type': 'object', + 'properties': { + 'code': {'type': 'string', 'pattern': r'^[A-Z]{3}-[0-9]{2}$'}, + 'count': {'type': 'integer', 'minimum': 3, 'maximum': 7}, + 'tags': { + 'type': 'array', + 'items': {r'$ref': r'#/$defs/tag'}, + 'minItems': 1, + 'maxItems': 3, + }, + 'owner': { + 'anyOf': [ + {'type': 'null'}, + { + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'maxLength': 12}, + }, + 'required': ['name'], + 'additionalProperties': false, + }, + ], + }, + }, + 'required': ['code', 'count', 'tags', 'owner'], + 'additionalProperties': false, + r'$defs': { + 'tag': { + 'enum': ['red', 'green', 'blue'], + }, + }, +}; +const _longString = { + 'type': 'object', + 'properties': { + 'story': {'type': 'string', 'minLength': 400}, + }, + 'required': ['story'], + 'additionalProperties': false, +}; + +Map _format(Map schema) => { + 'type': 'json_schema', + 'json_schema': {'schema': schema}, +}; + +Future _resolveModel() async { + const path = String.fromEnvironment('LITERT_LM_MODEL'); + if (path.isNotEmpty) return path; + const url = String.fromEnvironment('LITERT_LM_MODEL_URL'); + final directory = await getApplicationSupportDirectory(); + final target = File('${directory.path}/${Uri.parse(url).pathSegments.last}'); + if (!target.existsSync()) await Dio().download(url, target.path); + return target.path; +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const configured = + String.fromEnvironment('LITERT_LM_MODEL') != '' || + String.fromEnvironment('LITERT_LM_MODEL_URL') != ''; + const backend = String.fromEnvironment( + 'LITERT_LM_BACKEND', + defaultValue: 'cpu', + ); + + testWidgets('native JSON Schema enforcement, contract, thinking and cutoff', ( + tester, + ) async { + final model = await _resolveModel(); + final digest = (await sha256.bind(File(model).openRead()).first).toString(); + final family = _families[digest]; + expect(family, isNotNull, reason: 'Use a qualified model artifact.'); + final engine = LlamaEngine(LlamaBackend()); + final records = >[]; + Future run( + String name, { + Map? schema, + bool thinking = false, + GenerationParams params = _params, + }) async { + final completion = await engine + .create( + _messages, + params: params, + enableThinking: thinking, + responseFormat: schema == null ? null : _format(schema), + ) + .collect(); + records.add({ + 'case': name, + 'text': completion.text, + 'thinking_chars': completion.thinking.length, + 'finish': completion.finishReason?.name, + }); + return completion; + } + + Map parse(LlamaCompletion reply, Map schema) => + LlamaStructuredOutput>.jsonSchema( + schema: Map.from(schema), + decoder: (json) => json, + ).parse(reply.text); + + try { + await engine.setModel( + LlamaModel(ModelSource.path(model)), + params: ModelParams( + device: backend == 'gpu' ? ComputeDevice.gpu : ComputeDevice.cpu, + contextSize: 2048, + numberOfThreads: backend == 'gpu' ? 0 : 2, + ), + ); + expect((await engine.capabilities).supportsStructuredOutput, isTrue); + expect((await run('unconstrained')).text.trim(), isNot(startsWith('{'))); + final sentinel = await run('sentinel', schema: _sentinel); + expect(jsonDecode(sentinel.text), {'verdict': 'CEDAR_174'}); + expect(sentinel.finishReason, LlamaFinishReason.stop); + final wide = await run( + 'wide_contract', + schema: _wide, + params: _params.copyWith(maxTokens: 192), + ); + expect(wide.finishReason, LlamaFinishReason.stop); + parse(wide, _wide); + await expectLater( + engine + .create( + _messages, + params: _params, + enableThinking: false, + responseFormat: _format(const { + 'type': 'object', + 'properties': { + 'v': {'type': 'string', 'format': 'time'}, + }, + }), + ) + .drain(), + throwsA(isA()), + ); + final thinking = run( + 'thinking', + schema: _sentinel, + thinking: true, + params: _params.copyWith(maxTokens: 1024), + ); + if (family == 'gemma-4-e2b') { + final reply = await thinking; + expect(jsonDecode(reply.text), {'verdict': 'CEDAR_174'}); + expect(reply.thinking, isNotEmpty); + } else { + await expectLater(thinking, throwsA(isA())); + } + final cutoff = await run( + 'cut_inside_constrained_string', + schema: _longString, + params: _params.copyWith(maxTokens: 24), + ); + expect(cutoff.finishReason, LlamaFinishReason.length); + expect( + () => parse(cutoff, _longString), + throwsA(isA()), + ); + } finally { + await engine.dispose(); + // ignore: avoid_print + print( + 'LITERT_JSON_SCHEMA_RESULT ${jsonEncode({'model_sha256': digest, 'family': family, 'backend': '${Platform.operatingSystem}-$backend', 'cases': records})}', + ); + } + }, skip: !configured); +} diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index abb2d4053..43e44a184 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -58,6 +58,17 @@ const String _liteRtLmVideoUnsupportedMessage = 'LiteRT-LM video input is not supported through llamadart. ' 'Extract and send image frames instead.'; +// Hosts and accelerators where real-model JSON Schema runs passed. +const _jsonSchemaQualifiedBackendsByAbi = >{ + Abi.macosArm64: {'cpu', 'gpu'}, + Abi.linuxX64: {'cpu', 'gpu'}, + Abi.linuxArm64: {'cpu'}, + Abi.windowsX64: {'cpu', 'gpu'}, + Abi.androidArm64: {'cpu', 'gpu'}, + Abi.androidX64: {'cpu'}, + Abi.iosArm64: {'cpu', 'gpu'}, +}; + /// Reads what the `.litertlm` bundle at a path declares, as /// [LiteRtLmRuntimeClient.bundleCapabilities] does. typedef LiteRtLmBundleCapabilitiesReader = @@ -132,7 +143,7 @@ class LiteRtLmService { LiteRtLmBundleChatTemplateReader? readBundleChatTemplate, LiteRtLmBundleFirstChannelReader? readBundleFirstChannel, String? finishReasonProbeLibraryPath, - bool Function()? jsonSchemaPlatformSupported, + Set Function()? jsonSchemaQualifiedBackends, LiteRtLmVulkanAdapters Function()? probeGpuAdapters, }) : _probeGpuAdapters = probeGpuAdapters ?? @@ -141,9 +152,9 @@ class LiteRtLmService { runtimeClientFactory == null ? _systemVulkanAdaptersProbe : null), - _jsonSchemaPlatformSupported = - jsonSchemaPlatformSupported ?? - (() => Platform.isMacOS && Abi.current() == Abi.macosArm64), + _jsonSchemaQualifiedBackends = + jsonSchemaQualifiedBackends ?? + (() => _jsonSchemaQualifiedBackendsByAbi[liteRtLmGateAbi()] ?? {}), _clientFactory = runtimeClientFactory ?? (() => clientFactory == null @@ -219,7 +230,7 @@ class LiteRtLmService { bool _jsonSchemaAdmitted = false; bool _jsonSchemaThinking = false; - final bool Function() _jsonSchemaPlatformSupported; + final Set Function() _jsonSchemaQualifiedBackends; LiteRtLmEmbeddingRuntimeSession? _embedding; LiteRtLmCacheLease? _cacheLease; ModelParams? _modelParams; @@ -658,13 +669,14 @@ class LiteRtLmService { Future prepareJsonSchemaChat() async { if (_jsonSchemaAdmitted) return; _requireConversationEngine(); - const platformRefusal = - 'Native JSON Schema chat is qualified only on macOS arm64 CPU and GPU; ' - 'NPU and other platforms are unsupported.'; - if (!_jsonSchemaPlatformSupported() || - _backendNameFor(_modelParams ?? const ModelParams()) == 'npu') { - throw LlamaUnsupportedException(platformRefusal); - } + final qualified = _jsonSchemaQualifiedBackends(); + Never refuseBackend(String backend) => throw LlamaUnsupportedException( + 'Native JSON Schema chat is not qualified for the LiteRT-LM $backend ' + 'backend on ${liteRtLmGateAbi()}' + '${qualified.isEmpty ? '' : '; select ${qualified.join(' or ')}'}.', + ); + final requested = _backendNameFor(_modelParams ?? const ModelParams()); + if (!qualified.contains(requested)) refuseBackend(requested); final routing = _templateRouting(); final family = routing.family; final customTemplate = _modelParams?.chatTemplate; @@ -686,8 +698,8 @@ class LiteRtLmService { } _cancelRequested = false; final client = await _ensureClientForGeneration(const GenerationParams()); - if (_activeBackend != 'cpu' && _activeBackend != 'gpu') { - throw LlamaUnsupportedException(platformRefusal); + if (!qualified.contains(_activeBackend)) { + refuseBackend(_activeBackend ?? requested); } if (!client.supportsJsonSchemaConstraints) { throw LlamaUnsupportedException( diff --git a/test/unit/backends/litert_lm/litert_lm_service_test.dart b/test/unit/backends/litert_lm/litert_lm_service_test.dart index 0f6e6dd01..b4cc1a23d 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -71,7 +71,7 @@ void main() { ..finishReason = LiteRtLmFinishReason.stop; service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => true, + jsonSchemaQualifiedBackends: () => {'cpu', 'gpu'}, ); await service.loadModel( (await modelFile.copy('${tempDir.path}/Qwen3-0.6B.litertlm')).path, @@ -121,7 +121,7 @@ void main() { service.dispose(); service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => true, + jsonSchemaQualifiedBackends: () => {'cpu', 'gpu'}, ); await service.loadModel( '${tempDir.path}/Qwen3-0.6B.litertlm', @@ -137,7 +137,8 @@ void main() { service.dispose(); service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => excluded != 'host', + jsonSchemaQualifiedBackends: () => + excluded == 'host' ? const {} : {'cpu', 'gpu'}, ); final selected = excluded == 'template' ? const ModelParams( @@ -256,7 +257,7 @@ void main() { ..finishReason = LiteRtLmFinishReason.stop; service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => true, + jsonSchemaQualifiedBackends: () => {'cpu', 'gpu'}, readBundleFirstChannel: (_) => reasoningChannel ? (name: 'thought', isReasoning: true) : null, ); @@ -1963,7 +1964,7 @@ void main() { final client = _FakeLiteRtLmRuntimeClient(); final service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => true, + jsonSchemaQualifiedBackends: () => {'cpu', 'gpu'}, ); try { await service.loadModel( diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 24e4af546..60c3e5757 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -1596,7 +1596,19 @@ Future main(List args) async { for (final name in deviceScenarios) { Future dryRun(String device) async { final result = await runLocalE2e( - ['--scenario', name, '--device', device, '--dry-run'], + [ + '--scenario', + name, + '--device', + device, + if (name == 'chat-app-litert-json-schema') ...[ + '--model-path', + '/m.litertlm', + '--backend', + 'cpu', + ], + '--dry-run', + ], projectRoot: '/repo', displayShell: LocalE2eDisplayShell.posix, ); @@ -1675,6 +1687,56 @@ Future main(List args) async { expect(result.stdout, isNot(contains('LITERT_RELOAD_MODEL'))); }); + test('dry-runs the native JSON Schema device scenario', () async { + Future dryRun(List extra) => runLocalE2e( + [ + '--scenario', + 'chat-app-litert-json-schema', + '--device', + 'android', + ...extra, + '--dry-run', + ], + projectRoot: '/repo', + displayShell: LocalE2eDisplayShell.posix, + ); + for (final invalid in [ + ['--backend', 'cpu'], + ['--model-path', '/m.litertlm'], + ['--model-path', '/m.litertlm', '--backend', 'npu'], + ]) { + expect((await dryRun(invalid)).exitCode, 64, reason: '$invalid'); + } + final path = await dryRun([ + '--model-path', + '/data/local/tmp/Qwen3-0.6B.litertlm', + '--backend', + 'gpu', + ]); + expect(path.exitCode, 0); + expect( + path.stdout, + contains( + 'integration_test/litert_lm_json_schema_e2e_test.dart -d android ' + '--dart-define=LITERT_LM_MODEL=/data/local/tmp/Qwen3-0.6B.litertlm ' + '--dart-define=LITERT_LM_BACKEND=gpu', + ), + ); + final url = await dryRun([ + '--model-path', + 'http://10.0.2.2:8765/gemma-4-E2B-it.litertlm', + '--backend', + 'cpu', + ]); + expect( + url.stdout, + contains( + '--dart-define=LITERT_LM_MODEL_URL=' + 'http://10.0.2.2:8765/gemma-4-E2B-it.litertlm', + ), + ); + }); + test('dry-runs the LiteRT-LM read-only bundle device scenario', () async { final result = await runLocalE2e( const [ diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index 46a9a6e73..cbd817165 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -2237,6 +2237,38 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'chat-app-litert-json-schema', + group: LocalE2eScenarioGroup.flutterDevice, + description: + 'Qualify native LiteRT-LM JSON Schema output on a device with a ' + 'fixed Qwen3 or Gemma 4 model; --model-path is a path the app can ' + 'read or an http(s) URL it downloads.', + requiresDevice: true, + stepsBuilder: (context) { + final model = context.modelPath!; + final remote = + model.startsWith('http://') || model.startsWith('https://'); + return [ + LocalE2eCommandStep( + workingDirectory: context.chatAppDir, + executable: 'flutter', + arguments: [ + 'test', + '--run-skipped', + '-t', + 'local-only', + 'integration_test/litert_lm_json_schema_e2e_test.dart', + '-d', + context.device, + '--dart-define=${remote ? 'LITERT_LM_MODEL_URL' : 'LITERT_LM_MODEL'}=$model', + '--dart-define=LITERT_LM_BACKEND=${context.backend}', + ], + description: 'Flutter chat app native JSON Schema E2E', + ), + ]; + }, + ), LocalE2eScenario( name: 'chat-app-litert-read-only-bundle', group: LocalE2eScenarioGroup.flutterDevice, @@ -2953,12 +2985,21 @@ Future runLocalE2e( '--model-path and --head-path are required for decision-model-smoke.\n', ); } - if (scenario.name == 'litert-lm-json-schema' && + if ((scenario.name == 'litert-lm-json-schema' || + scenario.name == 'chat-app-litert-json-schema') && + parsed.modelPath == null) { + return LocalE2eResult( + 64, + stderr: '--model-path is required for ${scenario.name}.\n', + ); + } + if ((scenario.name == 'litert-lm-json-schema' || + scenario.name == 'chat-app-litert-json-schema') && (!parsed.backendProvided || (parsed.backend != 'cpu' && parsed.backend != 'gpu'))) { - return const LocalE2eResult( + return LocalE2eResult( 64, - stderr: 'litert-lm-json-schema requires --backend cpu or gpu.\n', + stderr: '${scenario.name} requires --backend cpu or gpu.\n', ); } if ((scenario.name == 'qwen3-litert-cpu-unicode' || diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 45b164d04..aebad30f2 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -1332,6 +1332,24 @@ const List testMatrixRows = [ useWhen: 'Chat app model lifecycle, cache, projector, or device UI changes.', ), + TestMatrixRow( + id: 'chat-app-litert-json-schema', + tier: 'high-risk', + mode: 'local-only; device', + covers: + 'Native JSON Schema enforcement on a device: adversarial control, ' + 'nested/array/ref/anyOf/pattern contract, typed contract refusal, ' + 'Gemma 4 thinking or Qwen3 thinking refusal and a length cutoff ' + 'inside a constrained string', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'chat-app-litert-json-schema --device ' + '--model-path --backend cpu', + useWhen: + 'Qualifying native schema output on Android or iOS, or changing the ' + 'platform gate. Run per fixed model (Qwen3-0.6B, Gemma 4 E2B) and ' + 'per backend (cpu, gpu).', + ), TestMatrixRow( id: 'chat-app-litert-reload-memory', tier: 'targeted', From 40bbd1d19c8a54e99d3744c2285570c449b36b49 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 10 Nov 2026 13:10:01 -0500 Subject: [PATCH 2/4] Admit native LiteRT-LM JSON Schema only where real-model runs passed macOS and iOS arm64 keep CPU and GPU and Android arm64 keeps the CPU; Linux, Windows, Android GPU and Android x64 stay refused until a run on that host passes. The device test now surfaces the admission error. Part of #174. --- CHANGELOG.md | 1 + README.md | 2 +- doc/litert_lm_templates.md | 3 +- .../litert_lm_json_schema_e2e_test.dart | 13 ++++- .../backends/litert_lm/litert_lm_service.dart | 9 ++-- skills/llamadart-chat-streaming/SKILL.md | 4 +- .../litert_lm/litert_lm_service_test.dart | 50 +++++++++++++++++++ website/docs/changelog/recent-releases.md | 1 + .../docs/guides/generation-and-streaming.md | 5 +- website/docs/platforms/support-matrix.md | 2 +- 10 files changed, 76 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20bd16276..6809e0001 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Releases before 0.10.0 are in the ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64 CPU, the hosts with passing real-model runs; Linux, Windows and Android GPU still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/README.md b/README.md index 101f60176..0bf764010 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ concrete engine; see [shared lifecycle ownership](https://llamadart.leehack.com/ LFM2 Python-style tool calls use declared argument types and preserve copied string backslashes; see [tool calling](https://llamadart.leehack.com/docs/guides/tool-calling). The automatic grammar preserves copied singleton string spellings and can use an existing Python arguments wrapper for unambiguous JSON-escaped string values. Foreign XML closing tags remain raw diagnostics with no executable calls. Native llama.cpp applies schema-directed lazy grammar to LFM2 automatic Python tool calls. Web additionally requires bridge assets v0.1.82+ with a loaded-core prompt-penalty capability; older runtimes reject before inference. -Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS arm64 CPU and GPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). +Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS and iOS arm64 CPU and GPU and the Android arm64 CPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). LFM2 replies cut off at a reported length limit expose raw `partialToolCalls` diagnostics separately from executable calls and history. LFM2 tool markers inside reasoning stay in reasoning and produce no executable calls. Explicit parallel-tool requests reach supported Dart tool grammars even when template probes do not recognize parallel history. ## Install diff --git a/doc/litert_lm_templates.md b/doc/litert_lm_templates.md index 8c5ac42a3..ebb13bb8a 100644 --- a/doc/litert_lm_templates.md +++ b/doc/litert_lm_templates.md @@ -367,7 +367,8 @@ backend, not the registry: real-model-tested rendered-prompt compatibility path, but its handler grammar is still not applied by LiteRT-LM and must not be reported as grammar support. - **Native JSON Schema uses its own provider.** Canonical Qwen3 text chat and - Gemma 4 chat with its bundle template, on macOS arm64 CPU and GPU, pass the + Gemma 4 chat with its bundle template, on macOS/iOS arm64 CPU and GPU and + the Android arm64 CPU, pass the schema directly to LLGuidance after constructing the model's provider. The schema must sit in the subset both LLGuidance and the GBNF converter enforce. Gemma 4 may think first; Qwen3 must disable thinking. Tools, media, custom diff --git a/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart index b1fd47c31..83e732007 100644 --- a/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart +++ b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart @@ -157,7 +157,18 @@ void main() { numberOfThreads: backend == 'gpu' ? 0 : 2, ), ); - expect((await engine.capabilities).supportsStructuredOutput, isTrue); + if (!(await engine.capabilities).supportsStructuredOutput) { + // The engine loads lazily, so the capability probe hides why admission + // failed; a strict request rethrows the admission error. + await engine + .create( + _messages, + params: _params, + responseFormat: _format(_sentinel), + ) + .drain(); + fail('Native JSON Schema output is unsupported on this device.'); + } expect((await run('unconstrained')).text.trim(), isNot(startsWith('{'))); final sentinel = await run('sentinel', schema: _sentinel); expect(jsonDecode(sentinel.text), {'verdict': 'CEDAR_174'}); diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index 43e44a184..32c829b16 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -58,15 +58,12 @@ const String _liteRtLmVideoUnsupportedMessage = 'LiteRT-LM video input is not supported through llamadart. ' 'Extract and send image frames instead.'; -// Hosts and accelerators where real-model JSON Schema runs passed. +// Hosts and accelerators where real-model JSON Schema runs passed; the others +// stay refused until a run on that host passes. const _jsonSchemaQualifiedBackendsByAbi = >{ Abi.macosArm64: {'cpu', 'gpu'}, - Abi.linuxX64: {'cpu', 'gpu'}, - Abi.linuxArm64: {'cpu'}, - Abi.windowsX64: {'cpu', 'gpu'}, - Abi.androidArm64: {'cpu', 'gpu'}, - Abi.androidX64: {'cpu'}, Abi.iosArm64: {'cpu', 'gpu'}, + Abi.androidArm64: {'cpu'}, }; /// Reads what the `.litertlm` bundle at a path declares, as diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index 2e7604fb4..1c20ecee7 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -188,8 +188,8 @@ modalities and speculative strategies before offering them. - For strict JSON, use `LlamaStructuredOutput` with `engine.createStructuredJson`; it constrains decoding and validates the final output. Native LiteRT-LM supports Qwen3 (canonical text template) and - Gemma 4 (bundle template) on macOS arm64 CPU and GPU after provider - admission, for schemas that both the GBNF converter and LiteRT-LM's + Gemma 4 (bundle template) on macOS/iOS arm64 CPU and GPU and the Android + arm64 CPU after provider admission, for schemas that both the GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); `oneOf`, other formats, open tuples and the other differences listed in the structured-output guide throw diff --git a/test/unit/backends/litert_lm/litert_lm_service_test.dart b/test/unit/backends/litert_lm/litert_lm_service_test.dart index b4cc1a23d..b648a1ada 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -160,6 +160,56 @@ void main() { expect(client.generateCount, 0); }); } + group('default qualification table', () { + tearDown(() => debugLiteRtLmAbiOverride = null); + const expected = >{ + Abi.macosArm64: {'cpu', 'gpu'}, + Abi.iosArm64: {'cpu', 'gpu'}, + Abi.androidArm64: {'cpu'}, + Abi.androidX64: {}, + Abi.linuxX64: {}, + Abi.linuxArm64: {}, + Abi.windowsX64: {}, + Abi.macosX64: {}, + }; + for (final MapEntry(key: abi, value: backends) in expected.entries) { + for (final backend in ['cpu', 'gpu']) { + final admitted = backends.contains(backend); + // Admitting the GPU also needs a host GPU; 'admits the GPU delegate' + // covers it. + if (admitted && backend == 'gpu') continue; + test('${admitted ? 'admits' : 'refuses'} $backend on $abi', () async { + service.dispose(); + service = LiteRtLmService(clientFactory: () => client); + await service.loadModel( + '${tempDir.path}/Qwen3-0.6B.litertlm', + backend == 'cpu' + ? params + : const ModelParams( + liteRtLmBackend: LiteRtLmBackendPreference.gpu, + ), + ); + debugLiteRtLmAbiOverride = abi; + if (admitted) { + await service.prepareJsonSchemaChat(); + expect(client.lastJsonSchemaConfig, isTrue); + } else { + await expectLater( + service.prepareJsonSchemaChat(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('not qualified for the LiteRT-LM $backend'), + ), + ), + ); + expect(client.createConversationCount, 0); + } + }); + } + } + }); test('missing optional API never admits or starts generation', () async { client.jsonSchemaSupport = false; await expectLater( diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 67ac58301..df5693807 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -14,6 +14,7 @@ validate against the exact release tag notes. ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64 CPU, the hosts with passing real-model runs; Linux, Windows and Android GPU still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index f495c3c5d..3c52e4cce 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -484,8 +484,9 @@ classes/ranges and groups, with group alternation and repetition counts up to 1024; unsupported regex constructs are rejected. Backends without grammar constraints still fail early for strict output unless they expose a separate admitted JSON Schema provider. Native LiteRT-LM has that path on -macOS arm64 CPU and GPU with Qwen3 (canonical text template) and Gemma 4 -(bundle template) models; LiteRT-LM Web does not. +macOS arm64 and iOS arm64 CPU and GPU and on the Android arm64 CPU, with Qwen3 +(canonical text template) and Gemma 4 (bundle template) models. Linux, Windows, +Android GPU and LiteRT-LM Web refuse it. Native LiteRT-LM accepts the schemas that both the GBNF converter above and LiteRT-LM's LLGuidance provider enforce alike, so a request is accepted or diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index 5facd4156..c57abcbd3 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -156,7 +156,7 @@ native and web. Model architecture support depends on the pinned runtime; see | Row split (`ModelSplitMode.row`) | Needs llama.cpp split buffer types, which no bundled backend provides; a load on a bundled GPU backend whose module loads (Metal, CUDA, HIP, Vulkan, OpenCL), with `GpuBackend.blas` or `GpuBackend.cpu`, with `auto` on Android, the iOS simulator and macOS x86_64 (which runs on the CPU), or that falls back to the CPU because the requested backend is missing or Vulkan is refused, throws `LlamaUnsupportedException` before the model loads, so use `ModelSplitMode.layer`; a bundled module that fails to load or finds no device loads row on the CPU instead ([#1576](https://github.com/leehack/llamadart/issues/1576)) | No | No | No | | Renamed legacy Qwen3 thinking switch | N/A: GGUF metadata | N/A: GGUF metadata | `chatTemplate: liteRtLmQwen3ChatTemplate`; requires native template setter | Canonical override throws at load: no template setter in `@litert-lm/core@0.19.0` | | Thinking budget | Text-only, without speculative decoding, when the native reasoning-budget export resolves | Text-only, with bridge assets whose `getCompletionCapabilities()` reports `thinkingBudget` ([llama-web-bridge#144](https://github.com/leehack/llama-web-bridge/pull/144)); otherwise rejected | Native chat, without speculative decoding, on bundles whose first response channel is a thinking channel (Gemma 4); bounds that channel only; `0` and `forcedMessage` rejected | No | -| Strict `responseFormat` | Yes | Yes, without tools | macOS arm64 CPU and GPU, admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | +| Strict `responseFormat` | Yes | Yes, without tools | macOS and iOS arm64 CPU and GPU, Android arm64 CPU (Linux, Windows and Android GPU refused), admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | | Lazy grammar | Yes | Yes when the loaded bridge reports `lazyGrammar`; otherwise first-token `root` only | No GBNF grammar | No GBNF grammar | | Presence penalty | Yes | With bridge assets whose `getCompletionCapabilities()` reports `presencePenalty` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | Yes, without speculative decoding; counts only tokens of the current send | No: rejects a non-zero value | | Min-P | Yes | With bridge assets whose `getCompletionCapabilities()` reports `minP` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | No: rejects a non-zero value | No: rejects a non-zero value | From 2e90b3ad096ec8a91ff420c76c61bb0c7bc3f71d Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 10 Nov 2026 13:59:48 -0500 Subject: [PATCH 3/4] Admit native LiteRT-LM JSON Schema on Linux x64/arm64 and Windows x64 CPU Qwen3-0.6B and Gemma 4 E2B passed the litert-lm-json-schema e2e on GCE Linux x64, Linux arm64 and Windows x64 CPU. GPUs there stay refused: no L4 run completed. Part of #174. --- CHANGELOG.md | 2 +- README.md | 2 +- doc/litert_lm_templates.md | 2 +- lib/src/backends/litert_lm/litert_lm_service.dart | 3 +++ skills/llamadart-chat-streaming/SKILL.md | 2 +- test/unit/backends/litert_lm/litert_lm_service_test.dart | 6 +++--- website/docs/changelog/recent-releases.md | 2 +- website/docs/guides/generation-and-streaming.md | 7 ++++--- website/docs/platforms/support-matrix.md | 2 +- 9 files changed, 16 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6809e0001..b13edcaac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Releases before 0.10.0 are in the ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). -- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64 CPU, the hosts with passing real-model runs; Linux, Windows and Android GPU still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; GPUs on Android, Linux and Windows still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/README.md b/README.md index 0bf764010..04fb01c53 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ concrete engine; see [shared lifecycle ownership](https://llamadart.leehack.com/ LFM2 Python-style tool calls use declared argument types and preserve copied string backslashes; see [tool calling](https://llamadart.leehack.com/docs/guides/tool-calling). The automatic grammar preserves copied singleton string spellings and can use an existing Python arguments wrapper for unambiguous JSON-escaped string values. Foreign XML closing tags remain raw diagnostics with no executable calls. Native llama.cpp applies schema-directed lazy grammar to LFM2 automatic Python tool calls. Web additionally requires bridge assets v0.1.82+ with a loaded-core prompt-penalty capability; older runtimes reject before inference. -Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS and iOS arm64 CPU and GPU and the Android arm64 CPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). +Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS and iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). LFM2 replies cut off at a reported length limit expose raw `partialToolCalls` diagnostics separately from executable calls and history. LFM2 tool markers inside reasoning stay in reasoning and produce no executable calls. Explicit parallel-tool requests reach supported Dart tool grammars even when template probes do not recognize parallel history. ## Install diff --git a/doc/litert_lm_templates.md b/doc/litert_lm_templates.md index ebb13bb8a..9fbf69c86 100644 --- a/doc/litert_lm_templates.md +++ b/doc/litert_lm_templates.md @@ -368,7 +368,7 @@ backend, not the registry: is still not applied by LiteRT-LM and must not be reported as grammar support. - **Native JSON Schema uses its own provider.** Canonical Qwen3 text chat and Gemma 4 chat with its bundle template, on macOS/iOS arm64 CPU and GPU and - the Android arm64 CPU, pass the + the Android arm64, Linux x64/arm64 and Windows x64 CPU, pass the schema directly to LLGuidance after constructing the model's provider. The schema must sit in the subset both LLGuidance and the GBNF converter enforce. Gemma 4 may think first; Qwen3 must disable thinking. Tools, media, custom diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index d7074d1e2..7778417ee 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -64,6 +64,9 @@ const _jsonSchemaQualifiedBackendsByAbi = >{ Abi.macosArm64: {'cpu', 'gpu'}, Abi.iosArm64: {'cpu', 'gpu'}, Abi.androidArm64: {'cpu'}, + Abi.linuxX64: {'cpu'}, + Abi.linuxArm64: {'cpu'}, + Abi.windowsX64: {'cpu'}, }; /// Reads what the `.litertlm` bundle at a path declares, as diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index 1c20ecee7..0ec76834a 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -189,7 +189,7 @@ modalities and speculative strategies before offering them. `engine.createStructuredJson`; it constrains decoding and validates the final output. Native LiteRT-LM supports Qwen3 (canonical text template) and Gemma 4 (bundle template) on macOS/iOS arm64 CPU and GPU and the Android - arm64 CPU after provider admission, for schemas that both the GBNF converter and LiteRT-LM's + arm64, Linux x64/arm64 and Windows x64 CPU after provider admission, for schemas that both the GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); `oneOf`, other formats, open tuples and the other differences listed in the structured-output guide throw diff --git a/test/unit/backends/litert_lm/litert_lm_service_test.dart b/test/unit/backends/litert_lm/litert_lm_service_test.dart index 0bd1b3e9f..87bd3f9e6 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -167,9 +167,9 @@ void main() { Abi.iosArm64: {'cpu', 'gpu'}, Abi.androidArm64: {'cpu'}, Abi.androidX64: {}, - Abi.linuxX64: {}, - Abi.linuxArm64: {}, - Abi.windowsX64: {}, + Abi.linuxX64: {'cpu'}, + Abi.linuxArm64: {'cpu'}, + Abi.windowsX64: {'cpu'}, Abi.macosX64: {}, }; for (final MapEntry(key: abi, value: backends) in expected.entries) { diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index df5693807..6bf2995ef 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -14,7 +14,7 @@ validate against the exact release tag notes. ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). -- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64 CPU, the hosts with passing real-model runs; Linux, Windows and Android GPU still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; GPUs on Android, Linux and Windows still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 4915b51e5..46990f655 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -484,9 +484,10 @@ classes/ranges and groups, with group alternation and repetition counts up to 1024; unsupported regex constructs are rejected. Backends without grammar constraints still fail early for strict output unless they expose a separate admitted JSON Schema provider. Native LiteRT-LM has that path on -macOS arm64 and iOS arm64 CPU and GPU and on the Android arm64 CPU, with Qwen3 -(canonical text template) and Gemma 4 (bundle template) models. Linux, Windows, -Android GPU and LiteRT-LM Web refuse it. +macOS arm64 and iOS arm64 CPU and GPU and on the Android arm64, Linux x64/arm64 +and Windows x64 CPU, with Qwen3 (canonical text template) and Gemma 4 (bundle +template) models. GPUs on Android, Linux and Windows, and LiteRT-LM Web, refuse +it. Native LiteRT-LM accepts only schemas that both the GBNF converter above and LiteRT-LM's LLGuidance provider enforce alike, so every schema it accepts is diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index c57abcbd3..a565c6298 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -156,7 +156,7 @@ native and web. Model architecture support depends on the pinned runtime; see | Row split (`ModelSplitMode.row`) | Needs llama.cpp split buffer types, which no bundled backend provides; a load on a bundled GPU backend whose module loads (Metal, CUDA, HIP, Vulkan, OpenCL), with `GpuBackend.blas` or `GpuBackend.cpu`, with `auto` on Android, the iOS simulator and macOS x86_64 (which runs on the CPU), or that falls back to the CPU because the requested backend is missing or Vulkan is refused, throws `LlamaUnsupportedException` before the model loads, so use `ModelSplitMode.layer`; a bundled module that fails to load or finds no device loads row on the CPU instead ([#1576](https://github.com/leehack/llamadart/issues/1576)) | No | No | No | | Renamed legacy Qwen3 thinking switch | N/A: GGUF metadata | N/A: GGUF metadata | `chatTemplate: liteRtLmQwen3ChatTemplate`; requires native template setter | Canonical override throws at load: no template setter in `@litert-lm/core@0.19.0` | | Thinking budget | Text-only, without speculative decoding, when the native reasoning-budget export resolves | Text-only, with bridge assets whose `getCompletionCapabilities()` reports `thinkingBudget` ([llama-web-bridge#144](https://github.com/leehack/llama-web-bridge/pull/144)); otherwise rejected | Native chat, without speculative decoding, on bundles whose first response channel is a thinking channel (Gemma 4); bounds that channel only; `0` and `forcedMessage` rejected | No | -| Strict `responseFormat` | Yes | Yes, without tools | macOS and iOS arm64 CPU and GPU, Android arm64 CPU (Linux, Windows and Android GPU refused), admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | +| Strict `responseFormat` | Yes | Yes, without tools | macOS and iOS arm64 CPU and GPU; Android arm64, Linux x64/arm64 and Windows x64 CPU (Android, Linux and Windows GPU refused), admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | | Lazy grammar | Yes | Yes when the loaded bridge reports `lazyGrammar`; otherwise first-token `root` only | No GBNF grammar | No GBNF grammar | | Presence penalty | Yes | With bridge assets whose `getCompletionCapabilities()` reports `presencePenalty` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | Yes, without speculative decoding; counts only tokens of the current send | No: rejects a non-zero value | | Min-P | Yes | With bridge assets whose `getCompletionCapabilities()` reports `minP` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | No: rejects a non-zero value | No: rejects a non-zero value | From bc5d97267c628aa0832c40c3657d207d31f49da9 Mon Sep 17 00:00:00 2001 From: leehack Date: Tue, 10 Nov 2026 14:53:14 -0500 Subject: [PATCH 4/4] Gate native LiteRT-LM JSON Schema on the backend that actually loads The deprecated LiteRtLmBackend(preferredBackend:) override reached schema generation on unqualified GPUs because admission read ModelParams only. The gate now checks the loaded backend before creating an engine and the active backend after, names ComputeDevice in the refusal, and the device scenario refuses model URLs carrying credentials, a query or a fragment. Docs list per-host model evidence. Part of #174. --- CHANGELOG.md | 2 +- README.md | 2 +- doc/testing_matrix.md | 8 +- .../litert_lm_json_schema_e2e_test.dart | 3 +- .../backends/litert_lm/litert_lm_service.dart | 20 +-- skills/llamadart-chat-streaming/SKILL.md | 4 +- .../litert_lm/litert_lm_service_test.dart | 132 ++++++++++++++---- test/unit/tooling/run_local_e2e_test.dart | 11 +- test/unit/tooling/test_matrix_test.dart | 30 ++++ tool/testing/run_local_e2e.dart | 16 +++ website/docs/changelog/recent-releases.md | 2 +- .../docs/guides/generation-and-streaming.md | 16 ++- website/docs/platforms/support-matrix.md | 2 +- 13 files changed, 195 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b13edcaac..2715deec7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Releases before 0.10.0 are in the ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). -- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; GPUs on Android, Linux and Windows still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; other hosts, GPUs on Android, Linux and Windows, and NPU throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/README.md b/README.md index 04fb01c53..b6c4b05dc 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ concrete engine; see [shared lifecycle ownership](https://llamadart.leehack.com/ LFM2 Python-style tool calls use declared argument types and preserve copied string backslashes; see [tool calling](https://llamadart.leehack.com/docs/guides/tool-calling). The automatic grammar preserves copied singleton string spellings and can use an existing Python arguments wrapper for unambiguous JSON-escaped string values. Foreign XML closing tags remain raw diagnostics with no executable calls. Native llama.cpp applies schema-directed lazy grammar to LFM2 automatic Python tool calls. Web additionally requires bridge assets v0.1.82+ with a loaded-core prompt-penalty capability; older runtimes reject before inference. -Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS and iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). +Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on the macOS and iOS arm64 CPU and GPU and the Android arm64, Linux and Windows CPU (per-host model evidence in the structured-output guide), for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix). LFM2 replies cut off at a reported length limit expose raw `partialToolCalls` diagnostics separately from executable calls and history. LFM2 tool markers inside reasoning stay in reasoning and produce no executable calls. Explicit parallel-tool requests reach supported Dart tool grammars even when template probes do not recognize parallel history. ## Install diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 64a5773dd..16961047f 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -1248,9 +1248,11 @@ Qwen3 is refused), system/history, before/after-content cancellation and a backend; `--list` and `--dry-run` first. Each host platform needs its own run. `chat-app-litert-json-schema` runs the same checks in the chat app on an Android or iOS device, simulator or emulator. `--model-path` is a path the app -can read (a host path works on the iOS simulator and macOS) or an `http(s)` -URL the app downloads into its support directory; for an Android emulator, -serve the bundle on the host and use `http://10.0.2.2:/`. +can read (a host path works on the iOS simulator; the sandboxed macOS app +reads only its own container) or a plain `http(s)` URL the app downloads +into its support directory; for an Android emulator, serve the bundle on the +host and use `http://10.0.2.2:/`. URLs with credentials, a query +or a fragment are refused, since the URL is printed and compiled into the app. ### Complete image checkpoint containers diff --git a/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart index 83e732007..f8ad04fba 100644 --- a/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart +++ b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart @@ -3,7 +3,8 @@ /// Device qualification of native LiteRT-LM JSON Schema output. /// /// Run through `run_local_e2e.dart --scenario chat-app-litert-json-schema`, -/// which serves the model to the device and passes these defines. +/// which passes the model path or URL and the backend as defines; serving a +/// URL is up to the caller. library; import 'dart:convert'; diff --git a/lib/src/backends/litert_lm/litert_lm_service.dart b/lib/src/backends/litert_lm/litert_lm_service.dart index 7778417ee..c74f3be1a 100644 --- a/lib/src/backends/litert_lm/litert_lm_service.dart +++ b/lib/src/backends/litert_lm/litert_lm_service.dart @@ -670,16 +670,14 @@ class LiteRtLmService { if (_jsonSchemaAdmitted) return; _requireConversationEngine(); final qualified = _jsonSchemaQualifiedBackends(); - final requested = _backendNameFor(_modelParams ?? const ModelParams()); - // An auto GPU request can only fall back to the CPU, which every - // qualified host admits, so the requested backend decides. - if (!qualified.contains(requested)) { - throw LlamaUnsupportedException( - 'Native JSON Schema chat is not qualified for the LiteRT-LM $requested ' - 'backend on ${liteRtLmGateAbi()}' - '${qualified.isEmpty ? '' : '; select ${qualified.join(' or ')}'}.', - ); - } + Never refuseBackend(String backend) => throw LlamaUnsupportedException( + 'Native JSON Schema chat is not qualified for the LiteRT-LM $backend ' + 'backend on ${liteRtLmGateAbi()}' + '${qualified.isEmpty ? '' : '; load with ${qualified.map((b) => 'ComputeDevice.$b').join(' or ')}'}.', + ); + // The loaded backend includes the deprecated preferredBackend override. + final loaded = _loadedBackend!; + if (!qualified.contains(loaded)) refuseBackend(loaded); final routing = _templateRouting(); final family = routing.family; final customTemplate = _modelParams?.chatTemplate; @@ -701,6 +699,8 @@ class LiteRtLmService { } _cancelRequested = false; final client = await _ensureClientForGeneration(const GenerationParams()); + // An automatic GPU load can run on the CPU instead. + if (!qualified.contains(_activeBackend)) refuseBackend(_activeBackend!); if (!client.supportsJsonSchemaConstraints) { throw LlamaUnsupportedException( 'Native JSON Schema chat requires all constraint-provider and thinking-config symbols. ' diff --git a/skills/llamadart-chat-streaming/SKILL.md b/skills/llamadart-chat-streaming/SKILL.md index 0ec76834a..f774e66de 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -189,7 +189,9 @@ modalities and speculative strategies before offering them. `engine.createStructuredJson`; it constrains decoding and validates the final output. Native LiteRT-LM supports Qwen3 (canonical text template) and Gemma 4 (bundle template) on macOS/iOS arm64 CPU and GPU and the Android - arm64, Linux x64/arm64 and Windows x64 CPU after provider admission, for schemas that both the GBNF converter and LiteRT-LM's + arm64, Linux x64/arm64 and Windows x64 CPU after provider admission (other + hosts, accelerators and NPU throw; per-host model evidence is in the + structured-output guide), for schemas that both the GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); `oneOf`, other formats, open tuples and the other differences listed in the structured-output guide throw diff --git a/test/unit/backends/litert_lm/litert_lm_service_test.dart b/test/unit/backends/litert_lm/litert_lm_service_test.dart index 87bd3f9e6..f17a8a66b 100644 --- a/test/unit/backends/litert_lm/litert_lm_service_test.dart +++ b/test/unit/backends/litert_lm/litert_lm_service_test.dart @@ -162,6 +162,35 @@ void main() { } group('default qualification table', () { tearDown(() => debugLiteRtLmAbiOverride = null); + const hardwareGpu = LiteRtLmVulkanAdapters.devices([ + LiteRtLmVulkanAdapter(name: 'GPU', deviceType: 2), + ]); + LiteRtLmService tableService({ + LiteRtLmVulkanAdapters adapters = hardwareGpu, + Set Function()? qualified, + }) => LiteRtLmService( + clientFactory: () => client, + probeGpuAdapters: () => adapters, + jsonSchemaQualifiedBackends: qualified, + ); + Future expectRefused( + String backend, { + bool beforeEngine = true, + }) async { + await expectLater( + service.prepareJsonSchemaChat(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('not qualified for the LiteRT-LM $backend'), + ), + ), + ); + expect(client.createConversationCount, 0); + if (beforeEngine) expect(client.lastBackend, isNull); + } + const expected = >{ Abi.macosArm64: {'cpu', 'gpu'}, Abi.iosArm64: {'cpu', 'gpu'}, @@ -175,40 +204,87 @@ void main() { for (final MapEntry(key: abi, value: backends) in expected.entries) { for (final backend in ['cpu', 'gpu']) { final admitted = backends.contains(backend); - // Admitting the GPU also needs a host GPU; 'admits the GPU delegate' - // covers it. - if (admitted && backend == 'gpu') continue; - test('${admitted ? 'admits' : 'refuses'} $backend on $abi', () async { + test( + '${admitted ? 'admits' : 'refuses'} $backend on $abi', + skip: backend == 'gpu' && !hostHasGpu + ? 'needs a host with a LiteRT-LM GPU backend' + : null, + () async { + service.dispose(); + service = tableService(); + await service.loadModel( + '${tempDir.path}/Qwen3-0.6B.litertlm', + backend == 'cpu' + ? params + : const ModelParams( + liteRtLmBackend: LiteRtLmBackendPreference.gpu, + ), + ); + debugLiteRtLmAbiOverride = abi; + if (admitted) { + await service.prepareJsonSchemaChat(); + expect(client.lastBackend, backend); + expect(client.lastJsonSchemaConfig, isTrue); + } else { + await expectRefused(backend); + } + }, + ); + } + } + for (final abi in [Abi.linuxX64, Abi.windowsX64, Abi.androidArm64]) { + test( + 'refuses the deprecated gpu backend override on $abi', + skip: hostHasGpu ? null : 'needs a host with a LiteRT-LM GPU backend', + () async { service.dispose(); - service = LiteRtLmService(clientFactory: () => client); + service = tableService(); await service.loadModel( '${tempDir.path}/Qwen3-0.6B.litertlm', - backend == 'cpu' - ? params - : const ModelParams( - liteRtLmBackend: LiteRtLmBackendPreference.gpu, - ), + const ModelParams(), + backendOverride: 'gpu', ); debugLiteRtLmAbiOverride = abi; - if (admitted) { - await service.prepareJsonSchemaChat(); - expect(client.lastJsonSchemaConfig, isTrue); - } else { - await expectLater( - service.prepareJsonSchemaChat(), - throwsA( - isA().having( - (e) => e.message, - 'message', - contains('not qualified for the LiteRT-LM $backend'), - ), - ), - ); - expect(client.createConversationCount, 0); - } - }); - } + await expectRefused('gpu'); + }, + ); } + test( + 'refuses an automatic GPU load that runs on an unqualified CPU', + skip: liteRtLmDefaultNativeBackendForCurrentPlatform() == 'gpu' + ? null + : 'needs a host whose automatic LiteRT-LM backend is the GPU', + () async { + service.dispose(); + service = tableService( + adapters: const LiteRtLmVulkanAdapters.devices([ + LiteRtLmVulkanAdapter( + name: 'llvmpipe', + deviceType: vulkanPhysicalDeviceTypeCpu, + ), + ]), + qualified: () => {'gpu'}, + ); + await service.loadModel( + '${tempDir.path}/Qwen3-0.6B.litertlm', + const ModelParams(), + ); + await expectRefused('cpu', beforeEngine: false); + expect(client.lastBackend, 'cpu'); + }, + ); + test('a reload repeats admission', () async { + service.dispose(); + service = tableService(); + final model = '${tempDir.path}/Qwen3-0.6B.litertlm'; + await service.loadModel(model, params); + debugLiteRtLmAbiOverride = Abi.linuxX64; + await service.prepareJsonSchemaChat(); + await service.loadModel(model, params); + debugLiteRtLmAbiOverride = Abi.macosX64; + client.createConversationCount = 0; + await expectRefused('cpu', beforeEngine: false); + }); }); test('missing optional API never admits or starts generation', () async { client.jsonSchemaSupport = false; diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 60c3e5757..f0d603ec2 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -1704,8 +1704,17 @@ Future main(List args) async { ['--backend', 'cpu'], ['--model-path', '/m.litertlm'], ['--model-path', '/m.litertlm', '--backend', 'npu'], + for (final secret in [ + 'https://user:token@example.com/m.litertlm', + 'https://example.com/m.litertlm?X-Amz-Signature=abc', + 'https://example.com/m.litertlm#token', + ]) + ['--model-path', secret, '--backend', 'cpu'], ]) { - expect((await dryRun(invalid)).exitCode, 64, reason: '$invalid'); + final rejected = await dryRun(invalid); + expect(rejected.exitCode, 64, reason: '$invalid'); + expect(rejected.stdout, isNot(contains('token'))); + expect(rejected.stderr, isNot(contains('token'))); } final path = await dryRun([ '--model-path', diff --git a/test/unit/tooling/test_matrix_test.dart b/test/unit/tooling/test_matrix_test.dart index 1cc40f504..9bcd22401 100644 --- a/test/unit/tooling/test_matrix_test.dart +++ b/test/unit/tooling/test_matrix_test.dart @@ -236,6 +236,36 @@ void main() { isFalse, ); }); + test('the device JSON Schema matrix command dry-runs its scenario', () async { + final row = testMatrixRows.singleWhere( + (row) => row.id == 'chat-app-litert-json-schema', + ); + expect(row.tier, 'high-risk'); + final args = row.command + .split(' ') + .skip(3) + .map( + (arg) => switch (arg) { + '' => 'android', + '' => '/data/local/tmp/m.litertlm', + _ => arg, + }, + ) + .toList(); + expect(args[args.indexOf('--scenario') + 1], row.id); + final result = await runLocalE2e( + [...args, '--dry-run'], + projectRoot: '/repo', + displayShell: LocalE2eDisplayShell.posix, + ); + expect(result.exitCode, 0, reason: result.stderr); + expect( + result.stdout, + contains( + 'integration_test/litert_lm_json_schema_e2e_test.dart -d android', + ), + ); + }); test( 'native JSON Schema matrix command reaches its maintained local-only scenario', () async { diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index cbd817165..ad1116099 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -2993,6 +2993,22 @@ Future runLocalE2e( stderr: '--model-path is required for ${scenario.name}.\n', ); } + // The URL is printed and compiled into the app, so it must carry no secret. + final modelUrl = scenario.name == 'chat-app-litert-json-schema' + ? Uri.tryParse(parsed.modelPath!) + : null; + if (modelUrl != null && + modelUrl.hasScheme && + (modelUrl.userInfo.isNotEmpty || + modelUrl.hasQuery || + modelUrl.hasFragment)) { + return LocalE2eResult( + 64, + stderr: + '${scenario.name} accepts a model URL without credentials, query or ' + 'fragment; serve the bundle from a plain URL.\n', + ); + } if ((scenario.name == 'litert-lm-json-schema' || scenario.name == 'chat-app-litert-json-schema') && (!parsed.backendProvided || diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 6bf2995ef..9063be7f7 100644 --- a/website/docs/changelog/recent-releases.md +++ b/website/docs/changelog/recent-releases.md @@ -14,7 +14,7 @@ validate against the exact release tag notes. ## Unreleased - Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)). -- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; GPUs on Android, Linux and Windows still throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). +- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; other hosts, GPUs on Android, Linux and Windows, and NPU throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)). ## 0.19.4 diff --git a/website/docs/guides/generation-and-streaming.md b/website/docs/guides/generation-and-streaming.md index 46990f655..161531a49 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -483,11 +483,17 @@ Patterns must be anchored `^...$` sequences of safe literals, positive character classes/ranges and groups, with group alternation and repetition counts up to 1024; unsupported regex constructs are rejected. Backends without grammar constraints still fail early for strict output unless they expose a -separate admitted JSON Schema provider. Native LiteRT-LM has that path on -macOS arm64 and iOS arm64 CPU and GPU and on the Android arm64, Linux x64/arm64 -and Windows x64 CPU, with Qwen3 (canonical text template) and Gemma 4 (bundle -template) models. GPUs on Android, Linux and Windows, and LiteRT-LM Web, refuse -it. +separate admitted JSON Schema provider. Native LiteRT-LM has that path for +Qwen3 (canonical text template) and Gemma 4 (bundle template) models on the +hosts below; every other host or accelerator, including NPU, Android x64, +macOS x64 and LiteRT-LM Web, refuses it before loading an engine. + +| Host | Admitted | Real-model runs that passed | +| --- | --- | --- | +| macOS arm64 | CPU, GPU | Qwen3 and Gemma 4, CPU and GPU | +| iOS arm64 | CPU, GPU | Simulator only: Qwen3 CPU and GPU, Gemma 4 CPU; Gemma 4 cannot create a GPU engine there | +| Android arm64 | CPU | Emulator only: Qwen3 CPU; Gemma 4 not yet run | +| Linux x64, Linux arm64, Windows x64 | CPU | Qwen3 and Gemma 4, CPU | Native LiteRT-LM accepts only schemas that both the GBNF converter above and LiteRT-LM's LLGuidance provider enforce alike, so every schema it accepts is diff --git a/website/docs/platforms/support-matrix.md b/website/docs/platforms/support-matrix.md index a565c6298..f2e7ef375 100644 --- a/website/docs/platforms/support-matrix.md +++ b/website/docs/platforms/support-matrix.md @@ -156,7 +156,7 @@ native and web. Model architecture support depends on the pinned runtime; see | Row split (`ModelSplitMode.row`) | Needs llama.cpp split buffer types, which no bundled backend provides; a load on a bundled GPU backend whose module loads (Metal, CUDA, HIP, Vulkan, OpenCL), with `GpuBackend.blas` or `GpuBackend.cpu`, with `auto` on Android, the iOS simulator and macOS x86_64 (which runs on the CPU), or that falls back to the CPU because the requested backend is missing or Vulkan is refused, throws `LlamaUnsupportedException` before the model loads, so use `ModelSplitMode.layer`; a bundled module that fails to load or finds no device loads row on the CPU instead ([#1576](https://github.com/leehack/llamadart/issues/1576)) | No | No | No | | Renamed legacy Qwen3 thinking switch | N/A: GGUF metadata | N/A: GGUF metadata | `chatTemplate: liteRtLmQwen3ChatTemplate`; requires native template setter | Canonical override throws at load: no template setter in `@litert-lm/core@0.19.0` | | Thinking budget | Text-only, without speculative decoding, when the native reasoning-budget export resolves | Text-only, with bridge assets whose `getCompletionCapabilities()` reports `thinkingBudget` ([llama-web-bridge#144](https://github.com/leehack/llama-web-bridge/pull/144)); otherwise rejected | Native chat, without speculative decoding, on bundles whose first response channel is a thinking channel (Gemma 4); bounds that channel only; `0` and `forcedMessage` rejected | No | -| Strict `responseFormat` | Yes | Yes, without tools | macOS and iOS arm64 CPU and GPU; Android arm64, Linux x64/arm64 and Windows x64 CPU (Android, Linux and Windows GPU refused), admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | +| Strict `responseFormat` | Yes | Yes, without tools | macOS arm64 CPU/GPU, iOS arm64 CPU/GPU (simulator runs; Gemma 4 GPU fails engine creation), Android arm64 CPU (emulator, Qwen3 only), Linux x64/arm64 and Windows x64 CPU; every other host, GPU or NPU refused, admitted Qwen3 (canonical text template) or Gemma 4 (bundle template) model; the schema subset both GBNF and LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); thinking with Gemma 4 only; no tools/media/speculation/caller stops | No | | Lazy grammar | Yes | Yes when the loaded bridge reports `lazyGrammar`; otherwise first-token `root` only | No GBNF grammar | No GBNF grammar | | Presence penalty | Yes | With bridge assets whose `getCompletionCapabilities()` reports `presencePenalty` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | Yes, without speculative decoding; counts only tokens of the current send | No: rejects a non-zero value | | Min-P | Yes | With bridge assets whose `getCompletionCapabilities()` reports `minP` ([llama-web-bridge#140](https://github.com/leehack/llama-web-bridge/pull/140)); otherwise rejects a non-zero value | No: rejects a non-zero value | No: rejects a non-zero value |