diff --git a/doc/testing_matrix.md b/doc/testing_matrix.md index 8c154ddae..e00015220 100644 --- a/doc/testing_matrix.md +++ b/doc/testing_matrix.md @@ -150,6 +150,7 @@ Pick targeted rows based on the touched surface: | LiteRT-LM web / Gemma 4 web bundle | `gemma4-litert-web` | | Chat app model cache/download/projector | `chat-app-device-cache` | | LiteRT-LM engine reload memory on a device | `chat-app-litert-reload-memory` | +| Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` | | Isolate shutdown releases, exit teardown, a Flutter pin bump, or app-exit guidance | `chat-app-macos-quit` | | Speech-to-text API or adapter | `speech-to-text-smoke`, `web-speech-to-text-smoke`, plus `litert-lm-asr-smoke` for the dedicated LiteRT-LM streaming engine | | Text-to-speech API or adapter | `text-to-speech-smoke`, plus `web-text-to-speech-smoke` for browser synthesis/playback/export | diff --git a/example/chat_app/README.md b/example/chat_app/README.md index f16086963..18df2369f 100644 --- a/example/chat_app/README.md +++ b/example/chat_app/README.md @@ -807,3 +807,95 @@ temperature 0, seed 1). The matching build-time defaults are `LITERT_RELOAD_TEMPERATURE` and `LITERT_RELOAD_SEED`. An argument passed as an empty string keeps its default. Fewer than three iterations record the steps without the memory check. + +#### Micro-batch sweep and the Android Vulkan prompt cap + +`integration_test/micro_batch_sweep_e2e_test.dart` loads the locked +`chat-gguf-vulkan` model at several micro-batch sizes in one process and sends +a short history prompt, a long history prompt and a tool request with +`ToolChoice.auto` and `ToolChoice.required` at each. Size `0` is the library +default and the only one the test judges, so the sizes must include it: a +default attempt must load, answer both history prompts with the code and +nothing else, and end both tool requests as the `get_weather` call. + +Every other size is a control that is only recorded. An explicit size, even +`512` (the default `n_ubatch`), makes the library leave the Android Vulkan +prompt cap off, so `0+512` compares the capped default with the same context +uncapped. On a Vulkan device with the small matmul tile defect the control is +expected to answer wrongly (a Pixel 9 Pro's Mali-G715, subgroup size 16, +answered `8888...`); a correct control there says the cap is no longer needed. + +Every repeat of the default size runs first, then the controls repeat by +repeat, and a control sends the tool requests only in its last repeat, so +nothing a control does to the process costs a judged repeat. + +```sh +dart run tool/testing/run_local_e2e.dart \ + --scenario chat-app-micro-batch-sweep --device +``` + +Only an Android device whose GPU ggml-vulkan registers makes the library +decide about the cap. Elsewhere the run checks the default path and the +harness. + +For Test Lab, build both APKs from that target as above, then add: + +```sh +--environment-variables=microBatchArms=0+512,microBatchRepeats=6,microBatchBudgetSeconds=450,microBatchNativeLog=debug \ +--directories-to-pull=/sdcard/Android/data/com.example.llamadart_chat_example/files/micro_batch_sweep +``` + +The pulled directory holds `journal.jsonl`, `native_stderr.log`, `vkjson.json` +(`cmd gpu vkjson`, saved before Flutter starts: the driver's API version and +subgroup size) and `app_apk.sha256`. Every journal record is written through +before the next step, and the same records appear in logcat as +`MICRO_BATCH_SWEEP` lines. In the journal: + +- `attempt_verdict` is the verdict of one attempt: `passed`, the judged cases + one by one, the failures and the cap state. `judged` is true for the default + size. A run that dies keeps the verdicts of the attempts before it. +- `prompt_cap` is what is known about the cap of an attempt's context, as + `state`: + - `capped` (with `cap_tokens`) or `not_capped`: the library's own debug + line, with the Vulkan devices it decided from (`name`, `api_version`, + `loader_api_version`, `subgroup_size`). The library logs it only when it + has a Vulkan device to decide from. + - `no_vulkan_device`: the load asked Vulkan for GPU layers but ggml-vulkan + registered no device. The library logs nothing and applies the cap all the + same, although the context runs on the CPU (an emulator, or a load that + fell back). + - `explicit_size`: an explicit size, which leaves the cap off. + - `vulkan_not_requested`, `not_android`: no cap. + - `not_logged`: a Vulkan device is registered and the cap was to be decided, + but no decision reached the log. Treat the record as missing. +- `load` holds the backend the model runs on, its GPU layer count and the GPU + devices the runtime lists. +- `log` is every `LlamaLogger` record, among them the warning of a load that + fell back to the CPU because the Vulkan driver is below 1.2. +- `load_refused` is a typed exception from a load. +- `case` and `case_error` are each answer (with `passed` for a judged case) + and each typed exception from a request; `summary` counts the passing + answers by size. + +`microBatchDevice=gpu` asks each load for `ComputeDevice.gpu` first, records a +typed refusal as `load_refused` and then loads as the profile does +(`ComputeDevice.auto`), so one run shows whether a device that cannot run +Vulkan gets a typed error and a CPU fallback. The other arguments are +`microBatchProfile` (a validation profile id) and, at build time, +`--dart-define=MICRO_BATCH_SWEEP_ARMS`, `MICRO_BATCH_SWEEP_REPEATS`, +`MICRO_BATCH_SWEEP_BUDGET_SECONDS`, `MICRO_BATCH_SWEEP_NATIVE_LOG`, +`MICRO_BATCH_SWEEP_DEVICE`, `MICRO_BATCH_SWEEP_PROFILE` and +`MICRO_BATCH_SWEEP_MODEL`. + +The budget counts from the end of the model download and check. Past it no +attempt and no request starts and the test fails, which keeps a slow device +inside the Test Lab timeout; give the timeout the download on top (it took 1.5 +to 4 minutes for this model on Test Lab) and the length of one request. + +`--dart-define=MICRO_BATCH_SWEEP_NEGATIVE_CONTROL=true` checks the judge: it +expects a code the prompts do not hold, so the test must fail, with failures +of the default size only. + +When a native crash ends the app, Test Lab reports `Test failed to run`. It +still pulls the directory: the last `attempt_started` or `case_started` record +without its result names the step that was running. diff --git a/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java b/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java index 87c10a159..556a28f80 100644 --- a/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java +++ b/example/chat_app/android/app/src/androidTest/java/com/example/llamadart_chat_example/MainActivityTest.java @@ -30,6 +30,7 @@ public MainActivityTest() throws IOException { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); if ("true".equals(arguments.getString("stageModel"))) stageModel(instrumentation); forwardReloadMemoryArguments(arguments, instrumentation); + forwardMicroBatchSweepArguments(arguments, instrumentation); } private static void stageModel(Instrumentation instrumentation) throws IOException { @@ -85,6 +86,33 @@ private static void forwardReloadMemoryArguments(Bundle arguments, Instrumentati if (snapshots) startDumpsysResponder(instrumentation, cache); } + // Hands micro_batch_sweep_e2e_test.dart its instrumentation arguments, and + // with any of them saves the device facts next to its journal. + private static void forwardMicroBatchSweepArguments(Bundle arguments, Instrumentation instrumentation) + throws IOException { + File file = new File(instrumentation.getTargetContext().getCacheDir(), "micro_batch_sweep_args.json"); + JSONObject json = new JSONObject(); + try { + json.put("arms", optional(arguments, "microBatchArms")); + json.put("repeats", optional(arguments, "microBatchRepeats")); + json.put("budget_seconds", optional(arguments, "microBatchBudgetSeconds")); + json.put("profile", optional(arguments, "microBatchProfile")); + json.put("native_log", optional(arguments, "microBatchNativeLog")); + json.put("device", optional(arguments, "microBatchDevice")); + if (json.length() == 0) { + file.delete(); + return; + } + json.put("pid", Process.myPid()); + } catch (JSONException error) { + throw new IOException(error); + } + write(file, json.toString()); + // Connect UiAutomation before Flutter starts, as the dumpsys responder does. + instrumentation.getUiAutomation(); + saveDeviceFacts(instrumentation, "micro_batch_sweep"); + } + // Null for a blank value: a runner that passes an optional argument as an // empty string means the default, and JSONObject.put drops a null value. private static String optional(Bundle arguments, String name) { @@ -95,10 +123,10 @@ private static String optional(Bundle arguments, String name) { // Next to the journal: the Vulkan driver's own limits, from which a WebGPU // limit that a run trips over is derived, and the hash of the installed // app APK, which names the runtime libraries the run loaded. - private static void saveDeviceFacts(Instrumentation instrumentation) { + private static void saveDeviceFacts(Instrumentation instrumentation, String output) { try { Context context = instrumentation.getTargetContext(); - File directory = new File(context.getExternalFilesDir(null), "litert_reload_memory"); + File directory = new File(context.getExternalFilesDir(null), output); if (!directory.isDirectory() && !directory.mkdirs()) { throw new IOException("Unable to create " + directory); } @@ -122,7 +150,7 @@ private static void startDumpsysResponder(Instrumentation instrumentation, File // semantics. Connect before Flutter starts: a semantics handle that // appears during the test fails it at the end. instrumentation.getUiAutomation(); - saveDeviceFacts(instrumentation); + saveDeviceFacts(instrumentation, "litert_reload_memory"); Thread responder = new Thread(() -> { while (true) { try { diff --git a/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart b/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart new file mode 100644 index 000000000..92dbc5075 --- /dev/null +++ b/example/chat_app/integration_test/micro_batch_sweep_e2e_test.dart @@ -0,0 +1,973 @@ +@Tags(['local-only', 'e2e']) +@Timeout(Duration(minutes: 25)) +/// Local-only E2E that runs history, long-history and tool prompts at several +/// micro-batch sizes (`ModelParams.microBatchSize`, llama.cpp `n_ubatch`) in +/// one process, and records what the library decided about the Android Vulkan +/// text prompt cap (https://github.com/leehack/llamadart/issues/948). +/// +/// Each attempt loads the locked model of a validation profile on a new +/// engine, generates the `C03.raw`, `C04.hello`, `C04.arithmetic`, +/// `C06.history`, `X01.long_history`, `C07.tools.auto` and +/// `C07.tools.required` requests through the validation engine, and disposes +/// the engine. +/// +/// Size `0` is the library default and the only one the test judges; the +/// sizes must include it. A default attempt passes when it loads, answers +/// `C06.history` and `X01.long_history` with the code and nothing else, and +/// ends both tool requests as the `get_weather` call. The test fails after +/// the sweep when a default attempt did not pass. On Android Vulkan the +/// default is the capped path wherever the library applies the cap. +/// +/// Every other size is a control and is only recorded. An explicit size, even +/// one equal to the default `n_ubatch` (512), makes the library leave the cap +/// off, so `0,512` compares the capped default with the same context +/// uncapped. That control is expected to answer wrongly on a Vulkan device +/// with the small matmul tile defect (a Pixel 9 Pro's Mali-G715, subgroup size +/// 16, answered `8888...`); a correct control there says the cap is no longer +/// needed. +/// +/// Every repeat of the default size runs first, then the controls repeat by +/// repeat, and a control sends the tool requests only in its last repeat: a +/// grammar over a control's logits is what aborted the process before native +/// exceptions were typed, and nothing a control does to the process may cost +/// a judged repeat. +/// +/// Records go to `micro_batch_sweep/journal.jsonl` (app external files on +/// Android, the temporary directory elsewhere), each written through before +/// the next step, and, shortened, to the log as `MICRO_BATCH_SWEEP {json}` +/// lines. An `attempt_started` and a `case_started` record precede each step, +/// so a run that dies names the step it died in, and the verdicts of the +/// attempts before it are already in the file. `t_ms` is the time since the +/// test opened the journal. +/// +/// - `log`: every `LlamaLogger` record at `debug` and above, among them the +/// warning of a load that fell back to the CPU. +/// - `load`: the backend the model runs on, its GPU layer count, the batch +/// sizes and the GPU devices the runtime lists. +/// - `prompt_cap`: what is known about the cap of the attempt's context, as +/// `state`. `capped` (with `cap_tokens`) and `not_capped` are the library's +/// own debug line, with the Vulkan devices the decision was made from +/// (name, driver and loader API version, subgroup size). The library logs +/// that line only when it has a Vulkan device to decide from, so the other +/// states are derived from the load: `explicit_size` (an explicit size +/// leaves the cap off), `not_android`, `vulkan_not_requested` (no GPU layer +/// asked of Vulkan: no cap), `no_vulkan_device` (GPU layers asked of Vulkan +/// but ggml-vulkan registered no device: the library applies the cap +/// without logging, and the context runs on the CPU) and `not_logged` (a +/// Vulkan device is registered but no decision reached the log). +/// - `load_refused`: a typed exception from a load, such as the refusal of a +/// Vulkan driver below 1.2. +/// - `case`, `case_error`: each answer with its timings and, for a judged +/// case, `passed`; a typed exception from a request. +/// - `attempt_verdict`: whether the attempt passed, case by case, with the +/// failures and the cap state. `judged` is true for the default size. +/// - `summary`: the passing answers by size and the test's failures. +/// +/// A `case` record times the prompt twice. `native_prompt_ms` is the llama.cpp +/// worker's own clock around prompt ingestion, valid at every micro-batch +/// size, and `prompt_tps` is `prompt_tokens` over it. `native_prompt_tokens` +/// is llama.cpp's counter, which leaves the prompt out at micro-batch size 1. +/// `ttfa_ms` is this isolate's clock from the request to the first streamed +/// text: it adds templating, the isolate hops and the first stream batch. +/// +/// Native llama.cpp output goes to standard error, which Android discards; +/// this test points standard error at `micro_batch_sweep/native_stderr.log` +/// and copies the `ggml_vulkan:` device lines and the context's `n_batch` and +/// `n_ubatch` from it into the records. The device lines need `debug`. +/// +/// ```bash +/// cd example/chat_app +/// flutter test --run-skipped -t local-only \ +/// integration_test/micro_batch_sweep_e2e_test.dart -d \ +/// --dart-define=MICRO_BATCH_SWEEP_ARMS=0,512 \ +/// --dart-define=MICRO_BATCH_SWEEP_REPEATS=3 +/// ``` +/// +/// `MICRO_BATCH_SWEEP_ARMS` lists the sizes. `MICRO_BATCH_SWEEP_REPEATS` +/// counts the rounds. `MICRO_BATCH_SWEEP_BUDGET_SECONDS` is the time the sweep +/// may take, counted from the end of the model download and check: past it no +/// attempt and no request starts, and the test fails. +/// `MICRO_BATCH_SWEEP_PROFILE` names the validation profile (default +/// `chat-gguf-vulkan`), `MICRO_BATCH_SWEEP_NATIVE_LOG` the native log level +/// (`info` or `debug`, default `info`) and `MICRO_BATCH_SWEEP_MODEL` a local +/// copy of the profile's model. `MICRO_BATCH_SWEEP_DEVICE=gpu` asks each load +/// for `ComputeDevice.gpu` first, records a typed refusal and then loads as +/// the profile does (`ComputeDevice.auto`), so one run shows both what a +/// required GPU and what the default do on the device. A blank value keeps +/// the default. +/// +/// `MICRO_BATCH_SWEEP_NEGATIVE_CONTROL=true` checks the judge: it expects a +/// code the prompts do not hold, so the test must fail, with failures of the +/// default size only. +/// +/// Under Android instrumentation (Firebase Test Lab or `adb shell am +/// instrument`), `MainActivityTest` forwards the arguments `microBatchArms` +/// (`+`-separated), `microBatchRepeats`, `microBatchBudgetSeconds`, +/// `microBatchProfile`, `microBatchNativeLog` and `microBatchDevice`, and with +/// any of them saves `cmd gpu vkjson` (the Vulkan driver's properties, among +/// them the API version and the subgroup size) and the installed app APK's +/// SHA-256 next to the journal before Flutter starts. +library; + +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:integration_test/integration_test.dart'; +import 'package:llamadart/llamadart.dart'; +import 'package:llamadart_validation/io.dart'; +import 'package:llamadart_validation/llamadart_validation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import 'support/micro_batch_sweep_support.dart'; +import 'support/process_memory_snapshot.dart'; + +const _logTag = 'MICRO_BATCH_SWEEP'; +const _profileAssets = 'packages/llamadart_validation/assets/profiles/'; +const _argumentsFile = 'micro_batch_sweep_args.json'; +const _maxLoggedText = 160; +const _defaultArm = 0; +const _historyCase = 'C06.history'; +const _longCase = 'X01.long_history'; +// The locked Q4_0 model answers this prompt with `42` on CPU and Metal too; +// only the Q4_K_M quantization repeats the whole `maple42`. +const _longCodes = ['42', 'maple42']; +const _negativeControlCode = 'birch93'; +const _longMaxTokens = 12; +const _toolMaxTokens = 128; +const _toolCases = { + 'C07.tools.auto': ToolChoice.auto, + 'C07.tools.required': ToolChoice.required, +}; + +/// A history of about 300 prompt tokens whose first turn holds the code. The +/// filler spells its numbers out, so a digit in the answer comes from the code. +const _longHistory = <(LlamaChatRole, String)>[ + ( + LlamaChatRole.system, + 'You are a careful assistant. Remember the access code exactly.', + ), + (LlamaChatRole.user, 'The access code is maple42.'), + (LlamaChatRole.assistant, 'I will remember the access code.'), + ( + LlamaChatRole.user, + 'Before we continue, here is a note about the warehouse. The north ' + 'shelves hold garden tools, the south shelves hold paint, and the ' + 'loading dock opens at seven each morning.', + ), + ( + LlamaChatRole.assistant, + 'Noted: garden tools north, paint south, and the dock opens at seven.', + ), + ( + LlamaChatRole.user, + 'Another note. The delivery van is blue, it needs new tires before ' + 'winter, and the driver prefers the coastal road because it has fewer ' + 'traffic lights.', + ), + ( + LlamaChatRole.assistant, + 'Noted: the blue van needs tires, and the driver likes the coastal road.', + ), + ( + LlamaChatRole.user, + 'One more. The office plants are watered on Mondays, the printer on the ' + 'second floor jams when the paper is damp, and the spare keys are ' + 'kept in the grey cabinet.', + ), + ( + LlamaChatRole.assistant, + 'Noted: plants on Mondays, a moody printer, and keys in the grey cabinet.', + ), + ( + LlamaChatRole.user, + 'Last note. The team lunch is on Thursday at noon, the bakery across the ' + 'street closes early on Fridays, and the meeting room projector needs ' + 'a new cable.', + ), + ( + LlamaChatRole.assistant, + 'Noted: lunch on Thursday at noon, the bakery closes early on Fridays, ' + 'and the projector needs a cable.', + ), + (LlamaChatRole.user, 'What is the access code? Reply with only the code.'), +]; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('the default micro-batch answers history and tool prompts', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold(body: Text('Running micro-batch sweep E2E')), + ), + ); + final temporary = await getTemporaryDirectory(); + final config = _Config.resolve(temporary); + final output = Directory( + p.join( + ((Platform.isAndroid ? await getExternalStorageDirectory() : null) ?? + temporary) + .path, + 'micro_batch_sweep', + ), + )..createSync(recursive: true); + final journal = _Journal(File(p.join(output.path, 'journal.jsonl'))); + final nativeLog = _NativeLog.capture( + File(p.join(output.path, 'native_stderr.log')), + ); + addTearDown(nativeLog.restore); + final order = sweepOrder( + config.arms, + config.repeats, + judgedArm: _defaultArm, + ); + journal.log({ + 'event': 'config', + 'profile': config.profile, + 'arms': config.arms, + 'repeats': config.repeats, + 'order': [ + for (final attempt in order) [attempt.repeat, attempt.arm], + ], + 'budget_seconds': config.budget?.inSeconds, + 'native_log': config.nativeLevel.name, + 'device': config.device?.name, + 'negative_control': config.negativeControl, + 'source': config.source, + 'native_stderr_captured': nativeLog.captured, + 'pid': pid, + 'os': Platform.operatingSystem, + 'os_version': Platform.operatingSystemVersion, + }); + final logs = _LibraryLog(journal); + // Set once, before the first engine starts its worker: ggml-vulkan prints + // its device lines only when the process first initializes the backend. + await LlamaLogging.configure( + level: LlamaLogLevel.debug, + nativeLevel: config.nativeLevel, + handler: logs.record, + ); + addTearDown(LlamaLogging.configure); + + final profile = await _loadProfile(config.profile); + final modelPath = await _prepareModel(profile, config.model, journal); + // The budget is for the sweep: a download takes minutes that vary with + // the network, and would otherwise decide how many repeats run. + final elapsed = Stopwatch()..start(); + final budget = config.budget; + bool overBudget() => budget != null && elapsed.elapsed > budget; + final codes = config.negativeControl + ? const { + _historyCase: [_negativeControlCode], + _longCase: [_negativeControlCode], + } + : { + _historyCase: [profile.fixtureText('history', 'expected')], + _longCase: _longCodes, + }; + final judgedCases = [...codes.keys, ..._toolCases.keys]; + final failures = []; + final correct = { + for (final id in judgedCases) id: {for (final arm in config.arms) arm: 0}, + }; + final capStates = {for (final arm in config.arms) arm: {}}; + var judgedPassed = 0; + for (final (:repeat, :arm) in order) { + final labels = {'repeat': repeat, 'micro_batch': arm}; + final judged = arm == _defaultArm; + final withTools = judged || repeat == config.repeats; + if (overBudget()) { + journal.log({ + 'event': 'budget_exhausted', + ...labels, + 'elapsed_seconds': elapsed.elapsed.inSeconds, + }); + failures.add( + 'stopped before micro-batch $arm repeat $repeat: over the ' + '${budget!.inSeconds} s budget', + ); + break; + } + logs.begin(labels); + var results = const {}; + String? loadError; + try { + results = await _attempt( + profile, + modelPath, + labels, + arm, + config.device, + withTools: withTools, + codes: codes, + overBudget: overBudget, + journal: journal, + nativeLog: nativeLog, + logs: logs, + ); + } on LlamaException catch (error) { + journal.log({ + 'event': 'attempt_error', + ...labels, + 'error_type': '${error.runtimeType}', + 'error': '$error', + }); + loadError = '${error.runtimeType}: $error'; + } + final verdict = judgeAttempt( + [...codes.keys, if (withTools) ..._toolCases.keys], + results, + loadError: loadError, + ); + journal.log({ + 'event': 'attempt_verdict', + ...labels, + 'judged': judged, + 'passed': verdict.passed, + 'cases': verdict.cases, + 'failures': verdict.failures, + 'prompt_cap': logs.capState, + }); + for (final MapEntry(key: id, value: passed) in verdict.cases.entries) { + if (passed) correct[id]![arm] = correct[id]![arm]! + 1; + } + if (logs.capState case final state?) capStates[arm]!.add(state); + if (judged) { + if (verdict.passed) judgedPassed++; + failures.addAll([ + for (final failure in verdict.failures) + 'default micro-batch repeat $repeat: $failure', + ]); + } + } + logs.begin(const {}); + journal.log({ + 'event': 'summary', + 'expected': codes, + 'repeats': config.repeats, + 'judged_micro_batch': _defaultArm, + 'judged_passed': judgedPassed, + 'correct': { + for (final MapEntry(key: id, value: arms) in correct.entries) + id: { + for (final MapEntry(:key, :value) in arms.entries) '$key': value, + }, + }, + 'prompt_cap': { + for (final MapEntry(:key, :value) in capStates.entries) + '$key': value.toList(), + }, + 'failures': failures, + }); + expect(failures, isEmpty, reason: failures.join('\n')); + }, timeout: const Timeout(Duration(minutes: 25))); +} + +class _Config { + _Config( + this.profile, + this.arms, + this.repeats, + this.budget, + this.nativeLevel, + this.device, + this.model, + this.source, { + required this.negativeControl, + }); + + factory _Config.resolve(Directory temporary) { + var profile = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_PROFILE'), + ) ?? + 'chat-gguf-vulkan'; + var arms = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_ARMS'), + ) ?? + '0,512'; + var repeats = const int.fromEnvironment( + 'MICRO_BATCH_SWEEP_REPEATS', + defaultValue: 3, + ); + var budget = const int.fromEnvironment('MICRO_BATCH_SWEEP_BUDGET_SECONDS'); + var nativeLog = + optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_NATIVE_LOG'), + ) ?? + 'info'; + var device = optionalArgument( + const String.fromEnvironment('MICRO_BATCH_SWEEP_DEVICE'), + ); + var source = 'dart-define'; + final file = File(p.join(temporary.path, _argumentsFile)); + if (Platform.isAndroid && file.existsSync()) { + final arguments = jsonDecode(file.readAsStringSync()) as Map; + // The file outlives the instrumentation that wrote it. + if (arguments['pid'] == pid) { + profile = optionalArgument(arguments['profile']) ?? profile; + arms = optionalArgument(arguments['arms']) ?? arms; + final count = optionalArgument(arguments['repeats']); + if (count != null) repeats = int.parse(count); + final seconds = optionalArgument(arguments['budget_seconds']); + if (seconds != null) budget = int.parse(seconds); + nativeLog = optionalArgument(arguments['native_log']) ?? nativeLog; + device = optionalArgument(arguments['device']) ?? device; + source = 'instrumentation'; + } + } + final sizes = [ + for (final size in arms.split(RegExp('[,+]'))) + if (size.trim().isNotEmpty) int.parse(size.trim()), + ]; + if (sizes.any((size) => size < 0)) { + throw ArgumentError.value(arms, 'arms', 'needs non-negative sizes'); + } + if (!sizes.contains(_defaultArm)) { + throw ArgumentError.value( + arms, + 'arms', + 'must include 0, the library default, which is the size the test ' + 'judges', + ); + } + if (repeats < 1) { + throw ArgumentError.value(repeats, 'repeats', 'must be at least 1'); + } + if (budget < 0) { + throw ArgumentError.value(budget, 'budget', 'must not be negative'); + } + if (!const {'info', 'debug'}.contains(nativeLog)) { + throw ArgumentError.value(nativeLog, 'native log', 'is info or debug'); + } + if (!const {null, 'auto', 'gpu'}.contains(device)) { + throw ArgumentError.value(device, 'device', 'is auto or gpu'); + } + return _Config( + profile, + sizes, + repeats, + budget == 0 ? null : Duration(seconds: budget), + LlamaLogLevel.values.byName(nativeLog), + device == null ? null : ComputeDevice.values.byName(device), + optionalArgument(const String.fromEnvironment('MICRO_BATCH_SWEEP_MODEL')), + source, + negativeControl: const bool.fromEnvironment( + 'MICRO_BATCH_SWEEP_NEGATIVE_CONTROL', + ), + ); + } + + final String profile; + + /// Micro-batch sizes; 0 is the library default and is always among them. + final List arms; + final int repeats; + + /// The time after the model is ready past which no attempt and no request + /// starts; null for no limit. + final Duration? budget; + final LlamaLogLevel nativeLevel; + + /// The device each load asks for first; null for the profile's own. + final ComputeDevice? device; + final String? model; + final String source; + + /// Whether the judge expects a code the prompts do not hold. + final bool negativeControl; +} + +Future _loadProfile(String id) async { + final source = await rootBundle.loadString('$_profileAssets$id.json'); + final data = jsonDecode(source) as Map; + data['execution_path'] = 'public_api'; + return ValidationProfile.fromJson(data); +} + +Future _prepareModel( + ValidationProfile profile, + String? supplied, + _Journal journal, +) async { + final cache = Directory( + p.join( + (await getApplicationSupportDirectory()).path, + 'validation', + 'models', + ), + ); + final client = http.Client(); + try { + final model = await prepareModel( + profile, + cache, + suppliedPath: supplied, + client: client, + timeout: const Duration(minutes: 10), + ); + journal.log({ + 'event': 'model', + 'filename': profile.filename, + 'revision': profile.model['revision'], + ...model.evidence, + }); + return model.path; + } finally { + client.close(); + } +} + +/// Loads [modelPath] on a new engine with [params]. +/// +/// With a [first] device other than the one in [params], that device is +/// tried first; a typed refusal is recorded and the load is repeated as +/// [params] has it. +Future<({LlamaEngine engine, ModelParams params})> _load( + String modelPath, + ModelParams params, + ComputeDevice? first, + Map labels, + _Journal journal, +) async { + final devices = {?first, params.device}; + for (final device in devices) { + final attempt = params.copyWith(device: device); + final engine = LlamaEngine(LlamaBackend()); + try { + await engine.setModel( + LlamaModel(ModelSource.parse(modelPath)), + params: attempt, + ); + return (engine: engine, params: attempt); + } on LlamaException catch (error) { + await engine.dispose(); + journal.log({ + 'event': 'load_refused', + ...labels, + 'device': device.name, + 'error_type': '${error.runtimeType}', + 'message': error.message, + 'details': error.details?.toString(), + }); + if (device == devices.last) rethrow; + } + } + throw StateError('unreachable: the last device rethrows'); +} + +/// Runs one load, the requests and the dispose, and returns how each judged +/// request ended by case. A request that [overBudget] stopped is left out. +Future> _attempt( + ValidationProfile profile, + String modelPath, + Map labels, + int microBatchSize, + ComputeDevice? device, { + required bool withTools, + required Map> codes, + required bool Function() overBudget, + required _Journal journal, + required _NativeLog nativeLog, + required _LibraryLog logs, +}) async { + journal.log({'event': 'attempt_started', ...labels}); + final logStart = nativeLog.length; + final watch = Stopwatch()..start(); + final loaded = await _load( + modelPath, + profile.loadParams.copyWith(microBatchSize: microBatchSize), + device, + labels, + journal, + ); + final engine = loaded.engine; + // The validation engine sends the requests exactly as the validation suite + // does; it is handed a loaded engine because its own load has no + // micro-batch size and resets the log levels. + final validation = PublicValidationEngine(engineFactory: () => engine); + try { + final diagnostics = await validation.diagnostics(); + final loadLog = nativeLog.since(logStart); + final resolved = resolveModelContextBatchSizes( + loaded.params, + profile.contextSize, + ); + List? gpuDevices; + try { + gpuDevices = await engine.listGpuDevices(); + } on LlamaException catch (error) { + journal.log({ + 'event': 'gpu_devices_error', + ...labels, + 'error_type': '${error.runtimeType}', + 'message': error.message, + }); + } + final gpuLayers = diagnostics['reported_gpu_layers'] as int? ?? 0; + journal.log({ + 'event': 'load', + ...labels, + 'ms': watch.elapsedMilliseconds, + 'device': loaded.params.device.name, + 'resolved_batch': resolved.batchSize, + 'resolved_micro_batch': resolved.microBatchSize, + 'native_n_batch': _contextValue(loadLog, 'n_batch'), + 'native_n_ubatch': _contextValue(loadLog, 'n_ubatch'), + 'backend_name': diagnostics['backend_name'], + 'reported_gpu_layers': gpuLayers, + 'context_size': diagnostics['context_size'], + 'gpu_devices': gpuDevices == null + ? null + : [ + for (final gpu in gpuDevices) + { + 'name': gpu.name, + 'backend': gpu.backend.name, + 'description': gpu.description, + }, + ], + 'native_log_bytes': loadLog.length, + }); + for (final line in loadLog.split('\n')) { + if (line.startsWith('ggml_vulkan:')) { + journal.log({'event': 'native_device', ...labels, 'line': line.trim()}); + } + } + final vulkanDevices = gpuDevices + ?.where((gpu) => gpu.backend == GpuBackend.vulkan) + .length; + final vulkanRequested = + loaded.params.preferredBackend == GpuBackend.vulkan && gpuLayers > 0; + final decision = logs.decision; + final state = promptCapState( + logged: decision, + microBatchSize: microBatchSize, + isAndroid: Platform.isAndroid, + vulkanRequested: vulkanRequested, + registeredVulkanDevices: vulkanDevices, + ); + logs.capState = state.wireName; + journal.log({ + 'event': 'prompt_cap', + ...labels, + 'state': state.wireName, + 'cap_tokens': decision?.capTokens, + 'devices': [ + for (final vulkan in decision?.devices ?? const []) + { + 'name': vulkan.name, + 'api_version': vulkan.apiVersion, + 'loader_api_version': vulkan.loaderApiVersion, + 'subgroup_size': vulkan.subgroupSize, + }, + ], + 'detail': decision?.detail, + 'backend_name': diagnostics['backend_name'], + 'vulkan_requested': vulkanRequested, + 'registered_vulkan_devices': vulkanDevices, + }); + + LlamaChatMessage message( + LlamaChatRole role, + String fixture, + String field, + ) => LlamaChatMessage.fromText( + role: role, + text: profile.fixtureText(fixture, field), + ); + final cases = ?>{ + 'C03.raw': null, + 'C04.hello': [message(LlamaChatRole.user, 'hello', 'prompt')], + 'C04.arithmetic': [message(LlamaChatRole.user, 'arithmetic', 'prompt')], + _historyCase: [ + message(LlamaChatRole.system, 'history', 'system'), + message(LlamaChatRole.user, 'history', 'user'), + message(LlamaChatRole.assistant, 'history', 'assistant'), + message(LlamaChatRole.user, 'history', 'prompt'), + ], + _longCase: [ + for (final (role, text) in _longHistory) + LlamaChatMessage.fromText(role: role, text: text), + ], + if (withTools) + for (final id in _toolCases.keys) + id: [message(LlamaChatRole.user, 'tools', 'prompt')], + }; + final toolFixture = profile.fixtures['tools'] as Map; + final toolFunction = (toolFixture['tool'] as Map)['function'] as Map; + final tool = ToolDefinition( + name: toolFunction['name'] as String, + description: toolFunction['description'] as String, + parameters: [ToolParam.string('city', required: true)], + ); + final results = {}; + for (final MapEntry(key: id, value: messages) in cases.entries) { + if (overBudget()) { + journal.log({'event': 'budget_exhausted', ...labels, 'case_id': id}); + break; + } + journal.log({'event': 'case_started', ...labels, 'case_id': id}); + final rawPrompt = profile.fixtureText('raw', 'prompt'); + final toolChoice = _toolCases[id]; + final judged = toolChoice != null || codes.containsKey(id); + final Map output; + try { + output = messages == null + ? await validation.generate(rawPrompt, profile, raw: true) + : toolChoice != null + ? await validation.generate( + messages.last.content, + profile, + history: messages, + tools: [tool], + toolChoice: toolChoice, + enableThinking: false, + maxTokens: _toolMaxTokens, + ) + : await validation.generate( + messages.last.content, + profile, + history: messages, + maxTokens: id == _longCase ? _longMaxTokens : null, + streamBatchTokens: id == _longCase ? 1 : null, + ); + } on LlamaException catch (error) { + journal.log({ + 'event': 'case_error', + ...labels, + 'case_id': id, + 'error_type': '${error.runtimeType}', + 'message': error.message, + 'details': error.details?.toString(), + if (judged) 'passed': false, + }); + if (judged) { + results[id] = ( + passed: false, + description: 'threw ${error.runtimeType}: $error', + ); + } + continue; + } + // llama.cpp counts a decode of one token as generation, so at + // micro-batch size 1 its prompt counter leaves the prompt out. + final promptTokens = messages == null + ? (await engine.tokenize(rawPrompt)).length + : (await engine.chatTemplate( + messages, + enableThinking: toolChoice == null && profile.enableThinking, + tools: toolChoice == null ? null : [tool], + toolChoice: toolChoice ?? ToolChoice.auto, + )).tokenCount; + final content = output['content'] as String; + final finish = output['finish_reasons']; + final call = reconstructToolCall(output['tool_call_deltas'] as List); + final passed = toolChoice != null + ? toolCallMatches( + finishReasons: finish, + call: call, + name: tool.name, + arguments: toolFixture['expected_arguments'], + ) + : codes[id] == null + ? null + : answerIsCode(content, codes[id]!); + final metrics = output['metrics'] as Map; + final promptMs = metrics['native_prompt_ms'] as double?; + journal.log({ + 'event': 'case', + ...labels, + 'case_id': id, + 'passed': ?passed, + 'expected': ?codes[id], + 'prompt_tokens': promptTokens, + 'native_prompt_tokens': metrics['native_prompt_tokens'], + 'native_decode_tokens': metrics['native_decode_tokens'], + 'finish_reasons': finish, + 'content': content, + if (toolChoice != null) ...{ + 'tool_choice': toolChoice.name, + 'tool_call_name': call.name, + 'tool_call_arguments': call.arguments, + }, + 'chunks': output['chunks'], + 'max_tokens': output['max_tokens'], + 'stream_batch_tokens': output['stream_batch_tokens'], + 'wall_ms': metrics['wall_ms'], + 'ttfa_ms': metrics['ttfa_ms'], + 'native_prompt_ms': promptMs, + 'prompt_tps': promptTokens == null || promptMs == null || promptMs <= 0 + ? null + : promptTokens * 1000 / promptMs, + 'native_decode_ms': metrics['native_decode_ms'], + }); + if (passed != null) { + results[id] = ( + passed: passed, + description: toolChoice != null + ? 'ended as ${call.name}(${jsonEncode(call.arguments)}), ' + 'finish ${jsonEncode(finish)}, content ' + '${jsonEncode(_shorten(content))}' + : 'answered ${jsonEncode(_shorten(content))}, finish ' + '${jsonEncode(finish)}, wanted one of ' + '${jsonEncode(codes[id])}', + ); + } + } + return results; + } finally { + await validation.dispose(); + } +} + +/// The value llama.cpp logs for [name] when it creates a context +/// (`llama_context: n_ubatch = 512`), or null when the line is missing. +int? _contextValue(String log, String name) { + final match = RegExp( + '^llama_context: $name\\s*=\\s*(\\d+)', + multiLine: true, + ).firstMatch(log); + return match == null ? null : int.parse(match[1]!); +} + +String _shorten(String text) => text.length <= _maxLoggedText + ? text + : '${text.substring(0, _maxLoggedText)}...'; + +class _Journal { + _Journal(this._file) { + _file.writeAsStringSync('', flush: true); + } + + final File _file; + final _clock = Stopwatch()..start(); + + void log(Map record) { + final event = {...record, 't_ms': _clock.elapsedMilliseconds}; + _file.writeAsStringSync( + '${jsonEncode(event)}\n', + mode: FileMode.append, + flush: true, + ); + // Android truncates a log line near 1 kB, and debugPrint buffers, which + // loses the last records when the process dies. + // ignore: avoid_print + print( + '$_logTag ${jsonEncode({for (final MapEntry(:key, :value) in event.entries) key: value is String ? _shorten(value) : value})}', + ); + } +} + +/// Journals the `LlamaLogger` records and keeps the prompt cap decision the +/// library logged for the attempt that is running. +class _LibraryLog { + _LibraryLog(this._journal); + + final _Journal _journal; + Map _labels = const {}; + + /// The decision the library logged since [begin], or null. + PromptCapDecision? decision; + + /// The journal name of the attempt's `PromptCapState`, once it is known. + String? capState; + + /// Starts the records of the attempt [labels] name. + void begin(Map labels) { + _labels = labels; + decision = null; + capState = null; + } + + void record(LlamaLogRecord record) { + _journal.log({ + 'event': 'log', + ..._labels, + 'level': record.level.name, + 'message': record.message, + 'error': record.error?.toString(), + }); + decision = parsePromptCapDecision(record.message) ?? decision; + } +} + +typedef _CreatNative = Int32 Function(Pointer, Uint32); +typedef _Creat = int Function(Pointer, int); +typedef _DupNative = Int32 Function(Int32); +typedef _Dup = int Function(int); +typedef _Dup2Native = Int32 Function(Int32, Int32); +typedef _Dup2 = int Function(int, int); + +/// Standard error of this process, pointed at a file while the test runs. +class _NativeLog { + _NativeLog._(this._file, this._saved); + + /// Points descriptor 2 at [file]. Where that is not possible, the test + /// still runs and records that native output was not captured. + factory _NativeLog.capture(File file) { + file.writeAsStringSync('', flush: true); + if (Platform.isWindows) return _NativeLog._(file, null); + try { + final process = DynamicLibrary.process(); + final creat = process.lookupFunction<_CreatNative, _Creat>('creat'); + final dup = process.lookupFunction<_DupNative, _Dup>('dup'); + final path = file.path.toNativeUtf8(); + try { + final descriptor = creat(path, 420); + if (descriptor < 0) return _NativeLog._(file, null); + final saved = dup(2); + final redirected = _dup2(descriptor, 2) == 2; + _close(descriptor); + if (!redirected) { + if (saved >= 0) _close(saved); + return _NativeLog._(file, null); + } + return _NativeLog._(file, saved); + } finally { + malloc.free(path); + } + } on ArgumentError { + return _NativeLog._(file, null); + } + } + + static final _Dup2 _dup2 = DynamicLibrary.process() + .lookupFunction<_Dup2Native, _Dup2>('dup2'); + static final _Dup _close = DynamicLibrary.process() + .lookupFunction<_DupNative, _Dup>('close'); + + final File _file; + final int? _saved; + bool _restored = false; + + bool get captured => _saved != null; + + int get length => _file.lengthSync(); + + /// The output written after byte [offset]. + String since(int offset) => utf8.decode( + _file.readAsBytesSync().sublist(offset), + allowMalformed: true, + ); + + void restore() { + final saved = _saved; + if (saved == null || _restored) return; + _restored = true; + if (saved >= 0) { + _dup2(saved, 2); + _close(saved); + } + } +} diff --git a/example/chat_app/integration_test/support/micro_batch_sweep_support.dart b/example/chat_app/integration_test/support/micro_batch_sweep_support.dart new file mode 100644 index 000000000..7eb034189 --- /dev/null +++ b/example/chat_app/integration_test/support/micro_batch_sweep_support.dart @@ -0,0 +1,228 @@ +import 'dart:convert'; + +/// One Vulkan device as the prompt cap log line of llamadart describes it. +typedef PromptCapDevice = ({ + String name, + String apiVersion, + String loaderApiVersion, + int subgroupSize, +}); + +/// What llamadart logged about the Android Vulkan text prompt cap when it +/// created a context. +/// +/// [capTokens] is the most prompt tokens one decode call takes, or null when +/// the cap is lifted. [devices] are the Vulkan devices the decision was made +/// from; when the probe could not list them, [detail] holds its reason. +typedef PromptCapDecision = ({ + int? capTokens, + List devices, + String detail, +}); + +final _capLine = RegExp( + r'Android Vulkan text prompt decode is ' + r'(?:capped at (\d+) tokens per call|not capped) \((.*)\)', + dotAll: true, +); +// A device name is free text and may hold a quote, so it ends at the quote +// that the version list follows. +final _capDevice = RegExp( + r'"(.*?)" \(API (\d+\.\d+), loader (\d+\.\d+), subgroup size (\d+)\)', + dotAll: true, +); + +/// The decision in a `LlamaLogger` debug [message], or null when the message +/// is not the prompt cap line. +PromptCapDecision? parsePromptCapDecision(String message) { + final match = _capLine.firstMatch(message); + if (match == null) return null; + final cap = match[1]; + final detail = match[2]!; + return ( + capTokens: cap == null ? null : int.parse(cap), + devices: [ + for (final device in _capDevice.allMatches(detail)) + ( + name: device[1]!, + apiVersion: device[2]!, + loaderApiVersion: device[3]!, + subgroupSize: int.parse(device[4]!), + ), + ], + detail: detail, + ); +} + +/// What is known about the Android Vulkan text prompt cap of one context. +enum PromptCapState { + /// The library logged that it caps the prompt decode. + capped('capped'), + + /// The library logged that it leaves the prompt decode uncapped. + notCapped('not_capped'), + + /// An explicit micro-batch size, which makes the library leave the cap off + /// without logging. + explicitSize('explicit_size'), + + /// A platform other than Android, where there is no cap. + notAndroid('not_android'), + + /// An Android load that asks Vulkan for no GPU layer, which gets no cap. + vulkanNotRequested('vulkan_not_requested'), + + /// An Android load that asks Vulkan for GPU layers while ggml-vulkan + /// registered no device. The library logs nothing and applies the cap all + /// the same, although the context runs on the CPU. + noVulkanDevice('no_vulkan_device'), + + /// A Vulkan device is registered and the cap was to be decided, but no + /// decision reached the log: the record is missing. + notLogged('not_logged'); + + const PromptCapState(this.wireName); + + /// The value the journal carries. + final String wireName; +} + +/// The state of the prompt cap for a context created with [microBatchSize] +/// (0 for the library default), from the library's [logged] decision when it +/// logged one and otherwise from what the load reported. +/// +/// [vulkanRequested] is whether the load prefers Vulkan and kept a positive +/// GPU layer count. [registeredVulkanDevices] is the number of Vulkan devices +/// the runtime lists, or null when it cannot be read. +PromptCapState promptCapState({ + required PromptCapDecision? logged, + required int microBatchSize, + required bool isAndroid, + required bool vulkanRequested, + required int? registeredVulkanDevices, +}) { + if (logged != null) { + return logged.capTokens == null + ? PromptCapState.notCapped + : PromptCapState.capped; + } + if (microBatchSize > 0) return PromptCapState.explicitSize; + if (!isAndroid) return PromptCapState.notAndroid; + if (!vulkanRequested) return PromptCapState.vulkanNotRequested; + if (registeredVulkanDevices == 0) return PromptCapState.noVulkanDevice; + return PromptCapState.notLogged; +} + +/// Whether [content] is one of [codes] and nothing else: surrounding +/// whitespace, letter case and one closing `.` or `!` are ignored. +bool answerIsCode(String content, Iterable codes) { + final answer = content.trim().toLowerCase().replaceFirst( + RegExp(r'[.!]$'), + '', + ); + return codes.any((code) => code.toLowerCase() == answer); +} + +/// The tool call that streamed tool-call [deltas] add up to: the +/// concatenated name and the decoded arguments. `arguments` is null when the +/// argument text is not JSON, and `wellFormed` is false then, when there are +/// no deltas, and when the deltas name more than one call. +({String name, Object? arguments, bool wellFormed}) reconstructToolCall( + List deltas, +) { + final name = StringBuffer(); + final arguments = StringBuffer(); + var wellFormed = deltas.isNotEmpty; + String? id; + for (final delta in deltas.cast>()) { + if (delta['index'] != 0) wellFormed = false; + if (delta['id'] case final String next) { + if (id != null && id != next) wellFormed = false; + id = next; + } + final function = delta['function'] as Map?; + name.write(function?['name'] ?? ''); + arguments.write(function?['arguments'] ?? ''); + } + Object? decoded; + try { + decoded = jsonDecode(arguments.toString()); + } on FormatException { + wellFormed = false; + } + return (name: name.toString(), arguments: decoded, wellFormed: wellFormed); +} + +/// Whether a request that ended with [finishReasons] and the tool [call] is +/// exactly one call of [name] with [arguments]. +bool toolCallMatches({ + required Object? finishReasons, + required ({String name, Object? arguments, bool wellFormed}) call, + required String name, + required Object? arguments, +}) => + jsonEncode(finishReasons) == jsonEncode(['tool_calls']) && + call.wellFormed && + call.name == name && + _canonical(call.arguments) == _canonical(arguments); + +/// JSON text of [value] with the keys of every object in order. +String _canonical(Object? value) => jsonEncode(_sorted(value)); + +Object? _sorted(Object? value) => switch (value) { + final Map map => { + for (final key in map.keys.map((key) => '$key').toList()..sort()) + key: _sorted(map[key]), + }, + final List list => [for (final item in list) _sorted(item)], + _ => value, +}; + +/// How one judged request ended: whether it [passed], and what to print when +/// it did not. +typedef JudgedCase = ({bool passed, String description}); + +/// The verdict of one attempt at the judged size. +/// +/// It passes when the load succeeded ([loadError] is null) and every case in +/// [judgedCases] has a passing entry in [results]. `cases` holds the verdict +/// of each judged case, false for one that never ran. +({bool passed, Map cases, List failures}) judgeAttempt( + Iterable judgedCases, + Map results, { + String? loadError, +}) { + final failures = []; + if (loadError != null) { + failures.add('did not load: $loadError'); + } else { + for (final id in judgedCases) { + final result = results[id]; + if (result == null) { + failures.add('$id did not run'); + } else if (!result.passed) { + failures.add('$id ${result.description}'); + } + } + } + return ( + passed: failures.isEmpty, + cases: {for (final id in judgedCases) id: results[id]?.passed ?? false}, + failures: failures, + ); +} + +/// The attempts of a sweep over [arms] and [repeats], in running order: every +/// repeat of the [judgedArm] first, so that nothing a control arm does to the +/// process can cost a judged repeat, then the control arms repeat by repeat. +List<({int repeat, int arm})> sweepOrder( + List arms, + int repeats, { + required int judgedArm, +}) => [ + for (var repeat = 1; repeat <= repeats; repeat++) + (repeat: repeat, arm: judgedArm), + for (var repeat = 1; repeat <= repeats; repeat++) + for (final arm in arms) + if (arm != judgedArm) (repeat: repeat, arm: arm), +]; diff --git a/example/chat_app/test/micro_batch_sweep_support_test.dart b/example/chat_app/test/micro_batch_sweep_support_test.dart new file mode 100644 index 000000000..e065b54b8 --- /dev/null +++ b/example/chat_app/test/micro_batch_sweep_support_test.dart @@ -0,0 +1,366 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; + +import '../integration_test/support/micro_batch_sweep_support.dart'; + +void main() { + group('parsePromptCapDecision', () { + test('reads a capped decision and the device as llamadart formats it', () { + const device = VulkanDeviceFacts( + name: 'Mali-G715', + deviceType: 1, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 3 << 12 | 283, + subgroupSize: 16, + ); + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call ($device)', + )!; + + expect(decision.capTokens, 8); + expect(decision.devices, [ + ( + name: 'Mali-G715', + apiVersion: '1.3', + loaderApiVersion: '1.3', + subgroupSize: 16, + ), + ]); + }); + + test('reads a lifted cap and every device', () { + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is not capped ' + '("Adreno (TM) 750" (API 1.3, loader 1.4, subgroup size 64), ' + '"llvmpipe (LLVM 19.1, 256 bits)" (API 1.4, loader 1.4, subgroup ' + 'size 8))', + )!; + + expect(decision.capTokens, isNull); + expect( + [for (final device in decision.devices) device.name], + ['Adreno (TM) 750', 'llvmpipe (LLVM 19.1, 256 bits)'], + ); + expect( + [for (final device in decision.devices) device.subgroupSize], + [64, 8], + ); + expect(decision.devices.first.loaderApiVersion, '1.4'); + }); + + test('keeps the reason of a probe that listed no device', () { + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call (llama_dart_vulkan_get_device_count returned ' + 'LLAMA_DART_VULKAN_STATUS_NO_LOADER)', + )!; + + expect(decision.capTokens, 8); + expect(decision.devices, isEmpty); + expect( + decision.detail, + 'llama_dart_vulkan_get_device_count returned ' + 'LLAMA_DART_VULKAN_STATUS_NO_LOADER', + ); + }); + + test('reads a device whose name holds a quote', () { + const devices = [ + VulkanDeviceFacts( + name: 'Weird "GPU" 9000', + deviceType: 2, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 1 << 12, + subgroupSize: 4, + ), + VulkanDeviceFacts( + name: 'Mali-G715', + deviceType: 1, + instanceApiVersion: 1 << 22 | 3 << 12, + apiVersion: 1 << 22 | 3 << 12, + subgroupSize: 16, + ), + ]; + final decision = parsePromptCapDecision( + 'llama_cpp_service: Android Vulkan text prompt decode is capped at 8 ' + 'tokens per call (${devices.join(', ')})', + )!; + + expect( + [for (final device in decision.devices) device.name], + ['Weird "GPU" 9000', 'Mali-G715'], + ); + expect(decision.devices.first.apiVersion, '1.1'); + expect(decision.devices.first.subgroupSize, 4); + expect(decision.devices.last.subgroupSize, 16); + }); + + test('ignores other records', () { + expect( + parsePromptCapDecision( + 'llama_cpp_service: promoting flash_attn=enabled for non-F16 KV', + ), + isNull, + ); + }); + }); + + group('reconstructToolCall', () { + test('joins the name and the argument pieces of one call', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'id': 'call_1', + 'function': {'name': 'get_weather', 'arguments': '{"city":'}, + }, + { + 'index': 0, + 'function': {'arguments': '"Montréal"}'}, + }, + ]); + + expect(call.name, 'get_weather'); + expect(call.arguments, {'city': 'Montréal'}); + expect(call.wellFormed, isTrue); + }); + + test('is not well formed without deltas', () { + expect(reconstructToolCall(const []).wellFormed, isFalse); + }); + + test('is not well formed when the arguments are not JSON', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'function': {'name': 'get_weather', 'arguments': '8888'}, + }, + { + 'index': 0, + 'function': {'arguments': '{'}, + }, + ]); + + expect(call.name, 'get_weather'); + expect(call.arguments, isNull); + expect(call.wellFormed, isFalse); + }); + + test('is not well formed when the deltas name two calls', () { + final call = reconstructToolCall([ + { + 'index': 0, + 'id': 'call_1', + 'function': {'name': 'get_weather', 'arguments': '{}'}, + }, + { + 'index': 1, + 'id': 'call_2', + 'function': {'name': 'get_weather', 'arguments': ''}, + }, + ]); + + expect(call.wellFormed, isFalse); + }); + }); + + group('promptCapState', () { + const capped = ( + capTokens: 8, + devices: [], + detail: 'probe unavailable', + ); + const lifted = ( + capTokens: null, + devices: [], + detail: '"Adreno" (API 1.3, loader 1.3, subgroup size 64)', + ); + PromptCapState state({ + PromptCapDecision? logged, + int microBatchSize = 0, + bool isAndroid = true, + bool vulkanRequested = true, + int? registeredVulkanDevices = 1, + }) => promptCapState( + logged: logged, + microBatchSize: microBatchSize, + isAndroid: isAndroid, + vulkanRequested: vulkanRequested, + registeredVulkanDevices: registeredVulkanDevices, + ); + + test('takes a logged decision over everything else', () { + expect(state(logged: capped), PromptCapState.capped); + expect(state(logged: lifted), PromptCapState.notCapped); + expect( + state(logged: capped, registeredVulkanDevices: 0), + PromptCapState.capped, + ); + }); + + test('names why the library logged nothing', () { + expect(state(microBatchSize: 512), PromptCapState.explicitSize); + expect(state(isAndroid: false), PromptCapState.notAndroid); + expect(state(vulkanRequested: false), PromptCapState.vulkanNotRequested); + }); + + test('tells a silent cap without a Vulkan device from a missing ' + 'record', () { + expect(state(registeredVulkanDevices: 0), PromptCapState.noVulkanDevice); + expect(state(registeredVulkanDevices: 1), PromptCapState.notLogged); + expect(state(registeredVulkanDevices: null), PromptCapState.notLogged); + }); + + test('an explicit size is not a silent cap even without a device', () { + expect( + state(microBatchSize: 512, registeredVulkanDevices: 0), + PromptCapState.explicitSize, + ); + }); + }); + + group('answerIsCode', () { + test('accepts the code alone, whatever its case and closing mark', () { + expect(answerIsCode('Cedar17', ['cedar17']), isTrue); + expect(answerIsCode(' cedar17.\n', ['cedar17']), isTrue); + expect(answerIsCode('42', ['42', 'maple42']), isTrue); + expect(answerIsCode('maple42!', ['42', 'maple42']), isTrue); + }); + + test('rejects an answer that only holds the code', () { + expect(answerIsCode('8888888842888', ['42', 'maple42']), isFalse); + expect(answerIsCode('1 2 3 42 5', ['42', 'maple42']), isFalse); + expect(answerIsCode('The code is cedar17', ['cedar17']), isFalse); + expect(answerIsCode('', ['cedar17']), isFalse); + }); + }); + + group('toolCallMatches', () { + const call = ( + name: 'get_weather', + arguments: {'city': 'Montréal'}, + wellFormed: true, + ); + bool matches({ + Object? finishReasons = const ['tool_calls'], + ({String name, Object? arguments, bool wellFormed}) call = call, + }) => toolCallMatches( + finishReasons: finishReasons, + call: call, + name: 'get_weather', + arguments: const {'city': 'Montréal'}, + ); + + test('accepts the one expected call', () { + expect(matches(), isTrue); + }); + + test('rejects another finish, name, argument or a malformed call', () { + expect(matches(finishReasons: const ['stop']), isFalse); + expect(matches(finishReasons: const ['length']), isFalse); + expect( + matches( + call: (name: 'get_time', arguments: call.arguments, wellFormed: true), + ), + isFalse, + ); + expect( + matches( + call: ( + name: 'get_weather', + arguments: const {'city': 'Toronto'}, + wellFormed: true, + ), + ), + isFalse, + ); + expect( + matches( + call: ( + name: 'get_weather', + arguments: call.arguments, + wellFormed: false, + ), + ), + isFalse, + ); + }); + }); + + group('judgeAttempt', () { + const cases = ['C06.history', 'X01.long_history', 'C07.tools.auto']; + const pass = (passed: true, description: 'ok'); + + test('passes when every judged case passed', () { + final verdict = judgeAttempt(cases, { + for (final id in cases) id: pass, + 'C04.hello': (passed: false, description: 'not judged'), + }); + + expect(verdict.passed, isTrue); + expect(verdict.failures, isEmpty); + expect(verdict.cases, {for (final id in cases) id: true}); + }); + + test('fails on a wrong answer and says what it was', () { + final verdict = judgeAttempt(cases, { + 'C06.history': pass, + 'X01.long_history': (passed: false, description: 'answered "8888"'), + 'C07.tools.auto': pass, + }); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['X01.long_history answered "8888"']); + expect(verdict.cases['X01.long_history'], isFalse); + expect(verdict.cases['C06.history'], isTrue); + }); + + test('fails on a judged case that never ran', () { + final verdict = judgeAttempt(cases, { + 'C06.history': pass, + 'X01.long_history': pass, + }); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['C07.tools.auto did not run']); + expect(verdict.cases['C07.tools.auto'], isFalse); + }); + + test('fails on a load error without listing the cases', () { + final verdict = judgeAttempt( + cases, + const {}, + loadError: 'LlamaModelException: no', + ); + + expect(verdict.passed, isFalse); + expect(verdict.failures, ['did not load: LlamaModelException: no']); + expect(verdict.cases.values, everyElement(isFalse)); + }); + }); + + group('sweepOrder', () { + test('runs every judged repeat before any control', () { + expect(sweepOrder([0, 512], 3, judgedArm: 0), [ + (repeat: 1, arm: 0), + (repeat: 2, arm: 0), + (repeat: 3, arm: 0), + (repeat: 1, arm: 512), + (repeat: 2, arm: 512), + (repeat: 3, arm: 512), + ]); + }); + + test('keeps the controls repeat by repeat, wherever the judged size is ' + 'listed', () { + expect(sweepOrder([512, 0, 1], 2, judgedArm: 0), [ + (repeat: 1, arm: 0), + (repeat: 2, arm: 0), + (repeat: 1, arm: 512), + (repeat: 1, arm: 1), + (repeat: 2, arm: 512), + (repeat: 2, arm: 1), + ]); + }); + }); +} diff --git a/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart b/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart new file mode 100644 index 000000000..09136ab8b --- /dev/null +++ b/test/unit/backends/llama_cpp/android_vulkan_prompt_cap_log_test.dart @@ -0,0 +1,156 @@ +@TestOn('vm') +library; + +import 'dart:mirrors'; + +import 'package:llamadart/src/backends/llama_cpp/llama_cpp_service.dart'; +import 'package:llamadart/src/backends/llama_cpp/load_device_selection.dart'; +import 'package:llamadart/src/backends/llama_cpp/vulkan_device_probe.dart'; +import 'package:llamadart/src/core/llama_logger.dart'; +import 'package:llamadart/src/core/models/config/log_level.dart'; +import 'package:test/test.dart'; + +import '../../../../example/chat_app/integration_test/support/micro_batch_sweep_support.dart'; + +const _vulkan13 = 1 << 22 | 3 << 12; + +VulkanDeviceFacts _facts(String name, int subgroupSize) => VulkanDeviceFacts( + name: name, + deviceType: 1, + instanceApiVersion: _vulkan13, + apiVersion: _vulkan13 | 283, + subgroupSize: subgroupSize, +); + +/// The debug records and the result of the service's own cap decision for +/// an Android runtime that registered [registered] Vulkan devices and whose +/// probe answers [probe]. Nothing native is loaded: the registry and the +/// probe are the injected ones. +({bool defect, List debug}) _decide( + VulkanDeviceProbe probe, { + int registered = 1, +}) { + final service = LlamaCppService( + isAndroid: true, + vulkanDeviceProbe: () => probe, + registeredDevices: () => [ + for (var index = 0; index < registered; index++) + GgmlDeviceEntry(name: 'Vulkan$index', type: 1, registry: 'Vulkan'), + ], + ); + final logger = LlamaLogger.instance; + final level = logger.level; + final debug = []; + logger + ..setLevel(LlamaLogLevel.debug) + ..setHandler((record) { + if (record.level == LlamaLogLevel.debug) debug.add(record.message); + }); + try { + final owner = reflectClass(LlamaCppService).owner as LibraryMirror; + final defect = + reflect(service) + .invoke( + MirrorSystem.getSymbol( + '_androidVulkanHasSmallMatmulTileDefect', + owner, + ), + const [], + ) + .reflectee + as bool; + return (defect: defect, debug: debug); + } finally { + logger + ..setHandler(null) + ..setLevel(level); + } +} + +/// The micro-batch sweep E2E of the chat app reads the cap decision out of +/// the line the service logs. These tests take that line from the service +/// itself, so rewording it there fails here instead of turning the E2E's +/// record into `not_logged`. +void main() { + test('the sweep E2E reads the line the service logs for a capped ' + 'device', () { + final decided = _decide( + VulkanDeviceProbe.devices([_facts('Mali-G715', 16)]), + ); + + expect(decided.defect, isTrue); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect( + decision.capTokens, + LlamaCppService.androidVulkanPromptMicroBatchSize, + ); + expect(decision.devices, [ + ( + name: 'Mali-G715', + apiVersion: '1.3', + loaderApiVersion: '1.3', + subgroupSize: 16, + ), + ]); + }); + + test('the sweep E2E reads the line the service logs when it lifts the ' + 'cap', () { + final decided = _decide( + VulkanDeviceProbe.devices([ + _facts('Adreno (TM) 750', 64), + _facts('Odd "GPU"', 8), + ]), + registered: 2, + ); + + expect(decided.defect, isFalse); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect(decision.capTokens, isNull); + expect( + [for (final device in decision.devices) device.name], + ['Adreno (TM) 750', 'Odd "GPU"'], + ); + expect( + [for (final device in decision.devices) device.subgroupSize], + [64, 8], + ); + }); + + test('the sweep E2E reads the line the service logs when the probe is ' + 'unavailable', () { + final decided = _decide( + const VulkanDeviceProbe.unavailable('no Vulkan loader'), + ); + + expect(decided.defect, isTrue); + final decision = parsePromptCapDecision(decided.debug.single)!; + expect( + decision.capTokens, + LlamaCppService.androidVulkanPromptMicroBatchSize, + ); + expect(decision.devices, isEmpty); + expect(decision.detail, 'no Vulkan loader'); + }); + + test('the service logs nothing and caps when no Vulkan device is ' + 'registered, which the sweep E2E records as no_vulkan_device', () { + final decided = _decide( + VulkanDeviceProbe.devices([_facts('Mali-G715', 16)]), + registered: 0, + ); + + expect(decided.defect, isTrue); + expect(decided.debug, isEmpty); + expect( + promptCapState( + logged: null, + microBatchSize: 0, + isAndroid: true, + vulkanRequested: true, + registeredVulkanDevices: 0, + ), + PromptCapState.noVulkanDevice, + ); + }); +} diff --git a/test/unit/tooling/run_local_e2e_test.dart b/test/unit/tooling/run_local_e2e_test.dart index 8d9e7631e..54c745cab 100644 --- a/test/unit/tooling/run_local_e2e_test.dart +++ b/test/unit/tooling/run_local_e2e_test.dart @@ -233,6 +233,31 @@ void main() { expect(result.stdout, isNot(contains('LITERT_RELOAD_MODEL'))); }); + test('dry-runs the micro-batch sweep device scenario', () async { + final result = await runLocalE2e(const [ + '--scenario', + 'chat-app-micro-batch-sweep', + '--device', + 'android', + '--model-path', + '/data/local/tmp/Qwen3.5-0.8B-Q4_0.gguf', + '--dry-run', + ], projectRoot: '/repo'); + + expect(result.exitCode, 0); + expect( + result.stdout, + contains( + 'cd /repo/example/chat_app && flutter test --run-skipped ' + '-t local-only ' + 'integration_test/micro_batch_sweep_e2e_test.dart ' + '-d android ' + '--dart-define=MICRO_BATCH_SWEEP_MODEL=' + '/data/local/tmp/Qwen3.5-0.8B-Q4_0.gguf', + ), + ); + }); + test('dry-runs Web Qwen3-ASR file and microphone transcription', () async { final result = await runLocalE2e(const [ '--scenario', diff --git a/tool/testing/run_local_e2e.dart b/tool/testing/run_local_e2e.dart index e6963f916..3d79be7c5 100644 --- a/tool/testing/run_local_e2e.dart +++ b/tool/testing/run_local_e2e.dart @@ -1031,6 +1031,33 @@ List buildLocalE2eScenarios({String? projectRoot}) { ), ], ), + LocalE2eScenario( + name: 'chat-app-micro-batch-sweep', + group: LocalE2eScenarioGroup.flutterDevice, + description: + 'Answer history and tool prompts at the default and at explicit ' + 'micro-batch sizes in one process, and record the Android Vulkan ' + 'prompt cap decision with the Vulkan device facts.', + requiresDevice: true, + stepsBuilder: (context) => [ + LocalE2eCommandStep( + workingDirectory: context.chatAppDir, + executable: 'flutter', + arguments: [ + 'test', + '--run-skipped', + '-t', + 'local-only', + 'integration_test/micro_batch_sweep_e2e_test.dart', + '-d', + context.device, + if (context.modelPath != null) + '--dart-define=MICRO_BATCH_SWEEP_MODEL=${context.modelPath}', + ], + description: 'Flutter chat app micro-batch sweep E2E', + ), + ], + ), LocalE2eScenario( name: 'chat-app-macos-quit', group: LocalE2eScenarioGroup.flutterDevice, diff --git a/tool/testing/test_matrix.dart b/tool/testing/test_matrix.dart index 6b9582225..67c0752ac 100644 --- a/tool/testing/test_matrix.dart +++ b/tool/testing/test_matrix.dart @@ -772,6 +772,28 @@ const List testMatrixRows = [ 'copy on the target device. Graphics memory needs the Test Lab ' 'arguments in example/chat_app/README.md.', ), + TestMatrixRow( + id: 'chat-app-micro-batch-sweep', + tier: 'targeted', + mode: 'local-only', + covers: + 'llama.cpp history, long-history and grammar-constrained tool ' + 'prompts at the default micro-batch and at explicit sizes in one ' + 'process on a device, with a flushed verdict per attempt, the ' + 'Android Vulkan prompt cap state (capped, not capped, or capped ' + 'without a Vulkan device), the Vulkan device name, API version and ' + 'subgroup size, and a typed load refusal recorded; the default size ' + 'must answer correctly, explicit sizes are controls', + command: + 'dart run tool/testing/run_local_e2e.dart --scenario ' + 'chat-app-micro-batch-sweep --device ', + useWhen: + 'llama.cpp native pin, Android Vulkan prompt cap, Vulkan device ' + 'facts or the Vulkan 1.2 load refusal changes. Downloads the locked ' + 'chat-gguf-vulkan model unless --model-path names a copy on the ' + 'target device. Only an Android Vulkan device exercises the cap; ' + 'the Test Lab arguments are in example/chat_app/README.md.', + ), TestMatrixRow( id: 'chat-app-macos-quit', tier: 'targeted',