diff --git a/CHANGELOG.md b/CHANGELOG.md index 20bd16276..2715deec7 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, 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 101f60176..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 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 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/litert_lm_templates.md b/doc/litert_lm_templates.md index 8c5ac42a3..9fbf69c86 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, 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/doc/testing_matrix.md b/doc/testing_matrix.md index 79bd9d096..16961047f 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,13 @@ 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; 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 new file mode 100644 index 000000000..f8ad04fba --- /dev/null +++ b/example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart @@ -0,0 +1,231 @@ +@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 passes the model path or URL and the backend as defines; serving a +/// URL is up to the caller. +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, + ), + ); + 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'}); + 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 78523b67a..c74f3be1a 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; the others +// stay refused until a run on that host passes. +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 /// [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,15 @@ 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 ? '' : '; 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; @@ -686,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 2e7604fb4..f774e66de 100644 --- a/skills/llamadart-chat-streaming/SKILL.md +++ b/skills/llamadart-chat-streaming/SKILL.md @@ -188,8 +188,10 @@ 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, 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 4df0baf81..f17a8a66b 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( @@ -159,6 +160,132 @@ void main() { expect(client.generateCount, 0); }); } + 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'}, + Abi.androidArm64: {'cpu'}, + Abi.androidX64: {}, + Abi.linuxX64: {'cpu'}, + Abi.linuxArm64: {'cpu'}, + Abi.windowsX64: {'cpu'}, + Abi.macosX64: {}, + }; + for (final MapEntry(key: abi, value: backends) in expected.entries) { + for (final backend in ['cpu', 'gpu']) { + final admitted = backends.contains(backend); + 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 = tableService(); + await service.loadModel( + '${tempDir.path}/Qwen3-0.6B.litertlm', + const ModelParams(), + backendOverride: 'gpu', + ); + debugLiteRtLmAbiOverride = abi; + 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; await expectLater( @@ -256,7 +383,7 @@ void main() { ..finishReason = LiteRtLmFinishReason.stop; service = LiteRtLmService( clientFactory: () => client, - jsonSchemaPlatformSupported: () => true, + jsonSchemaQualifiedBackends: () => {'cpu', 'gpu'}, readBundleFirstChannel: (_) => reasoningChannel ? (name: 'thought', isReasoning: true) : null, ); @@ -2015,7 +2142,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..f0d603ec2 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,65 @@ 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'], + 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'], + ]) { + 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', + '/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/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 46a9a6e73..ad1116099 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,37 @@ 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', + ); + } + // 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 || (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', diff --git a/website/docs/changelog/recent-releases.md b/website/docs/changelog/recent-releases.md index 67ac58301..9063be7f7 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, 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 c53c4e165..161531a49 100644 --- a/website/docs/guides/generation-and-streaming.md +++ b/website/docs/guides/generation-and-streaming.md @@ -483,9 +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 CPU and GPU with Qwen3 (canonical text template) and Gemma 4 -(bundle template) models; LiteRT-LM Web does not. +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 5facd4156..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 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 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 |